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 |
|---|---|---|---|---|---|---|---|---|
tensorflow/datasets | tensorflow_datasets/image/open_images.py | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/image/open_images.py#L221-L262 | def _split_generators(self, dl_manager):
"""Returns SplitGenerators."""
paths = dl_manager.download_and_extract(_URLS)
# Load labels from CSVs:
def load(names):
csv_positions = [0] * len(names)
return functools.partial(_load_objects, [paths[name] for name in names],
... | [
"def",
"_split_generators",
"(",
"self",
",",
"dl_manager",
")",
":",
"paths",
"=",
"dl_manager",
".",
"download_and_extract",
"(",
"_URLS",
")",
"# Load labels from CSVs:",
"def",
"load",
"(",
"names",
")",
":",
"csv_positions",
"=",
"[",
"0",
"]",
"*",
"le... | Returns SplitGenerators. | [
"Returns",
"SplitGenerators",
"."
] | python | train |
portfors-lab/sparkle | sparkle/tools/audiotools.py | https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/tools/audiotools.py#L53-L64 | def calc_spectrum(signal, rate):
"""Return the spectrum and frequency indexes for real-valued input signal"""
npts = len(signal)
padto = 1 << (npts - 1).bit_length()
# print 'length of signal {}, pad to {}'.format(npts, padto)
npts = padto
sp = np.fft.rfft(signal, n=padto) / npts
# print('s... | [
"def",
"calc_spectrum",
"(",
"signal",
",",
"rate",
")",
":",
"npts",
"=",
"len",
"(",
"signal",
")",
"padto",
"=",
"1",
"<<",
"(",
"npts",
"-",
"1",
")",
".",
"bit_length",
"(",
")",
"# print 'length of signal {}, pad to {}'.format(npts, padto)",
"npts",
"=... | Return the spectrum and frequency indexes for real-valued input signal | [
"Return",
"the",
"spectrum",
"and",
"frequency",
"indexes",
"for",
"real",
"-",
"valued",
"input",
"signal"
] | python | train |
vsoch/helpme | helpme/main/base/settings.py | https://github.com/vsoch/helpme/blob/e609172260b10cddadb2d2023ab26da8082a9feb/helpme/main/base/settings.py#L155-L193 | def get_setting(self, name, section=None, default=None, user=True):
'''return a setting from the environment (first priority) and then
secrets (second priority) if one can be found. If not, return None.
Parameters
==========
section: the section in the config, defaults to self.name
... | [
"def",
"get_setting",
"(",
"self",
",",
"name",
",",
"section",
"=",
"None",
",",
"default",
"=",
"None",
",",
"user",
"=",
"True",
")",
":",
"loader",
"=",
"self",
".",
"_load_config_user",
"if",
"not",
"user",
":",
"loader",
"=",
"self",
".",
"_loa... | return a setting from the environment (first priority) and then
secrets (second priority) if one can be found. If not, return None.
Parameters
==========
section: the section in the config, defaults to self.name
name: they key (index) of the setting to look up
default: (option... | [
"return",
"a",
"setting",
"from",
"the",
"environment",
"(",
"first",
"priority",
")",
"and",
"then",
"secrets",
"(",
"second",
"priority",
")",
"if",
"one",
"can",
"be",
"found",
".",
"If",
"not",
"return",
"None",
"."
] | python | train |
HazyResearch/metal | metal/tuners/random_tuner.py | https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/tuners/random_tuner.py#L14-L86 | def search(
self,
search_space,
valid_data,
init_args=[],
train_args=[],
init_kwargs={},
train_kwargs={},
module_args={},
module_kwargs={},
max_search=None,
shuffle=True,
verbose=True,
clean_up=True,
seed=Non... | [
"def",
"search",
"(",
"self",
",",
"search_space",
",",
"valid_data",
",",
"init_args",
"=",
"[",
"]",
",",
"train_args",
"=",
"[",
"]",
",",
"init_kwargs",
"=",
"{",
"}",
",",
"train_kwargs",
"=",
"{",
"}",
",",
"module_args",
"=",
"{",
"}",
",",
... | Args:
search_space: see config_generator() documentation
valid_data: a tuple of Tensors (X,Y), a Dataset, or a DataLoader of
X (data) and Y (labels) for the dev split
init_args: (list) positional args for initializing the model
train_args: (list) positiona... | [
"Args",
":",
"search_space",
":",
"see",
"config_generator",
"()",
"documentation",
"valid_data",
":",
"a",
"tuple",
"of",
"Tensors",
"(",
"X",
"Y",
")",
"a",
"Dataset",
"or",
"a",
"DataLoader",
"of",
"X",
"(",
"data",
")",
"and",
"Y",
"(",
"labels",
"... | python | train |
gofed/gofedlib | gofedlib/repository/githubclient.py | https://github.com/gofed/gofedlib/blob/0674c248fe3d8706f98f912996b65af469f96b10/gofedlib/repository/githubclient.py#L69-L80 | def commit(self, commit):
"""Get data for a given commit
Raises KeyError if a commit is not found or not parsed.
:param commit: repository commit
:type commit: string
"""
try:
return self._commitData(self.repo.get_commit(commit))
except (ValueError, KeyError, GithubException):
raise KeyError("Com... | [
"def",
"commit",
"(",
"self",
",",
"commit",
")",
":",
"try",
":",
"return",
"self",
".",
"_commitData",
"(",
"self",
".",
"repo",
".",
"get_commit",
"(",
"commit",
")",
")",
"except",
"(",
"ValueError",
",",
"KeyError",
",",
"GithubException",
")",
":... | Get data for a given commit
Raises KeyError if a commit is not found or not parsed.
:param commit: repository commit
:type commit: string | [
"Get",
"data",
"for",
"a",
"given",
"commit"
] | python | train |
fumitoh/modelx | modelx/io/excel.py | https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/io/excel.py#L161-L241 | def _get_namedrange(book, rangename, sheetname=None):
"""Get range from a workbook.
A workbook can contain multiple definitions for a single name,
as a name can be defined for the entire book or for
a particular sheet.
If sheet is None, the book-wide def is searched,
otherwise sheet-local def ... | [
"def",
"_get_namedrange",
"(",
"book",
",",
"rangename",
",",
"sheetname",
"=",
"None",
")",
":",
"def",
"cond",
"(",
"namedef",
")",
":",
"if",
"namedef",
".",
"type",
".",
"upper",
"(",
")",
"==",
"\"RANGE\"",
":",
"if",
"namedef",
".",
"name",
"."... | Get range from a workbook.
A workbook can contain multiple definitions for a single name,
as a name can be defined for the entire book or for
a particular sheet.
If sheet is None, the book-wide def is searched,
otherwise sheet-local def is looked up.
Args:
book: An openpyxl workbook o... | [
"Get",
"range",
"from",
"a",
"workbook",
"."
] | python | valid |
eerimoq/bitstruct | bitstruct.py | https://github.com/eerimoq/bitstruct/blob/8e887c10241aa51c2a77c10e9923bb3978b15bcb/bitstruct.py#L523-L534 | def pack_into(fmt, buf, offset, *args, **kwargs):
"""Pack given values v1, v2, ... into given bytearray `buf`, starting
at given bit offset `offset`. Pack according to given format
string `fmt`. Give `fill_padding` as ``False`` to leave padding
bits in `buf` unmodified.
"""
return CompiledForm... | [
"def",
"pack_into",
"(",
"fmt",
",",
"buf",
",",
"offset",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"CompiledFormat",
"(",
"fmt",
")",
".",
"pack_into",
"(",
"buf",
",",
"offset",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
"... | Pack given values v1, v2, ... into given bytearray `buf`, starting
at given bit offset `offset`. Pack according to given format
string `fmt`. Give `fill_padding` as ``False`` to leave padding
bits in `buf` unmodified. | [
"Pack",
"given",
"values",
"v1",
"v2",
"...",
"into",
"given",
"bytearray",
"buf",
"starting",
"at",
"given",
"bit",
"offset",
"offset",
".",
"Pack",
"according",
"to",
"given",
"format",
"string",
"fmt",
".",
"Give",
"fill_padding",
"as",
"False",
"to",
"... | python | valid |
clalancette/pycdlib | pycdlib/pycdlib.py | https://github.com/clalancette/pycdlib/blob/1e7b77a809e905d67dc71e12d70e850be26b6233/pycdlib/pycdlib.py#L5489-L5528 | def get_record(self, **kwargs):
# type: (str) -> Union[dr.DirectoryRecord, udfmod.UDFFileEntry]
'''
Get the directory record for a particular path.
Parameters:
iso_path - The absolute path on the ISO9660 filesystem to get the
record for.
rr_path - T... | [
"def",
"get_record",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# type: (str) -> Union[dr.DirectoryRecord, udfmod.UDFFileEntry]",
"if",
"not",
"self",
".",
"_initialized",
":",
"raise",
"pycdlibexception",
".",
"PyCdlibInvalidInput",
"(",
"'This object is not yet in... | Get the directory record for a particular path.
Parameters:
iso_path - The absolute path on the ISO9660 filesystem to get the
record for.
rr_path - The absolute path on the Rock Ridge filesystem to get the
record for.
joliet_path - The absolute ... | [
"Get",
"the",
"directory",
"record",
"for",
"a",
"particular",
"path",
"."
] | python | train |
niccokunzmann/ObservableList | ObservableList/__init__.py | https://github.com/niccokunzmann/ObservableList/blob/e5f6a93d82d2d13b248c7840ae74f98a4ba58c90/ObservableList/__init__.py#L252-L261 | def pop(self, index=-1):
"""See list.pop."""
if not isinstance(index, int):
if PY2:
raise TypeError('an integer is required')
raise TypeError("'str' object cannot be interpreted as an integer")
length = len(self)
if -length <= index < length:
... | [
"def",
"pop",
"(",
"self",
",",
"index",
"=",
"-",
"1",
")",
":",
"if",
"not",
"isinstance",
"(",
"index",
",",
"int",
")",
":",
"if",
"PY2",
":",
"raise",
"TypeError",
"(",
"'an integer is required'",
")",
"raise",
"TypeError",
"(",
"\"'str' object cann... | See list.pop. | [
"See",
"list",
".",
"pop",
"."
] | python | train |
rigetti/pyquil | pyquil/api/_qpu.py | https://github.com/rigetti/pyquil/blob/ec98e453084b0037d69d8c3245f6822a5422593d/pyquil/api/_qpu.py#L273-L294 | def _resolve_memory_references(self, expression: Expression) -> Union[float, int]:
"""
Traverse the given Expression, and replace any Memory References with whatever values
have been so far provided by the user for those memory spaces. Declared memory defaults
to zero.
:param ex... | [
"def",
"_resolve_memory_references",
"(",
"self",
",",
"expression",
":",
"Expression",
")",
"->",
"Union",
"[",
"float",
",",
"int",
"]",
":",
"if",
"isinstance",
"(",
"expression",
",",
"BinaryExp",
")",
":",
"left",
"=",
"self",
".",
"_resolve_memory_refe... | Traverse the given Expression, and replace any Memory References with whatever values
have been so far provided by the user for those memory spaces. Declared memory defaults
to zero.
:param expression: an Expression | [
"Traverse",
"the",
"given",
"Expression",
"and",
"replace",
"any",
"Memory",
"References",
"with",
"whatever",
"values",
"have",
"been",
"so",
"far",
"provided",
"by",
"the",
"user",
"for",
"those",
"memory",
"spaces",
".",
"Declared",
"memory",
"defaults",
"t... | python | train |
Alignak-monitoring/alignak | alignak/objects/item.py | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/item.py#L1427-L1454 | def linkify_with_timeperiods(self, timeperiods, prop):
"""
Link items with timeperiods items
:param timeperiods: all timeperiods object
:type timeperiods: alignak.objects.timeperiod.Timeperiods
:param prop: property name
:type prop: str
:return: None
"""
... | [
"def",
"linkify_with_timeperiods",
"(",
"self",
",",
"timeperiods",
",",
"prop",
")",
":",
"for",
"i",
"in",
"self",
":",
"if",
"not",
"hasattr",
"(",
"i",
",",
"prop",
")",
":",
"continue",
"tpname",
"=",
"getattr",
"(",
"i",
",",
"prop",
")",
".",
... | Link items with timeperiods items
:param timeperiods: all timeperiods object
:type timeperiods: alignak.objects.timeperiod.Timeperiods
:param prop: property name
:type prop: str
:return: None | [
"Link",
"items",
"with",
"timeperiods",
"items"
] | python | train |
grahambell/pymoc | lib/pymoc/util/tool.py | https://github.com/grahambell/pymoc/blob/0e2e57ce07ff3de6ac024627c1fb6ad30c2fde48/lib/pymoc/util/tool.py#L307-L322 | def normalize(self):
"""Normalize the MOC to a given order.
This command takes a MOC order (0-29) and normalizes the MOC so that
its maximum order is the given order.
::
pymoctool a.fits --normalize 10 --output a_10.fits
"""
if self.moc is None:
... | [
"def",
"normalize",
"(",
"self",
")",
":",
"if",
"self",
".",
"moc",
"is",
"None",
":",
"raise",
"CommandError",
"(",
"'No MOC information present for normalization'",
")",
"order",
"=",
"int",
"(",
"self",
".",
"params",
".",
"pop",
"(",
")",
")",
"self",... | Normalize the MOC to a given order.
This command takes a MOC order (0-29) and normalizes the MOC so that
its maximum order is the given order.
::
pymoctool a.fits --normalize 10 --output a_10.fits | [
"Normalize",
"the",
"MOC",
"to",
"a",
"given",
"order",
"."
] | python | train |
materialsproject/pymatgen | pymatgen/core/tensors.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/core/tensors.py#L437-L512 | def get_ieee_rotation(structure, refine_rotation=True):
"""
Given a structure associated with a tensor, determines
the rotation matrix for IEEE conversion according to
the 1987 IEEE standards.
Args:
structure (Structure): a structure associated with the
... | [
"def",
"get_ieee_rotation",
"(",
"structure",
",",
"refine_rotation",
"=",
"True",
")",
":",
"# Check conventional setting:",
"sga",
"=",
"SpacegroupAnalyzer",
"(",
"structure",
")",
"dataset",
"=",
"sga",
".",
"get_symmetry_dataset",
"(",
")",
"trans_mat",
"=",
"... | Given a structure associated with a tensor, determines
the rotation matrix for IEEE conversion according to
the 1987 IEEE standards.
Args:
structure (Structure): a structure associated with the
tensor to be converted to the IEEE standard
refine_rotation (... | [
"Given",
"a",
"structure",
"associated",
"with",
"a",
"tensor",
"determines",
"the",
"rotation",
"matrix",
"for",
"IEEE",
"conversion",
"according",
"to",
"the",
"1987",
"IEEE",
"standards",
"."
] | python | train |
pandas-dev/pandas | pandas/tseries/holiday.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/tseries/holiday.py#L75-L84 | def nearest_workday(dt):
"""
If holiday falls on Saturday, use day before (Friday) instead;
if holiday falls on Sunday, use day thereafter (Monday) instead.
"""
if dt.weekday() == 5:
return dt - timedelta(1)
elif dt.weekday() == 6:
return dt + timedelta(1)
return dt | [
"def",
"nearest_workday",
"(",
"dt",
")",
":",
"if",
"dt",
".",
"weekday",
"(",
")",
"==",
"5",
":",
"return",
"dt",
"-",
"timedelta",
"(",
"1",
")",
"elif",
"dt",
".",
"weekday",
"(",
")",
"==",
"6",
":",
"return",
"dt",
"+",
"timedelta",
"(",
... | If holiday falls on Saturday, use day before (Friday) instead;
if holiday falls on Sunday, use day thereafter (Monday) instead. | [
"If",
"holiday",
"falls",
"on",
"Saturday",
"use",
"day",
"before",
"(",
"Friday",
")",
"instead",
";",
"if",
"holiday",
"falls",
"on",
"Sunday",
"use",
"day",
"thereafter",
"(",
"Monday",
")",
"instead",
"."
] | python | train |
MisterWil/skybellpy | skybellpy/device.py | https://github.com/MisterWil/skybellpy/blob/ac966d9f590cda7654f6de7eecc94e2103459eef/skybellpy/device.py#L342-L385 | def _validate_setting(setting, value):
"""Validate the setting and value."""
if setting not in CONST.ALL_SETTINGS:
raise SkybellException(ERROR.INVALID_SETTING, setting)
if setting == CONST.SETTINGS_DO_NOT_DISTURB:
if value not in CONST.SETTINGS_DO_NOT_DISTURB_VALUES:
raise Skyb... | [
"def",
"_validate_setting",
"(",
"setting",
",",
"value",
")",
":",
"if",
"setting",
"not",
"in",
"CONST",
".",
"ALL_SETTINGS",
":",
"raise",
"SkybellException",
"(",
"ERROR",
".",
"INVALID_SETTING",
",",
"setting",
")",
"if",
"setting",
"==",
"CONST",
".",
... | Validate the setting and value. | [
"Validate",
"the",
"setting",
"and",
"value",
"."
] | python | train |
StackStorm/pybind | pybind/nos/v7_2_0/interface/hundredgigabitethernet/__init__.py | https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/nos/v7_2_0/interface/hundredgigabitethernet/__init__.py#L1672-L1693 | def _set_bpdu_drop(self, v, load=False):
"""
Setter method for bpdu_drop, mapped from YANG variable /interface/hundredgigabitethernet/bpdu_drop (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_bpdu_drop is considered as a private
method. Backends looking t... | [
"def",
"_set_bpdu_drop",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"base... | Setter method for bpdu_drop, mapped from YANG variable /interface/hundredgigabitethernet/bpdu_drop (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_bpdu_drop is considered as a private
method. Backends looking to populate this variable should
do so via calling... | [
"Setter",
"method",
"for",
"bpdu_drop",
"mapped",
"from",
"YANG",
"variable",
"/",
"interface",
"/",
"hundredgigabitethernet",
"/",
"bpdu_drop",
"(",
"container",
")",
"If",
"this",
"variable",
"is",
"read",
"-",
"only",
"(",
"config",
":",
"false",
")",
"in... | python | train |
rigetti/grove | grove/measurements/term_grouping.py | https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/measurements/term_grouping.py#L121-L136 | def check_trivial_commutation(pauli_list, single_pauli_term):
"""
Check if a PauliTerm trivially commutes with a list of other terms.
:param list pauli_list: A list of PauliTerm objects
:param PauliTerm single_pauli_term: A PauliTerm object
:returns: True if pauli_two object commutes with pauli_lis... | [
"def",
"check_trivial_commutation",
"(",
"pauli_list",
",",
"single_pauli_term",
")",
":",
"if",
"not",
"isinstance",
"(",
"pauli_list",
",",
"list",
")",
":",
"raise",
"TypeError",
"(",
"\"pauli_list should be a list\"",
")",
"for",
"term",
"in",
"pauli_list",
":... | Check if a PauliTerm trivially commutes with a list of other terms.
:param list pauli_list: A list of PauliTerm objects
:param PauliTerm single_pauli_term: A PauliTerm object
:returns: True if pauli_two object commutes with pauli_list, False otherwise
:rtype: bool | [
"Check",
"if",
"a",
"PauliTerm",
"trivially",
"commutes",
"with",
"a",
"list",
"of",
"other",
"terms",
"."
] | python | train |
bitlabstudio/django-development-fabfile | development_fabfile/fabfile/utils.py | https://github.com/bitlabstudio/django-development-fabfile/blob/a135c6eb5bdd0b496a7eccfd271aca558dd99243/development_fabfile/fabfile/utils.py#L9-L26 | def require_server(fn):
"""
Checks if the user has called the task with a server name.
Fabric tasks decorated with this decorator must be called like so::
fab <server name> <task name>
If no server name is given, the task will not be executed.
"""
@wraps(fn)
def wrapper(*args, **... | [
"def",
"require_server",
"(",
"fn",
")",
":",
"@",
"wraps",
"(",
"fn",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"env",
".",
"machine",
"is",
"None",
":",
"abort",
"(",
"red",
"(",
"'ERROR: You must provide a s... | Checks if the user has called the task with a server name.
Fabric tasks decorated with this decorator must be called like so::
fab <server name> <task name>
If no server name is given, the task will not be executed. | [
"Checks",
"if",
"the",
"user",
"has",
"called",
"the",
"task",
"with",
"a",
"server",
"name",
"."
] | python | train |
kkinder/NdbSearchableBase | NdbSearchableBase/SearchableModel.py | https://github.com/kkinder/NdbSearchableBase/blob/4f999336b464704a0929cec135c1f09fb1ddfb7c/NdbSearchableBase/SearchableModel.py#L49-L94 | def search(cls,
query_string,
options=None,
enable_facet_discovery=False,
return_facets=None,
facet_options=None,
facet_refinements=None,
deadline=None,
**kwargs):
"""
Searches the ind... | [
"def",
"search",
"(",
"cls",
",",
"query_string",
",",
"options",
"=",
"None",
",",
"enable_facet_discovery",
"=",
"False",
",",
"return_facets",
"=",
"None",
",",
"facet_options",
"=",
"None",
",",
"facet_refinements",
"=",
"None",
",",
"deadline",
"=",
"No... | Searches the index. Conveniently searches only for documents that belong to instances of this class.
:param query_string: The query to match against documents in the index. See search.Query() for details.
:param options: A QueryOptions describing post-processing of search results.
:param enable... | [
"Searches",
"the",
"index",
".",
"Conveniently",
"searches",
"only",
"for",
"documents",
"that",
"belong",
"to",
"instances",
"of",
"this",
"class",
"."
] | python | train |
user-cont/conu | conu/backend/podman/image.py | https://github.com/user-cont/conu/blob/08caae7bb6bdd265b55bb106c3da6a7946a5a352/conu/backend/podman/image.py#L416-L425 | def get_metadata(self):
"""
Provide metadata about this image.
:return: ImageMetadata, Image metadata instance
"""
if self._metadata is None:
self._metadata = ImageMetadata()
inspect_to_metadata(self._metadata, self.inspect(refresh=True))
return self.... | [
"def",
"get_metadata",
"(",
"self",
")",
":",
"if",
"self",
".",
"_metadata",
"is",
"None",
":",
"self",
".",
"_metadata",
"=",
"ImageMetadata",
"(",
")",
"inspect_to_metadata",
"(",
"self",
".",
"_metadata",
",",
"self",
".",
"inspect",
"(",
"refresh",
... | Provide metadata about this image.
:return: ImageMetadata, Image metadata instance | [
"Provide",
"metadata",
"about",
"this",
"image",
"."
] | python | train |
econ-ark/HARK | HARK/core.py | https://github.com/econ-ark/HARK/blob/3d184153a189e618a87c9540df1cd12044039cc5/HARK/core.py#L494-L534 | def makeShockHistory(self):
'''
Makes a pre-specified history of shocks for the simulation. Shock variables should be named
in self.shock_vars, a list of strings that is subclass-specific. This method runs a subset
of the standard simulation loop by simulating only mortality and shocks... | [
"def",
"makeShockHistory",
"(",
"self",
")",
":",
"# Make sure time is flowing forward and re-initialize the simulation",
"orig_time",
"=",
"self",
".",
"time_flow",
"self",
".",
"timeFwd",
"(",
")",
"self",
".",
"initializeSim",
"(",
")",
"# Make blank history arrays for... | Makes a pre-specified history of shocks for the simulation. Shock variables should be named
in self.shock_vars, a list of strings that is subclass-specific. This method runs a subset
of the standard simulation loop by simulating only mortality and shocks; each variable named
in shock_vars is s... | [
"Makes",
"a",
"pre",
"-",
"specified",
"history",
"of",
"shocks",
"for",
"the",
"simulation",
".",
"Shock",
"variables",
"should",
"be",
"named",
"in",
"self",
".",
"shock_vars",
"a",
"list",
"of",
"strings",
"that",
"is",
"subclass",
"-",
"specific",
".",... | python | train |
dgomes/pyipma | pyipma/station.py | https://github.com/dgomes/pyipma/blob/cd808abeb70dca0e336afdf55bef3f73973eaa71/pyipma/station.py#L37-L48 | async def get(cls, websession, lat, lon):
"""Retrieve the nearest station."""
self = Station(websession)
stations = await self.api.stations()
self.station = self._filter_closest(lat, lon, stations)
logger.info("Using %s as weather station", self.station.local)
... | [
"async",
"def",
"get",
"(",
"cls",
",",
"websession",
",",
"lat",
",",
"lon",
")",
":",
"self",
"=",
"Station",
"(",
"websession",
")",
"stations",
"=",
"await",
"self",
".",
"api",
".",
"stations",
"(",
")",
"self",
".",
"station",
"=",
"self",
".... | Retrieve the nearest station. | [
"Retrieve",
"the",
"nearest",
"station",
"."
] | python | train |
mfcloud/python-zvm-sdk | zvmsdk/smtclient.py | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/smtclient.py#L1580-L1658 | def _couple_nic(self, userid, vdev, vswitch_name,
active=False):
"""Couple NIC to vswitch by adding vswitch into user direct."""
if active:
self._is_active(userid)
msg = ('Start to couple nic device %(vdev)s of guest %(vm)s '
'with vswitch %(vsw)s'... | [
"def",
"_couple_nic",
"(",
"self",
",",
"userid",
",",
"vdev",
",",
"vswitch_name",
",",
"active",
"=",
"False",
")",
":",
"if",
"active",
":",
"self",
".",
"_is_active",
"(",
"userid",
")",
"msg",
"=",
"(",
"'Start to couple nic device %(vdev)s of guest %(vm)... | Couple NIC to vswitch by adding vswitch into user direct. | [
"Couple",
"NIC",
"to",
"vswitch",
"by",
"adding",
"vswitch",
"into",
"user",
"direct",
"."
] | python | train |
pypa/pipenv | pipenv/vendor/ptyprocess/ptyprocess.py | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/ptyprocess/ptyprocess.py#L830-L836 | def write(self, s):
"""Write the unicode string ``s`` to the pseudoterminal.
Returns the number of bytes written.
"""
b = s.encode(self.encoding)
return super(PtyProcessUnicode, self).write(b) | [
"def",
"write",
"(",
"self",
",",
"s",
")",
":",
"b",
"=",
"s",
".",
"encode",
"(",
"self",
".",
"encoding",
")",
"return",
"super",
"(",
"PtyProcessUnicode",
",",
"self",
")",
".",
"write",
"(",
"b",
")"
] | Write the unicode string ``s`` to the pseudoterminal.
Returns the number of bytes written. | [
"Write",
"the",
"unicode",
"string",
"s",
"to",
"the",
"pseudoterminal",
"."
] | python | train |
heikomuller/sco-client | scocli/__init__.py | https://github.com/heikomuller/sco-client/blob/c4afab71297f73003379bba4c1679be9dcf7cef8/scocli/__init__.py#L140-L162 | def get_api_references(self, api_url=None):
"""Get set of HATEOAS reference for the given SCO-API. Use the default
SCO-API if none is given. References are cached as they are not expected
to change.
Parameters
----------
Returns
-------
"""
# Get... | [
"def",
"get_api_references",
"(",
"self",
",",
"api_url",
"=",
"None",
")",
":",
"# Get subject listing Url for SCO-API",
"if",
"not",
"api_url",
"is",
"None",
":",
"url",
"=",
"api_url",
"else",
":",
"url",
"=",
"self",
".",
"api_url",
"# Check if API reference... | Get set of HATEOAS reference for the given SCO-API. Use the default
SCO-API if none is given. References are cached as they are not expected
to change.
Parameters
----------
Returns
------- | [
"Get",
"set",
"of",
"HATEOAS",
"reference",
"for",
"the",
"given",
"SCO",
"-",
"API",
".",
"Use",
"the",
"default",
"SCO",
"-",
"API",
"if",
"none",
"is",
"given",
".",
"References",
"are",
"cached",
"as",
"they",
"are",
"not",
"expected",
"to",
"chang... | python | train |
elastic/apm-agent-python | elasticapm/traces.py | https://github.com/elastic/apm-agent-python/blob/2975663d7bd22282dc39336b2c37b37c12c7a774/elasticapm/traces.py#L293-L312 | def begin_transaction(self, transaction_type, trace_parent=None):
"""
Start a new transactions and bind it in a thread-local variable
:returns the Transaction object
"""
if trace_parent:
is_sampled = bool(trace_parent.trace_options.recorded)
else:
... | [
"def",
"begin_transaction",
"(",
"self",
",",
"transaction_type",
",",
"trace_parent",
"=",
"None",
")",
":",
"if",
"trace_parent",
":",
"is_sampled",
"=",
"bool",
"(",
"trace_parent",
".",
"trace_options",
".",
"recorded",
")",
"else",
":",
"is_sampled",
"=",... | Start a new transactions and bind it in a thread-local variable
:returns the Transaction object | [
"Start",
"a",
"new",
"transactions",
"and",
"bind",
"it",
"in",
"a",
"thread",
"-",
"local",
"variable"
] | python | train |
polyaxon/polyaxon | polyaxon/db/models/experiments.py | https://github.com/polyaxon/polyaxon/blob/e1724f0756b1a42f9e7aa08a976584a84ef7f016/polyaxon/db/models/experiments.py#L205-L207 | def has_running_jobs(self) -> bool:
""""Return a boolean indicating if the experiment has any running jobs"""
return self.jobs.exclude(status__status__in=ExperimentLifeCycle.DONE_STATUS).exists() | [
"def",
"has_running_jobs",
"(",
"self",
")",
"->",
"bool",
":",
"return",
"self",
".",
"jobs",
".",
"exclude",
"(",
"status__status__in",
"=",
"ExperimentLifeCycle",
".",
"DONE_STATUS",
")",
".",
"exists",
"(",
")"
] | Return a boolean indicating if the experiment has any running jobs | [
"Return",
"a",
"boolean",
"indicating",
"if",
"the",
"experiment",
"has",
"any",
"running",
"jobs"
] | python | train |
anti1869/sunhead | src/sunhead/workers/http/ext/runtime.py | https://github.com/anti1869/sunhead/blob/5117ec797a38eb82d955241d20547d125efe80f3/src/sunhead/workers/http/ext/runtime.py#L56-L63 | async def get(self):
"""Printing runtime statistics in JSON"""
context_data = self.get_context_data()
context_data.update(getattr(self.request.app, "stats", {}))
response = self.json_response(context_data)
return response | [
"async",
"def",
"get",
"(",
"self",
")",
":",
"context_data",
"=",
"self",
".",
"get_context_data",
"(",
")",
"context_data",
".",
"update",
"(",
"getattr",
"(",
"self",
".",
"request",
".",
"app",
",",
"\"stats\"",
",",
"{",
"}",
")",
")",
"response",... | Printing runtime statistics in JSON | [
"Printing",
"runtime",
"statistics",
"in",
"JSON"
] | python | train |
TadLeonard/tfatool | tfatool/sync.py | https://github.com/TadLeonard/tfatool/blob/12da2807b5fb538c5317ef255d846b32ceb174d0/tfatool/sync.py#L83-L115 | def up_down_by_arrival(*filters, local_dir=".",
remote_dir=DEFAULT_REMOTE_DIR):
"""Monitors a local directory and a remote FlashAir directory and
generates sets of new files to be uploaded or downloaded.
Sets to upload are generated in a tuple
like (Direction.up, {...}), while dow... | [
"def",
"up_down_by_arrival",
"(",
"*",
"filters",
",",
"local_dir",
"=",
"\".\"",
",",
"remote_dir",
"=",
"DEFAULT_REMOTE_DIR",
")",
":",
"local_monitor",
"=",
"watch_local_files",
"(",
"*",
"filters",
",",
"local_dir",
"=",
"local_dir",
")",
"remote_monitor",
"... | Monitors a local directory and a remote FlashAir directory and
generates sets of new files to be uploaded or downloaded.
Sets to upload are generated in a tuple
like (Direction.up, {...}), while download sets to download
are generated in a tuple like (Direction.down, {...}). The generator yields
bef... | [
"Monitors",
"a",
"local",
"directory",
"and",
"a",
"remote",
"FlashAir",
"directory",
"and",
"generates",
"sets",
"of",
"new",
"files",
"to",
"be",
"uploaded",
"or",
"downloaded",
".",
"Sets",
"to",
"upload",
"are",
"generated",
"in",
"a",
"tuple",
"like",
... | python | train |
aetros/aetros-cli | aetros/logger.py | https://github.com/aetros/aetros-cli/blob/a2a1f38d6af1660e1e2680c7d413ec2aef45faab/aetros/logger.py#L69-L143 | def attach(self, buffer, read_line=None):
"""
Read buffer until end (read() returns '') and sends it to self.logger and self.job_backend.
:param buffer: a buffer instance with block read() or readline() method
:param read_line: callable or True to read line per line. If callable is give... | [
"def",
"attach",
"(",
"self",
",",
"buffer",
",",
"read_line",
"=",
"None",
")",
":",
"bid",
"=",
"id",
"(",
"buffer",
")",
"self",
".",
"attach_last_messages",
"[",
"bid",
"]",
"=",
"b''",
"def",
"reader",
"(",
")",
":",
"current_line",
"=",
"b''",
... | Read buffer until end (read() returns '') and sends it to self.logger and self.job_backend.
:param buffer: a buffer instance with block read() or readline() method
:param read_line: callable or True to read line per line. If callable is given, it will be executed per line
and ... | [
"Read",
"buffer",
"until",
"end",
"(",
"read",
"()",
"returns",
")",
"and",
"sends",
"it",
"to",
"self",
".",
"logger",
"and",
"self",
".",
"job_backend",
"."
] | python | train |
erinxocon/requests-xml | requests_xml.py | https://github.com/erinxocon/requests-xml/blob/923571ceae4ddd4f2f57a2fc8780d89b50f3e7a1/requests_xml.py#L133-L135 | def links(self) -> _Links:
"""All found links on page, in as–is form. Only works for Atom feeds."""
return list(set(x.text for x in self.xpath('//link'))) | [
"def",
"links",
"(",
"self",
")",
"->",
"_Links",
":",
"return",
"list",
"(",
"set",
"(",
"x",
".",
"text",
"for",
"x",
"in",
"self",
".",
"xpath",
"(",
"'//link'",
")",
")",
")"
] | All found links on page, in as–is form. Only works for Atom feeds. | [
"All",
"found",
"links",
"on",
"page",
"in",
"as–is",
"form",
".",
"Only",
"works",
"for",
"Atom",
"feeds",
"."
] | python | train |
twisted/axiom | axiom/scheduler.py | https://github.com/twisted/axiom/blob/7de70bc8fe1bb81f9c2339fba8daec9eb2e92b68/axiom/scheduler.py#L268-L293 | def _transientSchedule(self, when, now):
"""
If the service is currently running, schedule a tick to happen no
later than C{when}.
@param when: The time at which to tick.
@type when: L{epsilon.extime.Time}
@param now: The current time.
@type now: L{epsilon.extim... | [
"def",
"_transientSchedule",
"(",
"self",
",",
"when",
",",
"now",
")",
":",
"if",
"not",
"self",
".",
"running",
":",
"return",
"if",
"self",
".",
"timer",
"is",
"not",
"None",
":",
"if",
"self",
".",
"timer",
".",
"getTime",
"(",
")",
"<",
"when"... | If the service is currently running, schedule a tick to happen no
later than C{when}.
@param when: The time at which to tick.
@type when: L{epsilon.extime.Time}
@param now: The current time.
@type now: L{epsilon.extime.Time} | [
"If",
"the",
"service",
"is",
"currently",
"running",
"schedule",
"a",
"tick",
"to",
"happen",
"no",
"later",
"than",
"C",
"{",
"when",
"}",
"."
] | python | train |
collectiveacuity/labPack | labpack/storage/aws/s3.py | https://github.com/collectiveacuity/labPack/blob/52949ece35e72e3cc308f54d9ffa6bfbd96805b8/labpack/storage/aws/s3.py#L2023-L2038 | def remove(self):
'''
a method to remove collection and all records in the collection
:return: string with confirmation of deletion
'''
title = '%s.remove' % self.__class__.__name__
# request bucket delete
self.s3.delete_bucket(self.bucket_na... | [
"def",
"remove",
"(",
"self",
")",
":",
"title",
"=",
"'%s.remove'",
"%",
"self",
".",
"__class__",
".",
"__name__",
"# request bucket delete ",
"self",
".",
"s3",
".",
"delete_bucket",
"(",
"self",
".",
"bucket_name",
")",
"# return confirmation",
"exit_msg",
... | a method to remove collection and all records in the collection
:return: string with confirmation of deletion | [
"a",
"method",
"to",
"remove",
"collection",
"and",
"all",
"records",
"in",
"the",
"collection"
] | python | train |
notanumber/xapian-haystack | xapian_backend.py | https://github.com/notanumber/xapian-haystack/blob/2247b23d3cb6322ce477d45f84d52da47a940348/xapian_backend.py#L1478-L1490 | def _phrase_query(self, term_list, field_name, field_type):
"""
Returns a query that matches exact terms with
positional order (i.e. ["this", "thing"] != ["thing", "this"])
and no stem.
If `field_name` is not `None`, restrict to the field.
"""
term_list = [self._... | [
"def",
"_phrase_query",
"(",
"self",
",",
"term_list",
",",
"field_name",
",",
"field_type",
")",
":",
"term_list",
"=",
"[",
"self",
".",
"_term_query",
"(",
"term",
",",
"field_name",
",",
"field_type",
",",
"stemmed",
"=",
"False",
")",
"for",
"term",
... | Returns a query that matches exact terms with
positional order (i.e. ["this", "thing"] != ["thing", "this"])
and no stem.
If `field_name` is not `None`, restrict to the field. | [
"Returns",
"a",
"query",
"that",
"matches",
"exact",
"terms",
"with",
"positional",
"order",
"(",
"i",
".",
"e",
".",
"[",
"this",
"thing",
"]",
"!",
"=",
"[",
"thing",
"this",
"]",
")",
"and",
"no",
"stem",
"."
] | python | train |
fmenabe/python-dokuwiki | dokuwiki.py | https://github.com/fmenabe/python-dokuwiki/blob/7b5b13b764912b36f49a03a445c88f0934260eb1/dokuwiki.py#L36-L44 | def date(date):
"""DokuWiki returns dates of `xmlrpclib`/`xmlrpc.client` ``DateTime``
type and the format changes between DokuWiki versions ... This function
convert *date* to a `datetime` object.
"""
date = date.value
return (datetime.strptime(date[:-5], '%Y-%m-%dT%H:%M:%S')
if len(... | [
"def",
"date",
"(",
"date",
")",
":",
"date",
"=",
"date",
".",
"value",
"return",
"(",
"datetime",
".",
"strptime",
"(",
"date",
"[",
":",
"-",
"5",
"]",
",",
"'%Y-%m-%dT%H:%M:%S'",
")",
"if",
"len",
"(",
"date",
")",
"==",
"24",
"else",
"datetime... | DokuWiki returns dates of `xmlrpclib`/`xmlrpc.client` ``DateTime``
type and the format changes between DokuWiki versions ... This function
convert *date* to a `datetime` object. | [
"DokuWiki",
"returns",
"dates",
"of",
"xmlrpclib",
"/",
"xmlrpc",
".",
"client",
"DateTime",
"type",
"and",
"the",
"format",
"changes",
"between",
"DokuWiki",
"versions",
"...",
"This",
"function",
"convert",
"*",
"date",
"*",
"to",
"a",
"datetime",
"object",
... | python | train |
akissa/clamavmirror | clamavmirror/__init__.py | https://github.com/akissa/clamavmirror/blob/6ef1cfa9fb4fa4a7b8439004f1cd8775f51d77f6/clamavmirror/__init__.py#L175-L180 | def verify_sigfile(sigdir, sig):
"""Verify a signature file"""
cmd = ['sigtool', '-i', '%s/%s.cvd' % (sigdir, sig)]
sigtool = Popen(cmd, stdout=PIPE, stderr=PIPE)
ret_val = sigtool.wait()
return ret_val == 0 | [
"def",
"verify_sigfile",
"(",
"sigdir",
",",
"sig",
")",
":",
"cmd",
"=",
"[",
"'sigtool'",
",",
"'-i'",
",",
"'%s/%s.cvd'",
"%",
"(",
"sigdir",
",",
"sig",
")",
"]",
"sigtool",
"=",
"Popen",
"(",
"cmd",
",",
"stdout",
"=",
"PIPE",
",",
"stderr",
"... | Verify a signature file | [
"Verify",
"a",
"signature",
"file"
] | python | train |
mitsei/dlkit | dlkit/records/assessment/basic/drag_and_drop_records.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/records/assessment/basic/drag_and_drop_records.py#L228-L233 | def get_coordinate_conditions(self):
"""stub"""
condition_list = deepcopy(self.my_osid_object._my_map['coordinateConditions'])
for condition in condition_list:
condition['coordinate'] = BasicCoordinate(condition['coordinate'])
return condition_list | [
"def",
"get_coordinate_conditions",
"(",
"self",
")",
":",
"condition_list",
"=",
"deepcopy",
"(",
"self",
".",
"my_osid_object",
".",
"_my_map",
"[",
"'coordinateConditions'",
"]",
")",
"for",
"condition",
"in",
"condition_list",
":",
"condition",
"[",
"'coordina... | stub | [
"stub"
] | python | train |
rq/django-rq | django_rq/queues.py | https://github.com/rq/django-rq/blob/f50097dfe44351bd2a2d9d40edb19150dfc6a168/django_rq/queues.py#L181-L216 | def get_queues(*queue_names, **kwargs):
"""
Return queue instances from specified queue names.
All instances must use the same Redis connection.
"""
from .settings import QUEUES
if len(queue_names) <= 1:
# Return "default" queue if no queue name is specified
# or one queue with ... | [
"def",
"get_queues",
"(",
"*",
"queue_names",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
".",
"settings",
"import",
"QUEUES",
"if",
"len",
"(",
"queue_names",
")",
"<=",
"1",
":",
"# Return \"default\" queue if no queue name is specified",
"# or one queue with speci... | Return queue instances from specified queue names.
All instances must use the same Redis connection. | [
"Return",
"queue",
"instances",
"from",
"specified",
"queue",
"names",
".",
"All",
"instances",
"must",
"use",
"the",
"same",
"Redis",
"connection",
"."
] | python | train |
boxed/mutmut | mutmut/__init__.py | https://github.com/boxed/mutmut/blob/dd3bbe9aba3168ed21b85fbfe0b654b150239697/mutmut/__init__.py#L512-L561 | def mutate_node(node, context):
"""
:type context: Context
"""
context.stack.append(node)
try:
if node.type in ('tfpdef', 'import_from', 'import_name'):
return
if node.start_pos[0] - 1 != context.current_line_index:
context.current_line_index = node.start_pos... | [
"def",
"mutate_node",
"(",
"node",
",",
"context",
")",
":",
"context",
".",
"stack",
".",
"append",
"(",
"node",
")",
"try",
":",
"if",
"node",
".",
"type",
"in",
"(",
"'tfpdef'",
",",
"'import_from'",
",",
"'import_name'",
")",
":",
"return",
"if",
... | :type context: Context | [
":",
"type",
"context",
":",
"Context"
] | python | valid |
benmack/eo-box | eobox/raster/cube.py | https://github.com/benmack/eo-box/blob/a291450c766bf50ea06adcdeb5729a4aad790ed5/eobox/raster/cube.py#L517-L562 | def read_data_by_variable(self, mask=True):
"""Reads and masks (if desired) the data and converts it in one dataframe per variable."""
def print_elapsed_time(start, last_stopped, prefix):
# print(f"{prefix} - Elapsed time [s] since start / last stopped: \
# {(int(time.time() ... | [
"def",
"read_data_by_variable",
"(",
"self",
",",
"mask",
"=",
"True",
")",
":",
"def",
"print_elapsed_time",
"(",
"start",
",",
"last_stopped",
",",
"prefix",
")",
":",
"# print(f\"{prefix} - Elapsed time [s] since start / last stopped: \\",
"# {(int(time.time() - star... | Reads and masks (if desired) the data and converts it in one dataframe per variable. | [
"Reads",
"and",
"masks",
"(",
"if",
"desired",
")",
"the",
"data",
"and",
"converts",
"it",
"in",
"one",
"dataframe",
"per",
"variable",
"."
] | python | train |
facelessuser/wcmatch | wcmatch/_wcparse.py | https://github.com/facelessuser/wcmatch/blob/d153e7007cc73b994ae1ba553dc4584039f5c212/wcmatch/_wcparse.py#L1153-L1225 | def root(self, pattern, current):
"""Start parsing the pattern."""
self.set_after_start()
i = util.StringIter(pattern)
iter(i)
root_specified = False
if self.win_drive_detect:
m = RE_WIN_PATH.match(pattern)
if m:
drive = m.group(0)... | [
"def",
"root",
"(",
"self",
",",
"pattern",
",",
"current",
")",
":",
"self",
".",
"set_after_start",
"(",
")",
"i",
"=",
"util",
".",
"StringIter",
"(",
"pattern",
")",
"iter",
"(",
"i",
")",
"root_specified",
"=",
"False",
"if",
"self",
".",
"win_d... | Start parsing the pattern. | [
"Start",
"parsing",
"the",
"pattern",
"."
] | python | train |
ewels/MultiQC | multiqc/modules/theta2/theta2.py | https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/theta2/theta2.py#L56-L72 | def parse_theta2_report (self, fh):
""" Parse the final THetA2 log file. """
parsed_data = {}
for l in fh:
if l.startswith('#'):
continue
else:
s = l.split("\t")
purities = s[1].split(',')
parsed_data['propor... | [
"def",
"parse_theta2_report",
"(",
"self",
",",
"fh",
")",
":",
"parsed_data",
"=",
"{",
"}",
"for",
"l",
"in",
"fh",
":",
"if",
"l",
".",
"startswith",
"(",
"'#'",
")",
":",
"continue",
"else",
":",
"s",
"=",
"l",
".",
"split",
"(",
"\"\\t\"",
"... | Parse the final THetA2 log file. | [
"Parse",
"the",
"final",
"THetA2",
"log",
"file",
"."
] | python | train |
ambitioninc/django-query-builder | querybuilder/helpers.py | https://github.com/ambitioninc/django-query-builder/blob/113a7d845d3ddc6a45621b9880308e756f87c5bf/querybuilder/helpers.py#L22-L53 | def set_value_for_keypath(item, keypath, value, create_if_needed=False, delimeter='.'):
"""
Sets the value for a keypath in a dictionary
if the keypath exists. This modifies the
original dictionary.
"""
if len(keypath) == 0:
return None
keys = keypath.split(delimeter)
if len(ke... | [
"def",
"set_value_for_keypath",
"(",
"item",
",",
"keypath",
",",
"value",
",",
"create_if_needed",
"=",
"False",
",",
"delimeter",
"=",
"'.'",
")",
":",
"if",
"len",
"(",
"keypath",
")",
"==",
"0",
":",
"return",
"None",
"keys",
"=",
"keypath",
".",
"... | Sets the value for a keypath in a dictionary
if the keypath exists. This modifies the
original dictionary. | [
"Sets",
"the",
"value",
"for",
"a",
"keypath",
"in",
"a",
"dictionary",
"if",
"the",
"keypath",
"exists",
".",
"This",
"modifies",
"the",
"original",
"dictionary",
"."
] | python | train |
awslabs/sockeye | sockeye/lexical_constraints.py | https://github.com/awslabs/sockeye/blob/5d64a1ee1ef3cbba17c6d1d94bc061020c43f6ab/sockeye/lexical_constraints.py#L67-L80 | def add_phrase(self,
phrase: List[int]) -> None:
"""
Recursively adds a phrase to this trie node.
:param phrase: A list of word IDs to add to this trie node.
"""
if len(phrase) == 1:
self.final_ids.add(phrase[0])
else:
next_word... | [
"def",
"add_phrase",
"(",
"self",
",",
"phrase",
":",
"List",
"[",
"int",
"]",
")",
"->",
"None",
":",
"if",
"len",
"(",
"phrase",
")",
"==",
"1",
":",
"self",
".",
"final_ids",
".",
"add",
"(",
"phrase",
"[",
"0",
"]",
")",
"else",
":",
"next_... | Recursively adds a phrase to this trie node.
:param phrase: A list of word IDs to add to this trie node. | [
"Recursively",
"adds",
"a",
"phrase",
"to",
"this",
"trie",
"node",
"."
] | python | train |
RonenNess/Fileter | fileter/iterators/grep.py | https://github.com/RonenNess/Fileter/blob/5372221b4049d5d46a9926573b91af17681c81f3/fileter/iterators/grep.py#L39-L55 | def process_file(self, path, dryrun):
"""
Print files path.
"""
# if dryrun just return files
if dryrun:
return path
# scan file and match lines
ret = []
with open(path, "r") as infile:
for line in infile:
if re.sea... | [
"def",
"process_file",
"(",
"self",
",",
"path",
",",
"dryrun",
")",
":",
"# if dryrun just return files",
"if",
"dryrun",
":",
"return",
"path",
"# scan file and match lines",
"ret",
"=",
"[",
"]",
"with",
"open",
"(",
"path",
",",
"\"r\"",
")",
"as",
"infi... | Print files path. | [
"Print",
"files",
"path",
"."
] | python | train |
hydraplatform/hydra-base | hydra_base/lib/users.py | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/users.py#L84-L106 | def add_user(user, **kwargs):
"""
Add a user
"""
#check_perm(kwargs.get('user_id'), 'add_user')
u = User()
u.username = user.username
u.display_name = user.display_name
user_id = _get_user_id(u.username)
#If the user is already there, cannot add another with
#the same ... | [
"def",
"add_user",
"(",
"user",
",",
"*",
"*",
"kwargs",
")",
":",
"#check_perm(kwargs.get('user_id'), 'add_user')",
"u",
"=",
"User",
"(",
")",
"u",
".",
"username",
"=",
"user",
".",
"username",
"u",
".",
"display_name",
"=",
"user",
".",
"display_name",
... | Add a user | [
"Add",
"a",
"user"
] | python | train |
timothydmorton/VESPA | vespa/populations.py | https://github.com/timothydmorton/VESPA/blob/0446b54d48009f3655cfd1a3957ceea21d3adcaa/vespa/populations.py#L451-L566 | def _make_kde(self, use_sklearn=False, bandwidth=None, rtol=1e-6,
sig_clip=50, no_sig_clip=False, cov_all=True,
**kwargs):
"""Creates KDE objects for 3-d shape parameter distribution
KDE represents likelihood as function of trapezoidal
shape parameters (log(d... | [
"def",
"_make_kde",
"(",
"self",
",",
"use_sklearn",
"=",
"False",
",",
"bandwidth",
"=",
"None",
",",
"rtol",
"=",
"1e-6",
",",
"sig_clip",
"=",
"50",
",",
"no_sig_clip",
"=",
"False",
",",
"cov_all",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
... | Creates KDE objects for 3-d shape parameter distribution
KDE represents likelihood as function of trapezoidal
shape parameters (log(delta), T, T/tau).
Uses :class:`scipy.stats.gaussian_kde`` KDE by default;
Scikit-learn KDE implementation tested a bit, but not
fully implemented... | [
"Creates",
"KDE",
"objects",
"for",
"3",
"-",
"d",
"shape",
"parameter",
"distribution"
] | python | train |
GoogleCloudPlatform/appengine-gcs-client | python/src/cloudstorage/rest_api.py | https://github.com/GoogleCloudPlatform/appengine-gcs-client/blob/d11078331ecd915d753c886e96a80133599f3f98/python/src/cloudstorage/rest_api.py#L65-L84 | def _make_sync_method(name):
"""Helper to synthesize a synchronous method from an async method name.
Used by the @add_sync_methods class decorator below.
Args:
name: The name of the synchronous method.
Returns:
A method (with first argument 'self') that retrieves and calls
self.<name>, passing it... | [
"def",
"_make_sync_method",
"(",
"name",
")",
":",
"def",
"sync_wrapper",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
":",
"method",
"=",
"getattr",
"(",
"self",
",",
"name",
")",
"future",
"=",
"method",
"(",
"*",
"args",
",",
"*",
... | Helper to synthesize a synchronous method from an async method name.
Used by the @add_sync_methods class decorator below.
Args:
name: The name of the synchronous method.
Returns:
A method (with first argument 'self') that retrieves and calls
self.<name>, passing its own arguments, expects it to ret... | [
"Helper",
"to",
"synthesize",
"a",
"synchronous",
"method",
"from",
"an",
"async",
"method",
"name",
"."
] | python | train |
abingham/docopt-subcommands | docopt_subcommands/__init__.py | https://github.com/abingham/docopt-subcommands/blob/4b5cd75bb8eed01f9405345446ca58e9a29d67ad/docopt_subcommands/__init__.py#L8-L14 | def command(name=None):
"""A decorator to register a subcommand with the global `Subcommands` instance.
"""
def decorator(f):
_commands.append((name, f))
return f
return decorator | [
"def",
"command",
"(",
"name",
"=",
"None",
")",
":",
"def",
"decorator",
"(",
"f",
")",
":",
"_commands",
".",
"append",
"(",
"(",
"name",
",",
"f",
")",
")",
"return",
"f",
"return",
"decorator"
] | A decorator to register a subcommand with the global `Subcommands` instance. | [
"A",
"decorator",
"to",
"register",
"a",
"subcommand",
"with",
"the",
"global",
"Subcommands",
"instance",
"."
] | python | train |
pyfca/pyfca | pyfca/implications.py | https://github.com/pyfca/pyfca/blob/cf8cea9e76076dbf4bb3f38996dcb5491b0eb0b0/pyfca/implications.py#L93-L107 | def A(g,i):
"""recursively constructs A line for g; i = len(g)-1"""
g1 = g&(2**i)
if i:
n = Awidth(i)
An = A(g,i-1)
if g1:
return An<<n | An
else:
return int('1'*n,2)<<n | An
else:
if g1:
return int('00',2)
else:
... | [
"def",
"A",
"(",
"g",
",",
"i",
")",
":",
"g1",
"=",
"g",
"&",
"(",
"2",
"**",
"i",
")",
"if",
"i",
":",
"n",
"=",
"Awidth",
"(",
"i",
")",
"An",
"=",
"A",
"(",
"g",
",",
"i",
"-",
"1",
")",
"if",
"g1",
":",
"return",
"An",
"<<",
"n... | recursively constructs A line for g; i = len(g)-1 | [
"recursively",
"constructs",
"A",
"line",
"for",
"g",
";",
"i",
"=",
"len",
"(",
"g",
")",
"-",
"1"
] | python | train |
simpleai-team/simpleai | simpleai/machine_learning/classifiers.py | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/machine_learning/classifiers.py#L322-L334 | def _max_gain_split(self, examples):
"""
Returns an OnlineInformationGain of the attribute with
max gain based on `examples`.
"""
gains = self._new_set_of_gain_counters()
for example in examples:
for gain in gains:
gain.add(example)
win... | [
"def",
"_max_gain_split",
"(",
"self",
",",
"examples",
")",
":",
"gains",
"=",
"self",
".",
"_new_set_of_gain_counters",
"(",
")",
"for",
"example",
"in",
"examples",
":",
"for",
"gain",
"in",
"gains",
":",
"gain",
".",
"add",
"(",
"example",
")",
"winn... | Returns an OnlineInformationGain of the attribute with
max gain based on `examples`. | [
"Returns",
"an",
"OnlineInformationGain",
"of",
"the",
"attribute",
"with",
"max",
"gain",
"based",
"on",
"examples",
"."
] | python | train |
saltstack/salt | salt/utils/configparser.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/configparser.py#L57-L137 | def _read(self, fp, fpname):
'''
Makes the following changes from the RawConfigParser:
1. Strip leading tabs from non-section-header lines.
2. Treat 8 spaces at the beginning of a line as a tab.
3. Treat lines beginning with a tab as options.
4. Drops support for continu... | [
"def",
"_read",
"(",
"self",
",",
"fp",
",",
"fpname",
")",
":",
"cursect",
"=",
"None",
"# None, or a dictionary",
"optname",
"=",
"None",
"lineno",
"=",
"0",
"e",
"=",
"None",
"# None, or an exception",
"while",
"True",
":",
"line",
"=",
"salt",
".",
"... | Makes the following changes from the RawConfigParser:
1. Strip leading tabs from non-section-header lines.
2. Treat 8 spaces at the beginning of a line as a tab.
3. Treat lines beginning with a tab as options.
4. Drops support for continuation lines.
5. Multiple values for a giv... | [
"Makes",
"the",
"following",
"changes",
"from",
"the",
"RawConfigParser",
":"
] | python | train |
Unity-Technologies/ml-agents | ml-agents/mlagents/trainers/bc/trainer.py | https://github.com/Unity-Technologies/ml-agents/blob/37d139af636e4a2351751fbf0f2fca5a9ed7457f/ml-agents/mlagents/trainers/bc/trainer.py#L87-L114 | def add_experiences(self, curr_info: AllBrainInfo, next_info: AllBrainInfo,
take_action_outputs):
"""
Adds experiences to each agent's experience history.
:param curr_info: Current AllBrainInfo (Dictionary of all current brains and corresponding BrainInfo).
:param... | [
"def",
"add_experiences",
"(",
"self",
",",
"curr_info",
":",
"AllBrainInfo",
",",
"next_info",
":",
"AllBrainInfo",
",",
"take_action_outputs",
")",
":",
"# Used to collect information about student performance.",
"info_student",
"=",
"curr_info",
"[",
"self",
".",
"br... | Adds experiences to each agent's experience history.
:param curr_info: Current AllBrainInfo (Dictionary of all current brains and corresponding BrainInfo).
:param next_info: Next AllBrainInfo (Dictionary of all current brains and corresponding BrainInfo).
:param take_action_outputs: The outputs ... | [
"Adds",
"experiences",
"to",
"each",
"agent",
"s",
"experience",
"history",
".",
":",
"param",
"curr_info",
":",
"Current",
"AllBrainInfo",
"(",
"Dictionary",
"of",
"all",
"current",
"brains",
"and",
"corresponding",
"BrainInfo",
")",
".",
":",
"param",
"next_... | python | train |
sporteasy/python-poeditor | poeditor/client.py | https://github.com/sporteasy/python-poeditor/blob/e9c0a8ab08816903122f730b73ffaab46601076c/poeditor/client.py#L501-L552 | def export(self, project_id, language_code, file_type='po', filters=None,
tags=None, local_file=None):
"""
Return terms / translations
filters - filter by self._filter_by
tags - filter results by tags;
local_file - save content into it. If None, save content into
... | [
"def",
"export",
"(",
"self",
",",
"project_id",
",",
"language_code",
",",
"file_type",
"=",
"'po'",
",",
"filters",
"=",
"None",
",",
"tags",
"=",
"None",
",",
"local_file",
"=",
"None",
")",
":",
"if",
"file_type",
"not",
"in",
"self",
".",
"FILE_TY... | Return terms / translations
filters - filter by self._filter_by
tags - filter results by tags;
local_file - save content into it. If None, save content into
random temp file.
>>> tags = 'name-of-tag'
>>> tags = ["name-of-tag"]
>>> tags = ["name-of-tag", "nam... | [
"Return",
"terms",
"/",
"translations"
] | python | train |
ianmiell/shutit | shutit.py | https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit.py#L33-L94 | def create_session(docker_image=None,
docker_rm=None,
echo=False,
loglevel='WARNING',
nocolor=False,
session_type='bash',
vagrant_session_name=None,
vagrant_image='ubuntu/xenial64',
... | [
"def",
"create_session",
"(",
"docker_image",
"=",
"None",
",",
"docker_rm",
"=",
"None",
",",
"echo",
"=",
"False",
",",
"loglevel",
"=",
"'WARNING'",
",",
"nocolor",
"=",
"False",
",",
"session_type",
"=",
"'bash'",
",",
"vagrant_session_name",
"=",
"None"... | Creates a distinct ShutIt session. Sessions can be of type:
bash - a bash shell is spawned and
vagrant - a Vagrantfile is created and 'vagrant up'ped | [
"Creates",
"a",
"distinct",
"ShutIt",
"session",
".",
"Sessions",
"can",
"be",
"of",
"type",
":"
] | python | train |
Gorialis/jishaku | jishaku/cog.py | https://github.com/Gorialis/jishaku/blob/fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e/jishaku/cog.py#L639-L644 | async def jsk_git(self, ctx: commands.Context, *, argument: CodeblockConverter):
"""
Shortcut for 'jsk sh git'. Invokes the system shell.
"""
return await ctx.invoke(self.jsk_shell, argument=Codeblock(argument.language, "git " + argument.content)) | [
"async",
"def",
"jsk_git",
"(",
"self",
",",
"ctx",
":",
"commands",
".",
"Context",
",",
"*",
",",
"argument",
":",
"CodeblockConverter",
")",
":",
"return",
"await",
"ctx",
".",
"invoke",
"(",
"self",
".",
"jsk_shell",
",",
"argument",
"=",
"Codeblock"... | Shortcut for 'jsk sh git'. Invokes the system shell. | [
"Shortcut",
"for",
"jsk",
"sh",
"git",
".",
"Invokes",
"the",
"system",
"shell",
"."
] | python | train |
penguinmenac3/starttf | starttf/layers/tile_2d.py | https://github.com/penguinmenac3/starttf/blob/f4086489d169757c0504e822165db2fea534b944/starttf/layers/tile_2d.py#L131-L157 | def upsampling_feature_passthrough(early_feat, late_feat, filters, name, kernel_size=(1, 1)):
"""
An upsampling feature passthrough layer inspired by yolo9000 and the tiling layer.
It can be proven, that this layer does the same as conv(concat(early_feat, tile_2d(late_feat))).
This layer has no activat... | [
"def",
"upsampling_feature_passthrough",
"(",
"early_feat",
",",
"late_feat",
",",
"filters",
",",
"name",
",",
"kernel_size",
"=",
"(",
"1",
",",
"1",
")",
")",
":",
"_",
",",
"h_early",
",",
"w_early",
",",
"c_early",
"=",
"early_feat",
".",
"get_shape",... | An upsampling feature passthrough layer inspired by yolo9000 and the tiling layer.
It can be proven, that this layer does the same as conv(concat(early_feat, tile_2d(late_feat))).
This layer has no activation function.
:param early_feat: The early feature layer of shape [batch_size, h * s_x, w * s_y, _].
... | [
"An",
"upsampling",
"feature",
"passthrough",
"layer",
"inspired",
"by",
"yolo9000",
"and",
"the",
"tiling",
"layer",
"."
] | python | train |
krukas/Trionyx | trionyx/config.py | https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/config.py#L215-L220 | def auto_load_configs(self):
"""Auto load all configs from app configs"""
for app in apps.get_app_configs():
for model in app.get_models():
config = ModelConfig(model, getattr(app, model.__name__, None))
self.configs[self.get_model_name(model)] = config | [
"def",
"auto_load_configs",
"(",
"self",
")",
":",
"for",
"app",
"in",
"apps",
".",
"get_app_configs",
"(",
")",
":",
"for",
"model",
"in",
"app",
".",
"get_models",
"(",
")",
":",
"config",
"=",
"ModelConfig",
"(",
"model",
",",
"getattr",
"(",
"app",... | Auto load all configs from app configs | [
"Auto",
"load",
"all",
"configs",
"from",
"app",
"configs"
] | python | train |
theislab/scanpy | scanpy/tools/_diffmap.py | https://github.com/theislab/scanpy/blob/9e4e5ee02e04cf618872d9b098e24f0542e8b227/scanpy/tools/_diffmap.py#L4-L46 | def diffmap(adata, n_comps=15, copy=False):
"""Diffusion Maps [Coifman05]_ [Haghverdi15]_ [Wolf18]_.
Diffusion maps [Coifman05]_ has been proposed for visualizing single-cell
data by [Haghverdi15]_. The tool uses the adapted Gaussian kernel suggested
by [Haghverdi16]_ in the implementation of [Wolf18]_... | [
"def",
"diffmap",
"(",
"adata",
",",
"n_comps",
"=",
"15",
",",
"copy",
"=",
"False",
")",
":",
"if",
"'neighbors'",
"not",
"in",
"adata",
".",
"uns",
":",
"raise",
"ValueError",
"(",
"'You need to run `pp.neighbors` first to compute a neighborhood graph.'",
")",
... | Diffusion Maps [Coifman05]_ [Haghverdi15]_ [Wolf18]_.
Diffusion maps [Coifman05]_ has been proposed for visualizing single-cell
data by [Haghverdi15]_. The tool uses the adapted Gaussian kernel suggested
by [Haghverdi16]_ in the implementation of [Wolf18]_.
The width ("sigma") of the connectivity kern... | [
"Diffusion",
"Maps",
"[",
"Coifman05",
"]",
"_",
"[",
"Haghverdi15",
"]",
"_",
"[",
"Wolf18",
"]",
"_",
"."
] | python | train |
Microsoft/nni | examples/trials/weight_sharing/ga_squad/data.py | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/weight_sharing/ga_squad/data.py#L223-L237 | def get_answer_begin_end(data):
'''
Get answer's index of begin and end.
'''
begin = []
end = []
for qa_pair in data:
tokens = qa_pair['passage_tokens']
char_begin = qa_pair['answer_begin']
char_end = qa_pair['answer_end']
word_begin = get_word_index(tokens, char_... | [
"def",
"get_answer_begin_end",
"(",
"data",
")",
":",
"begin",
"=",
"[",
"]",
"end",
"=",
"[",
"]",
"for",
"qa_pair",
"in",
"data",
":",
"tokens",
"=",
"qa_pair",
"[",
"'passage_tokens'",
"]",
"char_begin",
"=",
"qa_pair",
"[",
"'answer_begin'",
"]",
"ch... | Get answer's index of begin and end. | [
"Get",
"answer",
"s",
"index",
"of",
"begin",
"and",
"end",
"."
] | python | train |
pvlib/pvlib-python | pvlib/irradiance.py | https://github.com/pvlib/pvlib-python/blob/2e844a595b820b43d1170269781fa66bd0ccc8a3/pvlib/irradiance.py#L1242-L1292 | def clearness_index(ghi, solar_zenith, extra_radiation, min_cos_zenith=0.065,
max_clearness_index=2.0):
"""
Calculate the clearness index.
The clearness index is the ratio of global to extraterrestrial
irradiance on a horizontal plane.
Parameters
----------
ghi : numeri... | [
"def",
"clearness_index",
"(",
"ghi",
",",
"solar_zenith",
",",
"extra_radiation",
",",
"min_cos_zenith",
"=",
"0.065",
",",
"max_clearness_index",
"=",
"2.0",
")",
":",
"cos_zenith",
"=",
"tools",
".",
"cosd",
"(",
"solar_zenith",
")",
"I0h",
"=",
"extra_radi... | Calculate the clearness index.
The clearness index is the ratio of global to extraterrestrial
irradiance on a horizontal plane.
Parameters
----------
ghi : numeric
Global horizontal irradiance in W/m^2.
solar_zenith : numeric
True (not refraction-corrected) solar zenith angle ... | [
"Calculate",
"the",
"clearness",
"index",
"."
] | python | train |
graphql-python/graphql-core | graphql/execution/executor.py | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/execution/executor.py#L717-L741 | def complete_nonnull_value(
exe_context, # type: ExecutionContext
return_type, # type: GraphQLNonNull
field_asts, # type: List[Field]
info, # type: ResolveInfo
path, # type: List[Union[int, str]]
result, # type: Any
):
# type: (...) -> Any
"""
Complete a NonNull value by comple... | [
"def",
"complete_nonnull_value",
"(",
"exe_context",
",",
"# type: ExecutionContext",
"return_type",
",",
"# type: GraphQLNonNull",
"field_asts",
",",
"# type: List[Field]",
"info",
",",
"# type: ResolveInfo",
"path",
",",
"# type: List[Union[int, str]]",
"result",
",",
"# ty... | Complete a NonNull value by completing the inner type | [
"Complete",
"a",
"NonNull",
"value",
"by",
"completing",
"the",
"inner",
"type"
] | python | train |
josiah-wolf-oberholtzer/uqbar | uqbar/containers/UniqueTreeNode.py | https://github.com/josiah-wolf-oberholtzer/uqbar/blob/eca7fefebbbee1e2ae13bf5d6baa838be66b1db6/uqbar/containers/UniqueTreeNode.py#L118-L154 | def graph_order(self):
"""
Get graph-order tuple for node.
::
>>> from uqbar.containers import UniqueTreeContainer, UniqueTreeNode
>>> root_container = UniqueTreeContainer(name="root")
>>> outer_container = UniqueTreeContainer(name="outer")
>>> i... | [
"def",
"graph_order",
"(",
"self",
")",
":",
"parentage",
"=",
"tuple",
"(",
"reversed",
"(",
"self",
".",
"parentage",
")",
")",
"graph_order",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"parentage",
")",
"-",
"1",
")",
":",
"paren... | Get graph-order tuple for node.
::
>>> from uqbar.containers import UniqueTreeContainer, UniqueTreeNode
>>> root_container = UniqueTreeContainer(name="root")
>>> outer_container = UniqueTreeContainer(name="outer")
>>> inner_container = UniqueTreeContainer(name="... | [
"Get",
"graph",
"-",
"order",
"tuple",
"for",
"node",
"."
] | python | train |
JukeboxPipeline/jukebox-core | src/jukeboxcore/addons/guerilla/guerillamgmt.py | https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/addons/guerilla/guerillamgmt.py#L1708-L1722 | def shot_view_task(self, ):
"""View the task that is currently selected on the shot page
:returns: None
:rtype: None
:raises: None
"""
if not self.cur_shot:
return
i = self.shot_task_tablev.currentIndex()
item = i.internalPointer()
if... | [
"def",
"shot_view_task",
"(",
"self",
",",
")",
":",
"if",
"not",
"self",
".",
"cur_shot",
":",
"return",
"i",
"=",
"self",
".",
"shot_task_tablev",
".",
"currentIndex",
"(",
")",
"item",
"=",
"i",
".",
"internalPointer",
"(",
")",
"if",
"item",
":",
... | View the task that is currently selected on the shot page
:returns: None
:rtype: None
:raises: None | [
"View",
"the",
"task",
"that",
"is",
"currently",
"selected",
"on",
"the",
"shot",
"page"
] | python | train |
conchoecia/gloTK | gloTK/scripts/glotk_mitoshaper.py | https://github.com/conchoecia/gloTK/blob/58abee663fcfbbd09f4863c3ca3ae054e33184a8/gloTK/scripts/glotk_mitoshaper.py#L247-L303 | def main():
"""
1. Reads in a meraculous config file and outputs all of the associated config
files to $PWD/configs
2. The name of each run and the path to the directory is passed to a
multiprocessing core that controls which assemblies are executed and when.
"""
parser = CommandLine(... | [
"def",
"main",
"(",
")",
":",
"parser",
"=",
"CommandLine",
"(",
")",
"#this block from here: http://stackoverflow.com/a/4042861/5843327",
"if",
"len",
"(",
"sys",
".",
"argv",
")",
"==",
"1",
":",
"parser",
".",
"parser",
".",
"print_help",
"(",
")",
"sys",
... | 1. Reads in a meraculous config file and outputs all of the associated config
files to $PWD/configs
2. The name of each run and the path to the directory is passed to a
multiprocessing core that controls which assemblies are executed and when. | [
"1",
".",
"Reads",
"in",
"a",
"meraculous",
"config",
"file",
"and",
"outputs",
"all",
"of",
"the",
"associated",
"config",
"files",
"to",
"$PWD",
"/",
"configs",
"2",
".",
"The",
"name",
"of",
"each",
"run",
"and",
"the",
"path",
"to",
"the",
"directo... | python | train |
python-beaver/python-beaver | beaver/worker/tail.py | https://github.com/python-beaver/python-beaver/blob/93941e968016c5a962dffed9e7a9f6dc1d23236c/beaver/worker/tail.py#L130-L184 | def _buffer_extract(self, data):
"""
Extract takes an arbitrary string of input data and returns an array of
tokenized entities, provided there were any available to extract. This
makes for easy processing of datagrams using a pattern like:
tokenizer.extract(data).map { |enti... | [
"def",
"_buffer_extract",
"(",
"self",
",",
"data",
")",
":",
"# Extract token-delimited entities from the input string with the split command.",
"# There's a bit of craftiness here with the -1 parameter. Normally split would",
"# behave no differently regardless of if the token lies at the ver... | Extract takes an arbitrary string of input data and returns an array of
tokenized entities, provided there were any available to extract. This
makes for easy processing of datagrams using a pattern like:
tokenizer.extract(data).map { |entity| Decode(entity) }.each do ... | [
"Extract",
"takes",
"an",
"arbitrary",
"string",
"of",
"input",
"data",
"and",
"returns",
"an",
"array",
"of",
"tokenized",
"entities",
"provided",
"there",
"were",
"any",
"available",
"to",
"extract",
".",
"This",
"makes",
"for",
"easy",
"processing",
"of",
... | python | train |
rodluger/everest | everest/standalone.py | https://github.com/rodluger/everest/blob/6779591f9f8b3556847e2fbf761bdfac7520eaea/everest/standalone.py#L42-L86 | def DetrendFITS(fitsfile, raw=False, season=None, clobber=False, **kwargs):
"""
De-trend a K2 FITS file using :py:class:`everest.detrender.rPLD`.
:param str fitsfile: The full path to the FITS file
:param ndarray aperture: A 2D integer array corresponding to the \
desired photometric apertur... | [
"def",
"DetrendFITS",
"(",
"fitsfile",
",",
"raw",
"=",
"False",
",",
"season",
"=",
"None",
",",
"clobber",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"# Get info",
"EPIC",
"=",
"pyfits",
".",
"getheader",
"(",
"fitsfile",
",",
"0",
")",
"[",
... | De-trend a K2 FITS file using :py:class:`everest.detrender.rPLD`.
:param str fitsfile: The full path to the FITS file
:param ndarray aperture: A 2D integer array corresponding to the \
desired photometric aperture (1 = in aperture, 0 = outside \
aperture). Default is to interactively sele... | [
"De",
"-",
"trend",
"a",
"K2",
"FITS",
"file",
"using",
":",
"py",
":",
"class",
":",
"everest",
".",
"detrender",
".",
"rPLD",
"."
] | python | train |
rosenbrockc/fortpy | fortpy/scripts/analyze.py | https://github.com/rosenbrockc/fortpy/blob/1ed0757c52d549e41d9d44bdea68cb89529293a5/fortpy/scripts/analyze.py#L822-L832 | def do_rmfit(self, arg):
"""Removes a fit function from a variable. See 'fit'."""
if arg in self.curargs["fits"]:
del self.curargs["fits"][arg]
#We also need to remove the variable entry if it exists.
if "timing" in arg:
fitvar = "{}|fit".format(arg)
... | [
"def",
"do_rmfit",
"(",
"self",
",",
"arg",
")",
":",
"if",
"arg",
"in",
"self",
".",
"curargs",
"[",
"\"fits\"",
"]",
":",
"del",
"self",
".",
"curargs",
"[",
"\"fits\"",
"]",
"[",
"arg",
"]",
"#We also need to remove the variable entry if it exists.",
"if"... | Removes a fit function from a variable. See 'fit'. | [
"Removes",
"a",
"fit",
"function",
"from",
"a",
"variable",
".",
"See",
"fit",
"."
] | python | train |
indico/indico-plugins | livesync/indico_livesync/cli.py | https://github.com/indico/indico-plugins/blob/fe50085cc63be9b8161b09539e662e7b04e4b38e/livesync/indico_livesync/cli.py#L45-L66 | def agents():
"""Lists the currently active agents"""
print 'The following LiveSync agents are active:'
agent_list = LiveSyncAgent.find().order_by(LiveSyncAgent.backend_name, db.func.lower(LiveSyncAgent.name)).all()
table_data = [['ID', 'Name', 'Backend', 'Initial Export', 'Queue']]
for agent in age... | [
"def",
"agents",
"(",
")",
":",
"print",
"'The following LiveSync agents are active:'",
"agent_list",
"=",
"LiveSyncAgent",
".",
"find",
"(",
")",
".",
"order_by",
"(",
"LiveSyncAgent",
".",
"backend_name",
",",
"db",
".",
"func",
".",
"lower",
"(",
"LiveSyncAge... | Lists the currently active agents | [
"Lists",
"the",
"currently",
"active",
"agents"
] | python | train |
UUDigitalHumanitieslab/tei_reader | tei_reader/models/element.py | https://github.com/UUDigitalHumanitieslab/tei_reader/blob/7b19c34a9d7cc941a36ecdcf6f361e26c6488697/tei_reader/models/element.py#L69-L81 | def parts(self):
"""
Get the parts directly below this element.
"""
for item in self.__parts_and_divisions:
if item.tag == 'part':
yield item
else:
# Divisions shouldn't be beneath a part, but here's a fallback
# fo... | [
"def",
"parts",
"(",
"self",
")",
":",
"for",
"item",
"in",
"self",
".",
"__parts_and_divisions",
":",
"if",
"item",
".",
"tag",
"==",
"'part'",
":",
"yield",
"item",
"else",
":",
"# Divisions shouldn't be beneath a part, but here's a fallback",
"# for if this does ... | Get the parts directly below this element. | [
"Get",
"the",
"parts",
"directly",
"below",
"this",
"element",
"."
] | python | train |
project-rig/rig | rig/place_and_route/place/rcm.py | https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/place_and_route/place/rcm.py#L45-L60 | def _get_connected_subgraphs(vertices, vertices_neighbours):
"""Break a graph containing unconnected subgraphs into a list of connected
subgraphs.
Returns
-------
[set([vertex, ...]), ...]
"""
remaining_vertices = set(vertices)
subgraphs = []
while remaining_vertices:
subgra... | [
"def",
"_get_connected_subgraphs",
"(",
"vertices",
",",
"vertices_neighbours",
")",
":",
"remaining_vertices",
"=",
"set",
"(",
"vertices",
")",
"subgraphs",
"=",
"[",
"]",
"while",
"remaining_vertices",
":",
"subgraph",
"=",
"set",
"(",
"_dfs",
"(",
"remaining... | Break a graph containing unconnected subgraphs into a list of connected
subgraphs.
Returns
-------
[set([vertex, ...]), ...] | [
"Break",
"a",
"graph",
"containing",
"unconnected",
"subgraphs",
"into",
"a",
"list",
"of",
"connected",
"subgraphs",
"."
] | python | train |
zhanglab/psamm | psamm/datasource/native.py | https://github.com/zhanglab/psamm/blob/dc427848c4f9d109ca590f0afa024c63b685b3f4/psamm/datasource/native.py#L1187-L1201 | def parse_model_group_list(path, groups):
"""Parse a structured list of model groups as obtained from a YAML file
Yields reaction IDs. Path can be given as a string or a context.
"""
context = FilePathContext(path)
for model_group in groups:
if 'include' in model_group:
include... | [
"def",
"parse_model_group_list",
"(",
"path",
",",
"groups",
")",
":",
"context",
"=",
"FilePathContext",
"(",
"path",
")",
"for",
"model_group",
"in",
"groups",
":",
"if",
"'include'",
"in",
"model_group",
":",
"include_context",
"=",
"context",
".",
"resolve... | Parse a structured list of model groups as obtained from a YAML file
Yields reaction IDs. Path can be given as a string or a context. | [
"Parse",
"a",
"structured",
"list",
"of",
"model",
"groups",
"as",
"obtained",
"from",
"a",
"YAML",
"file"
] | python | train |
roclark/sportsreference | sportsreference/ncaaf/roster.py | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/ncaaf/roster.py#L233-L264 | def _combine_all_stats(self, player_info):
"""
Pull stats from all tables into a single data structure.
Pull the stats from all of the requested tables into a dictionary that
is separated by season to allow easy queries of the player's stats for
each season.
Parameters
... | [
"def",
"_combine_all_stats",
"(",
"self",
",",
"player_info",
")",
":",
"all_stats_dict",
"=",
"{",
"}",
"for",
"table_id",
"in",
"[",
"'passing'",
",",
"'rushing'",
",",
"'defense'",
",",
"'scoring'",
"]",
":",
"table_items",
"=",
"utils",
".",
"_get_stats_... | Pull stats from all tables into a single data structure.
Pull the stats from all of the requested tables into a dictionary that
is separated by season to allow easy queries of the player's stats for
each season.
Parameters
----------
player_info : PyQuery object
... | [
"Pull",
"stats",
"from",
"all",
"tables",
"into",
"a",
"single",
"data",
"structure",
"."
] | python | train |
google/grr | grr/server/grr_response_server/aff4_objects/aff4_grr.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/aff4_objects/aff4_grr.py#L374-L400 | def Update(self, attribute=None):
"""Update an attribute from the client."""
# List the directory on the client
currently_running = self.Get(self.Schema.CONTENT_LOCK)
# Is this flow still active?
if currently_running:
flow_obj = aff4.FACTORY.Open(currently_running, token=self.token)
if ... | [
"def",
"Update",
"(",
"self",
",",
"attribute",
"=",
"None",
")",
":",
"# List the directory on the client",
"currently_running",
"=",
"self",
".",
"Get",
"(",
"self",
".",
"Schema",
".",
"CONTENT_LOCK",
")",
"# Is this flow still active?",
"if",
"currently_running"... | Update an attribute from the client. | [
"Update",
"an",
"attribute",
"from",
"the",
"client",
"."
] | python | train |
iamteem/redisco | redisco/models/base.py | https://github.com/iamteem/redisco/blob/a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91/redisco/models/base.py#L521-L528 | def get_model_from_key(key):
"""Gets the model from a given key."""
_known_models = {}
model_name = key.split(':', 2)[0]
# populate
for klass in Model.__subclasses__():
_known_models[klass.__name__] = klass
return _known_models.get(model_name, None) | [
"def",
"get_model_from_key",
"(",
"key",
")",
":",
"_known_models",
"=",
"{",
"}",
"model_name",
"=",
"key",
".",
"split",
"(",
"':'",
",",
"2",
")",
"[",
"0",
"]",
"# populate",
"for",
"klass",
"in",
"Model",
".",
"__subclasses__",
"(",
")",
":",
"_... | Gets the model from a given key. | [
"Gets",
"the",
"model",
"from",
"a",
"given",
"key",
"."
] | python | train |
horazont/aioxmpp | aioxmpp/structs.py | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/structs.py#L1310-L1328 | def lookup(self, language_ranges):
"""
Perform an RFC4647 language range lookup on the keys in the
dictionary. `language_ranges` must be a sequence of
:class:`LanguageRange` instances.
Return the entry in the dictionary with a key as produced by
`lookup_language`. If `lo... | [
"def",
"lookup",
"(",
"self",
",",
"language_ranges",
")",
":",
"keys",
"=",
"list",
"(",
"self",
".",
"keys",
"(",
")",
")",
"try",
":",
"keys",
".",
"remove",
"(",
"None",
")",
"except",
"ValueError",
":",
"pass",
"keys",
".",
"sort",
"(",
")",
... | Perform an RFC4647 language range lookup on the keys in the
dictionary. `language_ranges` must be a sequence of
:class:`LanguageRange` instances.
Return the entry in the dictionary with a key as produced by
`lookup_language`. If `lookup_language` does not find a match and the
ma... | [
"Perform",
"an",
"RFC4647",
"language",
"range",
"lookup",
"on",
"the",
"keys",
"in",
"the",
"dictionary",
".",
"language_ranges",
"must",
"be",
"a",
"sequence",
"of",
":",
"class",
":",
"LanguageRange",
"instances",
"."
] | python | train |
Contraz/demosys-py | demosys/management/base.py | https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/management/base.py#L80-L92 | def validate_name(self, name):
"""
Can the name be used as a python module or package?
Raises ``ValueError`` if the name is invalid.
:param name: the name to check
"""
if not name:
raise ValueError("Name cannot be empty")
# Can the name be ... | [
"def",
"validate_name",
"(",
"self",
",",
"name",
")",
":",
"if",
"not",
"name",
":",
"raise",
"ValueError",
"(",
"\"Name cannot be empty\"",
")",
"# Can the name be used as an identifier in python (module or package name)\r",
"if",
"not",
"name",
".",
"isidentifier",
"... | Can the name be used as a python module or package?
Raises ``ValueError`` if the name is invalid.
:param name: the name to check | [
"Can",
"the",
"name",
"be",
"used",
"as",
"a",
"python",
"module",
"or",
"package?",
"Raises",
"ValueError",
"if",
"the",
"name",
"is",
"invalid",
".",
":",
"param",
"name",
":",
"the",
"name",
"to",
"check"
] | python | valid |
SavinaRoja/OpenAccess_EPUB | src/openaccess_epub/publisher/plos.py | https://github.com/SavinaRoja/OpenAccess_EPUB/blob/6b77ba30b7394fd003920e7a7957bca963a90656/src/openaccess_epub/publisher/plos.py#L112-L120 | def package_description(self):
"""
Given an Article class instance, this is responsible for returning an
article description. For this method I have taken the approach of
serializing the article's first abstract, if it has one. This results
in 0 or 1 descriptions per article.
... | [
"def",
"package_description",
"(",
"self",
")",
":",
"abstract",
"=",
"self",
".",
"article",
".",
"root",
".",
"xpath",
"(",
"'./front/article-meta/abstract'",
")",
"return",
"serialize",
"(",
"abstract",
"[",
"0",
"]",
",",
"strip",
"=",
"True",
")",
"if... | Given an Article class instance, this is responsible for returning an
article description. For this method I have taken the approach of
serializing the article's first abstract, if it has one. This results
in 0 or 1 descriptions per article. | [
"Given",
"an",
"Article",
"class",
"instance",
"this",
"is",
"responsible",
"for",
"returning",
"an",
"article",
"description",
".",
"For",
"this",
"method",
"I",
"have",
"taken",
"the",
"approach",
"of",
"serializing",
"the",
"article",
"s",
"first",
"abstrac... | python | train |
quantopian/pgcontents | pgcontents/utils/migrate.py | https://github.com/quantopian/pgcontents/blob/ed36268b7917332d16868208e1e565742a8753e1/pgcontents/utils/migrate.py#L17-L31 | def temp_alembic_ini(alembic_dir_location, sqlalchemy_url):
"""
Temporarily write an alembic.ini file for use with alembic migration
scripts.
"""
with TemporaryDirectory() as tempdir:
alembic_ini_filename = join(tempdir, 'temp_alembic.ini')
with open(alembic_ini_filename, 'w') as f:
... | [
"def",
"temp_alembic_ini",
"(",
"alembic_dir_location",
",",
"sqlalchemy_url",
")",
":",
"with",
"TemporaryDirectory",
"(",
")",
"as",
"tempdir",
":",
"alembic_ini_filename",
"=",
"join",
"(",
"tempdir",
",",
"'temp_alembic.ini'",
")",
"with",
"open",
"(",
"alembi... | Temporarily write an alembic.ini file for use with alembic migration
scripts. | [
"Temporarily",
"write",
"an",
"alembic",
".",
"ini",
"file",
"for",
"use",
"with",
"alembic",
"migration",
"scripts",
"."
] | python | test |
MediaFire/mediafire-python-open-sdk | mediafire/client.py | https://github.com/MediaFire/mediafire-python-open-sdk/blob/8f1f23db1b16f16e026f5c6777aec32d00baa05f/mediafire/client.py#L132-L164 | def get_resource_by_key(self, resource_key):
"""Return resource by quick_key/folder_key.
key -- quick_key or folder_key
"""
# search for quick_key by default
lookup_order = ["quick_key", "folder_key"]
if len(resource_key) == FOLDER_KEY_LENGTH:
lookup_order ... | [
"def",
"get_resource_by_key",
"(",
"self",
",",
"resource_key",
")",
":",
"# search for quick_key by default",
"lookup_order",
"=",
"[",
"\"quick_key\"",
",",
"\"folder_key\"",
"]",
"if",
"len",
"(",
"resource_key",
")",
"==",
"FOLDER_KEY_LENGTH",
":",
"lookup_order",... | Return resource by quick_key/folder_key.
key -- quick_key or folder_key | [
"Return",
"resource",
"by",
"quick_key",
"/",
"folder_key",
"."
] | python | train |
hubo1016/vlcp | vlcp/server/module.py | https://github.com/hubo1016/vlcp/blob/239055229ec93a99cc7e15208075724ccf543bd1/vlcp/server/module.py#L642-L723 | async def reload_modules(self, pathlist):
"""
Reload modules with a full path in the pathlist
"""
loadedModules = []
failures = []
for path in pathlist:
p, module = findModule(path, False)
if module is not None and hasattr(module, '_instance') and ... | [
"async",
"def",
"reload_modules",
"(",
"self",
",",
"pathlist",
")",
":",
"loadedModules",
"=",
"[",
"]",
"failures",
"=",
"[",
"]",
"for",
"path",
"in",
"pathlist",
":",
"p",
",",
"module",
"=",
"findModule",
"(",
"path",
",",
"False",
")",
"if",
"m... | Reload modules with a full path in the pathlist | [
"Reload",
"modules",
"with",
"a",
"full",
"path",
"in",
"the",
"pathlist"
] | python | train |
PMEAL/OpenPNM | openpnm/io/iMorph.py | https://github.com/PMEAL/OpenPNM/blob/0547b5724ffedc0a593aae48639d36fe10e0baed/openpnm/io/iMorph.py#L23-L204 | def load(cls, path,
node_file="throats_cellsThroatsGraph_Nodes.txt",
graph_file="throats_cellsThroatsGraph.txt",
network=None, voxel_size=None, return_geometry=False):
r"""
Loads network data from an iMorph processed image stack
Parameters
--------... | [
"def",
"load",
"(",
"cls",
",",
"path",
",",
"node_file",
"=",
"\"throats_cellsThroatsGraph_Nodes.txt\"",
",",
"graph_file",
"=",
"\"throats_cellsThroatsGraph.txt\"",
",",
"network",
"=",
"None",
",",
"voxel_size",
"=",
"None",
",",
"return_geometry",
"=",
"False",
... | r"""
Loads network data from an iMorph processed image stack
Parameters
----------
path : string
The path of the folder where the subfiles are held
node_file : string
The file that describes the pores and throats, the
default iMorph name is: ... | [
"r",
"Loads",
"network",
"data",
"from",
"an",
"iMorph",
"processed",
"image",
"stack"
] | python | train |
johnbywater/eventsourcing | eventsourcing/contrib/suffixtrees/domain/model/suffixtree.py | https://github.com/johnbywater/eventsourcing/blob/de2c22c653fdccf2f5ee96faea74453ff1847e42/eventsourcing/contrib/suffixtrees/domain/model/suffixtree.py#L374-L397 | def find_substring(substring, suffix_tree, edge_repo):
"""Returns the index if substring in tree, otherwise -1.
"""
assert isinstance(substring, str)
assert isinstance(suffix_tree, SuffixTree)
assert isinstance(edge_repo, EventSourcedRepository)
if not substring:
return -1
if suffix_... | [
"def",
"find_substring",
"(",
"substring",
",",
"suffix_tree",
",",
"edge_repo",
")",
":",
"assert",
"isinstance",
"(",
"substring",
",",
"str",
")",
"assert",
"isinstance",
"(",
"suffix_tree",
",",
"SuffixTree",
")",
"assert",
"isinstance",
"(",
"edge_repo",
... | Returns the index if substring in tree, otherwise -1. | [
"Returns",
"the",
"index",
"if",
"substring",
"in",
"tree",
"otherwise",
"-",
"1",
"."
] | python | train |
minio/minio-py | minio/helpers.py | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/helpers.py#L308-L327 | def is_virtual_host(endpoint_url, bucket_name):
"""
Check to see if the ``bucket_name`` can be part of virtual host
style.
:param endpoint_url: Endpoint url which will be used for virtual host.
:param bucket_name: Bucket name to be validated against.
"""
is_valid_bucket_name(bucket_name)
... | [
"def",
"is_virtual_host",
"(",
"endpoint_url",
",",
"bucket_name",
")",
":",
"is_valid_bucket_name",
"(",
"bucket_name",
")",
"parsed_url",
"=",
"urlsplit",
"(",
"endpoint_url",
")",
"# bucket_name can be valid but '.' in the hostname will fail",
"# SSL certificate validation. ... | Check to see if the ``bucket_name`` can be part of virtual host
style.
:param endpoint_url: Endpoint url which will be used for virtual host.
:param bucket_name: Bucket name to be validated against. | [
"Check",
"to",
"see",
"if",
"the",
"bucket_name",
"can",
"be",
"part",
"of",
"virtual",
"host",
"style",
"."
] | python | train |
tensorflow/datasets | tensorflow_datasets/image/imagenet.py | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/image/imagenet.py#L86-L102 | def _get_validation_labels(val_path):
"""Returns labels for validation.
Args:
val_path: path to TAR file containing validation images. It is used to
retrieve the name of pictures and associate them to labels.
Returns:
dict, mapping from image name (str) to label (str).
"""
labels... | [
"def",
"_get_validation_labels",
"(",
"val_path",
")",
":",
"labels_path",
"=",
"tfds",
".",
"core",
".",
"get_tfds_path",
"(",
"_VALIDATION_LABELS_FNAME",
")",
"with",
"tf",
".",
"io",
".",
"gfile",
".",
"GFile",
"(",
"labels_path",
")",
"as",
"labels_f",
"... | Returns labels for validation.
Args:
val_path: path to TAR file containing validation images. It is used to
retrieve the name of pictures and associate them to labels.
Returns:
dict, mapping from image name (str) to label (str). | [
"Returns",
"labels",
"for",
"validation",
"."
] | python | train |
geertj/gruvi | lib/gruvi/util.py | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/util.py#L94-L143 | def delegate_method(other, method, name=None):
"""Add a method to the current class that delegates to another method.
The *other* argument must be a property that returns the instance to
delegate to. Due to an implementation detail, the property must be defined
in the current class. The *method* argume... | [
"def",
"delegate_method",
"(",
"other",
",",
"method",
",",
"name",
"=",
"None",
")",
":",
"frame",
"=",
"sys",
".",
"_getframe",
"(",
"1",
")",
"classdict",
"=",
"frame",
".",
"f_locals",
"@",
"functools",
".",
"wraps",
"(",
"method",
")",
"def",
"d... | Add a method to the current class that delegates to another method.
The *other* argument must be a property that returns the instance to
delegate to. Due to an implementation detail, the property must be defined
in the current class. The *method* argument specifies a method to delegate
to. It can be an... | [
"Add",
"a",
"method",
"to",
"the",
"current",
"class",
"that",
"delegates",
"to",
"another",
"method",
"."
] | python | train |
NuGrid/NuGridPy | nugridpy/astronomy.py | https://github.com/NuGrid/NuGridPy/blob/eee8047446e398be77362d82c1d8b3310054fab0/nugridpy/astronomy.py#L289-L312 | def mass_loss_loon05(L,Teff):
'''
mass loss rate van Loon etal (2005).
Parameters
----------
L : float
L in L_sun.
Teff : float
Teff in K.
Returns
-------
Mdot
Mdot in Msun/yr
Notes
-----
ref: van Loon etal 2005, A&A 438, 273
... | [
"def",
"mass_loss_loon05",
"(",
"L",
",",
"Teff",
")",
":",
"Mdot",
"=",
"-",
"5.65",
"+",
"np",
".",
"log10",
"(",
"old_div",
"(",
"L",
",",
"10.",
"**",
"4",
")",
")",
"-",
"6.3",
"*",
"np",
".",
"log10",
"(",
"old_div",
"(",
"Teff",
",",
"... | mass loss rate van Loon etal (2005).
Parameters
----------
L : float
L in L_sun.
Teff : float
Teff in K.
Returns
-------
Mdot
Mdot in Msun/yr
Notes
-----
ref: van Loon etal 2005, A&A 438, 273 | [
"mass",
"loss",
"rate",
"van",
"Loon",
"etal",
"(",
"2005",
")",
"."
] | python | train |
annoviko/pyclustering | pyclustering/cluster/clique.py | https://github.com/annoviko/pyclustering/blob/98aa0dd89fd36f701668fb1eb29c8fb5662bf7d0/pyclustering/cluster/clique.py#L108-L125 | def __draw_two_dimension_data(ax, data, pair):
"""!
@brief Display data in two-dimensional canvas.
@param[in] ax (Axis): Canvas where data should be displayed.
@param[in] data (list): Data points that should be displayed.
@param[in] pair (tuple): Pair of dimension indexes.... | [
"def",
"__draw_two_dimension_data",
"(",
"ax",
",",
"data",
",",
"pair",
")",
":",
"ax",
".",
"set_xlabel",
"(",
"\"x%d\"",
"%",
"pair",
"[",
"0",
"]",
")",
"ax",
".",
"set_ylabel",
"(",
"\"x%d\"",
"%",
"pair",
"[",
"1",
"]",
")",
"for",
"point",
"... | !
@brief Display data in two-dimensional canvas.
@param[in] ax (Axis): Canvas where data should be displayed.
@param[in] data (list): Data points that should be displayed.
@param[in] pair (tuple): Pair of dimension indexes. | [
"!"
] | python | valid |
pyQode/pyqode.core | pyqode/core/modes/filewatcher.py | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/modes/filewatcher.py#L184-L193 | def _check_for_pending(self, *args, **kwargs):
"""
Checks if a notification is pending.
"""
if self._notification_pending and not self._processing:
self._processing = True
args, kwargs = self._data
self._notify(*args, **kwargs)
self._notifi... | [
"def",
"_check_for_pending",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"_notification_pending",
"and",
"not",
"self",
".",
"_processing",
":",
"self",
".",
"_processing",
"=",
"True",
"args",
",",
"kwargs",
"=",... | Checks if a notification is pending. | [
"Checks",
"if",
"a",
"notification",
"is",
"pending",
"."
] | python | train |
trec-kba/streamcorpus-pipeline | streamcorpus_pipeline/_run_lingpipe.py | https://github.com/trec-kba/streamcorpus-pipeline/blob/8bb82ea1beb83c6b40ed03fa1659df2897c2292a/streamcorpus_pipeline/_run_lingpipe.py#L126-L192 | def align_chunk_with_ner(tmp_ner_path, i_chunk, tmp_done_path):
'''
iterate through the i_chunk and tmp_ner_path to generate a new
Chunk with body.ner
'''
o_chunk = Chunk()
input_iter = i_chunk.__iter__()
ner = ''
stream_id = None
all_ner = xml.dom.minidom.parse(open(tmp_ner_path))
... | [
"def",
"align_chunk_with_ner",
"(",
"tmp_ner_path",
",",
"i_chunk",
",",
"tmp_done_path",
")",
":",
"o_chunk",
"=",
"Chunk",
"(",
")",
"input_iter",
"=",
"i_chunk",
".",
"__iter__",
"(",
")",
"ner",
"=",
"''",
"stream_id",
"=",
"None",
"all_ner",
"=",
"xml... | iterate through the i_chunk and tmp_ner_path to generate a new
Chunk with body.ner | [
"iterate",
"through",
"the",
"i_chunk",
"and",
"tmp_ner_path",
"to",
"generate",
"a",
"new",
"Chunk",
"with",
"body",
".",
"ner"
] | python | test |
kodexlab/reliure | reliure/utils/log.py | https://github.com/kodexlab/reliure/blob/0450c7a9254c5c003162738458bbe0c49e777ba5/reliure/utils/log.py#L76-L119 | def get_app_logger_color(appname, app_log_level=logging.INFO, log_level=logging.WARN, logfile=None):
""" Configure the logging for an app using reliure (it log's both the app and reliure lib)
:param appname: the name of the application to log
:parap app_log_level: log level for the app
:param log_level... | [
"def",
"get_app_logger_color",
"(",
"appname",
",",
"app_log_level",
"=",
"logging",
".",
"INFO",
",",
"log_level",
"=",
"logging",
".",
"WARN",
",",
"logfile",
"=",
"None",
")",
":",
"# create lib handler",
"stderr_handler",
"=",
"logging",
".",
"StreamHandler"... | Configure the logging for an app using reliure (it log's both the app and reliure lib)
:param appname: the name of the application to log
:parap app_log_level: log level for the app
:param log_level: log level for the reliure
:param logfile: file that store the log, time rotating file (by day), no if N... | [
"Configure",
"the",
"logging",
"for",
"an",
"app",
"using",
"reliure",
"(",
"it",
"log",
"s",
"both",
"the",
"app",
"and",
"reliure",
"lib",
")"
] | python | train |
OpenHydrology/floodestimation | floodestimation/fehdata.py | https://github.com/OpenHydrology/floodestimation/blob/782da7c5abd1348923129efe89fb70003ebb088c/floodestimation/fehdata.py#L137-L157 | def nrfa_metadata():
"""
Return metadata on the NRFA data.
Returned metadata is a dict with the following elements:
- `url`: string with NRFA data download URL
- `version`: string with NRFA version number, e.g. '3.3.4'
- `published_on`: datetime of data release/publication (only month and year... | [
"def",
"nrfa_metadata",
"(",
")",
":",
"result",
"=",
"{",
"'url'",
":",
"config",
".",
"get",
"(",
"'nrfa'",
",",
"'url'",
",",
"fallback",
"=",
"None",
")",
"or",
"None",
",",
"# Empty strings '' become None",
"'version'",
":",
"config",
".",
"get",
"(... | Return metadata on the NRFA data.
Returned metadata is a dict with the following elements:
- `url`: string with NRFA data download URL
- `version`: string with NRFA version number, e.g. '3.3.4'
- `published_on`: datetime of data release/publication (only month and year are accurate, rest should be ign... | [
"Return",
"metadata",
"on",
"the",
"NRFA",
"data",
"."
] | python | train |
jayclassless/tidypy | src/tidypy/config.py | https://github.com/jayclassless/tidypy/blob/3c3497ca377fbbe937103b77b02b326c860c748f/src/tidypy/config.py#L124-L135 | def purge_config_cache(location=None):
"""
Clears out the cache of TidyPy configurations that were retrieved from
outside the normal locations.
"""
cache_path = get_cache_path(location)
if location:
os.remove(cache_path)
else:
shutil.rmtree(cache_path) | [
"def",
"purge_config_cache",
"(",
"location",
"=",
"None",
")",
":",
"cache_path",
"=",
"get_cache_path",
"(",
"location",
")",
"if",
"location",
":",
"os",
".",
"remove",
"(",
"cache_path",
")",
"else",
":",
"shutil",
".",
"rmtree",
"(",
"cache_path",
")"... | Clears out the cache of TidyPy configurations that were retrieved from
outside the normal locations. | [
"Clears",
"out",
"the",
"cache",
"of",
"TidyPy",
"configurations",
"that",
"were",
"retrieved",
"from",
"outside",
"the",
"normal",
"locations",
"."
] | python | valid |
christophertbrown/bioscripts | ctbBio/16SfromHMM.py | https://github.com/christophertbrown/bioscripts/blob/83b2566b3a5745437ec651cd6cafddd056846240/ctbBio/16SfromHMM.py#L85-L101 | def hit_groups(hits):
"""
* each sequence may have more than one 16S rRNA gene
* group hits for each gene
"""
groups = []
current = False
for hit in sorted(hits, key = itemgetter(0)):
if current is False:
current = [hit]
elif check_overlap(current, hit) is True or... | [
"def",
"hit_groups",
"(",
"hits",
")",
":",
"groups",
"=",
"[",
"]",
"current",
"=",
"False",
"for",
"hit",
"in",
"sorted",
"(",
"hits",
",",
"key",
"=",
"itemgetter",
"(",
"0",
")",
")",
":",
"if",
"current",
"is",
"False",
":",
"current",
"=",
... | * each sequence may have more than one 16S rRNA gene
* group hits for each gene | [
"*",
"each",
"sequence",
"may",
"have",
"more",
"than",
"one",
"16S",
"rRNA",
"gene",
"*",
"group",
"hits",
"for",
"each",
"gene"
] | python | train |
estnltk/estnltk | estnltk/text.py | https://github.com/estnltk/estnltk/blob/28ae334a68a0673072febc318635f04da0dcc54a/estnltk/text.py#L401-L405 | def paragraph_starts(self):
"""The start positions of ``paragraphs`` layer elements."""
if not self.is_tagged(PARAGRAPHS):
self.tokenize_paragraphs()
return self.starts(PARAGRAPHS) | [
"def",
"paragraph_starts",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_tagged",
"(",
"PARAGRAPHS",
")",
":",
"self",
".",
"tokenize_paragraphs",
"(",
")",
"return",
"self",
".",
"starts",
"(",
"PARAGRAPHS",
")"
] | The start positions of ``paragraphs`` layer elements. | [
"The",
"start",
"positions",
"of",
"paragraphs",
"layer",
"elements",
"."
] | python | train |
pbrod/numdifftools | src/numdifftools/step_generators.py | https://github.com/pbrod/numdifftools/blob/2c88878df732c9c6629febea56e7a91fd898398d/src/numdifftools/step_generators.py#L21-L29 | def valarray(shape, value=np.NaN, typecode=None):
"""Return an array of all value."""
if typecode is None:
typecode = bool
out = np.ones(shape, dtype=typecode) * value
if not isinstance(out, np.ndarray):
out = np.asarray(out)
return out | [
"def",
"valarray",
"(",
"shape",
",",
"value",
"=",
"np",
".",
"NaN",
",",
"typecode",
"=",
"None",
")",
":",
"if",
"typecode",
"is",
"None",
":",
"typecode",
"=",
"bool",
"out",
"=",
"np",
".",
"ones",
"(",
"shape",
",",
"dtype",
"=",
"typecode",
... | Return an array of all value. | [
"Return",
"an",
"array",
"of",
"all",
"value",
"."
] | python | train |
buriburisuri/sugartensor | sugartensor/sg_initializer.py | https://github.com/buriburisuri/sugartensor/blob/d2c039954777c7fbe3eb0c2ae40c45c9854deb40/sugartensor/sg_initializer.py#L152-L184 | def orthogonal(name, shape, scale=1.1, dtype=tf.sg_floatx, summary=True, regularizer=None, trainable=True):
r"""Creates a tensor variable of which initial values are of
an orthogonal ndarray.
See [Saxe et al. 2014.](http://arxiv.org/pdf/1312.6120.pdf)
Args:
name: The name of new variable... | [
"def",
"orthogonal",
"(",
"name",
",",
"shape",
",",
"scale",
"=",
"1.1",
",",
"dtype",
"=",
"tf",
".",
"sg_floatx",
",",
"summary",
"=",
"True",
",",
"regularizer",
"=",
"None",
",",
"trainable",
"=",
"True",
")",
":",
"flat_shape",
"=",
"(",
"shape... | r"""Creates a tensor variable of which initial values are of
an orthogonal ndarray.
See [Saxe et al. 2014.](http://arxiv.org/pdf/1312.6120.pdf)
Args:
name: The name of new variable.
shape: A tuple/list of integers.
scale: A Python scalar.
dtype: Either float32 or float64.
... | [
"r",
"Creates",
"a",
"tensor",
"variable",
"of",
"which",
"initial",
"values",
"are",
"of",
"an",
"orthogonal",
"ndarray",
".",
"See",
"[",
"Saxe",
"et",
"al",
".",
"2014",
".",
"]",
"(",
"http",
":",
"//",
"arxiv",
".",
"org",
"/",
"pdf",
"/",
"13... | python | train |
Ex-Mente/auxi.0 | auxi/modelling/process/materials/thermo.py | https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/process/materials/thermo.py#L1666-L1676 | def afr(self):
"""
Determine the sum of amount flow rates of all the compounds.
:returns: Amount flow rate. [kmol/h]
"""
result = 0.0
for compound in self.material.compounds:
result += self.get_compound_afr(compound)
return result | [
"def",
"afr",
"(",
"self",
")",
":",
"result",
"=",
"0.0",
"for",
"compound",
"in",
"self",
".",
"material",
".",
"compounds",
":",
"result",
"+=",
"self",
".",
"get_compound_afr",
"(",
"compound",
")",
"return",
"result"
] | Determine the sum of amount flow rates of all the compounds.
:returns: Amount flow rate. [kmol/h] | [
"Determine",
"the",
"sum",
"of",
"amount",
"flow",
"rates",
"of",
"all",
"the",
"compounds",
"."
] | python | valid |
annoviko/pyclustering | pyclustering/cluster/bang.py | https://github.com/annoviko/pyclustering/blob/98aa0dd89fd36f701668fb1eb29c8fb5662bf7d0/pyclustering/cluster/bang.py#L1128-L1141 | def __validate_arguments(self):
"""!
@brief Check input arguments of BANG algorithm and if one of them is not correct then appropriate exception
is thrown.
"""
if self.__levels <= 0:
raise ValueError("Incorrect amount of levels '%d'. Level value should... | [
"def",
"__validate_arguments",
"(",
"self",
")",
":",
"if",
"self",
".",
"__levels",
"<=",
"0",
":",
"raise",
"ValueError",
"(",
"\"Incorrect amount of levels '%d'. Level value should be greater than 0.\"",
"%",
"self",
".",
"__levels",
")",
"if",
"len",
"(",
"self"... | !
@brief Check input arguments of BANG algorithm and if one of them is not correct then appropriate exception
is thrown. | [
"!"
] | python | valid |
AndrewAnnex/SpiceyPy | spiceypy/spiceypy.py | https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L3833-L3868 | def ekacld(handle, segno, column, dvals, entszs, nlflgs, rcptrs, wkindx):
"""
Add an entire double precision column to an EK segment.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekacld_c.html
:param handle: EK file handle.
:type handle: int
:param segno: Number of segment to add co... | [
"def",
"ekacld",
"(",
"handle",
",",
"segno",
",",
"column",
",",
"dvals",
",",
"entszs",
",",
"nlflgs",
",",
"rcptrs",
",",
"wkindx",
")",
":",
"handle",
"=",
"ctypes",
".",
"c_int",
"(",
"handle",
")",
"segno",
"=",
"ctypes",
".",
"c_int",
"(",
"... | Add an entire double precision column to an EK segment.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekacld_c.html
:param handle: EK file handle.
:type handle: int
:param segno: Number of segment to add column to.
:type segno: int
:param column: Column name.
:type column: str
... | [
"Add",
"an",
"entire",
"double",
"precision",
"column",
"to",
"an",
"EK",
"segment",
"."
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.