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 |
|---|---|---|---|---|---|---|---|---|
vallis/libstempo | libstempo/plot.py | https://github.com/vallis/libstempo/blob/0b19300a9b24d64c9ddc25cd6ddbfd12b6231990/libstempo/plot.py#L7-L38 | def plotres(psr,deleted=False,group=None,**kwargs):
"""Plot residuals, compute unweighted rms residual."""
res, t, errs = psr.residuals(), psr.toas(), psr.toaerrs
if (not deleted) and N.any(psr.deleted != 0):
res, t, errs = res[psr.deleted == 0], t[psr.deleted == 0], errs[psr.deleted == 0]
... | [
"def",
"plotres",
"(",
"psr",
",",
"deleted",
"=",
"False",
",",
"group",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"res",
",",
"t",
",",
"errs",
"=",
"psr",
".",
"residuals",
"(",
")",
",",
"psr",
".",
"toas",
"(",
")",
",",
"psr",
"."... | Plot residuals, compute unweighted rms residual. | [
"Plot",
"residuals",
"compute",
"unweighted",
"rms",
"residual",
"."
] | python | train |
openai/baselines | baselines/common/misc_util.py | https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/common/misc_util.py#L123-L134 | def update(self, new_val):
"""Update the estimate.
Parameters
----------
new_val: float
new observated value of estimated quantity.
"""
if self._value is None:
self._value = new_val
else:
self._value = self._gamma * self._value... | [
"def",
"update",
"(",
"self",
",",
"new_val",
")",
":",
"if",
"self",
".",
"_value",
"is",
"None",
":",
"self",
".",
"_value",
"=",
"new_val",
"else",
":",
"self",
".",
"_value",
"=",
"self",
".",
"_gamma",
"*",
"self",
".",
"_value",
"+",
"(",
"... | Update the estimate.
Parameters
----------
new_val: float
new observated value of estimated quantity. | [
"Update",
"the",
"estimate",
"."
] | python | valid |
romanz/trezor-agent | libagent/gpg/keyring.py | https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/keyring.py#L84-L94 | def unescape(s):
"""Unescape ASSUAN message (0xAB <-> '%AB')."""
s = bytearray(s)
i = 0
while i < len(s):
if s[i] == ord('%'):
hex_bytes = bytes(s[i+1:i+3])
value = int(hex_bytes.decode('ascii'), 16)
s[i:i+3] = [value]
i += 1
return bytes(s) | [
"def",
"unescape",
"(",
"s",
")",
":",
"s",
"=",
"bytearray",
"(",
"s",
")",
"i",
"=",
"0",
"while",
"i",
"<",
"len",
"(",
"s",
")",
":",
"if",
"s",
"[",
"i",
"]",
"==",
"ord",
"(",
"'%'",
")",
":",
"hex_bytes",
"=",
"bytes",
"(",
"s",
"[... | Unescape ASSUAN message (0xAB <-> '%AB'). | [
"Unescape",
"ASSUAN",
"message",
"(",
"0xAB",
"<",
"-",
">",
"%AB",
")",
"."
] | python | train |
alpha-xone/xbbg | xbbg/core/utils.py | https://github.com/alpha-xone/xbbg/blob/70226eb19a72a08144b5d8cea9db4913200f7bc5/xbbg/core/utils.py#L12-L47 | def flatten(iterable, maps=None, unique=False) -> list:
"""
Flatten any array of items to list
Args:
iterable: any array or value
maps: map items to values
unique: drop duplicates
Returns:
list: flattened list
References:
https://stackoverflow.com/a/4085770... | [
"def",
"flatten",
"(",
"iterable",
",",
"maps",
"=",
"None",
",",
"unique",
"=",
"False",
")",
"->",
"list",
":",
"if",
"iterable",
"is",
"None",
":",
"return",
"[",
"]",
"if",
"maps",
"is",
"None",
":",
"maps",
"=",
"dict",
"(",
")",
"if",
"isin... | Flatten any array of items to list
Args:
iterable: any array or value
maps: map items to values
unique: drop duplicates
Returns:
list: flattened list
References:
https://stackoverflow.com/a/40857703/1332656
Examples:
>>> flatten('abc')
['abc']
... | [
"Flatten",
"any",
"array",
"of",
"items",
"to",
"list"
] | python | valid |
ajenhl/tacl | tacl/jitc.py | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/jitc.py#L279-L307 | def _process_intersection(self, yes_work, maybe_work, work_dir,
ym_results_path, stats):
"""Returns statistics on the intersection between `yes_work` and
`maybe_work`.
:param yes_work: name of work for which stats are collected
:type yes_work: `str`
... | [
"def",
"_process_intersection",
"(",
"self",
",",
"yes_work",
",",
"maybe_work",
",",
"work_dir",
",",
"ym_results_path",
",",
"stats",
")",
":",
"catalogue",
"=",
"{",
"yes_work",
":",
"self",
".",
"_no_label",
",",
"maybe_work",
":",
"self",
".",
"_maybe_l... | Returns statistics on the intersection between `yes_work` and
`maybe_work`.
:param yes_work: name of work for which stats are collected
:type yes_work: `str`
:param maybe_work: name of work being compared with `yes_work`
:type maybe_work: `str`
:param work_dir: directory... | [
"Returns",
"statistics",
"on",
"the",
"intersection",
"between",
"yes_work",
"and",
"maybe_work",
"."
] | python | train |
apache/spark | python/pyspark/sql/functions.py | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/sql/functions.py#L1597-L1610 | def substring(str, pos, len):
"""
Substring starts at `pos` and is of length `len` when str is String type or
returns the slice of byte array that starts at `pos` in byte and is of length `len`
when str is Binary type.
.. note:: The position is not zero based, but 1 based index.
>>> df = spark... | [
"def",
"substring",
"(",
"str",
",",
"pos",
",",
"len",
")",
":",
"sc",
"=",
"SparkContext",
".",
"_active_spark_context",
"return",
"Column",
"(",
"sc",
".",
"_jvm",
".",
"functions",
".",
"substring",
"(",
"_to_java_column",
"(",
"str",
")",
",",
"pos"... | Substring starts at `pos` and is of length `len` when str is String type or
returns the slice of byte array that starts at `pos` in byte and is of length `len`
when str is Binary type.
.. note:: The position is not zero based, but 1 based index.
>>> df = spark.createDataFrame([('abcd',)], ['s',])
... | [
"Substring",
"starts",
"at",
"pos",
"and",
"is",
"of",
"length",
"len",
"when",
"str",
"is",
"String",
"type",
"or",
"returns",
"the",
"slice",
"of",
"byte",
"array",
"that",
"starts",
"at",
"pos",
"in",
"byte",
"and",
"is",
"of",
"length",
"len",
"whe... | python | train |
PaulHancock/Aegean | AegeanTools/regions.py | https://github.com/PaulHancock/Aegean/blob/185d2b4a51b48441a1df747efc9a5271c79399fd/AegeanTools/regions.py#L137-L151 | def add_pixels(self, pix, depth):
"""
Add one or more HEALPix pixels to this region.
Parameters
----------
pix : int or iterable
The pixels to be added
depth : int
The depth at which the pixels are added.
"""
if depth not in self.... | [
"def",
"add_pixels",
"(",
"self",
",",
"pix",
",",
"depth",
")",
":",
"if",
"depth",
"not",
"in",
"self",
".",
"pixeldict",
":",
"self",
".",
"pixeldict",
"[",
"depth",
"]",
"=",
"set",
"(",
")",
"self",
".",
"pixeldict",
"[",
"depth",
"]",
".",
... | Add one or more HEALPix pixels to this region.
Parameters
----------
pix : int or iterable
The pixels to be added
depth : int
The depth at which the pixels are added. | [
"Add",
"one",
"or",
"more",
"HEALPix",
"pixels",
"to",
"this",
"region",
"."
] | python | train |
GuiltyTargets/ppi-network-annotation | src/ppi_network_annotation/model/attribute_network.py | https://github.com/GuiltyTargets/ppi-network-annotation/blob/4d7b6713485f2d0a0957e6457edc1b1b5a237460/src/ppi_network_annotation/model/attribute_network.py#L74-L85 | def _add_disease_association_attributes(self, att_ind_start, att_mappings):
"""Add disease association information to the attribute mapping dictionary.
:param int att_ind_start: Start index for enumerating the attributes.
:param dict att_mappings: Dictionary of mappings between vertices and enu... | [
"def",
"_add_disease_association_attributes",
"(",
"self",
",",
"att_ind_start",
",",
"att_mappings",
")",
":",
"disease_mappings",
"=",
"self",
".",
"get_disease_mappings",
"(",
"att_ind_start",
")",
"for",
"vertex",
"in",
"self",
".",
"graph",
".",
"vs",
":",
... | Add disease association information to the attribute mapping dictionary.
:param int att_ind_start: Start index for enumerating the attributes.
:param dict att_mappings: Dictionary of mappings between vertices and enumerated attributes. | [
"Add",
"disease",
"association",
"information",
"to",
"the",
"attribute",
"mapping",
"dictionary",
"."
] | python | train |
yakupadakli/python-unsplash | unsplash/models.py | https://github.com/yakupadakli/python-unsplash/blob/6e43dce3225237e1b8111fd475fb98b1ea33972c/unsplash/models.py#L18-L25 | def parse_list(cls, data):
"""Parse a list of JSON objects into a result set of model instances."""
results = ResultSet()
data = data or []
for obj in data:
if obj:
results.append(cls.parse(obj))
return results | [
"def",
"parse_list",
"(",
"cls",
",",
"data",
")",
":",
"results",
"=",
"ResultSet",
"(",
")",
"data",
"=",
"data",
"or",
"[",
"]",
"for",
"obj",
"in",
"data",
":",
"if",
"obj",
":",
"results",
".",
"append",
"(",
"cls",
".",
"parse",
"(",
"obj",... | Parse a list of JSON objects into a result set of model instances. | [
"Parse",
"a",
"list",
"of",
"JSON",
"objects",
"into",
"a",
"result",
"set",
"of",
"model",
"instances",
"."
] | python | train |
rootpy/rootpy | rootpy/plotting/hist.py | https://github.com/rootpy/rootpy/blob/3926935e1f2100d8ba68070c2ab44055d4800f73/rootpy/plotting/hist.py#L1260-L1273 | def set_sum_w2(self, w, ix, iy=0, iz=0):
"""
Sets the true number of entries in the bin weighted by w^2
"""
if self.GetSumw2N() == 0:
raise RuntimeError(
"Attempting to access Sumw2 in histogram "
"where weights were not stored")
xl = s... | [
"def",
"set_sum_w2",
"(",
"self",
",",
"w",
",",
"ix",
",",
"iy",
"=",
"0",
",",
"iz",
"=",
"0",
")",
":",
"if",
"self",
".",
"GetSumw2N",
"(",
")",
"==",
"0",
":",
"raise",
"RuntimeError",
"(",
"\"Attempting to access Sumw2 in histogram \"",
"\"where we... | Sets the true number of entries in the bin weighted by w^2 | [
"Sets",
"the",
"true",
"number",
"of",
"entries",
"in",
"the",
"bin",
"weighted",
"by",
"w^2"
] | python | train |
clab/dynet | python/dynet_viz.py | https://github.com/clab/dynet/blob/21cc62606b74f81bb4b11a9989a6c2bd0caa09c5/python/dynet_viz.py#L775-L947 | def make_network_graph(compact, expression_names, lookup_names):
"""
Make a network graph, represented as of nodes and a set of edges.
The nodes are represented as tuples: (name: string, input_dim: Dim, label: string, output_dim: Dim, children: set[name], features: string)
# The edges are represented as dict ... | [
"def",
"make_network_graph",
"(",
"compact",
",",
"expression_names",
",",
"lookup_names",
")",
":",
"nodes",
"=",
"set",
"(",
")",
"# edges = defaultdict(set) # parent -> (child, extra)",
"var_name_dict",
"=",
"dict",
"(",
")",
"if",
"expression_names",
":",
"for",... | Make a network graph, represented as of nodes and a set of edges.
The nodes are represented as tuples: (name: string, input_dim: Dim, label: string, output_dim: Dim, children: set[name], features: string)
# The edges are represented as dict of children to sets of parents: (child: string) -> [(parent: string, feat... | [
"Make",
"a",
"network",
"graph",
"represented",
"as",
"of",
"nodes",
"and",
"a",
"set",
"of",
"edges",
".",
"The",
"nodes",
"are",
"represented",
"as",
"tuples",
":",
"(",
"name",
":",
"string",
"input_dim",
":",
"Dim",
"label",
":",
"string",
"output_di... | python | valid |
jazzband/django-axes | axes/attempts.py | https://github.com/jazzband/django-axes/blob/3e215a174030e43e7ab8c2a79c395eb0eeddc667/axes/attempts.py#L61-L73 | def clean_expired_user_attempts(attempt_time: datetime = None) -> int:
"""
Clean expired user attempts from the database.
"""
if settings.AXES_COOLOFF_TIME is None:
log.debug('AXES: Skipping clean for expired access attempts because no AXES_COOLOFF_TIME is configured')
return 0
thr... | [
"def",
"clean_expired_user_attempts",
"(",
"attempt_time",
":",
"datetime",
"=",
"None",
")",
"->",
"int",
":",
"if",
"settings",
".",
"AXES_COOLOFF_TIME",
"is",
"None",
":",
"log",
".",
"debug",
"(",
"'AXES: Skipping clean for expired access attempts because no AXES_CO... | Clean expired user attempts from the database. | [
"Clean",
"expired",
"user",
"attempts",
"from",
"the",
"database",
"."
] | python | train |
dpursehouse/pygerrit2 | pygerrit2/rest/__init__.py | https://github.com/dpursehouse/pygerrit2/blob/141031469603b33369d89c38c703390eb3786bd0/pygerrit2/rest/__init__.py#L46-L75 | def _decode_response(response):
"""Strip off Gerrit's magic prefix and decode a response.
:returns:
Decoded JSON content as a dict, or raw text if content could not be
decoded as JSON.
:raises:
requests.HTTPError if the response contains an HTTP error status code.
"""
cont... | [
"def",
"_decode_response",
"(",
"response",
")",
":",
"content_type",
"=",
"response",
".",
"headers",
".",
"get",
"(",
"'content-type'",
",",
"''",
")",
"logger",
".",
"debug",
"(",
"\"status[%s] content_type[%s] encoding[%s]\"",
"%",
"(",
"response",
".",
"sta... | Strip off Gerrit's magic prefix and decode a response.
:returns:
Decoded JSON content as a dict, or raw text if content could not be
decoded as JSON.
:raises:
requests.HTTPError if the response contains an HTTP error status code. | [
"Strip",
"off",
"Gerrit",
"s",
"magic",
"prefix",
"and",
"decode",
"a",
"response",
"."
] | python | train |
shoebot/shoebot | lib/beziereditor/__init__.py | https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/beziereditor/__init__.py#L318-L635 | def update(self):
""" Update runs each frame to check for mouse interaction.
Alters the path by allowing the user to add new points,
drag point handles and move their location.
Updates are automatically stored as SVG
in the given filename.
"""
... | [
"def",
"update",
"(",
"self",
")",
":",
"x",
",",
"y",
"=",
"mouse",
"(",
")",
"if",
"self",
".",
"show_grid",
":",
"x",
",",
"y",
"=",
"self",
".",
"grid",
".",
"snap",
"(",
"x",
",",
"y",
")",
"if",
"_ctx",
".",
"_ns",
"[",
"\"mousedown\"",... | Update runs each frame to check for mouse interaction.
Alters the path by allowing the user to add new points,
drag point handles and move their location.
Updates are automatically stored as SVG
in the given filename. | [
"Update",
"runs",
"each",
"frame",
"to",
"check",
"for",
"mouse",
"interaction",
".",
"Alters",
"the",
"path",
"by",
"allowing",
"the",
"user",
"to",
"add",
"new",
"points",
"drag",
"point",
"handles",
"and",
"move",
"their",
"location",
".",
"Updates",
"a... | python | valid |
log2timeline/plaso | plaso/engine/worker.py | https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/engine/worker.py#L338-L374 | def _ExtractMetadataFromFileEntry(self, mediator, file_entry, data_stream):
"""Extracts metadata from a file entry.
Args:
mediator (ParserMediator): mediates the interactions between
parsers and other components, such as storage and abort signals.
file_entry (dfvfs.FileEntry): file entry ... | [
"def",
"_ExtractMetadataFromFileEntry",
"(",
"self",
",",
"mediator",
",",
"file_entry",
",",
"data_stream",
")",
":",
"# Do not extract metadata from the root file entry when it is virtual.",
"if",
"file_entry",
".",
"IsRoot",
"(",
")",
"and",
"file_entry",
".",
"type_in... | Extracts metadata from a file entry.
Args:
mediator (ParserMediator): mediates the interactions between
parsers and other components, such as storage and abort signals.
file_entry (dfvfs.FileEntry): file entry to extract metadata from.
data_stream (dfvfs.DataStream): data stream or None... | [
"Extracts",
"metadata",
"from",
"a",
"file",
"entry",
"."
] | python | train |
olitheolix/qtmacs | qtmacs/base_macro.py | https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/base_macro.py#L418-L469 | def qtePrepareToRun(self):
"""
This method is called by Qtmacs to prepare the macro for
execution.
It is probably a bad idea to overload this method as it only
administrates the macro execution and calls the ``qteRun``
method (which *should* be overloaded by the macro pr... | [
"def",
"qtePrepareToRun",
"(",
"self",
")",
":",
"# Report the execution attempt.",
"msgObj",
"=",
"QtmacsMessage",
"(",
"(",
"self",
".",
"qteMacroName",
"(",
")",
",",
"self",
".",
"qteWidget",
")",
",",
"None",
")",
"msgObj",
".",
"setSignalName",
"(",
"'... | This method is called by Qtmacs to prepare the macro for
execution.
It is probably a bad idea to overload this method as it only
administrates the macro execution and calls the ``qteRun``
method (which *should* be overloaded by the macro programmer
in order for the macro to do s... | [
"This",
"method",
"is",
"called",
"by",
"Qtmacs",
"to",
"prepare",
"the",
"macro",
"for",
"execution",
"."
] | python | train |
Fantomas42/mots-vides | mots_vides/factory.py | https://github.com/Fantomas42/mots-vides/blob/eaeccf73bdb415d0c5559ccd74de360b37a2bbac/mots_vides/factory.py#L111-L118 | def write_collection(self, filename, collection):
"""
Writes a collection of stop words into a file.
"""
collection = sorted(list(collection))
with open(filename, 'wb+') as fd:
fd.truncate()
fd.write('\n'.join(collection).encode('utf-8')) | [
"def",
"write_collection",
"(",
"self",
",",
"filename",
",",
"collection",
")",
":",
"collection",
"=",
"sorted",
"(",
"list",
"(",
"collection",
")",
")",
"with",
"open",
"(",
"filename",
",",
"'wb+'",
")",
"as",
"fd",
":",
"fd",
".",
"truncate",
"("... | Writes a collection of stop words into a file. | [
"Writes",
"a",
"collection",
"of",
"stop",
"words",
"into",
"a",
"file",
"."
] | python | train |
ergoithz/browsepy | browsepy/manager.py | https://github.com/ergoithz/browsepy/blob/1612a930ef220fae507e1b152c531707e555bd92/browsepy/manager.py#L395-L409 | def get_mimetype(self, path):
'''
Get mimetype of given path calling all registered mime functions (and
default ones).
:param path: filesystem path of file
:type path: str
:returns: mimetype
:rtype: str
'''
for fnc in self._mimetype_functions:
... | [
"def",
"get_mimetype",
"(",
"self",
",",
"path",
")",
":",
"for",
"fnc",
"in",
"self",
".",
"_mimetype_functions",
":",
"mime",
"=",
"fnc",
"(",
"path",
")",
"if",
"mime",
":",
"return",
"mime",
"return",
"mimetype",
".",
"by_default",
"(",
"path",
")"... | Get mimetype of given path calling all registered mime functions (and
default ones).
:param path: filesystem path of file
:type path: str
:returns: mimetype
:rtype: str | [
"Get",
"mimetype",
"of",
"given",
"path",
"calling",
"all",
"registered",
"mime",
"functions",
"(",
"and",
"default",
"ones",
")",
"."
] | python | train |
bsolomon1124/pyfinance | pyfinance/returns.py | https://github.com/bsolomon1124/pyfinance/blob/c95925209a809b4e648e79cbeaf7711d8e5ff1a6/pyfinance/returns.py#L449-L468 | def drawdown_recov(self, return_int=False):
"""Length of drawdown recovery in days.
This is the duration from trough to recovery date.
Parameters
----------
return_int : bool, default False
If True, return the number of days as an int.
If False, return a... | [
"def",
"drawdown_recov",
"(",
"self",
",",
"return_int",
"=",
"False",
")",
":",
"td",
"=",
"self",
".",
"recov_date",
"(",
")",
"-",
"self",
".",
"drawdown_end",
"(",
")",
"if",
"return_int",
":",
"return",
"td",
".",
"days",
"return",
"td"
] | Length of drawdown recovery in days.
This is the duration from trough to recovery date.
Parameters
----------
return_int : bool, default False
If True, return the number of days as an int.
If False, return a Pandas Timedelta object.
Returns
----... | [
"Length",
"of",
"drawdown",
"recovery",
"in",
"days",
"."
] | python | train |
thesharp/htpasswd | htpasswd/basic.py | https://github.com/thesharp/htpasswd/blob/8bf5cee0bd5362af586729f4c9cea8131eedd74f/htpasswd/basic.py#L88-L97 | def _encrypt_password(self, password):
"""encrypt the password for given mode """
if self.encryption_mode.lower() == 'crypt':
return self._crypt_password(password)
elif self.encryption_mode.lower() == 'md5':
return self._md5_password(password)
elif self.encryption... | [
"def",
"_encrypt_password",
"(",
"self",
",",
"password",
")",
":",
"if",
"self",
".",
"encryption_mode",
".",
"lower",
"(",
")",
"==",
"'crypt'",
":",
"return",
"self",
".",
"_crypt_password",
"(",
"password",
")",
"elif",
"self",
".",
"encryption_mode",
... | encrypt the password for given mode | [
"encrypt",
"the",
"password",
"for",
"given",
"mode"
] | python | train |
ihmeuw/vivarium | src/vivarium/framework/configuration.py | https://github.com/ihmeuw/vivarium/blob/c5f5d50f775c8bf337d3aae1ff7c57c025a8e258/src/vivarium/framework/configuration.py#L25-L36 | def validate_model_specification_file(file_path: str) -> str:
"""Ensures the provided file is a yaml file"""
if not os.path.isfile(file_path):
raise ConfigurationError('If you provide a model specification file, it must be a file. '
f'You provided {file_path}')
exte... | [
"def",
"validate_model_specification_file",
"(",
"file_path",
":",
"str",
")",
"->",
"str",
":",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"file_path",
")",
":",
"raise",
"ConfigurationError",
"(",
"'If you provide a model specification file, it must be a fi... | Ensures the provided file is a yaml file | [
"Ensures",
"the",
"provided",
"file",
"is",
"a",
"yaml",
"file"
] | python | train |
foutaise/texttable | texttable.py | https://github.com/foutaise/texttable/blob/8eea49c20458ec40478e2f26b4b260ad47550838/texttable.py#L294-L306 | def set_cols_valign(self, array):
"""Set the desired columns vertical alignment
- the elements of the array should be either "t", "m" or "b":
* "t": column aligned on the top of the cell
* "m": column aligned on the middle of the cell
* "b": column aligned on the bo... | [
"def",
"set_cols_valign",
"(",
"self",
",",
"array",
")",
":",
"self",
".",
"_check_row_size",
"(",
"array",
")",
"self",
".",
"_valign",
"=",
"array",
"return",
"self"
] | Set the desired columns vertical alignment
- the elements of the array should be either "t", "m" or "b":
* "t": column aligned on the top of the cell
* "m": column aligned on the middle of the cell
* "b": column aligned on the bottom of the cell | [
"Set",
"the",
"desired",
"columns",
"vertical",
"alignment"
] | python | train |
ungarj/mapchete | mapchete/formats/default/raster_file.py | https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/formats/default/raster_file.py#L90-L119 | def bbox(self, out_crs=None):
"""
Return data bounding box.
Parameters
----------
out_crs : ``rasterio.crs.CRS``
rasterio CRS object (default: CRS of process pyramid)
Returns
-------
bounding box : geometry
Shapely geometry object... | [
"def",
"bbox",
"(",
"self",
",",
"out_crs",
"=",
"None",
")",
":",
"out_crs",
"=",
"self",
".",
"pyramid",
".",
"crs",
"if",
"out_crs",
"is",
"None",
"else",
"out_crs",
"with",
"rasterio",
".",
"open",
"(",
"self",
".",
"path",
")",
"as",
"inp",
":... | Return data bounding box.
Parameters
----------
out_crs : ``rasterio.crs.CRS``
rasterio CRS object (default: CRS of process pyramid)
Returns
-------
bounding box : geometry
Shapely geometry object | [
"Return",
"data",
"bounding",
"box",
"."
] | python | valid |
genialis/resolwe | resolwe/elastic/builder.py | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/elastic/builder.py#L505-L510 | def destroy(self):
"""Delete all indexes from Elasticsearch and index builder."""
self.unregister_signals()
for index in self.indexes:
index.destroy()
self.indexes = [] | [
"def",
"destroy",
"(",
"self",
")",
":",
"self",
".",
"unregister_signals",
"(",
")",
"for",
"index",
"in",
"self",
".",
"indexes",
":",
"index",
".",
"destroy",
"(",
")",
"self",
".",
"indexes",
"=",
"[",
"]"
] | Delete all indexes from Elasticsearch and index builder. | [
"Delete",
"all",
"indexes",
"from",
"Elasticsearch",
"and",
"index",
"builder",
"."
] | python | train |
assamite/creamas | creamas/rules/rule.py | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/rules/rule.py#L153-L167 | def add_subrule(self, subrule, weight):
"""Add subrule to the rule.
:param subrule:
Subrule to add to this rule, an instance of :class:`Rule` or
:class:`RuleLeaf`.
:param float weight: Weight of the subrule
"""
if not issubclass(subrule.__class__, (Rule,... | [
"def",
"add_subrule",
"(",
"self",
",",
"subrule",
",",
"weight",
")",
":",
"if",
"not",
"issubclass",
"(",
"subrule",
".",
"__class__",
",",
"(",
"Rule",
",",
"RuleLeaf",
")",
")",
":",
"raise",
"TypeError",
"(",
"\"Rule's class must be (subclass of) {} or {}... | Add subrule to the rule.
:param subrule:
Subrule to add to this rule, an instance of :class:`Rule` or
:class:`RuleLeaf`.
:param float weight: Weight of the subrule | [
"Add",
"subrule",
"to",
"the",
"rule",
"."
] | python | train |
ansible/molecule | molecule/provisioner/ansible.py | https://github.com/ansible/molecule/blob/766dc35b0b0ce498cd5e3a62b40f828742d0d08c/molecule/provisioner/ansible.py#L641-L656 | def converge(self, playbook=None, **kwargs):
"""
Executes ``ansible-playbook`` against the converge playbook unless
specified otherwise and returns a string.
:param playbook: An optional string containing an absolute path to a
playbook.
:param kwargs: An optional keywor... | [
"def",
"converge",
"(",
"self",
",",
"playbook",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"playbook",
"is",
"None",
":",
"pb",
"=",
"self",
".",
"_get_ansible_playbook",
"(",
"self",
".",
"playbooks",
".",
"converge",
",",
"*",
"*",
"kwa... | Executes ``ansible-playbook`` against the converge playbook unless
specified otherwise and returns a string.
:param playbook: An optional string containing an absolute path to a
playbook.
:param kwargs: An optional keyword arguments.
:return: str | [
"Executes",
"ansible",
"-",
"playbook",
"against",
"the",
"converge",
"playbook",
"unless",
"specified",
"otherwise",
"and",
"returns",
"a",
"string",
"."
] | python | train |
jilljenn/tryalgo | tryalgo/convex_hull.py | https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/convex_hull.py#L20-L38 | def andrew(S):
"""Convex hull by Andrew
:param S: list of points as coordinate pairs
:requires: S has at least 2 points
:returns: list of points of the convex hull
:complexity: `O(n log n)`
"""
S.sort()
top = []
bot = []
for p in S:
while len(top) >= 2 and not left_turn(... | [
"def",
"andrew",
"(",
"S",
")",
":",
"S",
".",
"sort",
"(",
")",
"top",
"=",
"[",
"]",
"bot",
"=",
"[",
"]",
"for",
"p",
"in",
"S",
":",
"while",
"len",
"(",
"top",
")",
">=",
"2",
"and",
"not",
"left_turn",
"(",
"p",
",",
"top",
"[",
"-"... | Convex hull by Andrew
:param S: list of points as coordinate pairs
:requires: S has at least 2 points
:returns: list of points of the convex hull
:complexity: `O(n log n)` | [
"Convex",
"hull",
"by",
"Andrew"
] | python | train |
AllTheWayDown/turgles | turgles/buffer.py | https://github.com/AllTheWayDown/turgles/blob/1bb17abe9b3aa0953d9a8e9b05a23369c5bf8852/turgles/buffer.py#L79-L86 | def resize(self, new_size):
"""Create a new larger array, and copy data over"""
assert new_size > self.size
new_data = self._allocate(new_size)
# copy
new_data[0:self.size * self.chunk_size] = self.data
self.size = new_size
self.data = new_data | [
"def",
"resize",
"(",
"self",
",",
"new_size",
")",
":",
"assert",
"new_size",
">",
"self",
".",
"size",
"new_data",
"=",
"self",
".",
"_allocate",
"(",
"new_size",
")",
"# copy",
"new_data",
"[",
"0",
":",
"self",
".",
"size",
"*",
"self",
".",
"chu... | Create a new larger array, and copy data over | [
"Create",
"a",
"new",
"larger",
"array",
"and",
"copy",
"data",
"over"
] | python | train |
OpenTreeOfLife/peyotl | tutorials/ot-oti-find-tree.py | https://github.com/OpenTreeOfLife/peyotl/blob/5e4e52a0fdbd17f490aa644ad79fda6ea2eda7c0/tutorials/ot-oti-find-tree.py#L12-L24 | def ot_find_tree(arg_dict, exact=True, verbose=False, oti_wrapper=None):
"""Uses a peyotl wrapper around an Open Tree web service to get a list of trees including values `value` for a given property to be searched on `porperty`.
The oti_wrapper can be None (in which case the default wrapper from peyotl.sugar w... | [
"def",
"ot_find_tree",
"(",
"arg_dict",
",",
"exact",
"=",
"True",
",",
"verbose",
"=",
"False",
",",
"oti_wrapper",
"=",
"None",
")",
":",
"if",
"oti_wrapper",
"is",
"None",
":",
"from",
"peyotl",
".",
"sugar",
"import",
"oti",
"oti_wrapper",
"=",
"oti"... | Uses a peyotl wrapper around an Open Tree web service to get a list of trees including values `value` for a given property to be searched on `porperty`.
The oti_wrapper can be None (in which case the default wrapper from peyotl.sugar will be used.
All other arguments correspond to the arguments of the web-serv... | [
"Uses",
"a",
"peyotl",
"wrapper",
"around",
"an",
"Open",
"Tree",
"web",
"service",
"to",
"get",
"a",
"list",
"of",
"trees",
"including",
"values",
"value",
"for",
"a",
"given",
"property",
"to",
"be",
"searched",
"on",
"porperty",
"."
] | python | train |
openstack/networking-cisco | networking_cisco/apps/saf/server/services/firewall/native/drivers/native.py | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/services/firewall/native/drivers/native.py#L445-L472 | def network_create_notif(self, tenant_id, tenant_name, cidr):
"""Tenant Network create Notification.
Restart is not supported currently for this. fixme(padkrish).
"""
router_id = self.get_router_id(tenant_id, tenant_name)
if not router_id:
LOG.error("Rout ID not pres... | [
"def",
"network_create_notif",
"(",
"self",
",",
"tenant_id",
",",
"tenant_name",
",",
"cidr",
")",
":",
"router_id",
"=",
"self",
".",
"get_router_id",
"(",
"tenant_id",
",",
"tenant_name",
")",
"if",
"not",
"router_id",
":",
"LOG",
".",
"error",
"(",
"\"... | Tenant Network create Notification.
Restart is not supported currently for this. fixme(padkrish). | [
"Tenant",
"Network",
"create",
"Notification",
"."
] | python | train |
mrstephenneal/mysql-toolkit | mysql/toolkit/commands/execute.py | https://github.com/mrstephenneal/mysql-toolkit/blob/6964f718f4b72eb30f2259adfcfaf3090526c53d/mysql/toolkit/commands/execute.py#L43-L75 | def commands(self):
"""
Fetch individual SQL commands from a SQL commands containing many commands.
:return: List of commands
"""
# Retrieve all commands via split function or splitting on ';'
print('\tRetrieving commands from', self.sql_script)
print('\tUsing co... | [
"def",
"commands",
"(",
"self",
")",
":",
"# Retrieve all commands via split function or splitting on ';'",
"print",
"(",
"'\\tRetrieving commands from'",
",",
"self",
".",
"sql_script",
")",
"print",
"(",
"'\\tUsing command splitter algorithm {0}'",
".",
"format",
"(",
"se... | Fetch individual SQL commands from a SQL commands containing many commands.
:return: List of commands | [
"Fetch",
"individual",
"SQL",
"commands",
"from",
"a",
"SQL",
"commands",
"containing",
"many",
"commands",
"."
] | python | train |
monarch-initiative/dipper | dipper/sources/ZFIN.py | https://github.com/monarch-initiative/dipper/blob/24cc80db355bbe15776edc5c7b41e0886959ba41/dipper/sources/ZFIN.py#L1390-L1437 | def _process_genes(self, limit=None):
"""
This table provides the ZFIN gene id, the SO type of the gene,
the gene symbol, and the NCBI Gene ID.
Triples created:
<gene id> a class
<gene id> rdfs:label gene_symbol
<gene id> equivalent class <ncbi_gene_id>
:... | [
"def",
"_process_genes",
"(",
"self",
",",
"limit",
"=",
"None",
")",
":",
"LOG",
".",
"info",
"(",
"\"Processing genes\"",
")",
"if",
"self",
".",
"test_mode",
":",
"graph",
"=",
"self",
".",
"testgraph",
"else",
":",
"graph",
"=",
"self",
".",
"graph... | This table provides the ZFIN gene id, the SO type of the gene,
the gene symbol, and the NCBI Gene ID.
Triples created:
<gene id> a class
<gene id> rdfs:label gene_symbol
<gene id> equivalent class <ncbi_gene_id>
:param limit:
:return: | [
"This",
"table",
"provides",
"the",
"ZFIN",
"gene",
"id",
"the",
"SO",
"type",
"of",
"the",
"gene",
"the",
"gene",
"symbol",
"and",
"the",
"NCBI",
"Gene",
"ID",
"."
] | python | train |
googledatalab/pydatalab | google/datalab/bigquery/commands/_bigquery.py | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/bigquery/commands/_bigquery.py#L683-L754 | def _table_cell(args, cell_body):
"""Implements the BigQuery table magic subcommand used to operate on tables
The supported syntax is:
%%bq tables <command> <args>
Commands:
{list, create, delete, describe, view}
Args:
args: the optional arguments following '%%bq tables command'.
cell_body: o... | [
"def",
"_table_cell",
"(",
"args",
",",
"cell_body",
")",
":",
"if",
"args",
"[",
"'command'",
"]",
"==",
"'list'",
":",
"filter_",
"=",
"args",
"[",
"'filter'",
"]",
"if",
"args",
"[",
"'filter'",
"]",
"else",
"'*'",
"if",
"args",
"[",
"'dataset'",
... | Implements the BigQuery table magic subcommand used to operate on tables
The supported syntax is:
%%bq tables <command> <args>
Commands:
{list, create, delete, describe, view}
Args:
args: the optional arguments following '%%bq tables command'.
cell_body: optional contents of the cell interprete... | [
"Implements",
"the",
"BigQuery",
"table",
"magic",
"subcommand",
"used",
"to",
"operate",
"on",
"tables"
] | python | train |
mabuchilab/QNET | src/qnet/algebra/core/indexed_operations.py | https://github.com/mabuchilab/QNET/blob/cc20d26dad78691d34c67173e5cd67dcac94208a/src/qnet/algebra/core/indexed_operations.py#L100-L124 | def doit(
self, classes=None, recursive=True, indices=None, max_terms=None,
**kwargs):
"""Write out the indexed sum explicitly
If `classes` is None or :class:`IndexedSum` is in `classes`,
(partially) write out the indexed sum in to an explicit sum of terms.
If `r... | [
"def",
"doit",
"(",
"self",
",",
"classes",
"=",
"None",
",",
"recursive",
"=",
"True",
",",
"indices",
"=",
"None",
",",
"max_terms",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"super",
"(",
")",
".",
"doit",
"(",
"classes",
",",
... | Write out the indexed sum explicitly
If `classes` is None or :class:`IndexedSum` is in `classes`,
(partially) write out the indexed sum in to an explicit sum of terms.
If `recursive` is True, write out each of the new sum's summands by
calling its :meth:`doit` method.
Args:
... | [
"Write",
"out",
"the",
"indexed",
"sum",
"explicitly"
] | python | train |
graphql-python/graphene | graphene/pyutils/version.py | https://github.com/graphql-python/graphene/blob/abff3d75a39bc8f2d1fdb48aafa1866cf47dfff6/graphene/pyutils/version.py#L40-L50 | def get_complete_version(version=None):
"""Returns a tuple of the graphene version. If version argument is non-empty,
then checks for correctness of the tuple provided.
"""
if version is None:
from graphene import VERSION as version
else:
assert len(version) == 5
assert versi... | [
"def",
"get_complete_version",
"(",
"version",
"=",
"None",
")",
":",
"if",
"version",
"is",
"None",
":",
"from",
"graphene",
"import",
"VERSION",
"as",
"version",
"else",
":",
"assert",
"len",
"(",
"version",
")",
"==",
"5",
"assert",
"version",
"[",
"3... | Returns a tuple of the graphene version. If version argument is non-empty,
then checks for correctness of the tuple provided. | [
"Returns",
"a",
"tuple",
"of",
"the",
"graphene",
"version",
".",
"If",
"version",
"argument",
"is",
"non",
"-",
"empty",
"then",
"checks",
"for",
"correctness",
"of",
"the",
"tuple",
"provided",
"."
] | python | train |
jlesquembre/jlle | jlle/releaser/vcs.py | https://github.com/jlesquembre/jlle/blob/3645d8f203708355853ef911f4b887ae4d794826/jlle/releaser/vcs.py#L121-L138 | def history_file(self, location=None):
"""Return history file location.
"""
if location:
# Hardcoded location passed from the config file.
if os.path.exists(location):
return location
else:
logger.warn("The specified history fil... | [
"def",
"history_file",
"(",
"self",
",",
"location",
"=",
"None",
")",
":",
"if",
"location",
":",
"# Hardcoded location passed from the config file.",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"location",
")",
":",
"return",
"location",
"else",
":",
"logge... | Return history file location. | [
"Return",
"history",
"file",
"location",
"."
] | python | train |
Nukesor/pueue | pueue/daemon/daemon.py | https://github.com/Nukesor/pueue/blob/f1d276360454d4dd2738658a13df1e20caa4b926/pueue/daemon/daemon.py#L319-L344 | def send_status(self, payload):
"""Send the daemon status and the current queue for displaying."""
answer = {}
data = []
# Get daemon status
if self.paused:
answer['status'] = 'paused'
else:
answer['status'] = 'running'
# Add current queue... | [
"def",
"send_status",
"(",
"self",
",",
"payload",
")",
":",
"answer",
"=",
"{",
"}",
"data",
"=",
"[",
"]",
"# Get daemon status",
"if",
"self",
".",
"paused",
":",
"answer",
"[",
"'status'",
"]",
"=",
"'paused'",
"else",
":",
"answer",
"[",
"'status'... | Send the daemon status and the current queue for displaying. | [
"Send",
"the",
"daemon",
"status",
"and",
"the",
"current",
"queue",
"for",
"displaying",
"."
] | python | train |
pvlib/pvlib-python | pvlib/pvsystem.py | https://github.com/pvlib/pvlib-python/blob/2e844a595b820b43d1170269781fa66bd0ccc8a3/pvlib/pvsystem.py#L1825-L1908 | def sapm_celltemp(poa_global, wind_speed, temp_air,
model='open_rack_cell_glassback'):
'''
Estimate cell and module temperatures per the Sandia PV Array
Performance Model (SAPM, SAND2004-3535), from the incident
irradiance, wind speed, ambient temperature, and SAPM module
parameter... | [
"def",
"sapm_celltemp",
"(",
"poa_global",
",",
"wind_speed",
",",
"temp_air",
",",
"model",
"=",
"'open_rack_cell_glassback'",
")",
":",
"temp_models",
"=",
"TEMP_MODEL_PARAMS",
"[",
"'sapm'",
"]",
"if",
"isinstance",
"(",
"model",
",",
"str",
")",
":",
"mode... | Estimate cell and module temperatures per the Sandia PV Array
Performance Model (SAPM, SAND2004-3535), from the incident
irradiance, wind speed, ambient temperature, and SAPM module
parameters.
Parameters
----------
poa_global : float or Series
Total incident irradiance in W/m^2.
w... | [
"Estimate",
"cell",
"and",
"module",
"temperatures",
"per",
"the",
"Sandia",
"PV",
"Array",
"Performance",
"Model",
"(",
"SAPM",
"SAND2004",
"-",
"3535",
")",
"from",
"the",
"incident",
"irradiance",
"wind",
"speed",
"ambient",
"temperature",
"and",
"SAPM",
"m... | python | train |
theonion/django-bulbs | bulbs/utils/vault.py | https://github.com/theonion/django-bulbs/blob/0c0e6e3127a7dc487b96677fab95cacd2b3806da/bulbs/utils/vault.py#L15-L27 | def read(path):
"""Read a secret from Vault REST endpoint"""
url = '{}/{}/{}'.format(settings.VAULT_BASE_URL.rstrip('/'),
settings.VAULT_BASE_SECRET_PATH.strip('/'),
path.lstrip('/'))
headers = {'X-Vault-Token': settings.VAULT_ACCESS_TOKEN}
resp =... | [
"def",
"read",
"(",
"path",
")",
":",
"url",
"=",
"'{}/{}/{}'",
".",
"format",
"(",
"settings",
".",
"VAULT_BASE_URL",
".",
"rstrip",
"(",
"'/'",
")",
",",
"settings",
".",
"VAULT_BASE_SECRET_PATH",
".",
"strip",
"(",
"'/'",
")",
",",
"path",
".",
"lst... | Read a secret from Vault REST endpoint | [
"Read",
"a",
"secret",
"from",
"Vault",
"REST",
"endpoint"
] | python | train |
pyblish/pyblish-qml | pyblish_qml/ipc/formatting.py | https://github.com/pyblish/pyblish-qml/blob/6095d18b2ec0afd0409a9b1a17e53b0658887283/pyblish_qml/ipc/formatting.py#L153-L185 | def format_instance(instance):
"""Serialise `instance`
For children to be visualised and modified,
they must provide an appropriate implementation
of __str__.
Data that isn't JSON compatible cannot be
visualised nor modified.
Attributes:
name (str): Name of instance
niceNa... | [
"def",
"format_instance",
"(",
"instance",
")",
":",
"instance",
"=",
"{",
"\"name\"",
":",
"instance",
".",
"name",
",",
"\"id\"",
":",
"instance",
".",
"id",
",",
"\"data\"",
":",
"format_data",
"(",
"instance",
".",
"data",
")",
",",
"\"children\"",
"... | Serialise `instance`
For children to be visualised and modified,
they must provide an appropriate implementation
of __str__.
Data that isn't JSON compatible cannot be
visualised nor modified.
Attributes:
name (str): Name of instance
niceName (str, optional): Nice name of insta... | [
"Serialise",
"instance"
] | python | train |
saltstack/salt | salt/states/grafana4_org.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/grafana4_org.py#L220-L251 | def absent(name, profile='grafana'):
'''
Ensure that a org is present.
name
Name of the org to remove.
profile
Configuration profile used to connect to the Grafana instance.
Default is 'grafana'.
'''
if isinstance(profile, string_types):
profile = __salt__['conf... | [
"def",
"absent",
"(",
"name",
",",
"profile",
"=",
"'grafana'",
")",
":",
"if",
"isinstance",
"(",
"profile",
",",
"string_types",
")",
":",
"profile",
"=",
"__salt__",
"[",
"'config.option'",
"]",
"(",
"profile",
")",
"ret",
"=",
"{",
"'name'",
":",
"... | Ensure that a org is present.
name
Name of the org to remove.
profile
Configuration profile used to connect to the Grafana instance.
Default is 'grafana'. | [
"Ensure",
"that",
"a",
"org",
"is",
"present",
"."
] | python | train |
libChEBI/libChEBIpy | libchebipy/_parsers.py | https://github.com/libChEBI/libChEBIpy/blob/89f223a91f518619d5e3910070d283adcac1626e/libchebipy/_parsers.py#L83-L88 | def get_mass(chebi_id):
'''Returns mass'''
if len(__MASSES) == 0:
__parse_chemical_data()
return __MASSES[chebi_id] if chebi_id in __MASSES else float('NaN') | [
"def",
"get_mass",
"(",
"chebi_id",
")",
":",
"if",
"len",
"(",
"__MASSES",
")",
"==",
"0",
":",
"__parse_chemical_data",
"(",
")",
"return",
"__MASSES",
"[",
"chebi_id",
"]",
"if",
"chebi_id",
"in",
"__MASSES",
"else",
"float",
"(",
"'NaN'",
")"
] | Returns mass | [
"Returns",
"mass"
] | python | train |
sbarham/dsrt | dsrt/data/SampleSet.py | https://github.com/sbarham/dsrt/blob/bc664739f2f52839461d3e72773b71146fd56a9a/dsrt/data/SampleSet.py#L48-L63 | def log(self, priority, msg):
"""
Just a wrapper, for convenience.
NB1: priority may be set to one of:
- CRITICAL [50]
- ERROR [40]
- WARNING [30]
- INFO [20]
- DEBUG [10]
- NOTSET [0]
Anything else defa... | [
"def",
"log",
"(",
"self",
",",
"priority",
",",
"msg",
")",
":",
"# self.logger.log(self.config.levelmap[priority], msg)",
"self",
".",
"logger",
".",
"log",
"(",
"logging",
".",
"CRITICAL",
",",
"msg",
")"
] | Just a wrapper, for convenience.
NB1: priority may be set to one of:
- CRITICAL [50]
- ERROR [40]
- WARNING [30]
- INFO [20]
- DEBUG [10]
- NOTSET [0]
Anything else defaults to [20]
NB2: the levelmap is a defaul... | [
"Just",
"a",
"wrapper",
"for",
"convenience",
".",
"NB1",
":",
"priority",
"may",
"be",
"set",
"to",
"one",
"of",
":",
"-",
"CRITICAL",
"[",
"50",
"]",
"-",
"ERROR",
"[",
"40",
"]",
"-",
"WARNING",
"[",
"30",
"]",
"-",
"INFO",
"[",
"20",
"]",
"... | python | train |
jkokorian/pyqt2waybinding | pyqt2waybinding/__init__.py | https://github.com/jkokorian/pyqt2waybinding/blob/fb1fb84f55608cfbf99c6486650100ba81743117/pyqt2waybinding/__init__.py#L168-L188 | def _updateEndpoints(self,*args,**kwargs):
"""
Updates all endpoints except the one from which this slot was called.
Note: this method is probably not complete threadsafe. Maybe a lock is needed when setter self.ignoreEvents
"""
sender = self.sender()
if not self.ignore... | [
"def",
"_updateEndpoints",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"sender",
"=",
"self",
".",
"sender",
"(",
")",
"if",
"not",
"self",
".",
"ignoreEvents",
":",
"self",
".",
"ignoreEvents",
"=",
"True",
"for",
"binding",
"i... | Updates all endpoints except the one from which this slot was called.
Note: this method is probably not complete threadsafe. Maybe a lock is needed when setter self.ignoreEvents | [
"Updates",
"all",
"endpoints",
"except",
"the",
"one",
"from",
"which",
"this",
"slot",
"was",
"called",
"."
] | python | train |
jobovy/galpy | galpy/potential/SpiralArmsPotential.py | https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/potential/SpiralArmsPotential.py#L248-L335 | def _R2deriv(self, R, z, phi=0, t=0):
"""
NAME:
_R2deriv
PURPOSE:
Evaluate the second (cylindrical) radial derivative of the potential.
(d^2 potential / d R^2)
INPUT:
:param R: galactocentric cylindrical radius (must be scalar, not array)
... | [
"def",
"_R2deriv",
"(",
"self",
",",
"R",
",",
"z",
",",
"phi",
"=",
"0",
",",
"t",
"=",
"0",
")",
":",
"Rs",
"=",
"self",
".",
"_Rs",
"He",
"=",
"self",
".",
"_H",
"*",
"np",
".",
"exp",
"(",
"-",
"(",
"R",
"-",
"self",
".",
"_r_ref",
... | NAME:
_R2deriv
PURPOSE:
Evaluate the second (cylindrical) radial derivative of the potential.
(d^2 potential / d R^2)
INPUT:
:param R: galactocentric cylindrical radius (must be scalar, not array)
:param z: vertical height (must be scalar, not... | [
"NAME",
":",
"_R2deriv",
"PURPOSE",
":",
"Evaluate",
"the",
"second",
"(",
"cylindrical",
")",
"radial",
"derivative",
"of",
"the",
"potential",
".",
"(",
"d^2",
"potential",
"/",
"d",
"R^2",
")",
"INPUT",
":",
":",
"param",
"R",
":",
"galactocentric",
"... | python | train |
pyQode/pyqode.core | pyqode/core/widgets/tabs.py | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/tabs.py#L89-L101 | def close_others(self):
"""
Closes every editors tabs except the current one.
"""
current_widget = self.currentWidget()
self._try_close_dirty_tabs(exept=current_widget)
i = 0
while self.count() > 1:
widget = self.widget(i)
if widget != curr... | [
"def",
"close_others",
"(",
"self",
")",
":",
"current_widget",
"=",
"self",
".",
"currentWidget",
"(",
")",
"self",
".",
"_try_close_dirty_tabs",
"(",
"exept",
"=",
"current_widget",
")",
"i",
"=",
"0",
"while",
"self",
".",
"count",
"(",
")",
">",
"1",... | Closes every editors tabs except the current one. | [
"Closes",
"every",
"editors",
"tabs",
"except",
"the",
"current",
"one",
"."
] | python | train |
GoogleCloudPlatform/appengine-gcs-client | python/src/cloudstorage/common.py | https://github.com/GoogleCloudPlatform/appengine-gcs-client/blob/d11078331ecd915d753c886e96a80133599f3f98/python/src/cloudstorage/common.py#L272-L287 | def _validate_path(path):
"""Basic validation of Google Storage paths.
Args:
path: a Google Storage path. It should have form '/bucket/filename'
or '/bucket'.
Raises:
ValueError: if path is invalid.
TypeError: if path is not of type basestring.
"""
if not path:
raise ValueError('Path i... | [
"def",
"_validate_path",
"(",
"path",
")",
":",
"if",
"not",
"path",
":",
"raise",
"ValueError",
"(",
"'Path is empty'",
")",
"if",
"not",
"isinstance",
"(",
"path",
",",
"basestring",
")",
":",
"raise",
"TypeError",
"(",
"'Path should be a string but is %s (%s)... | Basic validation of Google Storage paths.
Args:
path: a Google Storage path. It should have form '/bucket/filename'
or '/bucket'.
Raises:
ValueError: if path is invalid.
TypeError: if path is not of type basestring. | [
"Basic",
"validation",
"of",
"Google",
"Storage",
"paths",
"."
] | python | train |
inasafe/inasafe | safe/gui/tools/wizard/step_fc90_analysis.py | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/step_fc90_analysis.py#L293-L300 | def setup_gui_analysis_done(self):
"""Helper method to setup gui if analysis is done."""
self.progress_bar.hide()
self.lblAnalysisStatus.setText(tr('Analysis done.'))
self.pbnReportWeb.show()
self.pbnReportPDF.show()
# self.pbnReportComposer.show() # Hide until it works ... | [
"def",
"setup_gui_analysis_done",
"(",
"self",
")",
":",
"self",
".",
"progress_bar",
".",
"hide",
"(",
")",
"self",
".",
"lblAnalysisStatus",
".",
"setText",
"(",
"tr",
"(",
"'Analysis done.'",
")",
")",
"self",
".",
"pbnReportWeb",
".",
"show",
"(",
")",... | Helper method to setup gui if analysis is done. | [
"Helper",
"method",
"to",
"setup",
"gui",
"if",
"analysis",
"is",
"done",
"."
] | python | train |
sci-bots/pygtkhelpers | pygtkhelpers/ui/objectlist/view.py | https://github.com/sci-bots/pygtkhelpers/blob/3a6e6d6340221c686229cd1c951d7537dae81b07/pygtkhelpers/ui/objectlist/view.py#L507-L518 | def remove(self, item):
"""Remove an item from the list
:param item: The item to remove from the list.
:raises ValueError: If the item is not present in the list.
"""
if item not in self:
raise ValueError('objectlist.remove(item) failed, item not in list')
it... | [
"def",
"remove",
"(",
"self",
",",
"item",
")",
":",
"if",
"item",
"not",
"in",
"self",
":",
"raise",
"ValueError",
"(",
"'objectlist.remove(item) failed, item not in list'",
")",
"item_id",
"=",
"int",
"(",
"self",
".",
"_view_path_for",
"(",
"item",
")",
"... | Remove an item from the list
:param item: The item to remove from the list.
:raises ValueError: If the item is not present in the list. | [
"Remove",
"an",
"item",
"from",
"the",
"list"
] | python | train |
jupyter-widgets/ipywidgets | ipywidgets/widgets/interaction.py | https://github.com/jupyter-widgets/ipywidgets/blob/36fe37594cd5a268def228709ca27e37b99ac606/ipywidgets/widgets/interaction.py#L60-L80 | def interactive_output(f, controls):
"""Connect widget controls to a function.
This function does not generate a user interface for the widgets (unlike `interact`).
This enables customisation of the widget user interface layout.
The user interface layout must be defined and displayed manually.
"""
... | [
"def",
"interactive_output",
"(",
"f",
",",
"controls",
")",
":",
"out",
"=",
"Output",
"(",
")",
"def",
"observer",
"(",
"change",
")",
":",
"kwargs",
"=",
"{",
"k",
":",
"v",
".",
"value",
"for",
"k",
",",
"v",
"in",
"controls",
".",
"items",
"... | Connect widget controls to a function.
This function does not generate a user interface for the widgets (unlike `interact`).
This enables customisation of the widget user interface layout.
The user interface layout must be defined and displayed manually. | [
"Connect",
"widget",
"controls",
"to",
"a",
"function",
"."
] | python | train |
cs01/pygdbmi | pygdbmi/gdbmiparser.py | https://github.com/cs01/pygdbmi/blob/709c781794d3c3b903891f83da011d2d995895d1/pygdbmi/gdbmiparser.py#L182-L193 | def _get_notify_msg_and_payload(result, stream):
"""Get notify message and payload dict"""
token = stream.advance_past_chars(["=", "*"])
token = int(token) if token != "" else None
logger.debug("%s", fmt_green("parsing message"))
message = stream.advance_past_chars([","])
logger.debug("parsed m... | [
"def",
"_get_notify_msg_and_payload",
"(",
"result",
",",
"stream",
")",
":",
"token",
"=",
"stream",
".",
"advance_past_chars",
"(",
"[",
"\"=\"",
",",
"\"*\"",
"]",
")",
"token",
"=",
"int",
"(",
"token",
")",
"if",
"token",
"!=",
"\"\"",
"else",
"None... | Get notify message and payload dict | [
"Get",
"notify",
"message",
"and",
"payload",
"dict"
] | python | valid |
python-diamond/Diamond | src/collectors/numa/numa.py | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/numa/numa.py#L21-L30 | def get_default_config(self):
"""
Returns the default collector settings
"""
config = super(NumaCollector, self).get_default_config()
config.update({
'path': 'numa',
'bin': self.find_binary('numactl'),
})
return config | [
"def",
"get_default_config",
"(",
"self",
")",
":",
"config",
"=",
"super",
"(",
"NumaCollector",
",",
"self",
")",
".",
"get_default_config",
"(",
")",
"config",
".",
"update",
"(",
"{",
"'path'",
":",
"'numa'",
",",
"'bin'",
":",
"self",
".",
"find_bin... | Returns the default collector settings | [
"Returns",
"the",
"default",
"collector",
"settings"
] | python | train |
Hrabal/TemPy | tempy/tempy.py | https://github.com/Hrabal/TemPy/blob/7d229b73e2ce3ccbb8254deae05c1f758f626ed6/tempy/tempy.py#L340-L343 | def append(self, _, child, name=None):
"""Adds childs to this tag, after the current existing childs."""
self._insert(child, name=name)
return self | [
"def",
"append",
"(",
"self",
",",
"_",
",",
"child",
",",
"name",
"=",
"None",
")",
":",
"self",
".",
"_insert",
"(",
"child",
",",
"name",
"=",
"name",
")",
"return",
"self"
] | Adds childs to this tag, after the current existing childs. | [
"Adds",
"childs",
"to",
"this",
"tag",
"after",
"the",
"current",
"existing",
"childs",
"."
] | python | train |
pymacaron/pymacaron-core | pymacaron_core/swagger/spec.py | https://github.com/pymacaron/pymacaron-core/blob/95070a39ed7065a84244ff5601fea4d54cc72b66/pymacaron_core/swagger/spec.py#L95-L105 | def model_to_json(self, object, cleanup=True):
"""Take a model instance and return it as a json struct"""
model_name = type(object).__name__
if model_name not in self.swagger_dict['definitions']:
raise ValidationError("Swagger spec has no definition for model %s" % model_name)
... | [
"def",
"model_to_json",
"(",
"self",
",",
"object",
",",
"cleanup",
"=",
"True",
")",
":",
"model_name",
"=",
"type",
"(",
"object",
")",
".",
"__name__",
"if",
"model_name",
"not",
"in",
"self",
".",
"swagger_dict",
"[",
"'definitions'",
"]",
":",
"rais... | Take a model instance and return it as a json struct | [
"Take",
"a",
"model",
"instance",
"and",
"return",
"it",
"as",
"a",
"json",
"struct"
] | python | train |
xav-b/pyconsul | pyconsul/http.py | https://github.com/xav-b/pyconsul/blob/06ce3b921d01010c19643424486bea4b22196076/pyconsul/http.py#L27-L32 | def get(self, key, **kwargs):
'''
Fetch value at the given key
kwargs can hold `recurse`, `wait` and `index` params
'''
return self._get('/'.join([self._endpoint, key]), payload=kwargs) | [
"def",
"get",
"(",
"self",
",",
"key",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_get",
"(",
"'/'",
".",
"join",
"(",
"[",
"self",
".",
"_endpoint",
",",
"key",
"]",
")",
",",
"payload",
"=",
"kwargs",
")"
] | Fetch value at the given key
kwargs can hold `recurse`, `wait` and `index` params | [
"Fetch",
"value",
"at",
"the",
"given",
"key",
"kwargs",
"can",
"hold",
"recurse",
"wait",
"and",
"index",
"params"
] | python | train |
allenai/allennlp | allennlp/semparse/domain_languages/wikitables_language.py | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/wikitables_language.py#L477-L488 | def mode_number(self, rows: List[Row], column: NumberColumn) -> Number:
"""
Takes a list of rows and a column and returns the most frequent value under
that column in those rows.
"""
most_frequent_list = self._get_most_frequent_values(rows, column)
if not most_frequent_li... | [
"def",
"mode_number",
"(",
"self",
",",
"rows",
":",
"List",
"[",
"Row",
"]",
",",
"column",
":",
"NumberColumn",
")",
"->",
"Number",
":",
"most_frequent_list",
"=",
"self",
".",
"_get_most_frequent_values",
"(",
"rows",
",",
"column",
")",
"if",
"not",
... | Takes a list of rows and a column and returns the most frequent value under
that column in those rows. | [
"Takes",
"a",
"list",
"of",
"rows",
"and",
"a",
"column",
"and",
"returns",
"the",
"most",
"frequent",
"value",
"under",
"that",
"column",
"in",
"those",
"rows",
"."
] | python | train |
inspirehep/refextract | refextract/references/kbs.py | https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/kbs.py#L161-L174 | def create_institute_numeration_group_regexp_pattern(patterns):
"""Using a list of regexp patterns for recognising numeration patterns
for institute preprint references, ordered by length - longest to
shortest - create a grouped 'OR' or of these patterns, ready to be
used in a bigger regexp.
... | [
"def",
"create_institute_numeration_group_regexp_pattern",
"(",
"patterns",
")",
":",
"patterns_list",
"=",
"[",
"institute_num_pattern_to_regex",
"(",
"p",
"[",
"1",
"]",
")",
"for",
"p",
"in",
"patterns",
"]",
"grouped_numeration_pattern",
"=",
"u\"(?P<numn>%s)\"",
... | Using a list of regexp patterns for recognising numeration patterns
for institute preprint references, ordered by length - longest to
shortest - create a grouped 'OR' or of these patterns, ready to be
used in a bigger regexp.
@param patterns: (list) of strings. All of the numeration regexp
... | [
"Using",
"a",
"list",
"of",
"regexp",
"patterns",
"for",
"recognising",
"numeration",
"patterns",
"for",
"institute",
"preprint",
"references",
"ordered",
"by",
"length",
"-",
"longest",
"to",
"shortest",
"-",
"create",
"a",
"grouped",
"OR",
"or",
"of",
"these... | python | train |
gabstopper/smc-python | smc/core/route.py | https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/core/route.py#L504-L529 | def add_static_route(self, gateway, destination, network=None):
"""
Add a static route to this route table. Destination can be any element
type supported in the routing table such as a Group of network members.
Since a static route gateway needs to be on the same network as the
i... | [
"def",
"add_static_route",
"(",
"self",
",",
"gateway",
",",
"destination",
",",
"network",
"=",
"None",
")",
":",
"routing_node_gateway",
"=",
"RoutingNodeGateway",
"(",
"gateway",
",",
"destinations",
"=",
"destination",
")",
"return",
"self",
".",
"_add_gatew... | Add a static route to this route table. Destination can be any element
type supported in the routing table such as a Group of network members.
Since a static route gateway needs to be on the same network as the
interface, provide a value for `network` if an interface has multiple
address... | [
"Add",
"a",
"static",
"route",
"to",
"this",
"route",
"table",
".",
"Destination",
"can",
"be",
"any",
"element",
"type",
"supported",
"in",
"the",
"routing",
"table",
"such",
"as",
"a",
"Group",
"of",
"network",
"members",
".",
"Since",
"a",
"static",
"... | python | train |
viniciuschiele/flask-apscheduler | flask_apscheduler/scheduler.py | https://github.com/viniciuschiele/flask-apscheduler/blob/cc52c39e1948c4e8de5da0d01db45f1779f61997/flask_apscheduler/scheduler.py#L162-L173 | def delete_job(self, id, jobstore=None):
"""
DEPRECATED, use remove_job instead.
Remove a job, preventing it from being run any more.
:param str id: the identifier of the job
:param str jobstore: alias of the job store that contains the job
"""
warnings.warn('de... | [
"def",
"delete_job",
"(",
"self",
",",
"id",
",",
"jobstore",
"=",
"None",
")",
":",
"warnings",
".",
"warn",
"(",
"'delete_job has been deprecated, use remove_job instead.'",
",",
"DeprecationWarning",
")",
"self",
".",
"remove_job",
"(",
"id",
",",
"jobstore",
... | DEPRECATED, use remove_job instead.
Remove a job, preventing it from being run any more.
:param str id: the identifier of the job
:param str jobstore: alias of the job store that contains the job | [
"DEPRECATED",
"use",
"remove_job",
"instead",
"."
] | python | train |
chriso/timeseries | timeseries/time_series.py | https://github.com/chriso/timeseries/blob/8b81e6cfd955a7cf75a421dfdb71b3f9e53be64d/timeseries/time_series.py#L62-L66 | def trend_coefficients(self, order=LINEAR):
'''Calculate trend coefficients for the specified order.'''
if not len(self.points):
raise ArithmeticError('Cannot calculate the trend of an empty series')
return LazyImport.numpy().polyfit(self.timestamps, self.values, order) | [
"def",
"trend_coefficients",
"(",
"self",
",",
"order",
"=",
"LINEAR",
")",
":",
"if",
"not",
"len",
"(",
"self",
".",
"points",
")",
":",
"raise",
"ArithmeticError",
"(",
"'Cannot calculate the trend of an empty series'",
")",
"return",
"LazyImport",
".",
"nump... | Calculate trend coefficients for the specified order. | [
"Calculate",
"trend",
"coefficients",
"for",
"the",
"specified",
"order",
"."
] | python | train |
pyrogram/pyrogram | pyrogram/client/methods/chats/export_chat_invite_link.py | https://github.com/pyrogram/pyrogram/blob/e7258a341ba905cfa86264c22040654db732ec1c/pyrogram/client/methods/chats/export_chat_invite_link.py#L26-L58 | def export_chat_invite_link(
self,
chat_id: Union[int, str]
) -> str:
"""Use this method to generate a new invite link for a chat; any previously generated link is revoked.
You must be an administrator in the chat for this to work and have the appropriate admin rights.
Args... | [
"def",
"export_chat_invite_link",
"(",
"self",
",",
"chat_id",
":",
"Union",
"[",
"int",
",",
"str",
"]",
")",
"->",
"str",
":",
"peer",
"=",
"self",
".",
"resolve_peer",
"(",
"chat_id",
")",
"if",
"isinstance",
"(",
"peer",
",",
"types",
".",
"InputPe... | Use this method to generate a new invite link for a chat; any previously generated link is revoked.
You must be an administrator in the chat for this to work and have the appropriate admin rights.
Args:
chat_id (``int`` | ``str``):
Unique identifier for the target chat or u... | [
"Use",
"this",
"method",
"to",
"generate",
"a",
"new",
"invite",
"link",
"for",
"a",
"chat",
";",
"any",
"previously",
"generated",
"link",
"is",
"revoked",
"."
] | python | train |
waqasbhatti/astrobase | astrobase/periodbase/__init__.py | https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/periodbase/__init__.py#L509-L589 | def make_combined_periodogram(pflist, outfile, addmethods=False):
'''This just puts all of the period-finders on a single periodogram.
This will renormalize all of the periodograms so their values lie between 0
and 1, with values lying closer to 1 being more significant. Periodograms
that give the same... | [
"def",
"make_combined_periodogram",
"(",
"pflist",
",",
"outfile",
",",
"addmethods",
"=",
"False",
")",
":",
"import",
"matplotlib",
".",
"pyplot",
"as",
"plt",
"for",
"pf",
"in",
"pflist",
":",
"if",
"pf",
"[",
"'method'",
"]",
"==",
"'pdm'",
":",
"plt... | This just puts all of the period-finders on a single periodogram.
This will renormalize all of the periodograms so their values lie between 0
and 1, with values lying closer to 1 being more significant. Periodograms
that give the same best periods will have their peaks line up together.
Parameters
... | [
"This",
"just",
"puts",
"all",
"of",
"the",
"period",
"-",
"finders",
"on",
"a",
"single",
"periodogram",
"."
] | python | valid |
estnltk/estnltk | estnltk/disambiguator.py | https://github.com/estnltk/estnltk/blob/28ae334a68a0673072febc318635f04da0dcc54a/estnltk/disambiguator.py#L491-L545 | def __find_hidden_analyses(self, docs):
""" Jätab meelde, millised analüüsid on nn peidetud ehk siis mida ei
tule arvestada lemmade järelühestamisel:
*) kesksõnade nud, dud, tud mitmesused;
*) muutumatute sõnade sõnaliigi mitmesus;
*) oleviku 'olema' mitmesus... | [
"def",
"__find_hidden_analyses",
"(",
"self",
",",
"docs",
")",
":",
"hidden",
"=",
"dict",
"(",
")",
"nudTudLopud",
"=",
"re",
".",
"compile",
"(",
"'^.*[ntd]ud$'",
")",
"for",
"d",
"in",
"range",
"(",
"len",
"(",
"docs",
")",
")",
":",
"for",
"w",
... | Jätab meelde, millised analüüsid on nn peidetud ehk siis mida ei
tule arvestada lemmade järelühestamisel:
*) kesksõnade nud, dud, tud mitmesused;
*) muutumatute sõnade sõnaliigi mitmesus;
*) oleviku 'olema' mitmesus ('nad on' vs 'ta on');
*) asesõnade ai... | [
"Jätab",
"meelde",
"millised",
"analüüsid",
"on",
"nn",
"peidetud",
"ehk",
"siis",
"mida",
"ei",
"tule",
"arvestada",
"lemmade",
"järelühestamisel",
":",
"*",
")",
"kesksõnade",
"nud",
"dud",
"tud",
"mitmesused",
";",
"*",
")",
"muutumatute",
"sõnade",
"sõnali... | python | train |
klen/muffin-admin | muffin_admin/peewee.py | https://github.com/klen/muffin-admin/blob/404dc8e5107e943b7c42fa21c679c34ddb4de1d5/muffin_admin/peewee.py#L212-L221 | def apply(self, query, data):
"""Filter a query."""
field = self.model_field or query.model_class._meta.fields.get(self.name)
if not field or self.name not in data:
return query
value = self.value(data)
if value is self.default:
return query
value ... | [
"def",
"apply",
"(",
"self",
",",
"query",
",",
"data",
")",
":",
"field",
"=",
"self",
".",
"model_field",
"or",
"query",
".",
"model_class",
".",
"_meta",
".",
"fields",
".",
"get",
"(",
"self",
".",
"name",
")",
"if",
"not",
"field",
"or",
"self... | Filter a query. | [
"Filter",
"a",
"query",
"."
] | python | train |
thautwarm/Redy | Redy/Magic/Classic.py | https://github.com/thautwarm/Redy/blob/8beee5c5f752edfd2754bb1e6b5f4acb016a7770/Redy/Magic/Classic.py#L77-L102 | def execute(func: types.FunctionType):
"""
>>> from Redy.Magic.Classic import execute
>>> x = 1
>>> @execute
>>> def f(x = x) -> int:
>>> return x + 1
>>> assert f is 2
"""
spec = getfullargspec(func)
default = spec.defaults
arg_cursor = 0
def get_item(name):
... | [
"def",
"execute",
"(",
"func",
":",
"types",
".",
"FunctionType",
")",
":",
"spec",
"=",
"getfullargspec",
"(",
"func",
")",
"default",
"=",
"spec",
".",
"defaults",
"arg_cursor",
"=",
"0",
"def",
"get_item",
"(",
"name",
")",
":",
"nonlocal",
"arg_curso... | >>> from Redy.Magic.Classic import execute
>>> x = 1
>>> @execute
>>> def f(x = x) -> int:
>>> return x + 1
>>> assert f is 2 | [
">>>",
"from",
"Redy",
".",
"Magic",
".",
"Classic",
"import",
"execute",
">>>",
"x",
"=",
"1",
">>>"
] | python | train |
luckydonald/pytgbot | code_generation/output/pytgbot/api_types/receivable/stickers.py | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/pytgbot/api_types/receivable/stickers.py#L81-L96 | def to_array(self):
"""
Serializes this StickerSet to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(StickerSet, self).to_array()
array['name'] = u(self.name) # py2: type unicode, py3: type str
array['tit... | [
"def",
"to_array",
"(",
"self",
")",
":",
"array",
"=",
"super",
"(",
"StickerSet",
",",
"self",
")",
".",
"to_array",
"(",
")",
"array",
"[",
"'name'",
"]",
"=",
"u",
"(",
"self",
".",
"name",
")",
"# py2: type unicode, py3: type str",
"array",
"[",
"... | Serializes this StickerSet to a dictionary.
:return: dictionary representation of this object.
:rtype: dict | [
"Serializes",
"this",
"StickerSet",
"to",
"a",
"dictionary",
"."
] | python | train |
pydata/xarray | xarray/core/dataset.py | https://github.com/pydata/xarray/blob/6d93a95d05bdbfc33fff24064f67d29dd891ab58/xarray/core/dataset.py#L3129-L3200 | def reduce(self, func, dim=None, keep_attrs=None, numeric_only=False,
allow_lazy=False, **kwargs):
"""Reduce this dataset by applying `func` along some dimension(s).
Parameters
----------
func : function
Function which can be called in the form
`f(... | [
"def",
"reduce",
"(",
"self",
",",
"func",
",",
"dim",
"=",
"None",
",",
"keep_attrs",
"=",
"None",
",",
"numeric_only",
"=",
"False",
",",
"allow_lazy",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"dim",
"is",
"ALL_DIMS",
":",
"dim",
"=... | Reduce this dataset by applying `func` along some dimension(s).
Parameters
----------
func : function
Function which can be called in the form
`f(x, axis=axis, **kwargs)` to return the result of reducing an
np.ndarray over an integer valued axis.
dim ... | [
"Reduce",
"this",
"dataset",
"by",
"applying",
"func",
"along",
"some",
"dimension",
"(",
"s",
")",
"."
] | python | train |
qacafe/cdrouter.py | cdrouter/highlights.py | https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/highlights.py#L85-L94 | def create(self, id, seq, resource): # pylint: disable=invalid-name,redefined-builtin
"""Create a highlight.
:param id: Result ID as an int.
:param seq: TestResult sequence ID as an int.
:param resource: :class:`highlights.Highlight <highlights.Highlight>` object
:return: :class... | [
"def",
"create",
"(",
"self",
",",
"id",
",",
"seq",
",",
"resource",
")",
":",
"# pylint: disable=invalid-name,redefined-builtin",
"return",
"self",
".",
"create_or_edit",
"(",
"id",
",",
"seq",
",",
"resource",
")"
] | Create a highlight.
:param id: Result ID as an int.
:param seq: TestResult sequence ID as an int.
:param resource: :class:`highlights.Highlight <highlights.Highlight>` object
:return: :class:`highlights.Highlight <highlights.Highlight>` object
:rtype: highlights.Highlight | [
"Create",
"a",
"highlight",
"."
] | python | train |
grundic/yagocd | yagocd/client.py | https://github.com/grundic/yagocd/blob/4c75336ae6f107c8723d37b15e52169151822127/yagocd/client.py#L221-L229 | def info(self):
"""
Property for accessing :class:`InfoManager` instance, which is used to general server info.
:rtype: yagocd.resources.info.InfoManager
"""
if self._info_manager is None:
self._info_manager = InfoManager(session=self._session)
return self._i... | [
"def",
"info",
"(",
"self",
")",
":",
"if",
"self",
".",
"_info_manager",
"is",
"None",
":",
"self",
".",
"_info_manager",
"=",
"InfoManager",
"(",
"session",
"=",
"self",
".",
"_session",
")",
"return",
"self",
".",
"_info_manager"
] | Property for accessing :class:`InfoManager` instance, which is used to general server info.
:rtype: yagocd.resources.info.InfoManager | [
"Property",
"for",
"accessing",
":",
"class",
":",
"InfoManager",
"instance",
"which",
"is",
"used",
"to",
"general",
"server",
"info",
"."
] | python | train |
fabioz/PyDev.Debugger | third_party/pep8/autopep8.py | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/autopep8.py#L1897-L1921 | def _split_after_delimiter(self, item, indent_amt):
"""Split the line only after a delimiter."""
self._delete_whitespace()
if self.fits_on_current_line(item.size):
return
last_space = None
for item in reversed(self._lines):
if (
last_spac... | [
"def",
"_split_after_delimiter",
"(",
"self",
",",
"item",
",",
"indent_amt",
")",
":",
"self",
".",
"_delete_whitespace",
"(",
")",
"if",
"self",
".",
"fits_on_current_line",
"(",
"item",
".",
"size",
")",
":",
"return",
"last_space",
"=",
"None",
"for",
... | Split the line only after a delimiter. | [
"Split",
"the",
"line",
"only",
"after",
"a",
"delimiter",
"."
] | python | train |
quantopian/zipline | zipline/lib/labelarray.py | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/lib/labelarray.py#L38-L43 | def compare_arrays(left, right):
"Eq check with a short-circuit for identical objects."
return (
left is right
or ((left.shape == right.shape) and (left == right).all())
) | [
"def",
"compare_arrays",
"(",
"left",
",",
"right",
")",
":",
"return",
"(",
"left",
"is",
"right",
"or",
"(",
"(",
"left",
".",
"shape",
"==",
"right",
".",
"shape",
")",
"and",
"(",
"left",
"==",
"right",
")",
".",
"all",
"(",
")",
")",
")"
] | Eq check with a short-circuit for identical objects. | [
"Eq",
"check",
"with",
"a",
"short",
"-",
"circuit",
"for",
"identical",
"objects",
"."
] | python | train |
reingart/pyafipws | wsctg.py | https://github.com/reingart/pyafipws/blob/ee87cfe4ac12285ab431df5fec257f103042d1ab/wsctg.py#L640-L654 | def ConsultarConstanciaCTGPDF(self, numero_ctg=None,
archivo="constancia.pdf"):
"Operación Consultar Constancia de CTG en PDF"
ret = self.client.consultarConstanciaCTGPDF(request=dict(
auth={
'token': self.Token... | [
"def",
"ConsultarConstanciaCTGPDF",
"(",
"self",
",",
"numero_ctg",
"=",
"None",
",",
"archivo",
"=",
"\"constancia.pdf\"",
")",
":",
"ret",
"=",
"self",
".",
"client",
".",
"consultarConstanciaCTGPDF",
"(",
"request",
"=",
"dict",
"(",
"auth",
"=",
"{",
"'t... | Operación Consultar Constancia de CTG en PDF | [
"Operación",
"Consultar",
"Constancia",
"de",
"CTG",
"en",
"PDF"
] | python | train |
hvac/hvac | hvac/v1/__init__.py | https://github.com/hvac/hvac/blob/cce5b86889193f622c2a72a4a1b7e1c9c8aff1ce/hvac/v1/__init__.py#L675-L703 | def create_userpass(self, username, password, policies, mount_point='userpass', **kwargs):
"""POST /auth/<mount point>/users/<username>
:param username:
:type username:
:param password:
:type password:
:param policies:
:type policies:
:param mount_point:
... | [
"def",
"create_userpass",
"(",
"self",
",",
"username",
",",
"password",
",",
"policies",
",",
"mount_point",
"=",
"'userpass'",
",",
"*",
"*",
"kwargs",
")",
":",
"# Users can have more than 1 policy. It is easier for the user to pass in the",
"# policies as a list so if t... | POST /auth/<mount point>/users/<username>
:param username:
:type username:
:param password:
:type password:
:param policies:
:type policies:
:param mount_point:
:type mount_point:
:param kwargs:
:type kwargs:
:return:
:rtyp... | [
"POST",
"/",
"auth",
"/",
"<mount",
"point",
">",
"/",
"users",
"/",
"<username",
">"
] | python | train |
ibm-watson-iot/iot-python | samples/customMessageFormat/myCustomCodec.py | https://github.com/ibm-watson-iot/iot-python/blob/195f05adce3fba4ec997017e41e02ebd85c0c4cc/samples/customMessageFormat/myCustomCodec.py#L45-L61 | def decode(message):
'''
The decoder understands the comma-seperated format produced by the encoder and
allocates the two values to the correct keys:
data['hello'] = 'world'
data['x'] = 10
'''
(hello, x) = message.payload.split(",")
data = {}
... | [
"def",
"decode",
"(",
"message",
")",
":",
"(",
"hello",
",",
"x",
")",
"=",
"message",
".",
"payload",
".",
"split",
"(",
"\",\"",
")",
"data",
"=",
"{",
"}",
"data",
"[",
"'hello'",
"]",
"=",
"hello",
"data",
"[",
"'x'",
"]",
"=",
"x",
"times... | The decoder understands the comma-seperated format produced by the encoder and
allocates the two values to the correct keys:
data['hello'] = 'world'
data['x'] = 10 | [
"The",
"decoder",
"understands",
"the",
"comma",
"-",
"seperated",
"format",
"produced",
"by",
"the",
"encoder",
"and",
"allocates",
"the",
"two",
"values",
"to",
"the",
"correct",
"keys",
":",
"data",
"[",
"hello",
"]",
"=",
"world",
"data",
"[",
"x",
"... | python | test |
crytic/slither | slither/core/declarations/contract.py | https://github.com/crytic/slither/blob/04c147f7e50223c6af458ca430befae747ccd259/slither/core/declarations/contract.py#L488-L494 | def all_state_variables_written(self):
'''
list(StateVariable): List all of the state variables written
'''
all_state_variables_written = [f.all_state_variables_written() for f in self.functions + self.modifiers]
all_state_variables_written = [item for sublist in all_state_va... | [
"def",
"all_state_variables_written",
"(",
"self",
")",
":",
"all_state_variables_written",
"=",
"[",
"f",
".",
"all_state_variables_written",
"(",
")",
"for",
"f",
"in",
"self",
".",
"functions",
"+",
"self",
".",
"modifiers",
"]",
"all_state_variables_written",
... | list(StateVariable): List all of the state variables written | [
"list",
"(",
"StateVariable",
")",
":",
"List",
"all",
"of",
"the",
"state",
"variables",
"written"
] | python | train |
andialbrecht/sqlparse | sqlparse/formatter.py | https://github.com/andialbrecht/sqlparse/blob/913b56e34edc7e3025feea4744dbd762774805c3/sqlparse/formatter.py#L15-L130 | def validate_options(options):
"""Validates options."""
kwcase = options.get('keyword_case')
if kwcase not in [None, 'upper', 'lower', 'capitalize']:
raise SQLParseError('Invalid value for keyword_case: '
'{0!r}'.format(kwcase))
idcase = options.get('identifier_case'... | [
"def",
"validate_options",
"(",
"options",
")",
":",
"kwcase",
"=",
"options",
".",
"get",
"(",
"'keyword_case'",
")",
"if",
"kwcase",
"not",
"in",
"[",
"None",
",",
"'upper'",
",",
"'lower'",
",",
"'capitalize'",
"]",
":",
"raise",
"SQLParseError",
"(",
... | Validates options. | [
"Validates",
"options",
"."
] | python | train |
GearPlug/payu-python | payu/recurring.py | https://github.com/GearPlug/payu-python/blob/47ec5c9fc89f1f89a53ec0a68c84f358bbe3394e/payu/recurring.py#L386-L397 | def get_additional_charge_by_identifier(self, recurring_billing_id):
"""
Query extra charge information of an invoice from its identifier.
Args:
recurring_billing_id: Identifier of the additional charge.
Returns:
"""
fmt = 'recurringBillItems/{}'.format(rec... | [
"def",
"get_additional_charge_by_identifier",
"(",
"self",
",",
"recurring_billing_id",
")",
":",
"fmt",
"=",
"'recurringBillItems/{}'",
".",
"format",
"(",
"recurring_billing_id",
")",
"return",
"self",
".",
"client",
".",
"_get",
"(",
"self",
".",
"url",
"+",
... | Query extra charge information of an invoice from its identifier.
Args:
recurring_billing_id: Identifier of the additional charge.
Returns: | [
"Query",
"extra",
"charge",
"information",
"of",
"an",
"invoice",
"from",
"its",
"identifier",
"."
] | python | train |
Microsoft/nni | src/sdk/pynni/nni/hyperopt_tuner/hyperopt_tuner.py | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/hyperopt_tuner/hyperopt_tuner.py#L88-L116 | def json2parameter(in_x, parameter, name=ROOT):
"""
Change json to parameters.
"""
out_y = copy.deepcopy(in_x)
if isinstance(in_x, dict):
if TYPE in in_x.keys():
_type = in_x[TYPE]
name = name + '-' + _type
if _type == 'choice':
_index = pa... | [
"def",
"json2parameter",
"(",
"in_x",
",",
"parameter",
",",
"name",
"=",
"ROOT",
")",
":",
"out_y",
"=",
"copy",
".",
"deepcopy",
"(",
"in_x",
")",
"if",
"isinstance",
"(",
"in_x",
",",
"dict",
")",
":",
"if",
"TYPE",
"in",
"in_x",
".",
"keys",
"(... | Change json to parameters. | [
"Change",
"json",
"to",
"parameters",
"."
] | python | train |
reingart/gui2py | gui/controls/listview.py | https://github.com/reingart/gui2py/blob/aca0a05f6fcde55c94ad7cc058671a06608b01a4/gui/controls/listview.py#L397-L402 | def clear(self):
"Remove all items and reset internal structures"
dict.clear(self)
self._key = 0
if hasattr(self._list_view, "wx_obj"):
self._list_view.wx_obj.DeleteAllItems() | [
"def",
"clear",
"(",
"self",
")",
":",
"dict",
".",
"clear",
"(",
"self",
")",
"self",
".",
"_key",
"=",
"0",
"if",
"hasattr",
"(",
"self",
".",
"_list_view",
",",
"\"wx_obj\"",
")",
":",
"self",
".",
"_list_view",
".",
"wx_obj",
".",
"DeleteAllItems... | Remove all items and reset internal structures | [
"Remove",
"all",
"items",
"and",
"reset",
"internal",
"structures"
] | python | test |
SuperCowPowers/workbench | workbench/clients/client_helper.py | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/clients/client_helper.py#L7-L24 | def grab_server_args():
"""Grab server info from configuration file"""
workbench_conf = ConfigParser.ConfigParser()
config_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'config.ini')
workbench_conf.read(config_path)
server = workbench_conf.get('workbench', 'server_uri')
p... | [
"def",
"grab_server_args",
"(",
")",
":",
"workbench_conf",
"=",
"ConfigParser",
".",
"ConfigParser",
"(",
")",
"config_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"realpath",
"(",
"_... | Grab server info from configuration file | [
"Grab",
"server",
"info",
"from",
"configuration",
"file"
] | python | train |
apache/incubator-heron | heron/statemgrs/src/python/filestatemanager.py | https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/statemgrs/src/python/filestatemanager.py#L273-L285 | def get_scheduler_location(self, topologyName, callback=None):
"""
Get scheduler location
"""
if callback:
self.scheduler_location_watchers[topologyName].append(callback)
else:
scheduler_location_path = self.get_scheduler_location_path(topologyName)
with open(scheduler_location_pat... | [
"def",
"get_scheduler_location",
"(",
"self",
",",
"topologyName",
",",
"callback",
"=",
"None",
")",
":",
"if",
"callback",
":",
"self",
".",
"scheduler_location_watchers",
"[",
"topologyName",
"]",
".",
"append",
"(",
"callback",
")",
"else",
":",
"scheduler... | Get scheduler location | [
"Get",
"scheduler",
"location"
] | python | valid |
reingart/pyafipws | wsctg.py | https://github.com/reingart/pyafipws/blob/ee87cfe4ac12285ab431df5fec257f103042d1ab/wsctg.py#L387-L410 | def ConfirmarDefinitivo(self, numero_carta_de_porte, numero_ctg,
establecimiento=None, codigo_cosecha=None, peso_neto_carga=None,
**kwargs):
"Confirma arribo definitivo CTG"
ret = self.client.confirmarDefinitivo(request=dict(
... | [
"def",
"ConfirmarDefinitivo",
"(",
"self",
",",
"numero_carta_de_porte",
",",
"numero_ctg",
",",
"establecimiento",
"=",
"None",
",",
"codigo_cosecha",
"=",
"None",
",",
"peso_neto_carga",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"self",
"... | Confirma arribo definitivo CTG | [
"Confirma",
"arribo",
"definitivo",
"CTG"
] | python | train |
glue-viz/glue-vispy-viewers | glue_vispy_viewers/extern/vispy/color/color_space.py | https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/color/color_space.py#L78-L106 | def _hsv_to_rgb(hsvs):
"""Convert Nx3 or Nx4 hsv to rgb"""
hsvs, n_dim = _check_color_dim(hsvs)
# In principle, we *might* be able to vectorize this, but might as well
# wait until a compelling use case appears
rgbs = list()
for hsv in hsvs:
c = hsv[1] * hsv[2]
m = hsv[2] - c
... | [
"def",
"_hsv_to_rgb",
"(",
"hsvs",
")",
":",
"hsvs",
",",
"n_dim",
"=",
"_check_color_dim",
"(",
"hsvs",
")",
"# In principle, we *might* be able to vectorize this, but might as well",
"# wait until a compelling use case appears",
"rgbs",
"=",
"list",
"(",
")",
"for",
"hs... | Convert Nx3 or Nx4 hsv to rgb | [
"Convert",
"Nx3",
"or",
"Nx4",
"hsv",
"to",
"rgb"
] | python | train |
ewels/MultiQC | multiqc/modules/picard/ValidateSamFile.py | https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/picard/ValidateSamFile.py#L318-L352 | def _generate_detailed_table(data):
"""
Generates and retuns the HTML table that overviews the details found.
"""
headers = _get_general_stats_headers()
# Only add headers for errors/warnings we have found
for problems in data.values():
for problem in problems:
if proble... | [
"def",
"_generate_detailed_table",
"(",
"data",
")",
":",
"headers",
"=",
"_get_general_stats_headers",
"(",
")",
"# Only add headers for errors/warnings we have found",
"for",
"problems",
"in",
"data",
".",
"values",
"(",
")",
":",
"for",
"problem",
"in",
"problems",... | Generates and retuns the HTML table that overviews the details found. | [
"Generates",
"and",
"retuns",
"the",
"HTML",
"table",
"that",
"overviews",
"the",
"details",
"found",
"."
] | python | train |
ReFirmLabs/binwalk | src/binwalk/core/magic.py | https://github.com/ReFirmLabs/binwalk/blob/a0c5315fd2bae167e5c3d8469ce95d5defc743c2/src/binwalk/core/magic.py#L548-L771 | def _analyze(self, signature, offset):
'''
Analyzes self.data for the specified signature data at the specified offset .
@signature - The signature to apply to the data.
@offset - The offset in self.data to apply the signature to.
Returns a dictionary of tags parsed from the... | [
"def",
"_analyze",
"(",
"self",
",",
"signature",
",",
"offset",
")",
":",
"description",
"=",
"[",
"]",
"max_line_level",
"=",
"0",
"previous_line_end",
"=",
"0",
"tags",
"=",
"{",
"'id'",
":",
"signature",
".",
"id",
",",
"'offset'",
":",
"offset",
"... | Analyzes self.data for the specified signature data at the specified offset .
@signature - The signature to apply to the data.
@offset - The offset in self.data to apply the signature to.
Returns a dictionary of tags parsed from the data. | [
"Analyzes",
"self",
".",
"data",
"for",
"the",
"specified",
"signature",
"data",
"at",
"the",
"specified",
"offset",
"."
] | python | train |
log2timeline/plaso | plaso/cli/time_slices.py | https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/cli/time_slices.py#L43-L49 | def start_timestamp(self):
"""int: slice start timestamp or None."""
if self.event_timestamp:
return self.event_timestamp - (
self.duration * self._MICRO_SECONDS_PER_MINUTE)
return None | [
"def",
"start_timestamp",
"(",
"self",
")",
":",
"if",
"self",
".",
"event_timestamp",
":",
"return",
"self",
".",
"event_timestamp",
"-",
"(",
"self",
".",
"duration",
"*",
"self",
".",
"_MICRO_SECONDS_PER_MINUTE",
")",
"return",
"None"
] | int: slice start timestamp or None. | [
"int",
":",
"slice",
"start",
"timestamp",
"or",
"None",
"."
] | python | train |
pjuren/pyokit | src/pyokit/io/maf.py | https://github.com/pjuren/pyokit/blob/fddae123b5d817daa39496183f19c000d9c3791f/src/pyokit/io/maf.py#L195-L271 | def maf_iterator(fn, index_friendly=False,
yield_class=MultipleSequenceAlignment, yield_kw_args={},
verbose=False):
"""
Iterate of MAF format file and yield <yield_class> objects for each block.
MAF files are arranged in blocks. Each block is a multiple alignment. Within
a blo... | [
"def",
"maf_iterator",
"(",
"fn",
",",
"index_friendly",
"=",
"False",
",",
"yield_class",
"=",
"MultipleSequenceAlignment",
",",
"yield_kw_args",
"=",
"{",
"}",
",",
"verbose",
"=",
"False",
")",
":",
"try",
":",
"fh",
"=",
"open",
"(",
"fn",
")",
"exce... | Iterate of MAF format file and yield <yield_class> objects for each block.
MAF files are arranged in blocks. Each block is a multiple alignment. Within
a block, the first character of a line indicates what kind of line it is:
a -- key-value pair meta data for block; one per block, should be first line
s -- a ... | [
"Iterate",
"of",
"MAF",
"format",
"file",
"and",
"yield",
"<yield_class",
">",
"objects",
"for",
"each",
"block",
"."
] | python | train |
MycroftAI/padatious | padatious/intent_container.py | https://github.com/MycroftAI/padatious/blob/794a2530d6079bdd06e193edd0d30b2cc793e631/padatious/intent_container.py#L105-L118 | def load_entity(self, name, file_name, reload_cache=False):
"""
Loads an entity, optionally checking the cache first
Args:
name (str): The associated name of the entity
file_name (str): The location of the entity file
reload_cache (bool): Whether to refresh all of... | [
"def",
"load_entity",
"(",
"self",
",",
"name",
",",
"file_name",
",",
"reload_cache",
"=",
"False",
")",
":",
"Entity",
".",
"verify_name",
"(",
"name",
")",
"self",
".",
"entities",
".",
"load",
"(",
"Entity",
".",
"wrap_name",
"(",
"name",
")",
",",... | Loads an entity, optionally checking the cache first
Args:
name (str): The associated name of the entity
file_name (str): The location of the entity file
reload_cache (bool): Whether to refresh all of cache | [
"Loads",
"an",
"entity",
"optionally",
"checking",
"the",
"cache",
"first"
] | python | valid |
google/grr | grr/server/grr_response_server/notification.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/notification.py#L16-L33 | def _HostPrefix(client_id):
"""Build a host prefix for a notification message based on a client id."""
if not client_id:
return ""
hostname = None
if data_store.RelationalDBEnabled():
client_snapshot = data_store.REL_DB.ReadClientSnapshot(client_id)
if client_snapshot:
hostname = client_snaps... | [
"def",
"_HostPrefix",
"(",
"client_id",
")",
":",
"if",
"not",
"client_id",
":",
"return",
"\"\"",
"hostname",
"=",
"None",
"if",
"data_store",
".",
"RelationalDBEnabled",
"(",
")",
":",
"client_snapshot",
"=",
"data_store",
".",
"REL_DB",
".",
"ReadClientSnap... | Build a host prefix for a notification message based on a client id. | [
"Build",
"a",
"host",
"prefix",
"for",
"a",
"notification",
"message",
"based",
"on",
"a",
"client",
"id",
"."
] | python | train |
mathandy/svgpathtools | svgpathtools/misctools.py | https://github.com/mathandy/svgpathtools/blob/fd7348a1dfd88b65ea61da02325c6605aedf8c4f/svgpathtools/misctools.py#L37-L39 | def isclose(a, b, rtol=1e-5, atol=1e-8):
"""This is essentially np.isclose, but slightly faster."""
return abs(a - b) < (atol + rtol * abs(b)) | [
"def",
"isclose",
"(",
"a",
",",
"b",
",",
"rtol",
"=",
"1e-5",
",",
"atol",
"=",
"1e-8",
")",
":",
"return",
"abs",
"(",
"a",
"-",
"b",
")",
"<",
"(",
"atol",
"+",
"rtol",
"*",
"abs",
"(",
"b",
")",
")"
] | This is essentially np.isclose, but slightly faster. | [
"This",
"is",
"essentially",
"np",
".",
"isclose",
"but",
"slightly",
"faster",
"."
] | python | train |
rigetti/grove | grove/tomography/operator_utils.py | https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/tomography/operator_utils.py#L70-L94 | def make_diagonal_povm(pi_basis, confusion_rate_matrix):
"""
Create a DiagonalPOVM from a ``pi_basis`` and the ``confusion_rate_matrix`` associated with a
readout.
See also the grove documentation.
:param OperatorBasis pi_basis: An operator basis of rank-1 projection operators.
:param numpy.nd... | [
"def",
"make_diagonal_povm",
"(",
"pi_basis",
",",
"confusion_rate_matrix",
")",
":",
"confusion_rate_matrix",
"=",
"np",
".",
"asarray",
"(",
"confusion_rate_matrix",
")",
"if",
"not",
"np",
".",
"allclose",
"(",
"confusion_rate_matrix",
".",
"sum",
"(",
"axis",
... | Create a DiagonalPOVM from a ``pi_basis`` and the ``confusion_rate_matrix`` associated with a
readout.
See also the grove documentation.
:param OperatorBasis pi_basis: An operator basis of rank-1 projection operators.
:param numpy.ndarray confusion_rate_matrix: The matrix of detection probabilities co... | [
"Create",
"a",
"DiagonalPOVM",
"from",
"a",
"pi_basis",
"and",
"the",
"confusion_rate_matrix",
"associated",
"with",
"a",
"readout",
"."
] | python | train |
fronzbot/blinkpy | blinkpy/api.py | https://github.com/fronzbot/blinkpy/blob/bfdc1e47bdd84903f1aca653605846f3c99bcfac/blinkpy/api.py#L56-L64 | def request_syncmodule(blink, network):
"""
Request sync module info.
:param blink: Blink instance.
:param network: Sync module network id.
"""
url = "{}/network/{}/syncmodules".format(blink.urls.base_url, network)
return http_get(blink, url) | [
"def",
"request_syncmodule",
"(",
"blink",
",",
"network",
")",
":",
"url",
"=",
"\"{}/network/{}/syncmodules\"",
".",
"format",
"(",
"blink",
".",
"urls",
".",
"base_url",
",",
"network",
")",
"return",
"http_get",
"(",
"blink",
",",
"url",
")"
] | Request sync module info.
:param blink: Blink instance.
:param network: Sync module network id. | [
"Request",
"sync",
"module",
"info",
"."
] | python | train |
KelSolaar/Foundations | foundations/strings.py | https://github.com/KelSolaar/Foundations/blob/5c141330faf09dad70a12bc321f4c564917d0a91/foundations/strings.py#L175-L192 | def get_words(data):
"""
Extracts the words from given string.
Usage::
>>> get_words("Users are: John Doe, Jane Doe, Z6PO.")
[u'Users', u'are', u'John', u'Doe', u'Jane', u'Doe', u'Z6PO']
:param data: Data to extract words from.
:type data: unicode
:return: Words.
:rtype: l... | [
"def",
"get_words",
"(",
"data",
")",
":",
"words",
"=",
"re",
".",
"findall",
"(",
"r\"\\w+\"",
",",
"data",
")",
"LOGGER",
".",
"debug",
"(",
"\"> Words: '{0}'\"",
".",
"format",
"(",
"\", \"",
".",
"join",
"(",
"words",
")",
")",
")",
"return",
"w... | Extracts the words from given string.
Usage::
>>> get_words("Users are: John Doe, Jane Doe, Z6PO.")
[u'Users', u'are', u'John', u'Doe', u'Jane', u'Doe', u'Z6PO']
:param data: Data to extract words from.
:type data: unicode
:return: Words.
:rtype: list | [
"Extracts",
"the",
"words",
"from",
"given",
"string",
"."
] | python | train |
DLR-RM/RAFCON | source/rafcon/core/execution/execution_engine.py | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/execution/execution_engine.py#L451-L474 | def _modify_run_to_states(self, state):
"""
This is a special case. Inside a hierarchy state a step_over is triggered and affects the last child.
In this case the self.run_to_states has to be modified in order to contain the parent of the hierarchy state.
Otherwise the execution won't re... | [
"def",
"_modify_run_to_states",
"(",
"self",
",",
"state",
")",
":",
"if",
"self",
".",
"_status",
".",
"execution_mode",
"is",
"StateMachineExecutionStatus",
".",
"FORWARD_OVER",
"or",
"self",
".",
"_status",
".",
"execution_mode",
"is",
"StateMachineExecutionStatu... | This is a special case. Inside a hierarchy state a step_over is triggered and affects the last child.
In this case the self.run_to_states has to be modified in order to contain the parent of the hierarchy state.
Otherwise the execution won't respect the step_over any more and run until the end of the st... | [
"This",
"is",
"a",
"special",
"case",
".",
"Inside",
"a",
"hierarchy",
"state",
"a",
"step_over",
"is",
"triggered",
"and",
"affects",
"the",
"last",
"child",
".",
"In",
"this",
"case",
"the",
"self",
".",
"run_to_states",
"has",
"to",
"be",
"modified",
... | python | train |
saltstack/salt | salt/modules/bigip.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bigip.py#L472-L549 | def modify_node(hostname, username, password, name,
connection_limit=None,
description=None,
dynamic_ratio=None,
logging=None,
monitor=None,
rate_limit=None,
ratio=None,
session=None,
... | [
"def",
"modify_node",
"(",
"hostname",
",",
"username",
",",
"password",
",",
"name",
",",
"connection_limit",
"=",
"None",
",",
"description",
"=",
"None",
",",
"dynamic_ratio",
"=",
"None",
",",
"logging",
"=",
"None",
",",
"monitor",
"=",
"None",
",",
... | A function to connect to a bigip device and modify an existing node.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node to modify
connection_limit
[integer]
descr... | [
"A",
"function",
"to",
"connect",
"to",
"a",
"bigip",
"device",
"and",
"modify",
"an",
"existing",
"node",
"."
] | python | train |
ggravlingen/pytradfri | pytradfri/api/aiocoap_api.py | https://github.com/ggravlingen/pytradfri/blob/63750fa8fb27158c013d24865cdaa7fb82b3ab53/pytradfri/api/aiocoap_api.py#L152-L161 | async def request(self, api_commands):
"""Make a request."""
if not isinstance(api_commands, list):
result = await self._execute(api_commands)
return result
commands = (self._execute(api_command) for api_command in api_commands)
command_results = await asyncio.ga... | [
"async",
"def",
"request",
"(",
"self",
",",
"api_commands",
")",
":",
"if",
"not",
"isinstance",
"(",
"api_commands",
",",
"list",
")",
":",
"result",
"=",
"await",
"self",
".",
"_execute",
"(",
"api_commands",
")",
"return",
"result",
"commands",
"=",
... | Make a request. | [
"Make",
"a",
"request",
"."
] | python | train |
JukeboxPipeline/jukebox-core | src/jukeboxcore/addons/guerilla/guerillamgmt.py | https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/addons/guerilla/guerillamgmt.py#L150-L165 | def create_seq(self, ):
"""Create a sequence and store it in the self.sequence
:returns: None
:rtype: None
:raises: None
"""
name = self.name_le.text()
desc = self.desc_pte.toPlainText()
try:
seq = djadapter.models.Sequence(name=name, project=... | [
"def",
"create_seq",
"(",
"self",
",",
")",
":",
"name",
"=",
"self",
".",
"name_le",
".",
"text",
"(",
")",
"desc",
"=",
"self",
".",
"desc_pte",
".",
"toPlainText",
"(",
")",
"try",
":",
"seq",
"=",
"djadapter",
".",
"models",
".",
"Sequence",
"(... | Create a sequence and store it in the self.sequence
:returns: None
:rtype: None
:raises: None | [
"Create",
"a",
"sequence",
"and",
"store",
"it",
"in",
"the",
"self",
".",
"sequence"
] | python | train |
datadesk/django-greeking | greeking/templatetags/greeking_tags.py | https://github.com/datadesk/django-greeking/blob/72509c94952279503bbe8d5a710c1fd344da0670/greeking/templatetags/greeking_tags.py#L111-L147 | def placeholdit(
width,
height,
background_color="cccccc",
text_color="969696",
text=None,
random_background_color=False
):
"""
Creates a placeholder image using placehold.it
Usage format:
{% placeholdit [width] [height] [background_color] [text_color] [text] %}
Example ... | [
"def",
"placeholdit",
"(",
"width",
",",
"height",
",",
"background_color",
"=",
"\"cccccc\"",
",",
"text_color",
"=",
"\"969696\"",
",",
"text",
"=",
"None",
",",
"random_background_color",
"=",
"False",
")",
":",
"url",
"=",
"get_placeholdit_url",
"(",
"widt... | Creates a placeholder image using placehold.it
Usage format:
{% placeholdit [width] [height] [background_color] [text_color] [text] %}
Example usage:
Default image at 250 square
{% placeholdit 250 %}
100 wide and 200 high
{% placeholdit 100 200 %}
Custom backg... | [
"Creates",
"a",
"placeholder",
"image",
"using",
"placehold",
".",
"it"
] | python | train |
Gorialis/jishaku | jishaku/cog.py | https://github.com/Gorialis/jishaku/blob/fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e/jishaku/cog.py#L480-L502 | async def jsk_source(self, ctx: commands.Context, *, command_name: str):
"""
Displays the source code for a command.
"""
command = self.bot.get_command(command_name)
if not command:
return await ctx.send(f"Couldn't find command `{command_name}`.")
try:
... | [
"async",
"def",
"jsk_source",
"(",
"self",
",",
"ctx",
":",
"commands",
".",
"Context",
",",
"*",
",",
"command_name",
":",
"str",
")",
":",
"command",
"=",
"self",
".",
"bot",
".",
"get_command",
"(",
"command_name",
")",
"if",
"not",
"command",
":",
... | Displays the source code for a command. | [
"Displays",
"the",
"source",
"code",
"for",
"a",
"command",
"."
] | python | train |
marrabld/planarradpy | libplanarradpy/planrad.py | https://github.com/marrabld/planarradpy/blob/5095d1cb98d4f67a7c3108c9282f2d59253e89a8/libplanarradpy/planrad.py#L486-L494 | def build_b(self, scattering_fraction=0.01833):
"""Calculates the total scattering from back-scattering
:param scattering_fraction: the fraction of back-scattering to total scattering default = 0.01833
b = ( bb[sea water] + bb[p] ) /0.01833
"""
lg.info('Building b with scatteri... | [
"def",
"build_b",
"(",
"self",
",",
"scattering_fraction",
"=",
"0.01833",
")",
":",
"lg",
".",
"info",
"(",
"'Building b with scattering fraction of :: '",
"+",
"str",
"(",
"scattering_fraction",
")",
")",
"self",
".",
"b",
"=",
"(",
"self",
".",
"b_b",
"+"... | Calculates the total scattering from back-scattering
:param scattering_fraction: the fraction of back-scattering to total scattering default = 0.01833
b = ( bb[sea water] + bb[p] ) /0.01833 | [
"Calculates",
"the",
"total",
"scattering",
"from",
"back",
"-",
"scattering"
] | python | test |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.