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 |
|---|---|---|---|---|---|---|---|---|
riggsd/davies | examples/pockettopo2therion.py | https://github.com/riggsd/davies/blob/8566c626202a875947ad01c087300108c68d80b5/examples/pockettopo2therion.py#L24-L42 | def pockettopo2therion(txtfilename):
"""Main function which converts a PocketTopo .TXT file to a Compass .DAT file"""
print 'Converting PocketTopo data file %s ...' % txtfilename
infile = pockettopo.TxtFile.read(txtfilename, merge_duplicate_shots=True)
outfilename = convert_filename(txtfilename)
wi... | [
"def",
"pockettopo2therion",
"(",
"txtfilename",
")",
":",
"print",
"'Converting PocketTopo data file %s ...'",
"%",
"txtfilename",
"infile",
"=",
"pockettopo",
".",
"TxtFile",
".",
"read",
"(",
"txtfilename",
",",
"merge_duplicate_shots",
"=",
"True",
")",
"outfilena... | Main function which converts a PocketTopo .TXT file to a Compass .DAT file | [
"Main",
"function",
"which",
"converts",
"a",
"PocketTopo",
".",
"TXT",
"file",
"to",
"a",
"Compass",
".",
"DAT",
"file"
] | python | train |
paylogic/pip-accel | pip_accel/__init__.py | https://github.com/paylogic/pip-accel/blob/ccad1b784927a322d996db593403b1d2d2e22666/pip_accel/__init__.py#L612-L616 | def clear_build_directory(self):
"""Clear the build directory where pip unpacks the source distribution archives."""
stat = os.stat(self.build_directory)
shutil.rmtree(self.build_directory)
os.makedirs(self.build_directory, stat.st_mode) | [
"def",
"clear_build_directory",
"(",
"self",
")",
":",
"stat",
"=",
"os",
".",
"stat",
"(",
"self",
".",
"build_directory",
")",
"shutil",
".",
"rmtree",
"(",
"self",
".",
"build_directory",
")",
"os",
".",
"makedirs",
"(",
"self",
".",
"build_directory",
... | Clear the build directory where pip unpacks the source distribution archives. | [
"Clear",
"the",
"build",
"directory",
"where",
"pip",
"unpacks",
"the",
"source",
"distribution",
"archives",
"."
] | python | train |
ml4ai/delphi | delphi/utils/indra.py | https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/utils/indra.py#L91-L93 | def is_grounded_statement(s: Influence) -> bool:
""" Check if an Influence statement is grounded """
return is_grounded_concept(s.subj) and is_grounded_concept(s.obj) | [
"def",
"is_grounded_statement",
"(",
"s",
":",
"Influence",
")",
"->",
"bool",
":",
"return",
"is_grounded_concept",
"(",
"s",
".",
"subj",
")",
"and",
"is_grounded_concept",
"(",
"s",
".",
"obj",
")"
] | Check if an Influence statement is grounded | [
"Check",
"if",
"an",
"Influence",
"statement",
"is",
"grounded"
] | python | train |
openego/eTraGo | etrago/tools/io.py | https://github.com/openego/eTraGo/blob/2a8fc6d4368d0e9abe6fe0d0c39baf66ea0126b9/etrago/tools/io.py#L831-L853 | def distance(x0, x1, y0, y1):
"""
Function that calculates the square of the distance between two points.
Parameters
-----
x0: x - coordinate of point 0
x1: x - coordinate of point 1
y0: y - coordinate of point 0
y1: y - coordinate of point 1
Returns
-----... | [
"def",
"distance",
"(",
"x0",
",",
"x1",
",",
"y0",
",",
"y1",
")",
":",
"# Calculate square of the distance between two points (Pythagoras)",
"distance",
"=",
"(",
"x1",
".",
"values",
"-",
"x0",
".",
"values",
")",
"*",
"(",
"x1",
".",
"values",
"-",
"x0... | Function that calculates the square of the distance between two points.
Parameters
-----
x0: x - coordinate of point 0
x1: x - coordinate of point 1
y0: y - coordinate of point 0
y1: y - coordinate of point 1
Returns
------
distance : float
square ... | [
"Function",
"that",
"calculates",
"the",
"square",
"of",
"the",
"distance",
"between",
"two",
"points",
"."
] | python | train |
openstax/rhaptos.cnxmlutils | rhaptos/cnxmlutils/utils.py | https://github.com/openstax/rhaptos.cnxmlutils/blob/c32b1a7428dc652e8cd745f3fdf4019a20543649/rhaptos/cnxmlutils/utils.py#L57-L72 | def _post_tidy(html):
""" This method transforms post tidy. Will go away when tidy goes away. """
tree = etree.fromstring(html)
ems = tree.xpath(
"//xh:em[@class='underline']|//xh:em[contains(@class, ' underline ')]",
namespaces={'xh': 'http://www.w3.org/1999/xhtml'})
for el in ems:
... | [
"def",
"_post_tidy",
"(",
"html",
")",
":",
"tree",
"=",
"etree",
".",
"fromstring",
"(",
"html",
")",
"ems",
"=",
"tree",
".",
"xpath",
"(",
"\"//xh:em[@class='underline']|//xh:em[contains(@class, ' underline ')]\"",
",",
"namespaces",
"=",
"{",
"'xh'",
":",
"'... | This method transforms post tidy. Will go away when tidy goes away. | [
"This",
"method",
"transforms",
"post",
"tidy",
".",
"Will",
"go",
"away",
"when",
"tidy",
"goes",
"away",
"."
] | python | train |
mongodb/mongo-python-driver | gridfs/__init__.py | https://github.com/mongodb/mongo-python-driver/blob/c29c21449e3aae74154207058cf85fd94018d4cd/gridfs/__init__.py#L77-L94 | def new_file(self, **kwargs):
"""Create a new file in GridFS.
Returns a new :class:`~gridfs.grid_file.GridIn` instance to
which data can be written. Any keyword arguments will be
passed through to :meth:`~gridfs.grid_file.GridIn`.
If the ``"_id"`` of the file is manually specif... | [
"def",
"new_file",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# No need for __ensure_index_files_id() here; GridIn ensures",
"# the (files_id, n) index when needed.",
"return",
"GridIn",
"(",
"self",
".",
"__collection",
",",
"disable_md5",
"=",
"self",
".",
"__di... | Create a new file in GridFS.
Returns a new :class:`~gridfs.grid_file.GridIn` instance to
which data can be written. Any keyword arguments will be
passed through to :meth:`~gridfs.grid_file.GridIn`.
If the ``"_id"`` of the file is manually specified, it must
not already exist in... | [
"Create",
"a",
"new",
"file",
"in",
"GridFS",
"."
] | python | train |
EpistasisLab/tpot | tpot/gp_deap.py | https://github.com/EpistasisLab/tpot/blob/b626271e6b5896a73fb9d7d29bebc7aa9100772e/tpot/gp_deap.py#L383-L466 | def _wrapped_cross_val_score(sklearn_pipeline, features, target,
cv, scoring_function, sample_weight=None,
groups=None, use_dask=False):
"""Fit estimator and compute scores for a given dataset split.
Parameters
----------
sklearn_pipeline : pipe... | [
"def",
"_wrapped_cross_val_score",
"(",
"sklearn_pipeline",
",",
"features",
",",
"target",
",",
"cv",
",",
"scoring_function",
",",
"sample_weight",
"=",
"None",
",",
"groups",
"=",
"None",
",",
"use_dask",
"=",
"False",
")",
":",
"sample_weight_dict",
"=",
"... | Fit estimator and compute scores for a given dataset split.
Parameters
----------
sklearn_pipeline : pipeline object implementing 'fit'
The object to use to fit the data.
features : array-like of shape at least 2D
The data to fit.
target : array-like, optional, default: None
... | [
"Fit",
"estimator",
"and",
"compute",
"scores",
"for",
"a",
"given",
"dataset",
"split",
"."
] | python | train |
iskandr/fancyimpute | fancyimpute/iterative_imputer.py | https://github.com/iskandr/fancyimpute/blob/9f0837d387c7303d5c8c925a9989ca77a1a96e3e/fancyimpute/iterative_imputer.py#L865-L950 | def fit_transform(self, X, y=None):
"""Fits the imputer on X and return the transformed X.
Parameters
----------
X : array-like, shape (n_samples, n_features)
Input data, where "n_samples" is the number of samples and
"n_features" is the number of features.
... | [
"def",
"fit_transform",
"(",
"self",
",",
"X",
",",
"y",
"=",
"None",
")",
":",
"self",
".",
"random_state_",
"=",
"getattr",
"(",
"self",
",",
"\"random_state_\"",
",",
"check_random_state",
"(",
"self",
".",
"random_state",
")",
")",
"if",
"self",
".",... | Fits the imputer on X and return the transformed X.
Parameters
----------
X : array-like, shape (n_samples, n_features)
Input data, where "n_samples" is the number of samples and
"n_features" is the number of features.
y : ignored.
Returns
-----... | [
"Fits",
"the",
"imputer",
"on",
"X",
"and",
"return",
"the",
"transformed",
"X",
"."
] | python | train |
aliyun/aliyun-odps-python-sdk | odps/tunnel/pb/output_stream.py | https://github.com/aliyun/aliyun-odps-python-sdk/blob/4b0de18f5864386df6068f26f026e62f932c41e4/odps/tunnel/pb/output_stream.py#L65-L72 | def append_varint32(self, value):
"""Appends a signed 32-bit integer to the internal buffer,
encoded as a varint. (Note that a negative varint32 will
always require 10 bytes of space.)
"""
if not wire_format.INT32_MIN <= value <= wire_format.INT32_MAX:
raise errors.E... | [
"def",
"append_varint32",
"(",
"self",
",",
"value",
")",
":",
"if",
"not",
"wire_format",
".",
"INT32_MIN",
"<=",
"value",
"<=",
"wire_format",
".",
"INT32_MAX",
":",
"raise",
"errors",
".",
"EncodeError",
"(",
"'Value out of range: %d'",
"%",
"value",
")",
... | Appends a signed 32-bit integer to the internal buffer,
encoded as a varint. (Note that a negative varint32 will
always require 10 bytes of space.) | [
"Appends",
"a",
"signed",
"32",
"-",
"bit",
"integer",
"to",
"the",
"internal",
"buffer",
"encoded",
"as",
"a",
"varint",
".",
"(",
"Note",
"that",
"a",
"negative",
"varint32",
"will",
"always",
"require",
"10",
"bytes",
"of",
"space",
".",
")"
] | python | train |
eqcorrscan/EQcorrscan | eqcorrscan/utils/seismo_logs.py | https://github.com/eqcorrscan/EQcorrscan/blob/3121b4aca801ee5d38f56ca297ce1c0f9515d9ff/eqcorrscan/utils/seismo_logs.py#L32-L81 | def rt_time_log(logfile, startdate):
"""
Open and read reftek raw log-file.
Function to open and read a log-file as written by a RefTek RT130
datalogger. The information within is then scanned for timing errors
above the threshold.
:type logfile: str
:param logfile: The logfile to look in
... | [
"def",
"rt_time_log",
"(",
"logfile",
",",
"startdate",
")",
":",
"if",
"os",
".",
"name",
"==",
"'nt'",
":",
"f",
"=",
"io",
".",
"open",
"(",
"logfile",
",",
"'rb'",
")",
"else",
":",
"f",
"=",
"io",
".",
"open",
"(",
"logfile",
",",
"'rb'",
... | Open and read reftek raw log-file.
Function to open and read a log-file as written by a RefTek RT130
datalogger. The information within is then scanned for timing errors
above the threshold.
:type logfile: str
:param logfile: The logfile to look in
:type startdate: datetime.date
:param sta... | [
"Open",
"and",
"read",
"reftek",
"raw",
"log",
"-",
"file",
"."
] | python | train |
senaite/senaite.core | bika/lims/catalog/catalog_utilities.py | https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/catalog/catalog_utilities.py#L250-L301 | def _setup_catalog(portal, catalog_id, catalog_definition):
"""
Given a catalog definition it updates the indexes, columns and content_type
definitions of the catalog.
:portal: the Plone site object
:catalog_id: a string as the catalog id
:catalog_definition: a dictionary like
{
... | [
"def",
"_setup_catalog",
"(",
"portal",
",",
"catalog_id",
",",
"catalog_definition",
")",
":",
"reindex",
"=",
"False",
"catalog",
"=",
"getToolByName",
"(",
"portal",
",",
"catalog_id",
",",
"None",
")",
"if",
"catalog",
"is",
"None",
":",
"logger",
".",
... | Given a catalog definition it updates the indexes, columns and content_type
definitions of the catalog.
:portal: the Plone site object
:catalog_id: a string as the catalog id
:catalog_definition: a dictionary like
{
'types': ['ContentType', ...],
'indexes': {
... | [
"Given",
"a",
"catalog",
"definition",
"it",
"updates",
"the",
"indexes",
"columns",
"and",
"content_type",
"definitions",
"of",
"the",
"catalog",
".",
":",
"portal",
":",
"the",
"Plone",
"site",
"object",
":",
"catalog_id",
":",
"a",
"string",
"as",
"the",
... | python | train |
SBRG/ssbio | ssbio/biopython/Bio/Struct/WWW/WHATIF.py | https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/biopython/Bio/Struct/WWW/WHATIF.py#L58-L76 | def _smcra_to_str(self, smcra, temp_dir='/tmp/'):
"""
WHATIF's input are PDB format files.
Converts a SMCRA object to a PDB formatted string.
"""
temp_path = tempfile.mktemp( '.pdb', dir=temp_dir )
io = PDBIO()
io.set_structure(smcra)
io.... | [
"def",
"_smcra_to_str",
"(",
"self",
",",
"smcra",
",",
"temp_dir",
"=",
"'/tmp/'",
")",
":",
"temp_path",
"=",
"tempfile",
".",
"mktemp",
"(",
"'.pdb'",
",",
"dir",
"=",
"temp_dir",
")",
"io",
"=",
"PDBIO",
"(",
")",
"io",
".",
"set_structure",
"(",
... | WHATIF's input are PDB format files.
Converts a SMCRA object to a PDB formatted string. | [
"WHATIF",
"s",
"input",
"are",
"PDB",
"format",
"files",
".",
"Converts",
"a",
"SMCRA",
"object",
"to",
"a",
"PDB",
"formatted",
"string",
"."
] | python | train |
pyvisa/pyvisa | pyvisa/ctwrapper/functions.py | https://github.com/pyvisa/pyvisa/blob/b8b2d4371e1f00782856aa9176ff1ced6bcb3798/pyvisa/ctwrapper/functions.py#L994-L1015 | def move_in_16(library, session, space, offset, length, extended=False):
"""Moves an 16-bit block of data from the specified address space and offset to local memory.
Corresponds to viMoveIn16* functions of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique lo... | [
"def",
"move_in_16",
"(",
"library",
",",
"session",
",",
"space",
",",
"offset",
",",
"length",
",",
"extended",
"=",
"False",
")",
":",
"buffer_16",
"=",
"(",
"ViUInt16",
"*",
"length",
")",
"(",
")",
"if",
"extended",
":",
"ret",
"=",
"library",
"... | Moves an 16-bit block of data from the specified address space and offset to local memory.
Corresponds to viMoveIn16* functions of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param space: Specifies the address space. (C... | [
"Moves",
"an",
"16",
"-",
"bit",
"block",
"of",
"data",
"from",
"the",
"specified",
"address",
"space",
"and",
"offset",
"to",
"local",
"memory",
"."
] | python | train |
pypa/pipenv | pipenv/vendor/dotenv/cli.py | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/dotenv/cli.py#L24-L28 | def cli(ctx, file, quote):
'''This script is used to set, get or unset values from a .env file.'''
ctx.obj = {}
ctx.obj['FILE'] = file
ctx.obj['QUOTE'] = quote | [
"def",
"cli",
"(",
"ctx",
",",
"file",
",",
"quote",
")",
":",
"ctx",
".",
"obj",
"=",
"{",
"}",
"ctx",
".",
"obj",
"[",
"'FILE'",
"]",
"=",
"file",
"ctx",
".",
"obj",
"[",
"'QUOTE'",
"]",
"=",
"quote"
] | This script is used to set, get or unset values from a .env file. | [
"This",
"script",
"is",
"used",
"to",
"set",
"get",
"or",
"unset",
"values",
"from",
"a",
".",
"env",
"file",
"."
] | python | train |
sdispater/cachy | cachy/tagged_cache.py | https://github.com/sdispater/cachy/blob/ee4b044d6aafa80125730a00b1f679a7bd852b8a/cachy/tagged_cache.py#L225-L243 | def _get_minutes(self, duration):
"""
Calculate the number of minutes with the given duration.
:param duration: The duration
:type duration: int or datetime
:rtype: int or None
"""
if isinstance(duration, datetime.datetime):
from_now = (duration - da... | [
"def",
"_get_minutes",
"(",
"self",
",",
"duration",
")",
":",
"if",
"isinstance",
"(",
"duration",
",",
"datetime",
".",
"datetime",
")",
":",
"from_now",
"=",
"(",
"duration",
"-",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
")",
".",
"total_s... | Calculate the number of minutes with the given duration.
:param duration: The duration
:type duration: int or datetime
:rtype: int or None | [
"Calculate",
"the",
"number",
"of",
"minutes",
"with",
"the",
"given",
"duration",
"."
] | python | train |
google/grumpy | third_party/stdlib/csv.py | https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/csv.py#L218-L292 | def _guess_quote_and_delimiter(self, data, delimiters):
"""
Looks for text enclosed between two identical quotes
(the probable quotechar) which are preceded and followed
by the same character (the probable delimiter).
For example:
,'some text',
Th... | [
"def",
"_guess_quote_and_delimiter",
"(",
"self",
",",
"data",
",",
"delimiters",
")",
":",
"matches",
"=",
"[",
"]",
"for",
"restr",
"in",
"(",
"'(?P<delim>[^\\w\\n\"\\'])(?P<space> ?)(?P<quote>[\"\\']).*?(?P=quote)(?P=delim)'",
",",
"# ,\".*?\",",
"'(?:^|\\n)(?P<quote>[\"... | Looks for text enclosed between two identical quotes
(the probable quotechar) which are preceded and followed
by the same character (the probable delimiter).
For example:
,'some text',
The quote with the most wins, same with the delimiter.
If there is no ... | [
"Looks",
"for",
"text",
"enclosed",
"between",
"two",
"identical",
"quotes",
"(",
"the",
"probable",
"quotechar",
")",
"which",
"are",
"preceded",
"and",
"followed",
"by",
"the",
"same",
"character",
"(",
"the",
"probable",
"delimiter",
")",
".",
"For",
"exa... | python | valid |
SoCo/SoCo | soco/snapshot.py | https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/snapshot.py#L161-L253 | def restore(self, fade=False):
"""Restore the state of a device to that which was previously saved.
For coordinator devices restore everything. For slave devices
only restore volume etc., not transport info (transport info
comes from the slave's coordinator).
Args:
... | [
"def",
"restore",
"(",
"self",
",",
"fade",
"=",
"False",
")",
":",
"if",
"self",
".",
"is_coordinator",
":",
"# Start by ensuring that the speaker is paused as we don't want",
"# things all rolling back when we are changing them, as this could",
"# include things like audio",
"t... | Restore the state of a device to that which was previously saved.
For coordinator devices restore everything. For slave devices
only restore volume etc., not transport info (transport info
comes from the slave's coordinator).
Args:
fade (bool): Whether volume should be fade... | [
"Restore",
"the",
"state",
"of",
"a",
"device",
"to",
"that",
"which",
"was",
"previously",
"saved",
"."
] | python | train |
SeabornGames/Table | seaborn_table/table.py | https://github.com/SeabornGames/Table/blob/0c474ef2fb00db0e7cf47e8af91e3556c2e7485a/seaborn_table/table.py#L1280-L1292 | def pop_empty_columns(self, empty=None):
"""
This will pop columns from the printed columns if they only contain
'' or None
:param empty: list of values to treat as empty
"""
empty = ['', None] if empty is None else empty
if len(self) == 0:
ret... | [
"def",
"pop_empty_columns",
"(",
"self",
",",
"empty",
"=",
"None",
")",
":",
"empty",
"=",
"[",
"''",
",",
"None",
"]",
"if",
"empty",
"is",
"None",
"else",
"empty",
"if",
"len",
"(",
"self",
")",
"==",
"0",
":",
"return",
"for",
"col",
"in",
"l... | This will pop columns from the printed columns if they only contain
'' or None
:param empty: list of values to treat as empty | [
"This",
"will",
"pop",
"columns",
"from",
"the",
"printed",
"columns",
"if",
"they",
"only",
"contain",
"or",
"None",
":",
"param",
"empty",
":",
"list",
"of",
"values",
"to",
"treat",
"as",
"empty"
] | python | train |
IdentityPython/SATOSA | src/satosa/scripts/satosa_saml_metadata.py | https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/scripts/satosa_saml_metadata.py#L38-L63 | def create_and_write_saml_metadata(proxy_conf, key, cert, dir, valid, split_frontend_metadata=False,
split_backend_metadata=False):
"""
Generates SAML metadata for the given PROXY_CONF, signed with the given KEY and associated CERT.
"""
satosa_config = SATOSAConfig(pro... | [
"def",
"create_and_write_saml_metadata",
"(",
"proxy_conf",
",",
"key",
",",
"cert",
",",
"dir",
",",
"valid",
",",
"split_frontend_metadata",
"=",
"False",
",",
"split_backend_metadata",
"=",
"False",
")",
":",
"satosa_config",
"=",
"SATOSAConfig",
"(",
"proxy_co... | Generates SAML metadata for the given PROXY_CONF, signed with the given KEY and associated CERT. | [
"Generates",
"SAML",
"metadata",
"for",
"the",
"given",
"PROXY_CONF",
"signed",
"with",
"the",
"given",
"KEY",
"and",
"associated",
"CERT",
"."
] | python | train |
google/tangent | tangent/cfg.py | https://github.com/google/tangent/blob/6533e83af09de7345d1b438512679992f080dcc9/tangent/cfg.py#L87-L108 | def build_cfg(cls, node):
"""Build a CFG for a function.
Args:
node: A function definition the body of which to analyze.
Returns:
A CFG object.
Raises:
TypeError: If the input is not a function definition.
"""
if not isinstance(node, gast.FunctionDef):
raise TypeError(... | [
"def",
"build_cfg",
"(",
"cls",
",",
"node",
")",
":",
"if",
"not",
"isinstance",
"(",
"node",
",",
"gast",
".",
"FunctionDef",
")",
":",
"raise",
"TypeError",
"(",
"'input must be a function definition'",
")",
"cfg",
"=",
"cls",
"(",
")",
"cfg",
".",
"e... | Build a CFG for a function.
Args:
node: A function definition the body of which to analyze.
Returns:
A CFG object.
Raises:
TypeError: If the input is not a function definition. | [
"Build",
"a",
"CFG",
"for",
"a",
"function",
"."
] | python | train |
blockstack/virtualchain | virtualchain/lib/blockchain/bitcoin_blockchain/spv.py | https://github.com/blockstack/virtualchain/blob/fcfc970064ca7dfcab26ebd3ab955870a763ea39/virtualchain/lib/blockchain/bitcoin_blockchain/spv.py#L221-L238 | def run( self ):
"""
Interact with the blockchain peer,
until we get a socket error or we
exit the loop explicitly.
Return True on success
Raise on error
"""
self.handshake()
try:
self.loop()
except socket.error, se:
... | [
"def",
"run",
"(",
"self",
")",
":",
"self",
".",
"handshake",
"(",
")",
"try",
":",
"self",
".",
"loop",
"(",
")",
"except",
"socket",
".",
"error",
",",
"se",
":",
"if",
"self",
".",
"finished",
":",
"return",
"True",
"else",
":",
"raise"
] | Interact with the blockchain peer,
until we get a socket error or we
exit the loop explicitly.
Return True on success
Raise on error | [
"Interact",
"with",
"the",
"blockchain",
"peer",
"until",
"we",
"get",
"a",
"socket",
"error",
"or",
"we",
"exit",
"the",
"loop",
"explicitly",
".",
"Return",
"True",
"on",
"success",
"Raise",
"on",
"error"
] | python | train |
boundary/pulse-api-cli | boundary/api_call.py | https://github.com/boundary/pulse-api-cli/blob/b01ca65b442eed19faac309c9d62bbc3cb2c098f/boundary/api_call.py#L159-L166 | def _get_url_parameters(self):
"""
Encode URL parameters
"""
url_parameters = ''
if self._url_parameters is not None:
url_parameters = '?' + urllib.urlencode(self._url_parameters)
return url_parameters | [
"def",
"_get_url_parameters",
"(",
"self",
")",
":",
"url_parameters",
"=",
"''",
"if",
"self",
".",
"_url_parameters",
"is",
"not",
"None",
":",
"url_parameters",
"=",
"'?'",
"+",
"urllib",
".",
"urlencode",
"(",
"self",
".",
"_url_parameters",
")",
"return... | Encode URL parameters | [
"Encode",
"URL",
"parameters"
] | python | test |
pyQode/pyqode.core | pyqode/core/widgets/splittable_tab_widget.py | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/splittable_tab_widget.py#L1280-L1297 | def _create_code_edit(self, mimetype, *args, **kwargs):
"""
Create a code edit instance based on the mimetype of the file to
open/create.
:type mimetype: mime type
:param args: Positional arguments that must be forwarded to the editor
widget constructor.
:par... | [
"def",
"_create_code_edit",
"(",
"self",
",",
"mimetype",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"mimetype",
"in",
"self",
".",
"editors",
".",
"keys",
"(",
")",
":",
"return",
"self",
".",
"editors",
"[",
"mimetype",
"]",
"(",
... | Create a code edit instance based on the mimetype of the file to
open/create.
:type mimetype: mime type
:param args: Positional arguments that must be forwarded to the editor
widget constructor.
:param kwargs: Keyworded arguments that must be forwarded to the editor
... | [
"Create",
"a",
"code",
"edit",
"instance",
"based",
"on",
"the",
"mimetype",
"of",
"the",
"file",
"to",
"open",
"/",
"create",
"."
] | python | train |
pytroll/satpy | satpy/composites/__init__.py | https://github.com/pytroll/satpy/blob/1f21d20ac686b745fb0da9b4030d139893e066dd/satpy/composites/__init__.py#L1216-L1223 | def _get_band(self, high_res, low_res, color, ratio):
"""Figure out what data should represent this color."""
if self.high_resolution_band == color:
ret = high_res
else:
ret = low_res * ratio
ret.attrs = low_res.attrs.copy()
return ret | [
"def",
"_get_band",
"(",
"self",
",",
"high_res",
",",
"low_res",
",",
"color",
",",
"ratio",
")",
":",
"if",
"self",
".",
"high_resolution_band",
"==",
"color",
":",
"ret",
"=",
"high_res",
"else",
":",
"ret",
"=",
"low_res",
"*",
"ratio",
"ret",
".",... | Figure out what data should represent this color. | [
"Figure",
"out",
"what",
"data",
"should",
"represent",
"this",
"color",
"."
] | python | train |
VitorRamos/cpufreq | cpufreq/cpufreq.py | https://github.com/VitorRamos/cpufreq/blob/1246e35a8ceeb823df804af34730f7b15dc89204/cpufreq/cpufreq.py#L101-L120 | def reset(self, rg=None):
'''
Enable all offline cpus, and reset max and min frequencies files
rg: range or list of threads to reset
'''
if type(rg) == int:
rg= [rg]
to_reset= rg if rg else self.__get_ranges("present")
self.enable_cpu(to_reset)
... | [
"def",
"reset",
"(",
"self",
",",
"rg",
"=",
"None",
")",
":",
"if",
"type",
"(",
"rg",
")",
"==",
"int",
":",
"rg",
"=",
"[",
"rg",
"]",
"to_reset",
"=",
"rg",
"if",
"rg",
"else",
"self",
".",
"__get_ranges",
"(",
"\"present\"",
")",
"self",
"... | Enable all offline cpus, and reset max and min frequencies files
rg: range or list of threads to reset | [
"Enable",
"all",
"offline",
"cpus",
"and",
"reset",
"max",
"and",
"min",
"frequencies",
"files"
] | python | train |
faucamp/python-gsmmodem | tools/gsmtermlib/terminal.py | https://github.com/faucamp/python-gsmmodem/blob/834c68b1387ca2c91e2210faa8f75526b39723b5/tools/gsmtermlib/terminal.py#L142-L168 | def _inputLoop(self):
""" Loop and copy console->serial until EXIT_CHARCTER character is found. """
try:
while self.alive:
try:
c = console.getkey()
except KeyboardInterrupt:
print('kbint')
... | [
"def",
"_inputLoop",
"(",
"self",
")",
":",
"try",
":",
"while",
"self",
".",
"alive",
":",
"try",
":",
"c",
"=",
"console",
".",
"getkey",
"(",
")",
"except",
"KeyboardInterrupt",
":",
"print",
"(",
"'kbint'",
")",
"c",
"=",
"serial",
".",
"to_bytes... | Loop and copy console->serial until EXIT_CHARCTER character is found. | [
"Loop",
"and",
"copy",
"console",
"-",
">",
"serial",
"until",
"EXIT_CHARCTER",
"character",
"is",
"found",
"."
] | python | train |
IdentityPython/pysaml2 | src/saml2/__init__.py | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/__init__.py#L982-L1013 | def extension_elements_to_elements(extension_elements, schemas):
""" Create a list of elements each one matching one of the
given extension elements. This is of course dependent on the access
to schemas that describe the extension elements.
:param extension_elements: The list of extension elements
... | [
"def",
"extension_elements_to_elements",
"(",
"extension_elements",
",",
"schemas",
")",
":",
"res",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"schemas",
",",
"list",
")",
":",
"pass",
"elif",
"isinstance",
"(",
"schemas",
",",
"dict",
")",
":",
"schemas",
"... | Create a list of elements each one matching one of the
given extension elements. This is of course dependent on the access
to schemas that describe the extension elements.
:param extension_elements: The list of extension elements
:param schemas: Imported Python modules that represent the different
... | [
"Create",
"a",
"list",
"of",
"elements",
"each",
"one",
"matching",
"one",
"of",
"the",
"given",
"extension",
"elements",
".",
"This",
"is",
"of",
"course",
"dependent",
"on",
"the",
"access",
"to",
"schemas",
"that",
"describe",
"the",
"extension",
"element... | python | train |
Becksteinlab/GromacsWrapper | gromacs/cbook.py | https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/cbook.py#L466-L472 | def glob_parts(prefix, ext):
"""Find files from a continuation run"""
if ext.startswith('.'):
ext = ext[1:]
files = glob.glob(prefix+'.'+ext) + glob.glob(prefix+'.part[0-9][0-9][0-9][0-9].'+ext)
files.sort() # at least some rough sorting...
return files | [
"def",
"glob_parts",
"(",
"prefix",
",",
"ext",
")",
":",
"if",
"ext",
".",
"startswith",
"(",
"'.'",
")",
":",
"ext",
"=",
"ext",
"[",
"1",
":",
"]",
"files",
"=",
"glob",
".",
"glob",
"(",
"prefix",
"+",
"'.'",
"+",
"ext",
")",
"+",
"glob",
... | Find files from a continuation run | [
"Find",
"files",
"from",
"a",
"continuation",
"run"
] | python | valid |
eandersson/amqpstorm | amqpstorm/message.py | https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/message.py#L149-L170 | def publish(self, routing_key, exchange='', mandatory=False,
immediate=False):
"""Publish Message.
:param str routing_key: Message routing key
:param str exchange: The exchange to publish the message to
:param bool mandatory: Requires the message is published
:pa... | [
"def",
"publish",
"(",
"self",
",",
"routing_key",
",",
"exchange",
"=",
"''",
",",
"mandatory",
"=",
"False",
",",
"immediate",
"=",
"False",
")",
":",
"return",
"self",
".",
"_channel",
".",
"basic",
".",
"publish",
"(",
"body",
"=",
"self",
".",
"... | Publish Message.
:param str routing_key: Message routing key
:param str exchange: The exchange to publish the message to
:param bool mandatory: Requires the message is published
:param bool immediate: Request immediate delivery
:raises AMQPInvalidArgument: Invalid Parameters
... | [
"Publish",
"Message",
"."
] | python | train |
eddiejessup/spatious | spatious/geom.py | https://github.com/eddiejessup/spatious/blob/b7ae91bec029e85a45a7f303ee184076433723cd/spatious/geom.py#L223-L239 | def spheres_sep(ar, aR, br, bR):
"""Return the separation distance between two spheres.
Parameters
----------
ar, br: array-like, shape (n,) in n dimensions
Coordinates of the centres of the spheres `a` and `b`.
aR, bR: float
Radiuses of the spheres `a` and `b`.
Returns
---... | [
"def",
"spheres_sep",
"(",
"ar",
",",
"aR",
",",
"br",
",",
"bR",
")",
":",
"return",
"vector",
".",
"vector_mag",
"(",
"ar",
"-",
"br",
")",
"-",
"(",
"aR",
"+",
"bR",
")"
] | Return the separation distance between two spheres.
Parameters
----------
ar, br: array-like, shape (n,) in n dimensions
Coordinates of the centres of the spheres `a` and `b`.
aR, bR: float
Radiuses of the spheres `a` and `b`.
Returns
-------
d: float
Separation dis... | [
"Return",
"the",
"separation",
"distance",
"between",
"two",
"spheres",
"."
] | python | train |
BeyondTheClouds/enoslib | enoslib/infra/utils.py | https://github.com/BeyondTheClouds/enoslib/blob/fb00be58e56a7848cfe482187d659744919fe2f7/enoslib/infra/utils.py#L6-L12 | def mk_pools(things, keyfnc=lambda x: x):
"Indexes a thing by the keyfnc to construct pools of things."
pools = {}
sthings = sorted(things, key=keyfnc)
for key, thingz in groupby(sthings, key=keyfnc):
pools.setdefault(key, []).extend(list(thingz))
return pools | [
"def",
"mk_pools",
"(",
"things",
",",
"keyfnc",
"=",
"lambda",
"x",
":",
"x",
")",
":",
"pools",
"=",
"{",
"}",
"sthings",
"=",
"sorted",
"(",
"things",
",",
"key",
"=",
"keyfnc",
")",
"for",
"key",
",",
"thingz",
"in",
"groupby",
"(",
"sthings",
... | Indexes a thing by the keyfnc to construct pools of things. | [
"Indexes",
"a",
"thing",
"by",
"the",
"keyfnc",
"to",
"construct",
"pools",
"of",
"things",
"."
] | python | train |
tgbugs/pyontutils | pyontutils/scigraph_deploy.py | https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/pyontutils/scigraph_deploy.py#L398-L414 | def build(self, mode=None, check=False):
""" Just shuffle the current call off to the build server with --local attached """
kwargs = {}
if not self.build_only: # don't try to deploy twice
kwargs[' --build-only'] = True
if not self.local:
kwargs['--local'] = True... | [
"def",
"build",
"(",
"self",
",",
"mode",
"=",
"None",
",",
"check",
"=",
"False",
")",
":",
"kwargs",
"=",
"{",
"}",
"if",
"not",
"self",
".",
"build_only",
":",
"# don't try to deploy twice",
"kwargs",
"[",
"' --build-only'",
"]",
"=",
"True",
"if",
... | Just shuffle the current call off to the build server with --local attached | [
"Just",
"shuffle",
"the",
"current",
"call",
"off",
"to",
"the",
"build",
"server",
"with",
"--",
"local",
"attached"
] | python | train |
klahnakoski/pyLibrary | mo_dots/__init__.py | https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/mo_dots/__init__.py#L586-L592 | def tuplewrap(value):
"""
INTENDED TO TURN lists INTO tuples FOR USE AS KEYS
"""
if isinstance(value, (list, set, tuple) + generator_types):
return tuple(tuplewrap(v) if is_sequence(v) else v for v in value)
return unwrap(value), | [
"def",
"tuplewrap",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"(",
"list",
",",
"set",
",",
"tuple",
")",
"+",
"generator_types",
")",
":",
"return",
"tuple",
"(",
"tuplewrap",
"(",
"v",
")",
"if",
"is_sequence",
"(",
"v",
")",
... | INTENDED TO TURN lists INTO tuples FOR USE AS KEYS | [
"INTENDED",
"TO",
"TURN",
"lists",
"INTO",
"tuples",
"FOR",
"USE",
"AS",
"KEYS"
] | python | train |
saltstack/salt | salt/states/smartos.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/smartos.py#L205-L225 | def _write_config(config):
'''
writes /usbkey/config
'''
try:
with salt.utils.atomicfile.atomic_open('/usbkey/config', 'w') as config_file:
config_file.write("#\n# This file was generated by salt\n#\n")
for prop in salt.utils.odict.OrderedDict(sorted(config.items())):
... | [
"def",
"_write_config",
"(",
"config",
")",
":",
"try",
":",
"with",
"salt",
".",
"utils",
".",
"atomicfile",
".",
"atomic_open",
"(",
"'/usbkey/config'",
",",
"'w'",
")",
"as",
"config_file",
":",
"config_file",
".",
"write",
"(",
"\"#\\n# This file was gener... | writes /usbkey/config | [
"writes",
"/",
"usbkey",
"/",
"config"
] | python | train |
manns/pyspread | pyspread/src/interfaces/pys.py | https://github.com/manns/pyspread/blob/0e2fd44c2e0f06605efc3058c20a43a8c1f9e7e0/pyspread/src/interfaces/pys.py#L168-L174 | def _pys2code(self, line):
"""Updates code in pys code_array"""
row, col, tab, code = self._split_tidy(line, maxsplit=3)
key = self._get_key(row, col, tab)
self.code_array.dict_grid[key] = unicode(code, encoding='utf-8') | [
"def",
"_pys2code",
"(",
"self",
",",
"line",
")",
":",
"row",
",",
"col",
",",
"tab",
",",
"code",
"=",
"self",
".",
"_split_tidy",
"(",
"line",
",",
"maxsplit",
"=",
"3",
")",
"key",
"=",
"self",
".",
"_get_key",
"(",
"row",
",",
"col",
",",
... | Updates code in pys code_array | [
"Updates",
"code",
"in",
"pys",
"code_array"
] | python | train |
twisted/axiom | axiom/dependency.py | https://github.com/twisted/axiom/blob/7de70bc8fe1bb81f9c2339fba8daec9eb2e92b68/axiom/dependency.py#L150-L172 | def uninstallFrom(self, target):
"""
Remove this object from the target, as well as any dependencies
that it automatically installed which were not explicitly
"pinned" by calling "install", and raising an exception if
anything still depends on this.
"""
#did this class powerup on any interf... | [
"def",
"uninstallFrom",
"(",
"self",
",",
"target",
")",
":",
"#did this class powerup on any interfaces? powerdown if so.",
"target",
".",
"powerDown",
"(",
"self",
")",
"for",
"dc",
"in",
"self",
".",
"store",
".",
"query",
"(",
"_DependencyConnector",
",",
"_De... | Remove this object from the target, as well as any dependencies
that it automatically installed which were not explicitly
"pinned" by calling "install", and raising an exception if
anything still depends on this. | [
"Remove",
"this",
"object",
"from",
"the",
"target",
"as",
"well",
"as",
"any",
"dependencies",
"that",
"it",
"automatically",
"installed",
"which",
"were",
"not",
"explicitly",
"pinned",
"by",
"calling",
"install",
"and",
"raising",
"an",
"exception",
"if",
"... | python | train |
whyscream/dspam-milter | dspam/client.py | https://github.com/whyscream/dspam-milter/blob/f9939b718eed02cb7e56f8c5b921db4cfe1cd85a/dspam/client.py#L512-L524 | def quit(self):
"""
Send LMTP QUIT command, read the server response and disconnect.
"""
self._send('QUIT\r\n')
resp = self._read()
if not resp.startswith('221'):
logger.warning('Unexpected server response at QUIT: ' + resp)
self._socket.close()
... | [
"def",
"quit",
"(",
"self",
")",
":",
"self",
".",
"_send",
"(",
"'QUIT\\r\\n'",
")",
"resp",
"=",
"self",
".",
"_read",
"(",
")",
"if",
"not",
"resp",
".",
"startswith",
"(",
"'221'",
")",
":",
"logger",
".",
"warning",
"(",
"'Unexpected server respon... | Send LMTP QUIT command, read the server response and disconnect. | [
"Send",
"LMTP",
"QUIT",
"command",
"read",
"the",
"server",
"response",
"and",
"disconnect",
"."
] | python | train |
wuher/devil | example/userdb/api/resources.py | https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/example/userdb/api/resources.py#L81-L95 | def _dict_to_model(self, data):
""" Create new user model instance based on the received data.
Note that the created user is not saved into database.
"""
try:
# we can do this because we have same fields
# in the representation and in the model:
user... | [
"def",
"_dict_to_model",
"(",
"self",
",",
"data",
")",
":",
"try",
":",
"# we can do this because we have same fields",
"# in the representation and in the model:",
"user",
"=",
"models",
".",
"User",
"(",
"*",
"*",
"data",
")",
"except",
"TypeError",
":",
"# clien... | Create new user model instance based on the received data.
Note that the created user is not saved into database. | [
"Create",
"new",
"user",
"model",
"instance",
"based",
"on",
"the",
"received",
"data",
"."
] | python | train |
arraylabs/pymyq | pymyq/api.py | https://github.com/arraylabs/pymyq/blob/413ae01ca23568f7b5f698a87e872f456072356b/pymyq/api.py#L91-L104 | async def close_websession(self):
"""Close web session if not already closed and created by us."""
# We do not close the web session if it was provided.
if self._supplied_websession or self._websession is None:
return
_LOGGER.debug('Closing connections')
# Need to se... | [
"async",
"def",
"close_websession",
"(",
"self",
")",
":",
"# We do not close the web session if it was provided.",
"if",
"self",
".",
"_supplied_websession",
"or",
"self",
".",
"_websession",
"is",
"None",
":",
"return",
"_LOGGER",
".",
"debug",
"(",
"'Closing connec... | Close web session if not already closed and created by us. | [
"Close",
"web",
"session",
"if",
"not",
"already",
"closed",
"and",
"created",
"by",
"us",
"."
] | python | train |
influxdata/influxdb-python | influxdb/influxdb08/client.py | https://github.com/influxdata/influxdb-python/blob/d5d12499f3755199d5eedd8b363450f1cf4073bd/influxdb/influxdb08/client.py#L660-L673 | def alter_database_admin(self, username, is_admin):
"""Alter the database admin."""
url = "db/{0}/users/{1}".format(self._database, username)
data = {'admin': is_admin}
self.request(
url=url,
method='POST',
data=data,
expected_response_co... | [
"def",
"alter_database_admin",
"(",
"self",
",",
"username",
",",
"is_admin",
")",
":",
"url",
"=",
"\"db/{0}/users/{1}\"",
".",
"format",
"(",
"self",
".",
"_database",
",",
"username",
")",
"data",
"=",
"{",
"'admin'",
":",
"is_admin",
"}",
"self",
".",
... | Alter the database admin. | [
"Alter",
"the",
"database",
"admin",
"."
] | python | train |
fishtown-analytics/dbt | core/dbt/adapters/cache.py | https://github.com/fishtown-analytics/dbt/blob/aa4f771df28b307af0cf9fe2fc24432f10a8236b/core/dbt/adapters/cache.py#L360-L390 | def _rename_relation(self, old_key, new_relation):
"""Rename a relation named old_key to new_key, updating references.
Return whether or not there was a key to rename.
:param _ReferenceKey old_key: The existing key, to rename from.
:param _CachedRelation new_key: The new relation, to re... | [
"def",
"_rename_relation",
"(",
"self",
",",
"old_key",
",",
"new_relation",
")",
":",
"# On the database level, a rename updates all values that were",
"# previously referenced by old_name to be referenced by new_name.",
"# basically, the name changes but some underlying ID moves. Kind of",... | Rename a relation named old_key to new_key, updating references.
Return whether or not there was a key to rename.
:param _ReferenceKey old_key: The existing key, to rename from.
:param _CachedRelation new_key: The new relation, to rename to. | [
"Rename",
"a",
"relation",
"named",
"old_key",
"to",
"new_key",
"updating",
"references",
".",
"Return",
"whether",
"or",
"not",
"there",
"was",
"a",
"key",
"to",
"rename",
"."
] | python | train |
jaraco/svg.charts | svg/charts/graph.py | https://github.com/jaraco/svg.charts/blob/23053497b3f1af4e760f355050107ae3bc05909d/svg/charts/graph.py#L482-L491 | def draw_titles(self):
"Draws the graph title and subtitle"
if self.show_graph_title:
self.draw_graph_title()
if self.show_graph_subtitle:
self.draw_graph_subtitle()
if self.show_x_title:
self.draw_x_title()
if self.show_y_title:
self.draw_y_title() | [
"def",
"draw_titles",
"(",
"self",
")",
":",
"if",
"self",
".",
"show_graph_title",
":",
"self",
".",
"draw_graph_title",
"(",
")",
"if",
"self",
".",
"show_graph_subtitle",
":",
"self",
".",
"draw_graph_subtitle",
"(",
")",
"if",
"self",
".",
"show_x_title"... | Draws the graph title and subtitle | [
"Draws",
"the",
"graph",
"title",
"and",
"subtitle"
] | python | test |
mikekatz04/BOWIE | snr_calculator_folder/gwsnrcalc/gw_snr_calculator.py | https://github.com/mikekatz04/BOWIE/blob/a941342a3536cb57c817a1643896d99a3f354a86/snr_calculator_folder/gwsnrcalc/gw_snr_calculator.py#L102-L144 | def parallel_snr_func(num, binary_args, phenomdwave, signal_type,
noise_interpolants, prefactor, verbose):
"""SNR calulation with PhenomDWaveforms
Generate PhenomDWaveforms and calculate their SNR against sensitivity curves.
Args:
num (int): Process number. If only a single p... | [
"def",
"parallel_snr_func",
"(",
"num",
",",
"binary_args",
",",
"phenomdwave",
",",
"signal_type",
",",
"noise_interpolants",
",",
"prefactor",
",",
"verbose",
")",
":",
"wave",
"=",
"phenomdwave",
"(",
"*",
"binary_args",
")",
"out_vals",
"=",
"{",
"}",
"f... | SNR calulation with PhenomDWaveforms
Generate PhenomDWaveforms and calculate their SNR against sensitivity curves.
Args:
num (int): Process number. If only a single process, num=0.
binary_args (tuple): Binary arguments for
:meth:`gwsnrcalc.utils.waveforms.EccentricBinaries.__call__... | [
"SNR",
"calulation",
"with",
"PhenomDWaveforms"
] | python | train |
tBaxter/tango-comments | build/lib/tango_comments/forms.py | https://github.com/tBaxter/tango-comments/blob/1fd335c6fc9e81bba158e42e1483f1a149622ab4/build/lib/tango_comments/forms.py#L55-L60 | def clean_timestamp(self):
"""Make sure the timestamp isn't too far (> 2 hours) in the past."""
ts = self.cleaned_data["timestamp"]
if time.time() - ts > (2 * 60 * 60):
raise forms.ValidationError("Timestamp check failed")
return ts | [
"def",
"clean_timestamp",
"(",
"self",
")",
":",
"ts",
"=",
"self",
".",
"cleaned_data",
"[",
"\"timestamp\"",
"]",
"if",
"time",
".",
"time",
"(",
")",
"-",
"ts",
">",
"(",
"2",
"*",
"60",
"*",
"60",
")",
":",
"raise",
"forms",
".",
"ValidationErr... | Make sure the timestamp isn't too far (> 2 hours) in the past. | [
"Make",
"sure",
"the",
"timestamp",
"isn",
"t",
"too",
"far",
"(",
">",
"2",
"hours",
")",
"in",
"the",
"past",
"."
] | python | train |
jilljenn/tryalgo | tryalgo/knuth_morris_pratt.py | https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/knuth_morris_pratt.py#L10-L26 | def maximum_border_length(w):
"""Maximum string borders by Knuth-Morris-Pratt
:param w: string
:returns: table f such that f[i] is the longest border length of w[:i + 1]
:complexity: linear
"""
n = len(w)
f = [0] * n # init f[0] = 0
k = 0 # current lo... | [
"def",
"maximum_border_length",
"(",
"w",
")",
":",
"n",
"=",
"len",
"(",
"w",
")",
"f",
"=",
"[",
"0",
"]",
"*",
"n",
"# init f[0] = 0",
"k",
"=",
"0",
"# current longest border length",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"n",
")",
":",
"# ... | Maximum string borders by Knuth-Morris-Pratt
:param w: string
:returns: table f such that f[i] is the longest border length of w[:i + 1]
:complexity: linear | [
"Maximum",
"string",
"borders",
"by",
"Knuth",
"-",
"Morris",
"-",
"Pratt"
] | python | train |
wandb/client | wandb/vendor/prompt_toolkit/contrib/regular_languages/compiler.py | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/contrib/regular_languages/compiler.py#L289-L299 | def _nodes_to_values(self):
"""
Returns list of list of (Node, string_value) tuples.
"""
def is_none(slice):
return slice[0] == -1 and slice[1] == -1
def get(slice):
return self.string[slice[0]:slice[1]]
return [(varname, get(slice), slice) for v... | [
"def",
"_nodes_to_values",
"(",
"self",
")",
":",
"def",
"is_none",
"(",
"slice",
")",
":",
"return",
"slice",
"[",
"0",
"]",
"==",
"-",
"1",
"and",
"slice",
"[",
"1",
"]",
"==",
"-",
"1",
"def",
"get",
"(",
"slice",
")",
":",
"return",
"self",
... | Returns list of list of (Node, string_value) tuples. | [
"Returns",
"list",
"of",
"list",
"of",
"(",
"Node",
"string_value",
")",
"tuples",
"."
] | python | train |
limix/bgen-reader-py | libpath.py | https://github.com/limix/bgen-reader-py/blob/3f66a39e15a71b981e8c5f887a4adc3ad486a45f/libpath.py#L109-L119 | def find_libname(self, name):
"""Try to infer the correct library name."""
names = ["{}.lib", "lib{}.lib", "{}lib.lib"]
names = [n.format(name) for n in names]
dirs = self.get_library_dirs()
for d in dirs:
for n in names:
if exists(join(d, n)):
... | [
"def",
"find_libname",
"(",
"self",
",",
"name",
")",
":",
"names",
"=",
"[",
"\"{}.lib\"",
",",
"\"lib{}.lib\"",
",",
"\"{}lib.lib\"",
"]",
"names",
"=",
"[",
"n",
".",
"format",
"(",
"name",
")",
"for",
"n",
"in",
"names",
"]",
"dirs",
"=",
"self",... | Try to infer the correct library name. | [
"Try",
"to",
"infer",
"the",
"correct",
"library",
"name",
"."
] | python | valid |
pantsbuild/pants | src/python/pants/java/nailgun_protocol.py | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/java/nailgun_protocol.py#L302-L304 | def send_stderr(cls, sock, payload):
"""Send the Stderr chunk over the specified socket."""
cls.write_chunk(sock, ChunkType.STDERR, payload) | [
"def",
"send_stderr",
"(",
"cls",
",",
"sock",
",",
"payload",
")",
":",
"cls",
".",
"write_chunk",
"(",
"sock",
",",
"ChunkType",
".",
"STDERR",
",",
"payload",
")"
] | Send the Stderr chunk over the specified socket. | [
"Send",
"the",
"Stderr",
"chunk",
"over",
"the",
"specified",
"socket",
"."
] | python | train |
watson-developer-cloud/python-sdk | ibm_watson/speech_to_text_v1.py | https://github.com/watson-developer-cloud/python-sdk/blob/4c2c9df4466fcde88975da9ecd834e6ba95eb353/ibm_watson/speech_to_text_v1.py#L4858-L4870 | def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'transcript') and self.transcript is not None:
_dict['transcript'] = self.transcript
if hasattr(self, 'confidence') and self.confidence is not None:
_dict['conf... | [
"def",
"_to_dict",
"(",
"self",
")",
":",
"_dict",
"=",
"{",
"}",
"if",
"hasattr",
"(",
"self",
",",
"'transcript'",
")",
"and",
"self",
".",
"transcript",
"is",
"not",
"None",
":",
"_dict",
"[",
"'transcript'",
"]",
"=",
"self",
".",
"transcript",
"... | Return a json dictionary representing this model. | [
"Return",
"a",
"json",
"dictionary",
"representing",
"this",
"model",
"."
] | python | train |
notifiers/notifiers | notifiers/utils/schema/formats.py | https://github.com/notifiers/notifiers/blob/6dd8aafff86935dbb4763db9c56f9cdd7fc08b65/notifiers/utils/schema/formats.py#L25-L29 | def is_iso8601(instance: str):
"""Validates ISO8601 format"""
if not isinstance(instance, str):
return True
return ISO8601.match(instance) is not None | [
"def",
"is_iso8601",
"(",
"instance",
":",
"str",
")",
":",
"if",
"not",
"isinstance",
"(",
"instance",
",",
"str",
")",
":",
"return",
"True",
"return",
"ISO8601",
".",
"match",
"(",
"instance",
")",
"is",
"not",
"None"
] | Validates ISO8601 format | [
"Validates",
"ISO8601",
"format"
] | python | train |
bspaans/python-mingus | mingus/midi/pyfluidsynth.py | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/pyfluidsynth.py#L242-L256 | def cc(self, chan, ctrl, val):
"""Send control change value.
The controls that are recognized are dependent on the
SoundFont. Values are always 0 to 127. Typical controls
include:
1: vibrato
7: volume
10: pan (left to right)
11: expression (soft... | [
"def",
"cc",
"(",
"self",
",",
"chan",
",",
"ctrl",
",",
"val",
")",
":",
"return",
"fluid_synth_cc",
"(",
"self",
".",
"synth",
",",
"chan",
",",
"ctrl",
",",
"val",
")"
] | Send control change value.
The controls that are recognized are dependent on the
SoundFont. Values are always 0 to 127. Typical controls
include:
1: vibrato
7: volume
10: pan (left to right)
11: expression (soft to loud)
64: sustain
... | [
"Send",
"control",
"change",
"value",
"."
] | python | train |
streamlink/streamlink | src/streamlink/plugin/api/validate.py | https://github.com/streamlink/streamlink/blob/c8ed1daff14ac03195870238b9b900c1109dd5c1/src/streamlink/plugin/api/validate.py#L109-L118 | def length(length):
"""Checks value for minimum length using len()."""
def min_len(value):
if not len(value) >= length:
raise ValueError(
"Minimum length is {0} but value is {1}".format(length, len(value))
)
return True
return min_len | [
"def",
"length",
"(",
"length",
")",
":",
"def",
"min_len",
"(",
"value",
")",
":",
"if",
"not",
"len",
"(",
"value",
")",
">=",
"length",
":",
"raise",
"ValueError",
"(",
"\"Minimum length is {0} but value is {1}\"",
".",
"format",
"(",
"length",
",",
"le... | Checks value for minimum length using len(). | [
"Checks",
"value",
"for",
"minimum",
"length",
"using",
"len",
"()",
"."
] | python | test |
DistrictDataLabs/yellowbrick | yellowbrick/regressor/residuals.py | https://github.com/DistrictDataLabs/yellowbrick/blob/59b67236a3862c73363e8edad7cd86da5b69e3b2/yellowbrick/regressor/residuals.py#L456-L474 | def fit(self, X, y, **kwargs):
"""
Parameters
----------
X : ndarray or DataFrame of shape n x m
A matrix of n instances with m features
y : ndarray or Series of length n
An array or series of target values
kwargs: keyword arguments passed to Sci... | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
",",
"*",
"*",
"kwargs",
")",
":",
"super",
"(",
"ResidualsPlot",
",",
"self",
")",
".",
"fit",
"(",
"X",
",",
"y",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"score",
"(",
"X",
",",
"y",
",",
... | Parameters
----------
X : ndarray or DataFrame of shape n x m
A matrix of n instances with m features
y : ndarray or Series of length n
An array or series of target values
kwargs: keyword arguments passed to Scikit-Learn API.
Returns
-------
... | [
"Parameters",
"----------",
"X",
":",
"ndarray",
"or",
"DataFrame",
"of",
"shape",
"n",
"x",
"m",
"A",
"matrix",
"of",
"n",
"instances",
"with",
"m",
"features"
] | python | train |
koenedaele/skosprovider | skosprovider/skos.py | https://github.com/koenedaele/skosprovider/blob/7304a37953978ca8227febc2d3cc2b2be178f215/skosprovider/skos.py#L596-L615 | def dict_to_note(dict):
'''
Transform a dict with keys `note`, `type` and `language` into a
:class:`Note`.
Only the `note` key is mandatory. If `type` is not present, it will
default to `note`. If `language` is not present, it will default to `und`.
If `markup` is not present it will default to... | [
"def",
"dict_to_note",
"(",
"dict",
")",
":",
"if",
"isinstance",
"(",
"dict",
",",
"Note",
")",
":",
"return",
"dict",
"return",
"Note",
"(",
"dict",
"[",
"'note'",
"]",
",",
"dict",
".",
"get",
"(",
"'type'",
",",
"'note'",
")",
",",
"dict",
".",... | Transform a dict with keys `note`, `type` and `language` into a
:class:`Note`.
Only the `note` key is mandatory. If `type` is not present, it will
default to `note`. If `language` is not present, it will default to `und`.
If `markup` is not present it will default to `None`.
If the argument passed... | [
"Transform",
"a",
"dict",
"with",
"keys",
"note",
"type",
"and",
"language",
"into",
"a",
":",
"class",
":",
"Note",
"."
] | python | valid |
JukeboxPipeline/jukebox-core | src/jukeboxcore/plugins.py | https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/plugins.py#L94-L104 | def _unload(self, ):
"""Unloads the plugin
:raises: errors.PluginUninitError
"""
try:
self.uninit()
except Exception as e:
log.exception("Unload failed!")
raise errors.PluginUninitError('%s' % e)
self.__status = self.__UNLOADED | [
"def",
"_unload",
"(",
"self",
",",
")",
":",
"try",
":",
"self",
".",
"uninit",
"(",
")",
"except",
"Exception",
"as",
"e",
":",
"log",
".",
"exception",
"(",
"\"Unload failed!\"",
")",
"raise",
"errors",
".",
"PluginUninitError",
"(",
"'%s'",
"%",
"e... | Unloads the plugin
:raises: errors.PluginUninitError | [
"Unloads",
"the",
"plugin"
] | python | train |
swharden/SWHLab | doc/uses/EPSCs-and-IPSCs/smooth histogram method/01.py | https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/doc/uses/EPSCs-and-IPSCs/smooth histogram method/01.py#L19-L28 | def kernel_gaussian(size=100, sigma=None, forwardOnly=False):
"""
return a 1d gassuan array of a given size and sigma.
If sigma isn't given, it will be 1/10 of the size, which is usually good.
"""
if sigma is None:sigma=size/10
points=np.exp(-np.power(np.arange(size)-size/2,2)/(2*np.power(sigma,... | [
"def",
"kernel_gaussian",
"(",
"size",
"=",
"100",
",",
"sigma",
"=",
"None",
",",
"forwardOnly",
"=",
"False",
")",
":",
"if",
"sigma",
"is",
"None",
":",
"sigma",
"=",
"size",
"/",
"10",
"points",
"=",
"np",
".",
"exp",
"(",
"-",
"np",
".",
"po... | return a 1d gassuan array of a given size and sigma.
If sigma isn't given, it will be 1/10 of the size, which is usually good. | [
"return",
"a",
"1d",
"gassuan",
"array",
"of",
"a",
"given",
"size",
"and",
"sigma",
".",
"If",
"sigma",
"isn",
"t",
"given",
"it",
"will",
"be",
"1",
"/",
"10",
"of",
"the",
"size",
"which",
"is",
"usually",
"good",
"."
] | python | valid |
DLR-RM/RAFCON | source/rafcon/gui/mygaphas/items/state.py | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/mygaphas/items/state.py#L336-L345 | def show_content(self, with_content=False):
"""Checks if the state is a library with the `show_content` flag set
:param with_content: If this parameter is `True`, the method return only True if the library represents a
ContainerState
:return: Whether the content of a library state is ... | [
"def",
"show_content",
"(",
"self",
",",
"with_content",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"model",
",",
"LibraryStateModel",
")",
"and",
"self",
".",
"model",
".",
"show_content",
"(",
")",
":",
"return",
"not",
"with_content",... | Checks if the state is a library with the `show_content` flag set
:param with_content: If this parameter is `True`, the method return only True if the library represents a
ContainerState
:return: Whether the content of a library state is shown | [
"Checks",
"if",
"the",
"state",
"is",
"a",
"library",
"with",
"the",
"show_content",
"flag",
"set"
] | python | train |
optimizely/python-sdk | optimizely/event_builder.py | https://github.com/optimizely/python-sdk/blob/ec028d9efcf22498c3820f2650fa10f5c30bec90/optimizely/event_builder.py#L109-L138 | def _get_common_params(self, user_id, attributes):
""" Get params which are used same in both conversion and impression events.
Args:
user_id: ID for user.
attributes: Dict representing user attributes and values which need to be recorded.
Returns:
Dict consisting of parameters common to ... | [
"def",
"_get_common_params",
"(",
"self",
",",
"user_id",
",",
"attributes",
")",
":",
"commonParams",
"=",
"{",
"}",
"commonParams",
"[",
"self",
".",
"EventParams",
".",
"PROJECT_ID",
"]",
"=",
"self",
".",
"_get_project_id",
"(",
")",
"commonParams",
"[",... | Get params which are used same in both conversion and impression events.
Args:
user_id: ID for user.
attributes: Dict representing user attributes and values which need to be recorded.
Returns:
Dict consisting of parameters common to both impression and conversion events. | [
"Get",
"params",
"which",
"are",
"used",
"same",
"in",
"both",
"conversion",
"and",
"impression",
"events",
"."
] | python | train |
photo/openphoto-python | trovebox/http.py | https://github.com/photo/openphoto-python/blob/209a1da27c8d8c88dbcf4ea6c6f57031ea1bc44b/trovebox/http.py#L196-L202 | def _process_params(self, params):
""" Converts Unicode/lists/booleans inside HTTP parameters """
processed_params = {}
for key, value in params.items():
processed_params[key] = self._process_param_value(value)
return processed_params | [
"def",
"_process_params",
"(",
"self",
",",
"params",
")",
":",
"processed_params",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"params",
".",
"items",
"(",
")",
":",
"processed_params",
"[",
"key",
"]",
"=",
"self",
".",
"_process_param_value",
"("... | Converts Unicode/lists/booleans inside HTTP parameters | [
"Converts",
"Unicode",
"/",
"lists",
"/",
"booleans",
"inside",
"HTTP",
"parameters"
] | python | train |
WoLpH/python-statsd | statsd/connection.py | https://github.com/WoLpH/python-statsd/blob/a757da04375c48d03d322246405b33382d37f03f/statsd/connection.py#L47-L81 | def send(self, data, sample_rate=None):
'''Send the data over UDP while taking the sample_rate in account
The sample rate should be a number between `0` and `1` which indicates
the probability that a message will be sent. The sample_rate is also
communicated to `statsd` so it knows what... | [
"def",
"send",
"(",
"self",
",",
"data",
",",
"sample_rate",
"=",
"None",
")",
":",
"if",
"self",
".",
"_disabled",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"'Connection disabled, not sending data'",
")",
"return",
"False",
"if",
"sample_rate",
"is",
... | Send the data over UDP while taking the sample_rate in account
The sample rate should be a number between `0` and `1` which indicates
the probability that a message will be sent. The sample_rate is also
communicated to `statsd` so it knows what multiplier to use.
:keyword data: The dat... | [
"Send",
"the",
"data",
"over",
"UDP",
"while",
"taking",
"the",
"sample_rate",
"in",
"account"
] | python | train |
log2timeline/plaso | plaso/lib/objectfilter.py | https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/lib/objectfilter.py#L782-L788 | def InsertFloatArg(self, string='', **unused_kwargs):
"""Inserts a Float argument."""
try:
float_value = float(string)
except (TypeError, ValueError):
raise errors.ParseError('{0:s} is not a valid float.'.format(string))
return self.InsertArg(float_value) | [
"def",
"InsertFloatArg",
"(",
"self",
",",
"string",
"=",
"''",
",",
"*",
"*",
"unused_kwargs",
")",
":",
"try",
":",
"float_value",
"=",
"float",
"(",
"string",
")",
"except",
"(",
"TypeError",
",",
"ValueError",
")",
":",
"raise",
"errors",
".",
"Par... | Inserts a Float argument. | [
"Inserts",
"a",
"Float",
"argument",
"."
] | python | train |
ulule/django-linguist | linguist/metaclasses.py | https://github.com/ulule/django-linguist/blob/d2b95a6ab921039d56d5eeb352badfe5be9e8f77/linguist/metaclasses.py#L41-L59 | def default_value_getter(field):
"""
When accessing to the name of the field itself, the value
in the current language will be returned. Unless it's set,
the value in the default language will be returned.
"""
def default_value_func_getter(self):
localized_field = utils.build_localized_... | [
"def",
"default_value_getter",
"(",
"field",
")",
":",
"def",
"default_value_func_getter",
"(",
"self",
")",
":",
"localized_field",
"=",
"utils",
".",
"build_localized_field_name",
"(",
"field",
",",
"self",
".",
"_linguist",
".",
"active_language",
")",
"value",... | When accessing to the name of the field itself, the value
in the current language will be returned. Unless it's set,
the value in the default language will be returned. | [
"When",
"accessing",
"to",
"the",
"name",
"of",
"the",
"field",
"itself",
"the",
"value",
"in",
"the",
"current",
"language",
"will",
"be",
"returned",
".",
"Unless",
"it",
"s",
"set",
"the",
"value",
"in",
"the",
"default",
"language",
"will",
"be",
"re... | python | train |
django-xxx/django-mobi2 | mobi2/middleware.py | https://github.com/django-xxx/django-mobi2/blob/7ac323faa1a9599f3cd39acd3c49626819ce0538/mobi2/middleware.py#L26-L64 | def process_request(request):
"""Adds a "mobile" attribute to the request which is True or False
depending on whether the request should be considered to come from a
small-screen device such as a phone or a PDA"""
if 'HTTP_X_OPERAMINI_FEATURES' in request.META:
# Then ... | [
"def",
"process_request",
"(",
"request",
")",
":",
"if",
"'HTTP_X_OPERAMINI_FEATURES'",
"in",
"request",
".",
"META",
":",
"# Then it's running opera mini. 'Nuff said.",
"# Reference from:",
"# http://dev.opera.com/articles/view/opera-mini-request-headers/",
"request",
".",
"mob... | Adds a "mobile" attribute to the request which is True or False
depending on whether the request should be considered to come from a
small-screen device such as a phone or a PDA | [
"Adds",
"a",
"mobile",
"attribute",
"to",
"the",
"request",
"which",
"is",
"True",
"or",
"False",
"depending",
"on",
"whether",
"the",
"request",
"should",
"be",
"considered",
"to",
"come",
"from",
"a",
"small",
"-",
"screen",
"device",
"such",
"as",
"a",
... | python | train |
jakevdp/lpproj | lpproj/lpproj.py | https://github.com/jakevdp/lpproj/blob/9c9042b0c2d16c153b53dcc0a759c7fe8c272176/lpproj/lpproj.py#L105-L173 | def eigh_robust(a, b=None, eigvals=None, eigvals_only=False,
overwrite_a=False, overwrite_b=False,
turbo=True, check_finite=True):
"""Robustly solve the Hermitian generalized eigenvalue problem
This function robustly solves the Hermetian generalized eigenvalue problem
``A v ... | [
"def",
"eigh_robust",
"(",
"a",
",",
"b",
"=",
"None",
",",
"eigvals",
"=",
"None",
",",
"eigvals_only",
"=",
"False",
",",
"overwrite_a",
"=",
"False",
",",
"overwrite_b",
"=",
"False",
",",
"turbo",
"=",
"True",
",",
"check_finite",
"=",
"True",
")",... | Robustly solve the Hermitian generalized eigenvalue problem
This function robustly solves the Hermetian generalized eigenvalue problem
``A v = lambda B v`` in the case that B is not strictly positive definite.
When B is strictly positive-definite, the result is equivalent to
scipy.linalg.eigh() within ... | [
"Robustly",
"solve",
"the",
"Hermitian",
"generalized",
"eigenvalue",
"problem"
] | python | train |
alevinval/scheduling | scheduling/graph.py | https://github.com/alevinval/scheduling/blob/127239712c0b73b929ca19b4b5c2855eebb7fcf0/scheduling/graph.py#L60-L67 | def depends(self, *nodes):
""" Adds nodes as relatives to this one, and
updates the relatives with self as children.
:param nodes: GraphNode(s)
"""
for node in nodes:
self.add_relative(node)
node.add_children(self) | [
"def",
"depends",
"(",
"self",
",",
"*",
"nodes",
")",
":",
"for",
"node",
"in",
"nodes",
":",
"self",
".",
"add_relative",
"(",
"node",
")",
"node",
".",
"add_children",
"(",
"self",
")"
] | Adds nodes as relatives to this one, and
updates the relatives with self as children.
:param nodes: GraphNode(s) | [
"Adds",
"nodes",
"as",
"relatives",
"to",
"this",
"one",
"and",
"updates",
"the",
"relatives",
"with",
"self",
"as",
"children",
".",
":",
"param",
"nodes",
":",
"GraphNode",
"(",
"s",
")"
] | python | train |
glue-viz/glue-vispy-viewers | glue_vispy_viewers/extern/vispy/gloo/gl/_pyopengl2.py | https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/gloo/gl/_pyopengl2.py#L22-L30 | def glBufferData(target, data, usage):
""" Data can be numpy array or the size of data to allocate.
"""
if isinstance(data, int):
size = data
data = None
else:
size = data.nbytes
GL.glBufferData(target, size, data, usage) | [
"def",
"glBufferData",
"(",
"target",
",",
"data",
",",
"usage",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"int",
")",
":",
"size",
"=",
"data",
"data",
"=",
"None",
"else",
":",
"size",
"=",
"data",
".",
"nbytes",
"GL",
".",
"glBufferData",
... | Data can be numpy array or the size of data to allocate. | [
"Data",
"can",
"be",
"numpy",
"array",
"or",
"the",
"size",
"of",
"data",
"to",
"allocate",
"."
] | python | train |
psd-tools/psd-tools | src/psd_tools/api/pil_io.py | https://github.com/psd-tools/psd-tools/blob/4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e/src/psd_tools/api/pil_io.py#L120-L138 | def convert_mask_to_pil(mask, real=True):
"""Convert Mask to PIL Image."""
from PIL import Image
header = mask._layer._psd._record.header
channel_ids = [ci.id for ci in mask._layer._record.channel_info]
if real and mask._has_real():
width = mask._data.real_right - mask._data.real_left
... | [
"def",
"convert_mask_to_pil",
"(",
"mask",
",",
"real",
"=",
"True",
")",
":",
"from",
"PIL",
"import",
"Image",
"header",
"=",
"mask",
".",
"_layer",
".",
"_psd",
".",
"_record",
".",
"header",
"channel_ids",
"=",
"[",
"ci",
".",
"id",
"for",
"ci",
... | Convert Mask to PIL Image. | [
"Convert",
"Mask",
"to",
"PIL",
"Image",
"."
] | python | train |
lsbardel/python-stdnet | stdnet/backends/redisb/__init__.py | https://github.com/lsbardel/python-stdnet/blob/78db5320bdedc3f28c5e4f38cda13a4469e35db7/stdnet/backends/redisb/__init__.py#L346-L363 | def related_lua_args(self):
'''Generator of load_related arguments'''
related = self.queryelem.select_related
if related:
meta = self.meta
for rel in related:
field = meta.dfields[rel]
relmodel = field.relmodel
bk = ... | [
"def",
"related_lua_args",
"(",
"self",
")",
":",
"related",
"=",
"self",
".",
"queryelem",
".",
"select_related",
"if",
"related",
":",
"meta",
"=",
"self",
".",
"meta",
"for",
"rel",
"in",
"related",
":",
"field",
"=",
"meta",
".",
"dfields",
"[",
"r... | Generator of load_related arguments | [
"Generator",
"of",
"load_related",
"arguments"
] | python | train |
jonathf/chaospy | chaospy/bertran/operators.py | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/bertran/operators.py#L291-L330 | def olindex(order, dim):
"""
Create an lexiographical sorted basis for a given order.
Examples
--------
>>> chaospy.bertran.olindex(3, 2)
array([[0, 3],
[1, 2],
[2, 1],
[3, 0]])
"""
idxm = [0]*dim
out = []
def _olindex(idx):
"""Recursive... | [
"def",
"olindex",
"(",
"order",
",",
"dim",
")",
":",
"idxm",
"=",
"[",
"0",
"]",
"*",
"dim",
"out",
"=",
"[",
"]",
"def",
"_olindex",
"(",
"idx",
")",
":",
"\"\"\"Recursive backend for olindex.\"\"\"",
"if",
"numpy",
".",
"sum",
"(",
"idxm",
")",
"=... | Create an lexiographical sorted basis for a given order.
Examples
--------
>>> chaospy.bertran.olindex(3, 2)
array([[0, 3],
[1, 2],
[2, 1],
[3, 0]]) | [
"Create",
"an",
"lexiographical",
"sorted",
"basis",
"for",
"a",
"given",
"order",
"."
] | python | train |
matttproud/python_quantile_estimation | com/matttproud/quantile/__init__.py | https://github.com/matttproud/python_quantile_estimation/blob/698c329077805375d2a5e4191ec4709289150fd6/com/matttproud/quantile/__init__.py#L99-L118 | def _replace_batch(self):
"""Incorporates all pending values into the estimator."""
if not self._head:
self._head, self._buffer = self._record(self._buffer[0], 1, 0, None), self._buffer[1:]
rank = 0.0
current = self._head
for b in self._buffer:
if b < self... | [
"def",
"_replace_batch",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_head",
":",
"self",
".",
"_head",
",",
"self",
".",
"_buffer",
"=",
"self",
".",
"_record",
"(",
"self",
".",
"_buffer",
"[",
"0",
"]",
",",
"1",
",",
"0",
",",
"None",
... | Incorporates all pending values into the estimator. | [
"Incorporates",
"all",
"pending",
"values",
"into",
"the",
"estimator",
"."
] | python | train |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/psutil/__init__.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/psutil/__init__.py#L868-L926 | def cpu_percent(interval=0.1, percpu=False):
"""Return a float representing the current system-wide CPU
utilization as a percentage.
When interval is > 0.0 compares system CPU times elapsed before
and after the interval (blocking).
When interval is 0.0 or None compares system CPU times elapsed
... | [
"def",
"cpu_percent",
"(",
"interval",
"=",
"0.1",
",",
"percpu",
"=",
"False",
")",
":",
"global",
"_last_cpu_times",
"global",
"_last_per_cpu_times",
"blocking",
"=",
"interval",
"is",
"not",
"None",
"and",
"interval",
">",
"0.0",
"def",
"calculate",
"(",
... | Return a float representing the current system-wide CPU
utilization as a percentage.
When interval is > 0.0 compares system CPU times elapsed before
and after the interval (blocking).
When interval is 0.0 or None compares system CPU times elapsed
since last call or module import, returning immedia... | [
"Return",
"a",
"float",
"representing",
"the",
"current",
"system",
"-",
"wide",
"CPU",
"utilization",
"as",
"a",
"percentage",
"."
] | python | test |
rigetti/pyquil | pyquil/noise.py | https://github.com/rigetti/pyquil/blob/ec98e453084b0037d69d8c3245f6822a5422593d/pyquil/noise.py#L202-L217 | def _create_kraus_pragmas(name, qubit_indices, kraus_ops):
"""
Generate the pragmas to define a Kraus map for a specific gate on some qubits.
:param str name: The name of the gate.
:param list|tuple qubit_indices: The qubits
:param list|tuple kraus_ops: The Kraus operators as matrices.
:return:... | [
"def",
"_create_kraus_pragmas",
"(",
"name",
",",
"qubit_indices",
",",
"kraus_ops",
")",
":",
"pragmas",
"=",
"[",
"Pragma",
"(",
"\"ADD-KRAUS\"",
",",
"[",
"name",
"]",
"+",
"list",
"(",
"qubit_indices",
")",
",",
"\"({})\"",
".",
"format",
"(",
"\" \"",... | Generate the pragmas to define a Kraus map for a specific gate on some qubits.
:param str name: The name of the gate.
:param list|tuple qubit_indices: The qubits
:param list|tuple kraus_ops: The Kraus operators as matrices.
:return: A QUIL string with PRAGMA ADD-KRAUS ... statements.
:rtype: str | [
"Generate",
"the",
"pragmas",
"to",
"define",
"a",
"Kraus",
"map",
"for",
"a",
"specific",
"gate",
"on",
"some",
"qubits",
"."
] | python | train |
cherrypy/cheroot | cheroot/server.py | https://github.com/cherrypy/cheroot/blob/2af3b1798d66da697957480d3a8b4831a405770b/cheroot/server.py#L1682-L1700 | def bind_addr(self, value):
"""Set the interface on which to listen for connections."""
if isinstance(value, tuple) and value[0] in ('', None):
# Despite the socket module docs, using '' does not
# allow AI_PASSIVE to work. Passing None instead
# returns '0.0.0.0' lik... | [
"def",
"bind_addr",
"(",
"self",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"tuple",
")",
"and",
"value",
"[",
"0",
"]",
"in",
"(",
"''",
",",
"None",
")",
":",
"# Despite the socket module docs, using '' does not",
"# allow AI_PASSIVE to w... | Set the interface on which to listen for connections. | [
"Set",
"the",
"interface",
"on",
"which",
"to",
"listen",
"for",
"connections",
"."
] | python | train |
django-userena-ce/django-userena-ce | userena/views.py | https://github.com/django-userena-ce/django-userena-ce/blob/2d8b745eed25128134e961ca96c270802e730256/userena/views.py#L757-L818 | def profile_list(request, page=1, template_name='userena/profile_list.html',
paginate_by=50, extra_context=None, **kwargs): # pragma: no cover
"""
Returns a list of all profiles that are public.
It's possible to disable this by changing ``USERENA_DISABLE_PROFILE_LIST``
to ``True`` in y... | [
"def",
"profile_list",
"(",
"request",
",",
"page",
"=",
"1",
",",
"template_name",
"=",
"'userena/profile_list.html'",
",",
"paginate_by",
"=",
"50",
",",
"extra_context",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# pragma: no cover",
"warnings",
".",
... | Returns a list of all profiles that are public.
It's possible to disable this by changing ``USERENA_DISABLE_PROFILE_LIST``
to ``True`` in your settings.
:param page:
Integer of the active page used for pagination. Defaults to the first
page.
:param template_name:
String defini... | [
"Returns",
"a",
"list",
"of",
"all",
"profiles",
"that",
"are",
"public",
"."
] | python | train |
materialsproject/pymatgen | pymatgen/analysis/local_env.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/analysis/local_env.py#L1659-L1693 | def get_neighbors_of_site_with_index(struct, n, approach="min_dist", delta=0.1, \
cutoff=10.0):
"""
Returns the neighbors of a given site using a specific neighbor-finding
method.
Args:
struct (Structure): input structure.
n (int): index of site in S... | [
"def",
"get_neighbors_of_site_with_index",
"(",
"struct",
",",
"n",
",",
"approach",
"=",
"\"min_dist\"",
",",
"delta",
"=",
"0.1",
",",
"cutoff",
"=",
"10.0",
")",
":",
"if",
"approach",
"==",
"\"min_dist\"",
":",
"return",
"MinimumDistanceNN",
"(",
"tol",
... | Returns the neighbors of a given site using a specific neighbor-finding
method.
Args:
struct (Structure): input structure.
n (int): index of site in Structure object for which motif type
is to be determined.
approach (str): type of neighbor-finding approach, where
... | [
"Returns",
"the",
"neighbors",
"of",
"a",
"given",
"site",
"using",
"a",
"specific",
"neighbor",
"-",
"finding",
"method",
"."
] | python | train |
wavycloud/pyboto3 | pyboto3/dynamodb.py | https://github.com/wavycloud/pyboto3/blob/924957ccf994303713a4eed90b775ff2ab95b2e5/pyboto3/dynamodb.py#L2186-L2655 | def put_item(TableName=None, Item=None, Expected=None, ReturnValues=None, ReturnConsumedCapacity=None, ReturnItemCollectionMetrics=None, ConditionalOperator=None, ConditionExpression=None, ExpressionAttributeNames=None, ExpressionAttributeValues=None):
"""
Creates a new item, or replaces an old item with a new ... | [
"def",
"put_item",
"(",
"TableName",
"=",
"None",
",",
"Item",
"=",
"None",
",",
"Expected",
"=",
"None",
",",
"ReturnValues",
"=",
"None",
",",
"ReturnConsumedCapacity",
"=",
"None",
",",
"ReturnItemCollectionMetrics",
"=",
"None",
",",
"ConditionalOperator",
... | Creates a new item, or replaces an old item with a new item. If an item that has the same primary key as the new item already exists in the specified table, the new item completely replaces the existing item. You can perform a conditional put operation (add a new item if one with the specified primary key doesn't exist... | [
"Creates",
"a",
"new",
"item",
"or",
"replaces",
"an",
"old",
"item",
"with",
"a",
"new",
"item",
".",
"If",
"an",
"item",
"that",
"has",
"the",
"same",
"primary",
"key",
"as",
"the",
"new",
"item",
"already",
"exists",
"in",
"the",
"specified",
"table... | python | train |
numenta/nupic | src/nupic/swarming/hypersearch/hs_state.py | https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/hypersearch/hs_state.py#L106-L229 | def readStateFromDB(self):
"""Set our state to that obtained from the engWorkerState field of the
job record.
Parameters:
---------------------------------------------------------------------
stateJSON: JSON encoded state from job record
"""
self._priorStateJSON = self._hsObj._cjDAO.jo... | [
"def",
"readStateFromDB",
"(",
"self",
")",
":",
"self",
".",
"_priorStateJSON",
"=",
"self",
".",
"_hsObj",
".",
"_cjDAO",
".",
"jobGetFields",
"(",
"self",
".",
"_hsObj",
".",
"_jobID",
",",
"[",
"'engWorkerState'",
"]",
")",
"[",
"0",
"]",
"# Init if ... | Set our state to that obtained from the engWorkerState field of the
job record.
Parameters:
---------------------------------------------------------------------
stateJSON: JSON encoded state from job record | [
"Set",
"our",
"state",
"to",
"that",
"obtained",
"from",
"the",
"engWorkerState",
"field",
"of",
"the",
"job",
"record",
"."
] | python | valid |
fstab50/metal | metal/script_utils.py | https://github.com/fstab50/metal/blob/0488bbdd516a508909267cc44191f632e21156ba/metal/script_utils.py#L36-L60 | def bool_assignment(arg, patterns=None):
"""
Summary:
Enforces correct bool argment assignment
Arg:
:arg (*): arg which must be interpreted as either bool True or False
Returns:
bool assignment | TYPE: bool
"""
arg = str(arg) # only eval type str
try:
if p... | [
"def",
"bool_assignment",
"(",
"arg",
",",
"patterns",
"=",
"None",
")",
":",
"arg",
"=",
"str",
"(",
"arg",
")",
"# only eval type str",
"try",
":",
"if",
"patterns",
"is",
"None",
":",
"patterns",
"=",
"(",
"(",
"re",
".",
"compile",
"(",
"r'^(true|f... | Summary:
Enforces correct bool argment assignment
Arg:
:arg (*): arg which must be interpreted as either bool True or False
Returns:
bool assignment | TYPE: bool | [
"Summary",
":",
"Enforces",
"correct",
"bool",
"argment",
"assignment",
"Arg",
":",
":",
"arg",
"(",
"*",
")",
":",
"arg",
"which",
"must",
"be",
"interpreted",
"as",
"either",
"bool",
"True",
"or",
"False",
"Returns",
":",
"bool",
"assignment",
"|",
"TY... | python | train |
wonambi-python/wonambi | wonambi/attr/annotations.py | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/attr/annotations.py#L1193-L1210 | def time_in_stage(self, name, attr='stage'):
"""Return time (in seconds) in the selected stage.
Parameters
----------
name : str
one of the sleep stages, or qualifiers
attr : str, optional
either 'stage' or 'quality'
Returns
-------
... | [
"def",
"time_in_stage",
"(",
"self",
",",
"name",
",",
"attr",
"=",
"'stage'",
")",
":",
"return",
"sum",
"(",
"x",
"[",
"'end'",
"]",
"-",
"x",
"[",
"'start'",
"]",
"for",
"x",
"in",
"self",
".",
"epochs",
"if",
"x",
"[",
"attr",
"]",
"==",
"n... | Return time (in seconds) in the selected stage.
Parameters
----------
name : str
one of the sleep stages, or qualifiers
attr : str, optional
either 'stage' or 'quality'
Returns
-------
int
time spent in one stage/qualifier, in... | [
"Return",
"time",
"(",
"in",
"seconds",
")",
"in",
"the",
"selected",
"stage",
"."
] | python | train |
tijme/not-your-average-web-crawler | nyawc/Queue.py | https://github.com/tijme/not-your-average-web-crawler/blob/d77c14e1616c541bb3980f649a7e6f8ed02761fb/nyawc/Queue.py#L64-L77 | def add_request(self, request):
"""Add a request to the queue.
Args:
request (:class:`nyawc.http.Request`): The request to add.
Returns:
:class:`nyawc.QueueItem`: The created queue item.
"""
queue_item = QueueItem(request, Response(request.url))
... | [
"def",
"add_request",
"(",
"self",
",",
"request",
")",
":",
"queue_item",
"=",
"QueueItem",
"(",
"request",
",",
"Response",
"(",
"request",
".",
"url",
")",
")",
"self",
".",
"add",
"(",
"queue_item",
")",
"return",
"queue_item"
] | Add a request to the queue.
Args:
request (:class:`nyawc.http.Request`): The request to add.
Returns:
:class:`nyawc.QueueItem`: The created queue item. | [
"Add",
"a",
"request",
"to",
"the",
"queue",
"."
] | python | train |
tgbugs/pyontutils | pyontutils/utils.py | https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/pyontutils/utils.py#L45-L67 | def sysidpath(ignore_options=False):
""" get a unique identifier for the machine running this function """
# in the event we have to make our own
# this should not be passed in a as a parameter
# since we need these definitions to be more or less static
failover = Path('/tmp/machine-id')
if not... | [
"def",
"sysidpath",
"(",
"ignore_options",
"=",
"False",
")",
":",
"# in the event we have to make our own",
"# this should not be passed in a as a parameter",
"# since we need these definitions to be more or less static",
"failover",
"=",
"Path",
"(",
"'/tmp/machine-id'",
")",
"if... | get a unique identifier for the machine running this function | [
"get",
"a",
"unique",
"identifier",
"for",
"the",
"machine",
"running",
"this",
"function"
] | python | train |
sendgrid/sendgrid-python | examples/helpers/mail_example.py | https://github.com/sendgrid/sendgrid-python/blob/266c2abde7a35dfcce263e06bedc6a0bbdebeac9/examples/helpers/mail_example.py#L105-L309 | def build_kitchen_sink():
"""All settings set"""
from sendgrid.helpers.mail import (
Mail, From, To, Cc, Bcc, Subject, PlainTextContent,
HtmlContent, SendGridException, Substitution,
Header, CustomArg, SendAt, Content, MimeType, Attachment,
FileName, FileContent, FileType, Disp... | [
"def",
"build_kitchen_sink",
"(",
")",
":",
"from",
"sendgrid",
".",
"helpers",
".",
"mail",
"import",
"(",
"Mail",
",",
"From",
",",
"To",
",",
"Cc",
",",
"Bcc",
",",
"Subject",
",",
"PlainTextContent",
",",
"HtmlContent",
",",
"SendGridException",
",",
... | All settings set | [
"All",
"settings",
"set"
] | python | train |
okpy/ok-client | client/sources/common/interpreter.py | https://github.com/okpy/ok-client/blob/517f57dd76284af40ba9766e42d9222b644afd9c/client/sources/common/interpreter.py#L322-L329 | def output_lines(self):
"""Return a sequence of lines, suitable for printing or comparing
answers.
"""
if self.exception:
return [self.EXCEPTION_HEADERS[0], ' ...'] + self.exception_detail
else:
return self.output | [
"def",
"output_lines",
"(",
"self",
")",
":",
"if",
"self",
".",
"exception",
":",
"return",
"[",
"self",
".",
"EXCEPTION_HEADERS",
"[",
"0",
"]",
",",
"' ...'",
"]",
"+",
"self",
".",
"exception_detail",
"else",
":",
"return",
"self",
".",
"output"
] | Return a sequence of lines, suitable for printing or comparing
answers. | [
"Return",
"a",
"sequence",
"of",
"lines",
"suitable",
"for",
"printing",
"or",
"comparing",
"answers",
"."
] | python | train |
gitpython-developers/GitPython | git/repo/base.py | https://github.com/gitpython-developers/GitPython/blob/1f66e25c25cde2423917ee18c4704fff83b837d1/git/repo/base.py#L1000-L1012 | def clone_from(cls, url, to_path, progress=None, env=None, **kwargs):
"""Create a clone from the given URL
:param url: valid git url, see http://www.kernel.org/pub/software/scm/git/docs/git-clone.html#URLS
:param to_path: Path to which the repository should be cloned to
:param progress:... | [
"def",
"clone_from",
"(",
"cls",
",",
"url",
",",
"to_path",
",",
"progress",
"=",
"None",
",",
"env",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"git",
"=",
"Git",
"(",
"os",
".",
"getcwd",
"(",
")",
")",
"if",
"env",
"is",
"not",
"None",... | Create a clone from the given URL
:param url: valid git url, see http://www.kernel.org/pub/software/scm/git/docs/git-clone.html#URLS
:param to_path: Path to which the repository should be cloned to
:param progress: See 'git.remote.Remote.push'.
:param env: Optional dictionary containing... | [
"Create",
"a",
"clone",
"from",
"the",
"given",
"URL"
] | python | train |
Parquery/icontract | icontract/_recompute.py | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_recompute.py#L55-L60 | def visit_Str(self, node: ast.Str) -> str:
"""Recompute the value as the string at the node."""
result = node.s
self.recomputed_values[node] = result
return result | [
"def",
"visit_Str",
"(",
"self",
",",
"node",
":",
"ast",
".",
"Str",
")",
"->",
"str",
":",
"result",
"=",
"node",
".",
"s",
"self",
".",
"recomputed_values",
"[",
"node",
"]",
"=",
"result",
"return",
"result"
] | Recompute the value as the string at the node. | [
"Recompute",
"the",
"value",
"as",
"the",
"string",
"at",
"the",
"node",
"."
] | python | train |
django-parler/django-parler | parler/views.py | https://github.com/django-parler/django-parler/blob/11ae4af5e8faddb74c69c848870122df4006a54e/parler/views.py#L140-L184 | def get_object(self, queryset=None):
"""
Fetch the object using a translated slug.
"""
if queryset is None:
queryset = self.get_queryset()
slug = self.kwargs[self.slug_url_kwarg]
choices = self.get_language_choices()
obj = None
using_fallback... | [
"def",
"get_object",
"(",
"self",
",",
"queryset",
"=",
"None",
")",
":",
"if",
"queryset",
"is",
"None",
":",
"queryset",
"=",
"self",
".",
"get_queryset",
"(",
")",
"slug",
"=",
"self",
".",
"kwargs",
"[",
"self",
".",
"slug_url_kwarg",
"]",
"choices... | Fetch the object using a translated slug. | [
"Fetch",
"the",
"object",
"using",
"a",
"translated",
"slug",
"."
] | python | train |
mitsei/dlkit | dlkit/json_/logging_/sessions.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/logging_/sessions.py#L2252-L2266 | def get_log_hierarchy(self):
"""Gets the hierarchy associated with this session.
return: (osid.hierarchy.Hierarchy) - the hierarchy associated
with this session
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
... | [
"def",
"get_log_hierarchy",
"(",
"self",
")",
":",
"# Implemented from template for",
"# osid.resource.BinHierarchySession.get_bin_hierarchy",
"if",
"self",
".",
"_catalog_session",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_catalog_session",
".",
"get_catalog_hiera... | Gets the hierarchy associated with this session.
return: (osid.hierarchy.Hierarchy) - the hierarchy associated
with this session
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method mu... | [
"Gets",
"the",
"hierarchy",
"associated",
"with",
"this",
"session",
"."
] | python | train |
jvamvas/rhymediscovery | rhymediscovery/find_schemes.py | https://github.com/jvamvas/rhymediscovery/blob/b76509c98554b12efa06fe9ab557cca5fa5e4a79/rhymediscovery/find_schemes.py#L228-L254 | def iterate(t_table, wordlist, stanzas, schemes, rprobs, maxsteps):
"""
Iterate EM and return final probabilities
"""
data_probs = numpy.zeros(len(stanzas))
old_data_probs = None
probs = None
num_words = len(wordlist)
ctr = 0
for ctr in range(maxsteps):
logging.info("Iterati... | [
"def",
"iterate",
"(",
"t_table",
",",
"wordlist",
",",
"stanzas",
",",
"schemes",
",",
"rprobs",
",",
"maxsteps",
")",
":",
"data_probs",
"=",
"numpy",
".",
"zeros",
"(",
"len",
"(",
"stanzas",
")",
")",
"old_data_probs",
"=",
"None",
"probs",
"=",
"N... | Iterate EM and return final probabilities | [
"Iterate",
"EM",
"and",
"return",
"final",
"probabilities"
] | python | train |
pazz/alot | alot/settings/manager.py | https://github.com/pazz/alot/blob/d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded/alot/settings/manager.py#L314-L376 | def get_tagstring_representation(self, tag, onebelow_normal=None,
onebelow_focus=None):
"""
looks up user's preferred way to represent a given tagstring.
:param tag: tagstring
:type tag: str
:param onebelow_normal: attribute that shines throu... | [
"def",
"get_tagstring_representation",
"(",
"self",
",",
"tag",
",",
"onebelow_normal",
"=",
"None",
",",
"onebelow_focus",
"=",
"None",
")",
":",
"colourmode",
"=",
"int",
"(",
"self",
".",
"_config",
".",
"get",
"(",
"'colourmode'",
")",
")",
"theme",
"=... | looks up user's preferred way to represent a given tagstring.
:param tag: tagstring
:type tag: str
:param onebelow_normal: attribute that shines through if unfocussed
:type onebelow_normal: urwid.AttrSpec
:param onebelow_focus: attribute that shines through if focussed
:... | [
"looks",
"up",
"user",
"s",
"preferred",
"way",
"to",
"represent",
"a",
"given",
"tagstring",
"."
] | python | train |
tensorflow/datasets | tensorflow_datasets/core/utils/tf_utils.py | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/utils/tf_utils.py#L94-L111 | def _build_graph_run(self, run_args):
"""Create a new graph for the given args."""
# Could try to use tfe.py_func(fct) but this would require knowing
# information about the signature of the function.
# Create a new graph:
with tf.Graph().as_default() as g:
# Create placeholder
input_ =... | [
"def",
"_build_graph_run",
"(",
"self",
",",
"run_args",
")",
":",
"# Could try to use tfe.py_func(fct) but this would require knowing",
"# information about the signature of the function.",
"# Create a new graph:",
"with",
"tf",
".",
"Graph",
"(",
")",
".",
"as_default",
"(",
... | Create a new graph for the given args. | [
"Create",
"a",
"new",
"graph",
"for",
"the",
"given",
"args",
"."
] | python | train |
saltstack/salt | salt/modules/dnsutil.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dnsutil.py#L363-L401 | def serial(zone='', update=False):
'''
Return, store and update a dns serial for your zone files.
zone: a keyword for a specific zone
update: store an updated version of the serial in a grain
If ``update`` is False, the function will retrieve an existing serial or
return the current date if n... | [
"def",
"serial",
"(",
"zone",
"=",
"''",
",",
"update",
"=",
"False",
")",
":",
"grains",
"=",
"{",
"}",
"key",
"=",
"'dnsserial'",
"if",
"zone",
":",
"key",
"+=",
"'_{0}'",
".",
"format",
"(",
"zone",
")",
"stored",
"=",
"__salt__",
"[",
"'grains.... | Return, store and update a dns serial for your zone files.
zone: a keyword for a specific zone
update: store an updated version of the serial in a grain
If ``update`` is False, the function will retrieve an existing serial or
return the current date if no serial is stored. Nothing will be stored
... | [
"Return",
"store",
"and",
"update",
"a",
"dns",
"serial",
"for",
"your",
"zone",
"files",
"."
] | python | train |
google/grr | grr/client/grr_response_client/client_actions/osquery.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/client/grr_response_client/client_actions/osquery.py#L198-L214 | def ParseRow(header,
row):
"""Parses a single row of osquery output.
Args:
header: A parsed header describing the row format.
row: A row in a "parsed JSON" representation.
Returns:
A parsed `rdf_osquery.OsqueryRow` instance.
"""
precondition.AssertDictType(row, Text, Text)
result... | [
"def",
"ParseRow",
"(",
"header",
",",
"row",
")",
":",
"precondition",
".",
"AssertDictType",
"(",
"row",
",",
"Text",
",",
"Text",
")",
"result",
"=",
"rdf_osquery",
".",
"OsqueryRow",
"(",
")",
"for",
"column",
"in",
"header",
".",
"columns",
":",
"... | Parses a single row of osquery output.
Args:
header: A parsed header describing the row format.
row: A row in a "parsed JSON" representation.
Returns:
A parsed `rdf_osquery.OsqueryRow` instance. | [
"Parses",
"a",
"single",
"row",
"of",
"osquery",
"output",
"."
] | python | train |
YeoLab/anchor | anchor/infotheory.py | https://github.com/YeoLab/anchor/blob/1f9c9d6d30235b1e77b945e6ef01db5a0e55d53a/anchor/infotheory.py#L190-L215 | def binify_and_jsd(df1, df2, bins, pair=None):
"""Binify and calculate jensen-shannon divergence between two dataframes
Parameters
----------
df1, df2 : pandas.DataFrames
Dataframes to calculate JSD between columns of. Must have overlapping
column names
bins : array-like
Bin... | [
"def",
"binify_and_jsd",
"(",
"df1",
",",
"df2",
",",
"bins",
",",
"pair",
"=",
"None",
")",
":",
"binned1",
"=",
"binify",
"(",
"df1",
",",
"bins",
"=",
"bins",
")",
".",
"dropna",
"(",
"how",
"=",
"'all'",
",",
"axis",
"=",
"1",
")",
"binned2",... | Binify and calculate jensen-shannon divergence between two dataframes
Parameters
----------
df1, df2 : pandas.DataFrames
Dataframes to calculate JSD between columns of. Must have overlapping
column names
bins : array-like
Bins to use for transforming df{1,2} into probability dis... | [
"Binify",
"and",
"calculate",
"jensen",
"-",
"shannon",
"divergence",
"between",
"two",
"dataframes"
] | python | train |
TeamHG-Memex/eli5 | eli5/formatters/text_helpers.py | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/formatters/text_helpers.py#L58-L90 | def prepare_weighted_spans(targets, # type: List[TargetExplanation]
preserve_density=None, # type: Optional[bool]
):
# type: (...) -> List[Optional[List[PreparedWeightedSpans]]]
""" Return weighted spans prepared for rendering.
Calculate a separate wei... | [
"def",
"prepare_weighted_spans",
"(",
"targets",
",",
"# type: List[TargetExplanation]",
"preserve_density",
"=",
"None",
",",
"# type: Optional[bool]",
")",
":",
"# type: (...) -> List[Optional[List[PreparedWeightedSpans]]]",
"targets_char_weights",
"=",
"[",
"[",
"get_char_weig... | Return weighted spans prepared for rendering.
Calculate a separate weight range for each different weighted
span (for each different index): each target has the same number
of weighted spans. | [
"Return",
"weighted",
"spans",
"prepared",
"for",
"rendering",
".",
"Calculate",
"a",
"separate",
"weight",
"range",
"for",
"each",
"different",
"weighted",
"span",
"(",
"for",
"each",
"different",
"index",
")",
":",
"each",
"target",
"has",
"the",
"same",
"... | python | train |
HttpRunner/HttpRunner | httprunner/report.py | https://github.com/HttpRunner/HttpRunner/blob/f259551bf9c8ba905eae5c1afcf2efea20ae0871/httprunner/report.py#L248-L260 | def __get_total_response_time(meta_datas_expanded):
""" caculate total response time of all meta_datas
"""
try:
response_time = 0
for meta_data in meta_datas_expanded:
response_time += meta_data["stat"]["response_time_ms"]
return "{:.2f}".format(response_time)
excep... | [
"def",
"__get_total_response_time",
"(",
"meta_datas_expanded",
")",
":",
"try",
":",
"response_time",
"=",
"0",
"for",
"meta_data",
"in",
"meta_datas_expanded",
":",
"response_time",
"+=",
"meta_data",
"[",
"\"stat\"",
"]",
"[",
"\"response_time_ms\"",
"]",
"return... | caculate total response time of all meta_datas | [
"caculate",
"total",
"response",
"time",
"of",
"all",
"meta_datas"
] | python | train |
brycedrennan/eulerian-magnification | eulerian_magnification/io.py | https://github.com/brycedrennan/eulerian-magnification/blob/9ae0651fe3334176300d183f8240ad36d77759a9/eulerian_magnification/io.py#L74-L83 | def save_video(video, fps, save_filename='media/output.avi'):
"""Save a video to disk"""
# fourcc = cv2.CAP_PROP_FOURCC('M', 'J', 'P', 'G')
print(save_filename)
video = float_to_uint8(video)
fourcc = cv2.VideoWriter_fourcc(*'MJPG')
writer = cv2.VideoWriter(save_filename, fourcc, fps, (video.shap... | [
"def",
"save_video",
"(",
"video",
",",
"fps",
",",
"save_filename",
"=",
"'media/output.avi'",
")",
":",
"# fourcc = cv2.CAP_PROP_FOURCC('M', 'J', 'P', 'G')",
"print",
"(",
"save_filename",
")",
"video",
"=",
"float_to_uint8",
"(",
"video",
")",
"fourcc",
"=",
"cv2... | Save a video to disk | [
"Save",
"a",
"video",
"to",
"disk"
] | python | train |
jobovy/galpy | galpy/potential/KuzminDiskPotential.py | https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/potential/KuzminDiskPotential.py#L62-L78 | def _evaluate(self,R,z,phi=0.,t=0.):
"""
NAME:
_evaluate
PURPOSE:
evaluate the potential at (R,z)
INPUT:
R - Cylindrical Galactocentric radius
z - vertical height
phi - azimuth
t - time
OUTPUT:
potential... | [
"def",
"_evaluate",
"(",
"self",
",",
"R",
",",
"z",
",",
"phi",
"=",
"0.",
",",
"t",
"=",
"0.",
")",
":",
"return",
"-",
"self",
".",
"_denom",
"(",
"R",
",",
"z",
")",
"**",
"-",
"0.5"
] | NAME:
_evaluate
PURPOSE:
evaluate the potential at (R,z)
INPUT:
R - Cylindrical Galactocentric radius
z - vertical height
phi - azimuth
t - time
OUTPUT:
potential at (R,z)
HISTORY:
2016-05-09 - Writte... | [
"NAME",
":",
"_evaluate",
"PURPOSE",
":",
"evaluate",
"the",
"potential",
"at",
"(",
"R",
"z",
")",
"INPUT",
":",
"R",
"-",
"Cylindrical",
"Galactocentric",
"radius",
"z",
"-",
"vertical",
"height",
"phi",
"-",
"azimuth",
"t",
"-",
"time",
"OUTPUT",
":",... | python | train |
UpCloudLtd/upcloud-python-api | upcloud_api/server.py | https://github.com/UpCloudLtd/upcloud-python-api/blob/954b0ad7c4b932b2be31a95d88975f6b0eeac8ed/upcloud_api/server.py#L137-L155 | def shutdown(self, hard=False, timeout=30):
"""
Shutdown/stop the server. By default, issue a soft shutdown with a timeout of 30s.
After the a timeout a hard shutdown is performed if the server has not stopped.
Note: API responds immediately (unlike in start), with state: started.
... | [
"def",
"shutdown",
"(",
"self",
",",
"hard",
"=",
"False",
",",
"timeout",
"=",
"30",
")",
":",
"body",
"=",
"dict",
"(",
")",
"body",
"[",
"'stop_server'",
"]",
"=",
"{",
"'stop_type'",
":",
"'hard'",
"if",
"hard",
"else",
"'soft'",
",",
"'timeout'"... | Shutdown/stop the server. By default, issue a soft shutdown with a timeout of 30s.
After the a timeout a hard shutdown is performed if the server has not stopped.
Note: API responds immediately (unlike in start), with state: started.
This client will, however, set state as 'maintenance' to sig... | [
"Shutdown",
"/",
"stop",
"the",
"server",
".",
"By",
"default",
"issue",
"a",
"soft",
"shutdown",
"with",
"a",
"timeout",
"of",
"30s",
"."
] | python | train |
h2oai/h2o-3 | h2o-bindings/bin/gen_java.py | https://github.com/h2oai/h2o-3/blob/dd62aaa1e7f680a8b16ee14bc66b0fb5195c2ad8/h2o-bindings/bin/gen_java.py#L42-L69 | def translate_name(name):
"""
Convert names with underscores into camelcase.
For example:
"num_rows" => "numRows"
"very_long_json_name" => "veryLongJsonName"
"build_GBM_model" => "buildGbmModel"
"KEY" => "key"
"middle___underscores" => "middleUnderscores"
"_e... | [
"def",
"translate_name",
"(",
"name",
")",
":",
"parts",
"=",
"name",
".",
"split",
"(",
"\"_\"",
")",
"i",
"=",
"0",
"while",
"parts",
"[",
"i",
"]",
"==",
"\"\"",
":",
"parts",
"[",
"i",
"]",
"=",
"\"_\"",
"i",
"+=",
"1",
"parts",
"[",
"i",
... | Convert names with underscores into camelcase.
For example:
"num_rows" => "numRows"
"very_long_json_name" => "veryLongJsonName"
"build_GBM_model" => "buildGbmModel"
"KEY" => "key"
"middle___underscores" => "middleUnderscores"
"_exclude_fields" => "_excludeFields" (re... | [
"Convert",
"names",
"with",
"underscores",
"into",
"camelcase",
"."
] | python | test |
estnltk/estnltk | estnltk/taggers/adjective_phrase_tagger/adj_phrase_tagger.py | https://github.com/estnltk/estnltk/blob/28ae334a68a0673072febc318635f04da0dcc54a/estnltk/taggers/adjective_phrase_tagger/adj_phrase_tagger.py#L23-L58 | def __extract_lemmas(self, doc, m, phrase):
"""
:param sent: sentence from which the match was found
:param m: the found match
:phrase: name of the phrase
:return: tuple of the lemmas in the match
"""
ph_start = m['start']
ph_end = m['end']
start_... | [
"def",
"__extract_lemmas",
"(",
"self",
",",
"doc",
",",
"m",
",",
"phrase",
")",
":",
"ph_start",
"=",
"m",
"[",
"'start'",
"]",
"ph_end",
"=",
"m",
"[",
"'end'",
"]",
"start_index",
"=",
"None",
"for",
"ind",
",",
"word",
"in",
"enumerate",
"(",
... | :param sent: sentence from which the match was found
:param m: the found match
:phrase: name of the phrase
:return: tuple of the lemmas in the match | [
":",
"param",
"sent",
":",
"sentence",
"from",
"which",
"the",
"match",
"was",
"found",
":",
"param",
"m",
":",
"the",
"found",
"match",
":",
"phrase",
":",
"name",
"of",
"the",
"phrase",
":",
"return",
":",
"tuple",
"of",
"the",
"lemmas",
"in",
"the... | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.