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 |
|---|---|---|---|---|---|---|---|---|
spyder-ide/spyder | spyder/plugins/variableexplorer/widgets/dataframeeditor.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/dataframeeditor.py#L714-L740 | def data(self, index, role):
"""
Get the data for the header.
This is used when a header has levels.
"""
if not index.isValid() or \
index.row() >= self._shape[0] or \
index.column() >= self._shape[1]:
return None
row, col = ((... | [
"def",
"data",
"(",
"self",
",",
"index",
",",
"role",
")",
":",
"if",
"not",
"index",
".",
"isValid",
"(",
")",
"or",
"index",
".",
"row",
"(",
")",
">=",
"self",
".",
"_shape",
"[",
"0",
"]",
"or",
"index",
".",
"column",
"(",
")",
">=",
"s... | Get the data for the header.
This is used when a header has levels. | [
"Get",
"the",
"data",
"for",
"the",
"header",
".",
"This",
"is",
"used",
"when",
"a",
"header",
"has",
"levels",
"."
] | python | train |
OCHA-DAP/hdx-python-country | src/hdx/location/country.py | https://github.com/OCHA-DAP/hdx-python-country/blob/e86a0b5f182a5d010c4cd7faa36a213cfbcc01f6/src/hdx/location/country.py#L226-L245 | def get_iso2_from_iso3(cls, iso3, use_live=True, exception=None):
# type: (str, bool, Optional[ExceptionUpperBound]) -> Optional[str]
"""Get ISO2 from ISO3 code
Args:
iso3 (str): ISO3 code for which to get ISO2 code
use_live (bool): Try to get use latest data from web ra... | [
"def",
"get_iso2_from_iso3",
"(",
"cls",
",",
"iso3",
",",
"use_live",
"=",
"True",
",",
"exception",
"=",
"None",
")",
":",
"# type: (str, bool, Optional[ExceptionUpperBound]) -> Optional[str]",
"countriesdata",
"=",
"cls",
".",
"countriesdata",
"(",
"use_live",
"=",... | Get ISO2 from ISO3 code
Args:
iso3 (str): ISO3 code for which to get ISO2 code
use_live (bool): Try to get use latest data from web rather than file in package. Defaults to True.
exception (Optional[ExceptionUpperBound]): An exception to raise if country not found. Defaults ... | [
"Get",
"ISO2",
"from",
"ISO3",
"code"
] | python | train |
Gandi/gandi.cli | gandi/cli/core/base.py | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/core/base.py#L275-L304 | def update_progress(cls, progress, starttime):
""" Display an ascii progress bar while processing operation. """
width, _height = click.get_terminal_size()
if not width:
return
duration = datetime.utcnow() - starttime
hours, remainder = divmod(duration.seconds, 3600)... | [
"def",
"update_progress",
"(",
"cls",
",",
"progress",
",",
"starttime",
")",
":",
"width",
",",
"_height",
"=",
"click",
".",
"get_terminal_size",
"(",
")",
"if",
"not",
"width",
":",
"return",
"duration",
"=",
"datetime",
".",
"utcnow",
"(",
")",
"-",
... | Display an ascii progress bar while processing operation. | [
"Display",
"an",
"ascii",
"progress",
"bar",
"while",
"processing",
"operation",
"."
] | python | train |
hbldh/dlxsudoku | dlxsudoku/sudoku.py | https://github.com/hbldh/dlxsudoku/blob/8d774e0883eb615533d04f07e58a95db716226e0/dlxsudoku/sudoku.py#L301-L353 | def _fill_hidden_singles(self):
"""Look for hidden singles, i.e. cells with only one unique possible value in row, column or box.
:return: If any Hidden Single has been found.
:rtype: bool
"""
for i in utils.range_(self.side):
box_i = (i // self.order) * self.order
... | [
"def",
"_fill_hidden_singles",
"(",
"self",
")",
":",
"for",
"i",
"in",
"utils",
".",
"range_",
"(",
"self",
".",
"side",
")",
":",
"box_i",
"=",
"(",
"i",
"//",
"self",
".",
"order",
")",
"*",
"self",
".",
"order",
"for",
"j",
"in",
"utils",
"."... | Look for hidden singles, i.e. cells with only one unique possible value in row, column or box.
:return: If any Hidden Single has been found.
:rtype: bool | [
"Look",
"for",
"hidden",
"singles",
"i",
".",
"e",
".",
"cells",
"with",
"only",
"one",
"unique",
"possible",
"value",
"in",
"row",
"column",
"or",
"box",
"."
] | python | train |
spyder-ide/spyder | spyder/plugins/projects/projecttypes/python.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/projects/projecttypes/python.py#L29-L32 | def _set_relative_pythonpath(self, value):
"""Set PYTHONPATH list relative paths"""
self.pythonpath = [osp.abspath(osp.join(self.root_path, path))
for path in value] | [
"def",
"_set_relative_pythonpath",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"pythonpath",
"=",
"[",
"osp",
".",
"abspath",
"(",
"osp",
".",
"join",
"(",
"self",
".",
"root_path",
",",
"path",
")",
")",
"for",
"path",
"in",
"value",
"]"
] | Set PYTHONPATH list relative paths | [
"Set",
"PYTHONPATH",
"list",
"relative",
"paths"
] | python | train |
hearsaycorp/normalize | normalize/visitor.py | https://github.com/hearsaycorp/normalize/blob/8b36522ddca6d41b434580bd848f3bdaa7a999c8/normalize/visitor.py#L469-L478 | def produce(cls, mapped_props, aggregated, value_type, visitor):
"""Like :py:meth:`normalize.visitor.VisitorPattern.reduce`, but
constructs instances rather than returning plain dicts.
"""
kwargs = {} if not mapped_props else dict(
(k.name, v) for k, v in mapped_props
... | [
"def",
"produce",
"(",
"cls",
",",
"mapped_props",
",",
"aggregated",
",",
"value_type",
",",
"visitor",
")",
":",
"kwargs",
"=",
"{",
"}",
"if",
"not",
"mapped_props",
"else",
"dict",
"(",
"(",
"k",
".",
"name",
",",
"v",
")",
"for",
"k",
",",
"v"... | Like :py:meth:`normalize.visitor.VisitorPattern.reduce`, but
constructs instances rather than returning plain dicts. | [
"Like",
":",
"py",
":",
"meth",
":",
"normalize",
".",
"visitor",
".",
"VisitorPattern",
".",
"reduce",
"but",
"constructs",
"instances",
"rather",
"than",
"returning",
"plain",
"dicts",
"."
] | python | train |
corydodt/Crosscap | crosscap/openapi.py | https://github.com/corydodt/Crosscap/blob/388a2ec36b8aa85e8f1ed692bb6e43474ba76c8e/crosscap/openapi.py#L141-L151 | def representCleanOpenAPIOperation(dumper, data):
"""
Unpack nonstandard attributes while representing an OpenAPIOperation
"""
dct = _orderedCleanDict(data)
if '_extended' in dct:
for k, ext in list(data._extended.items()):
dct[k] = ext
del dct['_extended']
return du... | [
"def",
"representCleanOpenAPIOperation",
"(",
"dumper",
",",
"data",
")",
":",
"dct",
"=",
"_orderedCleanDict",
"(",
"data",
")",
"if",
"'_extended'",
"in",
"dct",
":",
"for",
"k",
",",
"ext",
"in",
"list",
"(",
"data",
".",
"_extended",
".",
"items",
"(... | Unpack nonstandard attributes while representing an OpenAPIOperation | [
"Unpack",
"nonstandard",
"attributes",
"while",
"representing",
"an",
"OpenAPIOperation"
] | python | train |
googleapis/google-cloud-python | bigquery/google/cloud/bigquery/model.py | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/model.py#L126-L137 | def created(self):
"""Union[datetime.datetime, None]: Datetime at which the model was
created (:data:`None` until set from the server).
Read-only.
"""
value = self._proto.creation_time
if value is not None and value != 0:
# value will be in milliseconds.
... | [
"def",
"created",
"(",
"self",
")",
":",
"value",
"=",
"self",
".",
"_proto",
".",
"creation_time",
"if",
"value",
"is",
"not",
"None",
"and",
"value",
"!=",
"0",
":",
"# value will be in milliseconds.",
"return",
"google",
".",
"cloud",
".",
"_helpers",
"... | Union[datetime.datetime, None]: Datetime at which the model was
created (:data:`None` until set from the server).
Read-only. | [
"Union",
"[",
"datetime",
".",
"datetime",
"None",
"]",
":",
"Datetime",
"at",
"which",
"the",
"model",
"was",
"created",
"(",
":",
"data",
":",
"None",
"until",
"set",
"from",
"the",
"server",
")",
"."
] | python | train |
devassistant/devassistant | devassistant/lang.py | https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/lang.py#L260-L283 | def parse_for(control_line):
"""Returns name of loop control variable(s), iteration type (in/word_in) and
expression to iterate on.
For example:
- given "for $i in $foo", returns (['i'], '$foo')
- given "for ${i} in $(ls $foo)", returns (['i'], '$(ls $foo)')
- given "for $k, $v in $foo", return... | [
"def",
"parse_for",
"(",
"control_line",
")",
":",
"error",
"=",
"'For loop call must be in form \\'for $var in expression\\', got: '",
"+",
"control_line",
"regex",
"=",
"re",
".",
"compile",
"(",
"r'for\\s+(\\${?\\S+}?)(?:\\s*,\\s+(\\${?\\S+}?))?\\s+(in|word_in)\\s+(\\S.+)'",
"... | Returns name of loop control variable(s), iteration type (in/word_in) and
expression to iterate on.
For example:
- given "for $i in $foo", returns (['i'], '$foo')
- given "for ${i} in $(ls $foo)", returns (['i'], '$(ls $foo)')
- given "for $k, $v in $foo", returns (['k', 'v'], '$foo') | [
"Returns",
"name",
"of",
"loop",
"control",
"variable",
"(",
"s",
")",
"iteration",
"type",
"(",
"in",
"/",
"word_in",
")",
"and",
"expression",
"to",
"iterate",
"on",
"."
] | python | train |
libfuse/python-fuse | fuseparts/subbedopts.py | https://github.com/libfuse/python-fuse/blob/2c088b657ad71faca6975b456f80b7d2c2cea2a7/fuseparts/subbedopts.py#L78-L96 | def add(self, opt, val=None):
"""Add a suboption."""
ov = opt.split('=', 1)
o = ov[0]
v = len(ov) > 1 and ov[1] or None
if (v):
if val != None:
raise AttributeError("ambiguous option value")
val = v
if val == False:
r... | [
"def",
"add",
"(",
"self",
",",
"opt",
",",
"val",
"=",
"None",
")",
":",
"ov",
"=",
"opt",
".",
"split",
"(",
"'='",
",",
"1",
")",
"o",
"=",
"ov",
"[",
"0",
"]",
"v",
"=",
"len",
"(",
"ov",
")",
">",
"1",
"and",
"ov",
"[",
"1",
"]",
... | Add a suboption. | [
"Add",
"a",
"suboption",
"."
] | python | train |
prompt-toolkit/pymux | pymux/commands/commands.py | https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/commands/commands.py#L658-L663 | def show_buffer(pymux, variables):
"""
Display the clipboard content.
"""
text = get_app().clipboard.get_data().text
pymux.get_client_state().layout_manager.display_popup('show-buffer', text) | [
"def",
"show_buffer",
"(",
"pymux",
",",
"variables",
")",
":",
"text",
"=",
"get_app",
"(",
")",
".",
"clipboard",
".",
"get_data",
"(",
")",
".",
"text",
"pymux",
".",
"get_client_state",
"(",
")",
".",
"layout_manager",
".",
"display_popup",
"(",
"'sh... | Display the clipboard content. | [
"Display",
"the",
"clipboard",
"content",
"."
] | python | train |
kajala/django-jutil | jutil/cache.py | https://github.com/kajala/django-jutil/blob/2abd93ebad51042744eaeb1ee1074ed0eb55ad0c/jutil/cache.py#L40-L46 | def update_cached_fields_pre_save(self, update_fields: list):
"""
Call on pre_save signal for objects (to automatically refresh on save).
:param update_fields: list of fields to update
"""
if self.id and update_fields is None:
self.update_cached_fields(commit=False, e... | [
"def",
"update_cached_fields_pre_save",
"(",
"self",
",",
"update_fields",
":",
"list",
")",
":",
"if",
"self",
".",
"id",
"and",
"update_fields",
"is",
"None",
":",
"self",
".",
"update_cached_fields",
"(",
"commit",
"=",
"False",
",",
"exceptions",
"=",
"F... | Call on pre_save signal for objects (to automatically refresh on save).
:param update_fields: list of fields to update | [
"Call",
"on",
"pre_save",
"signal",
"for",
"objects",
"(",
"to",
"automatically",
"refresh",
"on",
"save",
")",
".",
":",
"param",
"update_fields",
":",
"list",
"of",
"fields",
"to",
"update"
] | python | train |
miyakogi/wdom | wdom/element.py | https://github.com/miyakogi/wdom/blob/a21bcd23e94baceee71161829f6897bee3fd39c1/wdom/element.py#L175-L186 | def html(self) -> str:
"""Return string representation of this.
Used in start tag of HTML representation of the Element node.
"""
if self._owner and self.name in self._owner._special_attr_boolean:
return self.name
else:
value = self.value
if i... | [
"def",
"html",
"(",
"self",
")",
"->",
"str",
":",
"if",
"self",
".",
"_owner",
"and",
"self",
".",
"name",
"in",
"self",
".",
"_owner",
".",
"_special_attr_boolean",
":",
"return",
"self",
".",
"name",
"else",
":",
"value",
"=",
"self",
".",
"value"... | Return string representation of this.
Used in start tag of HTML representation of the Element node. | [
"Return",
"string",
"representation",
"of",
"this",
"."
] | python | train |
briancappello/flask-unchained | flask_unchained/clips_pattern.py | https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/clips_pattern.py#L344-L391 | def pluralize(word, pos=NOUN, custom=None, classical=True):
""" Returns the plural of a given word, e.g., child => children.
Handles nouns and adjectives, using classical inflection by default
(i.e., where "matrix" pluralizes to "matrices" and not "matrixes").
The custom dictionary is for us... | [
"def",
"pluralize",
"(",
"word",
",",
"pos",
"=",
"NOUN",
",",
"custom",
"=",
"None",
",",
"classical",
"=",
"True",
")",
":",
"if",
"custom",
"and",
"word",
"in",
"custom",
":",
"return",
"custom",
"[",
"word",
"]",
"# Recurse genitives.",
"# Remove the... | Returns the plural of a given word, e.g., child => children.
Handles nouns and adjectives, using classical inflection by default
(i.e., where "matrix" pluralizes to "matrices" and not "matrixes").
The custom dictionary is for user-defined replacements. | [
"Returns",
"the",
"plural",
"of",
"a",
"given",
"word",
"e",
".",
"g",
".",
"child",
"=",
">",
"children",
".",
"Handles",
"nouns",
"and",
"adjectives",
"using",
"classical",
"inflection",
"by",
"default",
"(",
"i",
".",
"e",
".",
"where",
"matrix",
"p... | python | train |
spacetelescope/drizzlepac | drizzlepac/imgclasses.py | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/imgclasses.py#L340-L368 | def buildSkyCatalog(self):
""" Convert sky catalog for all chips into a single catalog for
the entire field-of-view of this image.
"""
self.all_radec = None
self.all_radec_orig = None
ralist = []
declist = []
fluxlist = []
idlist = []
f... | [
"def",
"buildSkyCatalog",
"(",
"self",
")",
":",
"self",
".",
"all_radec",
"=",
"None",
"self",
".",
"all_radec_orig",
"=",
"None",
"ralist",
"=",
"[",
"]",
"declist",
"=",
"[",
"]",
"fluxlist",
"=",
"[",
"]",
"idlist",
"=",
"[",
"]",
"for",
"scichip... | Convert sky catalog for all chips into a single catalog for
the entire field-of-view of this image. | [
"Convert",
"sky",
"catalog",
"for",
"all",
"chips",
"into",
"a",
"single",
"catalog",
"for",
"the",
"entire",
"field",
"-",
"of",
"-",
"view",
"of",
"this",
"image",
"."
] | python | train |
kejbaly2/metrique | metrique/cubes/sqldata/generic.py | https://github.com/kejbaly2/metrique/blob/a10b076097441b7dde687949139f702f5c1e1b35/metrique/cubes/sqldata/generic.py#L228-L253 | def get_changed_oids(self, last_update=None):
'''
Returns a list of object ids of those objects that have changed since
`mtime`. This method expects that the changed objects can be
determined based on the `delta_mtime` property of the cube which
specifies the field name that carr... | [
"def",
"get_changed_oids",
"(",
"self",
",",
"last_update",
"=",
"None",
")",
":",
"mtime_columns",
"=",
"self",
".",
"lconfig",
".",
"get",
"(",
"'delta_mtime'",
",",
"[",
"]",
")",
"if",
"not",
"(",
"mtime_columns",
"and",
"last_update",
")",
":",
"ret... | Returns a list of object ids of those objects that have changed since
`mtime`. This method expects that the changed objects can be
determined based on the `delta_mtime` property of the cube which
specifies the field name that carries the time of the last change.
This method is expected ... | [
"Returns",
"a",
"list",
"of",
"object",
"ids",
"of",
"those",
"objects",
"that",
"have",
"changed",
"since",
"mtime",
".",
"This",
"method",
"expects",
"that",
"the",
"changed",
"objects",
"can",
"be",
"determined",
"based",
"on",
"the",
"delta_mtime",
"prop... | python | train |
xtrementl/focus | focus/parser/lexer.py | https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/parser/lexer.py#L174-L197 | def _tokenize(self, stream):
""" Tokenizes data from the provided string.
``stream``
``File``-like object.
"""
self._tokens = []
self._reset_token()
self._state = self.ST_TOKEN
for chunk in iter(lambda: stream.read(8192), ''):
... | [
"def",
"_tokenize",
"(",
"self",
",",
"stream",
")",
":",
"self",
".",
"_tokens",
"=",
"[",
"]",
"self",
".",
"_reset_token",
"(",
")",
"self",
".",
"_state",
"=",
"self",
".",
"ST_TOKEN",
"for",
"chunk",
"in",
"iter",
"(",
"lambda",
":",
"stream",
... | Tokenizes data from the provided string.
``stream``
``File``-like object. | [
"Tokenizes",
"data",
"from",
"the",
"provided",
"string",
"."
] | python | train |
canonical-ols/acceptable | acceptable/lint.py | https://github.com/canonical-ols/acceptable/blob/6ccbe969078166a5315d857da38b59b43b29fadc/acceptable/lint.py#L72-L95 | def metadata_lint(old, new, locations):
"""Run the linter over the new metadata, comparing to the old."""
# ensure we don't modify the metadata
old = old.copy()
new = new.copy()
# remove version info
old.pop('$version', None)
new.pop('$version', None)
for old_group_name in old:
... | [
"def",
"metadata_lint",
"(",
"old",
",",
"new",
",",
"locations",
")",
":",
"# ensure we don't modify the metadata",
"old",
"=",
"old",
".",
"copy",
"(",
")",
"new",
"=",
"new",
".",
"copy",
"(",
")",
"# remove version info",
"old",
".",
"pop",
"(",
"'$ver... | Run the linter over the new metadata, comparing to the old. | [
"Run",
"the",
"linter",
"over",
"the",
"new",
"metadata",
"comparing",
"to",
"the",
"old",
"."
] | python | train |
rmed/flask-waffleconf | flask_waffleconf/core.py | https://github.com/rmed/flask-waffleconf/blob/a75ed69101796c9f3f42eff9f91e91dc6dd13869/flask_waffleconf/core.py#L104-L144 | def update_db(self, new_values):
"""Update database values and application configuration.
The provided keys must be defined in the ``WAFFLE_CONFS`` setting.
Arguments:
new_values (dict): dict of configuration variables and their values
The dict has the following str... | [
"def",
"update_db",
"(",
"self",
",",
"new_values",
")",
":",
"confs",
"=",
"self",
".",
"app",
".",
"config",
".",
"get",
"(",
"'WAFFLE_CONFS'",
",",
"{",
"}",
")",
"to_update",
"=",
"{",
"}",
"for",
"key",
"in",
"new_values",
".",
"keys",
"(",
")... | Update database values and application configuration.
The provided keys must be defined in the ``WAFFLE_CONFS`` setting.
Arguments:
new_values (dict): dict of configuration variables and their values
The dict has the following structure:
{
... | [
"Update",
"database",
"values",
"and",
"application",
"configuration",
"."
] | python | train |
materialsproject/pymatgen | pymatgen/analysis/structure_matcher.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/analysis/structure_matcher.py#L1033-L1074 | def get_s2_like_s1(self, struct1, struct2, include_ignored_species=True):
"""
Performs transformations on struct2 to put it in a basis similar to
struct1 (without changing any of the inter-site distances)
Args:
struct1 (Structure): Reference structure
struct2 (St... | [
"def",
"get_s2_like_s1",
"(",
"self",
",",
"struct1",
",",
"struct2",
",",
"include_ignored_species",
"=",
"True",
")",
":",
"s1",
",",
"s2",
"=",
"self",
".",
"_process_species",
"(",
"[",
"struct1",
",",
"struct2",
"]",
")",
"trans",
"=",
"self",
".",
... | Performs transformations on struct2 to put it in a basis similar to
struct1 (without changing any of the inter-site distances)
Args:
struct1 (Structure): Reference structure
struct2 (Structure): Structure to transform.
include_ignored_species (bool): Defaults to True... | [
"Performs",
"transformations",
"on",
"struct2",
"to",
"put",
"it",
"in",
"a",
"basis",
"similar",
"to",
"struct1",
"(",
"without",
"changing",
"any",
"of",
"the",
"inter",
"-",
"site",
"distances",
")"
] | python | train |
tanghaibao/jcvi | jcvi/assembly/goldenpath.py | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/goldenpath.py#L1103-L1138 | def agp(args):
"""
%prog agp tpffile certificatefile agpfile
Build agpfile from overlap certificates.
Tiling Path File (tpf) is a file that lists the component and the gaps.
It is a three-column file similar to below, also see jcvi.formats.agp.tpf():
telomere chr1 na
AC229737.8 ... | [
"def",
"agp",
"(",
"args",
")",
":",
"from",
"jcvi",
".",
"formats",
".",
"base",
"import",
"DictFile",
"p",
"=",
"OptionParser",
"(",
"agp",
".",
"__doc__",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"if",
"len",
"(",... | %prog agp tpffile certificatefile agpfile
Build agpfile from overlap certificates.
Tiling Path File (tpf) is a file that lists the component and the gaps.
It is a three-column file similar to below, also see jcvi.formats.agp.tpf():
telomere chr1 na
AC229737.8 chr1 +
AC202463.29... | [
"%prog",
"agp",
"tpffile",
"certificatefile",
"agpfile"
] | python | train |
controversial/livejson | livejson.py | https://github.com/controversial/livejson/blob/91021de60903d2d8b2cfb7d8d8910bcf27ec003b/livejson.py#L214-L233 | def data(self, data):
"""Overwrite the file with new data. You probably shouldn't do
this yourself, it's easy to screw up your whole file with this."""
if self.is_caching:
self.cache = data
else:
fcontents = self.file_contents
with open(self.path, "w")... | [
"def",
"data",
"(",
"self",
",",
"data",
")",
":",
"if",
"self",
".",
"is_caching",
":",
"self",
".",
"cache",
"=",
"data",
"else",
":",
"fcontents",
"=",
"self",
".",
"file_contents",
"with",
"open",
"(",
"self",
".",
"path",
",",
"\"w\"",
")",
"a... | Overwrite the file with new data. You probably shouldn't do
this yourself, it's easy to screw up your whole file with this. | [
"Overwrite",
"the",
"file",
"with",
"new",
"data",
".",
"You",
"probably",
"shouldn",
"t",
"do",
"this",
"yourself",
"it",
"s",
"easy",
"to",
"screw",
"up",
"your",
"whole",
"file",
"with",
"this",
"."
] | python | valid |
mbj4668/pyang | pyang/statements.py | https://github.com/mbj4668/pyang/blob/f2a5cc3142162e5b9ee4e18d154568d939ff63dd/pyang/statements.py#L3107-L3139 | def mk_path_str(stmt,
with_prefixes=False,
prefix_onchange=False,
prefix_to_module=False,
resolve_top_prefix_to_module=False):
"""Returns the XPath path of the node.
with_prefixes indicates whether or not to prefix every node.
prefix_onchange ... | [
"def",
"mk_path_str",
"(",
"stmt",
",",
"with_prefixes",
"=",
"False",
",",
"prefix_onchange",
"=",
"False",
",",
"prefix_to_module",
"=",
"False",
",",
"resolve_top_prefix_to_module",
"=",
"False",
")",
":",
"resolved_names",
"=",
"mk_path_list",
"(",
"stmt",
"... | Returns the XPath path of the node.
with_prefixes indicates whether or not to prefix every node.
prefix_onchange modifies the behavior of with_prefixes and
only adds prefixes when the prefix changes mid-XPath.
prefix_to_module replaces prefixes with the module name of the prefix.
resolve_top_pr... | [
"Returns",
"the",
"XPath",
"path",
"of",
"the",
"node",
".",
"with_prefixes",
"indicates",
"whether",
"or",
"not",
"to",
"prefix",
"every",
"node",
"."
] | python | train |
fatihsucu/pyzomato | pyzomato/pyzomato.py | https://github.com/fatihsucu/pyzomato/blob/91c805bac8a49c808d497b7b0b6222a48f2d1324/pyzomato/pyzomato.py#L79-L97 | def getEstablishments(self, city_id, **kwargs):
"""
:param city_id: id of the city for which collections are needed
:param lat: latitude
:param lon: longitude
Get a list of restaurant types in a city. The location/City input can be provided in the following ways
- Using Z... | [
"def",
"getEstablishments",
"(",
"self",
",",
"city_id",
",",
"*",
"*",
"kwargs",
")",
":",
"params",
"=",
"{",
"\"city_id\"",
":",
"city_id",
"}",
"optional_params",
"=",
"[",
"\"lat\"",
",",
"\"lon\"",
"]",
"for",
"key",
"in",
"optional_params",
":",
"... | :param city_id: id of the city for which collections are needed
:param lat: latitude
:param lon: longitude
Get a list of restaurant types in a city. The location/City input can be provided in the following ways
- Using Zomato City ID
- Using coordinates of any location within a c... | [
":",
"param",
"city_id",
":",
"id",
"of",
"the",
"city",
"for",
"which",
"collections",
"are",
"needed",
":",
"param",
"lat",
":",
"latitude",
":",
"param",
"lon",
":",
"longitude",
"Get",
"a",
"list",
"of",
"restaurant",
"types",
"in",
"a",
"city",
".... | python | test |
andreikop/qutepart | qutepart/syntax/parser.py | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/syntax/parser.py#L468-L477 | def _matchPattern(regExp, string):
"""Try to match pattern.
Returns tuple (whole match, groups) or (None, None)
Python function, used by C code
"""
match = regExp.match(string)
if match is not None and match.group(0):
return match.group(0), (match.group(0), ) ... | [
"def",
"_matchPattern",
"(",
"regExp",
",",
"string",
")",
":",
"match",
"=",
"regExp",
".",
"match",
"(",
"string",
")",
"if",
"match",
"is",
"not",
"None",
"and",
"match",
".",
"group",
"(",
"0",
")",
":",
"return",
"match",
".",
"group",
"(",
"0... | Try to match pattern.
Returns tuple (whole match, groups) or (None, None)
Python function, used by C code | [
"Try",
"to",
"match",
"pattern",
".",
"Returns",
"tuple",
"(",
"whole",
"match",
"groups",
")",
"or",
"(",
"None",
"None",
")",
"Python",
"function",
"used",
"by",
"C",
"code"
] | python | train |
zhanglab/psamm | psamm/lpsolver/cplex.py | https://github.com/zhanglab/psamm/blob/dc427848c4f9d109ca590f0afa024c63b685b3f4/psamm/lpsolver/cplex.py#L288-L341 | def _reset_problem_type(self):
"""Reset problem type to whatever is appropriate."""
# Only need to reset the type after the first solve. This also works
# around a bug in Cplex where get_num_binary() is some rare cases
# causes a segfault.
if self._solve_count > 0:
i... | [
"def",
"_reset_problem_type",
"(",
"self",
")",
":",
"# Only need to reset the type after the first solve. This also works",
"# around a bug in Cplex where get_num_binary() is some rare cases",
"# causes a segfault.",
"if",
"self",
".",
"_solve_count",
">",
"0",
":",
"integer_count",... | Reset problem type to whatever is appropriate. | [
"Reset",
"problem",
"type",
"to",
"whatever",
"is",
"appropriate",
"."
] | python | train |
tensorflow/tensor2tensor | tensor2tensor/rl/evaluator.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/evaluator.py#L464-L477 | def get_game_for_worker(map_name, directory_id):
"""Get game for the given worker (directory) id."""
if map_name == "v100unfriendly":
games = ["chopper_command", "boxing", "asterix", "seaquest"]
worker_per_game = 5
elif map_name == "human_nice":
games = gym_env.ATARI_GAMES_WITH_HUMAN_SCORE_NICE
wo... | [
"def",
"get_game_for_worker",
"(",
"map_name",
",",
"directory_id",
")",
":",
"if",
"map_name",
"==",
"\"v100unfriendly\"",
":",
"games",
"=",
"[",
"\"chopper_command\"",
",",
"\"boxing\"",
",",
"\"asterix\"",
",",
"\"seaquest\"",
"]",
"worker_per_game",
"=",
"5",... | Get game for the given worker (directory) id. | [
"Get",
"game",
"for",
"the",
"given",
"worker",
"(",
"directory",
")",
"id",
"."
] | python | train |
astrocatalogs/astrocats | astrocats/catalog/entry.py | https://github.com/astrocatalogs/astrocats/blob/11abc3131c6366ecd23964369e55ff264add7805/astrocats/catalog/entry.py#L703-L710 | def add_photometry(self, compare_to_existing=True, **kwargs):
"""Add a `Photometry` instance to this entry."""
self._add_cat_dict(
Photometry,
self._KEYS.PHOTOMETRY,
compare_to_existing=compare_to_existing,
**kwargs)
return | [
"def",
"add_photometry",
"(",
"self",
",",
"compare_to_existing",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_add_cat_dict",
"(",
"Photometry",
",",
"self",
".",
"_KEYS",
".",
"PHOTOMETRY",
",",
"compare_to_existing",
"=",
"compare_to_existi... | Add a `Photometry` instance to this entry. | [
"Add",
"a",
"Photometry",
"instance",
"to",
"this",
"entry",
"."
] | python | train |
kakwa/ldapcherry | ldapcherry/roles.py | https://github.com/kakwa/ldapcherry/blob/b5e7cb6a44065abc30d164e72981b3713a172dda/ldapcherry/roles.py#L64-L83 | def _flatten(self, roles=None, groups=None):
""" flatten a (semi) nest roles structure"""
if roles is None:
roles_in = copy.deepcopy(self.roles_raw)
else:
roles_in = roles
for roleid in roles_in:
role = roles_in[roleid]
if groups is not Non... | [
"def",
"_flatten",
"(",
"self",
",",
"roles",
"=",
"None",
",",
"groups",
"=",
"None",
")",
":",
"if",
"roles",
"is",
"None",
":",
"roles_in",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
".",
"roles_raw",
")",
"else",
":",
"roles_in",
"=",
"roles",
... | flatten a (semi) nest roles structure | [
"flatten",
"a",
"(",
"semi",
")",
"nest",
"roles",
"structure"
] | python | train |
KelSolaar/Foundations | foundations/parsers.py | https://github.com/KelSolaar/Foundations/blob/5c141330faf09dad70a12bc321f4c564917d0a91/foundations/parsers.py#L1317-L1349 | def filter_values(self, pattern, flags=0):
"""
| Filters the :meth:`PlistFileParser.elements` class property elements using given pattern.
| Will return a list of matching elements values, if you want to get only one element value, use
the :meth:`PlistFileParser.get_value` method ins... | [
"def",
"filter_values",
"(",
"self",
",",
"pattern",
",",
"flags",
"=",
"0",
")",
":",
"values",
"=",
"[",
"]",
"if",
"not",
"self",
".",
"__elements",
":",
"return",
"values",
"for",
"item",
"in",
"foundations",
".",
"walkers",
".",
"dictionaries_walker... | | Filters the :meth:`PlistFileParser.elements` class property elements using given pattern.
| Will return a list of matching elements values, if you want to get only one element value, use
the :meth:`PlistFileParser.get_value` method instead.
Usage::
>>> plist_file_parser = Pli... | [
"|",
"Filters",
"the",
":",
"meth",
":",
"PlistFileParser",
".",
"elements",
"class",
"property",
"elements",
"using",
"given",
"pattern",
".",
"|",
"Will",
"return",
"a",
"list",
"of",
"matching",
"elements",
"values",
"if",
"you",
"want",
"to",
"get",
"o... | python | train |
C4ptainCrunch/ics.py | ics/timeline.py | https://github.com/C4ptainCrunch/ics.py/blob/bd918ec7453a7cf73a906cdcc78bd88eb4bab71b/ics/timeline.py#L55-L67 | def overlapping(self, start, stop):
"""Iterates (in chronological order) over every event that has an intersection
with the timespan between `start` and `stop`
Args:
start : (Arrow object)
stop : (Arrow object)
"""
for event in self:
if ((star... | [
"def",
"overlapping",
"(",
"self",
",",
"start",
",",
"stop",
")",
":",
"for",
"event",
"in",
"self",
":",
"if",
"(",
"(",
"start",
"<=",
"event",
".",
"begin",
"<=",
"stop",
"# if start is between the bonds",
"or",
"start",
"<=",
"event",
".",
"end",
... | Iterates (in chronological order) over every event that has an intersection
with the timespan between `start` and `stop`
Args:
start : (Arrow object)
stop : (Arrow object) | [
"Iterates",
"(",
"in",
"chronological",
"order",
")",
"over",
"every",
"event",
"that",
"has",
"an",
"intersection",
"with",
"the",
"timespan",
"between",
"start",
"and",
"stop"
] | python | train |
PaulHancock/Aegean | AegeanTools/catalogs.py | https://github.com/PaulHancock/Aegean/blob/185d2b4a51b48441a1df747efc9a5271c79399fd/AegeanTools/catalogs.py#L145-L194 | def save_catalog(filename, catalog, meta=None, prefix=None):
"""
Save a catalogue of sources using filename as a model. Meta data can be written to some file types
(fits, votable).
Each type of source will be in a separate file:
- base_comp.ext :class:`AegeanTools.models.OutputSource`
- base_i... | [
"def",
"save_catalog",
"(",
"filename",
",",
"catalog",
",",
"meta",
"=",
"None",
",",
"prefix",
"=",
"None",
")",
":",
"ascii_table_formats",
"=",
"{",
"'csv'",
":",
"'csv'",
",",
"'tab'",
":",
"'tab'",
",",
"'tex'",
":",
"'latex'",
",",
"'html'",
":"... | Save a catalogue of sources using filename as a model. Meta data can be written to some file types
(fits, votable).
Each type of source will be in a separate file:
- base_comp.ext :class:`AegeanTools.models.OutputSource`
- base_isle.ext :class:`AegeanTools.models.IslandSource`
- base_simp.ext :cla... | [
"Save",
"a",
"catalogue",
"of",
"sources",
"using",
"filename",
"as",
"a",
"model",
".",
"Meta",
"data",
"can",
"be",
"written",
"to",
"some",
"file",
"types",
"(",
"fits",
"votable",
")",
"."
] | python | train |
pvizeli/pydroid-ipcam | pydroid_ipcam.py | https://github.com/pvizeli/pydroid-ipcam/blob/42275a77fafa01e027d0752664f382b813a6f9b0/pydroid_ipcam.py#L238-L246 | def set_orientation(self, orientation='landscape'):
"""Set the video orientation.
Return a coroutine.
"""
if orientation not in ALLOWED_ORIENTATIONS:
_LOGGER.debug('%s is not a valid orientation', orientation)
return False
return self.change_setting('orie... | [
"def",
"set_orientation",
"(",
"self",
",",
"orientation",
"=",
"'landscape'",
")",
":",
"if",
"orientation",
"not",
"in",
"ALLOWED_ORIENTATIONS",
":",
"_LOGGER",
".",
"debug",
"(",
"'%s is not a valid orientation'",
",",
"orientation",
")",
"return",
"False",
"re... | Set the video orientation.
Return a coroutine. | [
"Set",
"the",
"video",
"orientation",
"."
] | python | train |
sliem/barrett | barrett/util.py | https://github.com/sliem/barrett/blob/d48e96591577d1fcecd50c21a9be71573218cde7/barrett/util.py#L6-L45 | def threenum(h5file, var, post_col='mult'):
""" Calculates the three number summary for a variable.
The three number summary is the minimum, maximum and the mean
of the data. Traditionally one would summerise data with the
five number summary: max, min, 1st, 2nd (median), 3rd quartile.
But quantile... | [
"def",
"threenum",
"(",
"h5file",
",",
"var",
",",
"post_col",
"=",
"'mult'",
")",
":",
"f",
"=",
"h5py",
".",
"File",
"(",
"h5file",
",",
"'r'",
")",
"d",
"=",
"f",
"[",
"var",
"]",
"w",
"=",
"f",
"[",
"post_col",
"]",
"s",
"=",
"d",
".",
... | Calculates the three number summary for a variable.
The three number summary is the minimum, maximum and the mean
of the data. Traditionally one would summerise data with the
five number summary: max, min, 1st, 2nd (median), 3rd quartile.
But quantiles are hard to calculate without sorting the data
... | [
"Calculates",
"the",
"three",
"number",
"summary",
"for",
"a",
"variable",
"."
] | python | train |
ultrabug/py3status | py3status/parse_config.py | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/parse_config.py#L507-L520 | def make_dict(self):
"""
We are in a dict so get key value pairs until the end token.
"""
out = {}
while True:
try:
key = self.dict_key()
self.separator(separator=":")
value = self.value_assign(end_token="]")
... | [
"def",
"make_dict",
"(",
"self",
")",
":",
"out",
"=",
"{",
"}",
"while",
"True",
":",
"try",
":",
"key",
"=",
"self",
".",
"dict_key",
"(",
")",
"self",
".",
"separator",
"(",
"separator",
"=",
"\":\"",
")",
"value",
"=",
"self",
".",
"value_assig... | We are in a dict so get key value pairs until the end token. | [
"We",
"are",
"in",
"a",
"dict",
"so",
"get",
"key",
"value",
"pairs",
"until",
"the",
"end",
"token",
"."
] | python | train |
googleapis/gax-python | google/gax/bundling.py | https://github.com/googleapis/gax-python/blob/309aedfcfd48e4c8fa22dd60e9c84c3cc71bb20e/google/gax/bundling.py#L57-L72 | def _str_dotted_getattr(obj, name):
"""Expands extends getattr to allow dots in x to indicate nested objects.
Args:
obj (object): an object.
name (str): a name for a field in the object.
Returns:
Any: the value of named attribute.
Raises:
AttributeError: if the named attri... | [
"def",
"_str_dotted_getattr",
"(",
"obj",
",",
"name",
")",
":",
"for",
"part",
"in",
"name",
".",
"split",
"(",
"'.'",
")",
":",
"obj",
"=",
"getattr",
"(",
"obj",
",",
"part",
")",
"return",
"str",
"(",
"obj",
")",
"if",
"obj",
"else",
"None"
] | Expands extends getattr to allow dots in x to indicate nested objects.
Args:
obj (object): an object.
name (str): a name for a field in the object.
Returns:
Any: the value of named attribute.
Raises:
AttributeError: if the named attribute does not exist. | [
"Expands",
"extends",
"getattr",
"to",
"allow",
"dots",
"in",
"x",
"to",
"indicate",
"nested",
"objects",
"."
] | python | train |
mitsei/dlkit | dlkit/json_/logging_/objects.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/logging_/objects.py#L564-L578 | def get_parent_log_nodes(self):
"""Gets the parents of this log.
return: (osid.logging.LogNodeList) - the parents of this log
*compliance: mandatory -- This method must be implemented.*
"""
parent_log_nodes = []
for node in self._my_map['parentNodes']:
paren... | [
"def",
"get_parent_log_nodes",
"(",
"self",
")",
":",
"parent_log_nodes",
"=",
"[",
"]",
"for",
"node",
"in",
"self",
".",
"_my_map",
"[",
"'parentNodes'",
"]",
":",
"parent_log_nodes",
".",
"append",
"(",
"LogNode",
"(",
"node",
".",
"_my_map",
",",
"runt... | Gets the parents of this log.
return: (osid.logging.LogNodeList) - the parents of this log
*compliance: mandatory -- This method must be implemented.* | [
"Gets",
"the",
"parents",
"of",
"this",
"log",
"."
] | python | train |
bwohlberg/sporco | sporco/common.py | https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/common.py#L59-L83 | def _fix_dynamic_class_lookup(cls, pstfx):
"""Fix name lookup problem that prevents pickling of dynamically
defined classes.
Parameters
----------
cls : class
Dynamically generated class to which fix is to be applied
pstfx : string
Postfix that can be used to identify dynamically ge... | [
"def",
"_fix_dynamic_class_lookup",
"(",
"cls",
",",
"pstfx",
")",
":",
"# Extended name for the class that will be added to the module namespace",
"extnm",
"=",
"'_'",
"+",
"cls",
".",
"__name__",
"+",
"'_'",
"+",
"pstfx",
"# Get the module in which the dynamic class is defi... | Fix name lookup problem that prevents pickling of dynamically
defined classes.
Parameters
----------
cls : class
Dynamically generated class to which fix is to be applied
pstfx : string
Postfix that can be used to identify dynamically generated classes
that are equivalent by const... | [
"Fix",
"name",
"lookup",
"problem",
"that",
"prevents",
"pickling",
"of",
"dynamically",
"defined",
"classes",
"."
] | python | train |
deepmind/pysc2 | pysc2/bin/agent_remote.py | https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/bin/agent_remote.py#L155-L229 | def human():
"""Run a host which expects one player to connect remotely."""
run_config = run_configs.get()
map_inst = maps.get(FLAGS.map)
if not FLAGS.rgb_screen_size or not FLAGS.rgb_minimap_size:
logging.info("Use --rgb_screen_size and --rgb_minimap_size if you want rgb "
"observations.... | [
"def",
"human",
"(",
")",
":",
"run_config",
"=",
"run_configs",
".",
"get",
"(",
")",
"map_inst",
"=",
"maps",
".",
"get",
"(",
"FLAGS",
".",
"map",
")",
"if",
"not",
"FLAGS",
".",
"rgb_screen_size",
"or",
"not",
"FLAGS",
".",
"rgb_minimap_size",
":",... | Run a host which expects one player to connect remotely. | [
"Run",
"a",
"host",
"which",
"expects",
"one",
"player",
"to",
"connect",
"remotely",
"."
] | python | train |
brocade/pynos | pynos/versions/ver_7/ver_7_1_0/yang/brocade_firmware.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_7/ver_7_1_0/yang/brocade_firmware.py#L772-L783 | def logical_chassis_fwdl_sanity_output_fwdl_cmd_msg(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
logical_chassis_fwdl_sanity = ET.Element("logical_chassis_fwdl_sanity")
config = logical_chassis_fwdl_sanity
output = ET.SubElement(logical_chassi... | [
"def",
"logical_chassis_fwdl_sanity_output_fwdl_cmd_msg",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"logical_chassis_fwdl_sanity",
"=",
"ET",
".",
"Element",
"(",
"\"logical_chassis_fwdl_sanity\"",
"... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train |
DEIB-GECO/PyGMQL | gmql/dataset/parsers/RegionParser.py | https://github.com/DEIB-GECO/PyGMQL/blob/e58b2f9402a86056dcda484a32e3de0bb06ed991/gmql/dataset/parsers/RegionParser.py#L167-L182 | def get_ordered_attributes(self):
""" Returns the ordered list of attributes
:return: list of strings
"""
attrs = self.get_attributes()
attr_arr = np.array(attrs)
poss = [self.chrPos, self.startPos, self.stopPos]
if self.strandPos is not None:
poss.ap... | [
"def",
"get_ordered_attributes",
"(",
"self",
")",
":",
"attrs",
"=",
"self",
".",
"get_attributes",
"(",
")",
"attr_arr",
"=",
"np",
".",
"array",
"(",
"attrs",
")",
"poss",
"=",
"[",
"self",
".",
"chrPos",
",",
"self",
".",
"startPos",
",",
"self",
... | Returns the ordered list of attributes
:return: list of strings | [
"Returns",
"the",
"ordered",
"list",
"of",
"attributes"
] | python | train |
nens/turn | turn/console.py | https://github.com/nens/turn/blob/98e806a0749ada0ddfd04b3c29fb04c15bf5ac18/turn/console.py#L43-L60 | def get_parser():
""" Return argument parser. """
parser = argparse.ArgumentParser(
formatter_class=argparse.RawTextHelpFormatter,
description=__doc__,
)
# connection to redis server
parser.add_argument('--host', default='localhost')
parser.add_argument('--port', default=6379, t... | [
"def",
"get_parser",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"formatter_class",
"=",
"argparse",
".",
"RawTextHelpFormatter",
",",
"description",
"=",
"__doc__",
",",
")",
"# connection to redis server",
"parser",
".",
"add_argument",
... | Return argument parser. | [
"Return",
"argument",
"parser",
"."
] | python | train |
peri-source/peri | peri/opt/optimize.py | https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/opt/optimize.py#L792-L872 | def _run2(self):
"""Workhorse for do_run_2"""
if self.check_update_J():
self.update_J()
else:
if self.check_Broyden_J():
self.update_Broyden_J()
if self.check_update_eig_J():
self.update_eig_J()
#0. Find _last_residuals... | [
"def",
"_run2",
"(",
"self",
")",
":",
"if",
"self",
".",
"check_update_J",
"(",
")",
":",
"self",
".",
"update_J",
"(",
")",
"else",
":",
"if",
"self",
".",
"check_Broyden_J",
"(",
")",
":",
"self",
".",
"update_Broyden_J",
"(",
")",
"if",
"self",
... | Workhorse for do_run_2 | [
"Workhorse",
"for",
"do_run_2"
] | python | valid |
brentp/cruzdb | cruzdb/__init__.py | https://github.com/brentp/cruzdb/blob/9068d46e25952f4a929dde0242beb31fa4c7e89a/cruzdb/__init__.py#L355-L441 | def knearest(self, table, chrom_or_feat, start=None, end=None, k=1,
_direction=None):
"""
Return k-nearest features
Parameters
----------
table : str or table
table against which to query
chrom_or_feat : str or feat
either a chromoso... | [
"def",
"knearest",
"(",
"self",
",",
"table",
",",
"chrom_or_feat",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
",",
"k",
"=",
"1",
",",
"_direction",
"=",
"None",
")",
":",
"assert",
"_direction",
"in",
"(",
"None",
",",
"\"up\"",
",",
"\"... | Return k-nearest features
Parameters
----------
table : str or table
table against which to query
chrom_or_feat : str or feat
either a chromosome, e.g. 'chr3' or a feature with .chrom, .start,
.end attributes
start : int
if `chr... | [
"Return",
"k",
"-",
"nearest",
"features"
] | python | train |
ciena/afkak | afkak/client.py | https://github.com/ciena/afkak/blob/6f5e05ba6f135ea3c29cdb80efda009f7845569a/afkak/client.py#L727-L762 | def _update_brokers(self, brokers, remove=False):
"""
Update `self._brokers` and `self.clients`
Update our self.clients based on brokers in received metadata
Take the received dict of brokers and reconcile it with our current
list of brokers (self.clients). If there is a new one... | [
"def",
"_update_brokers",
"(",
"self",
",",
"brokers",
",",
"remove",
"=",
"False",
")",
":",
"log",
".",
"debug",
"(",
"\"%r: _update_brokers(%r, remove=%r)\"",
",",
"self",
",",
"brokers",
",",
"remove",
")",
"brokers_by_id",
"=",
"{",
"bm",
".",
"node_id"... | Update `self._brokers` and `self.clients`
Update our self.clients based on brokers in received metadata
Take the received dict of brokers and reconcile it with our current
list of brokers (self.clients). If there is a new one, bring up a new
connection to it, and if remove is True, and ... | [
"Update",
"self",
".",
"_brokers",
"and",
"self",
".",
"clients"
] | python | train |
django-userena-ce/django-userena-ce | userena/models.py | https://github.com/django-userena-ce/django-userena-ce/blob/2d8b745eed25128134e961ca96c270802e730256/userena/models.py#L24-L39 | def upload_to_mugshot(instance, filename):
"""
Uploads a mugshot for a user to the ``USERENA_MUGSHOT_PATH`` and saving it
under unique hash for the image. This is for privacy reasons so others
can't just browse through the mugshot directory.
"""
extension = filename.split('.')[-1].lower()
s... | [
"def",
"upload_to_mugshot",
"(",
"instance",
",",
"filename",
")",
":",
"extension",
"=",
"filename",
".",
"split",
"(",
"'.'",
")",
"[",
"-",
"1",
"]",
".",
"lower",
"(",
")",
"salt",
",",
"hash",
"=",
"generate_sha1",
"(",
"instance",
".",
"pk",
")... | Uploads a mugshot for a user to the ``USERENA_MUGSHOT_PATH`` and saving it
under unique hash for the image. This is for privacy reasons so others
can't just browse through the mugshot directory. | [
"Uploads",
"a",
"mugshot",
"for",
"a",
"user",
"to",
"the",
"USERENA_MUGSHOT_PATH",
"and",
"saving",
"it",
"under",
"unique",
"hash",
"for",
"the",
"image",
".",
"This",
"is",
"for",
"privacy",
"reasons",
"so",
"others",
"can",
"t",
"just",
"browse",
"thro... | python | train |
hydpy-dev/hydpy | hydpy/auxs/xmltools.py | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/auxs/xmltools.py#L1155-L1187 | def load_series(self) -> None:
"""Load time series data as defined by the actual XML `reader`
element.
>>> from hydpy.core.examples import prepare_full_example_1
>>> prepare_full_example_1()
>>> from hydpy import HydPy, TestIO, XMLInterface
>>> hp = HydPy('LahnH')
... | [
"def",
"load_series",
"(",
"self",
")",
"->",
"None",
":",
"kwargs",
"=",
"{",
"}",
"for",
"keyword",
"in",
"(",
"'flattennetcdf'",
",",
"'isolatenetcdf'",
",",
"'timeaxisnetcdf'",
")",
":",
"argument",
"=",
"getattr",
"(",
"hydpy",
".",
"pub",
".",
"opt... | Load time series data as defined by the actual XML `reader`
element.
>>> from hydpy.core.examples import prepare_full_example_1
>>> prepare_full_example_1()
>>> from hydpy import HydPy, TestIO, XMLInterface
>>> hp = HydPy('LahnH')
>>> with TestIO():
... hp.p... | [
"Load",
"time",
"series",
"data",
"as",
"defined",
"by",
"the",
"actual",
"XML",
"reader",
"element",
"."
] | python | train |
Jammy2211/PyAutoLens | autolens/model/inversion/util/pixelization_util.py | https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/model/inversion/util/pixelization_util.py#L5-L30 | def rectangular_neighbors_from_shape(shape):
"""Compute the neighbors of every pixel as a list of the pixel index's each pixel shares a vertex with.
The uniformity of the rectangular grid's geometry is used to compute this.
"""
pixels = shape[0]*shape[1]
pixel_neighbors = -1 * np.ones(shape=(pix... | [
"def",
"rectangular_neighbors_from_shape",
"(",
"shape",
")",
":",
"pixels",
"=",
"shape",
"[",
"0",
"]",
"*",
"shape",
"[",
"1",
"]",
"pixel_neighbors",
"=",
"-",
"1",
"*",
"np",
".",
"ones",
"(",
"shape",
"=",
"(",
"pixels",
",",
"4",
")",
")",
"... | Compute the neighbors of every pixel as a list of the pixel index's each pixel shares a vertex with.
The uniformity of the rectangular grid's geometry is used to compute this. | [
"Compute",
"the",
"neighbors",
"of",
"every",
"pixel",
"as",
"a",
"list",
"of",
"the",
"pixel",
"index",
"s",
"each",
"pixel",
"shares",
"a",
"vertex",
"with",
"."
] | python | valid |
saltstack/salt | salt/states/pip_state.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/pip_state.py#L276-L297 | def _pep440_version_cmp(pkg1, pkg2, ignore_epoch=False):
'''
Compares two version strings using pkg_resources.parse_version.
Return -1 if version1 < version2, 0 if version1 ==version2,
and 1 if version1 > version2. Return None if there was a problem
making the comparison.
'''
normalize = lam... | [
"def",
"_pep440_version_cmp",
"(",
"pkg1",
",",
"pkg2",
",",
"ignore_epoch",
"=",
"False",
")",
":",
"normalize",
"=",
"lambda",
"x",
":",
"six",
".",
"text_type",
"(",
"x",
")",
".",
"split",
"(",
"'!'",
",",
"1",
")",
"[",
"-",
"1",
"]",
"if",
... | Compares two version strings using pkg_resources.parse_version.
Return -1 if version1 < version2, 0 if version1 ==version2,
and 1 if version1 > version2. Return None if there was a problem
making the comparison. | [
"Compares",
"two",
"version",
"strings",
"using",
"pkg_resources",
".",
"parse_version",
".",
"Return",
"-",
"1",
"if",
"version1",
"<",
"version2",
"0",
"if",
"version1",
"==",
"version2",
"and",
"1",
"if",
"version1",
">",
"version2",
".",
"Return",
"None"... | python | train |
python-beaver/python-beaver | beaver/transports/redis_transport.py | https://github.com/python-beaver/python-beaver/blob/93941e968016c5a962dffed9e7a9f6dc1d23236c/beaver/transports/redis_transport.py#L146-L151 | def _raise_server_index(self):
"""Round robin magic: Raises the current redis server index and returns it"""
self._current_server_index = (self._current_server_index + 1) % len(self._servers)
return self._current_server_index | [
"def",
"_raise_server_index",
"(",
"self",
")",
":",
"self",
".",
"_current_server_index",
"=",
"(",
"self",
".",
"_current_server_index",
"+",
"1",
")",
"%",
"len",
"(",
"self",
".",
"_servers",
")",
"return",
"self",
".",
"_current_server_index"
] | Round robin magic: Raises the current redis server index and returns it | [
"Round",
"robin",
"magic",
":",
"Raises",
"the",
"current",
"redis",
"server",
"index",
"and",
"returns",
"it"
] | python | train |
stephenmcd/django-socketio | django_socketio/example_project/chat/events.py | https://github.com/stephenmcd/django-socketio/blob/b704f912551829a3bcf15872ba0e1baf81dea106/django_socketio/example_project/chat/events.py#L41-L52 | def finish(request, socket, context):
"""
Event handler for a socket session ending in a room. Broadcast
the user leaving and delete them from the DB.
"""
try:
user = context["user"]
except KeyError:
return
left = {"action": "leave", "name": user.name, "id": user.id}
sock... | [
"def",
"finish",
"(",
"request",
",",
"socket",
",",
"context",
")",
":",
"try",
":",
"user",
"=",
"context",
"[",
"\"user\"",
"]",
"except",
"KeyError",
":",
"return",
"left",
"=",
"{",
"\"action\"",
":",
"\"leave\"",
",",
"\"name\"",
":",
"user",
"."... | Event handler for a socket session ending in a room. Broadcast
the user leaving and delete them from the DB. | [
"Event",
"handler",
"for",
"a",
"socket",
"session",
"ending",
"in",
"a",
"room",
".",
"Broadcast",
"the",
"user",
"leaving",
"and",
"delete",
"them",
"from",
"the",
"DB",
"."
] | python | train |
Rapptz/discord.py | discord/message.py | https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/message.py#L387-L391 | def raw_role_mentions(self):
"""A property that returns an array of role IDs matched with
the syntax of <@&role_id> in the message content.
"""
return [int(x) for x in re.findall(r'<@&([0-9]+)>', self.content)] | [
"def",
"raw_role_mentions",
"(",
"self",
")",
":",
"return",
"[",
"int",
"(",
"x",
")",
"for",
"x",
"in",
"re",
".",
"findall",
"(",
"r'<@&([0-9]+)>'",
",",
"self",
".",
"content",
")",
"]"
] | A property that returns an array of role IDs matched with
the syntax of <@&role_id> in the message content. | [
"A",
"property",
"that",
"returns",
"an",
"array",
"of",
"role",
"IDs",
"matched",
"with",
"the",
"syntax",
"of",
"<"
] | python | train |
BoboTiG/python-mss | mss/__main__.py | https://github.com/BoboTiG/python-mss/blob/56347f781edb38a0e7a5104080bd683f49c6f074/mss/__main__.py#L20-L87 | def main(args=None):
# type: (Optional[List[str]]) -> int
""" Main logic. """
cli_args = ArgumentParser()
cli_args.add_argument(
"-c",
"--coordinates",
default="",
type=str,
help="the part of the screen to capture: top, left, width, height",
)
cli_args.ad... | [
"def",
"main",
"(",
"args",
"=",
"None",
")",
":",
"# type: (Optional[List[str]]) -> int",
"cli_args",
"=",
"ArgumentParser",
"(",
")",
"cli_args",
".",
"add_argument",
"(",
"\"-c\"",
",",
"\"--coordinates\"",
",",
"default",
"=",
"\"\"",
",",
"type",
"=",
"st... | Main logic. | [
"Main",
"logic",
"."
] | python | train |
h2non/pook | pook/response.py | https://github.com/h2non/pook/blob/e64094e41e4d89d98d2d29af7608ef27dc50cf19/pook/response.py#L148-L161 | def body(self, body):
"""
Defines response body data.
Arguments:
body (str|bytes): response body to use.
Returns:
self: ``pook.Response`` current instance.
"""
if isinstance(body, bytes):
body = body.decode('utf-8')
self._bod... | [
"def",
"body",
"(",
"self",
",",
"body",
")",
":",
"if",
"isinstance",
"(",
"body",
",",
"bytes",
")",
":",
"body",
"=",
"body",
".",
"decode",
"(",
"'utf-8'",
")",
"self",
".",
"_body",
"=",
"body"
] | Defines response body data.
Arguments:
body (str|bytes): response body to use.
Returns:
self: ``pook.Response`` current instance. | [
"Defines",
"response",
"body",
"data",
"."
] | python | test |
openpermissions/perch | perch/organisation.py | https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/organisation.py#L199-L219 | def user_organisations(cls, user_id, state=None, include_deactivated=False):
"""
Get organisations that the user has joined
:param user_id: the user ID
:param state: the user's "join" state
:param include_deactivated: Include deactivated resources in response
:returns: l... | [
"def",
"user_organisations",
"(",
"cls",
",",
"user_id",
",",
"state",
"=",
"None",
",",
"include_deactivated",
"=",
"False",
")",
":",
"if",
"state",
"and",
"state",
"not",
"in",
"validators",
".",
"VALID_STATES",
":",
"raise",
"exceptions",
".",
"Validatio... | Get organisations that the user has joined
:param user_id: the user ID
:param state: the user's "join" state
:param include_deactivated: Include deactivated resources in response
:returns: list of Organisation instances
:raises: SocketError, CouchException | [
"Get",
"organisations",
"that",
"the",
"user",
"has",
"joined"
] | python | train |
twilio/twilio-python | twilio/rest/api/v2010/account/incoming_phone_number/local.py | https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/api/v2010/account/incoming_phone_number/local.py#L248-L257 | def get_instance(self, payload):
"""
Build an instance of LocalInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.api.v2010.account.incoming_phone_number.local.LocalInstance
:rtype: twilio.rest.api.v2010.account.incoming_phone_number.local.LocalIn... | [
"def",
"get_instance",
"(",
"self",
",",
"payload",
")",
":",
"return",
"LocalInstance",
"(",
"self",
".",
"_version",
",",
"payload",
",",
"account_sid",
"=",
"self",
".",
"_solution",
"[",
"'account_sid'",
"]",
",",
")"
] | Build an instance of LocalInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.api.v2010.account.incoming_phone_number.local.LocalInstance
:rtype: twilio.rest.api.v2010.account.incoming_phone_number.local.LocalInstance | [
"Build",
"an",
"instance",
"of",
"LocalInstance"
] | python | train |
KrishnaswamyLab/PHATE | Python/phate/utils.py | https://github.com/KrishnaswamyLab/PHATE/blob/346a4597dcfc523f8bef99bce482e677282b6719/Python/phate/utils.py#L55-L74 | def check_in(choices, **params):
"""Checks parameters are in a list of allowed parameters
Parameters
----------
choices : array-like, accepted values
params : object
Named arguments, parameters to be checked
Raises
------
ValueError : unacceptable choice of parameters
"""... | [
"def",
"check_in",
"(",
"choices",
",",
"*",
"*",
"params",
")",
":",
"for",
"p",
"in",
"params",
":",
"if",
"params",
"[",
"p",
"]",
"not",
"in",
"choices",
":",
"raise",
"ValueError",
"(",
"\"{} value {} not recognized. Choose from {}\"",
".",
"format",
... | Checks parameters are in a list of allowed parameters
Parameters
----------
choices : array-like, accepted values
params : object
Named arguments, parameters to be checked
Raises
------
ValueError : unacceptable choice of parameters | [
"Checks",
"parameters",
"are",
"in",
"a",
"list",
"of",
"allowed",
"parameters"
] | python | train |
Calysto/calysto | calysto/ai/conx.py | https://github.com/Calysto/calysto/blob/20813c0f48096317aa775d03a5c6b20f12fafc93/calysto/ai/conx.py#L140-L147 | def randomArray(size, bound):
"""
Returns an array initialized to random values between -max and max.
"""
if type(size) == type(1):
size = (size,)
temp = Numeric.array( ndim(*size) ) * (2.0 * bound)
return temp - bound | [
"def",
"randomArray",
"(",
"size",
",",
"bound",
")",
":",
"if",
"type",
"(",
"size",
")",
"==",
"type",
"(",
"1",
")",
":",
"size",
"=",
"(",
"size",
",",
")",
"temp",
"=",
"Numeric",
".",
"array",
"(",
"ndim",
"(",
"*",
"size",
")",
")",
"*... | Returns an array initialized to random values between -max and max. | [
"Returns",
"an",
"array",
"initialized",
"to",
"random",
"values",
"between",
"-",
"max",
"and",
"max",
"."
] | python | train |
dw/mitogen | ansible_mitogen/mixins.py | https://github.com/dw/mitogen/blob/a7fdb55e1300a7e0a5e404b09eb730cf9a525da7/ansible_mitogen/mixins.py#L193-L203 | def _make_tmp_path(self, remote_user=None):
"""
Create a temporary subdirectory as a child of the temporary directory
managed by the remote interpreter.
"""
LOG.debug('_make_tmp_path(remote_user=%r)', remote_user)
path = self._generate_tmp_path()
LOG.debug('Tempor... | [
"def",
"_make_tmp_path",
"(",
"self",
",",
"remote_user",
"=",
"None",
")",
":",
"LOG",
".",
"debug",
"(",
"'_make_tmp_path(remote_user=%r)'",
",",
"remote_user",
")",
"path",
"=",
"self",
".",
"_generate_tmp_path",
"(",
")",
"LOG",
".",
"debug",
"(",
"'Temp... | Create a temporary subdirectory as a child of the temporary directory
managed by the remote interpreter. | [
"Create",
"a",
"temporary",
"subdirectory",
"as",
"a",
"child",
"of",
"the",
"temporary",
"directory",
"managed",
"by",
"the",
"remote",
"interpreter",
"."
] | python | train |
projectatomic/atomic-reactor | atomic_reactor/plugins/post_group_manifests.py | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/plugins/post_group_manifests.py#L212-L244 | def check_existing_vr_tag(self):
"""
Checks if version-release tag (primary not floating tag) exists already,
and fails plugin if it does.
"""
primary_images = get_primary_images(self.workflow)
if not primary_images:
return
vr_image = None
fo... | [
"def",
"check_existing_vr_tag",
"(",
"self",
")",
":",
"primary_images",
"=",
"get_primary_images",
"(",
"self",
".",
"workflow",
")",
"if",
"not",
"primary_images",
":",
"return",
"vr_image",
"=",
"None",
"for",
"image",
"in",
"primary_images",
":",
"if",
"'-... | Checks if version-release tag (primary not floating tag) exists already,
and fails plugin if it does. | [
"Checks",
"if",
"version",
"-",
"release",
"tag",
"(",
"primary",
"not",
"floating",
"tag",
")",
"exists",
"already",
"and",
"fails",
"plugin",
"if",
"it",
"does",
"."
] | python | train |
blazelibs/blazeutils | blazeutils/helpers.py | https://github.com/blazelibs/blazeutils/blob/c94476325146007553cbddeeb9ef83394756babf/blazeutils/helpers.py#L147-L162 | def unique(seq, preserve_order=True):
"""
Take a sequence and make it unique. Not preserving order is faster, but
that won't matter so much for most uses.
copied from: http://www.peterbe.com/plog/uniqifiers-benchmark/uniqifiers_benchmark.py
"""
if preserve_order:
# f8 by Da... | [
"def",
"unique",
"(",
"seq",
",",
"preserve_order",
"=",
"True",
")",
":",
"if",
"preserve_order",
":",
"# f8 by Dave Kirby",
"# Order preserving",
"seen",
"=",
"set",
"(",
")",
"seen_add",
"=",
"seen",
".",
"add",
"# lookup method only once",
"return",
"[",
"... | Take a sequence and make it unique. Not preserving order is faster, but
that won't matter so much for most uses.
copied from: http://www.peterbe.com/plog/uniqifiers-benchmark/uniqifiers_benchmark.py | [
"Take",
"a",
"sequence",
"and",
"make",
"it",
"unique",
".",
"Not",
"preserving",
"order",
"is",
"faster",
"but",
"that",
"won",
"t",
"matter",
"so",
"much",
"for",
"most",
"uses",
"."
] | python | train |
log2timeline/dfvfs | dfvfs/vfs/apfs_file_entry.py | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/vfs/apfs_file_entry.py#L172-L175 | def change_time(self):
"""dfdatetime.DateTimeValues: change time or None if not available."""
timestamp = self._fsapfs_file_entry.get_inode_change_time_as_integer()
return dfdatetime_apfs_time.APFSTime(timestamp=timestamp) | [
"def",
"change_time",
"(",
"self",
")",
":",
"timestamp",
"=",
"self",
".",
"_fsapfs_file_entry",
".",
"get_inode_change_time_as_integer",
"(",
")",
"return",
"dfdatetime_apfs_time",
".",
"APFSTime",
"(",
"timestamp",
"=",
"timestamp",
")"
] | dfdatetime.DateTimeValues: change time or None if not available. | [
"dfdatetime",
".",
"DateTimeValues",
":",
"change",
"time",
"or",
"None",
"if",
"not",
"available",
"."
] | python | train |
manns/pyspread | pyspread/src/gui/_grid.py | https://github.com/manns/pyspread/blob/0e2fd44c2e0f06605efc3058c20a43a8c1f9e7e0/pyspread/src/gui/_grid.py#L1520-L1552 | def OnColSize(self, event):
"""Column size event handler"""
col = event.GetRowOrCol()
tab = self.grid.current_table
colsize = self.grid.GetColSize(col) / self.grid.grid_renderer.zoom
# Detect for resizing group of cols
cols = self.grid.GetSelectedCols()
if len(c... | [
"def",
"OnColSize",
"(",
"self",
",",
"event",
")",
":",
"col",
"=",
"event",
".",
"GetRowOrCol",
"(",
")",
"tab",
"=",
"self",
".",
"grid",
".",
"current_table",
"colsize",
"=",
"self",
".",
"grid",
".",
"GetColSize",
"(",
"col",
")",
"/",
"self",
... | Column size event handler | [
"Column",
"size",
"event",
"handler"
] | python | train |
mugurbil/gnm | gnm/gnm.py | https://github.com/mugurbil/gnm/blob/4f9711fb9d78cc02820c25234bc3ab9615014f11/gnm/gnm.py#L533-L576 | def _proposal_params(self, state):
"""
Proposal parameters
Calculate parameters needed for the proposal.
Inputs :
state :
x :
the present sample, the place to linearize around
f : f(x),
function value at x
J : ... | [
"def",
"_proposal_params",
"(",
"self",
",",
"state",
")",
":",
"x",
"=",
"state",
"[",
"'x'",
"]",
"f",
"=",
"state",
"[",
"'f'",
"]",
"J",
"=",
"state",
"[",
"'J'",
"]",
"JJ",
"=",
"np",
".",
"dot",
"(",
"J",
".",
"T",
",",
"J",
")",
"if"... | Proposal parameters
Calculate parameters needed for the proposal.
Inputs :
state :
x :
the present sample, the place to linearize around
f : f(x),
function value at x
J : f'(x),
the jacobian of the functio... | [
"Proposal",
"parameters",
"Calculate",
"parameters",
"needed",
"for",
"the",
"proposal",
".",
"Inputs",
":",
"state",
":",
"x",
":",
"the",
"present",
"sample",
"the",
"place",
"to",
"linearize",
"around",
"f",
":",
"f",
"(",
"x",
")",
"function",
"value",... | python | train |
google/grr | grr/core/grr_response_core/lib/utils.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/core/grr_response_core/lib/utils.py#L973-L1016 | def WriteFileFooter(self):
"""Writes the file footer (finished the file)."""
if not self._stream:
raise ArchiveAlreadyClosedError(
"Attempting to write to a ZIP archive that was already closed.")
if self.cur_cmpr:
buf = self.cur_cmpr.flush()
self.cur_compress_size += len(buf)
... | [
"def",
"WriteFileFooter",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_stream",
":",
"raise",
"ArchiveAlreadyClosedError",
"(",
"\"Attempting to write to a ZIP archive that was already closed.\"",
")",
"if",
"self",
".",
"cur_cmpr",
":",
"buf",
"=",
"self",
".... | Writes the file footer (finished the file). | [
"Writes",
"the",
"file",
"footer",
"(",
"finished",
"the",
"file",
")",
"."
] | python | train |
hannes-brt/hebel | hebel/pycuda_ops/cublas.py | https://github.com/hannes-brt/hebel/blob/1e2c3a9309c2646103901b26a55be4e312dd5005/hebel/pycuda_ops/cublas.py#L2814-L2824 | def cublasSsyr(handle, uplo, n, alpha, x, incx, A, lda):
"""
Rank-1 operation on real symmetric matrix.
"""
status = _libcublas.cublasSsyr_v2(handle,
_CUBLAS_FILL_MODE[uplo], n,
ctypes.byref(ctypes.c_float(alpha)),
... | [
"def",
"cublasSsyr",
"(",
"handle",
",",
"uplo",
",",
"n",
",",
"alpha",
",",
"x",
",",
"incx",
",",
"A",
",",
"lda",
")",
":",
"status",
"=",
"_libcublas",
".",
"cublasSsyr_v2",
"(",
"handle",
",",
"_CUBLAS_FILL_MODE",
"[",
"uplo",
"]",
",",
"n",
... | Rank-1 operation on real symmetric matrix. | [
"Rank",
"-",
"1",
"operation",
"on",
"real",
"symmetric",
"matrix",
"."
] | python | train |
jessevdk/cldoc | cldoc/clang/cindex.py | https://github.com/jessevdk/cldoc/blob/fc7f59405c4a891b8367c80a700f5aa3c5c9230c/cldoc/clang/cindex.py#L2737-L2809 | def from_source(cls, filename, args=None, unsaved_files=None, options=0,
index=None):
"""Create a TranslationUnit by parsing source.
This is capable of processing source code both from files on the
filesystem as well as in-memory contents.
Command-line arguments tha... | [
"def",
"from_source",
"(",
"cls",
",",
"filename",
",",
"args",
"=",
"None",
",",
"unsaved_files",
"=",
"None",
",",
"options",
"=",
"0",
",",
"index",
"=",
"None",
")",
":",
"if",
"args",
"is",
"None",
":",
"args",
"=",
"[",
"]",
"if",
"unsaved_fi... | Create a TranslationUnit by parsing source.
This is capable of processing source code both from files on the
filesystem as well as in-memory contents.
Command-line arguments that would be passed to clang are specified as
a list via args. These can be used to specify include paths, warn... | [
"Create",
"a",
"TranslationUnit",
"by",
"parsing",
"source",
"."
] | python | train |
ministryofjustice/django-moj-irat | moj_irat/healthchecks.py | https://github.com/ministryofjustice/django-moj-irat/blob/c1588426fffce783bef6d8b9d73395a5e9a833c9/moj_irat/healthchecks.py#L162-L169 | def load_healthchecks(self):
"""
Loads healthchecks.
"""
self.load_default_healthchecks()
if getattr(settings, 'AUTODISCOVER_HEALTHCHECKS', True):
self.autodiscover_healthchecks()
self._registry_loaded = True | [
"def",
"load_healthchecks",
"(",
"self",
")",
":",
"self",
".",
"load_default_healthchecks",
"(",
")",
"if",
"getattr",
"(",
"settings",
",",
"'AUTODISCOVER_HEALTHCHECKS'",
",",
"True",
")",
":",
"self",
".",
"autodiscover_healthchecks",
"(",
")",
"self",
".",
... | Loads healthchecks. | [
"Loads",
"healthchecks",
"."
] | python | train |
sirfoga/pyhal | hal/files/models/system.py | https://github.com/sirfoga/pyhal/blob/4394d8a1f7e45bea28a255ec390f4962ee64d33a/hal/files/models/system.py#L67-L82 | def fix_raw_path(path):
"""Prettify name of path
:param path: path to fix
:return: Good name for path
"""
double_path_separator = PATH_SEPARATOR + PATH_SEPARATOR
while path.find(
double_path_separator) >= 0: # there are double separators
path = path.replace(double_path_sepa... | [
"def",
"fix_raw_path",
"(",
"path",
")",
":",
"double_path_separator",
"=",
"PATH_SEPARATOR",
"+",
"PATH_SEPARATOR",
"while",
"path",
".",
"find",
"(",
"double_path_separator",
")",
">=",
"0",
":",
"# there are double separators",
"path",
"=",
"path",
".",
"replac... | Prettify name of path
:param path: path to fix
:return: Good name for path | [
"Prettify",
"name",
"of",
"path"
] | python | train |
hazelcast/hazelcast-python-client | hazelcast/proxy/queue.py | https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/proxy/queue.py#L164-L177 | def offer(self, item, timeout=0):
"""
Inserts the specified element into this queue if it is possible to do so immediately without violating capacity
restrictions. Returns ``true`` upon success. If there is no space currently available:
* If a timeout is provided, it waits until this... | [
"def",
"offer",
"(",
"self",
",",
"item",
",",
"timeout",
"=",
"0",
")",
":",
"check_not_none",
"(",
"item",
",",
"\"Value can't be None\"",
")",
"element_data",
"=",
"self",
".",
"_to_data",
"(",
"item",
")",
"return",
"self",
".",
"_encode_invoke",
"(",
... | Inserts the specified element into this queue if it is possible to do so immediately without violating capacity
restrictions. Returns ``true`` upon success. If there is no space currently available:
* If a timeout is provided, it waits until this timeout elapses and returns the result.
*... | [
"Inserts",
"the",
"specified",
"element",
"into",
"this",
"queue",
"if",
"it",
"is",
"possible",
"to",
"do",
"so",
"immediately",
"without",
"violating",
"capacity",
"restrictions",
".",
"Returns",
"true",
"upon",
"success",
".",
"If",
"there",
"is",
"no",
"... | python | train |
neighbordog/deviantart | deviantart/api.py | https://github.com/neighbordog/deviantart/blob/5612f1d5e2139a48c9d793d7fd19cde7e162d7b1/deviantart/api.py#L1624-L1640 | def move_notes(self, noteids, folderid):
"""Move notes to a folder
:param noteids: The noteids to move
:param folderid: The folderid to move notes to
"""
if self.standard_grant_type is not "authorization_code":
raise DeviantartError("Authentication through Authoriz... | [
"def",
"move_notes",
"(",
"self",
",",
"noteids",
",",
"folderid",
")",
":",
"if",
"self",
".",
"standard_grant_type",
"is",
"not",
"\"authorization_code\"",
":",
"raise",
"DeviantartError",
"(",
"\"Authentication through Authorization Code (Grant Type) is required in order... | Move notes to a folder
:param noteids: The noteids to move
:param folderid: The folderid to move notes to | [
"Move",
"notes",
"to",
"a",
"folder"
] | python | train |
signaturit/python-sdk | signaturit_sdk/signaturit_client.py | https://github.com/signaturit/python-sdk/blob/2419c6d9675d901244f807ae360dc58aa46109a9/signaturit_sdk/signaturit_client.py#L594-L609 | def create_group(self, name):
"""
Create group
:param name: Group name
"""
parameters = {
'name': name
}
url = self.TEAM_GROUPS_URL
connection = Connection(self.token)
connection.set_url(self.production, url)
connection.add_pa... | [
"def",
"create_group",
"(",
"self",
",",
"name",
")",
":",
"parameters",
"=",
"{",
"'name'",
":",
"name",
"}",
"url",
"=",
"self",
".",
"TEAM_GROUPS_URL",
"connection",
"=",
"Connection",
"(",
"self",
".",
"token",
")",
"connection",
".",
"set_url",
"(",... | Create group
:param name: Group name | [
"Create",
"group",
":",
"param",
"name",
":",
"Group",
"name"
] | python | train |
astropy/regions | ah_bootstrap.py | https://github.com/astropy/regions/blob/452d962c417e4ff20d1268f99535c6ff89c83437/ah_bootstrap.py#L486-L519 | def _directory_import(self):
"""
Import astropy_helpers from the given path, which will be added to
sys.path.
Must return True if the import succeeded, and False otherwise.
"""
# Return True on success, False on failure but download is allowed, and
# otherwise r... | [
"def",
"_directory_import",
"(",
"self",
")",
":",
"# Return True on success, False on failure but download is allowed, and",
"# otherwise raise SystemExit",
"path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"self",
".",
"path",
")",
"# Use an empty WorkingSet rather than ... | Import astropy_helpers from the given path, which will be added to
sys.path.
Must return True if the import succeeded, and False otherwise. | [
"Import",
"astropy_helpers",
"from",
"the",
"given",
"path",
"which",
"will",
"be",
"added",
"to",
"sys",
".",
"path",
"."
] | python | train |
saltstack/salt | salt/modules/cyg.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cyg.py#L242-L270 | def uninstall(packages,
cyg_arch='x86_64',
mirrors=None):
'''
Uninstall one or several packages.
packages
The packages to uninstall.
cyg_arch : x86_64
Specify the architecture to remove the package from
Current options are x86 and x86_64
CLI Exa... | [
"def",
"uninstall",
"(",
"packages",
",",
"cyg_arch",
"=",
"'x86_64'",
",",
"mirrors",
"=",
"None",
")",
":",
"args",
"=",
"[",
"]",
"if",
"packages",
"is",
"not",
"None",
":",
"args",
".",
"append",
"(",
"'--remove-packages {pkgs}'",
".",
"format",
"(",... | Uninstall one or several packages.
packages
The packages to uninstall.
cyg_arch : x86_64
Specify the architecture to remove the package from
Current options are x86 and x86_64
CLI Example:
.. code-block:: bash
salt '*' cyg.uninstall dos2unix
salt '*' cyg.unin... | [
"Uninstall",
"one",
"or",
"several",
"packages",
"."
] | python | train |
koszullab/metaTOR | metator/scripts/hicstuff.py | https://github.com/koszullab/metaTOR/blob/0c1203d1dffedfa5ea380c0335b4baa9cfb7e89a/metator/scripts/hicstuff.py#L1005-L1031 | def positions_to_contigs(positions):
"""Flattens and converts a positions array to a contigs array, if applicable.
"""
if isinstance(positions, np.ndarray):
flattened_positions = positions.flatten()
else:
try:
flattened_positions = np.array(
[pos for contig i... | [
"def",
"positions_to_contigs",
"(",
"positions",
")",
":",
"if",
"isinstance",
"(",
"positions",
",",
"np",
".",
"ndarray",
")",
":",
"flattened_positions",
"=",
"positions",
".",
"flatten",
"(",
")",
"else",
":",
"try",
":",
"flattened_positions",
"=",
"np"... | Flattens and converts a positions array to a contigs array, if applicable. | [
"Flattens",
"and",
"converts",
"a",
"positions",
"array",
"to",
"a",
"contigs",
"array",
"if",
"applicable",
"."
] | python | train |
chovanecm/sacredboard | sacredboard/app/data/filestorage/rundao.py | https://github.com/chovanecm/sacredboard/blob/47e1c99e3be3c1b099d3772bc077f5666020eb0b/sacredboard/app/data/filestorage/rundao.py#L20-L49 | def get_runs(self, sort_by=None, sort_direction=None, start=0, limit=None, query={"type": "and", "filters": []}):
"""
Return all runs in the file store.
If a run is corrupt, e.g. missing files, it is skipped.
:param sort_by: NotImplemented
:param sort_direction: NotImplemented... | [
"def",
"get_runs",
"(",
"self",
",",
"sort_by",
"=",
"None",
",",
"sort_direction",
"=",
"None",
",",
"start",
"=",
"0",
",",
"limit",
"=",
"None",
",",
"query",
"=",
"{",
"\"type\"",
":",
"\"and\"",
",",
"\"filters\"",
":",
"[",
"]",
"}",
")",
":"... | Return all runs in the file store.
If a run is corrupt, e.g. missing files, it is skipped.
:param sort_by: NotImplemented
:param sort_direction: NotImplemented
:param start: NotImplemented
:param limit: NotImplemented
:param query: NotImplemented
:return: FileS... | [
"Return",
"all",
"runs",
"in",
"the",
"file",
"store",
"."
] | python | train |
nerdvegas/rez | src/rez/wrapper.py | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/wrapper.py#L66-L81 | def run(self, *args):
"""Invoke the wrapped script.
Returns:
Return code of the command, or 0 if the command is not run.
"""
if self.prefix_char is None:
prefix_char = config.suite_alias_prefix_char
else:
prefix_char = self.prefix_char
... | [
"def",
"run",
"(",
"self",
",",
"*",
"args",
")",
":",
"if",
"self",
".",
"prefix_char",
"is",
"None",
":",
"prefix_char",
"=",
"config",
".",
"suite_alias_prefix_char",
"else",
":",
"prefix_char",
"=",
"self",
".",
"prefix_char",
"if",
"prefix_char",
"=="... | Invoke the wrapped script.
Returns:
Return code of the command, or 0 if the command is not run. | [
"Invoke",
"the",
"wrapped",
"script",
"."
] | python | train |
clalancette/pycdlib | pycdlib/pycdlib.py | https://github.com/clalancette/pycdlib/blob/1e7b77a809e905d67dc71e12d70e850be26b6233/pycdlib/pycdlib.py#L3153-L3185 | def _finish_remove(self, num_bytes_to_remove, is_partition):
# type: (int, bool) -> None
'''
An internal method to do all of the accounting needed whenever
something is removed from the ISO. This method should only be called
by public API implementations.
Parameters:
... | [
"def",
"_finish_remove",
"(",
"self",
",",
"num_bytes_to_remove",
",",
"is_partition",
")",
":",
"# type: (int, bool) -> None",
"for",
"pvd",
"in",
"self",
".",
"pvds",
":",
"pvd",
".",
"remove_from_space_size",
"(",
"num_bytes_to_remove",
")",
"if",
"self",
".",
... | An internal method to do all of the accounting needed whenever
something is removed from the ISO. This method should only be called
by public API implementations.
Parameters:
num_bytes_to_remove - The number of additional bytes to remove from the descriptors.
is_partition - W... | [
"An",
"internal",
"method",
"to",
"do",
"all",
"of",
"the",
"accounting",
"needed",
"whenever",
"something",
"is",
"removed",
"from",
"the",
"ISO",
".",
"This",
"method",
"should",
"only",
"be",
"called",
"by",
"public",
"API",
"implementations",
"."
] | python | train |
Ezhil-Language-Foundation/open-tamil | tamil/tweetparser.py | https://github.com/Ezhil-Language-Foundation/open-tamil/blob/b7556e88878d29bbc6c944ee17cdd3f75b8ea9f0/tamil/tweetparser.py#L71-L76 | def isTamilPredicate(word):
""" is Tamil word : boolean True/False"""
for c in word:
if unicodedata.name(c).split()[0] != u'TAMIL' :
return False
return True | [
"def",
"isTamilPredicate",
"(",
"word",
")",
":",
"for",
"c",
"in",
"word",
":",
"if",
"unicodedata",
".",
"name",
"(",
"c",
")",
".",
"split",
"(",
")",
"[",
"0",
"]",
"!=",
"u'TAMIL'",
":",
"return",
"False",
"return",
"True"
] | is Tamil word : boolean True/False | [
"is",
"Tamil",
"word",
":",
"boolean",
"True",
"/",
"False"
] | python | train |
saltstack/salt | salt/utils/event.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/event.py#L356-L370 | def unsubscribe(self, tag, match_type=None):
'''
Un-subscribe to events matching the passed tag.
'''
if tag is None:
return
match_func = self._get_match_func(match_type)
self.pending_tags.remove([tag, match_func])
old_events = self.pending_events
... | [
"def",
"unsubscribe",
"(",
"self",
",",
"tag",
",",
"match_type",
"=",
"None",
")",
":",
"if",
"tag",
"is",
"None",
":",
"return",
"match_func",
"=",
"self",
".",
"_get_match_func",
"(",
"match_type",
")",
"self",
".",
"pending_tags",
".",
"remove",
"(",... | Un-subscribe to events matching the passed tag. | [
"Un",
"-",
"subscribe",
"to",
"events",
"matching",
"the",
"passed",
"tag",
"."
] | python | train |
leancloud/python-sdk | leancloud/relation.py | https://github.com/leancloud/python-sdk/blob/fea3240257ce65e6a32c7312a5cee1f94a51a587/leancloud/relation.py#L21-L32 | def reverse_query(cls, parent_class, relation_key, child):
"""
创建一个新的 Query 对象,反向查询所有指向此 Relation 的父对象。
:param parent_class: 父类名称
:param relation_key: 父类中 Relation 的字段名
:param child: 子类对象
:return: leancloud.Query
"""
q = leancloud.Query(parent_class)
... | [
"def",
"reverse_query",
"(",
"cls",
",",
"parent_class",
",",
"relation_key",
",",
"child",
")",
":",
"q",
"=",
"leancloud",
".",
"Query",
"(",
"parent_class",
")",
"q",
".",
"equal_to",
"(",
"relation_key",
",",
"child",
".",
"_to_pointer",
"(",
")",
")... | 创建一个新的 Query 对象,反向查询所有指向此 Relation 的父对象。
:param parent_class: 父类名称
:param relation_key: 父类中 Relation 的字段名
:param child: 子类对象
:return: leancloud.Query | [
"创建一个新的",
"Query",
"对象,反向查询所有指向此",
"Relation",
"的父对象。"
] | python | train |
NeuroML/NeuroMLlite | neuromllite/SonataReader.py | https://github.com/NeuroML/NeuroMLlite/blob/f3fa2ff662e40febfa97c045e7f0e6915ad04161/neuromllite/SonataReader.py#L136-L606 | def parse(self, handler):
"""
Main method to parse the Sonata files and call the appropriate methods
in the handler
"""
########################################################################
# load the main configuration scripts
main_config_filename =... | [
"def",
"parse",
"(",
"self",
",",
"handler",
")",
":",
"########################################################################",
"# load the main configuration scripts ",
"main_config_filename",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"self",
".",
"parameters",
"... | Main method to parse the Sonata files and call the appropriate methods
in the handler | [
"Main",
"method",
"to",
"parse",
"the",
"Sonata",
"files",
"and",
"call",
"the",
"appropriate",
"methods",
"in",
"the",
"handler"
] | python | train |
ThreatConnect-Inc/tcex | tcex/tcex_ti/mappings/task.py | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti/mappings/task.py#L114-L126 | def reminder_date(self, reminder_date):
"""
Sets the task reminder_date
Args:
reminder_date: Converted to %Y-%m-%dT%H:%M:%SZ date format
"""
if not self.can_update():
self._tcex.handle_error(910, [self.type])
reminder_date = self._utils.format_dat... | [
"def",
"reminder_date",
"(",
"self",
",",
"reminder_date",
")",
":",
"if",
"not",
"self",
".",
"can_update",
"(",
")",
":",
"self",
".",
"_tcex",
".",
"handle_error",
"(",
"910",
",",
"[",
"self",
".",
"type",
"]",
")",
"reminder_date",
"=",
"self",
... | Sets the task reminder_date
Args:
reminder_date: Converted to %Y-%m-%dT%H:%M:%SZ date format | [
"Sets",
"the",
"task",
"reminder_date",
"Args",
":",
"reminder_date",
":",
"Converted",
"to",
"%Y",
"-",
"%m",
"-",
"%dT%H",
":",
"%M",
":",
"%SZ",
"date",
"format"
] | python | train |
blockstack/blockstack-core | blockstack/lib/nameset/namedb.py | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/namedb.py#L1443-L1459 | def is_name_owner( self, name, sender_script_pubkey ):
"""
Given the fully-qualified name and a sender's script pubkey,
determine if the sender owns the name.
The name must exist and not be revoked or expired at the
current block.
"""
if not self.is_name_register... | [
"def",
"is_name_owner",
"(",
"self",
",",
"name",
",",
"sender_script_pubkey",
")",
":",
"if",
"not",
"self",
".",
"is_name_registered",
"(",
"name",
")",
":",
"# no one owns it ",
"return",
"False",
"owner",
"=",
"self",
".",
"get_name_owner",
"(",
"name",
... | Given the fully-qualified name and a sender's script pubkey,
determine if the sender owns the name.
The name must exist and not be revoked or expired at the
current block. | [
"Given",
"the",
"fully",
"-",
"qualified",
"name",
"and",
"a",
"sender",
"s",
"script",
"pubkey",
"determine",
"if",
"the",
"sender",
"owns",
"the",
"name",
"."
] | python | train |
kivy/python-for-android | pythonforandroid/toolchain.py | https://github.com/kivy/python-for-android/blob/8e0e8056bc22e4d5bd3398a6b0301f38ff167933/pythonforandroid/toolchain.py#L1075-L1087 | def distributions(self, _args):
"""Lists all distributions currently available (i.e. that have already
been built)."""
ctx = self.ctx
dists = Distribution.get_distributions(ctx)
if dists:
print('{Style.BRIGHT}Distributions currently installed are:'
... | [
"def",
"distributions",
"(",
"self",
",",
"_args",
")",
":",
"ctx",
"=",
"self",
".",
"ctx",
"dists",
"=",
"Distribution",
".",
"get_distributions",
"(",
"ctx",
")",
"if",
"dists",
":",
"print",
"(",
"'{Style.BRIGHT}Distributions currently installed are:'",
"'{S... | Lists all distributions currently available (i.e. that have already
been built). | [
"Lists",
"all",
"distributions",
"currently",
"available",
"(",
"i",
".",
"e",
".",
"that",
"have",
"already",
"been",
"built",
")",
"."
] | python | train |
NoviceLive/intellicoder | intellicoder/synthesizers.py | https://github.com/NoviceLive/intellicoder/blob/6cac5ebfce65c370dbebe47756a1789b120ef982/intellicoder/synthesizers.py#L231-L243 | def c_module_relocs(self):
"""Build relocation for the module variable."""
if self.opts.no_structs or self.opts.windll:
return '', ''
x86 = reloc_var(
self.name, self._c_struct_names()[1],
self.opts.reloc_delta,
self._c_uses_pointer()
)
... | [
"def",
"c_module_relocs",
"(",
"self",
")",
":",
"if",
"self",
".",
"opts",
".",
"no_structs",
"or",
"self",
".",
"opts",
".",
"windll",
":",
"return",
"''",
",",
"''",
"x86",
"=",
"reloc_var",
"(",
"self",
".",
"name",
",",
"self",
".",
"_c_struct_n... | Build relocation for the module variable. | [
"Build",
"relocation",
"for",
"the",
"module",
"variable",
"."
] | python | train |
swistakm/graceful | src/graceful/validators.py | https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/validators.py#L48-L62 | def choices_validator(choices):
"""Return validator function that will check if ``value in choices``.
Args:
max_value (list, set, tuple): allowed choices for new validator
"""
def validator(value):
if value not in choices:
# note: make it a list for consistent representatio... | [
"def",
"choices_validator",
"(",
"choices",
")",
":",
"def",
"validator",
"(",
"value",
")",
":",
"if",
"value",
"not",
"in",
"choices",
":",
"# note: make it a list for consistent representation",
"raise",
"ValidationError",
"(",
"\"{} is not in {}\"",
".",
"format",... | Return validator function that will check if ``value in choices``.
Args:
max_value (list, set, tuple): allowed choices for new validator | [
"Return",
"validator",
"function",
"that",
"will",
"check",
"if",
"value",
"in",
"choices",
"."
] | python | train |
ic-labs/django-icekit | icekit_events/utils/timeutils.py | https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit_events/utils/timeutils.py#L31-L67 | def round_datetime(when=None, precision=60, rounding=ROUND_NEAREST):
"""
Round a datetime object to a time that matches the given precision.
when (datetime), default now
The datetime object to be rounded.
precision (int, timedelta, str), default 60
The number of seconds... | [
"def",
"round_datetime",
"(",
"when",
"=",
"None",
",",
"precision",
"=",
"60",
",",
"rounding",
"=",
"ROUND_NEAREST",
")",
":",
"when",
"=",
"when",
"or",
"djtz",
".",
"now",
"(",
")",
"weekday",
"=",
"WEEKDAYS",
".",
"get",
"(",
"precision",
",",
"... | Round a datetime object to a time that matches the given precision.
when (datetime), default now
The datetime object to be rounded.
precision (int, timedelta, str), default 60
The number of seconds, weekday (MON, TUE, WED, etc.) or timedelta
object to which the date... | [
"Round",
"a",
"datetime",
"object",
"to",
"a",
"time",
"that",
"matches",
"the",
"given",
"precision",
"."
] | python | train |
ska-sa/purr | Purr/Plugins/local_pychart/area.py | https://github.com/ska-sa/purr/blob/4c848768d0485d0f88b30850d0d5372221b21b66/Purr/Plugins/local_pychart/area.py#L118-L122 | def y_pos(self, yval):
"Return the y position (on the canvas) corresponding to YVAL."
off = self.y_coord.get_canvas_pos(self.size[1], yval,
self.y_range[0], self.y_range[1])
return self.loc[1] + off | [
"def",
"y_pos",
"(",
"self",
",",
"yval",
")",
":",
"off",
"=",
"self",
".",
"y_coord",
".",
"get_canvas_pos",
"(",
"self",
".",
"size",
"[",
"1",
"]",
",",
"yval",
",",
"self",
".",
"y_range",
"[",
"0",
"]",
",",
"self",
".",
"y_range",
"[",
"... | Return the y position (on the canvas) corresponding to YVAL. | [
"Return",
"the",
"y",
"position",
"(",
"on",
"the",
"canvas",
")",
"corresponding",
"to",
"YVAL",
"."
] | python | train |
randomir/plucky | plucky/__init__.py | https://github.com/randomir/plucky/blob/16b7b59aa19d619d8e619dc15dc7eeffc9fe078a/plucky/__init__.py#L144-L200 | def merge(a, b, op=None, recurse_list=False, max_depth=None):
"""Immutable merge ``a`` structure with ``b`` using binary operator ``op``
on leaf nodes. All nodes at, or below, ``max_depth`` are considered to be
leaf nodes.
Merged structure is returned, input data structures are not modified.
If ``... | [
"def",
"merge",
"(",
"a",
",",
"b",
",",
"op",
"=",
"None",
",",
"recurse_list",
"=",
"False",
",",
"max_depth",
"=",
"None",
")",
":",
"if",
"op",
"is",
"None",
":",
"op",
"=",
"operator",
".",
"add",
"if",
"max_depth",
"is",
"not",
"None",
":",... | Immutable merge ``a`` structure with ``b`` using binary operator ``op``
on leaf nodes. All nodes at, or below, ``max_depth`` are considered to be
leaf nodes.
Merged structure is returned, input data structures are not modified.
If ``recurse_list=True``, leaf lists of equal length will be merged on a
... | [
"Immutable",
"merge",
"a",
"structure",
"with",
"b",
"using",
"binary",
"operator",
"op",
"on",
"leaf",
"nodes",
".",
"All",
"nodes",
"at",
"or",
"below",
"max_depth",
"are",
"considered",
"to",
"be",
"leaf",
"nodes",
"."
] | python | train |
nion-software/nionswift-io | nionswift_plugin/TIFF_IO/tifffile.py | https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L9697-L9712 | def squeeze_axes(shape, axes, skip=None):
"""Return shape and axes with single-dimensional entries removed.
Remove unused dimensions unless their axes are listed in 'skip'.
>>> squeeze_axes((5, 1, 2, 1, 1), 'TZYXC')
((5, 2, 1), 'TYX')
"""
if len(shape) != len(axes):
raise ValueError('... | [
"def",
"squeeze_axes",
"(",
"shape",
",",
"axes",
",",
"skip",
"=",
"None",
")",
":",
"if",
"len",
"(",
"shape",
")",
"!=",
"len",
"(",
"axes",
")",
":",
"raise",
"ValueError",
"(",
"'dimensions of axes and shape do not match'",
")",
"if",
"skip",
"is",
... | Return shape and axes with single-dimensional entries removed.
Remove unused dimensions unless their axes are listed in 'skip'.
>>> squeeze_axes((5, 1, 2, 1, 1), 'TZYXC')
((5, 2, 1), 'TYX') | [
"Return",
"shape",
"and",
"axes",
"with",
"single",
"-",
"dimensional",
"entries",
"removed",
"."
] | python | train |
KelSolaar/Foundations | foundations/namespace.py | https://github.com/KelSolaar/Foundations/blob/5c141330faf09dad70a12bc321f4c564917d0a91/foundations/namespace.py#L98-L123 | def remove_namespace(attribute, namespace_splitter=NAMESPACE_SPLITTER, root_only=False):
"""
Returns attribute with stripped foundations.namespace.
Usage::
>>> remove_namespace("grandParent|parent|child")
u'child'
>>> remove_namespace("grandParent|parent|child", root_only=True)
... | [
"def",
"remove_namespace",
"(",
"attribute",
",",
"namespace_splitter",
"=",
"NAMESPACE_SPLITTER",
",",
"root_only",
"=",
"False",
")",
":",
"attribute_tokens",
"=",
"attribute",
".",
"split",
"(",
"namespace_splitter",
")",
"stripped_attribute",
"=",
"root_only",
"... | Returns attribute with stripped foundations.namespace.
Usage::
>>> remove_namespace("grandParent|parent|child")
u'child'
>>> remove_namespace("grandParent|parent|child", root_only=True)
u'parent|child'
:param attribute: Attribute.
:type attribute: unicode
:param namesp... | [
"Returns",
"attribute",
"with",
"stripped",
"foundations",
".",
"namespace",
"."
] | python | train |
orb-framework/orb | orb/core/query.py | https://github.com/orb-framework/orb/blob/575be2689cb269e65a0a2678232ff940acc19e5a/orb/core/query.py#L614-L631 | def columns(self, model=None):
"""
Returns a generator that loops through the columns that are associated with this query.
:return <generator>(orb.Column)
"""
column = self.column(model=model)
if column:
yield column
check = self.__value
... | [
"def",
"columns",
"(",
"self",
",",
"model",
"=",
"None",
")",
":",
"column",
"=",
"self",
".",
"column",
"(",
"model",
"=",
"model",
")",
"if",
"column",
":",
"yield",
"column",
"check",
"=",
"self",
".",
"__value",
"if",
"not",
"isinstance",
"(",
... | Returns a generator that loops through the columns that are associated with this query.
:return <generator>(orb.Column) | [
"Returns",
"a",
"generator",
"that",
"loops",
"through",
"the",
"columns",
"that",
"are",
"associated",
"with",
"this",
"query",
".",
":",
"return",
"<generator",
">",
"(",
"orb",
".",
"Column",
")"
] | python | train |
ppaquette/gym-pull | gym_pull/envs/registration.py | https://github.com/ppaquette/gym-pull/blob/5b2797fd081ba5be26544983d1eba764e6d9f73b/gym_pull/envs/registration.py#L63-L75 | def make(self):
"""Instantiates an instance of the environment with appropriate kwargs"""
if self._entry_point is None:
raise error.Error('Attempting to make deprecated env {}. (HINT: is there a newer registered version of this env?)'.format(self.id))
cls = load(self._entry_point)
... | [
"def",
"make",
"(",
"self",
")",
":",
"if",
"self",
".",
"_entry_point",
"is",
"None",
":",
"raise",
"error",
".",
"Error",
"(",
"'Attempting to make deprecated env {}. (HINT: is there a newer registered version of this env?)'",
".",
"format",
"(",
"self",
".",
"id",
... | Instantiates an instance of the environment with appropriate kwargs | [
"Instantiates",
"an",
"instance",
"of",
"the",
"environment",
"with",
"appropriate",
"kwargs"
] | python | train |
pytroll/trollimage | trollimage/image.py | https://github.com/pytroll/trollimage/blob/d35a7665ad475ff230e457085523e21f2cd3f454/trollimage/image.py#L963-L982 | def stretch_logarithmic(self, ch_nb, factor=100.):
"""Move data into range [1:factor] and do a normalized logarithmic
enhancement.
"""
logger.debug("Perform a logarithmic contrast stretch.")
if ((self.channels[ch_nb].size ==
np.ma.count_masked(self.channels[ch_nb])) ... | [
"def",
"stretch_logarithmic",
"(",
"self",
",",
"ch_nb",
",",
"factor",
"=",
"100.",
")",
":",
"logger",
".",
"debug",
"(",
"\"Perform a logarithmic contrast stretch.\"",
")",
"if",
"(",
"(",
"self",
".",
"channels",
"[",
"ch_nb",
"]",
".",
"size",
"==",
"... | Move data into range [1:factor] and do a normalized logarithmic
enhancement. | [
"Move",
"data",
"into",
"range",
"[",
"1",
":",
"factor",
"]",
"and",
"do",
"a",
"normalized",
"logarithmic",
"enhancement",
"."
] | python | train |
ladybug-tools/ladybug | ladybug/datatype/temperaturetime.py | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/datatype/temperaturetime.py#L46-L53 | def to_si(self, values, from_unit):
"""Return values in SI and the units to which the values have been converted."""
if from_unit in self._si_units:
return values, from_unit
elif from_unit == 'degF-hours':
return self.to_unit(values, 'degC-hours', from_unit), 'degC-hours'... | [
"def",
"to_si",
"(",
"self",
",",
"values",
",",
"from_unit",
")",
":",
"if",
"from_unit",
"in",
"self",
".",
"_si_units",
":",
"return",
"values",
",",
"from_unit",
"elif",
"from_unit",
"==",
"'degF-hours'",
":",
"return",
"self",
".",
"to_unit",
"(",
"... | Return values in SI and the units to which the values have been converted. | [
"Return",
"values",
"in",
"SI",
"and",
"the",
"units",
"to",
"which",
"the",
"values",
"have",
"been",
"converted",
"."
] | python | train |
Esri/ArcREST | src/arcrest/manageorg/_community.py | https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/manageorg/_community.py#L318-L330 | def __init(self):
"""loads the property data into the class"""
if self._portalId is None:
from .administration import Administration
portalSelf = Administration(url=self._securityHandler.org_url,
securityHandler=self._securityHandler,
... | [
"def",
"__init",
"(",
"self",
")",
":",
"if",
"self",
".",
"_portalId",
"is",
"None",
":",
"from",
".",
"administration",
"import",
"Administration",
"portalSelf",
"=",
"Administration",
"(",
"url",
"=",
"self",
".",
"_securityHandler",
".",
"org_url",
",",
... | loads the property data into the class | [
"loads",
"the",
"property",
"data",
"into",
"the",
"class"
] | python | train |
acutesoftware/AIKIF | aikif/dataTools/cls_datatable.py | https://github.com/acutesoftware/AIKIF/blob/fcf1582dc5f884b9a4fa7c6e20e9de9d94d21d03/aikif/dataTools/cls_datatable.py#L68-L74 | def describe_contents(self):
""" describes various contents of data table """
print('======================================================================')
print(self)
print('Table = ', str(len(self.header)) + ' cols x ' + str(len(self.arr)) + ' rows')
print('HEADER = ', self... | [
"def",
"describe_contents",
"(",
"self",
")",
":",
"print",
"(",
"'======================================================================'",
")",
"print",
"(",
"self",
")",
"print",
"(",
"'Table = '",
",",
"str",
"(",
"len",
"(",
"self",
".",
"header",
")",
")",
... | describes various contents of data table | [
"describes",
"various",
"contents",
"of",
"data",
"table"
] | python | train |
Mxit/python-mxit | mxit/oauth.py | https://github.com/Mxit/python-mxit/blob/6b18a54ef6fbfe1f9d94755ba3d4ad77743c8b0c/mxit/oauth.py#L113-L147 | def get_app_token(self, scope):
"""Gets the app auth token"""
app_token = self.__get_app_token(scope)
if app_token:
return app_token
if self.__cache is not None:
token = self.__cache.get(self.__app_token_cache_key(scope))
if token:
r... | [
"def",
"get_app_token",
"(",
"self",
",",
"scope",
")",
":",
"app_token",
"=",
"self",
".",
"__get_app_token",
"(",
"scope",
")",
"if",
"app_token",
":",
"return",
"app_token",
"if",
"self",
".",
"__cache",
"is",
"not",
"None",
":",
"token",
"=",
"self",... | Gets the app auth token | [
"Gets",
"the",
"app",
"auth",
"token"
] | python | train |
twilio/twilio-python | twilio/rest/sync/v1/service/sync_stream/__init__.py | https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/sync/v1/service/sync_stream/__init__.py#L350-L364 | def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: SyncStreamContext for this SyncStreamInstance
:rtype: twilio.rest.sync.v1.service.sync_stream.Syn... | [
"def",
"_proxy",
"(",
"self",
")",
":",
"if",
"self",
".",
"_context",
"is",
"None",
":",
"self",
".",
"_context",
"=",
"SyncStreamContext",
"(",
"self",
".",
"_version",
",",
"service_sid",
"=",
"self",
".",
"_solution",
"[",
"'service_sid'",
"]",
",",
... | Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: SyncStreamContext for this SyncStreamInstance
:rtype: twilio.rest.sync.v1.service.sync_stream.SyncStreamContext | [
"Generate",
"an",
"instance",
"context",
"for",
"the",
"instance",
"the",
"context",
"is",
"capable",
"of",
"performing",
"various",
"actions",
".",
"All",
"instance",
"actions",
"are",
"proxied",
"to",
"the",
"context"
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.