nwo stringlengths 5 106 | sha stringlengths 40 40 | path stringlengths 4 174 | language stringclasses 1
value | identifier stringlengths 1 140 | parameters stringlengths 0 87.7k | argument_list stringclasses 1
value | return_statement stringlengths 0 426k | docstring stringlengths 0 64.3k | docstring_summary stringlengths 0 26.3k | docstring_tokens list | function stringlengths 18 4.83M | function_tokens list | url stringlengths 83 304 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
mozillazg/pypy | 2ff5cd960c075c991389f842c6d59e71cf0cb7d0 | lib-python/2.7/lib-tk/Tkinter.py | python | Text.tag_raise | (self, tagName, aboveThis=None) | Change the priority of tag TAGNAME such that it is higher
than the priority of ABOVETHIS. | Change the priority of tag TAGNAME such that it is higher
than the priority of ABOVETHIS. | [
"Change",
"the",
"priority",
"of",
"tag",
"TAGNAME",
"such",
"that",
"it",
"is",
"higher",
"than",
"the",
"priority",
"of",
"ABOVETHIS",
"."
] | def tag_raise(self, tagName, aboveThis=None):
"""Change the priority of tag TAGNAME such that it is higher
than the priority of ABOVETHIS."""
self.tk.call(
self._w, 'tag', 'raise', tagName, aboveThis) | [
"def",
"tag_raise",
"(",
"self",
",",
"tagName",
",",
"aboveThis",
"=",
"None",
")",
":",
"self",
".",
"tk",
".",
"call",
"(",
"self",
".",
"_w",
",",
"'tag'",
",",
"'raise'",
",",
"tagName",
",",
"aboveThis",
")"
] | https://github.com/mozillazg/pypy/blob/2ff5cd960c075c991389f842c6d59e71cf0cb7d0/lib-python/2.7/lib-tk/Tkinter.py#L3220-L3224 | ||
IronLanguages/main | a949455434b1fda8c783289e897e78a9a0caabb5 | External.LCA_RESTRICTED/Languages/IronPython/27/Lib/logging/__init__.py | python | Logger.debug | (self, msg, *args, **kwargs) | Log 'msg % args' with severity 'DEBUG'.
To pass exception information, use the keyword argument exc_info with
a true value, e.g.
logger.debug("Houston, we have a %s", "thorny problem", exc_info=1) | Log 'msg % args' with severity 'DEBUG'. | [
"Log",
"msg",
"%",
"args",
"with",
"severity",
"DEBUG",
"."
] | def debug(self, msg, *args, **kwargs):
"""
Log 'msg % args' with severity 'DEBUG'.
To pass exception information, use the keyword argument exc_info with
a true value, e.g.
logger.debug("Houston, we have a %s", "thorny problem", exc_info=1)
"""
if self.isEnabledFor(DEBUG):
self._log(DEBUG, msg, args, **kwargs) | [
"def",
"debug",
"(",
"self",
",",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"isEnabledFor",
"(",
"DEBUG",
")",
":",
"self",
".",
"_log",
"(",
"DEBUG",
",",
"msg",
",",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/IronLanguages/main/blob/a949455434b1fda8c783289e897e78a9a0caabb5/External.LCA_RESTRICTED/Languages/IronPython/27/Lib/logging/__init__.py#L1145-L1155 | ||
celery/django-celery | c679b05b2abc174e6fa3231b120a07b49ec8f911 | djcelery/managers.py | python | TaskSetManager.restore_taskset | (self, taskset_id) | Get the async result instance by taskset id. | Get the async result instance by taskset id. | [
"Get",
"the",
"async",
"result",
"instance",
"by",
"taskset",
"id",
"."
] | def restore_taskset(self, taskset_id):
"""Get the async result instance by taskset id."""
try:
return self.get(taskset_id=taskset_id)
except self.model.DoesNotExist:
pass | [
"def",
"restore_taskset",
"(",
"self",
",",
"taskset_id",
")",
":",
"try",
":",
"return",
"self",
".",
"get",
"(",
"taskset_id",
"=",
"taskset_id",
")",
"except",
"self",
".",
"model",
".",
"DoesNotExist",
":",
"pass"
] | https://github.com/celery/django-celery/blob/c679b05b2abc174e6fa3231b120a07b49ec8f911/djcelery/managers.py#L229-L234 | ||
oddt/oddt | 8cf555820d97a692ade81c101ebe10e28bcb3722 | oddt/metrics.py | python | roc_log_auc | (y_true, y_score, pos_label=None, ascending_score=True,
log_min=0.001, log_max=1.) | return auc(log_fpr, tpr[idx]) | Computes area under semi-log ROC.
Parameters
----------
y_true : array, shape=[n_samples]
True binary labels, in range {0,1} or {-1,1}. If positive label is
different than 1, it must be explicitly defined.
y_score : array, shape=[n_samples]
Scores for tested series of samples
pos_label: int
Positive label of samples (if other than 1)
ascending_score: bool (default=True)
Indicates if your score is ascendig. Ascending score icreases with
deacreasing activity. In other words it ascends on ranking list
(where actives are on top).
log_min : float (default=0.001)
Minimum value for estimating AUC. Lower values will be clipped for
numerical stability.
log_max : float (default=1.)
Maximum value for estimating AUC. Higher values will be ignored.
Returns
-------
auc : float
semi-log ROC AUC | Computes area under semi-log ROC. | [
"Computes",
"area",
"under",
"semi",
"-",
"log",
"ROC",
"."
] | def roc_log_auc(y_true, y_score, pos_label=None, ascending_score=True,
log_min=0.001, log_max=1.):
"""Computes area under semi-log ROC.
Parameters
----------
y_true : array, shape=[n_samples]
True binary labels, in range {0,1} or {-1,1}. If positive label is
different than 1, it must be explicitly defined.
y_score : array, shape=[n_samples]
Scores for tested series of samples
pos_label: int
Positive label of samples (if other than 1)
ascending_score: bool (default=True)
Indicates if your score is ascendig. Ascending score icreases with
deacreasing activity. In other words it ascends on ranking list
(where actives are on top).
log_min : float (default=0.001)
Minimum value for estimating AUC. Lower values will be clipped for
numerical stability.
log_max : float (default=1.)
Maximum value for estimating AUC. Higher values will be ignored.
Returns
-------
auc : float
semi-log ROC AUC
"""
if ascending_score:
y_score = -y_score
fpr, tpr, t = roc(y_true, y_score, pos_label=pos_label)
fpr = fpr.clip(log_min)
idx = (fpr <= log_max)
log_fpr = 1 - np.log10(fpr[idx]) / np.log10(log_min)
return auc(log_fpr, tpr[idx]) | [
"def",
"roc_log_auc",
"(",
"y_true",
",",
"y_score",
",",
"pos_label",
"=",
"None",
",",
"ascending_score",
"=",
"True",
",",
"log_min",
"=",
"0.001",
",",
"log_max",
"=",
"1.",
")",
":",
"if",
"ascending_score",
":",
"y_score",
"=",
"-",
"y_score",
"fpr... | https://github.com/oddt/oddt/blob/8cf555820d97a692ade81c101ebe10e28bcb3722/oddt/metrics.py#L109-L148 | |
OpenRCE/sulley | bff0dd1864d055eb4bfa8aacbbb6ecf215e4db4b | sulley/__init__.py | python | s_word | (value, endian="<", format="binary", signed=False, full_range=False, fuzzable=True, name=None) | Push a word onto the current block stack.
@see: Aliases: s_short()
@type value: Integer
@param value: Default integer value
@type endian: Character
@param endian: (Optional, def=LITTLE_ENDIAN) Endianess of the bit field (LITTLE_ENDIAN: <, BIG_ENDIAN: >)
@type format: String
@param format: (Optional, def=binary) Output format, "binary" or "ascii"
@type signed: Boolean
@param signed: (Optional, def=False) Make size signed vs. unsigned (applicable only with format="ascii")
@type full_range: Boolean
@param full_range: (Optional, def=False) If enabled the field mutates through *all* possible values.
@type fuzzable: Boolean
@param fuzzable: (Optional, def=True) Enable/disable fuzzing of this primitive
@type name: String
@param name: (Optional, def=None) Specifying a name gives you direct access to a primitive | Push a word onto the current block stack. | [
"Push",
"a",
"word",
"onto",
"the",
"current",
"block",
"stack",
"."
] | def s_word (value, endian="<", format="binary", signed=False, full_range=False, fuzzable=True, name=None):
'''
Push a word onto the current block stack.
@see: Aliases: s_short()
@type value: Integer
@param value: Default integer value
@type endian: Character
@param endian: (Optional, def=LITTLE_ENDIAN) Endianess of the bit field (LITTLE_ENDIAN: <, BIG_ENDIAN: >)
@type format: String
@param format: (Optional, def=binary) Output format, "binary" or "ascii"
@type signed: Boolean
@param signed: (Optional, def=False) Make size signed vs. unsigned (applicable only with format="ascii")
@type full_range: Boolean
@param full_range: (Optional, def=False) If enabled the field mutates through *all* possible values.
@type fuzzable: Boolean
@param fuzzable: (Optional, def=True) Enable/disable fuzzing of this primitive
@type name: String
@param name: (Optional, def=None) Specifying a name gives you direct access to a primitive
'''
word = primitives.word(value, endian, format, signed, full_range, fuzzable, name)
blocks.CURRENT.push(word) | [
"def",
"s_word",
"(",
"value",
",",
"endian",
"=",
"\"<\"",
",",
"format",
"=",
"\"binary\"",
",",
"signed",
"=",
"False",
",",
"full_range",
"=",
"False",
",",
"fuzzable",
"=",
"True",
",",
"name",
"=",
"None",
")",
":",
"word",
"=",
"primitives",
"... | https://github.com/OpenRCE/sulley/blob/bff0dd1864d055eb4bfa8aacbbb6ecf215e4db4b/sulley/__init__.py#L469-L492 | ||
XX-net/XX-Net | a9898cfcf0084195fb7e69b6bc834e59aecdf14f | python3.8.2/Lib/site-packages/pkg_resources/_vendor/pyparsing.py | python | ParserElement.split | (self, instring, maxsplit=_MAX_INT, includeSeparators=False) | Generator method to split a string using the given expression as a separator.
May be called with optional C{maxsplit} argument, to limit the number of splits;
and the optional C{includeSeparators} argument (default=C{False}), if the separating
matching text should be included in the split results.
Example::
punc = oneOf(list(".,;:/-!?"))
print(list(punc.split("This, this?, this sentence, is badly punctuated!")))
prints::
['This', ' this', '', ' this sentence', ' is badly punctuated', ''] | Generator method to split a string using the given expression as a separator.
May be called with optional C{maxsplit} argument, to limit the number of splits;
and the optional C{includeSeparators} argument (default=C{False}), if the separating
matching text should be included in the split results.
Example::
punc = oneOf(list(".,;:/-!?"))
print(list(punc.split("This, this?, this sentence, is badly punctuated!")))
prints::
['This', ' this', '', ' this sentence', ' is badly punctuated', ''] | [
"Generator",
"method",
"to",
"split",
"a",
"string",
"using",
"the",
"given",
"expression",
"as",
"a",
"separator",
".",
"May",
"be",
"called",
"with",
"optional",
"C",
"{",
"maxsplit",
"}",
"argument",
"to",
"limit",
"the",
"number",
"of",
"splits",
";",
... | def split(self, instring, maxsplit=_MAX_INT, includeSeparators=False):
"""
Generator method to split a string using the given expression as a separator.
May be called with optional C{maxsplit} argument, to limit the number of splits;
and the optional C{includeSeparators} argument (default=C{False}), if the separating
matching text should be included in the split results.
Example::
punc = oneOf(list(".,;:/-!?"))
print(list(punc.split("This, this?, this sentence, is badly punctuated!")))
prints::
['This', ' this', '', ' this sentence', ' is badly punctuated', '']
"""
splits = 0
last = 0
for t,s,e in self.scanString(instring, maxMatches=maxsplit):
yield instring[last:s]
if includeSeparators:
yield t[0]
last = e
yield instring[last:] | [
"def",
"split",
"(",
"self",
",",
"instring",
",",
"maxsplit",
"=",
"_MAX_INT",
",",
"includeSeparators",
"=",
"False",
")",
":",
"splits",
"=",
"0",
"last",
"=",
"0",
"for",
"t",
",",
"s",
",",
"e",
"in",
"self",
".",
"scanString",
"(",
"instring",
... | https://github.com/XX-net/XX-Net/blob/a9898cfcf0084195fb7e69b6bc834e59aecdf14f/python3.8.2/Lib/site-packages/pkg_resources/_vendor/pyparsing.py#L1799-L1819 | ||
accel-brain/accel-brain-code | 86f489dc9be001a3bae6d053f48d6b57c0bedb95 | Reinforcement-Learning/pyqlearning/q_learning.py | python | QLearning.extract_possible_actions | (self, state_key) | Extract the list of the possible action in `self.t+1`.
Abstract method for concreate usecases.
Args:
state_key The key of state in `self.t+1`.
Returns:
`list` of the possible actions in `self.t+1`. | Extract the list of the possible action in `self.t+1`. | [
"Extract",
"the",
"list",
"of",
"the",
"possible",
"action",
"in",
"self",
".",
"t",
"+",
"1",
"."
] | def extract_possible_actions(self, state_key):
'''
Extract the list of the possible action in `self.t+1`.
Abstract method for concreate usecases.
Args:
state_key The key of state in `self.t+1`.
Returns:
`list` of the possible actions in `self.t+1`.
'''
raise NotImplementedError("This method must be implemented.") | [
"def",
"extract_possible_actions",
"(",
"self",
",",
"state_key",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"This method must be implemented.\"",
")"
] | https://github.com/accel-brain/accel-brain-code/blob/86f489dc9be001a3bae6d053f48d6b57c0bedb95/Reinforcement-Learning/pyqlearning/q_learning.py#L323-L336 | ||
biopython/biopython | 2dd97e71762af7b046d7f7f8a4f1e38db6b06c86 | Bio/Sequencing/Ace.py | python | wa.__init__ | (self, line=None) | Initialize the class. | Initialize the class. | [
"Initialize",
"the",
"class",
"."
] | def __init__(self, line=None):
"""Initialize the class."""
self.tag_type = ""
self.program = ""
self.date = ""
self.info = []
if line:
header = line.split()
self.tag_type = header[0]
self.program = header[1]
self.date = header[2] | [
"def",
"__init__",
"(",
"self",
",",
"line",
"=",
"None",
")",
":",
"self",
".",
"tag_type",
"=",
"\"\"",
"self",
".",
"program",
"=",
"\"\"",
"self",
".",
"date",
"=",
"\"\"",
"self",
".",
"info",
"=",
"[",
"]",
"if",
"line",
":",
"header",
"=",... | https://github.com/biopython/biopython/blob/2dd97e71762af7b046d7f7f8a4f1e38db6b06c86/Bio/Sequencing/Ace.py#L214-L224 | ||
Tautulli/Tautulli | 2410eb33805aaac4bd1c5dad0f71e4f15afaf742 | lib/twitter/models.py | python | DirectMessage.__init__ | (self, **kwargs) | [] | def __init__(self, **kwargs):
self.param_defaults = {
'created_at': None,
'id': None,
'recipient_id': None,
'sender_id': None,
'text': None,
}
for (param, default) in self.param_defaults.items():
setattr(self, param, kwargs.get(param, default)) | [
"def",
"__init__",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"param_defaults",
"=",
"{",
"'created_at'",
":",
"None",
",",
"'id'",
":",
"None",
",",
"'recipient_id'",
":",
"None",
",",
"'sender_id'",
":",
"None",
",",
"'text'",
":",
... | https://github.com/Tautulli/Tautulli/blob/2410eb33805aaac4bd1c5dad0f71e4f15afaf742/lib/twitter/models.py#L184-L194 | ||||
atlassian-api/atlassian-python-api | 6d8545a790c3aae10b75bdc225fb5c3a0aee44db | atlassian/xray.py | python | Xray.get_test_executions_with_test_plan | (self, test_plan_key) | return self.get(url) | Retrieve test executions associated with the given test plan.
:param test_plan_key: Test plan key (eg. 'PLAN-001').
:return: Return a list of the test executions associated with the test plan. | Retrieve test executions associated with the given test plan.
:param test_plan_key: Test plan key (eg. 'PLAN-001').
:return: Return a list of the test executions associated with the test plan. | [
"Retrieve",
"test",
"executions",
"associated",
"with",
"the",
"given",
"test",
"plan",
".",
":",
"param",
"test_plan_key",
":",
"Test",
"plan",
"key",
"(",
"eg",
".",
"PLAN",
"-",
"001",
")",
".",
":",
"return",
":",
"Return",
"a",
"list",
"of",
"the"... | def get_test_executions_with_test_plan(self, test_plan_key):
"""
Retrieve test executions associated with the given test plan.
:param test_plan_key: Test plan key (eg. 'PLAN-001').
:return: Return a list of the test executions associated with the test plan.
"""
url = "rest/raven/1.0/api/testplan/{0}/testexecution".format(test_plan_key)
return self.get(url) | [
"def",
"get_test_executions_with_test_plan",
"(",
"self",
",",
"test_plan_key",
")",
":",
"url",
"=",
"\"rest/raven/1.0/api/testplan/{0}/testexecution\"",
".",
"format",
"(",
"test_plan_key",
")",
"return",
"self",
".",
"get",
"(",
"url",
")"
] | https://github.com/atlassian-api/atlassian-python-api/blob/6d8545a790c3aae10b75bdc225fb5c3a0aee44db/atlassian/xray.py#L286-L293 | |
aws/sagemaker-python-sdk | 9d259b316f7f43838c16f35c10e98a110b56735b | src/sagemaker/tensorflow/processing.py | python | TensorFlowProcessor.__init__ | (
self,
framework_version, # New arg
role,
instance_count,
instance_type,
py_version="py3", # New kwarg
image_uri=None,
command=None,
volume_size_in_gb=30,
volume_kms_key=None,
output_kms_key=None,
code_location=None, # New arg
max_runtime_in_seconds=None,
base_job_name=None,
sagemaker_session=None,
env=None,
tags=None,
network_config=None,
) | This processor executes a Python script in a TensorFlow execution environment.
Unless ``image_uri`` is specified, the TensorFlow environment is an
Amazon-built Docker container that executes functions defined in the supplied
``code`` Python script.
The arguments have the exact same meaning as in ``FrameworkProcessor``.
.. tip::
You can find additional parameters for initializing this class at
:class:`~sagemaker.processing.FrameworkProcessor`. | This processor executes a Python script in a TensorFlow execution environment. | [
"This",
"processor",
"executes",
"a",
"Python",
"script",
"in",
"a",
"TensorFlow",
"execution",
"environment",
"."
] | def __init__(
self,
framework_version, # New arg
role,
instance_count,
instance_type,
py_version="py3", # New kwarg
image_uri=None,
command=None,
volume_size_in_gb=30,
volume_kms_key=None,
output_kms_key=None,
code_location=None, # New arg
max_runtime_in_seconds=None,
base_job_name=None,
sagemaker_session=None,
env=None,
tags=None,
network_config=None,
):
"""This processor executes a Python script in a TensorFlow execution environment.
Unless ``image_uri`` is specified, the TensorFlow environment is an
Amazon-built Docker container that executes functions defined in the supplied
``code`` Python script.
The arguments have the exact same meaning as in ``FrameworkProcessor``.
.. tip::
You can find additional parameters for initializing this class at
:class:`~sagemaker.processing.FrameworkProcessor`.
"""
super().__init__(
self.estimator_cls,
framework_version,
role,
instance_count,
instance_type,
py_version,
image_uri,
command,
volume_size_in_gb,
volume_kms_key,
output_kms_key,
code_location,
max_runtime_in_seconds,
base_job_name,
sagemaker_session,
env,
tags,
network_config,
) | [
"def",
"__init__",
"(",
"self",
",",
"framework_version",
",",
"# New arg",
"role",
",",
"instance_count",
",",
"instance_type",
",",
"py_version",
"=",
"\"py3\"",
",",
"# New kwarg",
"image_uri",
"=",
"None",
",",
"command",
"=",
"None",
",",
"volume_size_in_gb... | https://github.com/aws/sagemaker-python-sdk/blob/9d259b316f7f43838c16f35c10e98a110b56735b/src/sagemaker/tensorflow/processing.py#L29-L81 | ||
fluentpython/example-code-2e | 80f7f84274a47579e59c29a4657691525152c9d5 | 03-dict-set/missing.py | python | DictSub.__missing__ | (self, key) | return self[_upper(key)] | [] | def __missing__(self, key):
return self[_upper(key)] | [
"def",
"__missing__",
"(",
"self",
",",
"key",
")",
":",
"return",
"self",
"[",
"_upper",
"(",
"key",
")",
"]"
] | https://github.com/fluentpython/example-code-2e/blob/80f7f84274a47579e59c29a4657691525152c9d5/03-dict-set/missing.py#L75-L76 | |||
horovod/horovod | 976a87958d48b4359834b33564c95e808d005dab | horovod/ray/adapter.py | python | Adapter.start | (self,
executable_cls: type = None,
executable_args: Optional[List] = None,
executable_kwargs: Optional[Dict] = None,
extra_env_vars: Optional[Dict] = None) | Starts the Adapter
Args:
executable_cls (type): The class that will be created within
an actor (BaseHorovodWorker). This will allow Horovod
to establish its connections and set env vars.
executable_args (List): Arguments to be passed into the
worker class upon initialization.
executable_kwargs (Dict): Keyword arguments to be passed into the
worker class upon initialization.
extra_env_vars (Dict): Environment variables to be set
on the actors (worker processes) before initialization. | Starts the Adapter | [
"Starts",
"the",
"Adapter"
] | def start(self,
executable_cls: type = None,
executable_args: Optional[List] = None,
executable_kwargs: Optional[Dict] = None,
extra_env_vars: Optional[Dict] = None):
"""Starts the Adapter
Args:
executable_cls (type): The class that will be created within
an actor (BaseHorovodWorker). This will allow Horovod
to establish its connections and set env vars.
executable_args (List): Arguments to be passed into the
worker class upon initialization.
executable_kwargs (Dict): Keyword arguments to be passed into the
worker class upon initialization.
extra_env_vars (Dict): Environment variables to be set
on the actors (worker processes) before initialization.
"""
raise NotImplementedError("Method must be implemented in a subclass") | [
"def",
"start",
"(",
"self",
",",
"executable_cls",
":",
"type",
"=",
"None",
",",
"executable_args",
":",
"Optional",
"[",
"List",
"]",
"=",
"None",
",",
"executable_kwargs",
":",
"Optional",
"[",
"Dict",
"]",
"=",
"None",
",",
"extra_env_vars",
":",
"O... | https://github.com/horovod/horovod/blob/976a87958d48b4359834b33564c95e808d005dab/horovod/ray/adapter.py#L27-L45 | ||
leancloud/satori | 701caccbd4fe45765001ca60435c0cb499477c03 | satori-rules/plugin/libs/requests/packages/urllib3/packages/ordered_dict.py | python | OrderedDict.__delitem__ | (self, key, dict_delitem=dict.__delitem__) | od.__delitem__(y) <==> del od[y] | od.__delitem__(y) <==> del od[y] | [
"od",
".",
"__delitem__",
"(",
"y",
")",
"<",
"==",
">",
"del",
"od",
"[",
"y",
"]"
] | def __delitem__(self, key, dict_delitem=dict.__delitem__):
'od.__delitem__(y) <==> del od[y]'
# Deleting an existing item uses self.__map to find the link which is
# then removed by updating the links in the predecessor and successor nodes.
dict_delitem(self, key)
link_prev, link_next, key = self.__map.pop(key)
link_prev[1] = link_next
link_next[0] = link_prev | [
"def",
"__delitem__",
"(",
"self",
",",
"key",
",",
"dict_delitem",
"=",
"dict",
".",
"__delitem__",
")",
":",
"# Deleting an existing item uses self.__map to find the link which is",
"# then removed by updating the links in the predecessor and successor nodes.",
"dict_delitem",
"(... | https://github.com/leancloud/satori/blob/701caccbd4fe45765001ca60435c0cb499477c03/satori-rules/plugin/libs/requests/packages/urllib3/packages/ordered_dict.py#L54-L61 | ||
rndusr/stig | 334f03e2e3eda7c1856dd5489f0265a47b9861b6 | stig/settings/settings.py | python | RemoteSettings.syntax | (self, name) | return self._cfg.syntax(name[4:]) | Return setting's description | Return setting's description | [
"Return",
"setting",
"s",
"description"
] | def syntax(self, name):
"""Return setting's description"""
if not name.startswith('srv.'):
raise KeyError(name)
return self._cfg.syntax(name[4:]) | [
"def",
"syntax",
"(",
"self",
",",
"name",
")",
":",
"if",
"not",
"name",
".",
"startswith",
"(",
"'srv.'",
")",
":",
"raise",
"KeyError",
"(",
"name",
")",
"return",
"self",
".",
"_cfg",
".",
"syntax",
"(",
"name",
"[",
"4",
":",
"]",
")"
] | https://github.com/rndusr/stig/blob/334f03e2e3eda7c1856dd5489f0265a47b9861b6/stig/settings/settings.py#L200-L204 | |
xtiankisutsa/MARA_Framework | ac4ac88bfd38f33ae8780a606ed09ab97177c562 | tools/qark/qark/lib/blessed/sequences.py | python | init_sequence_patterns | (term) | return {'_re_will_move': _re_will_move,
'_re_wont_move': _re_wont_move,
'_re_cuf': _re_cuf,
'_re_cub': _re_cub,
'_cuf1': _cuf1,
'_cub1': _cub1, } | Given a Terminal instance, ``term``, this function processes
and parses several known terminal capabilities, and builds and
returns a dictionary database of regular expressions, which may
be re-attached to the terminal by attributes of the same key-name:
``_re_will_move``
any sequence matching this pattern will cause the terminal
cursor to move (such as *term.home*).
``_re_wont_move``
any sequence matching this pattern will not cause the cursor
to move (such as *term.bold*).
``_re_cuf``
regular expression that matches term.cuf(N) (move N characters forward),
or None if temrinal is without cuf sequence.
``_cuf1``
*term.cuf1* sequence (cursor forward 1 character) as a static value.
``_re_cub``
regular expression that matches term.cub(N) (move N characters backward),
or None if terminal is without cub sequence.
``_cub1``
*term.cuf1* sequence (cursor backward 1 character) as a static value.
These attributes make it possible to perform introspection on strings
containing sequences generated by this terminal, to determine the
printable length of a string. | Given a Terminal instance, ``term``, this function processes
and parses several known terminal capabilities, and builds and
returns a dictionary database of regular expressions, which may
be re-attached to the terminal by attributes of the same key-name: | [
"Given",
"a",
"Terminal",
"instance",
"term",
"this",
"function",
"processes",
"and",
"parses",
"several",
"known",
"terminal",
"capabilities",
"and",
"builds",
"and",
"returns",
"a",
"dictionary",
"database",
"of",
"regular",
"expressions",
"which",
"may",
"be",
... | def init_sequence_patterns(term):
"""Given a Terminal instance, ``term``, this function processes
and parses several known terminal capabilities, and builds and
returns a dictionary database of regular expressions, which may
be re-attached to the terminal by attributes of the same key-name:
``_re_will_move``
any sequence matching this pattern will cause the terminal
cursor to move (such as *term.home*).
``_re_wont_move``
any sequence matching this pattern will not cause the cursor
to move (such as *term.bold*).
``_re_cuf``
regular expression that matches term.cuf(N) (move N characters forward),
or None if temrinal is without cuf sequence.
``_cuf1``
*term.cuf1* sequence (cursor forward 1 character) as a static value.
``_re_cub``
regular expression that matches term.cub(N) (move N characters backward),
or None if terminal is without cub sequence.
``_cub1``
*term.cuf1* sequence (cursor backward 1 character) as a static value.
These attributes make it possible to perform introspection on strings
containing sequences generated by this terminal, to determine the
printable length of a string.
"""
if term._kind in _BINTERM_UNSUPPORTED:
warnings.warn(_BINTERM_UNSUPPORTED_MSG)
# Build will_move, a list of terminal capabilities that have
# indeterminate effects on the terminal cursor position.
_will_move = _merge_sequences(get_movement_sequence_patterns(term)
) if term.does_styling else set()
# Build wont_move, a list of terminal capabilities that mainly affect
# video attributes, for use with measure_length().
_wont_move = _merge_sequences(get_wontmove_sequence_patterns(term)
) if term.does_styling else set()
# compile as regular expressions, OR'd.
_re_will_move = re.compile('(%s)' % ('|'.join(_will_move)))
_re_wont_move = re.compile('(%s)' % ('|'.join(_wont_move)))
#
# static pattern matching for horizontal_distance(ucs, term)
#
bnc = functools.partial(_build_numeric_capability, term)
# parm_right_cursor: Move #1 characters to the right
_cuf = bnc(cap='cuf', optional=True)
_re_cuf = re.compile(_cuf) if _cuf else None
# cursor_right: Non-destructive space (move right one space)
_cuf1 = term.cuf1
# parm_left_cursor: Move #1 characters to the left
_cub = bnc(cap='cub', optional=True)
_re_cub = re.compile(_cub) if _cub else None
# cursor_left: Move left one space
_cub1 = term.cub1
return {'_re_will_move': _re_will_move,
'_re_wont_move': _re_wont_move,
'_re_cuf': _re_cuf,
'_re_cub': _re_cub,
'_cuf1': _cuf1,
'_cub1': _cub1, } | [
"def",
"init_sequence_patterns",
"(",
"term",
")",
":",
"if",
"term",
".",
"_kind",
"in",
"_BINTERM_UNSUPPORTED",
":",
"warnings",
".",
"warn",
"(",
"_BINTERM_UNSUPPORTED_MSG",
")",
"# Build will_move, a list of terminal capabilities that have",
"# indeterminate effects on th... | https://github.com/xtiankisutsa/MARA_Framework/blob/ac4ac88bfd38f33ae8780a606ed09ab97177c562/tools/qark/qark/lib/blessed/sequences.py#L222-L295 | |
buke/GreenOdoo | 3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df | runtime/python/lib/python2.7/site-packages/_xmlplus/parsers/xmlproc/xmlproc.py | python | XMLProcessor.get_construct_end | (self) | return self.pos | Returns the end position of the current construct (tag, comment,
etc). | Returns the end position of the current construct (tag, comment,
etc). | [
"Returns",
"the",
"end",
"position",
"of",
"the",
"current",
"construct",
"(",
"tag",
"comment",
"etc",
")",
"."
] | def get_construct_end(self):
"""Returns the end position of the current construct (tag, comment,
etc)."""
return self.pos | [
"def",
"get_construct_end",
"(",
"self",
")",
":",
"return",
"self",
".",
"pos"
] | https://github.com/buke/GreenOdoo/blob/3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df/runtime/python/lib/python2.7/site-packages/_xmlplus/parsers/xmlproc/xmlproc.py#L595-L598 | |
syuntoku14/fusion2urdf | 79af25950b4de8801602ca16192a6c836bab7063 | URDF_Exporter/core/Link.py | python | make_inertial_dict | (root, msg) | return inertial_dict, msg | Parameters
----------
root: adsk.fusion.Design.cast(product)
Root component
msg: str
Tell the status
Returns
----------
inertial_dict: {name:{mass, inertia, center_of_mass}}
msg: str
Tell the status | Parameters
----------
root: adsk.fusion.Design.cast(product)
Root component
msg: str
Tell the status
Returns
----------
inertial_dict: {name:{mass, inertia, center_of_mass}}
msg: str
Tell the status | [
"Parameters",
"----------",
"root",
":",
"adsk",
".",
"fusion",
".",
"Design",
".",
"cast",
"(",
"product",
")",
"Root",
"component",
"msg",
":",
"str",
"Tell",
"the",
"status",
"Returns",
"----------",
"inertial_dict",
":",
"{",
"name",
":",
"{",
"mass",
... | def make_inertial_dict(root, msg):
"""
Parameters
----------
root: adsk.fusion.Design.cast(product)
Root component
msg: str
Tell the status
Returns
----------
inertial_dict: {name:{mass, inertia, center_of_mass}}
msg: str
Tell the status
"""
# Get component properties.
allOccs = root.occurrences
inertial_dict = {}
for occs in allOccs:
# Skip the root component.
occs_dict = {}
prop = occs.getPhysicalProperties(adsk.fusion.CalculationAccuracy.VeryHighCalculationAccuracy)
occs_dict['name'] = re.sub('[ :()]', '_', occs.name)
mass = prop.mass # kg
occs_dict['mass'] = mass
center_of_mass = [_/100.0 for _ in prop.centerOfMass.asArray()] ## cm to m
occs_dict['center_of_mass'] = center_of_mass
# https://help.autodesk.com/view/fusion360/ENU/?guid=GUID-ce341ee6-4490-11e5-b25b-f8b156d7cd97
(_, xx, yy, zz, xy, yz, xz) = prop.getXYZMomentsOfInertia()
moment_inertia_world = [_ / 10000.0 for _ in [xx, yy, zz, xy, yz, xz] ] ## kg / cm^2 -> kg/m^2
occs_dict['inertia'] = utils.origin2center_of_mass(moment_inertia_world, center_of_mass, mass)
if occs.component.name == 'base_link':
inertial_dict['base_link'] = occs_dict
else:
inertial_dict[re.sub('[ :()]', '_', occs.name)] = occs_dict
return inertial_dict, msg | [
"def",
"make_inertial_dict",
"(",
"root",
",",
"msg",
")",
":",
"# Get component properties. ",
"allOccs",
"=",
"root",
".",
"occurrences",
"inertial_dict",
"=",
"{",
"}",
"for",
"occs",
"in",
"allOccs",
":",
"# Skip the root component.",
"occs_dict",
"=",
"{... | https://github.com/syuntoku14/fusion2urdf/blob/79af25950b4de8801602ca16192a6c836bab7063/URDF_Exporter/core/Link.py#L85-L127 | |
holoviz/param | c4a9e3252456ad368146140e1fc52cf6bba9f1f0 | numbergen/__init__.py | python | Hash.__getstate__ | (self) | return d | Avoid Hashlib.md5 TypeError in deepcopy (hashlib issue) | Avoid Hashlib.md5 TypeError in deepcopy (hashlib issue) | [
"Avoid",
"Hashlib",
".",
"md5",
"TypeError",
"in",
"deepcopy",
"(",
"hashlib",
"issue",
")"
] | def __getstate__(self):
"""
Avoid Hashlib.md5 TypeError in deepcopy (hashlib issue)
"""
d = self.__dict__.copy()
d.pop('_digest')
d.pop('_hash_struct')
return d | [
"def",
"__getstate__",
"(",
"self",
")",
":",
"d",
"=",
"self",
".",
"__dict__",
".",
"copy",
"(",
")",
"d",
".",
"pop",
"(",
"'_digest'",
")",
"d",
".",
"pop",
"(",
"'_hash_struct'",
")",
"return",
"d"
] | https://github.com/holoviz/param/blob/c4a9e3252456ad368146140e1fc52cf6bba9f1f0/numbergen/__init__.py#L242-L249 | |
DataDog/integrations-core | 934674b29d94b70ccc008f76ea172d0cdae05e1e | openstack/datadog_checks/openstack/openstack.py | python | OpenStackCheck.get_auth_token | (self, instance=None) | return self.get_scope_for_instance(instance).auth_token | [] | def get_auth_token(self, instance=None):
if not instance:
# Assume instance scope is populated on self
return self._current_scope.auth_token
return self.get_scope_for_instance(instance).auth_token | [
"def",
"get_auth_token",
"(",
"self",
",",
"instance",
"=",
"None",
")",
":",
"if",
"not",
"instance",
":",
"# Assume instance scope is populated on self",
"return",
"self",
".",
"_current_scope",
".",
"auth_token",
"return",
"self",
".",
"get_scope_for_instance",
"... | https://github.com/DataDog/integrations-core/blob/934674b29d94b70ccc008f76ea172d0cdae05e1e/openstack/datadog_checks/openstack/openstack.py#L664-L669 | |||
hubblestack/hubble | 763142474edcecdec5fd25591dc29c3536e8f969 | hubblestack/utils/aws.py | python | _sign | (key, msg) | return hmac.new(key, msg.encode('utf-8'), hashlib.sha256).digest() | Key derivation functions. See:
http://docs.aws.amazon.com/general/latest/gr/signature-v4-examples.html#signature-v4-examples-python | Key derivation functions. See: | [
"Key",
"derivation",
"functions",
".",
"See",
":"
] | def _sign(key, msg):
'''
Key derivation functions. See:
http://docs.aws.amazon.com/general/latest/gr/signature-v4-examples.html#signature-v4-examples-python
'''
return hmac.new(key, msg.encode('utf-8'), hashlib.sha256).digest() | [
"def",
"_sign",
"(",
"key",
",",
"msg",
")",
":",
"return",
"hmac",
".",
"new",
"(",
"key",
",",
"msg",
".",
"encode",
"(",
"'utf-8'",
")",
",",
"hashlib",
".",
"sha256",
")",
".",
"digest",
"(",
")"
] | https://github.com/hubblestack/hubble/blob/763142474edcecdec5fd25591dc29c3536e8f969/hubblestack/utils/aws.py#L54-L60 | |
IronLanguages/main | a949455434b1fda8c783289e897e78a9a0caabb5 | External.LCA_RESTRICTED/Languages/CPython/27/Lib/lib-tk/Tkinter.py | python | Tk.readprofile | (self, baseName, className) | Internal function. It reads BASENAME.tcl and CLASSNAME.tcl into
the Tcl Interpreter and calls execfile on BASENAME.py and CLASSNAME.py if
such a file exists in the home directory. | Internal function. It reads BASENAME.tcl and CLASSNAME.tcl into
the Tcl Interpreter and calls execfile on BASENAME.py and CLASSNAME.py if
such a file exists in the home directory. | [
"Internal",
"function",
".",
"It",
"reads",
"BASENAME",
".",
"tcl",
"and",
"CLASSNAME",
".",
"tcl",
"into",
"the",
"Tcl",
"Interpreter",
"and",
"calls",
"execfile",
"on",
"BASENAME",
".",
"py",
"and",
"CLASSNAME",
".",
"py",
"if",
"such",
"a",
"file",
"e... | def readprofile(self, baseName, className):
"""Internal function. It reads BASENAME.tcl and CLASSNAME.tcl into
the Tcl Interpreter and calls execfile on BASENAME.py and CLASSNAME.py if
such a file exists in the home directory."""
import os
if 'HOME' in os.environ: home = os.environ['HOME']
else: home = os.curdir
class_tcl = os.path.join(home, '.%s.tcl' % className)
class_py = os.path.join(home, '.%s.py' % className)
base_tcl = os.path.join(home, '.%s.tcl' % baseName)
base_py = os.path.join(home, '.%s.py' % baseName)
dir = {'self': self}
exec 'from Tkinter import *' in dir
if os.path.isfile(class_tcl):
self.tk.call('source', class_tcl)
if os.path.isfile(class_py):
execfile(class_py, dir)
if os.path.isfile(base_tcl):
self.tk.call('source', base_tcl)
if os.path.isfile(base_py):
execfile(base_py, dir) | [
"def",
"readprofile",
"(",
"self",
",",
"baseName",
",",
"className",
")",
":",
"import",
"os",
"if",
"'HOME'",
"in",
"os",
".",
"environ",
":",
"home",
"=",
"os",
".",
"environ",
"[",
"'HOME'",
"]",
"else",
":",
"home",
"=",
"os",
".",
"curdir",
"... | https://github.com/IronLanguages/main/blob/a949455434b1fda8c783289e897e78a9a0caabb5/External.LCA_RESTRICTED/Languages/CPython/27/Lib/lib-tk/Tkinter.py#L1733-L1753 | ||
scanlime/coastermelt | dd9a536a6928424a5f479fd9e6b5476e34763c06 | backdoor/png.py | python | mycallersname | () | return funname | Returns the name of the caller of the caller of this function
(hence the name of the caller of the function in which
"mycallersname()" textually appears). Returns None if this cannot
be determined. | Returns the name of the caller of the caller of this function
(hence the name of the caller of the function in which
"mycallersname()" textually appears). Returns None if this cannot
be determined. | [
"Returns",
"the",
"name",
"of",
"the",
"caller",
"of",
"the",
"caller",
"of",
"this",
"function",
"(",
"hence",
"the",
"name",
"of",
"the",
"caller",
"of",
"the",
"function",
"in",
"which",
"mycallersname",
"()",
"textually",
"appears",
")",
".",
"Returns"... | def mycallersname():
"""Returns the name of the caller of the caller of this function
(hence the name of the caller of the function in which
"mycallersname()" textually appears). Returns None if this cannot
be determined."""
# http://docs.python.org/library/inspect.html#the-interpreter-stack
import inspect
frame = inspect.currentframe()
if not frame:
return None
frame_,filename_,lineno_,funname,linelist_,listi_ = (
inspect.getouterframes(frame)[2])
return funname | [
"def",
"mycallersname",
"(",
")",
":",
"# http://docs.python.org/library/inspect.html#the-interpreter-stack",
"import",
"inspect",
"frame",
"=",
"inspect",
".",
"currentframe",
"(",
")",
"if",
"not",
"frame",
":",
"return",
"None",
"frame_",
",",
"filename_",
",",
"... | https://github.com/scanlime/coastermelt/blob/dd9a536a6928424a5f479fd9e6b5476e34763c06/backdoor/png.py#L2367-L2381 | |
mchristopher/PokemonGo-DesktopMap | ec37575f2776ee7d64456e2a1f6b6b78830b4fe0 | app/pywin/Lib/codeop.py | python | CommandCompiler.__call__ | (self, source, filename="<input>", symbol="single") | return _maybe_compile(self.compiler, source, filename, symbol) | r"""Compile a command and determine whether it is incomplete.
Arguments:
source -- the source string; may contain \n characters
filename -- optional filename from which source was read;
default "<input>"
symbol -- optional grammar start symbol; "single" (default) or
"eval"
Return value / exceptions raised:
- Return a code object if the command is complete and valid
- Return None if the command is incomplete
- Raise SyntaxError, ValueError or OverflowError if the command is a
syntax error (OverflowError and ValueError can be produced by
malformed literals). | r"""Compile a command and determine whether it is incomplete. | [
"r",
"Compile",
"a",
"command",
"and",
"determine",
"whether",
"it",
"is",
"incomplete",
"."
] | def __call__(self, source, filename="<input>", symbol="single"):
r"""Compile a command and determine whether it is incomplete.
Arguments:
source -- the source string; may contain \n characters
filename -- optional filename from which source was read;
default "<input>"
symbol -- optional grammar start symbol; "single" (default) or
"eval"
Return value / exceptions raised:
- Return a code object if the command is complete and valid
- Return None if the command is incomplete
- Raise SyntaxError, ValueError or OverflowError if the command is a
syntax error (OverflowError and ValueError can be produced by
malformed literals).
"""
return _maybe_compile(self.compiler, source, filename, symbol) | [
"def",
"__call__",
"(",
"self",
",",
"source",
",",
"filename",
"=",
"\"<input>\"",
",",
"symbol",
"=",
"\"single\"",
")",
":",
"return",
"_maybe_compile",
"(",
"self",
".",
"compiler",
",",
"source",
",",
"filename",
",",
"symbol",
")"
] | https://github.com/mchristopher/PokemonGo-DesktopMap/blob/ec37575f2776ee7d64456e2a1f6b6b78830b4fe0/app/pywin/Lib/codeop.py#L149-L168 | |
gem/oq-engine | 1bdb88f3914e390abcbd285600bfd39477aae47c | openquake/commonlib/util.py | python | closest_to_ref | (arrays, ref, cutoff=1E-12) | return [idx for dist, idx in pairs] | :param arrays: a sequence of arrays
:param ref: the reference array
:returns: a list of indices ordered by closeness
This function is used to extract the realization closest to the mean in
disaggregation. For instance, if there are 2 realizations with indices
0 and 1, the first hazard curve having values
>>> c0 = numpy.array([.99, .97, .5, .1])
and the second hazard curve having values
>>> c1 = numpy.array([.98, .96, .45, .09])
with weights 0.6 and 0.4 and mean
>>> mean = numpy.average([c0, c1], axis=0, weights=[0.6, 0.4])
then calling ``closest_to_ref`` will returns the indices 0 and 1
respectively:
>>> closest_to_ref([c0, c1], mean)
[0, 1]
This means that the realization 0 is the closest to the mean, as expected,
since it has a larger weight. You can check that it is indeed true by
computing the sum of the quadratic deviations:
>>> ((c0 - mean)**2).sum()
0.0004480000000000008
>>> ((c1 - mean)**2).sum()
0.0010079999999999985
If the 2 realizations have equal weights the distance from the mean will be
the same. In that case both the realizations will be okay; the one that
will be chosen by ``closest_to_ref`` depends on the magic of floating point
approximation (theoretically identical distances will likely be different
as numpy.float64 numbers) or on the magic of Python ``list.sort``. | :param arrays: a sequence of arrays
:param ref: the reference array
:returns: a list of indices ordered by closeness | [
":",
"param",
"arrays",
":",
"a",
"sequence",
"of",
"arrays",
":",
"param",
"ref",
":",
"the",
"reference",
"array",
":",
"returns",
":",
"a",
"list",
"of",
"indices",
"ordered",
"by",
"closeness"
] | def closest_to_ref(arrays, ref, cutoff=1E-12):
"""
:param arrays: a sequence of arrays
:param ref: the reference array
:returns: a list of indices ordered by closeness
This function is used to extract the realization closest to the mean in
disaggregation. For instance, if there are 2 realizations with indices
0 and 1, the first hazard curve having values
>>> c0 = numpy.array([.99, .97, .5, .1])
and the second hazard curve having values
>>> c1 = numpy.array([.98, .96, .45, .09])
with weights 0.6 and 0.4 and mean
>>> mean = numpy.average([c0, c1], axis=0, weights=[0.6, 0.4])
then calling ``closest_to_ref`` will returns the indices 0 and 1
respectively:
>>> closest_to_ref([c0, c1], mean)
[0, 1]
This means that the realization 0 is the closest to the mean, as expected,
since it has a larger weight. You can check that it is indeed true by
computing the sum of the quadratic deviations:
>>> ((c0 - mean)**2).sum()
0.0004480000000000008
>>> ((c1 - mean)**2).sum()
0.0010079999999999985
If the 2 realizations have equal weights the distance from the mean will be
the same. In that case both the realizations will be okay; the one that
will be chosen by ``closest_to_ref`` depends on the magic of floating point
approximation (theoretically identical distances will likely be different
as numpy.float64 numbers) or on the magic of Python ``list.sort``.
"""
dist = numpy.zeros(len(arrays))
logref = log(ref, cutoff)
pairs = []
for idx, array in enumerate(arrays):
diff = log(array, cutoff) - logref
dist = numpy.sqrt((diff * diff).sum())
pairs.append((dist, idx))
pairs.sort()
return [idx for dist, idx in pairs] | [
"def",
"closest_to_ref",
"(",
"arrays",
",",
"ref",
",",
"cutoff",
"=",
"1E-12",
")",
":",
"dist",
"=",
"numpy",
".",
"zeros",
"(",
"len",
"(",
"arrays",
")",
")",
"logref",
"=",
"log",
"(",
"ref",
",",
"cutoff",
")",
"pairs",
"=",
"[",
"]",
"for... | https://github.com/gem/oq-engine/blob/1bdb88f3914e390abcbd285600bfd39477aae47c/openquake/commonlib/util.py#L95-L144 | |
rnd-team-dev/plotoptix | d8c12fd18ceae4af0fc1a4644add9f5878239760 | plotoptix/npoptix.py | python | NpOptiX.load_normal_tilt | (self, name: str, file_name: str,
mapping: Union[TextureMapping, str] = TextureMapping.Flat,
addr_mode: Union[TextureAddressMode, str] = TextureAddressMode.Wrap,
prescale: float = 1.0,
baseline: float = 0.0,
refresh: bool = False) | Set normal tilt data.
Set shading normal tilt according to displacement map loaded from an image file. ``mapping``
determines how the normal tilt is calculated from the displacement data
(see :class:`plotoptix.enums.TextureMapping`). Tilt data is stored in the device memory only
(there is no host copy).
Parameters
----------
name : string
Material name.
file_name : string
Image file name with the displacement data.
mapping : TextureMapping or string, optional
Mapping mode (see :class:`plotoptix.enums.TextureMapping`).
addr_mode : TextureAddressMode or string, optional
Texture addressing mode on edge crossing.
prescale : float, optional
Scaling factor for displacement values.
baseline : float, optional
Baseline added to displacement values.
refresh : bool, optional
Set to ``True`` if the image should be re-computed. | Set normal tilt data. | [
"Set",
"normal",
"tilt",
"data",
"."
] | def load_normal_tilt(self, name: str, file_name: str,
mapping: Union[TextureMapping, str] = TextureMapping.Flat,
addr_mode: Union[TextureAddressMode, str] = TextureAddressMode.Wrap,
prescale: float = 1.0,
baseline: float = 0.0,
refresh: bool = False) -> None:
"""Set normal tilt data.
Set shading normal tilt according to displacement map loaded from an image file. ``mapping``
determines how the normal tilt is calculated from the displacement data
(see :class:`plotoptix.enums.TextureMapping`). Tilt data is stored in the device memory only
(there is no host copy).
Parameters
----------
name : string
Material name.
file_name : string
Image file name with the displacement data.
mapping : TextureMapping or string, optional
Mapping mode (see :class:`plotoptix.enums.TextureMapping`).
addr_mode : TextureAddressMode or string, optional
Texture addressing mode on edge crossing.
prescale : float, optional
Scaling factor for displacement values.
baseline : float, optional
Baseline added to displacement values.
refresh : bool, optional
Set to ``True`` if the image should be re-computed.
"""
if not isinstance(name, str): name = str(name)
if not isinstance(file_name, str): name = str(file_name)
if isinstance(mapping, str): mapping = TextureMapping[mapping]
if isinstance(addr_mode, str): addr_mode = TextureAddressMode[addr_mode]
self._logger.info("Set shading normal tilt map for %s using %s.", name, file_name)
if not self._optix.load_normal_tilt(name, file_name, mapping.value, addr_mode.value, prescale, baseline, refresh):
msg = "%s normal tilt map not uploaded." % name
self._logger.error(msg)
if self._raise_on_error: raise RuntimeError(msg) | [
"def",
"load_normal_tilt",
"(",
"self",
",",
"name",
":",
"str",
",",
"file_name",
":",
"str",
",",
"mapping",
":",
"Union",
"[",
"TextureMapping",
",",
"str",
"]",
"=",
"TextureMapping",
".",
"Flat",
",",
"addr_mode",
":",
"Union",
"[",
"TextureAddressMod... | https://github.com/rnd-team-dev/plotoptix/blob/d8c12fd18ceae4af0fc1a4644add9f5878239760/plotoptix/npoptix.py#L1381-L1422 | ||
llSourcell/tensorflow_demo | 613da5f137aa377e7251eea2e6338f80b1eaa51a | input_data.py | python | _read32 | (bytestream) | return numpy.frombuffer(bytestream.read(4), dtype=dt)[0] | [] | def _read32(bytestream):
dt = numpy.dtype(numpy.uint32).newbyteorder('>')
return numpy.frombuffer(bytestream.read(4), dtype=dt)[0] | [
"def",
"_read32",
"(",
"bytestream",
")",
":",
"dt",
"=",
"numpy",
".",
"dtype",
"(",
"numpy",
".",
"uint32",
")",
".",
"newbyteorder",
"(",
"'>'",
")",
"return",
"numpy",
".",
"frombuffer",
"(",
"bytestream",
".",
"read",
"(",
"4",
")",
",",
"dtype"... | https://github.com/llSourcell/tensorflow_demo/blob/613da5f137aa377e7251eea2e6338f80b1eaa51a/input_data.py#L23-L25 | |||
Terrance/SkPy | 055a24f2087a79552f5ffebc8b2da28951313015 | skpy/util.py | python | SkypeUtils.convertIds | (*types, **kwargs) | return wrapper | Class decorator: add helper methods to convert identifier properties into SkypeObjs.
Args:
types (str list): simple field types to add properties for (``user``, ``users`` or ``chat``)
user (str list): attribute names to treat as single user identifier fields
users (str list): attribute names to treat as user identifier lists
chat (str list): attribute names to treat as chat identifier fields
Returns:
method: decorator function, ready to apply to other methods | Class decorator: add helper methods to convert identifier properties into SkypeObjs. | [
"Class",
"decorator",
":",
"add",
"helper",
"methods",
"to",
"convert",
"identifier",
"properties",
"into",
"SkypeObjs",
"."
] | def convertIds(*types, **kwargs):
"""
Class decorator: add helper methods to convert identifier properties into SkypeObjs.
Args:
types (str list): simple field types to add properties for (``user``, ``users`` or ``chat``)
user (str list): attribute names to treat as single user identifier fields
users (str list): attribute names to treat as user identifier lists
chat (str list): attribute names to treat as chat identifier fields
Returns:
method: decorator function, ready to apply to other methods
"""
user = kwargs.get("user", ())
users = kwargs.get("users", ())
chat = kwargs.get("chat", ())
def userObj(self, field):
return self.skype.contacts[getattr(self, field)]
def userObjs(self, field):
return (self.skype.contacts[id] for id in getattr(self, field))
def chatObj(self, field):
return self.skype.chats[getattr(self, field)]
def attach(cls, fn, field, idField):
"""
Generate the property object and attach it to the class.
Args:
cls (type): class to attach the property to
fn (method): function to be attached
field (str): attribute name for the new property
idField (str): reference field to retrieve identifier from
"""
setattr(cls, field, property(functools.wraps(fn)(functools.partial(fn, field=idField))))
def wrapper(cls):
# Shorthand identifiers, e.g. @convertIds("user", "chat").
for type in types:
if type == "user":
attach(cls, userObj, "user", "userId")
elif type == "users":
attach(cls, userObjs, "users", "userIds")
elif type == "chat":
attach(cls, chatObj, "chat", "chatId")
# Custom field names, e.g. @convertIds(user=["creator"]).
for field in user:
attach(cls, userObj, field, "{0}Id".format(field))
for field in users:
attach(cls, userObjs, "{0}s".format(field), "{0}Ids".format(field))
for field in chat:
attach(cls, chatObj, field, "{0}Id".format(field))
return cls
return wrapper | [
"def",
"convertIds",
"(",
"*",
"types",
",",
"*",
"*",
"kwargs",
")",
":",
"user",
"=",
"kwargs",
".",
"get",
"(",
"\"user\"",
",",
"(",
")",
")",
"users",
"=",
"kwargs",
".",
"get",
"(",
"\"users\"",
",",
"(",
")",
")",
"chat",
"=",
"kwargs",
... | https://github.com/Terrance/SkPy/blob/055a24f2087a79552f5ffebc8b2da28951313015/skpy/util.py#L124-L180 | |
kanzure/nanoengineer | 874e4c9f8a9190f093625b267f9767e19f82e6c4 | cad/src/graphics/drawing/draw_grid_lines.py | python | displayLabelsAlongOriginLowerLeft | (h, w, hh, hw, uh, uw,
text_offset, text_color, font_size, glpane) | return | Display labels when origin is on the lower left corner.
@param h: height of the plane
@type h: float
@param w: width of the plane
@type w: float
@param hh: half the height of the plane
@type hh: float
@param hw: half the width of the plane
@type hw: float
@param uh: spacing along height of the plane
@type uh: float
@param uw: spacing along width of the plane
@type uw: float
@param text_offset: offset for label
@type text_offset: float
@param text_color: color of the text
@type: text_colot: tuple
@param font_size: size of the text font
@type: font_size: float
@param glpane: The 3D graphics area to draw it in.
@type glpane: L{GLPane} | Display labels when origin is on the lower left corner. | [
"Display",
"labels",
"when",
"origin",
"is",
"on",
"the",
"lower",
"left",
"corner",
"."
] | def displayLabelsAlongOriginLowerLeft(h, w, hh, hw, uh, uw,
text_offset, text_color, font_size, glpane):
"""
Display labels when origin is on the lower left corner.
@param h: height of the plane
@type h: float
@param w: width of the plane
@type w: float
@param hh: half the height of the plane
@type hh: float
@param hw: half the width of the plane
@type hw: float
@param uh: spacing along height of the plane
@type uh: float
@param uw: spacing along width of the plane
@type uw: float
@param text_offset: offset for label
@type text_offset: float
@param text_color: color of the text
@type: text_colot: tuple
@param font_size: size of the text font
@type: font_size: float
@param glpane: The 3D graphics area to draw it in.
@type glpane: L{GLPane}
"""
# Draw unit text labels for horizontal lines (nm)
y1 = 0
while y1 >= -h:
drawtext("%g" % (-y1 / 10.0), text_color,
V(-hw - 3 * text_offset, y1 + hh, 0.0), font_size, glpane)
y1 -= uh
# Draw unit text labels for vertical lines (nm).
x1 = 0
while x1 <= w:
drawtext("%g" % (x1 / 10.0), text_color,
V(x1 - hw, hh + 2 * text_offset, 0.0), font_size, glpane)
x1 += uw
return | [
"def",
"displayLabelsAlongOriginLowerLeft",
"(",
"h",
",",
"w",
",",
"hh",
",",
"hw",
",",
"uh",
",",
"uw",
",",
"text_offset",
",",
"text_color",
",",
"font_size",
",",
"glpane",
")",
":",
"# Draw unit text labels for horizontal lines (nm)",
"y1",
"=",
"0",
"... | https://github.com/kanzure/nanoengineer/blob/874e4c9f8a9190f093625b267f9767e19f82e6c4/cad/src/graphics/drawing/draw_grid_lines.py#L455-L495 | |
chribsen/simple-machine-learning-examples | dc94e52a4cebdc8bb959ff88b81ff8cfeca25022 | venv/lib/python2.7/site-packages/pip/_vendor/pyparsing.py | python | ungroup | (expr) | return TokenConverter(expr).setParseAction(lambda t:t[0]) | Helper to undo pyparsing's default grouping of And expressions, even
if all but one are non-empty. | Helper to undo pyparsing's default grouping of And expressions, even
if all but one are non-empty. | [
"Helper",
"to",
"undo",
"pyparsing",
"s",
"default",
"grouping",
"of",
"And",
"expressions",
"even",
"if",
"all",
"but",
"one",
"are",
"non",
"-",
"empty",
"."
] | def ungroup(expr):
"""
Helper to undo pyparsing's default grouping of And expressions, even
if all but one are non-empty.
"""
return TokenConverter(expr).setParseAction(lambda t:t[0]) | [
"def",
"ungroup",
"(",
"expr",
")",
":",
"return",
"TokenConverter",
"(",
"expr",
")",
".",
"setParseAction",
"(",
"lambda",
"t",
":",
"t",
"[",
"0",
"]",
")"
] | https://github.com/chribsen/simple-machine-learning-examples/blob/dc94e52a4cebdc8bb959ff88b81ff8cfeca25022/venv/lib/python2.7/site-packages/pip/_vendor/pyparsing.py#L4677-L4682 | |
postgres/pgadmin4 | 374c5e952fa594d749fadf1f88076c1cba8c5f64 | web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/foreign_key/__init__.py | python | ForeignKeyConstraintView.node | (self, gid, sid, did, scid, tid, fkid=None) | return make_json_response(
data=res,
status=200
) | This function returns all foreign key nodes as a
http response.
Args:
gid: Server Group ID
sid: Server ID
did: Database ID
scid: Schema ID
tid: Table ID
fkid: Foreign key constraint ID
Returns: | This function returns all foreign key nodes as a
http response. | [
"This",
"function",
"returns",
"all",
"foreign",
"key",
"nodes",
"as",
"a",
"http",
"response",
"."
] | def node(self, gid, sid, did, scid, tid, fkid=None):
"""
This function returns all foreign key nodes as a
http response.
Args:
gid: Server Group ID
sid: Server ID
did: Database ID
scid: Schema ID
tid: Table ID
fkid: Foreign key constraint ID
Returns:
"""
SQL = render_template(
"/".join([self.template_path, self._NODES_SQL]), tid=tid
)
status, rset = self.conn.execute_2darray(SQL)
if len(rset['rows']) == 0:
return gone(gettext(FOREIGN_KEY_NOT_FOUND))
if rset['rows'][0]["convalidated"]:
icon = "icon-foreign_key_no_validate"
valid = False
else:
icon = "icon-foreign_key"
valid = True
res = self.blueprint.generate_browser_node(
rset['rows'][0]['oid'],
tid,
rset['rows'][0]['name'],
icon=icon,
valid=valid
)
return make_json_response(
data=res,
status=200
) | [
"def",
"node",
"(",
"self",
",",
"gid",
",",
"sid",
",",
"did",
",",
"scid",
",",
"tid",
",",
"fkid",
"=",
"None",
")",
":",
"SQL",
"=",
"render_template",
"(",
"\"/\"",
".",
"join",
"(",
"[",
"self",
".",
"template_path",
",",
"self",
".",
"_NOD... | https://github.com/postgres/pgadmin4/blob/374c5e952fa594d749fadf1f88076c1cba8c5f64/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/foreign_key/__init__.py#L370-L412 | |
canonical/cloud-init | dc1aabfca851e520693c05322f724bd102c76364 | cloudinit/cmd/query.py | python | get_parser | (parser=None) | return parser | Build or extend an arg parser for query utility.
@param parser: Optional existing ArgumentParser instance representing the
query subcommand which will be extended to support the args of
this utility.
@returns: ArgumentParser with proper argument configuration. | Build or extend an arg parser for query utility. | [
"Build",
"or",
"extend",
"an",
"arg",
"parser",
"for",
"query",
"utility",
"."
] | def get_parser(parser=None):
"""Build or extend an arg parser for query utility.
@param parser: Optional existing ArgumentParser instance representing the
query subcommand which will be extended to support the args of
this utility.
@returns: ArgumentParser with proper argument configuration.
"""
if not parser:
parser = argparse.ArgumentParser(prog=NAME, description=__doc__)
parser.add_argument(
"-d",
"--debug",
action="store_true",
default=False,
help="Add verbose messages during template render",
)
parser.add_argument(
"-i",
"--instance-data",
type=str,
help="Path to instance-data.json file. Default is /run/cloud-init/%s"
% INSTANCE_JSON_FILE,
)
parser.add_argument(
"-l",
"--list-keys",
action="store_true",
default=False,
help=(
"List query keys available at the provided instance-data"
" <varname>."
),
)
parser.add_argument(
"-u",
"--user-data",
type=str,
help=(
"Path to user-data file. Default is"
" /var/lib/cloud/instance/user-data.txt"
),
)
parser.add_argument(
"-v",
"--vendor-data",
type=str,
help=(
"Path to vendor-data file. Default is"
" /var/lib/cloud/instance/vendor-data.txt"
),
)
parser.add_argument(
"varname",
type=str,
nargs="?",
help=(
"A dot-delimited specific variable to query from"
" instance-data. For example: v1.local_hostname. If the"
" value is not JSON serializable, it will be base64-encoded and"
' will contain the prefix "ci-b64:". '
),
)
parser.add_argument(
"-a",
"--all",
action="store_true",
default=False,
dest="dump_all",
help="Dump all available instance-data",
)
parser.add_argument(
"-f",
"--format",
type=str,
dest="format",
help=(
"Optionally specify a custom output format string. Any"
" instance-data variable can be specified between double-curly"
' braces. For example -f "{{ v2.cloud_name }}"'
),
)
return parser | [
"def",
"get_parser",
"(",
"parser",
"=",
"None",
")",
":",
"if",
"not",
"parser",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"prog",
"=",
"NAME",
",",
"description",
"=",
"__doc__",
")",
"parser",
".",
"add_argument",
"(",
"\"-d\"",
",",... | https://github.com/canonical/cloud-init/blob/dc1aabfca851e520693c05322f724bd102c76364/cloudinit/cmd/query.py#L38-L121 | |
zhanghan1990/zipline-chinese | 86904cac4b6e928271f640910aa83675ce945b8b | zipline/finance/performance/position.py | python | Position.to_dict | (self) | return {
'sid': self.sid,
'amount': self.amount,
'cost_basis': self.cost_basis,
'last_sale_price': self.last_sale_price
} | Creates a dictionary representing the state of this position.
Returns a dict object of the form: | Creates a dictionary representing the state of this position.
Returns a dict object of the form: | [
"Creates",
"a",
"dictionary",
"representing",
"the",
"state",
"of",
"this",
"position",
".",
"Returns",
"a",
"dict",
"object",
"of",
"the",
"form",
":"
] | def to_dict(self):
"""
Creates a dictionary representing the state of this position.
Returns a dict object of the form:
"""
return {
'sid': self.sid,
'amount': self.amount,
'cost_basis': self.cost_basis,
'last_sale_price': self.last_sale_price
} | [
"def",
"to_dict",
"(",
"self",
")",
":",
"return",
"{",
"'sid'",
":",
"self",
".",
"sid",
",",
"'amount'",
":",
"self",
".",
"amount",
",",
"'cost_basis'",
":",
"self",
".",
"cost_basis",
",",
"'last_sale_price'",
":",
"self",
".",
"last_sale_price",
"}"... | https://github.com/zhanghan1990/zipline-chinese/blob/86904cac4b6e928271f640910aa83675ce945b8b/zipline/finance/performance/position.py#L201-L211 | |
wzpan/dingdang-robot | 66d95402232a9102e223a2d8ccefcb83500d2c6a | client/plugins/CleanCache.py | python | isValid | (text) | return any(word in text.lower() for word in ["清除缓存", u"清空缓存", u"清缓存"]) | Returns True if input is related to the time.
Arguments:
text -- user-input, typically transcribed speech | Returns True if input is related to the time. | [
"Returns",
"True",
"if",
"input",
"is",
"related",
"to",
"the",
"time",
"."
] | def isValid(text):
"""
Returns True if input is related to the time.
Arguments:
text -- user-input, typically transcribed speech
"""
return any(word in text.lower() for word in ["清除缓存", u"清空缓存", u"清缓存"]) | [
"def",
"isValid",
"(",
"text",
")",
":",
"return",
"any",
"(",
"word",
"in",
"text",
".",
"lower",
"(",
")",
"for",
"word",
"in",
"[",
"\"清除缓存\", u\"清空缓存",
"\"",
" u\"清缓存\"])",
"",
"",
"",
""
] | https://github.com/wzpan/dingdang-robot/blob/66d95402232a9102e223a2d8ccefcb83500d2c6a/client/plugins/CleanCache.py#L28-L35 | |
AppScale/gts | 46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9 | AppDB/appscale/datastore/scripts/ua_server.py | python | is_connection_error | (err) | return isinstance(err, psycopg2.InterfaceError) | This function is used as retry criteria.
Args:
err: an instance of Exception.
Returns:
True if error is related to connection, False otherwise. | This function is used as retry criteria. | [
"This",
"function",
"is",
"used",
"as",
"retry",
"criteria",
"."
] | def is_connection_error(err):
""" This function is used as retry criteria.
Args:
err: an instance of Exception.
Returns:
True if error is related to connection, False otherwise.
"""
return isinstance(err, psycopg2.InterfaceError) | [
"def",
"is_connection_error",
"(",
"err",
")",
":",
"return",
"isinstance",
"(",
"err",
",",
"psycopg2",
".",
"InterfaceError",
")"
] | https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppDB/appscale/datastore/scripts/ua_server.py#L65-L73 | |
tensorflow/tensor2tensor | 2a33b152d7835af66a6d20afe7961751047e28dd | tensor2tensor/rl/envs/tf_atari_wrappers.py | python | WrapperBase.history_observations | (self) | return self._transform_history_observations(
self._batch_env.history_observations
) | Returns observations from the root simulated env's history_buffer.
Transforms them with a wrapper-specific function if necessary.
Raises:
AttributeError: if root env doesn't have a history_buffer (i.e. is not
simulated). | Returns observations from the root simulated env's history_buffer. | [
"Returns",
"observations",
"from",
"the",
"root",
"simulated",
"env",
"s",
"history_buffer",
"."
] | def history_observations(self):
"""Returns observations from the root simulated env's history_buffer.
Transforms them with a wrapper-specific function if necessary.
Raises:
AttributeError: if root env doesn't have a history_buffer (i.e. is not
simulated).
"""
return self._transform_history_observations(
self._batch_env.history_observations
) | [
"def",
"history_observations",
"(",
"self",
")",
":",
"return",
"self",
".",
"_transform_history_observations",
"(",
"self",
".",
"_batch_env",
".",
"history_observations",
")"
] | https://github.com/tensorflow/tensor2tensor/blob/2a33b152d7835af66a6d20afe7961751047e28dd/tensor2tensor/rl/envs/tf_atari_wrappers.py#L77-L88 | |
midgetspy/Sick-Beard | 171a607e41b7347a74cc815f6ecce7968d9acccf | cherrypy/lib/caching.py | python | MemoryCache.put | (self, variant, size) | Store the current variant in the cache. | Store the current variant in the cache. | [
"Store",
"the",
"current",
"variant",
"in",
"the",
"cache",
"."
] | def put(self, variant, size):
"""Store the current variant in the cache."""
request = cherrypy.serving.request
response = cherrypy.serving.response
uri = cherrypy.url(qs=request.query_string)
uricache = self.store.get(uri)
if uricache is None:
uricache = AntiStampedeCache()
uricache.selecting_headers = [
e.value for e in response.headers.elements('Vary')]
self.store[uri] = uricache
if len(self.store) < self.maxobjects:
total_size = self.cursize + size
# checks if there's space for the object
if (size < self.maxobj_size and total_size < self.maxsize):
# add to the expirations list
expiration_time = response.time + self.delay
bucket = self.expirations.setdefault(expiration_time, [])
bucket.append((size, uri, uricache.selecting_headers))
# add to the cache
header_values = [request.headers.get(h, '')
for h in uricache.selecting_headers]
header_values.sort()
uricache[tuple(header_values)] = variant
self.tot_puts += 1
self.cursize = total_size | [
"def",
"put",
"(",
"self",
",",
"variant",
",",
"size",
")",
":",
"request",
"=",
"cherrypy",
".",
"serving",
".",
"request",
"response",
"=",
"cherrypy",
".",
"serving",
".",
"response",
"uri",
"=",
"cherrypy",
".",
"url",
"(",
"qs",
"=",
"request",
... | https://github.com/midgetspy/Sick-Beard/blob/171a607e41b7347a74cc815f6ecce7968d9acccf/cherrypy/lib/caching.py#L177-L206 | ||
mozilla/mozillians | bd5da47fef01e4e09d3bb8cb0799735bdfbeb3f9 | mozillians/users/models.py | python | UserProfilePrivacyModel.privacy_fields | (cls) | return cls.CACHED_PRIVACY_FIELDS | Return a dictionary whose keys are the names of the fields in this
model that are privacy-controlled, and whose values are the default
values to use for those fields when the user is not privileged to
view their actual value.
Note: should be only used through UserProfile . We should
fix this. | Return a dictionary whose keys are the names of the fields in this
model that are privacy-controlled, and whose values are the default
values to use for those fields when the user is not privileged to
view their actual value. | [
"Return",
"a",
"dictionary",
"whose",
"keys",
"are",
"the",
"names",
"of",
"the",
"fields",
"in",
"this",
"model",
"that",
"are",
"privacy",
"-",
"controlled",
"and",
"whose",
"values",
"are",
"the",
"default",
"values",
"to",
"use",
"for",
"those",
"field... | def privacy_fields(cls):
"""
Return a dictionary whose keys are the names of the fields in this
model that are privacy-controlled, and whose values are the default
values to use for those fields when the user is not privileged to
view their actual value.
Note: should be only used through UserProfile . We should
fix this.
"""
# Cache on the class object
if cls.CACHED_PRIVACY_FIELDS is None:
privacy_fields = {}
field_names = list(set(chain.from_iterable(
(field.name, field.attname) if hasattr(field, 'attname') else
(field.name,) for field in cls._meta.get_fields()
if not (field.many_to_one and field.related_model is None)
)))
for name in field_names:
if name.startswith('privacy_') or not 'privacy_%s' % name in field_names:
# skip privacy fields and uncontrolled fields
continue
field = cls._meta.get_field(name)
# Okay, this is a field that is privacy-controlled
# Figure out a good default value for it (to show to users
# who aren't privileged to see the actual value)
if isinstance(field, ManyToManyField):
default = field.remote_field.model.objects.none()
else:
default = field.get_default()
privacy_fields[name] = default
# HACK: There's not really an email field on UserProfile,
# but it's faked with a property
privacy_fields['email'] = u''
cls.CACHED_PRIVACY_FIELDS = privacy_fields
return cls.CACHED_PRIVACY_FIELDS | [
"def",
"privacy_fields",
"(",
"cls",
")",
":",
"# Cache on the class object",
"if",
"cls",
".",
"CACHED_PRIVACY_FIELDS",
"is",
"None",
":",
"privacy_fields",
"=",
"{",
"}",
"field_names",
"=",
"list",
"(",
"set",
"(",
"chain",
".",
"from_iterable",
"(",
"(",
... | https://github.com/mozilla/mozillians/blob/bd5da47fef01e4e09d3bb8cb0799735bdfbeb3f9/mozillians/users/models.py#L102-L139 | |
apple/ccs-calendarserver | 13c706b985fb728b9aab42dc0fef85aae21921c3 | txdav/common/datastore/sql_sharing.py | python | SharingMixIn._bindForNameAndHomeID | (cls) | return cls._bindFor((bind.RESOURCE_NAME == Parameter("name"))
.And(bind.HOME_RESOURCE_ID == Parameter("homeID"))) | DAL query that looks up any bind rows by home child
resource ID and home resource ID. | DAL query that looks up any bind rows by home child
resource ID and home resource ID. | [
"DAL",
"query",
"that",
"looks",
"up",
"any",
"bind",
"rows",
"by",
"home",
"child",
"resource",
"ID",
"and",
"home",
"resource",
"ID",
"."
] | def _bindForNameAndHomeID(cls):
"""
DAL query that looks up any bind rows by home child
resource ID and home resource ID.
"""
bind = cls._bindSchema
return cls._bindFor((bind.RESOURCE_NAME == Parameter("name"))
.And(bind.HOME_RESOURCE_ID == Parameter("homeID"))) | [
"def",
"_bindForNameAndHomeID",
"(",
"cls",
")",
":",
"bind",
"=",
"cls",
".",
"_bindSchema",
"return",
"cls",
".",
"_bindFor",
"(",
"(",
"bind",
".",
"RESOURCE_NAME",
"==",
"Parameter",
"(",
"\"name\"",
")",
")",
".",
"And",
"(",
"bind",
".",
"HOME_RESO... | https://github.com/apple/ccs-calendarserver/blob/13c706b985fb728b9aab42dc0fef85aae21921c3/txdav/common/datastore/sql_sharing.py#L380-L387 | |
kennethreitz-archive/requests3 | 69eb662703b40db58fdc6c095d0fe130c56649bb | requests3/core/_http/_sync/connectionpool.py | python | ConnectionPool.__enter__ | (self) | return self | [] | def __enter__(self):
return self | [
"def",
"__enter__",
"(",
"self",
")",
":",
"return",
"self"
] | https://github.com/kennethreitz-archive/requests3/blob/69eb662703b40db58fdc6c095d0fe130c56649bb/requests3/core/_http/_sync/connectionpool.py#L120-L121 | |||
AppScale/gts | 46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9 | AppDB/appscale/datastore/fdb/codecs.py | python | Path.flatten | (path, allow_partial=False) | return tuple(item for element in element_list
for item in Path.encode_element(element, allow_partial)) | Converts a key path protobuf object to a tuple. | Converts a key path protobuf object to a tuple. | [
"Converts",
"a",
"key",
"path",
"protobuf",
"object",
"to",
"a",
"tuple",
"."
] | def flatten(path, allow_partial=False):
""" Converts a key path protobuf object to a tuple. """
if isinstance(path, entity_pb.PropertyValue):
element_list = path.referencevalue().pathelement_list()
elif isinstance(path, entity_pb.PropertyValue_ReferenceValue):
element_list = path.pathelement_list()
else:
element_list = path.element_list()
return tuple(item for element in element_list
for item in Path.encode_element(element, allow_partial)) | [
"def",
"flatten",
"(",
"path",
",",
"allow_partial",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"path",
",",
"entity_pb",
".",
"PropertyValue",
")",
":",
"element_list",
"=",
"path",
".",
"referencevalue",
"(",
")",
".",
"pathelement_list",
"(",
")",... | https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppDB/appscale/datastore/fdb/codecs.py#L391-L401 | |
OpenEndedGroup/Field | 4f7c8edfb01bb0ccc927b78d3c500f018a4ae37c | Contents/lib/python/SocketServer.py | python | ThreadingMixIn.process_request_thread | (self, request, client_address) | Same as in BaseServer but as a thread.
In addition, exception handling is done here. | Same as in BaseServer but as a thread. | [
"Same",
"as",
"in",
"BaseServer",
"but",
"as",
"a",
"thread",
"."
] | def process_request_thread(self, request, client_address):
"""Same as in BaseServer but as a thread.
In addition, exception handling is done here.
"""
try:
self.finish_request(request, client_address)
self.close_request(request)
except:
self.handle_error(request, client_address)
self.close_request(request) | [
"def",
"process_request_thread",
"(",
"self",
",",
"request",
",",
"client_address",
")",
":",
"try",
":",
"self",
".",
"finish_request",
"(",
"request",
",",
"client_address",
")",
"self",
".",
"close_request",
"(",
"request",
")",
"except",
":",
"self",
".... | https://github.com/OpenEndedGroup/Field/blob/4f7c8edfb01bb0ccc927b78d3c500f018a4ae37c/Contents/lib/python/SocketServer.py#L460-L471 | ||
inspurer/WorkAttendanceSystem | 1221e2d67bdf5bb15fe99517cc3ded58ccb066df | V2.0/venv/Lib/site-packages/pip-9.0.1-py3.5.egg/pip/vcs/bazaar.py | python | Bazaar.check_version | (self, dest, rev_options) | return False | Always assume the versions don't match | Always assume the versions don't match | [
"Always",
"assume",
"the",
"versions",
"don",
"t",
"match"
] | def check_version(self, dest, rev_options):
"""Always assume the versions don't match"""
return False | [
"def",
"check_version",
"(",
"self",
",",
"dest",
",",
"rev_options",
")",
":",
"return",
"False"
] | https://github.com/inspurer/WorkAttendanceSystem/blob/1221e2d67bdf5bb15fe99517cc3ded58ccb066df/V2.0/venv/Lib/site-packages/pip-9.0.1-py3.5.egg/pip/vcs/bazaar.py#L111-L113 | |
TengXiaoDai/DistributedCrawling | f5c2439e6ce68dd9b49bde084d76473ff9ed4963 | Lib/site-packages/pyparsing.py | python | ParserElement.parseWithTabs | ( self ) | return self | Overrides default behavior to expand C{<TAB>}s to spaces before parsing the input string.
Must be called before C{parseString} when the input grammar contains elements that
match C{<TAB>} characters. | Overrides default behavior to expand C{<TAB>}s to spaces before parsing the input string.
Must be called before C{parseString} when the input grammar contains elements that
match C{<TAB>} characters. | [
"Overrides",
"default",
"behavior",
"to",
"expand",
"C",
"{",
"<TAB",
">",
"}",
"s",
"to",
"spaces",
"before",
"parsing",
"the",
"input",
"string",
".",
"Must",
"be",
"called",
"before",
"C",
"{",
"parseString",
"}",
"when",
"the",
"input",
"grammar",
"c... | def parseWithTabs( self ):
"""
Overrides default behavior to expand C{<TAB>}s to spaces before parsing the input string.
Must be called before C{parseString} when the input grammar contains elements that
match C{<TAB>} characters.
"""
self.keepTabs = True
return self | [
"def",
"parseWithTabs",
"(",
"self",
")",
":",
"self",
".",
"keepTabs",
"=",
"True",
"return",
"self"
] | https://github.com/TengXiaoDai/DistributedCrawling/blob/f5c2439e6ce68dd9b49bde084d76473ff9ed4963/Lib/site-packages/pyparsing.py#L2048-L2055 | |
quantmind/pulsar | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | pulsar/apps/wsgi/wrappers.py | python | WsgiRequest.cache | (self) | return self.environ[PULSAR_CACHE] | The protocol consumer used as a cache for
pulsar-specific data. Stored in the :attr:`environ` at
the wsgi-extension key ``pulsar.cache`` | The protocol consumer used as a cache for
pulsar-specific data. Stored in the :attr:`environ` at
the wsgi-extension key ``pulsar.cache`` | [
"The",
"protocol",
"consumer",
"used",
"as",
"a",
"cache",
"for",
"pulsar",
"-",
"specific",
"data",
".",
"Stored",
"in",
"the",
":",
"attr",
":",
"environ",
"at",
"the",
"wsgi",
"-",
"extension",
"key",
"pulsar",
".",
"cache"
] | def cache(self):
"""The protocol consumer used as a cache for
pulsar-specific data. Stored in the :attr:`environ` at
the wsgi-extension key ``pulsar.cache``
"""
return self.environ[PULSAR_CACHE] | [
"def",
"cache",
"(",
"self",
")",
":",
"return",
"self",
".",
"environ",
"[",
"PULSAR_CACHE",
"]"
] | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/wrappers.py#L101-L106 | |
makehumancommunity/makehuman | 8006cf2cc851624619485658bb933a4244bbfd7c | makehuman/plugins/1_mhapi/_skeleton.py | python | Skeleton.clearPoseAndExpression | (self) | Put skeleton back into rest pose | Put skeleton back into rest pose | [
"Put",
"skeleton",
"back",
"into",
"rest",
"pose"
] | def clearPoseAndExpression(self):
"""Put skeleton back into rest pose"""
human.resetToRestPose()
human.removeAnimations() | [
"def",
"clearPoseAndExpression",
"(",
"self",
")",
":",
"human",
".",
"resetToRestPose",
"(",
")",
"human",
".",
"removeAnimations",
"(",
")"
] | https://github.com/makehumancommunity/makehuman/blob/8006cf2cc851624619485658bb933a4244bbfd7c/makehuman/plugins/1_mhapi/_skeleton.py#L51-L54 | ||
ghoseb/planet.clojure | a2e10e9e6bbf6bc544fad40beed8d0da7ab9518d | planet/vendor/compat_logging/__init__.py | python | LogRecord.__init__ | (self, name, level, pathname, lineno, msg, args, exc_info) | Initialize a logging record with interesting information. | Initialize a logging record with interesting information. | [
"Initialize",
"a",
"logging",
"record",
"with",
"interesting",
"information",
"."
] | def __init__(self, name, level, pathname, lineno, msg, args, exc_info):
"""
Initialize a logging record with interesting information.
"""
ct = time.time()
self.name = name
self.msg = msg
self.args = args
self.levelname = getLevelName(level)
self.levelno = level
self.pathname = pathname
try:
self.filename = os.path.basename(pathname)
self.module = os.path.splitext(self.filename)[0]
except:
self.filename = pathname
self.module = "Unknown module"
self.exc_info = exc_info
self.lineno = lineno
self.created = ct
self.msecs = (ct - long(ct)) * 1000
self.relativeCreated = (self.created - _startTime) * 1000
if thread:
self.thread = thread.get_ident()
else:
self.thread = None
if hasattr(os, 'getpid'):
self.process = os.getpid()
else:
self.process = None | [
"def",
"__init__",
"(",
"self",
",",
"name",
",",
"level",
",",
"pathname",
",",
"lineno",
",",
"msg",
",",
"args",
",",
"exc_info",
")",
":",
"ct",
"=",
"time",
".",
"time",
"(",
")",
"self",
".",
"name",
"=",
"name",
"self",
".",
"msg",
"=",
... | https://github.com/ghoseb/planet.clojure/blob/a2e10e9e6bbf6bc544fad40beed8d0da7ab9518d/planet/vendor/compat_logging/__init__.py#L183-L212 | ||
amzn/xfer | dd4a6a27ca00406df83eec5916d3a76a1a798248 | xfer-ml/xfer/neural_network_repurposer.py | python | NeuralNetworkRepurposer.predict_probability | (self, test_iterator: mx.io.DataIter) | return predictions.asnumpy() | Perform predictions on test data using the target_model (repurposed neural network).
:param test_iterator: Test data iterator to return predictions for
:type test_iterator: :class:`mxnet.io.DataIter`
:return: Predicted probabilities
:rtype: :class:`numpy.ndarray` | Perform predictions on test data using the target_model (repurposed neural network). | [
"Perform",
"predictions",
"on",
"test",
"data",
"using",
"the",
"target_model",
"(",
"repurposed",
"neural",
"network",
")",
"."
] | def predict_probability(self, test_iterator: mx.io.DataIter):
"""
Perform predictions on test data using the target_model (repurposed neural network).
:param test_iterator: Test data iterator to return predictions for
:type test_iterator: :class:`mxnet.io.DataIter`
:return: Predicted probabilities
:rtype: :class:`numpy.ndarray`
"""
# Validate the predict call
self._validate_before_predict()
# Bind target model symbol with data if not already bound
if not self.target_model.binded:
self.target_model.bind(data_shapes=test_iterator.provide_data, for_training=False)
# Call mxnet.BaseModule.predict. It handles batch padding and resets iterator before prediction.
predictions = self.target_model.predict(eval_data=test_iterator)
return predictions.asnumpy() | [
"def",
"predict_probability",
"(",
"self",
",",
"test_iterator",
":",
"mx",
".",
"io",
".",
"DataIter",
")",
":",
"# Validate the predict call",
"self",
".",
"_validate_before_predict",
"(",
")",
"# Bind target model symbol with data if not already bound",
"if",
"not",
... | https://github.com/amzn/xfer/blob/dd4a6a27ca00406df83eec5916d3a76a1a798248/xfer-ml/xfer/neural_network_repurposer.py#L117-L136 | |
oilshell/oil | 94388e7d44a9ad879b12615f6203b38596b5a2d3 | Python-2.7.13/Lib/socket.py | python | _socketobject.makefile | (self, mode='r', bufsize=-1) | return _fileobject(self._sock, mode, bufsize) | makefile([mode[, bufsize]]) -> file object
Return a regular file object corresponding to the socket. The mode
and bufsize arguments are as for the built-in open() function. | makefile([mode[, bufsize]]) -> file object | [
"makefile",
"(",
"[",
"mode",
"[",
"bufsize",
"]]",
")",
"-",
">",
"file",
"object"
] | def makefile(self, mode='r', bufsize=-1):
"""makefile([mode[, bufsize]]) -> file object
Return a regular file object corresponding to the socket. The mode
and bufsize arguments are as for the built-in open() function."""
return _fileobject(self._sock, mode, bufsize) | [
"def",
"makefile",
"(",
"self",
",",
"mode",
"=",
"'r'",
",",
"bufsize",
"=",
"-",
"1",
")",
":",
"return",
"_fileobject",
"(",
"self",
".",
"_sock",
",",
"mode",
",",
"bufsize",
")"
] | https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/Python-2.7.13/Lib/socket.py#L216-L221 | |
Dentosal/python-sc2 | e816cce83772d1aee1291b86b300b69405aa96b4 | sc2/unit.py | python | PassengerUnit.can_attack | (self) | return bool(self._weapons) | Can attack at all | Can attack at all | [
"Can",
"attack",
"at",
"all"
] | def can_attack(self) -> bool:
""" Can attack at all"""
return bool(self._weapons) | [
"def",
"can_attack",
"(",
"self",
")",
"->",
"bool",
":",
"return",
"bool",
"(",
"self",
".",
"_weapons",
")"
] | https://github.com/Dentosal/python-sc2/blob/e816cce83772d1aee1291b86b300b69405aa96b4/sc2/unit.py#L94-L96 | |
mit-han-lab/once-for-all | 4f6fce3652ee4553ea811d38f32f90ac8b1bc378 | ofa/imagenet_classification/run_manager/run_manager.py | python | RunManager.__init__ | (self, path, net, run_config, init=True, measure_latency=None, no_gpu=False) | [] | def __init__(self, path, net, run_config, init=True, measure_latency=None, no_gpu=False):
self.path = path
self.net = net
self.run_config = run_config
self.best_acc = 0
self.start_epoch = 0
os.makedirs(self.path, exist_ok=True)
# move network to GPU if available
if torch.cuda.is_available() and (not no_gpu):
self.device = torch.device('cuda:0')
self.net = self.net.to(self.device)
cudnn.benchmark = True
else:
self.device = torch.device('cpu')
# initialize model (default)
if init:
init_models(run_config.model_init)
# net info
net_info = get_net_info(self.net, self.run_config.data_provider.data_shape, measure_latency, True)
with open('%s/net_info.txt' % self.path, 'w') as fout:
fout.write(json.dumps(net_info, indent=4) + '\n')
# noinspection PyBroadException
try:
fout.write(self.network.module_str + '\n')
except Exception:
pass
fout.write('%s\n' % self.run_config.data_provider.train.dataset.transform)
fout.write('%s\n' % self.run_config.data_provider.test.dataset.transform)
fout.write('%s\n' % self.network)
# criterion
if isinstance(self.run_config.mixup_alpha, float):
self.train_criterion = cross_entropy_loss_with_soft_target
elif self.run_config.label_smoothing > 0:
self.train_criterion = \
lambda pred, target: cross_entropy_with_label_smoothing(pred, target, self.run_config.label_smoothing)
else:
self.train_criterion = nn.CrossEntropyLoss()
self.test_criterion = nn.CrossEntropyLoss()
# optimizer
if self.run_config.no_decay_keys:
keys = self.run_config.no_decay_keys.split('#')
net_params = [
self.network.get_parameters(keys, mode='exclude'), # parameters with weight decay
self.network.get_parameters(keys, mode='include'), # parameters without weight decay
]
else:
# noinspection PyBroadException
try:
net_params = self.network.weight_parameters()
except Exception:
net_params = []
for param in self.network.parameters():
if param.requires_grad:
net_params.append(param)
self.optimizer = self.run_config.build_optimizer(net_params)
self.net = torch.nn.DataParallel(self.net) | [
"def",
"__init__",
"(",
"self",
",",
"path",
",",
"net",
",",
"run_config",
",",
"init",
"=",
"True",
",",
"measure_latency",
"=",
"None",
",",
"no_gpu",
"=",
"False",
")",
":",
"self",
".",
"path",
"=",
"path",
"self",
".",
"net",
"=",
"net",
"sel... | https://github.com/mit-han-lab/once-for-all/blob/4f6fce3652ee4553ea811d38f32f90ac8b1bc378/ofa/imagenet_classification/run_manager/run_manager.py#L26-L88 | ||||
GoogleCloudPlatform/PerfKitBenchmarker | 6e3412d7d5e414b8ca30ed5eaf970cef1d919a67 | perfkitbenchmarker/linux_benchmarks/bidirectional_network_benchmark.py | python | Cleanup | (benchmark_spec) | Cleanup netperf on the target vm (by uninstalling).
Args:
benchmark_spec: The benchmark specification. Contains all data that is
required to run the benchmark. | Cleanup netperf on the target vm (by uninstalling). | [
"Cleanup",
"netperf",
"on",
"the",
"target",
"vm",
"(",
"by",
"uninstalling",
")",
"."
] | def Cleanup(benchmark_spec):
"""Cleanup netperf on the target vm (by uninstalling).
Args:
benchmark_spec: The benchmark specification. Contains all data that is
required to run the benchmark.
"""
vms = benchmark_spec.vms
for vm in vms[1:]:
vm.RemoteCommand('sudo killall netserver')
vms[0].RemoteCommand('sudo rm -rf %s' % REMOTE_SCRIPT) | [
"def",
"Cleanup",
"(",
"benchmark_spec",
")",
":",
"vms",
"=",
"benchmark_spec",
".",
"vms",
"for",
"vm",
"in",
"vms",
"[",
"1",
":",
"]",
":",
"vm",
".",
"RemoteCommand",
"(",
"'sudo killall netserver'",
")",
"vms",
"[",
"0",
"]",
".",
"RemoteCommand",
... | https://github.com/GoogleCloudPlatform/PerfKitBenchmarker/blob/6e3412d7d5e414b8ca30ed5eaf970cef1d919a67/perfkitbenchmarker/linux_benchmarks/bidirectional_network_benchmark.py#L346-L356 | ||
qitan/SOMS | 5d1e7b0676e3c9dc90f6ca5010884555296d6442 | deploy/saltapi.py | python | SaltAPI.remote_module | (self,tgt,fun,arg,kwarg,expr_form) | return jid | 异步部署模块 | 异步部署模块 | [
"异步部署模块"
] | def remote_module(self,tgt,fun,arg,kwarg,expr_form):
'''
异步部署模块
'''
params = {'client': 'local_async', 'tgt': tgt, 'fun': fun, 'arg': arg, 'expr_form': expr_form}
#kwarg = {'SALTSRC': 'PET'}
params2 = {'arg':'pillar={}'.format(kwarg)}
arg_add = urllib.urlencode(params2)
obj = urllib.urlencode(params)
obj = obj + '&' + arg_add
self.token_id()
content = self.postRequest(obj)
jid = content['return'][0]['jid']
return jid | [
"def",
"remote_module",
"(",
"self",
",",
"tgt",
",",
"fun",
",",
"arg",
",",
"kwarg",
",",
"expr_form",
")",
":",
"params",
"=",
"{",
"'client'",
":",
"'local_async'",
",",
"'tgt'",
":",
"tgt",
",",
"'fun'",
":",
"fun",
",",
"'arg'",
":",
"arg",
"... | https://github.com/qitan/SOMS/blob/5d1e7b0676e3c9dc90f6ca5010884555296d6442/deploy/saltapi.py#L130-L144 | |
wemake-services/wemake-python-styleguide | 11767452c7d9766dbf9aa49c75b231db9aaef937 | wemake_python_styleguide/logic/tree/decorators.py | python | has_overload_decorator | (function: AnyFunctionDef) | return False | Detects if a function has ``@overload`` or ``@typing.overload`` decorators.
It is useful, because ``@overload`` function defs
have slightly different rules: for example, they do not count as real defs
in complexity rules. | Detects if a function has ``@overload`` or ``@typing.overload`` decorators. | [
"Detects",
"if",
"a",
"function",
"has",
"@overload",
"or",
"@typing",
".",
"overload",
"decorators",
"."
] | def has_overload_decorator(function: AnyFunctionDef) -> bool:
"""
Detects if a function has ``@overload`` or ``@typing.overload`` decorators.
It is useful, because ``@overload`` function defs
have slightly different rules: for example, they do not count as real defs
in complexity rules.
"""
for decorator in function.decorator_list:
is_partial_name = (
isinstance(decorator, ast.Name) and
decorator.id == 'overload'
)
is_full_name = (
isinstance(decorator, ast.Attribute) and
decorator.attr == 'overload' and
isinstance(decorator.value, ast.Name) and
decorator.value.id == 'typing'
)
if is_partial_name or is_full_name:
return True
return False | [
"def",
"has_overload_decorator",
"(",
"function",
":",
"AnyFunctionDef",
")",
"->",
"bool",
":",
"for",
"decorator",
"in",
"function",
".",
"decorator_list",
":",
"is_partial_name",
"=",
"(",
"isinstance",
"(",
"decorator",
",",
"ast",
".",
"Name",
")",
"and",... | https://github.com/wemake-services/wemake-python-styleguide/blob/11767452c7d9766dbf9aa49c75b231db9aaef937/wemake_python_styleguide/logic/tree/decorators.py#L6-L27 | |
aws/aws-cli | d697e0ed79fca0f853ce53efe1f83ee41a478134 | awscli/customizations/cloudtrail/validation.py | python | CloudTrailValidateLogs._download_log | (self, log) | Download a log, decompress, and compare SHA256 checksums | Download a log, decompress, and compare SHA256 checksums | [
"Download",
"a",
"log",
"decompress",
"and",
"compare",
"SHA256",
"checksums"
] | def _download_log(self, log):
""" Download a log, decompress, and compare SHA256 checksums"""
try:
# Create a client that can work with this bucket.
client = self.s3_client_provider.get_client(log['s3Bucket'])
response = client.get_object(
Bucket=log['s3Bucket'], Key=log['s3Object'])
gzip_inflater = zlib.decompressobj(zlib.MAX_WBITS | 16)
rolling_hash = hashlib.sha256()
for chunk in iter(lambda: response['Body'].read(2048), b""):
data = gzip_inflater.decompress(chunk)
rolling_hash.update(data)
remaining_data = gzip_inflater.flush()
if remaining_data:
rolling_hash.update(remaining_data)
computed_hash = rolling_hash.hexdigest()
if computed_hash != log['hashValue']:
self._on_log_invalid(log)
else:
self._valid_logs += 1
self._write_status(('Log file\ts3://%s/%s\tvalid'
% (log['s3Bucket'], log['s3Object'])))
except ClientError as e:
if e.response['Error']['Code'] != 'NoSuchKey':
raise
self._on_missing_log(log)
except Exception:
self._on_invalid_log_format(log) | [
"def",
"_download_log",
"(",
"self",
",",
"log",
")",
":",
"try",
":",
"# Create a client that can work with this bucket.",
"client",
"=",
"self",
".",
"s3_client_provider",
".",
"get_client",
"(",
"log",
"[",
"'s3Bucket'",
"]",
")",
"response",
"=",
"client",
"... | https://github.com/aws/aws-cli/blob/d697e0ed79fca0f853ce53efe1f83ee41a478134/awscli/customizations/cloudtrail/validation.py#L786-L813 | ||
noamraph/dreampie | b09ee546ec099ee6549c649692ceb129e05fb229 | dulwich/object_store.py | python | BaseObjectStore.get_graph_walker | (self, heads) | return ObjectStoreGraphWalker(heads, lambda sha: self[sha].parents) | Obtain a graph walker for this object store.
:param heads: Local heads to start search with
:return: GraphWalker object | Obtain a graph walker for this object store. | [
"Obtain",
"a",
"graph",
"walker",
"for",
"this",
"object",
"store",
"."
] | def get_graph_walker(self, heads):
"""Obtain a graph walker for this object store.
:param heads: Local heads to start search with
:return: GraphWalker object
"""
return ObjectStoreGraphWalker(heads, lambda sha: self[sha].parents) | [
"def",
"get_graph_walker",
"(",
"self",
",",
"heads",
")",
":",
"return",
"ObjectStoreGraphWalker",
"(",
"heads",
",",
"lambda",
"sha",
":",
"self",
"[",
"sha",
"]",
".",
"parents",
")"
] | https://github.com/noamraph/dreampie/blob/b09ee546ec099ee6549c649692ceb129e05fb229/dulwich/object_store.py#L192-L198 | |
gem/oq-engine | 1bdb88f3914e390abcbd285600bfd39477aae47c | openquake/hazardlib/shakemap/parsers.py | python | get_array_file_npy | (kind, fname) | return numpy.load(fname) | Read a ShakeMap in .npy format from the local file system | Read a ShakeMap in .npy format from the local file system | [
"Read",
"a",
"ShakeMap",
"in",
".",
"npy",
"format",
"from",
"the",
"local",
"file",
"system"
] | def get_array_file_npy(kind, fname):
"""
Read a ShakeMap in .npy format from the local file system
"""
return numpy.load(fname) | [
"def",
"get_array_file_npy",
"(",
"kind",
",",
"fname",
")",
":",
"return",
"numpy",
".",
"load",
"(",
"fname",
")"
] | https://github.com/gem/oq-engine/blob/1bdb88f3914e390abcbd285600bfd39477aae47c/openquake/hazardlib/shakemap/parsers.py#L211-L215 | |
SamSchott/maestral | a32653bac7b5a76cb326d4fd5a4fb2c11f19a2fc | src/maestral/main.py | python | Maestral.log_level | (self, level_num: int) | Setter: log_level. | Setter: log_level. | [
"Setter",
":",
"log_level",
"."
] | def log_level(self, level_num: int) -> None:
"""Setter: log_level."""
self._root_logger.setLevel(min(level_num, logging.INFO))
self._log_handler_file.setLevel(level_num)
self._log_handler_stream.setLevel(level_num)
self._log_handler_journal.setLevel(level_num)
self._conf.set("app", "log_level", level_num) | [
"def",
"log_level",
"(",
"self",
",",
"level_num",
":",
"int",
")",
"->",
"None",
":",
"self",
".",
"_root_logger",
".",
"setLevel",
"(",
"min",
"(",
"level_num",
",",
"logging",
".",
"INFO",
")",
")",
"self",
".",
"_log_handler_file",
".",
"setLevel",
... | https://github.com/SamSchott/maestral/blob/a32653bac7b5a76cb326d4fd5a4fb2c11f19a2fc/src/maestral/main.py#L375-L381 | ||
khalim19/gimp-plugin-export-layers | b37255f2957ad322f4d332689052351cdea6e563 | export_layers/pygimplib/_lib/future/past/translation/__init__.py | python | detect_python2 | (source, pathname) | Returns a bool indicating whether we think the code is Py2 | Returns a bool indicating whether we think the code is Py2 | [
"Returns",
"a",
"bool",
"indicating",
"whether",
"we",
"think",
"the",
"code",
"is",
"Py2"
] | def detect_python2(source, pathname):
"""
Returns a bool indicating whether we think the code is Py2
"""
RTs.setup_detect_python2()
try:
tree = RTs._rt_py2_detect.refactor_string(source, pathname)
except ParseError as e:
if e.msg != 'bad input' or e.value != '=':
raise
tree = RTs._rtp.refactor_string(source, pathname)
if source != str(tree)[:-1]: # remove added newline
# The above fixers made changes, so we conclude it's Python 2 code
logger.debug('Detected Python 2 code: {0}'.format(pathname))
with open('/tmp/original_code.py', 'w') as f:
f.write('### Original code (detected as py2): %s\n%s' %
(pathname, source))
with open('/tmp/py2_detection_code.py', 'w') as f:
f.write('### Code after running py3 detection (from %s)\n%s' %
(pathname, str(tree)[:-1]))
return True
else:
logger.debug('Detected Python 3 code: {0}'.format(pathname))
with open('/tmp/original_code.py', 'w') as f:
f.write('### Original code (detected as py3): %s\n%s' %
(pathname, source))
try:
os.remove('/tmp/futurize_code.py')
except OSError:
pass
return False | [
"def",
"detect_python2",
"(",
"source",
",",
"pathname",
")",
":",
"RTs",
".",
"setup_detect_python2",
"(",
")",
"try",
":",
"tree",
"=",
"RTs",
".",
"_rt_py2_detect",
".",
"refactor_string",
"(",
"source",
",",
"pathname",
")",
"except",
"ParseError",
"as",... | https://github.com/khalim19/gimp-plugin-export-layers/blob/b37255f2957ad322f4d332689052351cdea6e563/export_layers/pygimplib/_lib/future/past/translation/__init__.py#L207-L238 | ||
cleverhans-lab/cleverhans | e5d00e537ce7ad6119ed5a8db1f0e9736d1f6e1d | cleverhans_v3.1.0/cleverhans/loss.py | python | LossFeaturePairing.__init__ | (self, model, weight, attack, **kwargs) | Constructor.
:param model: Model instance, the model on which to apply the loss.
:param weight: float, with of logic pairing loss.
:param attack: function, given an input x, return an attacked x'. | Constructor.
:param model: Model instance, the model on which to apply the loss.
:param weight: float, with of logic pairing loss.
:param attack: function, given an input x, return an attacked x'. | [
"Constructor",
".",
":",
"param",
"model",
":",
"Model",
"instance",
"the",
"model",
"on",
"which",
"to",
"apply",
"the",
"loss",
".",
":",
"param",
"weight",
":",
"float",
"with",
"of",
"logic",
"pairing",
"loss",
".",
":",
"param",
"attack",
":",
"fu... | def __init__(self, model, weight, attack, **kwargs):
"""Constructor.
:param model: Model instance, the model on which to apply the loss.
:param weight: float, with of logic pairing loss.
:param attack: function, given an input x, return an attacked x'.
"""
del kwargs
Loss.__init__(self, model, locals(), attack)
self.weight = weight | [
"def",
"__init__",
"(",
"self",
",",
"model",
",",
"weight",
",",
"attack",
",",
"*",
"*",
"kwargs",
")",
":",
"del",
"kwargs",
"Loss",
".",
"__init__",
"(",
"self",
",",
"model",
",",
"locals",
"(",
")",
",",
"attack",
")",
"self",
".",
"weight",
... | https://github.com/cleverhans-lab/cleverhans/blob/e5d00e537ce7ad6119ed5a8db1f0e9736d1f6e1d/cleverhans_v3.1.0/cleverhans/loss.py#L305-L313 | ||
idiap/fast-transformers | f22c13716fc748bb21a7b226ada7f7b5f87f867f | fast_transformers/builders/transformer_builders.py | python | RecurrentEncoderBuilder._get_attention_builder | (self) | return RecurrentAttentionBuilder() | Return an attention builder for recurrent attention. | Return an attention builder for recurrent attention. | [
"Return",
"an",
"attention",
"builder",
"for",
"recurrent",
"attention",
"."
] | def _get_attention_builder(self):
"""Return an attention builder for recurrent attention."""
return RecurrentAttentionBuilder() | [
"def",
"_get_attention_builder",
"(",
"self",
")",
":",
"return",
"RecurrentAttentionBuilder",
"(",
")"
] | https://github.com/idiap/fast-transformers/blob/f22c13716fc748bb21a7b226ada7f7b5f87f867f/fast_transformers/builders/transformer_builders.py#L305-L307 | |
PokemonGoF/PokemonGo-Bot-Desktop | 4bfa94f0183406c6a86f93645eff7abd3ad4ced8 | build/pywin/Lib/pydoc.py | python | splitdoc | (doc) | return '', join(lines, '\n') | Split a doc string into a synopsis line (if any) and the rest. | Split a doc string into a synopsis line (if any) and the rest. | [
"Split",
"a",
"doc",
"string",
"into",
"a",
"synopsis",
"line",
"(",
"if",
"any",
")",
"and",
"the",
"rest",
"."
] | def splitdoc(doc):
"""Split a doc string into a synopsis line (if any) and the rest."""
lines = split(strip(doc), '\n')
if len(lines) == 1:
return lines[0], ''
elif len(lines) >= 2 and not rstrip(lines[1]):
return lines[0], join(lines[2:], '\n')
return '', join(lines, '\n') | [
"def",
"splitdoc",
"(",
"doc",
")",
":",
"lines",
"=",
"split",
"(",
"strip",
"(",
"doc",
")",
",",
"'\\n'",
")",
"if",
"len",
"(",
"lines",
")",
"==",
"1",
":",
"return",
"lines",
"[",
"0",
"]",
",",
"''",
"elif",
"len",
"(",
"lines",
")",
"... | https://github.com/PokemonGoF/PokemonGo-Bot-Desktop/blob/4bfa94f0183406c6a86f93645eff7abd3ad4ced8/build/pywin/Lib/pydoc.py#L88-L95 | |
stevearc/dql | 9666cfba19773c20c7b4be29adc7d6179cf00d44 | dql/engine.py | python | Engine.connection | (self) | return self._connection | Get the dynamo connection | Get the dynamo connection | [
"Get",
"the",
"dynamo",
"connection"
] | def connection(self) -> DynamoDBConnection:
"""Get the dynamo connection"""
return self._connection | [
"def",
"connection",
"(",
"self",
")",
"->",
"DynamoDBConnection",
":",
"return",
"self",
".",
"_connection"
] | https://github.com/stevearc/dql/blob/9666cfba19773c20c7b4be29adc7d6179cf00d44/dql/engine.py#L150-L152 | |
cdhigh/KindleEar | 7c4ecf9625239f12a829210d1760b863ef5a23aa | lib/calibre/ebooks/BeautifulSoup.py | python | UnicodeDammit._detectEncoding | (self, xml_data, isHTML=False) | return xml_data, xml_encoding, sniffed_xml_encoding | Given a document, tries to detect its XML encoding. | Given a document, tries to detect its XML encoding. | [
"Given",
"a",
"document",
"tries",
"to",
"detect",
"its",
"XML",
"encoding",
"."
] | def _detectEncoding(self, xml_data, isHTML=False):
"""Given a document, tries to detect its XML encoding."""
xml_encoding = sniffed_xml_encoding = None
try:
if xml_data[:4] == '\x4c\x6f\xa7\x94':
# EBCDIC
xml_data = self._ebcdic_to_ascii(xml_data)
elif xml_data[:4] == '\x00\x3c\x00\x3f':
# UTF-16BE
sniffed_xml_encoding = 'utf-16be'
xml_data = unicode(xml_data, 'utf-16be').encode('utf-8')
elif (len(xml_data) >= 4) and (xml_data[:2] == '\xfe\xff') \
and (xml_data[2:4] != '\x00\x00'):
# UTF-16BE with BOM
sniffed_xml_encoding = 'utf-16be'
xml_data = unicode(xml_data[2:], 'utf-16be').encode('utf-8')
elif xml_data[:4] == '\x3c\x00\x3f\x00':
# UTF-16LE
sniffed_xml_encoding = 'utf-16le'
xml_data = unicode(xml_data, 'utf-16le').encode('utf-8')
elif (len(xml_data) >= 4) and (xml_data[:2] == '\xff\xfe') and \
(xml_data[2:4] != '\x00\x00'):
# UTF-16LE with BOM
sniffed_xml_encoding = 'utf-16le'
xml_data = unicode(xml_data[2:], 'utf-16le').encode('utf-8')
elif xml_data[:4] == '\x00\x00\x00\x3c':
# UTF-32BE
sniffed_xml_encoding = 'utf-32be'
xml_data = unicode(xml_data, 'utf-32be').encode('utf-8')
elif xml_data[:4] == '\x3c\x00\x00\x00':
# UTF-32LE
sniffed_xml_encoding = 'utf-32le'
xml_data = unicode(xml_data, 'utf-32le').encode('utf-8')
elif xml_data[:4] == '\x00\x00\xfe\xff':
# UTF-32BE with BOM
sniffed_xml_encoding = 'utf-32be'
xml_data = unicode(xml_data[4:], 'utf-32be').encode('utf-8')
elif xml_data[:4] == '\xff\xfe\x00\x00':
# UTF-32LE with BOM
sniffed_xml_encoding = 'utf-32le'
xml_data = unicode(xml_data[4:], 'utf-32le').encode('utf-8')
elif xml_data[:3] == '\xef\xbb\xbf':
# UTF-8 with BOM
sniffed_xml_encoding = 'utf-8'
xml_data = unicode(xml_data[3:], 'utf-8').encode('utf-8')
else:
sniffed_xml_encoding = 'ascii'
pass
except:
xml_encoding_match = None
xml_encoding_match = re.compile(
'^<\?.*encoding=[\'"](.*?)[\'"].*\?>').match(xml_data)
if not xml_encoding_match and isHTML:
regexp = re.compile('<\s*meta[^>]+charset=([^>]*?)[;\'">]', re.I)
xml_encoding_match = regexp.search(xml_data)
if xml_encoding_match is not None:
xml_encoding = xml_encoding_match.groups()[0].lower()
if isHTML:
self.declaredHTMLEncoding = xml_encoding
if sniffed_xml_encoding and \
(xml_encoding in ('iso-10646-ucs-2', 'ucs-2', 'csunicode',
'iso-10646-ucs-4', 'ucs-4', 'csucs4',
'utf-16', 'utf-32', 'utf_16', 'utf_32',
'utf16', 'u16')):
xml_encoding = sniffed_xml_encoding
return xml_data, xml_encoding, sniffed_xml_encoding | [
"def",
"_detectEncoding",
"(",
"self",
",",
"xml_data",
",",
"isHTML",
"=",
"False",
")",
":",
"xml_encoding",
"=",
"sniffed_xml_encoding",
"=",
"None",
"try",
":",
"if",
"xml_data",
"[",
":",
"4",
"]",
"==",
"'\\x4c\\x6f\\xa7\\x94'",
":",
"# EBCDIC",
"xml_d... | https://github.com/cdhigh/KindleEar/blob/7c4ecf9625239f12a829210d1760b863ef5a23aa/lib/calibre/ebooks/BeautifulSoup.py#L1867-L1932 | |
angr/angr | 4b04d56ace135018083d36d9083805be8146688b | angr/sim_state.py | python | SimState.ip | (self) | return self.regs.ip | Get the instruction pointer expression, trigger SimInspect breakpoints, and generate SimActions.
Use ``_ip`` to not trigger breakpoints or generate actions.
:return: an expression | Get the instruction pointer expression, trigger SimInspect breakpoints, and generate SimActions.
Use ``_ip`` to not trigger breakpoints or generate actions. | [
"Get",
"the",
"instruction",
"pointer",
"expression",
"trigger",
"SimInspect",
"breakpoints",
"and",
"generate",
"SimActions",
".",
"Use",
"_ip",
"to",
"not",
"trigger",
"breakpoints",
"or",
"generate",
"actions",
"."
] | def ip(self):
"""
Get the instruction pointer expression, trigger SimInspect breakpoints, and generate SimActions.
Use ``_ip`` to not trigger breakpoints or generate actions.
:return: an expression
"""
return self.regs.ip | [
"def",
"ip",
"(",
"self",
")",
":",
"return",
"self",
".",
"regs",
".",
"ip"
] | https://github.com/angr/angr/blob/4b04d56ace135018083d36d9083805be8146688b/angr/sim_state.py#L314-L321 | |
PyTorchLightning/pytorch-lightning | 5914fb748fb53d826ab337fc2484feab9883a104 | pytorch_lightning/loops/dataloader/evaluation_loop.py | python | EvaluationLoop.connect | (self, epoch_loop: EvaluationEpochLoop) | Connect the evaluation epoch loop with this loop. | Connect the evaluation epoch loop with this loop. | [
"Connect",
"the",
"evaluation",
"epoch",
"loop",
"with",
"this",
"loop",
"."
] | def connect(self, epoch_loop: EvaluationEpochLoop) -> None: # type: ignore[override]
"""Connect the evaluation epoch loop with this loop."""
self.epoch_loop = epoch_loop | [
"def",
"connect",
"(",
"self",
",",
"epoch_loop",
":",
"EvaluationEpochLoop",
")",
"->",
"None",
":",
"# type: ignore[override]",
"self",
".",
"epoch_loop",
"=",
"epoch_loop"
] | https://github.com/PyTorchLightning/pytorch-lightning/blob/5914fb748fb53d826ab337fc2484feab9883a104/pytorch_lightning/loops/dataloader/evaluation_loop.py#L62-L64 | ||
Sprytile/Sprytile | 6b68d0069aef5bfed6ab40d1d5a94a3382b41619 | rx/linq/observable/asobservable.py | python | as_observable | (self) | return AnonymousObservable(subscribe) | Hides the identity of an observable sequence.
:returns: An observable sequence that hides the identity of the source
sequence.
:rtype: Observable | Hides the identity of an observable sequence. | [
"Hides",
"the",
"identity",
"of",
"an",
"observable",
"sequence",
"."
] | def as_observable(self):
"""Hides the identity of an observable sequence.
:returns: An observable sequence that hides the identity of the source
sequence.
:rtype: Observable
"""
source = self
def subscribe(observer):
return source.subscribe(observer)
return AnonymousObservable(subscribe) | [
"def",
"as_observable",
"(",
"self",
")",
":",
"source",
"=",
"self",
"def",
"subscribe",
"(",
"observer",
")",
":",
"return",
"source",
".",
"subscribe",
"(",
"observer",
")",
"return",
"AnonymousObservable",
"(",
"subscribe",
")"
] | https://github.com/Sprytile/Sprytile/blob/6b68d0069aef5bfed6ab40d1d5a94a3382b41619/rx/linq/observable/asobservable.py#L6-L19 | |
leancloud/satori | 701caccbd4fe45765001ca60435c0cb499477c03 | satori-rules/plugin/libs/requests/packages/chardet/gb2312prober.py | python | GB2312Prober.__init__ | (self) | [] | def __init__(self):
MultiByteCharSetProber.__init__(self)
self._mCodingSM = CodingStateMachine(GB2312SMModel)
self._mDistributionAnalyzer = GB2312DistributionAnalysis()
self.reset() | [
"def",
"__init__",
"(",
"self",
")",
":",
"MultiByteCharSetProber",
".",
"__init__",
"(",
"self",
")",
"self",
".",
"_mCodingSM",
"=",
"CodingStateMachine",
"(",
"GB2312SMModel",
")",
"self",
".",
"_mDistributionAnalyzer",
"=",
"GB2312DistributionAnalysis",
"(",
"... | https://github.com/leancloud/satori/blob/701caccbd4fe45765001ca60435c0cb499477c03/satori-rules/plugin/libs/requests/packages/chardet/gb2312prober.py#L34-L38 | ||||
googleads/google-ads-python | 2a1d6062221f6aad1992a6bcca0e7e4a93d2db86 | google/ads/googleads/v9/services/services/customer_user_access_invitation_service/client.py | python | CustomerUserAccessInvitationServiceClient.customer_user_access_invitation_path | (
customer_id: str, invitation_id: str,
) | return "customers/{customer_id}/customerUserAccessInvitations/{invitation_id}".format(
customer_id=customer_id, invitation_id=invitation_id,
) | Return a fully-qualified customer_user_access_invitation string. | Return a fully-qualified customer_user_access_invitation string. | [
"Return",
"a",
"fully",
"-",
"qualified",
"customer_user_access_invitation",
"string",
"."
] | def customer_user_access_invitation_path(
customer_id: str, invitation_id: str,
) -> str:
"""Return a fully-qualified customer_user_access_invitation string."""
return "customers/{customer_id}/customerUserAccessInvitations/{invitation_id}".format(
customer_id=customer_id, invitation_id=invitation_id,
) | [
"def",
"customer_user_access_invitation_path",
"(",
"customer_id",
":",
"str",
",",
"invitation_id",
":",
"str",
",",
")",
"->",
"str",
":",
"return",
"\"customers/{customer_id}/customerUserAccessInvitations/{invitation_id}\"",
".",
"format",
"(",
"customer_id",
"=",
"cus... | https://github.com/googleads/google-ads-python/blob/2a1d6062221f6aad1992a6bcca0e7e4a93d2db86/google/ads/googleads/v9/services/services/customer_user_access_invitation_service/client.py#L188-L194 | |
MrH0wl/Cloudmare | 65e5bc9888f9d362ab2abfb103ea6c1e869d67aa | thirdparty/click/formatting.py | python | HelpFormatter.indent | (self) | Increases the indentation. | Increases the indentation. | [
"Increases",
"the",
"indentation",
"."
] | def indent(self):
"""Increases the indentation."""
self.current_indent += self.indent_increment | [
"def",
"indent",
"(",
"self",
")",
":",
"self",
".",
"current_indent",
"+=",
"self",
".",
"indent_increment"
] | https://github.com/MrH0wl/Cloudmare/blob/65e5bc9888f9d362ab2abfb103ea6c1e869d67aa/thirdparty/click/formatting.py#L122-L124 | ||
triaquae/triaquae | bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9 | TriAquae/models/django/contrib/gis/geos/polygon.py | python | Polygon.kml | (self) | return "<Polygon><outerBoundaryIs>%s</outerBoundaryIs>%s</Polygon>" % (self[0].kml, inner_kml) | Returns the KML representation of this Polygon. | Returns the KML representation of this Polygon. | [
"Returns",
"the",
"KML",
"representation",
"of",
"this",
"Polygon",
"."
] | def kml(self):
"Returns the KML representation of this Polygon."
inner_kml = ''.join(["<innerBoundaryIs>%s</innerBoundaryIs>" % self[i+1].kml
for i in xrange(self.num_interior_rings)])
return "<Polygon><outerBoundaryIs>%s</outerBoundaryIs>%s</Polygon>" % (self[0].kml, inner_kml) | [
"def",
"kml",
"(",
"self",
")",
":",
"inner_kml",
"=",
"''",
".",
"join",
"(",
"[",
"\"<innerBoundaryIs>%s</innerBoundaryIs>\"",
"%",
"self",
"[",
"i",
"+",
"1",
"]",
".",
"kml",
"for",
"i",
"in",
"xrange",
"(",
"self",
".",
"num_interior_rings",
")",
... | https://github.com/triaquae/triaquae/blob/bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9/TriAquae/models/django/contrib/gis/geos/polygon.py#L166-L170 | |
NuID/nebulousAD | 37a44f131d13f1668a73b61f2444ad93b9e657cc | nebulousAD/modimpacket/dot11.py | python | Dot11WPA2.get_extIV | (self) | return ((b>>5) & 0x1) | Return the \'WPA2 extID\' field | Return the \'WPA2 extID\' field | [
"Return",
"the",
"\\",
"WPA2",
"extID",
"\\",
"field"
] | def get_extIV(self):
'Return the \'WPA2 extID\' field'
b = self.header.get_byte(3)
return ((b>>5) & 0x1) | [
"def",
"get_extIV",
"(",
"self",
")",
":",
"b",
"=",
"self",
".",
"header",
".",
"get_byte",
"(",
"3",
")",
"return",
"(",
"(",
"b",
">>",
"5",
")",
"&",
"0x1",
")"
] | https://github.com/NuID/nebulousAD/blob/37a44f131d13f1668a73b61f2444ad93b9e657cc/nebulousAD/modimpacket/dot11.py#L1331-L1334 | |
readbeyond/aeneas | 4d200a050690903b30b3d885b44714fecb23f18a | aeneas/tree.py | python | Tree.add_child | (self, node, as_last=True) | Add the given child to the current list of children.
The new child is appended as the last child if ``as_last``
is ``True``, or as the first child if ``as_last`` is ``False``.
This call updates the ``__parent`` and ``__level`` fields of ``node``.
:param node: the child node to be added
:type node: :class:`~aeneas.tree.Tree`
:param bool as_last: if ``True``, append the node as the last child;
if ``False``, append the node as the first child
:raises: TypeError if ``node`` is not an instance of :class:`~aeneas.tree.Tree` | Add the given child to the current list of children. | [
"Add",
"the",
"given",
"child",
"to",
"the",
"current",
"list",
"of",
"children",
"."
] | def add_child(self, node, as_last=True):
"""
Add the given child to the current list of children.
The new child is appended as the last child if ``as_last``
is ``True``, or as the first child if ``as_last`` is ``False``.
This call updates the ``__parent`` and ``__level`` fields of ``node``.
:param node: the child node to be added
:type node: :class:`~aeneas.tree.Tree`
:param bool as_last: if ``True``, append the node as the last child;
if ``False``, append the node as the first child
:raises: TypeError if ``node`` is not an instance of :class:`~aeneas.tree.Tree`
"""
if not isinstance(node, Tree):
self.log_exc(u"node is not an instance of Tree", None, True, TypeError)
if as_last:
self.__children.append(node)
else:
self.__children = [node] + self.__children
node.__parent = self
new_height = 1 + self.level
for n in node.subtree:
n.__level += new_height | [
"def",
"add_child",
"(",
"self",
",",
"node",
",",
"as_last",
"=",
"True",
")",
":",
"if",
"not",
"isinstance",
"(",
"node",
",",
"Tree",
")",
":",
"self",
".",
"log_exc",
"(",
"u\"node is not an instance of Tree\"",
",",
"None",
",",
"True",
",",
"TypeE... | https://github.com/readbeyond/aeneas/blob/4d200a050690903b30b3d885b44714fecb23f18a/aeneas/tree.py#L219-L243 | ||
openSUSE/osc | 5c2e1b039a16334880e7ebe4a33baafe0f2d5e20 | osc/core.py | python | get_commit_message_template | (pac) | return template | Read the difference in .changes file(s) and put them as a template to commit message. | Read the difference in .changes file(s) and put them as a template to commit message. | [
"Read",
"the",
"difference",
"in",
".",
"changes",
"file",
"(",
"s",
")",
"and",
"put",
"them",
"as",
"a",
"template",
"to",
"commit",
"message",
"."
] | def get_commit_message_template(pac):
"""
Read the difference in .changes file(s) and put them as a template to commit message.
"""
diff = []
template = []
if pac.todo:
todo = pac.todo
else:
todo = pac.filenamelist + pac.filenamelist_unvers
files = [i for i in todo if i.endswith('.changes') and pac.status(i) in ('A', 'M')]
for filename in files:
if pac.status(filename) == 'M':
diff += get_source_file_diff(pac.absdir, filename, pac.rev)
elif pac.status(filename) == 'A':
with open(os.path.join(pac.absdir, filename), 'rb') as f:
diff.extend((b'+' + line for line in f))
if diff:
template = parse_diff_for_commit_message(''.join(decode_list(diff)))
return template | [
"def",
"get_commit_message_template",
"(",
"pac",
")",
":",
"diff",
"=",
"[",
"]",
"template",
"=",
"[",
"]",
"if",
"pac",
".",
"todo",
":",
"todo",
"=",
"pac",
".",
"todo",
"else",
":",
"todo",
"=",
"pac",
".",
"filenamelist",
"+",
"pac",
".",
"fi... | https://github.com/openSUSE/osc/blob/5c2e1b039a16334880e7ebe4a33baafe0f2d5e20/osc/core.py#L7342-L7366 | |
gwastro/pycbc | 1e1c85534b9dba8488ce42df693230317ca63dea | pycbc/vetoes/chisq.py | python | SingleDetPowerChisq.values | (self, corr, snrv, snr_norm, psd, indices, template) | Calculate the chisq at points given by indices.
Returns
-------
chisq: Array
Chisq values, one for each sample index, or zero for points below
the specified SNR threshold
chisq_dof: Array
Number of statistical degrees of freedom for the chisq test
in the given template, equal to 2 * num_bins - 2 | Calculate the chisq at points given by indices. | [
"Calculate",
"the",
"chisq",
"at",
"points",
"given",
"by",
"indices",
"."
] | def values(self, corr, snrv, snr_norm, psd, indices, template):
""" Calculate the chisq at points given by indices.
Returns
-------
chisq: Array
Chisq values, one for each sample index, or zero for points below
the specified SNR threshold
chisq_dof: Array
Number of statistical degrees of freedom for the chisq test
in the given template, equal to 2 * num_bins - 2
"""
if self.do:
num_above = len(indices)
if self.snr_threshold:
above = abs(snrv * snr_norm) > self.snr_threshold
num_above = above.sum()
logging.info('%s above chisq activation threshold' % num_above)
above_indices = indices[above]
above_snrv = snrv[above]
chisq_out = numpy.zeros(len(indices), dtype=numpy.float32)
dof = -100
else:
above_indices = indices
above_snrv = snrv
if num_above > 0:
bins = self.cached_chisq_bins(template, psd)
# len(bins) is number of bin edges, num_bins = len(bins) - 1
dof = (len(bins) - 1) * 2 - 2
_chisq = power_chisq_at_points_from_precomputed(corr,
above_snrv, snr_norm, bins, above_indices)
if self.snr_threshold:
if num_above > 0:
chisq_out[above] = _chisq
else:
chisq_out = _chisq
return chisq_out, numpy.repeat(dof, len(indices))# dof * numpy.ones_like(indices)
else:
return None, None | [
"def",
"values",
"(",
"self",
",",
"corr",
",",
"snrv",
",",
"snr_norm",
",",
"psd",
",",
"indices",
",",
"template",
")",
":",
"if",
"self",
".",
"do",
":",
"num_above",
"=",
"len",
"(",
"indices",
")",
"if",
"self",
".",
"snr_threshold",
":",
"ab... | https://github.com/gwastro/pycbc/blob/1e1c85534b9dba8488ce42df693230317ca63dea/pycbc/vetoes/chisq.py#L358-L400 | ||
spectacles/CodeComplice | 8ca8ee4236f72b58caa4209d2fbd5fa56bd31d62 | libs/codeintel2/parser_data.py | python | ModuleNode.__init__ | (self, the_name, line_num, unused=False) | [] | def __init__(self, the_name, line_num, unused=False):
self.name = the_name
Node.__init__(self, line_num, "Module") | [
"def",
"__init__",
"(",
"self",
",",
"the_name",
",",
"line_num",
",",
"unused",
"=",
"False",
")",
":",
"self",
".",
"name",
"=",
"the_name",
"Node",
".",
"__init__",
"(",
"self",
",",
"line_num",
",",
"\"Module\"",
")"
] | https://github.com/spectacles/CodeComplice/blob/8ca8ee4236f72b58caa4209d2fbd5fa56bd31d62/libs/codeintel2/parser_data.py#L211-L213 | ||||
triaquae/triaquae | bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9 | TriAquae/models/django/utils/feedgenerator.py | python | RssUserland091Feed.add_item_elements | (self, handler, item) | [] | def add_item_elements(self, handler, item):
handler.addQuickElement("title", item['title'])
handler.addQuickElement("link", item['link'])
if item['description'] is not None:
handler.addQuickElement("description", item['description']) | [
"def",
"add_item_elements",
"(",
"self",
",",
"handler",
",",
"item",
")",
":",
"handler",
".",
"addQuickElement",
"(",
"\"title\"",
",",
"item",
"[",
"'title'",
"]",
")",
"handler",
".",
"addQuickElement",
"(",
"\"link\"",
",",
"item",
"[",
"'link'",
"]",... | https://github.com/triaquae/triaquae/blob/bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9/TriAquae/models/django/utils/feedgenerator.py#L254-L258 | ||||
aimagelab/meshed-memory-transformer | e0fe3fae68091970407e82e5b907cbc423f25df2 | evaluation/bleu/bleu.py | python | Bleu.__init__ | (self, n=4) | [] | def __init__(self, n=4):
# default compute Blue score up to 4
self._n = n
self._hypo_for_image = {}
self.ref_for_image = {} | [
"def",
"__init__",
"(",
"self",
",",
"n",
"=",
"4",
")",
":",
"# default compute Blue score up to 4",
"self",
".",
"_n",
"=",
"n",
"self",
".",
"_hypo_for_image",
"=",
"{",
"}",
"self",
".",
"ref_for_image",
"=",
"{",
"}"
] | https://github.com/aimagelab/meshed-memory-transformer/blob/e0fe3fae68091970407e82e5b907cbc423f25df2/evaluation/bleu/bleu.py#L15-L19 | ||||
kovidgoyal/calibre | 2b41671370f2a9eb1109b9ae901ccf915f1bd0c8 | src/calibre/utils/zipfile.py | python | ZipFile.setpassword | (self, pwd) | Set default password for encrypted files. | Set default password for encrypted files. | [
"Set",
"default",
"password",
"for",
"encrypted",
"files",
"."
] | def setpassword(self, pwd):
"""Set default password for encrypted files."""
self.pwd = pwd | [
"def",
"setpassword",
"(",
"self",
",",
"pwd",
")",
":",
"self",
".",
"pwd",
"=",
"pwd"
] | https://github.com/kovidgoyal/calibre/blob/2b41671370f2a9eb1109b9ae901ccf915f1bd0c8/src/calibre/utils/zipfile.py#L999-L1001 | ||
almarklein/visvis | 766ed97767b44a55a6ff72c742d7385e074d3d55 | vvmovie/images2swf.py | python | twitsToBits | (arr) | return bits | Given a few (signed) numbers, store them
as compactly as possible in the wat specifief by the swf format.
The numbers are multiplied by 20, assuming they
are twits.
Can be used to make the RECT record. | Given a few (signed) numbers, store them
as compactly as possible in the wat specifief by the swf format.
The numbers are multiplied by 20, assuming they
are twits.
Can be used to make the RECT record. | [
"Given",
"a",
"few",
"(",
"signed",
")",
"numbers",
"store",
"them",
"as",
"compactly",
"as",
"possible",
"in",
"the",
"wat",
"specifief",
"by",
"the",
"swf",
"format",
".",
"The",
"numbers",
"are",
"multiplied",
"by",
"20",
"assuming",
"they",
"are",
"t... | def twitsToBits(arr):
""" Given a few (signed) numbers, store them
as compactly as possible in the wat specifief by the swf format.
The numbers are multiplied by 20, assuming they
are twits.
Can be used to make the RECT record.
"""
# first determine length using non justified bit strings
maxlen = 1
for i in arr:
tmp = len(signedIntToBits(i*20))
if tmp > maxlen:
maxlen = tmp
# build array
bits = intToBits(maxlen, 5)
for i in arr:
bits += signedIntToBits(i * 20, maxlen)
return bits | [
"def",
"twitsToBits",
"(",
"arr",
")",
":",
"# first determine length using non justified bit strings",
"maxlen",
"=",
"1",
"for",
"i",
"in",
"arr",
":",
"tmp",
"=",
"len",
"(",
"signedIntToBits",
"(",
"i",
"*",
"20",
")",
")",
"if",
"tmp",
">",
"maxlen",
... | https://github.com/almarklein/visvis/blob/766ed97767b44a55a6ff72c742d7385e074d3d55/vvmovie/images2swf.py#L364-L384 | |
bruinxiong/SENet.mxnet | 5f0b4691c3df326c81284b93b7f5083aa5824dd5 | symbol_se_resnet.py | python | residual_unit | (data, num_filter, ratio, stride, dim_match, name, bottle_neck=True, bn_mom=0.9, workspace=512, memonger=False) | Return ResNet Unit symbol for building ResNet
Parameters
----------
data : str
Input data
num_filter : int
Number of output channels
bnf : int
Bottle neck channels factor with regard to num_filter
stride : tupe
Stride used in convolution
dim_match : Boolen
True means channel number between input and output is the same, otherwise means differ
name : str
Base name of the operators
workspace : int
Workspace used in convolution operator | Return ResNet Unit symbol for building ResNet
Parameters
----------
data : str
Input data
num_filter : int
Number of output channels
bnf : int
Bottle neck channels factor with regard to num_filter
stride : tupe
Stride used in convolution
dim_match : Boolen
True means channel number between input and output is the same, otherwise means differ
name : str
Base name of the operators
workspace : int
Workspace used in convolution operator | [
"Return",
"ResNet",
"Unit",
"symbol",
"for",
"building",
"ResNet",
"Parameters",
"----------",
"data",
":",
"str",
"Input",
"data",
"num_filter",
":",
"int",
"Number",
"of",
"output",
"channels",
"bnf",
":",
"int",
"Bottle",
"neck",
"channels",
"factor",
"with... | def residual_unit(data, num_filter, ratio, stride, dim_match, name, bottle_neck=True, bn_mom=0.9, workspace=512, memonger=False):
"""Return ResNet Unit symbol for building ResNet
Parameters
----------
data : str
Input data
num_filter : int
Number of output channels
bnf : int
Bottle neck channels factor with regard to num_filter
stride : tupe
Stride used in convolution
dim_match : Boolen
True means channel number between input and output is the same, otherwise means differ
name : str
Base name of the operators
workspace : int
Workspace used in convolution operator
"""
if bottle_neck:
# the same as https://github.com/facebook/fb.resnet.torch#notes, a bit difference with origin paper
bn1 = mx.sym.BatchNorm(data=data, fix_gamma=False, eps=2e-5, momentum=bn_mom, name=name + '_bn1')
act1 = mx.sym.Activation(data=bn1, act_type='relu', name=name + '_relu1')
conv1 = mx.sym.Convolution(data=act1, num_filter=int(num_filter*0.25), kernel=(1,1), stride=(1,1), pad=(0,0),
no_bias=True, workspace=workspace, name=name + '_conv1')
bn2 = mx.sym.BatchNorm(data=conv1, fix_gamma=False, eps=2e-5, momentum=bn_mom, name=name + '_bn2')
act2 = mx.sym.Activation(data=bn2, act_type='relu', name=name + '_relu2')
conv2 = mx.sym.Convolution(data=act2, num_filter=int(num_filter*0.25), kernel=(3,3), stride=stride, pad=(1,1),
no_bias=True, workspace=workspace, name=name + '_conv2')
bn3 = mx.sym.BatchNorm(data=conv2, fix_gamma=False, eps=2e-5, momentum=bn_mom, name=name + '_bn3')
act3 = mx.sym.Activation(data=bn3, act_type='relu', name=name + '_relu3')
conv3 = mx.sym.Convolution(data=act3, num_filter=num_filter, kernel=(1,1), stride=(1,1), pad=(0,0), no_bias=True,
workspace=workspace, name=name + '_conv3')
squeeze = mx.sym.Pooling(data=conv3, global_pool=True, kernel=(7, 7), pool_type='avg', name=name + '_squeeze')
squeeze = mx.symbol.Flatten(data=squeeze, name=name + '_flatten')
excitation = mx.symbol.FullyConnected(data=squeeze, num_hidden=int(num_filter*ratio), name=name + '_excitation1')
excitation = mx.sym.Activation(data=excitation, act_type='relu', name=name + '_excitation1_relu')
excitation = mx.symbol.FullyConnected(data=excitation, num_hidden=num_filter, name=name + '_excitation2')
excitation = mx.sym.Activation(data=excitation, act_type='sigmoid', name=name + '_excitation2_sigmoid')
conv3 = mx.symbol.broadcast_mul(conv3, mx.symbol.reshape(data=excitation, shape=(-1, num_filter, 1, 1)))
if dim_match:
shortcut = data
else:
shortcut = mx.sym.Convolution(data=act1, num_filter=num_filter, kernel=(1,1), stride=stride, no_bias=True,
workspace=workspace, name=name+'_sc')
if memonger:
shortcut._set_attr(mirror_stage='True')
return conv3 + shortcut
else:
bn1 = mx.sym.BatchNorm(data=data, fix_gamma=False, momentum=bn_mom, eps=2e-5, name=name + '_bn1')
act1 = mx.sym.Activation(data=bn1, act_type='relu', name=name + '_relu1')
conv1 = mx.sym.Convolution(data=act1, num_filter=num_filter, kernel=(3,3), stride=stride, pad=(1,1),
no_bias=True, workspace=workspace, name=name + '_conv1')
bn2 = mx.sym.BatchNorm(data=conv1, fix_gamma=False, momentum=bn_mom, eps=2e-5, name=name + '_bn2')
act2 = mx.sym.Activation(data=bn2, act_type='relu', name=name + '_relu2')
conv2 = mx.sym.Convolution(data=act2, num_filter=num_filter, kernel=(3,3), stride=(1,1), pad=(1,1),
no_bias=True, workspace=workspace, name=name + '_conv2')
squeeze = mx.sym.Pooling(data=conv2, global_pool=True, kernel=(7, 7), pool_type='avg', name=name + '_squeeze')
squeeze = mx.symbol.Flatten(data=squeeze, name=name + '_flatten')
excitation = mx.symbol.FullyConnected(data=squeeze, num_hidden=int(num_filter*ratio), name=name + '_excitation1')
excitation = mx.sym.Activation(data=excitation, act_type='relu', name=name + '_excitation1_relu')
excitation = mx.symbol.FullyConnected(data=excitation, num_hidden=num_filter, name=name + '_excitation2')
excitation = mx.sym.Activation(data=excitation, act_type='sigmoid', name=name + '_excitation2_sigmoid')
conv2 = mx.symbol.broadcast_mul(conv2, mx.symbol.reshape(data=excitation, shape=(-1, num_filter, 1, 1)))
if dim_match:
shortcut = data
else:
shortcut = mx.sym.Convolution(data=act1, num_filter=num_filter, kernel=(1,1), stride=stride, no_bias=True,
workspace=workspace, name=name+'_sc')
if memonger:
shortcut._set_attr(mirror_stage='True')
return conv2 + shortcut | [
"def",
"residual_unit",
"(",
"data",
",",
"num_filter",
",",
"ratio",
",",
"stride",
",",
"dim_match",
",",
"name",
",",
"bottle_neck",
"=",
"True",
",",
"bn_mom",
"=",
"0.9",
",",
"workspace",
"=",
"512",
",",
"memonger",
"=",
"False",
")",
":",
"if",... | https://github.com/bruinxiong/SENet.mxnet/blob/5f0b4691c3df326c81284b93b7f5083aa5824dd5/symbol_se_resnet.py#L11-L86 | ||
rtqichen/torchdiffeq | 5a819e471c15cac5e4ec97a0e472b1569a1a872b | torchdiffeq/_impl/solvers.py | python | FixedGridODESolver.integrate_until_event | (self, t0, event_fn) | return event_time, solution | [] | def integrate_until_event(self, t0, event_fn):
assert self.step_size is not None, "Event handling for fixed step solvers currently requires `step_size` to be provided in options."
t0 = t0.type_as(self.y0)
y0 = self.y0
dt = self.step_size
sign0 = torch.sign(event_fn(t0, y0))
max_itrs = 20000
itr = 0
while True:
itr += 1
t1 = t0 + dt
dy, f0 = self._step_func(self.func, t0, dt, t1, y0)
y1 = y0 + dy
sign1 = torch.sign(event_fn(t1, y1))
if sign0 != sign1:
if self.interp == "linear":
interp_fn = lambda t: self._linear_interp(t0, t1, y0, y1, t)
elif self.interp == "cubic":
f1 = self.func(t1, y1)
interp_fn = lambda t: self._cubic_hermite_interp(t0, y0, f0, t1, y1, f1, t)
else:
raise ValueError(f"Unknown interpolation method {self.interp}")
event_time, y1 = find_event(interp_fn, sign0, t0, t1, event_fn, float(self.atol))
break
else:
t0, y0 = t1, y1
if itr >= max_itrs:
raise RuntimeError(f"Reached maximum number of iterations {max_itrs}.")
solution = torch.stack([self.y0, y1], dim=0)
return event_time, solution | [
"def",
"integrate_until_event",
"(",
"self",
",",
"t0",
",",
"event_fn",
")",
":",
"assert",
"self",
".",
"step_size",
"is",
"not",
"None",
",",
"\"Event handling for fixed step solvers currently requires `step_size` to be provided in options.\"",
"t0",
"=",
"t0",
".",
... | https://github.com/rtqichen/torchdiffeq/blob/5a819e471c15cac5e4ec97a0e472b1569a1a872b/torchdiffeq/_impl/solvers.py#L121-L155 | |||
home-assistant/core | 265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1 | homeassistant/components/directv/entity.py | python | DIRECTVEntity.__init__ | (self, *, dtv: DIRECTV, address: str = "0") | Initialize the DirecTV entity. | Initialize the DirecTV entity. | [
"Initialize",
"the",
"DirecTV",
"entity",
"."
] | def __init__(self, *, dtv: DIRECTV, address: str = "0") -> None:
"""Initialize the DirecTV entity."""
self._address = address
self._device_id = address if address != "0" else dtv.device.info.receiver_id
self._is_client = address != "0"
self.dtv = dtv | [
"def",
"__init__",
"(",
"self",
",",
"*",
",",
"dtv",
":",
"DIRECTV",
",",
"address",
":",
"str",
"=",
"\"0\"",
")",
"->",
"None",
":",
"self",
".",
"_address",
"=",
"address",
"self",
".",
"_device_id",
"=",
"address",
"if",
"address",
"!=",
"\"0\""... | https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/directv/entity.py#L14-L19 | ||
nfstream/nfstream | aa14fd1606ce4757f8b1589faeb032a0f5a93c5e | nfstream/plugin.py | python | NFPlugin.on_update | (self, packet, flow) | on_update(self, obs, flow): Method called to update each flow with its belonging packet.
Example: -------------------------------------------------------
if packet.raw_size == 40:
flow.udps.packet_40_count += 1
---------------------------------------------------------------- | on_update(self, obs, flow): Method called to update each flow with its belonging packet.
Example: -------------------------------------------------------
if packet.raw_size == 40:
flow.udps.packet_40_count += 1
---------------------------------------------------------------- | [
"on_update",
"(",
"self",
"obs",
"flow",
")",
":",
"Method",
"called",
"to",
"update",
"each",
"flow",
"with",
"its",
"belonging",
"packet",
".",
"Example",
":",
"-------------------------------------------------------",
"if",
"packet",
".",
"raw_size",
"==",
"40"... | def on_update(self, packet, flow):
"""
on_update(self, obs, flow): Method called to update each flow with its belonging packet.
Example: -------------------------------------------------------
if packet.raw_size == 40:
flow.udps.packet_40_count += 1
----------------------------------------------------------------
""" | [
"def",
"on_update",
"(",
"self",
",",
"packet",
",",
"flow",
")",
":"
] | https://github.com/nfstream/nfstream/blob/aa14fd1606ce4757f8b1589faeb032a0f5a93c5e/nfstream/plugin.py#L40-L47 | ||
zhl2008/awd-platform | 0416b31abea29743387b10b3914581fbe8e7da5e | web_flaskbb/lib/python2.7/site-packages/sqlalchemy/dialects/mysql/enumerated.py | python | _EnumeratedValues._strip_values | (cls, values) | return strip_values | [] | def _strip_values(cls, values):
strip_values = []
for a in values:
if a[0:1] == '"' or a[0:1] == "'":
# strip enclosing quotes and unquote interior
a = a[1:-1].replace(a[0] * 2, a[0])
strip_values.append(a)
return strip_values | [
"def",
"_strip_values",
"(",
"cls",
",",
"values",
")",
":",
"strip_values",
"=",
"[",
"]",
"for",
"a",
"in",
"values",
":",
"if",
"a",
"[",
"0",
":",
"1",
"]",
"==",
"'\"'",
"or",
"a",
"[",
"0",
":",
"1",
"]",
"==",
"\"'\"",
":",
"# strip encl... | https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/sqlalchemy/dialects/mysql/enumerated.py#L48-L55 | |||
linxid/Machine_Learning_Study_Path | 558e82d13237114bbb8152483977806fc0c222af | Machine Learning In Action/Chapter5-LogisticRegression/venv/Lib/site-packages/pip/_vendor/packaging/specifiers.py | python | _IndividualSpecifier.prereleases | (self, value) | [] | def prereleases(self, value):
self._prereleases = value | [
"def",
"prereleases",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"_prereleases",
"=",
"value"
] | https://github.com/linxid/Machine_Learning_Study_Path/blob/558e82d13237114bbb8152483977806fc0c222af/Machine Learning In Action/Chapter5-LogisticRegression/venv/Lib/site-packages/pip/_vendor/packaging/specifiers.py#L157-L158 | ||||
saltstack/salt | fae5bc757ad0f1716483ce7ae180b451545c2058 | salt/cloud/clouds/packet.py | python | __virtual__ | () | return __virtualname__ | Check for Packet configs. | Check for Packet configs. | [
"Check",
"for",
"Packet",
"configs",
"."
] | def __virtual__():
"""
Check for Packet configs.
"""
if HAS_PACKET is False:
return False, "The packet python library is not installed"
if get_configured_provider() is False:
return False
return __virtualname__ | [
"def",
"__virtual__",
"(",
")",
":",
"if",
"HAS_PACKET",
"is",
"False",
":",
"return",
"False",
",",
"\"The packet python library is not installed\"",
"if",
"get_configured_provider",
"(",
")",
"is",
"False",
":",
"return",
"False",
"return",
"__virtualname__"
] | https://github.com/saltstack/salt/blob/fae5bc757ad0f1716483ce7ae180b451545c2058/salt/cloud/clouds/packet.py#L83-L92 | |
openstack/swift | b8d7c3dcb817504dcc0959ba52cc4ed2cf66c100 | swift/common/middleware/recon.py | python | ReconMiddleware.get_mounted | (self, openr=open) | return mounts | get ALL mounted fs from /proc/mounts | get ALL mounted fs from /proc/mounts | [
"get",
"ALL",
"mounted",
"fs",
"from",
"/",
"proc",
"/",
"mounts"
] | def get_mounted(self, openr=open):
"""get ALL mounted fs from /proc/mounts"""
mounts = []
with openr('/proc/mounts', 'r') as procmounts:
for line in procmounts:
mount = {}
mount['device'], mount['path'], opt1, opt2, opt3, \
opt4 = line.rstrip().split()
mounts.append(mount)
return mounts | [
"def",
"get_mounted",
"(",
"self",
",",
"openr",
"=",
"open",
")",
":",
"mounts",
"=",
"[",
"]",
"with",
"openr",
"(",
"'/proc/mounts'",
",",
"'r'",
")",
"as",
"procmounts",
":",
"for",
"line",
"in",
"procmounts",
":",
"mount",
"=",
"{",
"}",
"mount"... | https://github.com/openstack/swift/blob/b8d7c3dcb817504dcc0959ba52cc4ed2cf66c100/swift/common/middleware/recon.py#L104-L113 | |
lspvic/CopyNet | 2cc44dd672115fe88a2d76bd59b76fb2d7389bb4 | nmt/nmt/gnmt_model.py | python | GNMTAttentionMultiCell.__call__ | (self, inputs, state, scope=None) | return cur_inp, tuple(new_states) | Run the cell with bottom layer's attention copied to all upper layers. | Run the cell with bottom layer's attention copied to all upper layers. | [
"Run",
"the",
"cell",
"with",
"bottom",
"layer",
"s",
"attention",
"copied",
"to",
"all",
"upper",
"layers",
"."
] | def __call__(self, inputs, state, scope=None):
"""Run the cell with bottom layer's attention copied to all upper layers."""
if not nest.is_sequence(state):
raise ValueError(
"Expected state to be a tuple of length %d, but received: %s"
% (len(self.state_size), state))
with tf.variable_scope(scope or "multi_rnn_cell"):
new_states = []
with tf.variable_scope("cell_0_attention"):
attention_cell = self._cells[0]
attention_state = state[0]
cur_inp, new_attention_state = attention_cell(inputs, attention_state)
new_states.append(new_attention_state)
for i in range(1, len(self._cells)):
with tf.variable_scope("cell_%d" % i):
cell = self._cells[i]
cur_state = state[i]
if self.use_new_attention:
cur_inp = tf.concat([cur_inp, new_attention_state.attention], -1)
else:
cur_inp = tf.concat([cur_inp, attention_state.attention], -1)
cur_inp, new_state = cell(cur_inp, cur_state)
new_states.append(new_state)
return cur_inp, tuple(new_states) | [
"def",
"__call__",
"(",
"self",
",",
"inputs",
",",
"state",
",",
"scope",
"=",
"None",
")",
":",
"if",
"not",
"nest",
".",
"is_sequence",
"(",
"state",
")",
":",
"raise",
"ValueError",
"(",
"\"Expected state to be a tuple of length %d, but received: %s\"",
"%",... | https://github.com/lspvic/CopyNet/blob/2cc44dd672115fe88a2d76bd59b76fb2d7389bb4/nmt/nmt/gnmt_model.py#L232-L262 | |
NVIDIA/NeMo | 5b0c0b4dec12d87d3cd960846de4105309ce938e | nemo/collections/cv/datasets/mnist_dataset.py | python | MNISTDataset.__getitem__ | (self, index: int) | return index, img, target, self._ix_to_word[target] | Returns a single sample.
Args:
index: index of the sample to return. | Returns a single sample. | [
"Returns",
"a",
"single",
"sample",
"."
] | def __getitem__(self, index: int):
"""
Returns a single sample.
Args:
index: index of the sample to return.
"""
# Get image and target.
img, target = self._dataset.__getitem__(index)
# Return sample.
return index, img, target, self._ix_to_word[target] | [
"def",
"__getitem__",
"(",
"self",
",",
"index",
":",
"int",
")",
":",
"# Get image and target.",
"img",
",",
"target",
"=",
"self",
".",
"_dataset",
".",
"__getitem__",
"(",
"index",
")",
"# Return sample.",
"return",
"index",
",",
"img",
",",
"target",
"... | https://github.com/NVIDIA/NeMo/blob/5b0c0b4dec12d87d3cd960846de4105309ce938e/nemo/collections/cv/datasets/mnist_dataset.py#L114-L125 | |
microsoft/ptvsd | 99c8513921021d2cc7cd82e132b65c644c256768 | src/ptvsd/_vendored/pydevd/pydevd_attach_to_process/winappdbg/sql.py | python | CrashDAO.find_by_example | (self, crash, offset = None, limit = None) | Find all crash dumps that have common properties with the crash dump
provided.
Results can be paged to avoid consuming too much memory if the database
is large.
@see: L{find}
@type crash: L{Crash}
@param crash: Crash object to compare with. Fields set to C{None} are
ignored, all other fields but the signature are used in the
comparison.
To search for signature instead use the L{find} method.
@type offset: int
@param offset: (Optional) Skip the first I{offset} results.
@type limit: int
@param limit: (Optional) Return at most I{limit} results.
@rtype: list(L{Crash})
@return: List of similar crash dumps found. | Find all crash dumps that have common properties with the crash dump
provided. | [
"Find",
"all",
"crash",
"dumps",
"that",
"have",
"common",
"properties",
"with",
"the",
"crash",
"dump",
"provided",
"."
] | def find_by_example(self, crash, offset = None, limit = None):
"""
Find all crash dumps that have common properties with the crash dump
provided.
Results can be paged to avoid consuming too much memory if the database
is large.
@see: L{find}
@type crash: L{Crash}
@param crash: Crash object to compare with. Fields set to C{None} are
ignored, all other fields but the signature are used in the
comparison.
To search for signature instead use the L{find} method.
@type offset: int
@param offset: (Optional) Skip the first I{offset} results.
@type limit: int
@param limit: (Optional) Return at most I{limit} results.
@rtype: list(L{Crash})
@return: List of similar crash dumps found.
"""
# Validate the parameters.
if limit is not None and not limit:
warnings.warn("CrashDAO.find_by_example() was set a limit of 0"
" results, returning without executing a query.")
return []
# Build the query.
query = self._session.query(CrashDTO)
# Order by row ID to get consistent results.
# Also some database engines require ordering when using offsets.
query = query.asc(CrashDTO.id)
# Build a CrashDTO from the Crash object.
dto = CrashDTO(crash)
# Filter all the fields in the crashes table that are present in the
# CrashDTO object and not set to None, except for the row ID.
for name, column in compat.iteritems(CrashDTO.__dict__):
if not name.startswith('__') and name not in ('id',
'signature',
'data'):
if isinstance(column, Column):
value = getattr(dto, name, None)
if value is not None:
query = query.filter(column == value)
# Page the query.
if offset:
query = query.offset(offset)
if limit:
query = query.limit(limit)
# Execute the SQL query and convert the results.
try:
return [dto.toCrash() for dto in query.all()]
except NoResultFound:
return [] | [
"def",
"find_by_example",
"(",
"self",
",",
"crash",
",",
"offset",
"=",
"None",
",",
"limit",
"=",
"None",
")",
":",
"# Validate the parameters.",
"if",
"limit",
"is",
"not",
"None",
"and",
"not",
"limit",
":",
"warnings",
".",
"warn",
"(",
"\"CrashDAO.fi... | https://github.com/microsoft/ptvsd/blob/99c8513921021d2cc7cd82e132b65c644c256768/src/ptvsd/_vendored/pydevd/pydevd_attach_to_process/winappdbg/sql.py#L898-L962 | ||
edwardlib/observations | 2c8b1ac31025938cb17762e540f2f592e302d5de | observations/r/sleep75.py | python | sleep75 | (path) | return x_train, metadata | sleep75
Data loads lazily. Type data(sleep75) into the console.
A data.frame with 706 rows and 34 variables:
- age. in years
- black. =1 if black
- case. identifier
- clerical. =1 if clerical worker
- construc. =1 if construction worker
- educ. years of schooling
- earns74. total earnings, 1974
- gdhlth. =1 if in good or excel. health
- inlf. =1 if in labor force
- leis1. sleep - totwrk
- leis2. slpnaps - totwrk
- leis3. rlxall - totwrk
- smsa. =1 if live in smsa
- lhrwage. log hourly wage
- lothinc. log othinc, unless othinc < 0
- male. =1 if male
- marr. =1 if married
- prot. =1 if Protestant
- rlxall. slpnaps + personal activs
- selfe. =1 if self employed
- sleep. mins sleep at night, per wk
- slpnaps. minutes sleep, inc. naps
- south. =1 if live in south
- spsepay. spousal wage income
- spwrk75. =1 if spouse works
- totwrk. mins worked per week
- union. =1 if belong to union
- worknrm. mins work main job
- workscnd. mins work second job
- exper. age - educ - 6
- yngkid. =1 if children < 3 present
- yrsmarr. years married
- hrwage. hourly wage
- agesq. age^2
https://www.cengage.com/cgi-wadsworth/course_products_wp.pl?fid=M20b&product_
isbn_issn=9781111531041
Args:
path: str.
Path to directory which either stores file or otherwise file will
be downloaded and extracted there.
Filename is `sleep75.csv`.
Returns:
Tuple of np.ndarray `x_train` with 706 rows and 34 columns and
dictionary `metadata` of column headers (feature names). | sleep75 | [
"sleep75"
] | def sleep75(path):
"""sleep75
Data loads lazily. Type data(sleep75) into the console.
A data.frame with 706 rows and 34 variables:
- age. in years
- black. =1 if black
- case. identifier
- clerical. =1 if clerical worker
- construc. =1 if construction worker
- educ. years of schooling
- earns74. total earnings, 1974
- gdhlth. =1 if in good or excel. health
- inlf. =1 if in labor force
- leis1. sleep - totwrk
- leis2. slpnaps - totwrk
- leis3. rlxall - totwrk
- smsa. =1 if live in smsa
- lhrwage. log hourly wage
- lothinc. log othinc, unless othinc < 0
- male. =1 if male
- marr. =1 if married
- prot. =1 if Protestant
- rlxall. slpnaps + personal activs
- selfe. =1 if self employed
- sleep. mins sleep at night, per wk
- slpnaps. minutes sleep, inc. naps
- south. =1 if live in south
- spsepay. spousal wage income
- spwrk75. =1 if spouse works
- totwrk. mins worked per week
- union. =1 if belong to union
- worknrm. mins work main job
- workscnd. mins work second job
- exper. age - educ - 6
- yngkid. =1 if children < 3 present
- yrsmarr. years married
- hrwage. hourly wage
- agesq. age^2
https://www.cengage.com/cgi-wadsworth/course_products_wp.pl?fid=M20b&product_
isbn_issn=9781111531041
Args:
path: str.
Path to directory which either stores file or otherwise file will
be downloaded and extracted there.
Filename is `sleep75.csv`.
Returns:
Tuple of np.ndarray `x_train` with 706 rows and 34 columns and
dictionary `metadata` of column headers (feature names).
"""
import pandas as pd
path = os.path.expanduser(path)
filename = 'sleep75.csv'
if not os.path.exists(os.path.join(path, filename)):
url = 'http://dustintran.com/data/r/wooldridge/sleep75.csv'
maybe_download_and_extract(path, url,
save_file_name='sleep75.csv',
resume=False)
data = pd.read_csv(os.path.join(path, filename), index_col=0,
parse_dates=True)
x_train = data.values
metadata = {'columns': data.columns}
return x_train, metadata | [
"def",
"sleep75",
"(",
"path",
")",
":",
"import",
"pandas",
"as",
"pd",
"path",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"path",
")",
"filename",
"=",
"'sleep75.csv'",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
"... | https://github.com/edwardlib/observations/blob/2c8b1ac31025938cb17762e540f2f592e302d5de/observations/r/sleep75.py#L14-L117 | |
Source-Python-Dev-Team/Source.Python | d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb | addons/source-python/Python3/telnetlib.py | python | Telnet.listener | (self) | Helper for mt_interact() -- this executes in the other thread. | Helper for mt_interact() -- this executes in the other thread. | [
"Helper",
"for",
"mt_interact",
"()",
"--",
"this",
"executes",
"in",
"the",
"other",
"thread",
"."
] | def listener(self):
"""Helper for mt_interact() -- this executes in the other thread."""
while 1:
try:
data = self.read_eager()
except EOFError:
print('*** Connection closed by remote host ***')
return
if data:
sys.stdout.write(data.decode('ascii'))
else:
sys.stdout.flush() | [
"def",
"listener",
"(",
"self",
")",
":",
"while",
"1",
":",
"try",
":",
"data",
"=",
"self",
".",
"read_eager",
"(",
")",
"except",
"EOFError",
":",
"print",
"(",
"'*** Connection closed by remote host ***'",
")",
"return",
"if",
"data",
":",
"sys",
".",
... | https://github.com/Source-Python-Dev-Team/Source.Python/blob/d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb/addons/source-python/Python3/telnetlib.py#L571-L582 | ||
nltk/nltk_contrib | c9da2c29777ca9df650740145f1f4a375ccac961 | nltk_contrib/tiger/query/tsqlparser.py | python | surround | (left, expr, right) | return suppressed_literal(left) + expr + suppressed_literal(right) | Circumfixes the expression `expr` with `left` and `right`.
Both `left` and `right` will be turned into suppressed literals.
*Parameters*:
`left`
the left part of the circumfix
`expr`
the grammar expression to be circumfixed
`right`
the right part of the circumfix | Circumfixes the expression `expr` with `left` and `right`.
Both `left` and `right` will be turned into suppressed literals.
*Parameters*:
`left`
the left part of the circumfix
`expr`
the grammar expression to be circumfixed
`right`
the right part of the circumfix | [
"Circumfixes",
"the",
"expression",
"expr",
"with",
"left",
"and",
"right",
".",
"Both",
"left",
"and",
"right",
"will",
"be",
"turned",
"into",
"suppressed",
"literals",
".",
"*",
"Parameters",
"*",
":",
"left",
"the",
"left",
"part",
"of",
"the",
"circum... | def surround(left, expr, right):
"""Circumfixes the expression `expr` with `left` and `right`.
Both `left` and `right` will be turned into suppressed literals.
*Parameters*:
`left`
the left part of the circumfix
`expr`
the grammar expression to be circumfixed
`right`
the right part of the circumfix
"""
return suppressed_literal(left) + expr + suppressed_literal(right) | [
"def",
"surround",
"(",
"left",
",",
"expr",
",",
"right",
")",
":",
"return",
"suppressed_literal",
"(",
"left",
")",
"+",
"expr",
"+",
"suppressed_literal",
"(",
"right",
")"
] | https://github.com/nltk/nltk_contrib/blob/c9da2c29777ca9df650740145f1f4a375ccac961/nltk_contrib/tiger/query/tsqlparser.py#L85-L98 | |
plkmo/BERT-Relation-Extraction | 06075620fccb044785f5fd319e8d06df9af15b50 | src/model/ALBERT/modeling_utils.py | python | PreTrainedModel.get_output_embeddings | (self) | return None | Returns the model's output embeddings.
Returns:
:obj:`nn.Module`:
A torch module mapping hidden states to vocabulary. | Returns the model's output embeddings. | [
"Returns",
"the",
"model",
"s",
"output",
"embeddings",
"."
] | def get_output_embeddings(self):
"""
Returns the model's output embeddings.
Returns:
:obj:`nn.Module`:
A torch module mapping hidden states to vocabulary.
"""
return None | [
"def",
"get_output_embeddings",
"(",
"self",
")",
":",
"return",
"None"
] | https://github.com/plkmo/BERT-Relation-Extraction/blob/06075620fccb044785f5fd319e8d06df9af15b50/src/model/ALBERT/modeling_utils.py#L144-L152 | |
jjhelmus/nmrglue | f47397dcda84854d2136395a9998fe0b57356cbf | nmrglue/fileio/sparky.py | python | get_data | (f) | return np.frombuffer(f.read(), dtype='>f4') | Read all data from sparky file object. | Read all data from sparky file object. | [
"Read",
"all",
"data",
"from",
"sparky",
"file",
"object",
"."
] | def get_data(f):
"""
Read all data from sparky file object.
"""
return np.frombuffer(f.read(), dtype='>f4') | [
"def",
"get_data",
"(",
"f",
")",
":",
"return",
"np",
".",
"frombuffer",
"(",
"f",
".",
"read",
"(",
")",
",",
"dtype",
"=",
"'>f4'",
")"
] | https://github.com/jjhelmus/nmrglue/blob/f47397dcda84854d2136395a9998fe0b57356cbf/nmrglue/fileio/sparky.py#L1309-L1313 | |
sagemath/sage | f9b2db94f675ff16963ccdefba4f1a3393b3fe0d | src/sage/groups/matrix_gps/isometries.py | python | GroupActionOnQuotientModule._act_ | (self, g, a) | return a.parent()(b) | r"""
This defines the group action.
INPUT:
- ``g`` -- an element of the acting group
- ``a`` -- an element of the invariant submodule
OUTPUT:
- an element of the invariant quotient module
EXAMPLES::
sage: from sage.groups.matrix_gps.isometries import GroupActionOnQuotientModule
sage: S = span(ZZ,[[0,1]])
sage: Q = S/(6*S)
sage: g = Matrix(QQ,2,[1,1,0,7])
sage: G = MatrixGroup([g])
sage: A = GroupActionOnQuotientModule(G,Q)
sage: A
Right action by Matrix group over Rational Field with 1 generators (
[1 1]
[0 7]
) on Finitely generated module V/W over Integer Ring with invariants (6)
sage: q = Q.an_element()
sage: g = G.an_element()
sage: A(q,g).parent()
Finitely generated module V/W over Integer Ring with invariants (6) | r"""
This defines the group action. | [
"r",
"This",
"defines",
"the",
"group",
"action",
"."
] | def _act_(self, g, a):
r"""
This defines the group action.
INPUT:
- ``g`` -- an element of the acting group
- ``a`` -- an element of the invariant submodule
OUTPUT:
- an element of the invariant quotient module
EXAMPLES::
sage: from sage.groups.matrix_gps.isometries import GroupActionOnQuotientModule
sage: S = span(ZZ,[[0,1]])
sage: Q = S/(6*S)
sage: g = Matrix(QQ,2,[1,1,0,7])
sage: G = MatrixGroup([g])
sage: A = GroupActionOnQuotientModule(G,Q)
sage: A
Right action by Matrix group over Rational Field with 1 generators (
[1 1]
[0 7]
) on Finitely generated module V/W over Integer Ring with invariants (6)
sage: q = Q.an_element()
sage: g = G.an_element()
sage: A(q,g).parent()
Finitely generated module V/W over Integer Ring with invariants (6)
"""
if self.is_left():
b = g.matrix() * a.lift()
else:
b = a.lift() * g.matrix()
return a.parent()(b) | [
"def",
"_act_",
"(",
"self",
",",
"g",
",",
"a",
")",
":",
"if",
"self",
".",
"is_left",
"(",
")",
":",
"b",
"=",
"g",
".",
"matrix",
"(",
")",
"*",
"a",
".",
"lift",
"(",
")",
"else",
":",
"b",
"=",
"a",
".",
"lift",
"(",
")",
"*",
"g"... | https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/groups/matrix_gps/isometries.py#L399-L435 | |
tobegit3hub/deep_image_model | 8a53edecd9e00678b278bb10f6fb4bdb1e4ee25e | java_predict_client/src/main/proto/tensorflow/contrib/learn/python/learn/dataframe/transforms/binary_transforms.py | python | register_binary_op | (method_name, operation) | Registers `Series` member functions for binary operations.
Args:
method_name: the name of the method that will be created in `Series`.
operation: underlying TensorFlow operation. | Registers `Series` member functions for binary operations. | [
"Registers",
"Series",
"member",
"functions",
"for",
"binary",
"operations",
"."
] | def register_binary_op(method_name, operation):
"""Registers `Series` member functions for binary operations.
Args:
method_name: the name of the method that will be created in `Series`.
operation: underlying TensorFlow operation.
"""
# Define series-series `Transform`.
@property
def series_name(self):
return operation.__name__
series_doc = _DOC_FORMAT_STRING.format(operation.__name__, operation.__doc__)
def series_apply_op(self, x, y):
return operation(x, y)
series_transform_cls = type("scalar_{}".format(operation.__name__),
(SeriesBinaryTransform,),
{"name": series_name,
"__doc__": series_doc,
"_apply_op": series_apply_op})
# Define series-scalar `Transform`.
@property
def scalar_name(self):
return "scalar_{}".format(operation.__name__)
scalar_doc = _DOC_FORMAT_STRING.format(operation.__name__, operation.__doc__)
def scalar_apply_op(self, x):
return operation(x, self.scalar)
scalar_transform_cls = type("scalar_{}".format(operation.__name__),
(ScalarBinaryTransform,),
{"name": scalar_name,
"__doc__": scalar_doc,
"_apply_op": scalar_apply_op})
# Define function that delegates to the two `Transforms`.
def _fn(self, other, *args, **kwargs):
# pylint: disable=not-callable,abstract-class-instantiated
if isinstance(other, series.Series):
return series_transform_cls(*args, **kwargs)([self, other])[0]
return scalar_transform_cls(other, *args, **kwargs)([self])[0]
# Register new member function of `Series`.
setattr(series.Series, method_name, _fn) | [
"def",
"register_binary_op",
"(",
"method_name",
",",
"operation",
")",
":",
"# Define series-series `Transform`.",
"@",
"property",
"def",
"series_name",
"(",
"self",
")",
":",
"return",
"operation",
".",
"__name__",
"series_doc",
"=",
"_DOC_FORMAT_STRING",
".",
"f... | https://github.com/tobegit3hub/deep_image_model/blob/8a53edecd9e00678b278bb10f6fb4bdb1e4ee25e/java_predict_client/src/main/proto/tensorflow/contrib/learn/python/learn/dataframe/transforms/binary_transforms.py#L104-L152 | ||
openshift/openshift-ansible-contrib | cd17fa3c5b8cab87b2403bde3a560eadcdcd0955 | reference-architecture/aws-ansible/playbooks/library/redhat_subscription.py | python | Rhsm.is_registered | (self) | Determine whether the current system
Returns:
* Boolean - whether the current system is currently registered to
RHSM. | Determine whether the current system
Returns:
* Boolean - whether the current system is currently registered to
RHSM. | [
"Determine",
"whether",
"the",
"current",
"system",
"Returns",
":",
"*",
"Boolean",
"-",
"whether",
"the",
"current",
"system",
"is",
"currently",
"registered",
"to",
"RHSM",
"."
] | def is_registered(self):
'''
Determine whether the current system
Returns:
* Boolean - whether the current system is currently registered to
RHSM.
'''
# Quick version...
if False:
return os.path.isfile('/etc/pki/consumer/cert.pem') and \
os.path.isfile('/etc/pki/consumer/key.pem')
args = ['subscription-manager', 'identity']
rc, stdout, stderr = self.module.run_command(args, check_rc=False)
if rc == 0:
return True
else:
return False | [
"def",
"is_registered",
"(",
"self",
")",
":",
"# Quick version...",
"if",
"False",
":",
"return",
"os",
".",
"path",
".",
"isfile",
"(",
"'/etc/pki/consumer/cert.pem'",
")",
"and",
"os",
".",
"path",
".",
"isfile",
"(",
"'/etc/pki/consumer/key.pem'",
")",
"ar... | https://github.com/openshift/openshift-ansible-contrib/blob/cd17fa3c5b8cab87b2403bde3a560eadcdcd0955/reference-architecture/aws-ansible/playbooks/library/redhat_subscription.py#L264-L281 | ||
cloudera/hue | 23f02102d4547c17c32bd5ea0eb24e9eadd657a4 | desktop/core/ext-py/celery-4.2.1/celery/concurrency/asynpool.py | python | AsynPool.process_flush_queues | (self, proc) | Flush all queues.
Including the outbound buffer, so that
all tasks that haven't been started will be discarded.
In Celery this is called whenever the transport connection is lost
(consumer restart), and when a process is terminated. | Flush all queues. | [
"Flush",
"all",
"queues",
"."
] | def process_flush_queues(self, proc):
"""Flush all queues.
Including the outbound buffer, so that
all tasks that haven't been started will be discarded.
In Celery this is called whenever the transport connection is lost
(consumer restart), and when a process is terminated.
"""
resq = proc.outq._reader
on_state_change = self._result_handler.on_state_change
fds = {resq}
while fds and not resq.closed and self._state != TERMINATE:
readable, _, _ = _select(fds, None, fds, timeout=0.01)
if readable:
try:
task = resq.recv()
except (OSError, IOError, EOFError) as exc:
_errno = getattr(exc, 'errno', None)
if _errno == errno.EINTR:
continue
elif _errno == errno.EAGAIN:
break
elif _errno not in UNAVAIL:
debug('got %r while flushing process %r',
exc, proc, exc_info=1)
break
else:
if task is None:
debug('got sentinel while flushing process %r', proc)
break
else:
on_state_change(task)
else:
break | [
"def",
"process_flush_queues",
"(",
"self",
",",
"proc",
")",
":",
"resq",
"=",
"proc",
".",
"outq",
".",
"_reader",
"on_state_change",
"=",
"self",
".",
"_result_handler",
".",
"on_state_change",
"fds",
"=",
"{",
"resq",
"}",
"while",
"fds",
"and",
"not",... | https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/celery-4.2.1/celery/concurrency/asynpool.py#L1171-L1205 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.