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 |
|---|---|---|---|---|---|---|---|---|
intelsdi-x/snap-plugin-lib-py | snap_plugin/v1/plugin.py | https://github.com/intelsdi-x/snap-plugin-lib-py/blob/8da5d00ac5f9d2b48a7239563ac7788209891ca4/snap_plugin/v1/plugin.py#L755-L783 | def _monitor(last_ping, stop_plugin, is_shutting_down, timeout=5):
"""Monitors health checks (pings) from the Snap framework.
If the plugin doesn't receive 3 consecutive health checks from Snap the
plugin will shutdown. The default timeout is set to 5 seconds.
"""
_timeout_count = 0
_last_chec... | [
"def",
"_monitor",
"(",
"last_ping",
",",
"stop_plugin",
",",
"is_shutting_down",
",",
"timeout",
"=",
"5",
")",
":",
"_timeout_count",
"=",
"0",
"_last_check",
"=",
"time",
".",
"time",
"(",
")",
"_sleep_interval",
"=",
"1",
"# set _sleep_interval if less than ... | Monitors health checks (pings) from the Snap framework.
If the plugin doesn't receive 3 consecutive health checks from Snap the
plugin will shutdown. The default timeout is set to 5 seconds. | [
"Monitors",
"health",
"checks",
"(",
"pings",
")",
"from",
"the",
"Snap",
"framework",
"."
] | python | train |
log2timeline/plaso | plaso/parsers/manager.py | https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/parsers/manager.py#L476-L492 | def RegisterParser(cls, parser_class):
"""Registers a parser class.
The parser classes are identified based on their lower case name.
Args:
parser_class (type): parser class (subclass of BaseParser).
Raises:
KeyError: if parser class is already set for the corresponding name.
"""
... | [
"def",
"RegisterParser",
"(",
"cls",
",",
"parser_class",
")",
":",
"parser_name",
"=",
"parser_class",
".",
"NAME",
".",
"lower",
"(",
")",
"if",
"parser_name",
"in",
"cls",
".",
"_parser_classes",
":",
"raise",
"KeyError",
"(",
"'Parser class already set for n... | Registers a parser class.
The parser classes are identified based on their lower case name.
Args:
parser_class (type): parser class (subclass of BaseParser).
Raises:
KeyError: if parser class is already set for the corresponding name. | [
"Registers",
"a",
"parser",
"class",
"."
] | python | train |
richq/cmake-lint | cmakelint/main.py | https://github.com/richq/cmake-lint/blob/058c6c0ed2536abd3e79a51c38ee6e686568e3b3/cmakelint/main.py#L91-L101 | def DefaultRC():
"""
Check XDG_CONFIG_DIR before ~/.cmakelintrc
"""
xdg = os.path.join(os.path.expanduser('~'), '.config')
if 'XDG_CONFIG_DIR' in os.environ:
xdg = os.environ['XDG_CONFIG_DIR']
xdgfile = os.path.join(xdg, 'cmakelintrc')
if os.path.exists(xdgfile):
return xdgfi... | [
"def",
"DefaultRC",
"(",
")",
":",
"xdg",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"'~'",
")",
",",
"'.config'",
")",
"if",
"'XDG_CONFIG_DIR'",
"in",
"os",
".",
"environ",
":",
"xdg",
"=",
"os",
".",
"e... | Check XDG_CONFIG_DIR before ~/.cmakelintrc | [
"Check",
"XDG_CONFIG_DIR",
"before",
"~",
"/",
".",
"cmakelintrc"
] | python | train |
spyder-ide/spyder | spyder/widgets/mixins.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/mixins.py#L1054-L1076 | def find_in_history(self, tocursor, start_idx, backward):
"""Find text 'tocursor' in history, from index 'start_idx'"""
if start_idx is None:
start_idx = len(self.history)
# Finding text in history
step = -1 if backward else 1
idx = start_idx
if len(toc... | [
"def",
"find_in_history",
"(",
"self",
",",
"tocursor",
",",
"start_idx",
",",
"backward",
")",
":",
"if",
"start_idx",
"is",
"None",
":",
"start_idx",
"=",
"len",
"(",
"self",
".",
"history",
")",
"# Finding text in history\r",
"step",
"=",
"-",
"1",
"if"... | Find text 'tocursor' in history, from index 'start_idx | [
"Find",
"text",
"tocursor",
"in",
"history",
"from",
"index",
"start_idx"
] | python | train |
DistrictDataLabs/yellowbrick | yellowbrick/model_selection/cross_validation.py | https://github.com/DistrictDataLabs/yellowbrick/blob/59b67236a3862c73363e8edad7cd86da5b69e3b2/yellowbrick/model_selection/cross_validation.py#L176-L241 | def cv_scores(model, X, y, ax=None, cv=None, scoring=None, **kwargs):
"""
Displays cross validation scores as a bar chart and the
average of the scores as a horizontal line
This helper function is a quick wrapper to utilize the
CVScores visualizer for one-off analysis.
Parameters
---------... | [
"def",
"cv_scores",
"(",
"model",
",",
"X",
",",
"y",
",",
"ax",
"=",
"None",
",",
"cv",
"=",
"None",
",",
"scoring",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# Initialize the visualizer",
"visualizer",
"=",
"CVScores",
"(",
"model",
",",
"ax... | Displays cross validation scores as a bar chart and the
average of the scores as a horizontal line
This helper function is a quick wrapper to utilize the
CVScores visualizer for one-off analysis.
Parameters
----------
model : a scikit-learn estimator
An object that implements ``fit`` ... | [
"Displays",
"cross",
"validation",
"scores",
"as",
"a",
"bar",
"chart",
"and",
"the",
"average",
"of",
"the",
"scores",
"as",
"a",
"horizontal",
"line"
] | python | train |
tensorflow/tensor2tensor | tensor2tensor/layers/area_attention.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/area_attention.py#L78-L128 | def basic_pool(features, max_area_width, max_area_height=1, height=1,
fn=tf.reduce_max, name=None):
"""Pools for each area based on a given pooling function (fn).
Args:
features: a Tensor in a shape of [batch_size, height * width, depth].
max_area_width: the max width allowed for an area.
... | [
"def",
"basic_pool",
"(",
"features",
",",
"max_area_width",
",",
"max_area_height",
"=",
"1",
",",
"height",
"=",
"1",
",",
"fn",
"=",
"tf",
".",
"reduce_max",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"name_scope",
"(",
"name",
",",
"d... | Pools for each area based on a given pooling function (fn).
Args:
features: a Tensor in a shape of [batch_size, height * width, depth].
max_area_width: the max width allowed for an area.
max_area_height: the max height allowed for an area.
height: the height of the image.
fn: the TF function for ... | [
"Pools",
"for",
"each",
"area",
"based",
"on",
"a",
"given",
"pooling",
"function",
"(",
"fn",
")",
"."
] | python | train |
brocade/pynos | pynos/versions/ver_6/ver_6_0_1/yang/brocade_interface_ext.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_interface_ext.py#L12-L25 | def get_vlan_brief_input_request_type_get_request_vlan_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_vlan_brief = ET.Element("get_vlan_brief")
config = get_vlan_brief
input = ET.SubElement(get_vlan_brief, "input")
request_type = ... | [
"def",
"get_vlan_brief_input_request_type_get_request_vlan_id",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"get_vlan_brief",
"=",
"ET",
".",
"Element",
"(",
"\"get_vlan_brief\"",
")",
"config",
"=... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train |
mlperf/training | reinforcement/tensorflow/minigo/gtp_engine.py | https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/gtp_engine.py#L133-L151 | def add_cmd_handler(self, handler_obj):
"""Registers a new command handler object.
All methods on `handler_obj` whose name starts with "cmd_" are
registered as a GTP command. For example, the method cmd_genmove will
be invoked when the engine receives a genmove command.
Args:
... | [
"def",
"add_cmd_handler",
"(",
"self",
",",
"handler_obj",
")",
":",
"for",
"field",
"in",
"dir",
"(",
"handler_obj",
")",
":",
"if",
"field",
".",
"startswith",
"(",
"\"cmd_\"",
")",
":",
"cmd",
"=",
"field",
"[",
"4",
":",
"]",
"fn",
"=",
"getattr"... | Registers a new command handler object.
All methods on `handler_obj` whose name starts with "cmd_" are
registered as a GTP command. For example, the method cmd_genmove will
be invoked when the engine receives a genmove command.
Args:
handler_obj: the handler object to registe... | [
"Registers",
"a",
"new",
"command",
"handler",
"object",
"."
] | python | train |
brentp/skidmarks | skidmarks.py | https://github.com/brentp/skidmarks/blob/f63b9f1b822cb47991215b655155b5041e86ea39/skidmarks.py#L102-L129 | def auto_correlation(sequence):
"""
test for the autocorrelation of a sequence between t and t - 1
as the 'auto_correlation' it is less likely that the sequence is
generated randomly.
:param sequence: any iterable with at most 2 values that can be turned
into a float via np.floa... | [
"def",
"auto_correlation",
"(",
"sequence",
")",
":",
"if",
"isinstance",
"(",
"sequence",
",",
"basestring",
")",
":",
"sequence",
"=",
"map",
"(",
"int",
",",
"sequence",
")",
"seq",
"=",
"np",
".",
"array",
"(",
"list",
"(",
"sequence",
")",
",",
... | test for the autocorrelation of a sequence between t and t - 1
as the 'auto_correlation' it is less likely that the sequence is
generated randomly.
:param sequence: any iterable with at most 2 values that can be turned
into a float via np.float . e.g.
'1001001'
... | [
"test",
"for",
"the",
"autocorrelation",
"of",
"a",
"sequence",
"between",
"t",
"and",
"t",
"-",
"1",
"as",
"the",
"auto_correlation",
"it",
"is",
"less",
"likely",
"that",
"the",
"sequence",
"is",
"generated",
"randomly",
".",
":",
"param",
"sequence",
":... | python | train |
DistrictDataLabs/yellowbrick | yellowbrick/datasets/loaders.py | https://github.com/DistrictDataLabs/yellowbrick/blob/59b67236a3862c73363e8edad7cd86da5b69e3b2/yellowbrick/datasets/loaders.py#L53-L58 | def _load_corpus(name, data_home=None):
"""
Load a corpus object by name.
"""
info = DATASETS[name]
return Corpus(name, data_home=data_home, **info) | [
"def",
"_load_corpus",
"(",
"name",
",",
"data_home",
"=",
"None",
")",
":",
"info",
"=",
"DATASETS",
"[",
"name",
"]",
"return",
"Corpus",
"(",
"name",
",",
"data_home",
"=",
"data_home",
",",
"*",
"*",
"info",
")"
] | Load a corpus object by name. | [
"Load",
"a",
"corpus",
"object",
"by",
"name",
"."
] | python | train |
sebp/scikit-survival | sksurv/linear_model/coxnet.py | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/linear_model/coxnet.py#L239-L263 | def _interpolate_coefficients(self, alpha):
"""Interpolate coefficients by calculating the weighted average of coefficient vectors corresponding to
neighbors of alpha in the list of alphas constructed during training."""
exact = False
coef_idx = None
for i, val in enumerate(self.... | [
"def",
"_interpolate_coefficients",
"(",
"self",
",",
"alpha",
")",
":",
"exact",
"=",
"False",
"coef_idx",
"=",
"None",
"for",
"i",
",",
"val",
"in",
"enumerate",
"(",
"self",
".",
"alphas_",
")",
":",
"if",
"val",
">",
"alpha",
":",
"coef_idx",
"=",
... | Interpolate coefficients by calculating the weighted average of coefficient vectors corresponding to
neighbors of alpha in the list of alphas constructed during training. | [
"Interpolate",
"coefficients",
"by",
"calculating",
"the",
"weighted",
"average",
"of",
"coefficient",
"vectors",
"corresponding",
"to",
"neighbors",
"of",
"alpha",
"in",
"the",
"list",
"of",
"alphas",
"constructed",
"during",
"training",
"."
] | python | train |
SBRG/ssbio | ssbio/protein/sequence/properties/residues.py | https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/protein/sequence/properties/residues.py#L113-L134 | def biopython_protein_scale(inseq, scale, custom_scale_dict=None, window=7):
"""Use Biopython to calculate properties using a sliding window over a sequence given a specific scale to use."""
if scale == 'kd_hydrophobicity':
scale_dict = kd_hydrophobicity_one
elif scale == 'bulkiness':
scale... | [
"def",
"biopython_protein_scale",
"(",
"inseq",
",",
"scale",
",",
"custom_scale_dict",
"=",
"None",
",",
"window",
"=",
"7",
")",
":",
"if",
"scale",
"==",
"'kd_hydrophobicity'",
":",
"scale_dict",
"=",
"kd_hydrophobicity_one",
"elif",
"scale",
"==",
"'bulkines... | Use Biopython to calculate properties using a sliding window over a sequence given a specific scale to use. | [
"Use",
"Biopython",
"to",
"calculate",
"properties",
"using",
"a",
"sliding",
"window",
"over",
"a",
"sequence",
"given",
"a",
"specific",
"scale",
"to",
"use",
"."
] | python | train |
MKLab-ITI/reveal-user-annotation | reveal_user_annotation/text/text_util.py | https://github.com/MKLab-ITI/reveal-user-annotation/blob/ed019c031857b091e5601f53ba3f01a499a0e3ef/reveal_user_annotation/text/text_util.py#L25-L42 | def reduce_list_of_bags_of_words(list_of_keyword_sets):
"""
Reduces a number of keyword sets to a bag-of-words.
Input: - list_of_keyword_sets: This is a python list of sets of strings.
Output: - bag_of_words: This is the corresponding multi-set or bag-of-words, in the form of a python dictionary.
... | [
"def",
"reduce_list_of_bags_of_words",
"(",
"list_of_keyword_sets",
")",
":",
"bag_of_words",
"=",
"dict",
"(",
")",
"get_bag_of_words_keys",
"=",
"bag_of_words",
".",
"keys",
"for",
"keyword_set",
"in",
"list_of_keyword_sets",
":",
"for",
"keyword",
"in",
"keyword_se... | Reduces a number of keyword sets to a bag-of-words.
Input: - list_of_keyword_sets: This is a python list of sets of strings.
Output: - bag_of_words: This is the corresponding multi-set or bag-of-words, in the form of a python dictionary. | [
"Reduces",
"a",
"number",
"of",
"keyword",
"sets",
"to",
"a",
"bag",
"-",
"of",
"-",
"words",
"."
] | python | train |
globality-corp/microcosm-flask | microcosm_flask/conventions/discovery.py | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/conventions/discovery.py#L16-L27 | def iter_links(operations, page):
"""
Generate links for an iterable of operations on a starting page.
"""
for operation, ns, rule, func in operations:
yield Link.for_(
operation=operation,
ns=ns,
type=ns.subject_name,
qs=page.to_items(),
... | [
"def",
"iter_links",
"(",
"operations",
",",
"page",
")",
":",
"for",
"operation",
",",
"ns",
",",
"rule",
",",
"func",
"in",
"operations",
":",
"yield",
"Link",
".",
"for_",
"(",
"operation",
"=",
"operation",
",",
"ns",
"=",
"ns",
",",
"type",
"=",... | Generate links for an iterable of operations on a starting page. | [
"Generate",
"links",
"for",
"an",
"iterable",
"of",
"operations",
"on",
"a",
"starting",
"page",
"."
] | python | train |
aws/sagemaker-python-sdk | src/sagemaker/fw_utils.py | https://github.com/aws/sagemaker-python-sdk/blob/a9e724c7d3f5572b68c3903548c792a59d99799a/src/sagemaker/fw_utils.py#L125-L139 | def validate_source_dir(script, directory):
"""Validate that the source directory exists and it contains the user script
Args:
script (str): Script filename.
directory (str): Directory containing the source file.
Raises:
ValueError: If ``directory`` does not exist, is not a direct... | [
"def",
"validate_source_dir",
"(",
"script",
",",
"directory",
")",
":",
"if",
"directory",
":",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"os",
".",
"path",
".",
"join",
"(",
"directory",
",",
"script",
")",
")",
":",
"raise",
"ValueError",
... | Validate that the source directory exists and it contains the user script
Args:
script (str): Script filename.
directory (str): Directory containing the source file.
Raises:
ValueError: If ``directory`` does not exist, is not a directory, or does not contain ``script``. | [
"Validate",
"that",
"the",
"source",
"directory",
"exists",
"and",
"it",
"contains",
"the",
"user",
"script"
] | python | train |
linjackson78/jstyleson | jstyleson.py | https://github.com/linjackson78/jstyleson/blob/a5aff96642684118a9a5efcb69e366f8b840346b/jstyleson.py#L4-L99 | def dispose(json_str):
"""Clear all comments in json_str.
Clear JS-style comments like // and /**/ in json_str.
Accept a str or unicode as input.
Args:
json_str: A json string of str or unicode to clean up comment
Returns:
str: The str without comments (or unicode if you pass in u... | [
"def",
"dispose",
"(",
"json_str",
")",
":",
"result_str",
"=",
"list",
"(",
"json_str",
")",
"escaped",
"=",
"False",
"normal",
"=",
"True",
"sl_comment",
"=",
"False",
"ml_comment",
"=",
"False",
"quoted",
"=",
"False",
"a_step_from_comment",
"=",
"False",... | Clear all comments in json_str.
Clear JS-style comments like // and /**/ in json_str.
Accept a str or unicode as input.
Args:
json_str: A json string of str or unicode to clean up comment
Returns:
str: The str without comments (or unicode if you pass in unicode) | [
"Clear",
"all",
"comments",
"in",
"json_str",
"."
] | python | test |
datacamp/pythonwhat | pythonwhat/checks/check_funcs.py | https://github.com/datacamp/pythonwhat/blob/ffbf7f8436a51f77c22f3bed75ba3bc37a5c666f/pythonwhat/checks/check_funcs.py#L212-L280 | def check_args(state, name, missing_msg=None):
"""Check whether a function argument is specified.
This function can follow ``check_function()`` in an SCT chain and verifies whether an argument is specified.
If you want to go on and check whether the argument was correctly specified, you can can continue ch... | [
"def",
"check_args",
"(",
"state",
",",
"name",
",",
"missing_msg",
"=",
"None",
")",
":",
"if",
"missing_msg",
"is",
"None",
":",
"missing_msg",
"=",
"\"Did you specify the {{part}}?\"",
"if",
"name",
"in",
"[",
"\"*args\"",
",",
"\"**kwargs\"",
"]",
":",
"... | Check whether a function argument is specified.
This function can follow ``check_function()`` in an SCT chain and verifies whether an argument is specified.
If you want to go on and check whether the argument was correctly specified, you can can continue chaining with
``has_equal_value()`` (value-based che... | [
"Check",
"whether",
"a",
"function",
"argument",
"is",
"specified",
"."
] | python | test |
ARMmbed/yotta | yotta/lib/registry_access.py | https://github.com/ARMmbed/yotta/blob/56bc1e56c602fa20307b23fe27518e9cd6c11af1/yotta/lib/registry_access.py#L621-L646 | def removeOwner(namespace, name, owner, registry=None):
''' Remove an owner for a module or target (owners are the people with
permission to publish versions and add/remove the owners).
'''
registry = registry or Registry_Base_URL
url = '%s/%s/%s/owners/%s' % (
registry,
namespa... | [
"def",
"removeOwner",
"(",
"namespace",
",",
"name",
",",
"owner",
",",
"registry",
"=",
"None",
")",
":",
"registry",
"=",
"registry",
"or",
"Registry_Base_URL",
"url",
"=",
"'%s/%s/%s/owners/%s'",
"%",
"(",
"registry",
",",
"namespace",
",",
"name",
",",
... | Remove an owner for a module or target (owners are the people with
permission to publish versions and add/remove the owners). | [
"Remove",
"an",
"owner",
"for",
"a",
"module",
"or",
"target",
"(",
"owners",
"are",
"the",
"people",
"with",
"permission",
"to",
"publish",
"versions",
"and",
"add",
"/",
"remove",
"the",
"owners",
")",
"."
] | python | valid |
cloudbase/python-hnvclient | hnv/common/utils.py | https://github.com/cloudbase/python-hnvclient/blob/b019452af01db22629809b8930357a2ebf6494be/hnv/common/utils.py#L59-L79 | def _session(self):
"""The current session used by the client.
The Session object allows you to persist certain parameters across
requests. It also persists cookies across all requests made from
the Session instance, and will use urllib3's connection pooling.
So if you're making... | [
"def",
"_session",
"(",
"self",
")",
":",
"if",
"self",
".",
"_http_session",
"is",
"None",
":",
"self",
".",
"_http_session",
"=",
"requests",
".",
"Session",
"(",
")",
"self",
".",
"_http_session",
".",
"headers",
".",
"update",
"(",
"self",
".",
"_g... | The current session used by the client.
The Session object allows you to persist certain parameters across
requests. It also persists cookies across all requests made from
the Session instance, and will use urllib3's connection pooling.
So if you're making several requests to the same h... | [
"The",
"current",
"session",
"used",
"by",
"the",
"client",
"."
] | python | train |
Rapptz/discord.py | discord/message.py | https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/message.py#L678-L697 | async def unpin(self):
"""|coro|
Unpins the message.
You must have the :attr:`~Permissions.manage_messages` permission to do
this in a non-private channel context.
Raises
-------
Forbidden
You do not have permissions to unpin the message.
No... | [
"async",
"def",
"unpin",
"(",
"self",
")",
":",
"await",
"self",
".",
"_state",
".",
"http",
".",
"unpin_message",
"(",
"self",
".",
"channel",
".",
"id",
",",
"self",
".",
"id",
")",
"self",
".",
"pinned",
"=",
"False"
] | |coro|
Unpins the message.
You must have the :attr:`~Permissions.manage_messages` permission to do
this in a non-private channel context.
Raises
-------
Forbidden
You do not have permissions to unpin the message.
NotFound
The message or ... | [
"|coro|"
] | python | train |
lisael/fastidious | fastidious/parser_base.py | https://github.com/lisael/fastidious/blob/2542db9de779ddabc3a64e9eb19a4e2de99741dc/fastidious/parser_base.py#L199-L212 | def p_parse(cls, input, methodname=None, parse_all=True):
"""
Parse the `input` using `methodname` as entry point.
If `parse_all` is true, the input MUST be fully consumed at the end of
the parsing, otherwise p_parse raises an exception.
"""
if methodname is None:
... | [
"def",
"p_parse",
"(",
"cls",
",",
"input",
",",
"methodname",
"=",
"None",
",",
"parse_all",
"=",
"True",
")",
":",
"if",
"methodname",
"is",
"None",
":",
"methodname",
"=",
"cls",
".",
"__default__",
"p",
"=",
"cls",
"(",
"input",
")",
"result",
"=... | Parse the `input` using `methodname` as entry point.
If `parse_all` is true, the input MUST be fully consumed at the end of
the parsing, otherwise p_parse raises an exception. | [
"Parse",
"the",
"input",
"using",
"methodname",
"as",
"entry",
"point",
"."
] | python | train |
gabstopper/smc-python | smc/administration/system.py | https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/administration/system.py#L240-L254 | def visible_security_group_mapping(self, filter=None): # @ReservedAssignment
"""
Return all security groups assigned to VSS container types. This
is only available on SMC >= 6.5.
:param str filter: filter for searching by name
:raises ActionCommandFailed: element not fo... | [
"def",
"visible_security_group_mapping",
"(",
"self",
",",
"filter",
"=",
"None",
")",
":",
"# @ReservedAssignment",
"if",
"'visible_security_group_mapping'",
"not",
"in",
"self",
".",
"data",
".",
"links",
":",
"raise",
"ResourceNotFound",
"(",
"'This entry point is ... | Return all security groups assigned to VSS container types. This
is only available on SMC >= 6.5.
:param str filter: filter for searching by name
:raises ActionCommandFailed: element not found on this version of SMC
:raises ResourceNotFound: unsupported method on SMC < 6.5
... | [
"Return",
"all",
"security",
"groups",
"assigned",
"to",
"VSS",
"container",
"types",
".",
"This",
"is",
"only",
"available",
"on",
"SMC",
">",
"=",
"6",
".",
"5",
".",
":",
"param",
"str",
"filter",
":",
"filter",
"for",
"searching",
"by",
"name",
":"... | python | train |
MycroftAI/adapt | adapt/expander.py | https://github.com/MycroftAI/adapt/blob/334f23248b8e09fb9d84a88398424ec5bd3bae4c/adapt/expander.py#L227-L267 | def _sub_expand(self, tags):
"""This called by expand to find cliques
Args:
tags (list): a list of the tags used to get cliques
Yields:
list : list of sorted tags by start_token this is a clique
"""
entities = {}
graph = self._build_graph(tags)
... | [
"def",
"_sub_expand",
"(",
"self",
",",
"tags",
")",
":",
"entities",
"=",
"{",
"}",
"graph",
"=",
"self",
".",
"_build_graph",
"(",
"tags",
")",
"# name entities",
"for",
"tag",
"in",
"tags",
":",
"for",
"entity_index",
"in",
"xrange",
"(",
"len",
"("... | This called by expand to find cliques
Args:
tags (list): a list of the tags used to get cliques
Yields:
list : list of sorted tags by start_token this is a clique | [
"This",
"called",
"by",
"expand",
"to",
"find",
"cliques"
] | python | train |
shapiromatron/bmds | bmds/drunner.py | https://github.com/shapiromatron/bmds/blob/395c6ce84ad82876fd9fa4a89a3497fb61616de0/bmds/drunner.py#L41-L87 | def execute_job(self, obj):
"""
Execute the BMDS model and parse outputs if successful.
"""
# get executable path
exe = session.BMDS.get_model(obj["bmds_version"], obj["model_name"]).get_exe_path()
# write dfile
dfile = self.tempfiles.get_tempfile(prefix="bmds-d... | [
"def",
"execute_job",
"(",
"self",
",",
"obj",
")",
":",
"# get executable path",
"exe",
"=",
"session",
".",
"BMDS",
".",
"get_model",
"(",
"obj",
"[",
"\"bmds_version\"",
"]",
",",
"obj",
"[",
"\"model_name\"",
"]",
")",
".",
"get_exe_path",
"(",
")",
... | Execute the BMDS model and parse outputs if successful. | [
"Execute",
"the",
"BMDS",
"model",
"and",
"parse",
"outputs",
"if",
"successful",
"."
] | python | train |
noahbenson/neuropythy | neuropythy/io/core.py | https://github.com/noahbenson/neuropythy/blob/b588889f6db36ddb9602ae4a72c1c0d3f41586b2/neuropythy/io/core.py#L287-L299 | def load_csv(filename, **kw):
'''
load_csv(filename) yields a pandas dataframe of the contents of the CSV file. If pandas cannot
be loaded, then an error is raised.
All optional arguments are passed along to the pandas.read_csv function.
'''
import pandas
if any(filename.endswith(s) for s... | [
"def",
"load_csv",
"(",
"filename",
",",
"*",
"*",
"kw",
")",
":",
"import",
"pandas",
"if",
"any",
"(",
"filename",
".",
"endswith",
"(",
"s",
")",
"for",
"s",
"in",
"(",
"'.gz'",
",",
"'.bz2'",
",",
"'.lzma'",
")",
")",
":",
"with",
"gzip",
"."... | load_csv(filename) yields a pandas dataframe of the contents of the CSV file. If pandas cannot
be loaded, then an error is raised.
All optional arguments are passed along to the pandas.read_csv function. | [
"load_csv",
"(",
"filename",
")",
"yields",
"a",
"pandas",
"dataframe",
"of",
"the",
"contents",
"of",
"the",
"CSV",
"file",
".",
"If",
"pandas",
"cannot",
"be",
"loaded",
"then",
"an",
"error",
"is",
"raised",
"."
] | python | train |
autokey/autokey | lib/autokey/scripting.py | https://github.com/autokey/autokey/blob/35decb72f286ce68cd2a1f09ace8891a520b58d1/lib/autokey/scripting.py#L568-L590 | def password_dialog(self, title="Enter password", message="Enter password", **kwargs):
"""
Show a password input dialog
Usage: C{dialog.password_dialog(title="Enter password", message="Enter password")}
@param title: window title for the dialog
@param message: m... | [
"def",
"password_dialog",
"(",
"self",
",",
"title",
"=",
"\"Enter password\"",
",",
"message",
"=",
"\"Enter password\"",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_run_zenity",
"(",
"title",
",",
"[",
"\"--entry\"",
",",
"\"--text\"",
",",... | Show a password input dialog
Usage: C{dialog.password_dialog(title="Enter password", message="Enter password")}
@param title: window title for the dialog
@param message: message displayed above the password input box
@return: a tuple containing the exit code and user in... | [
"Show",
"a",
"password",
"input",
"dialog",
"Usage",
":",
"C",
"{",
"dialog",
".",
"password_dialog",
"(",
"title",
"=",
"Enter",
"password",
"message",
"=",
"Enter",
"password",
")",
"}"
] | python | train |
MacHu-GWU/sqlalchemy_mate-project | sqlalchemy_mate/crud/selecting.py | https://github.com/MacHu-GWU/sqlalchemy_mate-project/blob/946754744c8870f083fd7b4339fca15d1d6128b2/sqlalchemy_mate/crud/selecting.py#L10-L23 | def count_row(engine, table):
"""
Return number of rows in a table.
Example::
>>> count_row(engine, table_user)
3
**中文文档**
返回一个表中的行数。
"""
return engine.execute(select([func.count()]).select_from(table)).fetchone()[0] | [
"def",
"count_row",
"(",
"engine",
",",
"table",
")",
":",
"return",
"engine",
".",
"execute",
"(",
"select",
"(",
"[",
"func",
".",
"count",
"(",
")",
"]",
")",
".",
"select_from",
"(",
"table",
")",
")",
".",
"fetchone",
"(",
")",
"[",
"0",
"]"... | Return number of rows in a table.
Example::
>>> count_row(engine, table_user)
3
**中文文档**
返回一个表中的行数。 | [
"Return",
"number",
"of",
"rows",
"in",
"a",
"table",
"."
] | python | train |
noahbenson/neuropythy | neuropythy/geometry/mesh.py | https://github.com/noahbenson/neuropythy/blob/b588889f6db36ddb9602ae4a72c1c0d3f41586b2/neuropythy/geometry/mesh.py#L3899-L3911 | def path_trace(map_projection, pts, closed=False, meta_data=None):
'''
path_trace(proj, points) yields a path-trace object that represents the given path of points on
the given map projection proj.
The following options may be given:
* closed (default: False) specifies whether the points fo... | [
"def",
"path_trace",
"(",
"map_projection",
",",
"pts",
",",
"closed",
"=",
"False",
",",
"meta_data",
"=",
"None",
")",
":",
"return",
"PathTrace",
"(",
"map_projection",
",",
"pts",
",",
"closed",
"=",
"closed",
",",
"meta_data",
"=",
"meta_data",
")"
] | path_trace(proj, points) yields a path-trace object that represents the given path of points on
the given map projection proj.
The following options may be given:
* closed (default: False) specifies whether the points form a closed loop. If they do form
such a loop, the points should be giv... | [
"path_trace",
"(",
"proj",
"points",
")",
"yields",
"a",
"path",
"-",
"trace",
"object",
"that",
"represents",
"the",
"given",
"path",
"of",
"points",
"on",
"the",
"given",
"map",
"projection",
"proj",
".",
"The",
"following",
"options",
"may",
"be",
"give... | python | train |
vertexproject/synapse | synapse/lib/cache.py | https://github.com/vertexproject/synapse/blob/22e67c5a8f6d7caddbcf34b39ab1bd2d6c4a6e0b/synapse/lib/cache.py#L101-L108 | def get(self, key, default=None):
'''
Note: we override default impl from parent to avoid costly KeyError
'''
valu = self.data.get(key, default)
if key in self.data:
self.data.move_to_end(key)
return valu | [
"def",
"get",
"(",
"self",
",",
"key",
",",
"default",
"=",
"None",
")",
":",
"valu",
"=",
"self",
".",
"data",
".",
"get",
"(",
"key",
",",
"default",
")",
"if",
"key",
"in",
"self",
".",
"data",
":",
"self",
".",
"data",
".",
"move_to_end",
"... | Note: we override default impl from parent to avoid costly KeyError | [
"Note",
":",
"we",
"override",
"default",
"impl",
"from",
"parent",
"to",
"avoid",
"costly",
"KeyError"
] | python | train |
google/grumpy | third_party/stdlib/rfc822.py | https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/rfc822.py#L338-L358 | def getaddrlist(self, name):
"""Get a list of addresses from a header.
Retrieves a list of addresses from a header, where each address is a
tuple as returned by getaddr(). Scans all named headers, so it works
properly with multiple To: or Cc: headers for example.
"""
ra... | [
"def",
"getaddrlist",
"(",
"self",
",",
"name",
")",
":",
"raw",
"=",
"[",
"]",
"for",
"h",
"in",
"self",
".",
"getallmatchingheaders",
"(",
"name",
")",
":",
"if",
"h",
"[",
"0",
"]",
"in",
"' \\t'",
":",
"raw",
".",
"append",
"(",
"h",
")",
"... | Get a list of addresses from a header.
Retrieves a list of addresses from a header, where each address is a
tuple as returned by getaddr(). Scans all named headers, so it works
properly with multiple To: or Cc: headers for example. | [
"Get",
"a",
"list",
"of",
"addresses",
"from",
"a",
"header",
"."
] | python | valid |
satellogic/telluric | telluric/features.py | https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/features.py#L262-L280 | def copy_with(self, geometry=None, properties=None, assets=None):
"""Generate a new GeoFeature with different geometry or preperties."""
def copy_assets_object(asset):
obj = asset.get("__object")
if hasattr("copy", obj):
new_obj = obj.copy()
if obj:
... | [
"def",
"copy_with",
"(",
"self",
",",
"geometry",
"=",
"None",
",",
"properties",
"=",
"None",
",",
"assets",
"=",
"None",
")",
":",
"def",
"copy_assets_object",
"(",
"asset",
")",
":",
"obj",
"=",
"asset",
".",
"get",
"(",
"\"__object\"",
")",
"if",
... | Generate a new GeoFeature with different geometry or preperties. | [
"Generate",
"a",
"new",
"GeoFeature",
"with",
"different",
"geometry",
"or",
"preperties",
"."
] | python | train |
androguard/androguard | androguard/core/bytecodes/dvm.py | https://github.com/androguard/androguard/blob/984c0d981be2950cf0451e484f7b0d4d53bc4911/androguard/core/bytecodes/dvm.py#L4509-L4515 | def get_keys(self):
"""
Return the keys of the instruction
:rtype: a list of long
"""
return [(self.first_key + i) for i in range(0, len(self.targets))] | [
"def",
"get_keys",
"(",
"self",
")",
":",
"return",
"[",
"(",
"self",
".",
"first_key",
"+",
"i",
")",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"self",
".",
"targets",
")",
")",
"]"
] | Return the keys of the instruction
:rtype: a list of long | [
"Return",
"the",
"keys",
"of",
"the",
"instruction"
] | python | train |
chrislit/abydos | abydos/phonetic/_koelner.py | https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/phonetic/_koelner.py#L57-L197 | def encode(self, word):
"""Return the Kölner Phonetik (numeric output) code for a word.
While the output code is numeric, it is still a str because 0s can lead
the code.
Parameters
----------
word : str
The word to transform
Returns
-------
... | [
"def",
"encode",
"(",
"self",
",",
"word",
")",
":",
"def",
"_after",
"(",
"word",
",",
"pos",
",",
"letters",
")",
":",
"\"\"\"Return True if word[pos] follows one of the supplied letters.\n\n Parameters\n ----------\n word : str\n ... | Return the Kölner Phonetik (numeric output) code for a word.
While the output code is numeric, it is still a str because 0s can lead
the code.
Parameters
----------
word : str
The word to transform
Returns
-------
str
The Kölner ... | [
"Return",
"the",
"Kölner",
"Phonetik",
"(",
"numeric",
"output",
")",
"code",
"for",
"a",
"word",
"."
] | python | valid |
saltstack/salt | salt/returners/mongo_return.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/mongo_return.py#L127-L165 | def _get_conn(ret):
'''
Return a mongodb connection object
'''
_options = _get_options(ret)
host = _options.get('host')
port = _options.get('port')
db_ = _options.get('db')
user = _options.get('user')
password = _options.get('password')
indexes = _options.get('indexes', False)
... | [
"def",
"_get_conn",
"(",
"ret",
")",
":",
"_options",
"=",
"_get_options",
"(",
"ret",
")",
"host",
"=",
"_options",
".",
"get",
"(",
"'host'",
")",
"port",
"=",
"_options",
".",
"get",
"(",
"'port'",
")",
"db_",
"=",
"_options",
".",
"get",
"(",
"... | Return a mongodb connection object | [
"Return",
"a",
"mongodb",
"connection",
"object"
] | python | train |
mabuchilab/QNET | src/qnet/visualization/circuit_pyx.py | https://github.com/mabuchilab/QNET/blob/cc20d26dad78691d34c67173e5cd67dcac94208a/src/qnet/visualization/circuit_pyx.py#L56-L263 | def draw_circuit_canvas(circuit, hunit = HUNIT, vunit = VUNIT, rhmargin = RHMARGIN, rvmargin = RVMARGIN, rpermutation_length = RPLENGTH, draw_boxes = True, permutation_arrows = False):
"""
Generate a PyX graphical representation of a circuit expression object.
:param circuit: The circuit expression
:ty... | [
"def",
"draw_circuit_canvas",
"(",
"circuit",
",",
"hunit",
"=",
"HUNIT",
",",
"vunit",
"=",
"VUNIT",
",",
"rhmargin",
"=",
"RHMARGIN",
",",
"rvmargin",
"=",
"RVMARGIN",
",",
"rpermutation_length",
"=",
"RPLENGTH",
",",
"draw_boxes",
"=",
"True",
",",
"permu... | Generate a PyX graphical representation of a circuit expression object.
:param circuit: The circuit expression
:type circuit: ca.Circuit
:param hunit: The horizontal length unit, default = ``HUNIT``
:type hunit: float
:param vunit: The vertical length unit, default = ``VUNIT``
:type vunit: floa... | [
"Generate",
"a",
"PyX",
"graphical",
"representation",
"of",
"a",
"circuit",
"expression",
"object",
"."
] | python | train |
autokey/autokey | lib/autokey/scripting.py | https://github.com/autokey/autokey/blob/35decb72f286ce68cd2a1f09ace8891a520b58d1/lib/autokey/scripting.py#L278-L290 | def input_dialog(self, title="Enter a value", message="Enter a value", default="", **kwargs):
"""
Show an input dialog
Usage: C{dialog.input_dialog(title="Enter a value", message="Enter a value", default="", **kwargs)}
@param title: window title for the dialog
@... | [
"def",
"input_dialog",
"(",
"self",
",",
"title",
"=",
"\"Enter a value\"",
",",
"message",
"=",
"\"Enter a value\"",
",",
"default",
"=",
"\"\"",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_run_kdialog",
"(",
"title",
",",
"[",
"\"--inputb... | Show an input dialog
Usage: C{dialog.input_dialog(title="Enter a value", message="Enter a value", default="", **kwargs)}
@param title: window title for the dialog
@param message: message displayed above the input box
@param default: default value for the input box
... | [
"Show",
"an",
"input",
"dialog",
"Usage",
":",
"C",
"{",
"dialog",
".",
"input_dialog",
"(",
"title",
"=",
"Enter",
"a",
"value",
"message",
"=",
"Enter",
"a",
"value",
"default",
"=",
"**",
"kwargs",
")",
"}"
] | python | train |
log2timeline/dfvfs | dfvfs/file_io/os_file_io.py | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/file_io/os_file_io.py#L34-L100 | def _Open(self, path_spec=None, mode='rb'):
"""Opens the file-like object defined by path specification.
Args:
path_spec (PathSpec): path specification.
mode (Optional[str]): file access mode.
Raises:
AccessError: if the access to open the file was denied.
IOError: if the file-like... | [
"def",
"_Open",
"(",
"self",
",",
"path_spec",
"=",
"None",
",",
"mode",
"=",
"'rb'",
")",
":",
"if",
"not",
"path_spec",
":",
"raise",
"ValueError",
"(",
"'Missing path specification.'",
")",
"if",
"path_spec",
".",
"HasParent",
"(",
")",
":",
"raise",
... | Opens the file-like object defined by path specification.
Args:
path_spec (PathSpec): path specification.
mode (Optional[str]): file access mode.
Raises:
AccessError: if the access to open the file was denied.
IOError: if the file-like object could not be opened.
OSError: if the ... | [
"Opens",
"the",
"file",
"-",
"like",
"object",
"defined",
"by",
"path",
"specification",
"."
] | python | train |
jadolg/rocketchat_API | rocketchat_API/rocketchat.py | https://github.com/jadolg/rocketchat_API/blob/f220d094434991cb9892418245f054ea06f28aad/rocketchat_API/rocketchat.py#L360-L362 | def channels_set_join_code(self, room_id, join_code, **kwargs):
"""Sets the code required to join the channel."""
return self.__call_api_post('channels.setJoinCode', roomId=room_id, joinCode=join_code, kwargs=kwargs) | [
"def",
"channels_set_join_code",
"(",
"self",
",",
"room_id",
",",
"join_code",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"__call_api_post",
"(",
"'channels.setJoinCode'",
",",
"roomId",
"=",
"room_id",
",",
"joinCode",
"=",
"join_code",
",",
... | Sets the code required to join the channel. | [
"Sets",
"the",
"code",
"required",
"to",
"join",
"the",
"channel",
"."
] | python | train |
e-dard/flask-s3 | flask_s3.py | https://github.com/e-dard/flask-s3/blob/b8c72b40eb38a05135eec36a90f1ee0c96248f72/flask_s3.py#L86-L97 | def hash_file(filename):
"""
Generate a hash for the contents of a file
"""
hasher = hashlib.sha1()
with open(filename, 'rb') as f:
buf = f.read(65536)
while len(buf) > 0:
hasher.update(buf)
buf = f.read(65536)
return hasher.hexdigest() | [
"def",
"hash_file",
"(",
"filename",
")",
":",
"hasher",
"=",
"hashlib",
".",
"sha1",
"(",
")",
"with",
"open",
"(",
"filename",
",",
"'rb'",
")",
"as",
"f",
":",
"buf",
"=",
"f",
".",
"read",
"(",
"65536",
")",
"while",
"len",
"(",
"buf",
")",
... | Generate a hash for the contents of a file | [
"Generate",
"a",
"hash",
"for",
"the",
"contents",
"of",
"a",
"file"
] | python | train |
JdeRobot/base | src/drivers/MAVLinkServer/MAVProxy/pymavlink/dialects/v10/matrixpilot.py | https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/pymavlink/dialects/v10/matrixpilot.py#L7579-L7582 | def __callbacks(self, msg):
'''this method exists only to make profiling results easier to read'''
if self.callback:
self.callback(msg, *self.callback_args, **self.callback_kwargs) | [
"def",
"__callbacks",
"(",
"self",
",",
"msg",
")",
":",
"if",
"self",
".",
"callback",
":",
"self",
".",
"callback",
"(",
"msg",
",",
"*",
"self",
".",
"callback_args",
",",
"*",
"*",
"self",
".",
"callback_kwargs",
")"
] | this method exists only to make profiling results easier to read | [
"this",
"method",
"exists",
"only",
"to",
"make",
"profiling",
"results",
"easier",
"to",
"read"
] | python | train |
saimn/sigal | sigal/plugins/extended_caching.py | https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/plugins/extended_caching.py#L53-L65 | def _restore_cache(gallery):
"""Restores the exif data cache from the cache file"""
cachePath = os.path.join(gallery.settings["destination"], ".exif_cache")
try:
if os.path.exists(cachePath):
with open(cachePath, "rb") as cacheFile:
gallery.exifCache = pickle.load(cacheFi... | [
"def",
"_restore_cache",
"(",
"gallery",
")",
":",
"cachePath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"gallery",
".",
"settings",
"[",
"\"destination\"",
"]",
",",
"\".exif_cache\"",
")",
"try",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"ca... | Restores the exif data cache from the cache file | [
"Restores",
"the",
"exif",
"data",
"cache",
"from",
"the",
"cache",
"file"
] | python | valid |
inveniosoftware/invenio-collections | invenio_collections/cli.py | https://github.com/inveniosoftware/invenio-collections/blob/f3adca45c6d00a4dbf1f48fd501e8a68fe347f2f/invenio_collections/cli.py#L142-L149 | def create(name, dry_run, verbose, query=None, parent=None):
"""Create new collection."""
if parent is not None:
parent = Collection.query.filter_by(name=parent).one().id
collection = Collection(name=name, dbquery=query, parent_id=parent)
db.session.add(collection)
if verbose:
click.... | [
"def",
"create",
"(",
"name",
",",
"dry_run",
",",
"verbose",
",",
"query",
"=",
"None",
",",
"parent",
"=",
"None",
")",
":",
"if",
"parent",
"is",
"not",
"None",
":",
"parent",
"=",
"Collection",
".",
"query",
".",
"filter_by",
"(",
"name",
"=",
... | Create new collection. | [
"Create",
"new",
"collection",
"."
] | python | train |
marcomusy/vtkplotter | vtkplotter/actors.py | https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/actors.py#L894-L916 | def backColor(self, bc=None):
"""
Set/get actor's backface color.
"""
backProp = self.GetBackfaceProperty()
if bc is None:
if backProp:
return backProp.GetDiffuseColor()
return None
if self.GetProperty().GetOpacity() < 1:
... | [
"def",
"backColor",
"(",
"self",
",",
"bc",
"=",
"None",
")",
":",
"backProp",
"=",
"self",
".",
"GetBackfaceProperty",
"(",
")",
"if",
"bc",
"is",
"None",
":",
"if",
"backProp",
":",
"return",
"backProp",
".",
"GetDiffuseColor",
"(",
")",
"return",
"N... | Set/get actor's backface color. | [
"Set",
"/",
"get",
"actor",
"s",
"backface",
"color",
"."
] | python | train |
riga/law | law/parser.py | https://github.com/riga/law/blob/479f84ce06ecf3bafe9d33cb7b8fc52e39fb80a1/law/parser.py#L27-L47 | def full_parser():
"""
Returns the full *ArgumentParser* used by the luigi ``CmdlineParser``. The returned instance is
cached.
"""
global _full_parser
if _full_parser:
return _full_parser
luigi_parser = luigi.cmdline_parser.CmdlineParser.get_instance()
if not luigi_parser:
... | [
"def",
"full_parser",
"(",
")",
":",
"global",
"_full_parser",
"if",
"_full_parser",
":",
"return",
"_full_parser",
"luigi_parser",
"=",
"luigi",
".",
"cmdline_parser",
".",
"CmdlineParser",
".",
"get_instance",
"(",
")",
"if",
"not",
"luigi_parser",
":",
"retur... | Returns the full *ArgumentParser* used by the luigi ``CmdlineParser``. The returned instance is
cached. | [
"Returns",
"the",
"full",
"*",
"ArgumentParser",
"*",
"used",
"by",
"the",
"luigi",
"CmdlineParser",
".",
"The",
"returned",
"instance",
"is",
"cached",
"."
] | python | train |
cdgriffith/Reusables | reusables/file_operations.py | https://github.com/cdgriffith/Reusables/blob/bc32f72e4baee7d76a6d58b88fcb23dd635155cd/reusables/file_operations.py#L223-L239 | def csv_to_list(csv_file):
"""
Open and transform a CSV file into a matrix (list of lists).
.. code:: python
reusables.csv_to_list("example.csv")
# [['Name', 'Location'],
# ['Chris', 'South Pole'],
# ['Harry', 'Depth of Winter'],
# ['Bob', 'Skull']]
:param c... | [
"def",
"csv_to_list",
"(",
"csv_file",
")",
":",
"with",
"open",
"(",
"csv_file",
",",
"'r'",
"if",
"PY3",
"else",
"'rb'",
")",
"as",
"f",
":",
"return",
"list",
"(",
"csv",
".",
"reader",
"(",
"f",
")",
")"
] | Open and transform a CSV file into a matrix (list of lists).
.. code:: python
reusables.csv_to_list("example.csv")
# [['Name', 'Location'],
# ['Chris', 'South Pole'],
# ['Harry', 'Depth of Winter'],
# ['Bob', 'Skull']]
:param csv_file: Path to CSV file as str
:r... | [
"Open",
"and",
"transform",
"a",
"CSV",
"file",
"into",
"a",
"matrix",
"(",
"list",
"of",
"lists",
")",
"."
] | python | train |
mariano/pyfire | pyfire/twistedx/producer.py | https://github.com/mariano/pyfire/blob/42e3490c138abc8e10f2e9f8f8f3b40240a80412/pyfire/twistedx/producer.py#L82-L87 | def resumeProducing(self):
""" Resume producing """
self._paused = False
result = self._produce()
if result:
return result | [
"def",
"resumeProducing",
"(",
"self",
")",
":",
"self",
".",
"_paused",
"=",
"False",
"result",
"=",
"self",
".",
"_produce",
"(",
")",
"if",
"result",
":",
"return",
"result"
] | Resume producing | [
"Resume",
"producing"
] | python | valid |
eqcorrscan/EQcorrscan | eqcorrscan/core/template_gen.py | https://github.com/eqcorrscan/EQcorrscan/blob/3121b4aca801ee5d38f56ca297ce1c0f9515d9ff/eqcorrscan/core/template_gen.py#L1076-L1162 | def from_sac(sac_files, lowcut, highcut, samp_rate, filt_order, length, swin,
prepick, all_horiz=False, delayed=True, plot=False, debug=0,
return_event=False, min_snr=None):
"""
Generate a multiplexed template from a list of SAC files.
Function to read picks and waveforms from SAC... | [
"def",
"from_sac",
"(",
"sac_files",
",",
"lowcut",
",",
"highcut",
",",
"samp_rate",
",",
"filt_order",
",",
"length",
",",
"swin",
",",
"prepick",
",",
"all_horiz",
"=",
"False",
",",
"delayed",
"=",
"True",
",",
"plot",
"=",
"False",
",",
"debug",
"... | Generate a multiplexed template from a list of SAC files.
Function to read picks and waveforms from SAC data, and generate a \
template from these. Usually sac_files is a list of all single-channel \
SAC files for a given event, a single, multi-channel template will be \
created from these traces.
... | [
"Generate",
"a",
"multiplexed",
"template",
"from",
"a",
"list",
"of",
"SAC",
"files",
"."
] | python | train |
peterbrittain/asciimatics | asciimatics/widgets.py | https://github.com/peterbrittain/asciimatics/blob/f471427d7786ce2d5f1eeb2dae0e67d19e46e085/asciimatics/widgets.py#L1271-L1290 | def save(self, validate):
"""
Save the current values in all the widgets back to the persistent data storage.
:param validate: whether to validate the saved data or not.
:raises: InvalidFields if any invalid data is found.
"""
invalid = []
for column in self._col... | [
"def",
"save",
"(",
"self",
",",
"validate",
")",
":",
"invalid",
"=",
"[",
"]",
"for",
"column",
"in",
"self",
".",
"_columns",
":",
"for",
"widget",
"in",
"column",
":",
"if",
"widget",
".",
"is_valid",
"or",
"not",
"validate",
":",
"if",
"widget",... | Save the current values in all the widgets back to the persistent data storage.
:param validate: whether to validate the saved data or not.
:raises: InvalidFields if any invalid data is found. | [
"Save",
"the",
"current",
"values",
"in",
"all",
"the",
"widgets",
"back",
"to",
"the",
"persistent",
"data",
"storage",
"."
] | python | train |
e3krisztian/pyrene | pyrene/shell.py | https://github.com/e3krisztian/pyrene/blob/ad9f2fb979f06930399c9c8214c3fe3c2d6efa06/pyrene/shell.py#L246-L258 | def do_directory_repo(self, repo):
'''
[Re]define REPO as directory package repository.
directory_repo REPO
'''
self.abort_on_missing_effective_repo_name(repo, 'directory_repo')
repo_name = self.get_effective_repo_name(repo)
try:
self.network.set(repo... | [
"def",
"do_directory_repo",
"(",
"self",
",",
"repo",
")",
":",
"self",
".",
"abort_on_missing_effective_repo_name",
"(",
"repo",
",",
"'directory_repo'",
")",
"repo_name",
"=",
"self",
".",
"get_effective_repo_name",
"(",
"repo",
")",
"try",
":",
"self",
".",
... | [Re]define REPO as directory package repository.
directory_repo REPO | [
"[",
"Re",
"]",
"define",
"REPO",
"as",
"directory",
"package",
"repository",
"."
] | python | train |
bwohlberg/sporco | sporco/admm/admm.py | https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/admm/admm.py#L1164-L1178 | def relax_AX(self):
"""Implement relaxation if option ``RelaxParam`` != 1.0."""
self.AXnr = self.cnst_A(self.X)
if self.rlx == 1.0:
self.AX = self.AXnr
else:
if not hasattr(self, '_cnst_c0'):
self._cnst_c0 = self.cnst_c0()
if not hasat... | [
"def",
"relax_AX",
"(",
"self",
")",
":",
"self",
".",
"AXnr",
"=",
"self",
".",
"cnst_A",
"(",
"self",
".",
"X",
")",
"if",
"self",
".",
"rlx",
"==",
"1.0",
":",
"self",
".",
"AX",
"=",
"self",
".",
"AXnr",
"else",
":",
"if",
"not",
"hasattr",... | Implement relaxation if option ``RelaxParam`` != 1.0. | [
"Implement",
"relaxation",
"if",
"option",
"RelaxParam",
"!",
"=",
"1",
".",
"0",
"."
] | python | train |
saltstack/salt | salt/utils/cache.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/cache.py#L197-L213 | def store(self):
'''
Write content of the entire cache to disk
'''
if msgpack is None:
log.error('Cache cannot be stored on disk: msgpack is missing')
else:
# TODO Dir hashing?
try:
with salt.utils.files.fopen(self._path, 'wb+')... | [
"def",
"store",
"(",
"self",
")",
":",
"if",
"msgpack",
"is",
"None",
":",
"log",
".",
"error",
"(",
"'Cache cannot be stored on disk: msgpack is missing'",
")",
"else",
":",
"# TODO Dir hashing?",
"try",
":",
"with",
"salt",
".",
"utils",
".",
"files",
".",
... | Write content of the entire cache to disk | [
"Write",
"content",
"of",
"the",
"entire",
"cache",
"to",
"disk"
] | python | train |
MouseLand/rastermap | rastermap/mapping_copy.py | https://github.com/MouseLand/rastermap/blob/eee7a46db80b6e33207543778e11618d0fed08a6/rastermap/mapping_copy.py#L257-L324 | def fit(self, X=None, u=None, sv=None, v=None):
"""Fit X into an embedded space.
Inputs
----------
X : array, shape (n_samples, n_features)
u,s,v : svd decomposition of X (optional)
Assigns
----------
embedding : array-like, shape (n_samples, n_components... | [
"def",
"fit",
"(",
"self",
",",
"X",
"=",
"None",
",",
"u",
"=",
"None",
",",
"sv",
"=",
"None",
",",
"v",
"=",
"None",
")",
":",
"if",
"self",
".",
"mode",
"is",
"'parallel'",
":",
"Xall",
"=",
"X",
".",
"copy",
"(",
")",
"X",
"=",
"np",
... | Fit X into an embedded space.
Inputs
----------
X : array, shape (n_samples, n_features)
u,s,v : svd decomposition of X (optional)
Assigns
----------
embedding : array-like, shape (n_samples, n_components)
Stores the embedding vectors.
u,sv,v ... | [
"Fit",
"X",
"into",
"an",
"embedded",
"space",
".",
"Inputs",
"----------",
"X",
":",
"array",
"shape",
"(",
"n_samples",
"n_features",
")",
"u",
"s",
"v",
":",
"svd",
"decomposition",
"of",
"X",
"(",
"optional",
")"
] | python | train |
ray-project/ray | python/ray/tune/web_server.py | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/web_server.py#L48-L51 | def get_all_trials(self):
"""Returns a list of all trials' information."""
response = requests.get(urljoin(self._path, "trials"))
return self._deserialize(response) | [
"def",
"get_all_trials",
"(",
"self",
")",
":",
"response",
"=",
"requests",
".",
"get",
"(",
"urljoin",
"(",
"self",
".",
"_path",
",",
"\"trials\"",
")",
")",
"return",
"self",
".",
"_deserialize",
"(",
"response",
")"
] | Returns a list of all trials' information. | [
"Returns",
"a",
"list",
"of",
"all",
"trials",
"information",
"."
] | python | train |
cloudendpoints/endpoints-management-python | endpoints_management/control/check_request.py | https://github.com/cloudendpoints/endpoints-management-python/blob/ec3c4a330ae9d65738861ce6df4dd6c3cb9f7731/endpoints_management/control/check_request.py#L126-L152 | def convert_response(check_response, project_id):
"""Computes a http status code and message `CheckResponse`
The return value a tuple (code, message, api_key_is_bad) where
code: is the http status code
message: is the message to return
api_key_is_bad: indicates that a given api_key is bad
Arg... | [
"def",
"convert_response",
"(",
"check_response",
",",
"project_id",
")",
":",
"if",
"not",
"check_response",
"or",
"not",
"check_response",
".",
"checkErrors",
":",
"return",
"_IS_OK",
"# only check the first error for now, as per ESP",
"theError",
"=",
"check_response",... | Computes a http status code and message `CheckResponse`
The return value a tuple (code, message, api_key_is_bad) where
code: is the http status code
message: is the message to return
api_key_is_bad: indicates that a given api_key is bad
Args:
check_response (:class:`endpoints_management.ge... | [
"Computes",
"a",
"http",
"status",
"code",
"and",
"message",
"CheckResponse"
] | python | train |
sorgerlab/indra | indra/assemblers/pybel/assembler.py | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/pybel/assembler.py#L463-L518 | def _get_agent_grounding(agent):
"""Convert an agent to the corresponding PyBEL DSL object (to be filled with variants later)."""
def _get_id(_agent, key):
_id = _agent.db_refs.get(key)
if isinstance(_id, list):
_id = _id[0]
return _id
hgnc_id = _get_id(agent, 'HGNC')
... | [
"def",
"_get_agent_grounding",
"(",
"agent",
")",
":",
"def",
"_get_id",
"(",
"_agent",
",",
"key",
")",
":",
"_id",
"=",
"_agent",
".",
"db_refs",
".",
"get",
"(",
"key",
")",
"if",
"isinstance",
"(",
"_id",
",",
"list",
")",
":",
"_id",
"=",
"_id... | Convert an agent to the corresponding PyBEL DSL object (to be filled with variants later). | [
"Convert",
"an",
"agent",
"to",
"the",
"corresponding",
"PyBEL",
"DSL",
"object",
"(",
"to",
"be",
"filled",
"with",
"variants",
"later",
")",
"."
] | python | train |
googleads/googleads-python-lib | examples/adwords/v201809/shopping/add_shopping_campaign_for_showcase_ads.py | https://github.com/googleads/googleads-python-lib/blob/aa3b1b474b0f9789ca55ca46f4b2b57aeae38874/examples/adwords/v201809/shopping/add_shopping_campaign_for_showcase_ads.py#L182-L234 | def CreateShoppingCampaign(client, budget_id, merchant_id):
"""Creates a shopping campaign with the given budget and merchant IDs.
Args:
client: an AdWordsClient instance.
budget_id: the str ID of the budget to be associated with the shopping
campaign.
merchant_id: the str ID of the merchant acco... | [
"def",
"CreateShoppingCampaign",
"(",
"client",
",",
"budget_id",
",",
"merchant_id",
")",
":",
"campaign_service",
"=",
"client",
".",
"GetService",
"(",
"'CampaignService'",
",",
"'v201809'",
")",
"campaign",
"=",
"{",
"'name'",
":",
"'Shopping campaign #%s'",
"... | Creates a shopping campaign with the given budget and merchant IDs.
Args:
client: an AdWordsClient instance.
budget_id: the str ID of the budget to be associated with the shopping
campaign.
merchant_id: the str ID of the merchant account to be associated with the
shopping campaign.
Returns... | [
"Creates",
"a",
"shopping",
"campaign",
"with",
"the",
"given",
"budget",
"and",
"merchant",
"IDs",
"."
] | python | train |
amadeus4dev/amadeus-python | amadeus/reference_data/_location.py | https://github.com/amadeus4dev/amadeus-python/blob/afb93667d2cd486ddc7f4a7f29f222f04453a44a/amadeus/reference_data/_location.py#L9-L21 | def get(self, **params):
'''
Returns details for a specific airport.
.. code-block:: python
amadeus.reference_data.location('ALHR').get()
:rtype: amadeus.Response
:raises amadeus.ResponseError: if the request could not be completed
'''
return self.c... | [
"def",
"get",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"return",
"self",
".",
"client",
".",
"get",
"(",
"'/v1/reference-data/locations/{0}'",
".",
"format",
"(",
"self",
".",
"location_id",
")",
",",
"*",
"*",
"params",
")"
] | Returns details for a specific airport.
.. code-block:: python
amadeus.reference_data.location('ALHR').get()
:rtype: amadeus.Response
:raises amadeus.ResponseError: if the request could not be completed | [
"Returns",
"details",
"for",
"a",
"specific",
"airport",
"."
] | python | train |
helixyte/everest | everest/resources/utils.py | https://github.com/helixyte/everest/blob/70c9b93c3061db5cb62428349d18b8fb8566411b/everest/resources/utils.py#L197-L210 | def resource_to_url(resource, request=None, quote=False):
"""
Converts the given resource to a URL.
:param request: Request object (required for the host name part of the
URL). If this is not given, the current request is used.
:param bool quote: If set, the URL returned will be quoted.
"""
... | [
"def",
"resource_to_url",
"(",
"resource",
",",
"request",
"=",
"None",
",",
"quote",
"=",
"False",
")",
":",
"if",
"request",
"is",
"None",
":",
"request",
"=",
"get_current_request",
"(",
")",
"# cnv = request.registry.getAdapter(request, IResourceUrlConverter)",... | Converts the given resource to a URL.
:param request: Request object (required for the host name part of the
URL). If this is not given, the current request is used.
:param bool quote: If set, the URL returned will be quoted. | [
"Converts",
"the",
"given",
"resource",
"to",
"a",
"URL",
"."
] | python | train |
apple/turicreate | deps/src/libxml2-2.9.1/python/libxml2.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L5546-L5551 | def stringDecodeEntities(self, str, what, end, end2, end3):
"""Takes a entity string content and process to do the
adequate substitutions. [67] Reference ::= EntityRef |
CharRef [69] PEReference ::= '%' Name ';' """
ret = libxml2mod.xmlStringDecodeEntities(self._o, str, what, end,... | [
"def",
"stringDecodeEntities",
"(",
"self",
",",
"str",
",",
"what",
",",
"end",
",",
"end2",
",",
"end3",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlStringDecodeEntities",
"(",
"self",
".",
"_o",
",",
"str",
",",
"what",
",",
"end",
",",
"end2",
"... | Takes a entity string content and process to do the
adequate substitutions. [67] Reference ::= EntityRef |
CharRef [69] PEReference ::= '%' Name ';' | [
"Takes",
"a",
"entity",
"string",
"content",
"and",
"process",
"to",
"do",
"the",
"adequate",
"substitutions",
".",
"[",
"67",
"]",
"Reference",
"::",
"=",
"EntityRef",
"|",
"CharRef",
"[",
"69",
"]",
"PEReference",
"::",
"=",
"%",
"Name",
";"
] | python | train |
michael-lazar/rtv | rtv/packages/praw/objects.py | https://github.com/michael-lazar/rtv/blob/ccef2af042566ad384977028cf0bde01bc524dda/rtv/packages/praw/objects.py#L775-L778 | def collapse(self):
"""Collapse a private message or modmail."""
url = self.reddit_session.config['collapse_message']
self.reddit_session.request_json(url, data={'id': self.name}) | [
"def",
"collapse",
"(",
"self",
")",
":",
"url",
"=",
"self",
".",
"reddit_session",
".",
"config",
"[",
"'collapse_message'",
"]",
"self",
".",
"reddit_session",
".",
"request_json",
"(",
"url",
",",
"data",
"=",
"{",
"'id'",
":",
"self",
".",
"name",
... | Collapse a private message or modmail. | [
"Collapse",
"a",
"private",
"message",
"or",
"modmail",
"."
] | python | train |
clab/dynet | examples/variational-autoencoder/basic-image-recon/utils.py | https://github.com/clab/dynet/blob/21cc62606b74f81bb4b11a9989a6c2bd0caa09c5/examples/variational-autoencoder/basic-image-recon/utils.py#L7-L41 | def load_mnist(dataset, path):
"""
wget -O - http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz | gunzip > train-images-idx3-ubyte
wget -O - http://yann.lecun.com/exdb/mnist/train-labels-idx1-ubyte.gz | gunzip > train-labels-idx1-ubyte
wget -O - http://yann.lecun.com/exdb/mnist/t10k-images-idx3... | [
"def",
"load_mnist",
"(",
"dataset",
",",
"path",
")",
":",
"if",
"dataset",
"is",
"\"training\"",
":",
"fname_img",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"\"train-images-idx3-ubyte\"",
")",
"fname_lbl",
"=",
"os",
".",
"path",
".",
"joi... | wget -O - http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz | gunzip > train-images-idx3-ubyte
wget -O - http://yann.lecun.com/exdb/mnist/train-labels-idx1-ubyte.gz | gunzip > train-labels-idx1-ubyte
wget -O - http://yann.lecun.com/exdb/mnist/t10k-images-idx3-ubyte.gz | gunzip > t10k-images-idx3-ubyte... | [
"wget",
"-",
"O",
"-",
"http",
":",
"//",
"yann",
".",
"lecun",
".",
"com",
"/",
"exdb",
"/",
"mnist",
"/",
"train",
"-",
"images",
"-",
"idx3",
"-",
"ubyte",
".",
"gz",
"|",
"gunzip",
">",
"train",
"-",
"images",
"-",
"idx3",
"-",
"ubyte",
"wg... | python | valid |
pvlib/pvlib-python | pvlib/location.py | https://github.com/pvlib/pvlib-python/blob/2e844a595b820b43d1170269781fa66bd0ccc8a3/pvlib/location.py#L131-L162 | def get_solarposition(self, times, pressure=None, temperature=12,
**kwargs):
"""
Uses the :py:func:`solarposition.get_solarposition` function
to calculate the solar zenith, azimuth, etc. at this location.
Parameters
----------
times : DatetimeIn... | [
"def",
"get_solarposition",
"(",
"self",
",",
"times",
",",
"pressure",
"=",
"None",
",",
"temperature",
"=",
"12",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"pressure",
"is",
"None",
":",
"pressure",
"=",
"atmosphere",
".",
"alt2pres",
"(",
"self",
"."... | Uses the :py:func:`solarposition.get_solarposition` function
to calculate the solar zenith, azimuth, etc. at this location.
Parameters
----------
times : DatetimeIndex
pressure : None, float, or array-like, default None
If None, pressure will be calculated using
... | [
"Uses",
"the",
":",
"py",
":",
"func",
":",
"solarposition",
".",
"get_solarposition",
"function",
"to",
"calculate",
"the",
"solar",
"zenith",
"azimuth",
"etc",
".",
"at",
"this",
"location",
"."
] | python | train |
chrisspen/dtree | dtree.py | https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L1539-L1582 | def predict(self, record):
"""
Attempts to predict the value of the class attribute by aggregating
the predictions of each tree.
Parameters:
weighting_formula := a callable that takes a list of trees and
returns a list of weights.
"""
... | [
"def",
"predict",
"(",
"self",
",",
"record",
")",
":",
"# Get raw predictions.",
"# {tree:raw prediction}",
"predictions",
"=",
"{",
"}",
"for",
"tree",
"in",
"self",
".",
"trees",
":",
"_p",
"=",
"tree",
".",
"predict",
"(",
"record",
")",
"if",
"_p",
... | Attempts to predict the value of the class attribute by aggregating
the predictions of each tree.
Parameters:
weighting_formula := a callable that takes a list of trees and
returns a list of weights. | [
"Attempts",
"to",
"predict",
"the",
"value",
"of",
"the",
"class",
"attribute",
"by",
"aggregating",
"the",
"predictions",
"of",
"each",
"tree",
".",
"Parameters",
":",
"weighting_formula",
":",
"=",
"a",
"callable",
"that",
"takes",
"a",
"list",
"of",
"tree... | python | train |
horazont/aioxmpp | aioxmpp/ibr/service.py | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/ibr/service.py#L149-L167 | def change_pass(self,
new_pass):
"""
Change the client password for 'new_pass'.
:param new_pass: New password of the client.
:type new_pass: :class:`str`
:param old_pass: Old password of the client.
:type old_pass: :class:`str`
"""
i... | [
"def",
"change_pass",
"(",
"self",
",",
"new_pass",
")",
":",
"iq",
"=",
"aioxmpp",
".",
"IQ",
"(",
"to",
"=",
"self",
".",
"client",
".",
"local_jid",
".",
"bare",
"(",
")",
".",
"replace",
"(",
"localpart",
"=",
"None",
")",
",",
"type_",
"=",
... | Change the client password for 'new_pass'.
:param new_pass: New password of the client.
:type new_pass: :class:`str`
:param old_pass: Old password of the client.
:type old_pass: :class:`str` | [
"Change",
"the",
"client",
"password",
"for",
"new_pass",
"."
] | python | train |
timgabets/bpc8583 | examples/isoClient.py | https://github.com/timgabets/bpc8583/blob/1b8e95d73ad273ad9d11bff40d1af3f06f0f3503/examples/isoClient.py#L301-L314 | def show_help(name):
"""
Show help and basic usage
"""
print('Usage: python3 {} [OPTIONS]... '.format(name))
print('ISO8583 message client')
print(' -v, --verbose\t\tRun transactions verbosely')
print(' -p, --port=[PORT]\t\tTCP port to connect to, 1337 by default')
print(' -s, --serve... | [
"def",
"show_help",
"(",
"name",
")",
":",
"print",
"(",
"'Usage: python3 {} [OPTIONS]... '",
".",
"format",
"(",
"name",
")",
")",
"print",
"(",
"'ISO8583 message client'",
")",
"print",
"(",
"' -v, --verbose\\t\\tRun transactions verbosely'",
")",
"print",
"(",
"... | Show help and basic usage | [
"Show",
"help",
"and",
"basic",
"usage"
] | python | train |
rbuffat/pyepw | pyepw/epw.py | https://github.com/rbuffat/pyepw/blob/373d4d3c8386c8d35789f086ac5f6018c2711745/pyepw/epw.py#L1805-L1826 | def db020(self, value=None):
""" Corresponds to IDD Field `db020`
mean coincident wet-bulb temperature to
Dry-bulb temperature corresponding to 2.0% annual cumulative frequency of occurrence (warm conditions)
Args:
value (float): value for IDD Field `db020`
... | [
"def",
"db020",
"(",
"self",
",",
"value",
"=",
"None",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"try",
":",
"value",
"=",
"float",
"(",
"value",
")",
"except",
"ValueError",
":",
"raise",
"ValueError",
"(",
"'value {} need to be of type float '"... | Corresponds to IDD Field `db020`
mean coincident wet-bulb temperature to
Dry-bulb temperature corresponding to 2.0% annual cumulative frequency of occurrence (warm conditions)
Args:
value (float): value for IDD Field `db020`
Unit: C
if `value` is None... | [
"Corresponds",
"to",
"IDD",
"Field",
"db020",
"mean",
"coincident",
"wet",
"-",
"bulb",
"temperature",
"to",
"Dry",
"-",
"bulb",
"temperature",
"corresponding",
"to",
"2",
".",
"0%",
"annual",
"cumulative",
"frequency",
"of",
"occurrence",
"(",
"warm",
"condit... | python | train |
joanvila/aioredlock | aioredlock/redis.py | https://github.com/joanvila/aioredlock/blob/6c62f0895c93b26b87ca8e3fe36bc024c81be421/aioredlock/redis.py#L227-L256 | async def set_lock(self, resource, lock_identifier):
"""
Tries to set the lock to all the redis instances
:param resource: The resource string name to lock
:param lock_identifier: The id of the lock. A unique string
:return float: The elapsed time that took to lock the instances... | [
"async",
"def",
"set_lock",
"(",
"self",
",",
"resource",
",",
"lock_identifier",
")",
":",
"start_time",
"=",
"time",
".",
"time",
"(",
")",
"lock_timeout",
"=",
"self",
".",
"lock_timeout",
"successes",
"=",
"await",
"asyncio",
".",
"gather",
"(",
"*",
... | Tries to set the lock to all the redis instances
:param resource: The resource string name to lock
:param lock_identifier: The id of the lock. A unique string
:return float: The elapsed time that took to lock the instances
in seconds
:raises: LockError if the lock has not be... | [
"Tries",
"to",
"set",
"the",
"lock",
"to",
"all",
"the",
"redis",
"instances"
] | python | train |
shoebot/shoebot | shoebot/data/basecolor.py | https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/data/basecolor.py#L381-L394 | def hex_to_rgb(hex):
""" Returns RGB values for a hex color string.
"""
hex = hex.lstrip("#")
if len(hex) < 6:
hex += hex[-1] * (6 - len(hex))
if len(hex) == 6:
r, g, b = hex[0:2], hex[2:4], hex[4:]
r, g, b = [int(n, 16) / 255.0 for n in (r, g, b)]
a = 1.0
elif le... | [
"def",
"hex_to_rgb",
"(",
"hex",
")",
":",
"hex",
"=",
"hex",
".",
"lstrip",
"(",
"\"#\"",
")",
"if",
"len",
"(",
"hex",
")",
"<",
"6",
":",
"hex",
"+=",
"hex",
"[",
"-",
"1",
"]",
"*",
"(",
"6",
"-",
"len",
"(",
"hex",
")",
")",
"if",
"l... | Returns RGB values for a hex color string. | [
"Returns",
"RGB",
"values",
"for",
"a",
"hex",
"color",
"string",
"."
] | python | valid |
bukun/TorCMS | torcms/handlers/entity_handler.py | https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/entity_handler.py#L121-L137 | def add_entity(self):
'''
Add the entity. All the information got from the post data.
'''
post_data = self.get_post_data()
if 'kind' in post_data:
if post_data['kind'] == '1':
self.add_pic(post_data)
elif post_data['kind'] == '2':
... | [
"def",
"add_entity",
"(",
"self",
")",
":",
"post_data",
"=",
"self",
".",
"get_post_data",
"(",
")",
"if",
"'kind'",
"in",
"post_data",
":",
"if",
"post_data",
"[",
"'kind'",
"]",
"==",
"'1'",
":",
"self",
".",
"add_pic",
"(",
"post_data",
")",
"elif"... | Add the entity. All the information got from the post data. | [
"Add",
"the",
"entity",
".",
"All",
"the",
"information",
"got",
"from",
"the",
"post",
"data",
"."
] | python | train |
honzamach/pydgets | pydgets/widgets.py | https://github.com/honzamach/pydgets/blob/5ca4ce19fc2d9b5f41441fb9163810f8ca502e79/pydgets/widgets.py#L404-L420 | def get_setup(self, content = None, **kwargs):
"""
Get current setup by combining internal settings with the ones given.
"""
if content is None:
content = self.content
if content is None:
raise Exception("No content given to be displayed")
setup =... | [
"def",
"get_setup",
"(",
"self",
",",
"content",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"content",
"is",
"None",
":",
"content",
"=",
"self",
".",
"content",
"if",
"content",
"is",
"None",
":",
"raise",
"Exception",
"(",
"\"No content gi... | Get current setup by combining internal settings with the ones given. | [
"Get",
"current",
"setup",
"by",
"combining",
"internal",
"settings",
"with",
"the",
"ones",
"given",
"."
] | python | train |
Erotemic/utool | utool/util_dev.py | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dev.py#L1774-L1828 | def print_object_size_tree(obj, lbl='obj', maxdepth=None):
""" Needs work """
from utool import util_str
from utool import util_type
byte_str2 = util_str.byte_str2
def _get_object_size_tree(obj, depth=0, lbl='obj', seen=None):
indent = ' ' * (depth * 4)
if maxdepth is not None and ... | [
"def",
"print_object_size_tree",
"(",
"obj",
",",
"lbl",
"=",
"'obj'",
",",
"maxdepth",
"=",
"None",
")",
":",
"from",
"utool",
"import",
"util_str",
"from",
"utool",
"import",
"util_type",
"byte_str2",
"=",
"util_str",
".",
"byte_str2",
"def",
"_get_object_si... | Needs work | [
"Needs",
"work"
] | python | train |
watson-developer-cloud/python-sdk | ibm_watson/speech_to_text_v1.py | https://github.com/watson-developer-cloud/python-sdk/blob/4c2c9df4466fcde88975da9ecd834e6ba95eb353/ibm_watson/speech_to_text_v1.py#L4491-L4498 | def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'status') and self.status is not None:
_dict['status'] = self.status
if hasattr(self, 'url') and self.url is not None:
_dict['url'] = self.url
return _d... | [
"def",
"_to_dict",
"(",
"self",
")",
":",
"_dict",
"=",
"{",
"}",
"if",
"hasattr",
"(",
"self",
",",
"'status'",
")",
"and",
"self",
".",
"status",
"is",
"not",
"None",
":",
"_dict",
"[",
"'status'",
"]",
"=",
"self",
".",
"status",
"if",
"hasattr"... | Return a json dictionary representing this model. | [
"Return",
"a",
"json",
"dictionary",
"representing",
"this",
"model",
"."
] | python | train |
vslutov/turingmarkov | turingmarkov/turing.py | https://github.com/vslutov/turingmarkov/blob/63e2ba255d7d0d868cbc4bf3e568b1c1bbcf38ce/turingmarkov/turing.py#L41-L58 | def _add_rule(self, state, rule):
"""Parse rule and add it to machine (for internal use)."""
if rule.strip() == "-":
parsed_rule = None
else:
parsed_rule = rule.split(',')
if (len(parsed_rule) != 3 or
parsed_rule[1] not in ['L', 'N', 'R'] or... | [
"def",
"_add_rule",
"(",
"self",
",",
"state",
",",
"rule",
")",
":",
"if",
"rule",
".",
"strip",
"(",
")",
"==",
"\"-\"",
":",
"parsed_rule",
"=",
"None",
"else",
":",
"parsed_rule",
"=",
"rule",
".",
"split",
"(",
"','",
")",
"if",
"(",
"len",
... | Parse rule and add it to machine (for internal use). | [
"Parse",
"rule",
"and",
"add",
"it",
"to",
"machine",
"(",
"for",
"internal",
"use",
")",
"."
] | python | train |
bitprophet/releases | releases/__init__.py | https://github.com/bitprophet/releases/blob/97a763e41bbe7374106a1c648b89346a0d935429/releases/__init__.py#L434-L455 | def handle_first_release_line(entries, manager):
"""
Set up initial line-manager entry for first encountered release line.
To be called at start of overall process; afterwards, subsequent major
lines are generated by `handle_upcoming_major_release`.
"""
# It's remotely possible the changelog is... | [
"def",
"handle_first_release_line",
"(",
"entries",
",",
"manager",
")",
":",
"# It's remotely possible the changelog is totally empty...",
"if",
"not",
"entries",
":",
"return",
"# Obtain (short-circuiting) first Release obj.",
"first_release",
"=",
"None",
"for",
"obj",
"in... | Set up initial line-manager entry for first encountered release line.
To be called at start of overall process; afterwards, subsequent major
lines are generated by `handle_upcoming_major_release`. | [
"Set",
"up",
"initial",
"line",
"-",
"manager",
"entry",
"for",
"first",
"encountered",
"release",
"line",
"."
] | python | train |
ssato/python-anyconfig | src/anyconfig/backend/xml.py | https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/xml.py#L329-L350 | def root_to_container(root, container=dict, nspaces=None, **options):
"""
Convert XML ElementTree Root Element to a collection of container objects.
:param root: etree root object or None
:param container: callble to make a container object
:param nspaces: A namespaces dict, {uri: prefix} or None
... | [
"def",
"root_to_container",
"(",
"root",
",",
"container",
"=",
"dict",
",",
"nspaces",
"=",
"None",
",",
"*",
"*",
"options",
")",
":",
"tree",
"=",
"container",
"(",
")",
"if",
"root",
"is",
"None",
":",
"return",
"tree",
"if",
"nspaces",
"is",
"no... | Convert XML ElementTree Root Element to a collection of container objects.
:param root: etree root object or None
:param container: callble to make a container object
:param nspaces: A namespaces dict, {uri: prefix} or None
:param options: Keyword options,
- tags: Dict of tags for special node... | [
"Convert",
"XML",
"ElementTree",
"Root",
"Element",
"to",
"a",
"collection",
"of",
"container",
"objects",
"."
] | python | train |
nornir-automation/nornir | nornir/core/inventory.py | https://github.com/nornir-automation/nornir/blob/3425c47fd870db896cb80f619bae23bd98d50c74/nornir/core/inventory.py#L431-L440 | def children_of_group(self, group: Union[str, Group]) -> Set[Host]:
"""
Returns set of hosts that belongs to a group including those that belong
indirectly via inheritance
"""
hosts: List[Host] = set()
for host in self.hosts.values():
if host.has_parent_group(... | [
"def",
"children_of_group",
"(",
"self",
",",
"group",
":",
"Union",
"[",
"str",
",",
"Group",
"]",
")",
"->",
"Set",
"[",
"Host",
"]",
":",
"hosts",
":",
"List",
"[",
"Host",
"]",
"=",
"set",
"(",
")",
"for",
"host",
"in",
"self",
".",
"hosts",
... | Returns set of hosts that belongs to a group including those that belong
indirectly via inheritance | [
"Returns",
"set",
"of",
"hosts",
"that",
"belongs",
"to",
"a",
"group",
"including",
"those",
"that",
"belong",
"indirectly",
"via",
"inheritance"
] | python | train |
ray-project/ray | python/ray/autoscaler/gcp/config.py | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/autoscaler/gcp/config.py#L36-L52 | def wait_for_crm_operation(operation):
"""Poll for cloud resource manager operation until finished."""
logger.info("wait_for_crm_operation: "
"Waiting for operation {} to finish...".format(operation))
for _ in range(MAX_POLLS):
result = crm.operations().get(name=operation["name"]).e... | [
"def",
"wait_for_crm_operation",
"(",
"operation",
")",
":",
"logger",
".",
"info",
"(",
"\"wait_for_crm_operation: \"",
"\"Waiting for operation {} to finish...\"",
".",
"format",
"(",
"operation",
")",
")",
"for",
"_",
"in",
"range",
"(",
"MAX_POLLS",
")",
":",
... | Poll for cloud resource manager operation until finished. | [
"Poll",
"for",
"cloud",
"resource",
"manager",
"operation",
"until",
"finished",
"."
] | python | train |
gwastro/pycbc | pycbc/events/eventmgr.py | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/events/eventmgr.py#L547-L553 | def add_template_events_to_ifo(self, ifo, columns, vectors):
""" Add a vector indexed """
# Just call through to the standard function
self.template_events = self.template_event_dict[ifo]
self.add_template_events(columns, vectors)
self.template_event_dict[ifo] = self.template_eve... | [
"def",
"add_template_events_to_ifo",
"(",
"self",
",",
"ifo",
",",
"columns",
",",
"vectors",
")",
":",
"# Just call through to the standard function",
"self",
".",
"template_events",
"=",
"self",
".",
"template_event_dict",
"[",
"ifo",
"]",
"self",
".",
"add_templa... | Add a vector indexed | [
"Add",
"a",
"vector",
"indexed"
] | python | train |
droope/droopescan | dscan/plugins/internal/base_plugin_internal.py | https://github.com/droope/droopescan/blob/424c48a0f9d12b4536dbef5a786f0fbd4ce9519a/dscan/plugins/internal/base_plugin_internal.py#L821-L847 | def enumerate_version_changelog(self, url, versions_estimated, timeout=15,
headers={}):
"""
If we have a changelog in store for this CMS, this function will be
called, and a changelog will be used for narrowing down which version is
installed. If the changelog's version is ou... | [
"def",
"enumerate_version_changelog",
"(",
"self",
",",
"url",
",",
"versions_estimated",
",",
"timeout",
"=",
"15",
",",
"headers",
"=",
"{",
"}",
")",
":",
"changelogs",
"=",
"self",
".",
"vf",
".",
"changelogs_get",
"(",
")",
"ch_hash",
"=",
"None",
"... | If we have a changelog in store for this CMS, this function will be
called, and a changelog will be used for narrowing down which version is
installed. If the changelog's version is outside our estimated range,
it is discarded.
@param url: the url to check against.
@param version... | [
"If",
"we",
"have",
"a",
"changelog",
"in",
"store",
"for",
"this",
"CMS",
"this",
"function",
"will",
"be",
"called",
"and",
"a",
"changelog",
"will",
"be",
"used",
"for",
"narrowing",
"down",
"which",
"version",
"is",
"installed",
".",
"If",
"the",
"ch... | python | train |
Qiskit/qiskit-terra | qiskit/qasm/node/node.py | https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/qasm/node/node.py#L34-L54 | def to_string(self, indent):
"""Print with indent."""
ind = indent * ' '
if self.root:
print(ind, self.type, '---', self.root)
else:
print(ind, self.type)
indent = indent + 3
ind = indent * ' '
for children in self.children:
if ... | [
"def",
"to_string",
"(",
"self",
",",
"indent",
")",
":",
"ind",
"=",
"indent",
"*",
"' '",
"if",
"self",
".",
"root",
":",
"print",
"(",
"ind",
",",
"self",
".",
"type",
",",
"'---'",
",",
"self",
".",
"root",
")",
"else",
":",
"print",
"(",
"... | Print with indent. | [
"Print",
"with",
"indent",
"."
] | python | test |
iamteem/redisco | redisco/containers.py | https://github.com/iamteem/redisco/blob/a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91/redisco/containers.py#L275-L280 | def reverse(self):
"""Reverse in place."""
r = self[:]
r.reverse()
self.clear()
self.extend(r) | [
"def",
"reverse",
"(",
"self",
")",
":",
"r",
"=",
"self",
"[",
":",
"]",
"r",
".",
"reverse",
"(",
")",
"self",
".",
"clear",
"(",
")",
"self",
".",
"extend",
"(",
"r",
")"
] | Reverse in place. | [
"Reverse",
"in",
"place",
"."
] | python | train |
ARMmbed/icetea | icetea_lib/tools/tools.py | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/tools/tools.py#L222-L242 | def import_module(modulename):
"""
Static method for importing module modulename. Can handle relative imports as well.
:param modulename: Name of module to import. Can be relative
:return: imported module instance.
"""
module = None
try:
module = importlib.import_module(modulename)
... | [
"def",
"import_module",
"(",
"modulename",
")",
":",
"module",
"=",
"None",
"try",
":",
"module",
"=",
"importlib",
".",
"import_module",
"(",
"modulename",
")",
"except",
"ImportError",
":",
"# If importing fails we see if the modulename has dots in it, split the name.",... | Static method for importing module modulename. Can handle relative imports as well.
:param modulename: Name of module to import. Can be relative
:return: imported module instance. | [
"Static",
"method",
"for",
"importing",
"module",
"modulename",
".",
"Can",
"handle",
"relative",
"imports",
"as",
"well",
"."
] | python | train |
gwpy/gwpy | gwpy/timeseries/io/nds2.py | https://github.com/gwpy/gwpy/blob/7a92b917e7dd2d99b15895293a1fa1d66cdb210a/gwpy/timeseries/io/nds2.py#L216-L221 | def _get_data_segments(channels, start, end, connection):
"""Get available data segments for the given channels
"""
allsegs = io_nds2.get_availability(channels, start, end,
connection=connection)
return allsegs.intersection(allsegs.keys()) | [
"def",
"_get_data_segments",
"(",
"channels",
",",
"start",
",",
"end",
",",
"connection",
")",
":",
"allsegs",
"=",
"io_nds2",
".",
"get_availability",
"(",
"channels",
",",
"start",
",",
"end",
",",
"connection",
"=",
"connection",
")",
"return",
"allsegs"... | Get available data segments for the given channels | [
"Get",
"available",
"data",
"segments",
"for",
"the",
"given",
"channels"
] | python | train |
salimm/pylods | pylods/deserialize.py | https://github.com/salimm/pylods/blob/d089e2a9afb1fa8cb6c754933fc574b512757c40/pylods/deserialize.py#L30-L36 | def copy_all(self, ctxt):
'''
copies all values into the current context from given context
:param ctxt:
'''
for key, value in ctxt.iteritems:
self.set_attribute(key, value) | [
"def",
"copy_all",
"(",
"self",
",",
"ctxt",
")",
":",
"for",
"key",
",",
"value",
"in",
"ctxt",
".",
"iteritems",
":",
"self",
".",
"set_attribute",
"(",
"key",
",",
"value",
")"
] | copies all values into the current context from given context
:param ctxt: | [
"copies",
"all",
"values",
"into",
"the",
"current",
"context",
"from",
"given",
"context",
":",
"param",
"ctxt",
":"
] | python | train |
pandas-dev/pandas | pandas/core/algorithms.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/algorithms.py#L723-L763 | def _value_counts_arraylike(values, dropna):
"""
Parameters
----------
values : arraylike
dropna : boolean
Returns
-------
(uniques, counts)
"""
values = _ensure_arraylike(values)
original = values
values, dtype, ndtype = _ensure_data(values)
if needs_i8_conversion... | [
"def",
"_value_counts_arraylike",
"(",
"values",
",",
"dropna",
")",
":",
"values",
"=",
"_ensure_arraylike",
"(",
"values",
")",
"original",
"=",
"values",
"values",
",",
"dtype",
",",
"ndtype",
"=",
"_ensure_data",
"(",
"values",
")",
"if",
"needs_i8_convers... | Parameters
----------
values : arraylike
dropna : boolean
Returns
-------
(uniques, counts) | [
"Parameters",
"----------",
"values",
":",
"arraylike",
"dropna",
":",
"boolean"
] | python | train |
thespacedoctor/transientNamer | transientNamer/search.py | https://github.com/thespacedoctor/transientNamer/blob/39be410c84275ed4669632f5df67e728d66a318f/transientNamer/search.py#L226-L280 | def csv(
self,
dirPath=None):
"""*Render the results in csv format*
**Key Arguments:**
- ``dirPath`` -- the path to the directory to save the rendered results to. Default *None*
**Return:**
- `csvSources` -- the top-level transient data
... | [
"def",
"csv",
"(",
"self",
",",
"dirPath",
"=",
"None",
")",
":",
"if",
"dirPath",
":",
"p",
"=",
"self",
".",
"_file_prefix",
"(",
")",
"csvSources",
"=",
"self",
".",
"sourceResults",
".",
"csv",
"(",
"filepath",
"=",
"dirPath",
"+",
"\"/\"",
"+",
... | *Render the results in csv format*
**Key Arguments:**
- ``dirPath`` -- the path to the directory to save the rendered results to. Default *None*
**Return:**
- `csvSources` -- the top-level transient data
- `csvPhot` -- all photometry associated with the transients
... | [
"*",
"Render",
"the",
"results",
"in",
"csv",
"format",
"*"
] | python | train |
saltstack/salt | salt/modules/boto_iam.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iam.py#L1398-L1423 | def get_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None):
'''
Retrieves the specified policy document for the specified user.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion boto_iam.get_user_policy myuser mypolicyname
''... | [
"def",
"get_user_policy",
"(",
"user_name",
",",
"policy_name",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"key",
... | Retrieves the specified policy document for the specified user.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion boto_iam.get_user_policy myuser mypolicyname | [
"Retrieves",
"the",
"specified",
"policy",
"document",
"for",
"the",
"specified",
"user",
"."
] | python | train |
msiemens/tinydb | tinydb/database.py | https://github.com/msiemens/tinydb/blob/10052cb1ae6a3682d26eb4272c44e3b020aa5877/tinydb/database.py#L610-L636 | def get(self, cond=None, doc_id=None, eid=None):
"""
Get exactly one document specified by a query or and ID.
Returns ``None`` if the document doesn't exist
:param cond: the condition to check against
:type cond: Query
:param doc_id: the document's ID
:returns... | [
"def",
"get",
"(",
"self",
",",
"cond",
"=",
"None",
",",
"doc_id",
"=",
"None",
",",
"eid",
"=",
"None",
")",
":",
"doc_id",
"=",
"_get_doc_id",
"(",
"doc_id",
",",
"eid",
")",
"# Cannot use process_elements here because we want to return a",
"# specific docume... | Get exactly one document specified by a query or and ID.
Returns ``None`` if the document doesn't exist
:param cond: the condition to check against
:type cond: Query
:param doc_id: the document's ID
:returns: the document or None
:rtype: Element | None | [
"Get",
"exactly",
"one",
"document",
"specified",
"by",
"a",
"query",
"or",
"and",
"ID",
"."
] | python | train |
dfm/casjobs | casjobs.py | https://github.com/dfm/casjobs/blob/1cc3f5511cc254d776082909221787e3c037ac16/casjobs.py#L164-L181 | def status(self, job_id):
"""
Check the status of a job.
## Arguments
* `job_id` (int): The job to check.
## Returns
* `code` (int): The status.
* `status` (str): The human-readable name of the current status.
"""
params = {"jobid": job_id}
... | [
"def",
"status",
"(",
"self",
",",
"job_id",
")",
":",
"params",
"=",
"{",
"\"jobid\"",
":",
"job_id",
"}",
"r",
"=",
"self",
".",
"_send_request",
"(",
"\"GetJobStatus\"",
",",
"params",
"=",
"params",
")",
"status",
"=",
"int",
"(",
"self",
".",
"_... | Check the status of a job.
## Arguments
* `job_id` (int): The job to check.
## Returns
* `code` (int): The status.
* `status` (str): The human-readable name of the current status. | [
"Check",
"the",
"status",
"of",
"a",
"job",
"."
] | python | train |
idlesign/django-sitetree | sitetree/sitetreeapp.py | https://github.com/idlesign/django-sitetree/blob/61de4608e6e415247c75fe8691027d7c4ed0d1e7/sitetree/sitetreeapp.py#L341-L348 | def get_entry(self, entry_name, key):
"""Returns cache entry parameter value by its name.
:param str|unicode entry_name:
:param key:
:return:
"""
return self.cache[entry_name].get(key, False) | [
"def",
"get_entry",
"(",
"self",
",",
"entry_name",
",",
"key",
")",
":",
"return",
"self",
".",
"cache",
"[",
"entry_name",
"]",
".",
"get",
"(",
"key",
",",
"False",
")"
] | Returns cache entry parameter value by its name.
:param str|unicode entry_name:
:param key:
:return: | [
"Returns",
"cache",
"entry",
"parameter",
"value",
"by",
"its",
"name",
"."
] | python | test |
juju/charm-helpers | charmhelpers/contrib/openstack/utils.py | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/utils.py#L375-L382 | def get_os_version_codename_swift(codename):
'''Determine OpenStack version number of swift from codename.'''
for k, v in six.iteritems(SWIFT_CODENAMES):
if k == codename:
return v[-1]
e = 'Could not derive swift version for '\
'codename: %s' % codename
error_out(e) | [
"def",
"get_os_version_codename_swift",
"(",
"codename",
")",
":",
"for",
"k",
",",
"v",
"in",
"six",
".",
"iteritems",
"(",
"SWIFT_CODENAMES",
")",
":",
"if",
"k",
"==",
"codename",
":",
"return",
"v",
"[",
"-",
"1",
"]",
"e",
"=",
"'Could not derive sw... | Determine OpenStack version number of swift from codename. | [
"Determine",
"OpenStack",
"version",
"number",
"of",
"swift",
"from",
"codename",
"."
] | python | train |
Crypto-toolbox/btfxwss | btfxwss/queue_processor.py | https://github.com/Crypto-toolbox/btfxwss/blob/16827fa6aacb2c0e289aa852bf61a18df6905835/btfxwss/queue_processor.py#L186-L203 | def _handle_auth(self, dtype, data, ts):
"""Handles authentication responses.
:param dtype:
:param data:
:param ts:
:return:
"""
# Contains keys status, chanId, userId, caps
if dtype == 'unauth':
raise NotImplementedError
channel_id = ... | [
"def",
"_handle_auth",
"(",
"self",
",",
"dtype",
",",
"data",
",",
"ts",
")",
":",
"# Contains keys status, chanId, userId, caps",
"if",
"dtype",
"==",
"'unauth'",
":",
"raise",
"NotImplementedError",
"channel_id",
"=",
"data",
".",
"pop",
"(",
"'chanId'",
")",... | Handles authentication responses.
:param dtype:
:param data:
:param ts:
:return: | [
"Handles",
"authentication",
"responses",
"."
] | python | test |
Toblerity/rtree | rtree/core.py | https://github.com/Toblerity/rtree/blob/5d33357c8e88f1a8344415dc15a7d2440211b281/rtree/core.py#L22-L29 | def check_void(result, func, cargs):
"Error checking for void* returns"
if not bool(result):
s = rt.Error_GetLastErrorMsg().decode()
msg = 'Error in "%s": %s' % (func.__name__, s)
rt.Error_Reset()
raise RTreeError(msg)
return result | [
"def",
"check_void",
"(",
"result",
",",
"func",
",",
"cargs",
")",
":",
"if",
"not",
"bool",
"(",
"result",
")",
":",
"s",
"=",
"rt",
".",
"Error_GetLastErrorMsg",
"(",
")",
".",
"decode",
"(",
")",
"msg",
"=",
"'Error in \"%s\": %s'",
"%",
"(",
"fu... | Error checking for void* returns | [
"Error",
"checking",
"for",
"void",
"*",
"returns"
] | python | test |
dwavesystems/dimod | dimod/reference/composites/fixedvariable.py | https://github.com/dwavesystems/dimod/blob/beff1b7f86b559d923ac653c1de6d593876d6d38/dimod/reference/composites/fixedvariable.py#L69-L102 | def sample(self, bqm, fixed_variables=None, **parameters):
"""Sample from the provided binary quadratic model.
Args:
bqm (:obj:`dimod.BinaryQuadraticModel`):
Binary quadratic model to be sampled from.
fixed_variables (dict):
A dictionary of varia... | [
"def",
"sample",
"(",
"self",
",",
"bqm",
",",
"fixed_variables",
"=",
"None",
",",
"*",
"*",
"parameters",
")",
":",
"# solve the problem on the child system",
"child",
"=",
"self",
".",
"child",
"bqm_copy",
"=",
"bqm",
".",
"copy",
"(",
")",
"if",
"fixed... | Sample from the provided binary quadratic model.
Args:
bqm (:obj:`dimod.BinaryQuadraticModel`):
Binary quadratic model to be sampled from.
fixed_variables (dict):
A dictionary of variable assignments.
**parameters:
Parameters... | [
"Sample",
"from",
"the",
"provided",
"binary",
"quadratic",
"model",
"."
] | python | train |
JukeboxPipeline/jukebox-core | src/jukeboxcore/gui/widgets/browser.py | https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/widgets/browser.py#L444-L460 | def add_lvl_to_ui(self, level, header):
"""Insert the level and header into the ui.
:param level: a newly created level
:type level: :class:`jukeboxcore.gui.widgets.browser.AbstractLevel`
:param header: a newly created header
:type header: QtCore.QWidget|None
:returns: N... | [
"def",
"add_lvl_to_ui",
"(",
"self",
",",
"level",
",",
"header",
")",
":",
"lay",
"=",
"self",
".",
"layout",
"(",
")",
"rc",
"=",
"lay",
".",
"rowCount",
"(",
")",
"lay",
".",
"addWidget",
"(",
"level",
",",
"rc",
"+",
"1",
",",
"1",
")",
"if... | Insert the level and header into the ui.
:param level: a newly created level
:type level: :class:`jukeboxcore.gui.widgets.browser.AbstractLevel`
:param header: a newly created header
:type header: QtCore.QWidget|None
:returns: None
:rtype: None
:raises: None | [
"Insert",
"the",
"level",
"and",
"header",
"into",
"the",
"ui",
"."
] | python | train |
lk-geimfari/mimesis | mimesis/providers/development.py | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/development.py#L29-L60 | def version(self, calver: bool = False, pre_release: bool = False) -> str:
"""Generate version number.
:param calver: Calendar versioning.
:param pre_release: Pre-release.
:return: Version.
:Example:
0.2.1
"""
# TODO: Optimize
version = '{}.{... | [
"def",
"version",
"(",
"self",
",",
"calver",
":",
"bool",
"=",
"False",
",",
"pre_release",
":",
"bool",
"=",
"False",
")",
"->",
"str",
":",
"# TODO: Optimize",
"version",
"=",
"'{}.{}.{}'",
"major",
",",
"minor",
",",
"patch",
"=",
"self",
".",
"ran... | Generate version number.
:param calver: Calendar versioning.
:param pre_release: Pre-release.
:return: Version.
:Example:
0.2.1 | [
"Generate",
"version",
"number",
"."
] | python | train |
pln-fing-udelar/fast-krippendorff | krippendorff/krippendorff.py | https://github.com/pln-fing-udelar/fast-krippendorff/blob/fbc983f206d41f76a6e8da8cabd7114941634420/krippendorff/krippendorff.py#L162-L261 | def alpha(reliability_data=None, value_counts=None, value_domain=None, level_of_measurement='interval',
dtype=np.float64):
"""Compute Krippendorff's alpha.
See https://en.wikipedia.org/wiki/Krippendorff%27s_alpha for more information.
Parameters
----------
reliability_data : array_like, ... | [
"def",
"alpha",
"(",
"reliability_data",
"=",
"None",
",",
"value_counts",
"=",
"None",
",",
"value_domain",
"=",
"None",
",",
"level_of_measurement",
"=",
"'interval'",
",",
"dtype",
"=",
"np",
".",
"float64",
")",
":",
"if",
"(",
"reliability_data",
"is",
... | Compute Krippendorff's alpha.
See https://en.wikipedia.org/wiki/Krippendorff%27s_alpha for more information.
Parameters
----------
reliability_data : array_like, with shape (M, N)
Reliability data matrix which has the rate the i coder gave to the j unit, where M is the number of raters
... | [
"Compute",
"Krippendorff",
"s",
"alpha",
"."
] | python | valid |
JustinLovinger/optimal | optimal/optimize.py | https://github.com/JustinLovinger/optimal/blob/ab48a4961697338cc32d50e3a6b06ac989e39c3f/optimal/optimize.py#L794-L838 | def _make_hyperparameter_decode_func(locked_values, meta_parameters):
"""Create a function that converts the binary solution to parameters."""
# Locked parameters are also returned by decode function, but are not
# based on solution
def decode(solution):
"""Convert solution into dict of hyperp... | [
"def",
"_make_hyperparameter_decode_func",
"(",
"locked_values",
",",
"meta_parameters",
")",
":",
"# Locked parameters are also returned by decode function, but are not",
"# based on solution",
"def",
"decode",
"(",
"solution",
")",
":",
"\"\"\"Convert solution into dict of hyperpar... | Create a function that converts the binary solution to parameters. | [
"Create",
"a",
"function",
"that",
"converts",
"the",
"binary",
"solution",
"to",
"parameters",
"."
] | python | train |
fermiPy/fermipy | fermipy/jobs/link.py | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/jobs/link.py#L959-L982 | def run_with_log(self, dry_run=False, stage_files=True, resubmit_failed=False):
"""Runs this link with output sent to a pre-defined logfile
Parameters
-----------
dry_run : bool
Print command but do not run it.
stage_files : bool
Copy files to and from s... | [
"def",
"run_with_log",
"(",
"self",
",",
"dry_run",
"=",
"False",
",",
"stage_files",
"=",
"True",
",",
"resubmit_failed",
"=",
"False",
")",
":",
"fullkey",
"=",
"JobDetails",
".",
"make_fullkey",
"(",
"self",
".",
"full_linkname",
")",
"job_details",
"=",
... | Runs this link with output sent to a pre-defined logfile
Parameters
-----------
dry_run : bool
Print command but do not run it.
stage_files : bool
Copy files to and from scratch staging area.
resubmit_failed : bool
Flag for sub-classes to re... | [
"Runs",
"this",
"link",
"with",
"output",
"sent",
"to",
"a",
"pre",
"-",
"defined",
"logfile"
] | python | train |
sdispater/orator | orator/orm/relations/belongs_to_many.py | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/orm/relations/belongs_to_many.py#L159-L168 | def _hydrate_pivot_relation(self, models):
"""
Hydrate the pivot table relationship on the models.
:type models: list
"""
for model in models:
pivot = self.new_existing_pivot(self._clean_pivot_attributes(model))
model.set_relation("pivot", pivot) | [
"def",
"_hydrate_pivot_relation",
"(",
"self",
",",
"models",
")",
":",
"for",
"model",
"in",
"models",
":",
"pivot",
"=",
"self",
".",
"new_existing_pivot",
"(",
"self",
".",
"_clean_pivot_attributes",
"(",
"model",
")",
")",
"model",
".",
"set_relation",
"... | Hydrate the pivot table relationship on the models.
:type models: list | [
"Hydrate",
"the",
"pivot",
"table",
"relationship",
"on",
"the",
"models",
"."
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.