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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
rembo10/headphones | b3199605be1ebc83a7a8feab6b1e99b64014187c | lib/mutagen/_util.py | python | is_fileobj | (fileobj) | return not isinstance(fileobj, (text_type, bytes)) | Returns:
bool: if an argument passed ot mutagen should be treated as a
file object | Returns:
bool: if an argument passed ot mutagen should be treated as a
file object | [
"Returns",
":",
"bool",
":",
"if",
"an",
"argument",
"passed",
"ot",
"mutagen",
"should",
"be",
"treated",
"as",
"a",
"file",
"object"
] | def is_fileobj(fileobj):
"""Returns:
bool: if an argument passed ot mutagen should be treated as a
file object
"""
# open() only handles str/bytes, so we can be strict
return not isinstance(fileobj, (text_type, bytes)) | [
"def",
"is_fileobj",
"(",
"fileobj",
")",
":",
"# open() only handles str/bytes, so we can be strict",
"return",
"not",
"isinstance",
"(",
"fileobj",
",",
"(",
"text_type",
",",
"bytes",
")",
")"
] | https://github.com/rembo10/headphones/blob/b3199605be1ebc83a7a8feab6b1e99b64014187c/lib/mutagen/_util.py#L36-L43 | |
zhl2008/awd-platform | 0416b31abea29743387b10b3914581fbe8e7da5e | web_flaskbb/lib/python2.7/site-packages/pygments/lexers/lisp.py | python | ShenLexer._relevant | (self, token) | return token not in (Text, Comment.Single, Comment.Multiline) | [] | def _relevant(self, token):
return token not in (Text, Comment.Single, Comment.Multiline) | [
"def",
"_relevant",
"(",
"self",
",",
"token",
")",
":",
"return",
"token",
"not",
"in",
"(",
"Text",
",",
"Comment",
".",
"Single",
",",
"Comment",
".",
"Multiline",
")"
] | https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/pygments/lexers/lisp.py#L2269-L2270 | |||
PaddlePaddle/PaddleClas | d089b69869b24b3051d200048979e17d4775624e | ppcls/utils/model_zoo.py | python | _download | (url, path) | return fullname | Download from url, save to path.
url (str): download url
path (str): download to given path | Download from url, save to path.
url (str): download url
path (str): download to given path | [
"Download",
"from",
"url",
"save",
"to",
"path",
".",
"url",
"(",
"str",
")",
":",
"download",
"url",
"path",
"(",
"str",
")",
":",
"download",
"to",
"given",
"path"
] | def _download(url, path):
"""
Download from url, save to path.
url (str): download url
path (str): download to given path
"""
if not os.path.exists(path):
os.makedirs(path)
fname = os.path.split(url)[-1]
fullname = os.path.join(path, fname)
retry_cnt = 0
while not os.path.exists(fullname):
if retry_cnt < DOWNLOAD_RETRY_LIMIT:
retry_cnt += 1
else:
raise RetryError(url, DOWNLOAD_RETRY_LIMIT)
logger.info("Downloading {} from {}".format(fname, url))
req = requests.get(url, stream=True)
if req.status_code != 200:
raise UrlError(url, req.status_code)
# For protecting download interupted, download to
# tmp_fullname firstly, move tmp_fullname to fullname
# after download finished
tmp_fullname = fullname + "_tmp"
total_size = req.headers.get('content-length')
with open(tmp_fullname, 'wb') as f:
if total_size:
for chunk in tqdm.tqdm(
req.iter_content(chunk_size=1024),
total=(int(total_size) + 1023) // 1024,
unit='KB'):
f.write(chunk)
else:
for chunk in req.iter_content(chunk_size=1024):
if chunk:
f.write(chunk)
shutil.move(tmp_fullname, fullname)
return fullname | [
"def",
"_download",
"(",
"url",
",",
"path",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"os",
".",
"makedirs",
"(",
"path",
")",
"fname",
"=",
"os",
".",
"path",
".",
"split",
"(",
"url",
")",
"[",
"-",
"1... | https://github.com/PaddlePaddle/PaddleClas/blob/d089b69869b24b3051d200048979e17d4775624e/ppcls/utils/model_zoo.py#L90-L133 | |
ladybug-tools/butterfly | c8fc0bbe317bb41bfe5f28305782a82347b8c776 | butterfly/grading.py | python | Grading.duplicate | (self) | return deepcopy(self) | Return a copy of this object. | Return a copy of this object. | [
"Return",
"a",
"copy",
"of",
"this",
"object",
"."
] | def duplicate(self):
"""Return a copy of this object."""
return deepcopy(self) | [
"def",
"duplicate",
"(",
"self",
")",
":",
"return",
"deepcopy",
"(",
"self",
")"
] | https://github.com/ladybug-tools/butterfly/blob/c8fc0bbe317bb41bfe5f28305782a82347b8c776/butterfly/grading.py#L193-L195 | |
raymontag/keepassc | 3a3c7ef7b3ee1ceb16b613176d54dad89c0408df | keepassc/control.py | python | Control.__init__ | (self) | The __init__-method.
It just initializes some variables and settings and changes
the working directory to /var/empty to prevent coredumps as
normal user. | The __init__-method. | [
"The",
"__init__",
"-",
"method",
"."
] | def __init__(self):
'''The __init__-method.
It just initializes some variables and settings and changes
the working directory to /var/empty to prevent coredumps as
normal user.
'''
try:
self.config_home = realpath(expanduser(getenv('XDG_CONFIG_HOME')))
except:
self.config_home = realpath(expanduser('~/.config'))
finally:
self.config_home = join(self.config_home, 'keepassc', 'config')
try:
self.data_home = realpath(expanduser(getenv('XDG_DATA_HOME')))
except:
self.data_home = realpath(expanduser('~/.local/share/'))
finally:
self.data_home = join(self.data_home, 'keepassc')
self.last_home = join(self.data_home, 'last')
self.remote_home = join(self.data_home, 'remote')
self.key_home = join(self.data_home, 'key')
self.config = parse_config(self)
if self.config['rem_key'] is False and isfile(self.key_home):
remove(self.key_home)
self.initialize_cur()
self.last_file = None
self.last_key = None
self.loginname = getpwuid(geteuid())[0]
self.hostname = gethostname()
self.cur_dir = getcwd()
chdir('/var/empty')
self.db = None | [
"def",
"__init__",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"config_home",
"=",
"realpath",
"(",
"expanduser",
"(",
"getenv",
"(",
"'XDG_CONFIG_HOME'",
")",
")",
")",
"except",
":",
"self",
".",
"config_home",
"=",
"realpath",
"(",
"expanduser",
"... | https://github.com/raymontag/keepassc/blob/3a3c7ef7b3ee1ceb16b613176d54dad89c0408df/keepassc/control.py#L27-L65 | ||
MozillaSecurity/peach | e5129cb50ce899e3ad009518d8b7cdc535233bbc | Peach/Engine/dom.py | python | DataElement.resetDataModel | (self, node = None) | Reset the entire data model. | Reset the entire data model. | [
"Reset",
"the",
"entire",
"data",
"model",
"."
] | def resetDataModel(self, node = None):
"""
Reset the entire data model.
"""
if node is None:
node = self.getRootOfDataMap()
node.reset()
for c in node._children:
if isinstance(c, DataElement):
self.resetDataModel(c) | [
"def",
"resetDataModel",
"(",
"self",
",",
"node",
"=",
"None",
")",
":",
"if",
"node",
"is",
"None",
":",
"node",
"=",
"self",
".",
"getRootOfDataMap",
"(",
")",
"node",
".",
"reset",
"(",
")",
"for",
"c",
"in",
"node",
".",
"_children",
":",
"if"... | https://github.com/MozillaSecurity/peach/blob/e5129cb50ce899e3ad009518d8b7cdc535233bbc/Peach/Engine/dom.py#L2320-L2332 | ||
igraph/python-igraph | e9f83e8af08f24ea025596e745917197d8b44d94 | src/igraph/__init__.py | python | Graph.as_directed | (self, *args, **kwds) | return copy | Returns a directed copy of this graph. Arguments are passed on
to L{to_directed()} that is invoked on the copy. | Returns a directed copy of this graph. Arguments are passed on
to L{to_directed()} that is invoked on the copy. | [
"Returns",
"a",
"directed",
"copy",
"of",
"this",
"graph",
".",
"Arguments",
"are",
"passed",
"on",
"to",
"L",
"{",
"to_directed",
"()",
"}",
"that",
"is",
"invoked",
"on",
"the",
"copy",
"."
] | def as_directed(self, *args, **kwds):
"""Returns a directed copy of this graph. Arguments are passed on
to L{to_directed()} that is invoked on the copy.
"""
copy = self.copy()
copy.to_directed(*args, **kwds)
return copy | [
"def",
"as_directed",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
":",
"copy",
"=",
"self",
".",
"copy",
"(",
")",
"copy",
".",
"to_directed",
"(",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
"return",
"copy"
] | https://github.com/igraph/python-igraph/blob/e9f83e8af08f24ea025596e745917197d8b44d94/src/igraph/__init__.py#L448-L454 | |
bendmorris/static-python | 2e0f8c4d7ed5b359dc7d8a75b6fb37e6b6c5c473 | Lib/decimal.py | python | Decimal.__mul__ | (self, other, context=None) | return ans | Return self * other.
(+-) INF * 0 (or its reverse) raise InvalidOperation. | Return self * other. | [
"Return",
"self",
"*",
"other",
"."
] | def __mul__(self, other, context=None):
"""Return self * other.
(+-) INF * 0 (or its reverse) raise InvalidOperation.
"""
other = _convert_other(other)
if other is NotImplemented:
return other
if context is None:
context = getcontext()
resultsign = self._sign ^ other._sign
if self._is_special or other._is_special:
ans = self._check_nans(other, context)
if ans:
return ans
if self._isinfinity():
if not other:
return context._raise_error(InvalidOperation, '(+-)INF * 0')
return _SignedInfinity[resultsign]
if other._isinfinity():
if not self:
return context._raise_error(InvalidOperation, '0 * (+-)INF')
return _SignedInfinity[resultsign]
resultexp = self._exp + other._exp
# Special case for multiplying by zero
if not self or not other:
ans = _dec_from_triple(resultsign, '0', resultexp)
# Fixing in case the exponent is out of bounds
ans = ans._fix(context)
return ans
# Special case for multiplying by power of 10
if self._int == '1':
ans = _dec_from_triple(resultsign, other._int, resultexp)
ans = ans._fix(context)
return ans
if other._int == '1':
ans = _dec_from_triple(resultsign, self._int, resultexp)
ans = ans._fix(context)
return ans
op1 = _WorkRep(self)
op2 = _WorkRep(other)
ans = _dec_from_triple(resultsign, str(op1.int * op2.int), resultexp)
ans = ans._fix(context)
return ans | [
"def",
"__mul__",
"(",
"self",
",",
"other",
",",
"context",
"=",
"None",
")",
":",
"other",
"=",
"_convert_other",
"(",
"other",
")",
"if",
"other",
"is",
"NotImplemented",
":",
"return",
"other",
"if",
"context",
"is",
"None",
":",
"context",
"=",
"g... | https://github.com/bendmorris/static-python/blob/2e0f8c4d7ed5b359dc7d8a75b6fb37e6b6c5c473/Lib/decimal.py#L1257-L1311 | |
lykops/lykops | ed7e35d0c1abb1eacf7ab365e041347d0862c0a7 | library/connecter/database/mongo.py | python | Op_Mongo.remove_all | (self, collect_name) | 删除所有数据,尽量勿用(最好使用重命名)
:参数
collect_name:集合名
:返回
一个列表 | 删除所有数据,尽量勿用(最好使用重命名)
:参数
collect_name:集合名
:返回
一个列表 | [
"删除所有数据,尽量勿用(最好使用重命名)",
":",
"参数",
"collect_name:集合名",
":",
"返回",
"一个列表"
] | def remove_all(self, collect_name):
'''
删除所有数据,尽量勿用(最好使用重命名)
:参数
collect_name:集合名
:返回
一个列表
'''
if not self.connecter:
self.logger.error(self.error_reason)
return (False, self.error_reason)
collection = self.dbs[collect_name]
try :
result = collection.remove({})
if result["ok"] == 1.0 :
self.logger.info(self.log_prefix + ' 从集合' + collect_name + '删除所有数据成功,删除条数为' + str(result["n"]))
return (True, '删除所有数据成功,删除条数为' + str(result["n"]))
else :
self.logger.error(self.log_prefix + ' 从集合' + collect_name + '删除所有数据成功,原因:' + str(result))
return (False, '删除所有数据成功,原因:' + str(result))
except Exception as e:
self.logger.error(self.log_prefix + ' 从集合' + collect_name + '删除所有数据成功,原因:未知错误,' + str(e))
return (False, '删除所有数据成功,未知错误,原因:' + str(e)) | [
"def",
"remove_all",
"(",
"self",
",",
"collect_name",
")",
":",
"if",
"not",
"self",
".",
"connecter",
":",
"self",
".",
"logger",
".",
"error",
"(",
"self",
".",
"error_reason",
")",
"return",
"(",
"False",
",",
"self",
".",
"error_reason",
")",
"col... | https://github.com/lykops/lykops/blob/ed7e35d0c1abb1eacf7ab365e041347d0862c0a7/library/connecter/database/mongo.py#L498-L524 | ||
CedricGuillemet/Imogen | ee417b42747ed5b46cb11b02ef0c3630000085b3 | bin/Lib/_osx_support.py | python | _supports_universal_builds | () | return bool(osx_version >= (10, 4)) if osx_version else False | Returns True if universal builds are supported on this system | Returns True if universal builds are supported on this system | [
"Returns",
"True",
"if",
"universal",
"builds",
"are",
"supported",
"on",
"this",
"system"
] | def _supports_universal_builds():
"""Returns True if universal builds are supported on this system"""
# As an approximation, we assume that if we are running on 10.4 or above,
# then we are running with an Xcode environment that supports universal
# builds, in particular -isysroot and -arch arguments to the compiler. This
# is in support of allowing 10.4 universal builds to run on 10.3.x systems.
osx_version = _get_system_version()
if osx_version:
try:
osx_version = tuple(int(i) for i in osx_version.split('.'))
except ValueError:
osx_version = ''
return bool(osx_version >= (10, 4)) if osx_version else False | [
"def",
"_supports_universal_builds",
"(",
")",
":",
"# As an approximation, we assume that if we are running on 10.4 or above,",
"# then we are running with an Xcode environment that supports universal",
"# builds, in particular -isysroot and -arch arguments to the compiler. This",
"# is in support ... | https://github.com/CedricGuillemet/Imogen/blob/ee417b42747ed5b46cb11b02ef0c3630000085b3/bin/Lib/_osx_support.py#L128-L141 | |
carrenD/Medical-Cross-Modality-Domain-Adaptation | 857602a622670b51205efdd40305a39d3e441335 | lib.py | python | _dice | (conf_matrix) | return dic | calculate dice coefficient from confusion_matrix | calculate dice coefficient from confusion_matrix | [
"calculate",
"dice",
"coefficient",
"from",
"confusion_matrix"
] | def _dice(conf_matrix):
"""
calculate dice coefficient from confusion_matrix
"""
num_cls = conf_matrix.shape[0]
dic = np.zeros(num_cls)
for ii in range(num_cls):
pp = np.sum(conf_matrix[:,ii])
gp = np.sum(conf_matrix[ii,:])
hit = conf_matrix[ii,ii]
if (pp + gp) == 0:
dic[ii] = 0
else:
dic[ii] = 2.0 * hit / (pp + gp)
return dic | [
"def",
"_dice",
"(",
"conf_matrix",
")",
":",
"num_cls",
"=",
"conf_matrix",
".",
"shape",
"[",
"0",
"]",
"dic",
"=",
"np",
".",
"zeros",
"(",
"num_cls",
")",
"for",
"ii",
"in",
"range",
"(",
"num_cls",
")",
":",
"pp",
"=",
"np",
".",
"sum",
"(",... | https://github.com/carrenD/Medical-Cross-Modality-Domain-Adaptation/blob/857602a622670b51205efdd40305a39d3e441335/lib.py#L138-L152 | |
magenta/magenta | be6558f1a06984faff6d6949234f5fe9ad0ffdb5 | magenta/models/music_vae/data.py | python | count_examples | (examples_path, tfds_name, data_converter,
file_reader=tf.python_io.tf_record_iterator) | return num_examples | Counts the number of examples produced by the converter from files. | Counts the number of examples produced by the converter from files. | [
"Counts",
"the",
"number",
"of",
"examples",
"produced",
"by",
"the",
"converter",
"from",
"files",
"."
] | def count_examples(examples_path, tfds_name, data_converter,
file_reader=tf.python_io.tf_record_iterator):
"""Counts the number of examples produced by the converter from files."""
def _file_generator():
filenames = tf.gfile.Glob(examples_path)
for f in filenames:
tf.logging.info('Counting examples in %s.', f)
reader = file_reader(f)
for item_str in reader:
yield data_converter.str_to_item_fn(item_str)
def _tfds_generator():
ds = tfds.as_numpy(
tfds.load(tfds_name, split=tfds.Split.VALIDATION, try_gcs=True))
# TODO(adarob): Generalize to other data types if needed.
for ex in ds:
yield note_seq.midi_to_note_sequence(ex['midi'])
num_examples = 0
generator = _tfds_generator if tfds_name else _file_generator
for item in generator():
tensors = data_converter.to_tensors(item)
num_examples += len(tensors.inputs)
tf.logging.info('Total examples: %d', num_examples)
return num_examples | [
"def",
"count_examples",
"(",
"examples_path",
",",
"tfds_name",
",",
"data_converter",
",",
"file_reader",
"=",
"tf",
".",
"python_io",
".",
"tf_record_iterator",
")",
":",
"def",
"_file_generator",
"(",
")",
":",
"filenames",
"=",
"tf",
".",
"gfile",
".",
... | https://github.com/magenta/magenta/blob/be6558f1a06984faff6d6949234f5fe9ad0ffdb5/magenta/models/music_vae/data.py#L1681-L1706 | |
pythonanywhere/dirigible-spreadsheet | c771e9a391708f3b219248bf9974e05b1582fdd0 | dirigible/sheet/parser/grammar.py | python | p__and_not_tests | (p) | _and_not_tests : AND not_test
| _and_not_tests AND not_test | _and_not_tests : AND not_test
| _and_not_tests AND not_test | [
"_and_not_tests",
":",
"AND",
"not_test",
"|",
"_and_not_tests",
"AND",
"not_test"
] | def p__and_not_tests(p):
"""_and_not_tests : AND not_test
| _and_not_tests AND not_test"""
if len(p) == 3:
p[0] = [p[1], p[2]]
else:
p[0] = p[1] + [p[2], p[3]] | [
"def",
"p__and_not_tests",
"(",
"p",
")",
":",
"if",
"len",
"(",
"p",
")",
"==",
"3",
":",
"p",
"[",
"0",
"]",
"=",
"[",
"p",
"[",
"1",
"]",
",",
"p",
"[",
"2",
"]",
"]",
"else",
":",
"p",
"[",
"0",
"]",
"=",
"p",
"[",
"1",
"]",
"+",
... | https://github.com/pythonanywhere/dirigible-spreadsheet/blob/c771e9a391708f3b219248bf9974e05b1582fdd0/dirigible/sheet/parser/grammar.py#L189-L195 | ||
oracle/graalpython | 577e02da9755d916056184ec441c26e00b70145c | graalpython/lib-python/3/tkinter/tix.py | python | HList.delete_siblings | (self, entry) | [] | def delete_siblings(self, entry):
self.tk.call(self._w, 'delete', 'siblings', entry) | [
"def",
"delete_siblings",
"(",
"self",
",",
"entry",
")",
":",
"self",
".",
"tk",
".",
"call",
"(",
"self",
".",
"_w",
",",
"'delete'",
",",
"'siblings'",
",",
"entry",
")"
] | https://github.com/oracle/graalpython/blob/577e02da9755d916056184ec441c26e00b70145c/graalpython/lib-python/3/tkinter/tix.py#L897-L898 | ||||
tensorlayer/RLzoo | 8dd3ff1003d1c7a446f45119bbd6b48c048990f4 | rlzoo/algorithms/ppo_clip/ppo_clip.py | python | PPO_CLIP.get_v | (self, s) | return res | Compute value
:param s: state
:return: value | Compute value | [
"Compute",
"value"
] | def get_v(self, s):
"""
Compute value
:param s: state
:return: value
"""
try:
s = s.astype(np.float32)
if s.ndim < 2: s = s[np.newaxis, :]
except:
pass
res = self.critic(s)[0, 0]
return res | [
"def",
"get_v",
"(",
"self",
",",
"s",
")",
":",
"try",
":",
"s",
"=",
"s",
".",
"astype",
"(",
"np",
".",
"float32",
")",
"if",
"s",
".",
"ndim",
"<",
"2",
":",
"s",
"=",
"s",
"[",
"np",
".",
"newaxis",
",",
":",
"]",
"except",
":",
"pas... | https://github.com/tensorlayer/RLzoo/blob/8dd3ff1003d1c7a446f45119bbd6b48c048990f4/rlzoo/algorithms/ppo_clip/ppo_clip.py#L161-L175 | |
quay/quay | b7d325ed42827db9eda2d9f341cb5a6cdfd155a6 | oauth/utils.py | python | url_dequery | (url) | return urllib.parse.urlunparse((url.scheme, url.netloc, url.path, url.params, "", url.fragment)) | Return a URL with the query component removed.
:param url: URL to dequery.
:type url: str
:rtype: str | Return a URL with the query component removed. | [
"Return",
"a",
"URL",
"with",
"the",
"query",
"component",
"removed",
"."
] | def url_dequery(url):
"""Return a URL with the query component removed.
:param url: URL to dequery.
:type url: str
:rtype: str
"""
url = urllib.parse.urlparse(url)
return urllib.parse.urlunparse((url.scheme, url.netloc, url.path, url.params, "", url.fragment)) | [
"def",
"url_dequery",
"(",
"url",
")",
":",
"url",
"=",
"urllib",
".",
"parse",
".",
"urlparse",
"(",
"url",
")",
"return",
"urllib",
".",
"parse",
".",
"urlunparse",
"(",
"(",
"url",
".",
"scheme",
",",
"url",
".",
"netloc",
",",
"url",
".",
"path... | https://github.com/quay/quay/blob/b7d325ed42827db9eda2d9f341cb5a6cdfd155a6/oauth/utils.py#L26-L34 | |
cloudera/hue | 23f02102d4547c17c32bd5ea0eb24e9eadd657a4 | desktop/libs/hadoop/src/hadoop/fs/hadoopfs.py | python | BlockCache.insert_new_blocks | (self, new_blocks) | Merge a list of Block objects from the NN into the list
of cached blocks.
If the set of blocks overlaps, the new blocks take precedence. | Merge a list of Block objects from the NN into the list
of cached blocks. | [
"Merge",
"a",
"list",
"of",
"Block",
"objects",
"from",
"the",
"NN",
"into",
"the",
"list",
"of",
"cached",
"blocks",
"."
] | def insert_new_blocks(self, new_blocks):
"""
Merge a list of Block objects from the NN into the list
of cached blocks.
If the set of blocks overlaps, the new blocks take precedence.
"""
# We could do a more efficient merge here since both lists
# are already sorted, but these data structures are small, so let's
# do the easy thing.
blocks_dict = dict((b.blockId, b) for b in self.blocks)
# Merge in new data to dictionary
for nb in new_blocks:
blocks_dict[nb.blockId] = nb
# Convert back to sorted list
block_list = list(blocks_dict.values())
block_list.sort(cmp=lambda a, b: cmp(a.startOffset, b.startOffset))
# Update cache with new data
self.blocks = block_list | [
"def",
"insert_new_blocks",
"(",
"self",
",",
"new_blocks",
")",
":",
"# We could do a more efficient merge here since both lists",
"# are already sorted, but these data structures are small, so let's",
"# do the easy thing.",
"blocks_dict",
"=",
"dict",
"(",
"(",
"b",
".",
"bloc... | https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/libs/hadoop/src/hadoop/fs/hadoopfs.py#L542-L564 | ||
frappe/erpnext | 9d36e30ef7043b391b5ed2523b8288bf46c45d18 | erpnext/accounts/doctype/c_form/c_form.py | python | CForm.validate | (self) | Validate invoice that c-form is applicable
and no other c-form is received for that | Validate invoice that c-form is applicable
and no other c-form is received for that | [
"Validate",
"invoice",
"that",
"c",
"-",
"form",
"is",
"applicable",
"and",
"no",
"other",
"c",
"-",
"form",
"is",
"received",
"for",
"that"
] | def validate(self):
"""Validate invoice that c-form is applicable
and no other c-form is received for that"""
for d in self.get('invoices'):
if d.invoice_no:
inv = frappe.db.sql("""select c_form_applicable, c_form_no from
`tabSales Invoice` where name = %s and docstatus = 1""", d.invoice_no)
if inv and inv[0][0] != 'Yes':
frappe.throw(_("C-form is not applicable for Invoice: {0}").format(d.invoice_no))
elif inv and inv[0][1] and inv[0][1] != self.name:
frappe.throw(_("""Invoice {0} is tagged in another C-form: {1}.
If you want to change C-form no for this invoice,
please remove invoice no from the previous c-form and then try again"""\
.format(d.invoice_no, inv[0][1])))
elif not inv:
frappe.throw(_("Row {0}: Invoice {1} is invalid, it might be cancelled / does not exist. \
Please enter a valid Invoice".format(d.idx, d.invoice_no))) | [
"def",
"validate",
"(",
"self",
")",
":",
"for",
"d",
"in",
"self",
".",
"get",
"(",
"'invoices'",
")",
":",
"if",
"d",
".",
"invoice_no",
":",
"inv",
"=",
"frappe",
".",
"db",
".",
"sql",
"(",
"\"\"\"select c_form_applicable, c_form_no from\n\t\t\t\t\t`tabS... | https://github.com/frappe/erpnext/blob/9d36e30ef7043b391b5ed2523b8288bf46c45d18/erpnext/accounts/doctype/c_form/c_form.py#L12-L32 | ||
pventuzelo/octopus | e8b8c5a9d5f6d9c63605afe9ef1528ab481ec983 | octopus/arch/wasm/analyzer.py | python | WasmModuleAnalyzer.__decode_name_section | (self, name_subsection) | return names_list | .. seealso:: https://github.com/WebAssembly/design/blob/master/BinaryEncoding.md#name-section | .. seealso:: https://github.com/WebAssembly/design/blob/master/BinaryEncoding.md#name-section | [
"..",
"seealso",
"::",
"https",
":",
"//",
"github",
".",
"com",
"/",
"WebAssembly",
"/",
"design",
"/",
"blob",
"/",
"master",
"/",
"BinaryEncoding",
".",
"md#name",
"-",
"section"
] | def __decode_name_section(self, name_subsection):
"""
.. seealso:: https://github.com/WebAssembly/design/blob/master/BinaryEncoding.md#name-section
"""
names_list = list()
if name_subsection.name_type == NAME_SUBSEC_FUNCTION:
subsection_function = name_subsection.payload
for name in subsection_function.names:
try:
name_str = name.name_str.tobytes().decode('utf-8')
except UnicodeDecodeError:
name_str = name.name_str.tobytes()
names_list.append((name.index, name.name_len, name_str))
elif name_subsection.name_type == NAME_SUBSEC_LOCAL:
print("__decode_name_section NAME_SUBSEC_LOCAL not implemented")
else:
print("__decode_name_section name_type unknown")
return names_list | [
"def",
"__decode_name_section",
"(",
"self",
",",
"name_subsection",
")",
":",
"names_list",
"=",
"list",
"(",
")",
"if",
"name_subsection",
".",
"name_type",
"==",
"NAME_SUBSEC_FUNCTION",
":",
"subsection_function",
"=",
"name_subsection",
".",
"payload",
"for",
... | https://github.com/pventuzelo/octopus/blob/e8b8c5a9d5f6d9c63605afe9ef1528ab481ec983/octopus/arch/wasm/analyzer.py#L332-L353 | |
nucypher/nucypher | f420caeb1c974f511f689fd1e5a9c6bbdf97f2d7 | nucypher/blockchain/eth/signers/hardware.py | python | TrezorSigner.sign_message | (self, message: bytes, checksum_address: str) | return HexBytes(signed_message.signature) | Signs a message via the TREZOR ethereum sign_message API and returns
a named tuple containing the signature and the address used to sign it.
This method requires interaction between the TREZOR and the user. | Signs a message via the TREZOR ethereum sign_message API and returns
a named tuple containing the signature and the address used to sign it.
This method requires interaction between the TREZOR and the user. | [
"Signs",
"a",
"message",
"via",
"the",
"TREZOR",
"ethereum",
"sign_message",
"API",
"and",
"returns",
"a",
"named",
"tuple",
"containing",
"the",
"signature",
"and",
"the",
"address",
"used",
"to",
"sign",
"it",
".",
"This",
"method",
"requires",
"interaction"... | def sign_message(self, message: bytes, checksum_address: str) -> HexBytes:
"""
Signs a message via the TREZOR ethereum sign_message API and returns
a named tuple containing the signature and the address used to sign it.
This method requires interaction between the TREZOR and the user.
"""
# TODO: #2262 Implement Trezor Message Signing
hd_path = self.__get_address_path(checksum_address=checksum_address)
signed_message = ethereum.sign_message(self.__client, hd_path, message)
return HexBytes(signed_message.signature) | [
"def",
"sign_message",
"(",
"self",
",",
"message",
":",
"bytes",
",",
"checksum_address",
":",
"str",
")",
"->",
"HexBytes",
":",
"# TODO: #2262 Implement Trezor Message Signing",
"hd_path",
"=",
"self",
".",
"__get_address_path",
"(",
"checksum_address",
"=",
"che... | https://github.com/nucypher/nucypher/blob/f420caeb1c974f511f689fd1e5a9c6bbdf97f2d7/nucypher/blockchain/eth/signers/hardware.py#L200-L209 | |
dmmiller612/bert-extractive-summarizer | 84f27333aef33629444589c24933b76448777d4f | summarizer/text_processors/sentence_abc.py | python | SentenceABC.sentence_processor | (
self, doc, min_length: int = 40, max_length: int = 600
) | return to_return | Processes a given spacy document and turns them into sentences.
:param doc: The document to use from spacy.
:param min_length: The minimum length a sentence should be to be considered.
:param max_length: The maximum length a sentence should be to be considered.
:return: Sentences. | Processes a given spacy document and turns them into sentences. | [
"Processes",
"a",
"given",
"spacy",
"document",
"and",
"turns",
"them",
"into",
"sentences",
"."
] | def sentence_processor(
self, doc, min_length: int = 40, max_length: int = 600
) -> List[str]:
"""
Processes a given spacy document and turns them into sentences.
:param doc: The document to use from spacy.
:param min_length: The minimum length a sentence should be to be considered.
:param max_length: The maximum length a sentence should be to be considered.
:return: Sentences.
"""
to_return = []
for c in doc.sents:
if max_length > len(c.text.strip()) > min_length:
if self.is_spacy_3:
to_return.append(c.text.strip())
else:
to_return.append(c.string.strip())
return to_return | [
"def",
"sentence_processor",
"(",
"self",
",",
"doc",
",",
"min_length",
":",
"int",
"=",
"40",
",",
"max_length",
":",
"int",
"=",
"600",
")",
"->",
"List",
"[",
"str",
"]",
":",
"to_return",
"=",
"[",
"]",
"for",
"c",
"in",
"doc",
".",
"sents",
... | https://github.com/dmmiller612/bert-extractive-summarizer/blob/84f27333aef33629444589c24933b76448777d4f/summarizer/text_processors/sentence_abc.py#L19-L40 | |
NVlabs/stylegan2 | bf0fe0baba9fc7039eae0cac575c1778be1ce3e3 | training/misc.py | python | load_pkl | (file_or_url) | [] | def load_pkl(file_or_url):
with open_file_or_url(file_or_url) as file:
return pickle.load(file, encoding='latin1') | [
"def",
"load_pkl",
"(",
"file_or_url",
")",
":",
"with",
"open_file_or_url",
"(",
"file_or_url",
")",
"as",
"file",
":",
"return",
"pickle",
".",
"load",
"(",
"file",
",",
"encoding",
"=",
"'latin1'",
")"
] | https://github.com/NVlabs/stylegan2/blob/bf0fe0baba9fc7039eae0cac575c1778be1ce3e3/training/misc.py#L25-L27 | ||||
huggingface/transformers | 623b4f7c63f60cce917677ee704d6c93ee960b4b | src/transformers/models/blenderbot/modeling_flax_blenderbot.py | python | FlaxBlenderbotPreTrainedModel.encode | (
self,
input_ids: jnp.ndarray,
attention_mask: Optional[jnp.ndarray] = None,
position_ids: Optional[jnp.ndarray] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
train: bool = False,
params: dict = None,
dropout_rng: PRNGKey = None,
) | return self.module.apply(
{"params": params or self.params},
input_ids=jnp.array(input_ids, dtype="i4"),
attention_mask=jnp.array(attention_mask, dtype="i4"),
position_ids=jnp.array(position_ids, dtype="i4"),
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
deterministic=not train,
rngs=rngs,
method=_encoder_forward,
) | r"""
Returns:
Example:
```python
>>> from transformers import BlenderbotTokenizer, FlaxBlenderbotForConditionalGeneration
>>> model = FlaxBlenderbotForConditionalGeneration.from_pretrained("facebook/blenderbot-400M-distill")
>>> tokenizer = BlenderbotTokenizer.from_pretrained("facebook/blenderbot-400M-distill")
>>> text = "My friends are cool but they eat too many carbs."
>>> inputs = tokenizer(text, max_length=1024, return_tensors="jax")
>>> encoder_outputs = model.encode(**inputs)
``` | r"""
Returns: | [
"r",
"Returns",
":"
] | def encode(
self,
input_ids: jnp.ndarray,
attention_mask: Optional[jnp.ndarray] = None,
position_ids: Optional[jnp.ndarray] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
train: bool = False,
params: dict = None,
dropout_rng: PRNGKey = None,
):
r"""
Returns:
Example:
```python
>>> from transformers import BlenderbotTokenizer, FlaxBlenderbotForConditionalGeneration
>>> model = FlaxBlenderbotForConditionalGeneration.from_pretrained("facebook/blenderbot-400M-distill")
>>> tokenizer = BlenderbotTokenizer.from_pretrained("facebook/blenderbot-400M-distill")
>>> text = "My friends are cool but they eat too many carbs."
>>> inputs = tokenizer(text, max_length=1024, return_tensors="jax")
>>> encoder_outputs = model.encode(**inputs)
```"""
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
output_hidden_states = (
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
)
return_dict = return_dict if return_dict is not None else self.config.return_dict
if attention_mask is None:
attention_mask = jnp.ones_like(input_ids)
if position_ids is None:
batch_size, sequence_length = input_ids.shape
position_ids = jnp.broadcast_to(jnp.arange(sequence_length)[None, :], (batch_size, sequence_length))
# Handle any PRNG if needed
rngs = {}
if dropout_rng is not None:
rngs["dropout"] = dropout_rng
def _encoder_forward(module, input_ids, attention_mask, position_ids, **kwargs):
encode_module = module._get_encoder_module()
return encode_module(input_ids, attention_mask, position_ids, **kwargs)
return self.module.apply(
{"params": params or self.params},
input_ids=jnp.array(input_ids, dtype="i4"),
attention_mask=jnp.array(attention_mask, dtype="i4"),
position_ids=jnp.array(position_ids, dtype="i4"),
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
deterministic=not train,
rngs=rngs,
method=_encoder_forward,
) | [
"def",
"encode",
"(",
"self",
",",
"input_ids",
":",
"jnp",
".",
"ndarray",
",",
"attention_mask",
":",
"Optional",
"[",
"jnp",
".",
"ndarray",
"]",
"=",
"None",
",",
"position_ids",
":",
"Optional",
"[",
"jnp",
".",
"ndarray",
"]",
"=",
"None",
",",
... | https://github.com/huggingface/transformers/blob/623b4f7c63f60cce917677ee704d6c93ee960b4b/src/transformers/models/blenderbot/modeling_flax_blenderbot.py#L965-L1024 | |
woshiyyya/DFGN-pytorch | 569bfdd67d8e54bb244339965a9268fb64806014 | bert_ner/pytorch_pretrained_bert/file_utils.py | python | url_to_filename | (url: str, etag: str = None) | return filename | Convert `url` into a hashed filename in a repeatable way.
If `etag` is specified, append its hash to the url's, delimited
by a period. | Convert `url` into a hashed filename in a repeatable way.
If `etag` is specified, append its hash to the url's, delimited
by a period. | [
"Convert",
"url",
"into",
"a",
"hashed",
"filename",
"in",
"a",
"repeatable",
"way",
".",
"If",
"etag",
"is",
"specified",
"append",
"its",
"hash",
"to",
"the",
"url",
"s",
"delimited",
"by",
"a",
"period",
"."
] | def url_to_filename(url: str, etag: str = None) -> str:
"""
Convert `url` into a hashed filename in a repeatable way.
If `etag` is specified, append its hash to the url's, delimited
by a period.
"""
url_bytes = url.encode('utf-8')
url_hash = sha256(url_bytes)
filename = url_hash.hexdigest()
if etag:
etag_bytes = etag.encode('utf-8')
etag_hash = sha256(etag_bytes)
filename += '.' + etag_hash.hexdigest()
return filename | [
"def",
"url_to_filename",
"(",
"url",
":",
"str",
",",
"etag",
":",
"str",
"=",
"None",
")",
"->",
"str",
":",
"url_bytes",
"=",
"url",
".",
"encode",
"(",
"'utf-8'",
")",
"url_hash",
"=",
"sha256",
"(",
"url_bytes",
")",
"filename",
"=",
"url_hash",
... | https://github.com/woshiyyya/DFGN-pytorch/blob/569bfdd67d8e54bb244339965a9268fb64806014/bert_ner/pytorch_pretrained_bert/file_utils.py#L30-L45 | |
twilio/twilio-python | 6e1e811ea57a1edfadd5161ace87397c563f6915 | twilio/rest/insights/v1/call_summaries.py | python | CallSummariesPage.__init__ | (self, version, response, solution) | Initialize the CallSummariesPage
:param Version version: Version that contains the resource
:param Response response: Response from the API
:returns: twilio.rest.insights.v1.call_summaries.CallSummariesPage
:rtype: twilio.rest.insights.v1.call_summaries.CallSummariesPage | Initialize the CallSummariesPage | [
"Initialize",
"the",
"CallSummariesPage"
] | def __init__(self, version, response, solution):
"""
Initialize the CallSummariesPage
:param Version version: Version that contains the resource
:param Response response: Response from the API
:returns: twilio.rest.insights.v1.call_summaries.CallSummariesPage
:rtype: twilio.rest.insights.v1.call_summaries.CallSummariesPage
"""
super(CallSummariesPage, self).__init__(version, response)
# Path Solution
self._solution = solution | [
"def",
"__init__",
"(",
"self",
",",
"version",
",",
"response",
",",
"solution",
")",
":",
"super",
"(",
"CallSummariesPage",
",",
"self",
")",
".",
"__init__",
"(",
"version",
",",
"response",
")",
"# Path Solution",
"self",
".",
"_solution",
"=",
"solut... | https://github.com/twilio/twilio-python/blob/6e1e811ea57a1edfadd5161ace87397c563f6915/twilio/rest/insights/v1/call_summaries.py#L263-L276 | ||
caiiiac/Machine-Learning-with-Python | 1a26c4467da41ca4ebc3d5bd789ea942ef79422f | MachineLearning/venv/lib/python3.5/site-packages/pip/_vendor/distlib/util.py | python | zip_dir | (directory) | return result | zip a directory tree into a BytesIO object | zip a directory tree into a BytesIO object | [
"zip",
"a",
"directory",
"tree",
"into",
"a",
"BytesIO",
"object"
] | def zip_dir(directory):
"""zip a directory tree into a BytesIO object"""
result = io.BytesIO()
dlen = len(directory)
with ZipFile(result, "w") as zf:
for root, dirs, files in os.walk(directory):
for name in files:
full = os.path.join(root, name)
rel = root[dlen:]
dest = os.path.join(rel, name)
zf.write(full, dest)
return result | [
"def",
"zip_dir",
"(",
"directory",
")",
":",
"result",
"=",
"io",
".",
"BytesIO",
"(",
")",
"dlen",
"=",
"len",
"(",
"directory",
")",
"with",
"ZipFile",
"(",
"result",
",",
"\"w\"",
")",
"as",
"zf",
":",
"for",
"root",
",",
"dirs",
",",
"files",
... | https://github.com/caiiiac/Machine-Learning-with-Python/blob/1a26c4467da41ca4ebc3d5bd789ea942ef79422f/MachineLearning/venv/lib/python3.5/site-packages/pip/_vendor/distlib/util.py#L1107-L1118 | |
meduza-corp/interstellar | 40a801ccd7856491726f5a126621d9318cabe2e1 | gsutil/gslib/third_party/protorpc/messages.py | python | Enum.def_enum | (dct, name) | return type(name, (Enum,), dct) | Define enum class from dictionary.
Args:
dct: Dictionary of enumerated values for type.
name: Name of enum. | Define enum class from dictionary. | [
"Define",
"enum",
"class",
"from",
"dictionary",
"."
] | def def_enum(dct, name):
"""Define enum class from dictionary.
Args:
dct: Dictionary of enumerated values for type.
name: Name of enum.
"""
return type(name, (Enum,), dct) | [
"def",
"def_enum",
"(",
"dct",
",",
"name",
")",
":",
"return",
"type",
"(",
"name",
",",
"(",
"Enum",
",",
")",
",",
"dct",
")"
] | https://github.com/meduza-corp/interstellar/blob/40a801ccd7856491726f5a126621d9318cabe2e1/gsutil/gslib/third_party/protorpc/messages.py#L488-L495 | |
xiaochus/MobileNetV3 | 2294bb7df353ce57cde256b940ca3e97e5ed2baf | model/mobilenet_v3_large.py | python | MobileNetV3_Large.__init__ | (self, shape, n_class, alpha=1.0, include_top=True) | Init.
# Arguments
input_shape: An integer or tuple/list of 3 integers, shape
of input tensor.
n_class: Integer, number of classes.
alpha: Integer, width multiplier.
include_top: if inculde classification layer.
# Returns
MobileNetv3 model. | Init. | [
"Init",
"."
] | def __init__(self, shape, n_class, alpha=1.0, include_top=True):
"""Init.
# Arguments
input_shape: An integer or tuple/list of 3 integers, shape
of input tensor.
n_class: Integer, number of classes.
alpha: Integer, width multiplier.
include_top: if inculde classification layer.
# Returns
MobileNetv3 model.
"""
super(MobileNetV3_Large, self).__init__(shape, n_class, alpha)
self.include_top = include_top | [
"def",
"__init__",
"(",
"self",
",",
"shape",
",",
"n_class",
",",
"alpha",
"=",
"1.0",
",",
"include_top",
"=",
"True",
")",
":",
"super",
"(",
"MobileNetV3_Large",
",",
"self",
")",
".",
"__init__",
"(",
"shape",
",",
"n_class",
",",
"alpha",
")",
... | https://github.com/xiaochus/MobileNetV3/blob/2294bb7df353ce57cde256b940ca3e97e5ed2baf/model/mobilenet_v3_large.py#L15-L29 | ||
mihaip/readerisdead | 0e35cf26e88f27e0a07432182757c1ce230f6936 | third_party/web/httpserver.py | python | LogMiddleware.__call__ | (self, environ, start_response) | return self.app(environ, xstart_response) | [] | def __call__(self, environ, start_response):
def xstart_response(status, response_headers, *args):
out = start_response(status, response_headers, *args)
self.log(status, environ)
return out
return self.app(environ, xstart_response) | [
"def",
"__call__",
"(",
"self",
",",
"environ",
",",
"start_response",
")",
":",
"def",
"xstart_response",
"(",
"status",
",",
"response_headers",
",",
"*",
"args",
")",
":",
"out",
"=",
"start_response",
"(",
"status",
",",
"response_headers",
",",
"*",
"... | https://github.com/mihaip/readerisdead/blob/0e35cf26e88f27e0a07432182757c1ce230f6936/third_party/web/httpserver.py#L300-L306 | |||
dimagi/commcare-hq | d67ff1d3b4c51fa050c19e60c3253a79d3452a39 | corehq/apps/hqadmin/utils.py | python | get_celery_stats | () | return mark_safe(worker_status) | [] | def get_celery_stats():
def get_stats(celery_monitoring, status_only=False, refresh=False):
params = {'refresh': 'true'} if refresh else {}
if status_only:
params['status'] = 'true'
try:
return requests.get(
celery_monitoring + '/api/workers',
params=params,
timeout=3,
).json()
except Exception:
return {}
def get_task_html(detailed_stats, worker_name):
tasks_ok = 'label-success'
tasks_full = 'label-warning'
tasks_html = format_html('<span class="label {}">unknown</span>', tasks_full)
try:
worker_stats = detailed_stats[worker_name]
pool_stats = worker_stats['stats']['pool']
running_tasks = pool_stats['writes']['inqueues']['active']
concurrency = pool_stats['max-concurrency']
completed_tasks = pool_stats['writes']['total']
tasks_class = tasks_full if running_tasks == concurrency else tasks_ok
tasks_html = format_html(
'<span class="label {}">{} / {}</span> :: {}',
tasks_class,
running_tasks,
concurrency,
completed_tasks
)
except KeyError:
pass
return tasks_html
celery_monitoring = getattr(settings, 'CELERY_FLOWER_URL', None)
worker_status = ""
if celery_monitoring:
worker_ok = '<span class="label label-success">OK</span>'
worker_bad = '<span class="label label-important">Down</span>'
worker_info = []
worker_stats = get_stats(celery_monitoring, status_only=True)
detailed_stats = get_stats(celery_monitoring, refresh=True)
for worker_name, status in worker_stats.items():
status_html = worker_ok if status else worker_bad
tasks_html = get_task_html(detailed_stats, worker_name)
worker_info.append(' '.join([worker_name, status_html, tasks_html]))
worker_status = '<br>'.join(worker_info)
# This is used by the system status admin page, and it doesn't look like celery is displayed
# properly on any environment, so this is likely not even used
return mark_safe(worker_status) | [
"def",
"get_celery_stats",
"(",
")",
":",
"def",
"get_stats",
"(",
"celery_monitoring",
",",
"status_only",
"=",
"False",
",",
"refresh",
"=",
"False",
")",
":",
"params",
"=",
"{",
"'refresh'",
":",
"'true'",
"}",
"if",
"refresh",
"else",
"{",
"}",
"if"... | https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/apps/hqadmin/utils.py#L28-L84 | |||
secdev/scapy | 65089071da1acf54622df0b4fa7fc7673d47d3cd | scapy/modules/six.py | python | python_2_unicode_compatible | (klass) | return klass | A decorator that defines __unicode__ and __str__ methods under Python 2.
Under Python 3 it does nothing.
To support Python 2 and 3 with a single code base, define a __str__ method
returning text and apply this decorator to the class. | A decorator that defines __unicode__ and __str__ methods under Python 2.
Under Python 3 it does nothing. | [
"A",
"decorator",
"that",
"defines",
"__unicode__",
"and",
"__str__",
"methods",
"under",
"Python",
"2",
".",
"Under",
"Python",
"3",
"it",
"does",
"nothing",
"."
] | def python_2_unicode_compatible(klass):
"""
A decorator that defines __unicode__ and __str__ methods under Python 2.
Under Python 3 it does nothing.
To support Python 2 and 3 with a single code base, define a __str__ method
returning text and apply this decorator to the class.
"""
if PY2:
if '__str__' not in klass.__dict__:
raise ValueError("@python_2_unicode_compatible cannot be applied "
"to %s because it doesn't define __str__()." %
klass.__name__)
klass.__unicode__ = klass.__str__
klass.__str__ = lambda self: self.__unicode__().encode('utf-8')
return klass | [
"def",
"python_2_unicode_compatible",
"(",
"klass",
")",
":",
"if",
"PY2",
":",
"if",
"'__str__'",
"not",
"in",
"klass",
".",
"__dict__",
":",
"raise",
"ValueError",
"(",
"\"@python_2_unicode_compatible cannot be applied \"",
"\"to %s because it doesn't define __str__().\""... | https://github.com/secdev/scapy/blob/65089071da1acf54622df0b4fa7fc7673d47d3cd/scapy/modules/six.py#L851-L866 | |
OfflineIMAP/offlineimap | e70d3992a0e9bb0fcdf3c94e1edf25a4124dfcd2 | offlineimap/ui/UIBase.py | python | UIBase.connecting | (self, reposname, hostname, port) | Log 'Establishing connection to'. | Log 'Establishing connection to'. | [
"Log",
"Establishing",
"connection",
"to",
"."
] | def connecting(self, reposname, hostname, port):
"""Log 'Establishing connection to'."""
if not self.logger.isEnabledFor(logging.INFO): return
displaystr = ''
hostname = hostname if hostname else ''
port = "%s"% port if port else ''
if hostname:
displaystr = ' to %s:%s' % (hostname, port)
self.logger.info("Establishing connection%s (%s)"%
(displaystr, reposname)) | [
"def",
"connecting",
"(",
"self",
",",
"reposname",
",",
"hostname",
",",
"port",
")",
":",
"if",
"not",
"self",
".",
"logger",
".",
"isEnabledFor",
"(",
"logging",
".",
"INFO",
")",
":",
"return",
"displaystr",
"=",
"''",
"hostname",
"=",
"hostname",
... | https://github.com/OfflineIMAP/offlineimap/blob/e70d3992a0e9bb0fcdf3c94e1edf25a4124dfcd2/offlineimap/ui/UIBase.py#L319-L329 | ||
otsaloma/gaupol | 6dec7826654d223c71a8d3279dcd967e95c46714 | aeidon/files/subviewer2.py | python | SubViewer2.read | (self) | return subtitles | Read file and return subtitles.
Raise :exc:`IOError` if reading fails.
Raise :exc:`UnicodeError` if decoding fails. | Read file and return subtitles. | [
"Read",
"file",
"and",
"return",
"subtitles",
"."
] | def read(self):
"""
Read file and return subtitles.
Raise :exc:`IOError` if reading fails.
Raise :exc:`UnicodeError` if decoding fails.
"""
self.header = ""
subtitles = []
lines = self._read_lines()
while lines[0].startswith("["):
self.header += "\n"
self.header += lines.pop(0)
self.header = self.header.lstrip()
for i, line in enumerate(lines + [""]):
match = self._re_time_line.match(line)
if match is None: continue
subtitle = self._get_subtitle()
subtitle.start_time = match.group(1) + "0"
subtitle.end_time = match.group(2) + "0"
text = lines[i+1].replace("[br]", "\n")
subtitle.main_text = text
subtitles.append(subtitle)
return subtitles | [
"def",
"read",
"(",
"self",
")",
":",
"self",
".",
"header",
"=",
"\"\"",
"subtitles",
"=",
"[",
"]",
"lines",
"=",
"self",
".",
"_read_lines",
"(",
")",
"while",
"lines",
"[",
"0",
"]",
".",
"startswith",
"(",
"\"[\"",
")",
":",
"self",
".",
"he... | https://github.com/otsaloma/gaupol/blob/6dec7826654d223c71a8d3279dcd967e95c46714/aeidon/files/subviewer2.py#L35-L58 | |
carnal0wnage/weirdAAL | c14e36d7bb82447f38a43da203f4bc29429f4cf4 | libs/aws/iam.py | python | iam_create_access_key | (username) | Create a new access & secret key for the specified username | Create a new access & secret key for the specified username | [
"Create",
"a",
"new",
"access",
"&",
"secret",
"key",
"for",
"the",
"specified",
"username"
] | def iam_create_access_key(username):
'''
Create a new access & secret key for the specified username
'''
client = boto3.client('iam', region_name=region)
try:
create_access_key = client.create_access_key(UserName=username)
print("Creating a new access key for: {}" .format(username))
pp.pprint(create_access_key['AccessKey'])
except botocore.exceptions.ClientError as e:
print("Unexpected error: {}" .format(e))
except KeyboardInterrupt:
print("CTRL-C received, exiting...") | [
"def",
"iam_create_access_key",
"(",
"username",
")",
":",
"client",
"=",
"boto3",
".",
"client",
"(",
"'iam'",
",",
"region_name",
"=",
"region",
")",
"try",
":",
"create_access_key",
"=",
"client",
".",
"create_access_key",
"(",
"UserName",
"=",
"username",
... | https://github.com/carnal0wnage/weirdAAL/blob/c14e36d7bb82447f38a43da203f4bc29429f4cf4/libs/aws/iam.py#L171-L184 | ||
kangasbros/django-bitcoin | 78bd509d815cfa27dbfd0a743aa742af644d27bf | django_bitcoin/models.py | python | Wallet.balance | (self, minconf=settings.BITCOIN_MINIMUM_CONFIRMATIONS,
timeframe=None, transactions=None) | Returns a "greater or equal than minimum" total ammount received at
this wallet with the given confirmations at the given timeframe. | Returns a "greater or equal than minimum" total ammount received at
this wallet with the given confirmations at the given timeframe. | [
"Returns",
"a",
"greater",
"or",
"equal",
"than",
"minimum",
"total",
"ammount",
"received",
"at",
"this",
"wallet",
"with",
"the",
"given",
"confirmations",
"at",
"the",
"given",
"timeframe",
"."
] | def balance(self, minconf=settings.BITCOIN_MINIMUM_CONFIRMATIONS,
timeframe=None, transactions=None):
"""
Returns a "greater or equal than minimum" total ammount received at
this wallet with the given confirmations at the given timeframe.
"""
if minconf == settings.BITCOIN_MINIMUM_CONFIRMATIONS:
return self.total_balance_sql(True)
elif minconf == 0:
return self.total_balance_sql(False)
raise Exception("Incorrect minconf parameter") | [
"def",
"balance",
"(",
"self",
",",
"minconf",
"=",
"settings",
".",
"BITCOIN_MINIMUM_CONFIRMATIONS",
",",
"timeframe",
"=",
"None",
",",
"transactions",
"=",
"None",
")",
":",
"if",
"minconf",
"==",
"settings",
".",
"BITCOIN_MINIMUM_CONFIRMATIONS",
":",
"return... | https://github.com/kangasbros/django-bitcoin/blob/78bd509d815cfa27dbfd0a743aa742af644d27bf/django_bitcoin/models.py#L836-L846 | ||
oracle/graalpython | 577e02da9755d916056184ec441c26e00b70145c | graalpython/lib-python/3/distutils/command/bdist_msi.py | python | PyDialog.__init__ | (self, *args, **kw) | Dialog(database, name, x, y, w, h, attributes, title, first,
default, cancel, bitmap=true) | Dialog(database, name, x, y, w, h, attributes, title, first,
default, cancel, bitmap=true) | [
"Dialog",
"(",
"database",
"name",
"x",
"y",
"w",
"h",
"attributes",
"title",
"first",
"default",
"cancel",
"bitmap",
"=",
"true",
")"
] | def __init__(self, *args, **kw):
"""Dialog(database, name, x, y, w, h, attributes, title, first,
default, cancel, bitmap=true)"""
Dialog.__init__(self, *args)
ruler = self.h - 36
bmwidth = 152*ruler/328
#if kw.get("bitmap", True):
# self.bitmap("Bitmap", 0, 0, bmwidth, ruler, "PythonWin")
self.line("BottomLine", 0, ruler, self.w, 0) | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"Dialog",
".",
"__init__",
"(",
"self",
",",
"*",
"args",
")",
"ruler",
"=",
"self",
".",
"h",
"-",
"36",
"bmwidth",
"=",
"152",
"*",
"ruler",
"/",
"328",
"#if kw.... | https://github.com/oracle/graalpython/blob/577e02da9755d916056184ec441c26e00b70145c/graalpython/lib-python/3/distutils/command/bdist_msi.py#L25-L33 | ||
quantopian/zipline | 014f1fc339dc8b7671d29be2d85ce57d3daec343 | zipline/pipeline/factors/factor.py | python | Factor.bottom | (self, N, mask=NotSpecified, groupby=NotSpecified) | return self.rank(ascending=True, mask=mask, groupby=groupby) <= N | Construct a Filter matching the bottom N asset values of self each day.
If ``groupby`` is supplied, returns a Filter matching the bottom N
asset values **for each group** defined by ``groupby``.
Parameters
----------
N : int
Number of assets passing the returned filter each day.
mask : zipline.pipeline.Filter, optional
A Filter representing assets to consider when computing ranks.
If mask is supplied, bottom values are computed ignoring any
asset/date pairs for which `mask` produces a value of False.
groupby : zipline.pipeline.Classifier, optional
A classifier defining partitions over which to perform ranking.
Returns
-------
filter : zipline.pipeline.Filter | Construct a Filter matching the bottom N asset values of self each day. | [
"Construct",
"a",
"Filter",
"matching",
"the",
"bottom",
"N",
"asset",
"values",
"of",
"self",
"each",
"day",
"."
] | def bottom(self, N, mask=NotSpecified, groupby=NotSpecified):
"""
Construct a Filter matching the bottom N asset values of self each day.
If ``groupby`` is supplied, returns a Filter matching the bottom N
asset values **for each group** defined by ``groupby``.
Parameters
----------
N : int
Number of assets passing the returned filter each day.
mask : zipline.pipeline.Filter, optional
A Filter representing assets to consider when computing ranks.
If mask is supplied, bottom values are computed ignoring any
asset/date pairs for which `mask` produces a value of False.
groupby : zipline.pipeline.Classifier, optional
A classifier defining partitions over which to perform ranking.
Returns
-------
filter : zipline.pipeline.Filter
"""
return self.rank(ascending=True, mask=mask, groupby=groupby) <= N | [
"def",
"bottom",
"(",
"self",
",",
"N",
",",
"mask",
"=",
"NotSpecified",
",",
"groupby",
"=",
"NotSpecified",
")",
":",
"return",
"self",
".",
"rank",
"(",
"ascending",
"=",
"True",
",",
"mask",
"=",
"mask",
",",
"groupby",
"=",
"groupby",
")",
"<="... | https://github.com/quantopian/zipline/blob/014f1fc339dc8b7671d29be2d85ce57d3daec343/zipline/pipeline/factors/factor.py#L1214-L1236 | |
nlloyd/SubliminalCollaborator | 5c619e17ddbe8acb9eea8996ec038169ddcd50a1 | libs/twisted/words/protocols/jabber/xmlstream.py | python | XmlStream.reset | (self) | Reset XML Stream.
Resets the XML Parser for incoming data. This is to be used after
successfully negotiating a new layer, e.g. TLS and SASL. Note that
registered event observers will continue to be in place. | Reset XML Stream. | [
"Reset",
"XML",
"Stream",
"."
] | def reset(self):
"""
Reset XML Stream.
Resets the XML Parser for incoming data. This is to be used after
successfully negotiating a new layer, e.g. TLS and SASL. Note that
registered event observers will continue to be in place.
"""
self._headerSent = False
self._initializeStream() | [
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"_headerSent",
"=",
"False",
"self",
".",
"_initializeStream",
"(",
")"
] | https://github.com/nlloyd/SubliminalCollaborator/blob/5c619e17ddbe8acb9eea8996ec038169ddcd50a1/libs/twisted/words/protocols/jabber/xmlstream.py#L507-L516 | ||
Trusted-AI/adversarial-robustness-toolbox | 9fabffdbb92947efa1ecc5d825d634d30dfbaf29 | art/defences/detector/poison/poison_filtering_defence.py | python | PoisonFilteringDefence.set_params | (self, **kwargs) | Take in a dictionary of parameters and apply attack-specific checks before saving them as attributes.
:param kwargs: A dictionary of defence-specific parameters. | Take in a dictionary of parameters and apply attack-specific checks before saving them as attributes. | [
"Take",
"in",
"a",
"dictionary",
"of",
"parameters",
"and",
"apply",
"attack",
"-",
"specific",
"checks",
"before",
"saving",
"them",
"as",
"attributes",
"."
] | def set_params(self, **kwargs) -> None:
"""
Take in a dictionary of parameters and apply attack-specific checks before saving them as attributes.
:param kwargs: A dictionary of defence-specific parameters.
"""
for key, value in kwargs.items():
if key in self.defence_params:
setattr(self, key, value)
self._check_params() | [
"def",
"set_params",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
"->",
"None",
":",
"for",
"key",
",",
"value",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"if",
"key",
"in",
"self",
".",
"defence_params",
":",
"setattr",
"(",
"self",
",",
"key",
... | https://github.com/Trusted-AI/adversarial-robustness-toolbox/blob/9fabffdbb92947efa1ecc5d825d634d30dfbaf29/art/defences/detector/poison/poison_filtering_defence.py#L79-L88 | ||
demisto/content | 5c664a65b992ac8ca90ac3f11b1b2cdf11ee9b07 | Packs/PassiveTotal/Scripts/RiskIQPassiveTotalWhoisWidgetScript/RiskIQPassiveTotalWhoisWidgetScript.py | python | set_arguments_for_widget_view | (indicator_data: Dict[str, Any]) | return {
'field': indicator_type,
'query': indicator_data.get('value', '')
} | Prepare argument for commands or message to set custom layout of indicator | Prepare argument for commands or message to set custom layout of indicator | [
"Prepare",
"argument",
"for",
"commands",
"or",
"message",
"to",
"set",
"custom",
"layout",
"of",
"indicator"
] | def set_arguments_for_widget_view(indicator_data: Dict[str, Any]) -> Union[Dict[str, str], str]:
"""
Prepare argument for commands or message to set custom layout of indicator
"""
indicator_type = indicator_data.get('indicator_type', '').lower()
if indicator_type == 'riskiqasset':
riskiq_asset_type = indicator_data.get('CustomFields', {}).get('riskiqassettype', '')
if riskiq_asset_type == '':
return 'Please provide value in the "RiskIQAsset Type" field to fetch detailed information of the asset.'
if riskiq_asset_type == 'Domain':
return {
'field': 'domain',
'query': indicator_data.get('value', '')
}
elif riskiq_asset_type == 'Contact':
return {
'field': 'email',
'query': indicator_data.get('value', '')
}
else:
return 'No domain information were found for the given argument(s).'
return {
'field': indicator_type,
'query': indicator_data.get('value', '')
} | [
"def",
"set_arguments_for_widget_view",
"(",
"indicator_data",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
")",
"->",
"Union",
"[",
"Dict",
"[",
"str",
",",
"str",
"]",
",",
"str",
"]",
":",
"indicator_type",
"=",
"indicator_data",
".",
"get",
"(",
"'indic... | https://github.com/demisto/content/blob/5c664a65b992ac8ca90ac3f11b1b2cdf11ee9b07/Packs/PassiveTotal/Scripts/RiskIQPassiveTotalWhoisWidgetScript/RiskIQPassiveTotalWhoisWidgetScript.py#L7-L31 | |
webpy/webpy | 62245f7da4aab8f8607c192b98d5ef93873f995b | web/template.py | python | TemplateResult.__unicode__ | (self) | return self["__body__"] | [] | def __unicode__(self):
self._prepare_body()
return self["__body__"] | [
"def",
"__unicode__",
"(",
"self",
")",
":",
"self",
".",
"_prepare_body",
"(",
")",
"return",
"self",
"[",
"\"__body__\"",
"]"
] | https://github.com/webpy/webpy/blob/62245f7da4aab8f8607c192b98d5ef93873f995b/web/template.py#L1491-L1493 | |||
zhl2008/awd-platform | 0416b31abea29743387b10b3914581fbe8e7da5e | web_flaskbb/lib/python2.7/site-packages/sqlalchemy/pool.py | python | manage | (module, **params) | r"""Return a proxy for a DB-API module that automatically
pools connections.
Given a DB-API 2.0 module and pool management parameters, returns
a proxy for the module that will automatically pool connections,
creating new connection pools for each distinct set of connection
arguments sent to the decorated module's connect() function.
:param module: a DB-API 2.0 database module
:param poolclass: the class used by the pool module to provide
pooling. Defaults to :class:`.QueuePool`.
:param \**params: will be passed through to *poolclass* | r"""Return a proxy for a DB-API module that automatically
pools connections. | [
"r",
"Return",
"a",
"proxy",
"for",
"a",
"DB",
"-",
"API",
"module",
"that",
"automatically",
"pools",
"connections",
"."
] | def manage(module, **params):
r"""Return a proxy for a DB-API module that automatically
pools connections.
Given a DB-API 2.0 module and pool management parameters, returns
a proxy for the module that will automatically pool connections,
creating new connection pools for each distinct set of connection
arguments sent to the decorated module's connect() function.
:param module: a DB-API 2.0 database module
:param poolclass: the class used by the pool module to provide
pooling. Defaults to :class:`.QueuePool`.
:param \**params: will be passed through to *poolclass*
"""
try:
return proxies[module]
except KeyError:
return proxies.setdefault(module, _DBProxy(module, **params)) | [
"def",
"manage",
"(",
"module",
",",
"*",
"*",
"params",
")",
":",
"try",
":",
"return",
"proxies",
"[",
"module",
"]",
"except",
"KeyError",
":",
"return",
"proxies",
".",
"setdefault",
"(",
"module",
",",
"_DBProxy",
"(",
"module",
",",
"*",
"*",
"... | https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/sqlalchemy/pool.py#L33-L53 | ||
django-cms/django-filer | c71e4d3de80c08d47f11e879594760aa9ed60a4d | filer/server/backends/base.py | python | ServerBase.save_as_header | (self, response, **kwargs) | * if save_as is False the header will not be added
* if save_as is a filename, it will be used in the header
* if save_as is True or None the filename will be determined from the
file path | * if save_as is False the header will not be added
* if save_as is a filename, it will be used in the header
* if save_as is True or None the filename will be determined from the
file path | [
"*",
"if",
"save_as",
"is",
"False",
"the",
"header",
"will",
"not",
"be",
"added",
"*",
"if",
"save_as",
"is",
"a",
"filename",
"it",
"will",
"be",
"used",
"in",
"the",
"header",
"*",
"if",
"save_as",
"is",
"True",
"or",
"None",
"the",
"filename",
"... | def save_as_header(self, response, **kwargs):
"""
* if save_as is False the header will not be added
* if save_as is a filename, it will be used in the header
* if save_as is True or None the filename will be determined from the
file path
"""
save_as = kwargs.get('save_as', None)
if save_as is False:
return
file_obj = kwargs.get('file_obj', None)
if save_as is True or save_as is None:
filename = os.path.basename(file_obj.path)
else:
filename = save_as
response['Content-Disposition'] = smart_str(
'attachment; filename=%s' % filename) | [
"def",
"save_as_header",
"(",
"self",
",",
"response",
",",
"*",
"*",
"kwargs",
")",
":",
"save_as",
"=",
"kwargs",
".",
"get",
"(",
"'save_as'",
",",
"None",
")",
"if",
"save_as",
"is",
"False",
":",
"return",
"file_obj",
"=",
"kwargs",
".",
"get",
... | https://github.com/django-cms/django-filer/blob/c71e4d3de80c08d47f11e879594760aa9ed60a4d/filer/server/backends/base.py#L16-L32 | ||
googleads/google-ads-python | 2a1d6062221f6aad1992a6bcca0e7e4a93d2db86 | google/ads/googleads/v7/services/services/ad_schedule_view_service/client.py | python | AdScheduleViewServiceClient.common_folder_path | (folder: str,) | return "folders/{folder}".format(folder=folder,) | Return a fully-qualified folder string. | Return a fully-qualified folder string. | [
"Return",
"a",
"fully",
"-",
"qualified",
"folder",
"string",
"."
] | def common_folder_path(folder: str,) -> str:
"""Return a fully-qualified folder string."""
return "folders/{folder}".format(folder=folder,) | [
"def",
"common_folder_path",
"(",
"folder",
":",
"str",
",",
")",
"->",
"str",
":",
"return",
"\"folders/{folder}\"",
".",
"format",
"(",
"folder",
"=",
"folder",
",",
")"
] | https://github.com/googleads/google-ads-python/blob/2a1d6062221f6aad1992a6bcca0e7e4a93d2db86/google/ads/googleads/v7/services/services/ad_schedule_view_service/client.py#L192-L194 | |
foremast/foremast | e8eb9bd24e975772532d90efa8a9ba1850e968cc | src/foremast/utils/tasks.py | python | wait_for_task | (task_data, task_uri='/tasks') | return check_task(taskid, timeout) | Run task and check the result.
Args:
task_data (str): the task json to execute
Returns:
str: Task status. | Run task and check the result. | [
"Run",
"task",
"and",
"check",
"the",
"result",
"."
] | def wait_for_task(task_data, task_uri='/tasks'):
"""Run task and check the result.
Args:
task_data (str): the task json to execute
Returns:
str: Task status.
"""
taskid = post_task(task_data, task_uri)
if isinstance(task_data, str):
json_data = json.loads(task_data)
else:
json_data = task_data
# inspect the task to see if a timeout is configured
job = json_data['job'][0]
env = job.get('credentials')
task_type = job.get('type')
timeout = TASK_TIMEOUTS.get(env, dict()).get(task_type, DEFAULT_TASK_TIMEOUT)
LOG.debug("Task %s will timeout after %s", task_type, timeout)
return check_task(taskid, timeout) | [
"def",
"wait_for_task",
"(",
"task_data",
",",
"task_uri",
"=",
"'/tasks'",
")",
":",
"taskid",
"=",
"post_task",
"(",
"task_data",
",",
"task_uri",
")",
"if",
"isinstance",
"(",
"task_data",
",",
"str",
")",
":",
"json_data",
"=",
"json",
".",
"loads",
... | https://github.com/foremast/foremast/blob/e8eb9bd24e975772532d90efa8a9ba1850e968cc/src/foremast/utils/tasks.py#L129-L155 | |
websauna/websauna | a57de54fb8a3fae859f24f373f0292e1e4b3c344 | websauna/system/devop/scripts/__init__.py | python | proxy_to_pyramid_script | (script: str, argv: t.List[str]) | Proxy call to the original Pyramid script.
:param script: Name of the original Pyramid script.
:param argv: Command line arguments.
:raises sys.SystemExit: | Proxy call to the original Pyramid script. | [
"Proxy",
"call",
"to",
"the",
"original",
"Pyramid",
"script",
"."
] | def proxy_to_pyramid_script(script: str, argv: t.List[str]):
"""Proxy call to the original Pyramid script.
:param script: Name of the original Pyramid script.
:param argv: Command line arguments.
:raises sys.SystemExit:
"""
if len(argv) < 2:
usage_message(argv)
# Make sure we are prefixing calls with our plaster schema loader.
config_uri = get_config_uri(argv)
argv[1] = config_uri
display_deprecation_warning(script, config_uri)
try:
sys.exit(
load_entry_point('pyramid', 'console_scripts', script)()
)
except SanityCheckFailed as exc:
feedback_and_exit(FAIL_MSG.format(exception=str(exc)), 1) | [
"def",
"proxy_to_pyramid_script",
"(",
"script",
":",
"str",
",",
"argv",
":",
"t",
".",
"List",
"[",
"str",
"]",
")",
":",
"if",
"len",
"(",
"argv",
")",
"<",
"2",
":",
"usage_message",
"(",
"argv",
")",
"# Make sure we are prefixing calls with our plaster ... | https://github.com/websauna/websauna/blob/a57de54fb8a3fae859f24f373f0292e1e4b3c344/websauna/system/devop/scripts/__init__.py#L91-L110 | ||
gepd/Deviot | 150caea06108369b30210eb287a580fcff4904af | api/deviot.py | python | packages_path | () | return path.dirname(plugin) | Path to Packages/ | Path to Packages/ | [
"Path",
"to",
"Packages",
"/"
] | def packages_path():
"""
Path to Packages/
"""
plugin = plugin_path()
return path.dirname(plugin) | [
"def",
"packages_path",
"(",
")",
":",
"plugin",
"=",
"plugin_path",
"(",
")",
"return",
"path",
".",
"dirname",
"(",
"plugin",
")"
] | https://github.com/gepd/Deviot/blob/150caea06108369b30210eb287a580fcff4904af/api/deviot.py#L111-L116 | |
nosmokingbandit/watcher | dadacd21a5790ee609058a98a17fcc8954d24439 | lib/hachoir_core/log.py | python | Log.newMessage | (self, level, text, ctxt=None) | Write a new message : append it in the buffer,
display it to the screen (if needed), and write
it in the log file (if needed).
@param level: Message level.
@type level: C{int}
@param text: Message content.
@type text: C{str}
@param ctxt: The caller instance. | Write a new message : append it in the buffer,
display it to the screen (if needed), and write
it in the log file (if needed). | [
"Write",
"a",
"new",
"message",
":",
"append",
"it",
"in",
"the",
"buffer",
"display",
"it",
"to",
"the",
"screen",
"(",
"if",
"needed",
")",
"and",
"write",
"it",
"in",
"the",
"log",
"file",
"(",
"if",
"needed",
")",
"."
] | def newMessage(self, level, text, ctxt=None):
"""
Write a new message : append it in the buffer,
display it to the screen (if needed), and write
it in the log file (if needed).
@param level: Message level.
@type level: C{int}
@param text: Message content.
@type text: C{str}
@param ctxt: The caller instance.
"""
if level < self.LOG_ERROR and config.quiet or \
level <= self.LOG_INFO and not config.verbose:
return
if config.debug:
from hachoir_core.error import getBacktrace
backtrace = getBacktrace(None)
if backtrace:
text += "\n\n" + backtrace
_text = text
if hasattr(ctxt, "_logger"):
_ctxt = ctxt._logger()
if _ctxt is not None:
text = "[%s] %s" % (_ctxt, text)
# Add message to log buffer
if self.use_buffer:
if not self.__buffer.has_key(level):
self.__buffer[level] = [text]
else:
self.__buffer[level].append(text)
# Add prefix
prefix = self.level_name.get(level, "[info]")
# Display on stdout (if used)
if self.use_print:
sys.stdout.flush()
sys.stderr.write("%s %s\n" % (prefix, text))
sys.stderr.flush()
# Write into outfile (if used)
if self.__file:
self._writeIntoFile("%s %s" % (prefix, text))
# Use callback (if used)
if self.on_new_message:
self.on_new_message (level, prefix, _text, ctxt) | [
"def",
"newMessage",
"(",
"self",
",",
"level",
",",
"text",
",",
"ctxt",
"=",
"None",
")",
":",
"if",
"level",
"<",
"self",
".",
"LOG_ERROR",
"and",
"config",
".",
"quiet",
"or",
"level",
"<=",
"self",
".",
"LOG_INFO",
"and",
"not",
"config",
".",
... | https://github.com/nosmokingbandit/watcher/blob/dadacd21a5790ee609058a98a17fcc8954d24439/lib/hachoir_core/log.py#L61-L111 | ||
CityOfZion/neo-python | 99783bc8310982a5380081ec41a6ee07ba843f3f | neo/Network/payloads/version.py | python | VersionPayload.deserialize_from_bytes | (cls, data_stream: Union[bytes, bytearray]) | return version_payload | Deserialize object from a byte array. | Deserialize object from a byte array. | [
"Deserialize",
"object",
"from",
"a",
"byte",
"array",
"."
] | def deserialize_from_bytes(cls, data_stream: Union[bytes, bytearray]):
""" Deserialize object from a byte array. """
br = BinaryReader(stream=data_stream)
version_payload = cls()
version_payload.deserialize(br)
br.cleanup()
return version_payload | [
"def",
"deserialize_from_bytes",
"(",
"cls",
",",
"data_stream",
":",
"Union",
"[",
"bytes",
",",
"bytearray",
"]",
")",
":",
"br",
"=",
"BinaryReader",
"(",
"stream",
"=",
"data_stream",
")",
"version_payload",
"=",
"cls",
"(",
")",
"version_payload",
".",
... | https://github.com/CityOfZion/neo-python/blob/99783bc8310982a5380081ec41a6ee07ba843f3f/neo/Network/payloads/version.py#L68-L74 | |
openstack/glance | 502fa0ffc8970c087c5924742231812c0da6a114 | glance/db/simple/api.py | python | metadef_namespace_create | (context, values) | return namespace | Create a namespace object | Create a namespace object | [
"Create",
"a",
"namespace",
"object"
] | def metadef_namespace_create(context, values):
"""Create a namespace object"""
global DATA
namespace_values = copy.deepcopy(values)
namespace_name = namespace_values.get('namespace')
required_attributes = ['namespace', 'owner']
allowed_attributes = ['namespace', 'owner', 'display_name', 'description',
'visibility', 'protected']
for namespace in DATA['metadef_namespaces']:
if namespace['namespace'] == namespace_name:
LOG.debug("Can not create the metadata definition namespace. "
"Namespace=%s already exists.", namespace_name)
raise exception.MetadefDuplicateNamespace(
namespace_name=namespace_name)
for key in required_attributes:
if key not in namespace_values:
raise exception.Invalid('%s is a required attribute' % key)
incorrect_keys = set(namespace_values.keys()) - set(allowed_attributes)
if incorrect_keys:
raise exception.Invalid(
'The keys %s are not valid' % str(incorrect_keys))
namespace = _format_namespace(namespace_values)
DATA['metadef_namespaces'].append(namespace)
return namespace | [
"def",
"metadef_namespace_create",
"(",
"context",
",",
"values",
")",
":",
"global",
"DATA",
"namespace_values",
"=",
"copy",
".",
"deepcopy",
"(",
"values",
")",
"namespace_name",
"=",
"namespace_values",
".",
"get",
"(",
"'namespace'",
")",
"required_attributes... | https://github.com/openstack/glance/blob/502fa0ffc8970c087c5924742231812c0da6a114/glance/db/simple/api.py#L1191-L1220 | |
clinton-hall/nzbToMedia | 27669389216902d1085660167e7bda0bd8527ecf | libs/common/pkg_resources/__init__.py | python | WorkingSet.iter_entry_points | (self, group, name=None) | return (
entry
for dist in self
for entry in dist.get_entry_map(group).values()
if name is None or name == entry.name
) | Yield entry point objects from `group` matching `name`
If `name` is None, yields all entry points in `group` from all
distributions in the working set, otherwise only ones matching
both `group` and `name` are yielded (in distribution order). | Yield entry point objects from `group` matching `name` | [
"Yield",
"entry",
"point",
"objects",
"from",
"group",
"matching",
"name"
] | def iter_entry_points(self, group, name=None):
"""Yield entry point objects from `group` matching `name`
If `name` is None, yields all entry points in `group` from all
distributions in the working set, otherwise only ones matching
both `group` and `name` are yielded (in distribution order).
"""
return (
entry
for dist in self
for entry in dist.get_entry_map(group).values()
if name is None or name == entry.name
) | [
"def",
"iter_entry_points",
"(",
"self",
",",
"group",
",",
"name",
"=",
"None",
")",
":",
"return",
"(",
"entry",
"for",
"dist",
"in",
"self",
"for",
"entry",
"in",
"dist",
".",
"get_entry_map",
"(",
"group",
")",
".",
"values",
"(",
")",
"if",
"nam... | https://github.com/clinton-hall/nzbToMedia/blob/27669389216902d1085660167e7bda0bd8527ecf/libs/common/pkg_resources/__init__.py#L644-L656 | |
sagemath/sage | f9b2db94f675ff16963ccdefba4f1a3393b3fe0d | src/sage/schemes/hyperelliptic_curves/hyperelliptic_padic_field.py | python | HyperellipticCurve_padic_field.coleman_integral_from_weierstrass_via_boundary | (self, w, P, Q, d) | return P_to_S + S_to_Q | r"""
Computes the Coleman integral `\int_P^Q w` via a boundary point
in the disc of `P`, defined over a degree `d` extension
INPUT:
- w: a differential
- P: a Weierstrass point
- Q: a non-Weierstrass point
- d: degree of extension where coordinates of boundary point lie
OUTPUT:
the Coleman integral `\int_P^Q w`, written in terms of the uniformizer
`a` of the degree `d` extension
EXAMPLES::
sage: R.<x> = QQ['x']
sage: H = HyperellipticCurve(x^3-10*x+9)
sage: K = Qp(5,6)
sage: HK = H.change_ring(K)
sage: P = HK(1,0)
sage: Q = HK(0,3)
sage: x,y = HK.monsky_washnitzer_gens()
sage: HK.coleman_integral_from_weierstrass_via_boundary(y.diff(),P,Q,20)
3 + O(a^119)
sage: HK.coleman_integral(y.diff(),P,Q)
3 + O(5^6)
sage: w = HK.invariant_differential()
sage: HK.coleman_integral_from_weierstrass_via_boundary(w,P,Q,20)
2*a^40 + a^80 + a^100 + O(a^105)
sage: HK.coleman_integral(w,P,Q)
2*5^2 + 5^4 + 5^5 + 3*5^6 + O(5^7)
AUTHOR:
- Jennifer Balakrishnan | r"""
Computes the Coleman integral `\int_P^Q w` via a boundary point
in the disc of `P`, defined over a degree `d` extension | [
"r",
"Computes",
"the",
"Coleman",
"integral",
"\\",
"int_P^Q",
"w",
"via",
"a",
"boundary",
"point",
"in",
"the",
"disc",
"of",
"P",
"defined",
"over",
"a",
"degree",
"d",
"extension"
] | def coleman_integral_from_weierstrass_via_boundary(self, w, P, Q, d):
r"""
Computes the Coleman integral `\int_P^Q w` via a boundary point
in the disc of `P`, defined over a degree `d` extension
INPUT:
- w: a differential
- P: a Weierstrass point
- Q: a non-Weierstrass point
- d: degree of extension where coordinates of boundary point lie
OUTPUT:
the Coleman integral `\int_P^Q w`, written in terms of the uniformizer
`a` of the degree `d` extension
EXAMPLES::
sage: R.<x> = QQ['x']
sage: H = HyperellipticCurve(x^3-10*x+9)
sage: K = Qp(5,6)
sage: HK = H.change_ring(K)
sage: P = HK(1,0)
sage: Q = HK(0,3)
sage: x,y = HK.monsky_washnitzer_gens()
sage: HK.coleman_integral_from_weierstrass_via_boundary(y.diff(),P,Q,20)
3 + O(a^119)
sage: HK.coleman_integral(y.diff(),P,Q)
3 + O(5^6)
sage: w = HK.invariant_differential()
sage: HK.coleman_integral_from_weierstrass_via_boundary(w,P,Q,20)
2*a^40 + a^80 + a^100 + O(a^105)
sage: HK.coleman_integral(w,P,Q)
2*5^2 + 5^4 + 5^5 + 3*5^6 + O(5^7)
AUTHOR:
- Jennifer Balakrishnan
"""
HJ = self.curve_over_ram_extn(d)
S = self.get_boundary_point(HJ,P)
P_to_S = self.coleman_integral_P_to_S(w,P,S)
S_to_Q = HJ.coleman_integral_S_to_Q(w,S,Q)
return P_to_S + S_to_Q | [
"def",
"coleman_integral_from_weierstrass_via_boundary",
"(",
"self",
",",
"w",
",",
"P",
",",
"Q",
",",
"d",
")",
":",
"HJ",
"=",
"self",
".",
"curve_over_ram_extn",
"(",
"d",
")",
"S",
"=",
"self",
".",
"get_boundary_point",
"(",
"HJ",
",",
"P",
")",
... | https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/schemes/hyperelliptic_curves/hyperelliptic_padic_field.py#L1314-L1359 | |
aaronportnoy/toolbag | 2d39457a7617b2f334d203d8c8cf88a5a25ef1fa | app/quicktime.py | python | getMinorDispatchTableAddress | (ea) | return idc.GetOperandValue(res, 1) | find address of last lea in function | find address of last lea in function | [
"find",
"address",
"of",
"last",
"lea",
"in",
"function"
] | def getMinorDispatchTableAddress(ea):
"""find address of last lea in function"""
start = idc.GetFunctionAttr(ea, idc.FUNCATTR_START)
end = idc.PrevHead( idc.GetFunctionAttr(ea, idc.FUNCATTR_END), start)
res = prevMnemonic(end, 'lea', start)
assert res != idc.BADADDR
return idc.GetOperandValue(res, 1) | [
"def",
"getMinorDispatchTableAddress",
"(",
"ea",
")",
":",
"start",
"=",
"idc",
".",
"GetFunctionAttr",
"(",
"ea",
",",
"idc",
".",
"FUNCATTR_START",
")",
"end",
"=",
"idc",
".",
"PrevHead",
"(",
"idc",
".",
"GetFunctionAttr",
"(",
"ea",
",",
"idc",
"."... | https://github.com/aaronportnoy/toolbag/blob/2d39457a7617b2f334d203d8c8cf88a5a25ef1fa/app/quicktime.py#L24-L30 | |
khanhnamle1994/natural-language-processing | 01d450d5ac002b0156ef4cf93a07cb508c1bcdc5 | assignment1/.env/lib/python2.7/site-packages/scipy/cluster/vq.py | python | py_vq | (obs, code_book) | return code, sqrt(min_dist) | Python version of vq algorithm.
The algorithm computes the euclidian distance between each
observation and every frame in the code_book.
Parameters
----------
obs : ndarray
Expects a rank 2 array. Each row is one observation.
code_book : ndarray
Code book to use. Same format than obs. Should have same number of
features (eg columns) than obs.
Returns
-------
code : ndarray
code[i] gives the label of the ith obversation, that its code is
code_book[code[i]].
mind_dist : ndarray
min_dist[i] gives the distance between the ith observation and its
corresponding code.
Notes
-----
This function is slower than the C version but works for
all input types. If the inputs have the wrong types for the
C versions of the function, this one is called as a last resort.
It is about 20 times slower than the C version. | Python version of vq algorithm. | [
"Python",
"version",
"of",
"vq",
"algorithm",
"."
] | def py_vq(obs, code_book):
""" Python version of vq algorithm.
The algorithm computes the euclidian distance between each
observation and every frame in the code_book.
Parameters
----------
obs : ndarray
Expects a rank 2 array. Each row is one observation.
code_book : ndarray
Code book to use. Same format than obs. Should have same number of
features (eg columns) than obs.
Returns
-------
code : ndarray
code[i] gives the label of the ith obversation, that its code is
code_book[code[i]].
mind_dist : ndarray
min_dist[i] gives the distance between the ith observation and its
corresponding code.
Notes
-----
This function is slower than the C version but works for
all input types. If the inputs have the wrong types for the
C versions of the function, this one is called as a last resort.
It is about 20 times slower than the C version.
"""
# n = number of observations
# d = number of features
if np.ndim(obs) == 1:
if not np.ndim(obs) == np.ndim(code_book):
raise ValueError(
"Observation and code_book should have the same rank")
else:
return _py_vq_1d(obs, code_book)
else:
(n, d) = shape(obs)
# code books and observations should have same number of features and same
# shape
if not np.ndim(obs) == np.ndim(code_book):
raise ValueError("Observation and code_book should have the same rank")
elif not d == code_book.shape[1]:
raise ValueError("Code book(%d) and obs(%d) should have the same "
"number of features (eg columns)""" %
(code_book.shape[1], d))
code = zeros(n, dtype=int)
min_dist = zeros(n)
for i in range(n):
dist = np.sum((obs[i] - code_book) ** 2, 1)
code[i] = argmin(dist)
min_dist[i] = dist[code[i]]
return code, sqrt(min_dist) | [
"def",
"py_vq",
"(",
"obs",
",",
"code_book",
")",
":",
"# n = number of observations",
"# d = number of features",
"if",
"np",
".",
"ndim",
"(",
"obs",
")",
"==",
"1",
":",
"if",
"not",
"np",
".",
"ndim",
"(",
"obs",
")",
"==",
"np",
".",
"ndim",
"(",... | https://github.com/khanhnamle1994/natural-language-processing/blob/01d450d5ac002b0156ef4cf93a07cb508c1bcdc5/assignment1/.env/lib/python2.7/site-packages/scipy/cluster/vq.py#L210-L269 | |
GNS3/gns3-gui | da8adbaa18ab60e053af2a619efd468f4c8950f3 | gns3/node.py | python | Node.node_id | (self) | return self._node_id | Return the ID of this device
:returns: identifier (string) | Return the ID of this device | [
"Return",
"the",
"ID",
"of",
"this",
"device"
] | def node_id(self):
"""
Return the ID of this device
:returns: identifier (string)
"""
return self._node_id | [
"def",
"node_id",
"(",
"self",
")",
":",
"return",
"self",
".",
"_node_id"
] | https://github.com/GNS3/gns3-gui/blob/da8adbaa18ab60e053af2a619efd468f4c8950f3/gns3/node.py#L71-L78 | |
flow-project/flow | a511c41c48e6b928bb2060de8ad1ef3c3e3d9554 | flow/networks/traffic_light_grid.py | python | TrafficLightGridNetwork.__init__ | (self,
name,
vehicles,
net_params,
initial_config=InitialConfig(),
traffic_lights=TrafficLightParams()) | Initialize an n*m traffic light grid network. | Initialize an n*m traffic light grid network. | [
"Initialize",
"an",
"n",
"*",
"m",
"traffic",
"light",
"grid",
"network",
"."
] | def __init__(self,
name,
vehicles,
net_params,
initial_config=InitialConfig(),
traffic_lights=TrafficLightParams()):
"""Initialize an n*m traffic light grid network."""
optional = ["tl_logic"]
for p in ADDITIONAL_NET_PARAMS.keys():
if p not in net_params.additional_params and p not in optional:
raise KeyError('Network parameter "{}" not supplied'.format(p))
for p in ADDITIONAL_NET_PARAMS["grid_array"].keys():
if p not in net_params.additional_params["grid_array"]:
raise KeyError(
'Grid array parameter "{}" not supplied'.format(p))
# retrieve all additional parameters
# refer to the ADDITIONAL_NET_PARAMS dict for more documentation
self.vertical_lanes = net_params.additional_params["vertical_lanes"]
self.horizontal_lanes = net_params.additional_params[
"horizontal_lanes"]
self.speed_limit = net_params.additional_params["speed_limit"]
if not isinstance(self.speed_limit, dict):
self.speed_limit = {
"horizontal": self.speed_limit,
"vertical": self.speed_limit
}
self.grid_array = net_params.additional_params["grid_array"]
self.row_num = self.grid_array["row_num"]
self.col_num = self.grid_array["col_num"]
self.inner_length = self.grid_array["inner_length"]
self.short_length = self.grid_array["short_length"]
self.long_length = self.grid_array["long_length"]
self.cars_heading_top = self.grid_array["cars_top"]
self.cars_heading_bot = self.grid_array["cars_bot"]
self.cars_heading_left = self.grid_array["cars_left"]
self.cars_heading_right = self.grid_array["cars_right"]
# specifies whether or not there will be traffic lights at the
# intersections (True by default)
self.use_traffic_lights = net_params.additional_params.get(
"traffic_lights", True)
# radius of the inner nodes (ie of the intersections)
self.inner_nodes_radius = 2.9 + 3.3 * max(self.vertical_lanes,
self.horizontal_lanes)
# total number of edges in the network
self.num_edges = 4 * ((self.col_num + 1) * self.row_num + self.col_num)
# name of the network (DO NOT CHANGE)
self.name = "BobLoblawsLawBlog"
super().__init__(name, vehicles, net_params, initial_config,
traffic_lights) | [
"def",
"__init__",
"(",
"self",
",",
"name",
",",
"vehicles",
",",
"net_params",
",",
"initial_config",
"=",
"InitialConfig",
"(",
")",
",",
"traffic_lights",
"=",
"TrafficLightParams",
"(",
")",
")",
":",
"optional",
"=",
"[",
"\"tl_logic\"",
"]",
"for",
... | https://github.com/flow-project/flow/blob/a511c41c48e6b928bb2060de8ad1ef3c3e3d9554/flow/networks/traffic_light_grid.py#L108-L164 | ||
python-telegram-bot/python-telegram-bot | ade1529986f5b6d394a65372d6a27045a70725b2 | telegram/ext/handler.py | python | Handler.collect_additional_context | (
self,
context: CCT,
update: UT,
dispatcher: 'Dispatcher',
check_result: Any,
) | Prepares additional arguments for the context. Override if needed.
Args:
context (:class:`telegram.ext.CallbackContext`): The context object.
update (:class:`telegram.Update`): The update to gather chat/user id from.
dispatcher (:class:`telegram.ext.Dispatcher`): The calling dispatcher.
check_result: The result (return value) from :attr:`check_update`. | Prepares additional arguments for the context. Override if needed. | [
"Prepares",
"additional",
"arguments",
"for",
"the",
"context",
".",
"Override",
"if",
"needed",
"."
] | def collect_additional_context(
self,
context: CCT,
update: UT,
dispatcher: 'Dispatcher',
check_result: Any,
) -> None:
"""Prepares additional arguments for the context. Override if needed.
Args:
context (:class:`telegram.ext.CallbackContext`): The context object.
update (:class:`telegram.Update`): The update to gather chat/user id from.
dispatcher (:class:`telegram.ext.Dispatcher`): The calling dispatcher.
check_result: The result (return value) from :attr:`check_update`.
""" | [
"def",
"collect_additional_context",
"(",
"self",
",",
"context",
":",
"CCT",
",",
"update",
":",
"UT",
",",
"dispatcher",
":",
"'Dispatcher'",
",",
"check_result",
":",
"Any",
",",
")",
"->",
"None",
":"
] | https://github.com/python-telegram-bot/python-telegram-bot/blob/ade1529986f5b6d394a65372d6a27045a70725b2/telegram/ext/handler.py#L207-L222 | ||
srossross/Meta | c449a07610b2df57e29bd0aefe36d6018f7b8c87 | meta/decompiler/simple_instructions.py | python | SimpleInstructions.STORE_SLICE_1 | (self, instr) | obj[lower:] = expr | obj[lower:] = expr | [
"obj",
"[",
"lower",
":",
"]",
"=",
"expr"
] | def STORE_SLICE_1(self, instr):
'obj[lower:] = expr'
lower = self.pop_ast_item()
value = self.pop_ast_item()
expr = self.pop_ast_item()
kw = dict(lineno=instr.lineno, col_offset=0)
slice = _ast.Slice(lower=lower, step=None, upper=None, **kw)
subscr = _ast.Subscript(value=value, slice=slice, ctx=_ast.Store(), **kw)
assign = _ast.Assign(targets=[subscr], value=expr, **kw)
self.push_ast_item(assign) | [
"def",
"STORE_SLICE_1",
"(",
"self",
",",
"instr",
")",
":",
"lower",
"=",
"self",
".",
"pop_ast_item",
"(",
")",
"value",
"=",
"self",
".",
"pop_ast_item",
"(",
")",
"expr",
"=",
"self",
".",
"pop_ast_item",
"(",
")",
"kw",
"=",
"dict",
"(",
"lineno... | https://github.com/srossross/Meta/blob/c449a07610b2df57e29bd0aefe36d6018f7b8c87/meta/decompiler/simple_instructions.py#L799-L810 | ||
edgewall/trac | beb3e4eaf1e0a456d801a50a8614ecab06de29fc | trac/wiki/api.py | python | WikiSystem.get_pages | (self, prefix=None) | Iterate over the names of existing Wiki pages.
:param prefix: if given, only names that start with that
prefix are included. | Iterate over the names of existing Wiki pages. | [
"Iterate",
"over",
"the",
"names",
"of",
"existing",
"Wiki",
"pages",
"."
] | def get_pages(self, prefix=None):
"""Iterate over the names of existing Wiki pages.
:param prefix: if given, only names that start with that
prefix are included.
"""
for page in self.pages:
if not prefix or page.startswith(prefix):
yield page | [
"def",
"get_pages",
"(",
"self",
",",
"prefix",
"=",
"None",
")",
":",
"for",
"page",
"in",
"self",
".",
"pages",
":",
"if",
"not",
"prefix",
"or",
"page",
".",
"startswith",
"(",
"prefix",
")",
":",
"yield",
"page"
] | https://github.com/edgewall/trac/blob/beb3e4eaf1e0a456d801a50a8614ecab06de29fc/trac/wiki/api.py#L304-L312 | ||
anyoptimization/pymoo | c6426a721d95c932ae6dbb610e09b6c1b0e13594 | pymoo/core/problem.py | python | Problem.__init__ | (self,
n_var=-1,
n_obj=1,
n_constr=0,
xl=None,
xu=None,
check_inconsistencies=True,
replace_nan_values_by=np.inf,
exclude_from_serialization=None,
callback=None,
**kwargs) | Parameters
----------
n_var : int
Number of Variables
n_obj : int
Number of Objectives
n_constr : int
Number of Constraints
xl : np.array, float, int
Lower bounds for the variables. if integer all lower bounds are equal.
xu : np.array, float, int
Upper bounds for the variable. if integer all upper bounds are equal.
type_var : numpy.dtype | [] | def __init__(self,
n_var=-1,
n_obj=1,
n_constr=0,
xl=None,
xu=None,
check_inconsistencies=True,
replace_nan_values_by=np.inf,
exclude_from_serialization=None,
callback=None,
**kwargs):
"""
Parameters
----------
n_var : int
Number of Variables
n_obj : int
Number of Objectives
n_constr : int
Number of Constraints
xl : np.array, float, int
Lower bounds for the variables. if integer all lower bounds are equal.
xu : np.array, float, int
Upper bounds for the variable. if integer all upper bounds are equal.
type_var : numpy.dtype
"""
if "elementwise_evaluation" in kwargs and kwargs.get("elementwise_evaluation"):
raise Exception("The interface in pymoo 0.5.0 has changed. Please inherit from the ElementwiseProblem "
"class AND remove the 'elementwise_evaluation=True' argument to disable this exception.")
# number of variable
self.n_var = n_var
# number of objectives
self.n_obj = n_obj
# number of constraints
self.n_constr = n_constr
# type of the variable to be evaluated
self.data = dict(**kwargs)
# the lower bounds, make sure it is a numpy array with the length of n_var
self.xl, self.xu = xl, xu
# a callback function to be called after every evaluation
self.callback = callback
# if it is a problem with an actual number of variables - make sure xl and xu are numpy arrays
if n_var > 0:
if self.xl is not None:
if not isinstance(self.xl, np.ndarray):
self.xl = np.ones(n_var) * xl
self.xl = self.xl.astype(float)
if self.xu is not None:
if not isinstance(self.xu, np.ndarray):
self.xu = np.ones(n_var) * xu
self.xu = self.xu.astype(float)
# whether the problem should strictly be checked for inconsistency during evaluation
self.check_inconsistencies = check_inconsistencies
# this defines if NaN values should be replaced or not
self.replace_nan_values_by = replace_nan_values_by
# attribute which are excluded from being serialized )
self.exclude_from_serialization = exclude_from_serialization if exclude_from_serialization is not None else []
# the loader for the pareto set (ps)
self._pareto_set = Cache(calc_ps, raise_exception=False)
# the loader for the pareto front (pf)
self._pareto_front = Cache(calc_pf, raise_exception=False)
self._ideal_point, self._nadir_point = None, None | [
"def",
"__init__",
"(",
"self",
",",
"n_var",
"=",
"-",
"1",
",",
"n_obj",
"=",
"1",
",",
"n_constr",
"=",
"0",
",",
"xl",
"=",
"None",
",",
"xu",
"=",
"None",
",",
"check_inconsistencies",
"=",
"True",
",",
"replace_nan_values_by",
"=",
"np",
".",
... | https://github.com/anyoptimization/pymoo/blob/c6426a721d95c932ae6dbb610e09b6c1b0e13594/pymoo/core/problem.py#L15-L101 | |||
Chaffelson/nipyapi | d3b186fd701ce308c2812746d98af9120955e810 | nipyapi/nifi/models/counters_entity.py | python | CountersEntity.to_str | (self) | return pformat(self.to_dict()) | Returns the string representation of the model | Returns the string representation of the model | [
"Returns",
"the",
"string",
"representation",
"of",
"the",
"model"
] | def to_str(self):
"""
Returns the string representation of the model
"""
return pformat(self.to_dict()) | [
"def",
"to_str",
"(",
"self",
")",
":",
"return",
"pformat",
"(",
"self",
".",
"to_dict",
"(",
")",
")"
] | https://github.com/Chaffelson/nipyapi/blob/d3b186fd701ce308c2812746d98af9120955e810/nipyapi/nifi/models/counters_entity.py#L98-L102 | |
ACloudGuru/AdvancedCloudFormation | 6831cfbff1888951c9b2ede6cb87eeb71cfd8bf5 | 206-LambdaCustomEnhancements/autosubnet/requests/packages/urllib3/poolmanager.py | python | PoolManager.connection_from_url | (self, url) | return self.connection_from_host(u.host, port=u.port, scheme=u.scheme) | Similar to :func:`urllib3.connectionpool.connection_from_url` but
doesn't pass any additional parameters to the
:class:`urllib3.connectionpool.ConnectionPool` constructor.
Additional parameters are taken from the :class:`.PoolManager`
constructor. | Similar to :func:`urllib3.connectionpool.connection_from_url` but
doesn't pass any additional parameters to the
:class:`urllib3.connectionpool.ConnectionPool` constructor. | [
"Similar",
"to",
":",
"func",
":",
"urllib3",
".",
"connectionpool",
".",
"connection_from_url",
"but",
"doesn",
"t",
"pass",
"any",
"additional",
"parameters",
"to",
"the",
":",
"class",
":",
"urllib3",
".",
"connectionpool",
".",
"ConnectionPool",
"constructor... | def connection_from_url(self, url):
"""
Similar to :func:`urllib3.connectionpool.connection_from_url` but
doesn't pass any additional parameters to the
:class:`urllib3.connectionpool.ConnectionPool` constructor.
Additional parameters are taken from the :class:`.PoolManager`
constructor.
"""
u = parse_url(url)
return self.connection_from_host(u.host, port=u.port, scheme=u.scheme) | [
"def",
"connection_from_url",
"(",
"self",
",",
"url",
")",
":",
"u",
"=",
"parse_url",
"(",
"url",
")",
"return",
"self",
".",
"connection_from_host",
"(",
"u",
".",
"host",
",",
"port",
"=",
"u",
".",
"port",
",",
"scheme",
"=",
"u",
".",
"scheme",... | https://github.com/ACloudGuru/AdvancedCloudFormation/blob/6831cfbff1888951c9b2ede6cb87eeb71cfd8bf5/206-LambdaCustomEnhancements/autosubnet/requests/packages/urllib3/poolmanager.py#L216-L226 | |
robcarver17/pysystemtrade | b0385705b7135c52d39cb6d2400feece881bcca9 | sysdata/arctic/arctic_futures_per_contract_prices.py | python | arcticFuturesContractPriceData._delete_prices_for_contract_object_with_no_checks_be_careful | (
self, futures_contract_object: futuresContract
) | Delete prices for a given contract object without performing any checks
WILL THIS WORK IF DOESN'T EXIST?
:param futures_contract_object:
:return: None | Delete prices for a given contract object without performing any checks | [
"Delete",
"prices",
"for",
"a",
"given",
"contract",
"object",
"without",
"performing",
"any",
"checks"
] | def _delete_prices_for_contract_object_with_no_checks_be_careful(
self, futures_contract_object: futuresContract
):
"""
Delete prices for a given contract object without performing any checks
WILL THIS WORK IF DOESN'T EXIST?
:param futures_contract_object:
:return: None
"""
log = futures_contract_object.log(self.log)
ident = from_contract_to_key(futures_contract_object)
self.arctic_connection.delete(ident)
log.msg(
"Deleted all prices for %s from %s"
% (futures_contract_object.key, str(self))
) | [
"def",
"_delete_prices_for_contract_object_with_no_checks_be_careful",
"(",
"self",
",",
"futures_contract_object",
":",
"futuresContract",
")",
":",
"log",
"=",
"futures_contract_object",
".",
"log",
"(",
"self",
".",
"log",
")",
"ident",
"=",
"from_contract_to_key",
"... | https://github.com/robcarver17/pysystemtrade/blob/b0385705b7135c52d39cb6d2400feece881bcca9/sysdata/arctic/arctic_futures_per_contract_prices.py#L117-L134 | ||
capless/warrant | e81f9a6dd6e36be3b6fa1dbbd11334ec92124ace | warrant/aws_srp.py | python | AWSSRP.generate_random_small_a | (self) | return random_long_int % self.big_n | helper function to generate a random big integer
:return {Long integer} a random value. | helper function to generate a random big integer
:return {Long integer} a random value. | [
"helper",
"function",
"to",
"generate",
"a",
"random",
"big",
"integer",
":",
"return",
"{",
"Long",
"integer",
"}",
"a",
"random",
"value",
"."
] | def generate_random_small_a(self):
"""
helper function to generate a random big integer
:return {Long integer} a random value.
"""
random_long_int = get_random(128)
return random_long_int % self.big_n | [
"def",
"generate_random_small_a",
"(",
"self",
")",
":",
"random_long_int",
"=",
"get_random",
"(",
"128",
")",
"return",
"random_long_int",
"%",
"self",
".",
"big_n"
] | https://github.com/capless/warrant/blob/e81f9a6dd6e36be3b6fa1dbbd11334ec92124ace/warrant/aws_srp.py#L116-L122 | |
edisonlz/fastor | 342078a18363ac41d3c6b1ab29dbdd44fdb0b7b3 | base/site-packages/atom/core.py | python | XmlElement._attach_members | (self, tree, version=1, encoding=None) | Convert members to XML elements/attributes and add them to the tree.
Args:
tree: An ElementTree.Element which will be modified. The members of
this object will be added as child elements or attributes
according to the rules described in _expected_elements and
_expected_attributes. The elements and attributes stored in
other_attributes and other_elements are also added a children
of this tree.
version: int Ingnored in this method but used by VersionedElement. | Convert members to XML elements/attributes and add them to the tree.
Args:
tree: An ElementTree.Element which will be modified. The members of
this object will be added as child elements or attributes
according to the rules described in _expected_elements and
_expected_attributes. The elements and attributes stored in
other_attributes and other_elements are also added a children
of this tree.
version: int Ingnored in this method but used by VersionedElement. | [
"Convert",
"members",
"to",
"XML",
"elements",
"/",
"attributes",
"and",
"add",
"them",
"to",
"the",
"tree",
".",
"Args",
":",
"tree",
":",
"An",
"ElementTree",
".",
"Element",
"which",
"will",
"be",
"modified",
".",
"The",
"members",
"of",
"this",
"obje... | def _attach_members(self, tree, version=1, encoding=None):
"""Convert members to XML elements/attributes and add them to the tree.
Args:
tree: An ElementTree.Element which will be modified. The members of
this object will be added as child elements or attributes
according to the rules described in _expected_elements and
_expected_attributes. The elements and attributes stored in
other_attributes and other_elements are also added a children
of this tree.
version: int Ingnored in this method but used by VersionedElement.
"""
qname, elements, attributes = self.__class__._get_rules(version)
encoding = encoding or STRING_ENCODING
# Add the expected elements and attributes to the tree.
if elements:
for tag, element_def in elements.iteritems():
member = getattr(self, element_def[0])
# If this is a repeating element and there are members in the list.
if member and element_def[2]:
for instance in member:
instance._become_child(tree, version)
elif member:
member._become_child(tree, version)
if attributes:
for attribute_tag, member_name in attributes.iteritems():
value = getattr(self, member_name)
if value:
tree.attrib[attribute_tag] = value
# Add the unexpected (other) elements and attributes to the tree.
for element in self._other_elements:
element._become_child(tree, version)
for key, value in self._other_attributes.iteritems():
# I'm not sure if unicode can be used in the attribute name, so for now
# we assume the encoding is correct for the attribute name.
if not isinstance(value, unicode):
value = value.decode(encoding)
tree.attrib[key] = value
if self.text:
if isinstance(self.text, unicode):
tree.text = self.text
else:
tree.text = self.text.decode(encoding) | [
"def",
"_attach_members",
"(",
"self",
",",
"tree",
",",
"version",
"=",
"1",
",",
"encoding",
"=",
"None",
")",
":",
"qname",
",",
"elements",
",",
"attributes",
"=",
"self",
".",
"__class__",
".",
"_get_rules",
"(",
"version",
")",
"encoding",
"=",
"... | https://github.com/edisonlz/fastor/blob/342078a18363ac41d3c6b1ab29dbdd44fdb0b7b3/base/site-packages/atom/core.py#L258-L300 | ||
translate/pootle | 742c08fce1a0dc16e6ab8d2494eb867c8879205d | pootle/apps/pootle_project/forms.py | python | TranslationProjectForm.__init__ | (self, *args, **kwargs) | If this form is not bound, it must be called with an initial value
for Project. | If this form is not bound, it must be called with an initial value
for Project. | [
"If",
"this",
"form",
"is",
"not",
"bound",
"it",
"must",
"be",
"called",
"with",
"an",
"initial",
"value",
"for",
"Project",
"."
] | def __init__(self, *args, **kwargs):
"""If this form is not bound, it must be called with an initial value
for Project.
"""
super(TranslationProjectForm, self).__init__(*args, **kwargs)
if kwargs.get("instance"):
project_id = kwargs["instance"].project.pk
project = kwargs["instance"].project
language = kwargs["instance"].language
mappings = project.config.get("pootle.core.lang_mapping", {})
mappings = dict((v, k) for k, v in mappings.iteritems())
mapped = mappings.get(language.code)
self.fields["fs_code"].initial = mapped
else:
project_id = kwargs["initial"]["project"]
self.fields["language"].queryset = (
self.fields["language"].queryset.exclude(
translationproject__project_id=project_id))
self.fields["project"].queryset = self.fields[
"project"].queryset.filter(pk=project_id) | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"super",
"(",
"TranslationProjectForm",
",",
"self",
")",
".",
"__init__",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"kwargs",
".",
"get",
"(",
"\"inst... | https://github.com/translate/pootle/blob/742c08fce1a0dc16e6ab8d2494eb867c8879205d/pootle/apps/pootle_project/forms.py#L83-L102 | ||
maraoz/proofofexistence | 10703675824e989f59a8d36fd8c06394e71a2c25 | babel/messages/checkers.py | python | python_format | (catalog, message) | Verify the format string placeholders in the translation. | Verify the format string placeholders in the translation. | [
"Verify",
"the",
"format",
"string",
"placeholders",
"in",
"the",
"translation",
"."
] | def python_format(catalog, message):
"""Verify the format string placeholders in the translation."""
if 'python-format' not in message.flags:
return
msgids = message.id
if not isinstance(msgids, (list, tuple)):
msgids = (msgids,)
msgstrs = message.string
if not isinstance(msgstrs, (list, tuple)):
msgstrs = (msgstrs,)
for msgid, msgstr in izip(msgids, msgstrs):
if msgstr:
_validate_format(msgid, msgstr) | [
"def",
"python_format",
"(",
"catalog",
",",
"message",
")",
":",
"if",
"'python-format'",
"not",
"in",
"message",
".",
"flags",
":",
"return",
"msgids",
"=",
"message",
".",
"id",
"if",
"not",
"isinstance",
"(",
"msgids",
",",
"(",
"list",
",",
"tuple",... | https://github.com/maraoz/proofofexistence/blob/10703675824e989f59a8d36fd8c06394e71a2c25/babel/messages/checkers.py#L46-L59 | ||
kubernetes-client/python | 47b9da9de2d02b2b7a34fbe05afb44afd130d73a | kubernetes/client/models/v1alpha1_storage_version_condition.py | python | V1alpha1StorageVersionCondition.reason | (self) | return self._reason | Gets the reason of this V1alpha1StorageVersionCondition. # noqa: E501
The reason for the condition's last transition. # noqa: E501
:return: The reason of this V1alpha1StorageVersionCondition. # noqa: E501
:rtype: str | Gets the reason of this V1alpha1StorageVersionCondition. # noqa: E501 | [
"Gets",
"the",
"reason",
"of",
"this",
"V1alpha1StorageVersionCondition",
".",
"#",
"noqa",
":",
"E501"
] | def reason(self):
"""Gets the reason of this V1alpha1StorageVersionCondition. # noqa: E501
The reason for the condition's last transition. # noqa: E501
:return: The reason of this V1alpha1StorageVersionCondition. # noqa: E501
:rtype: str
"""
return self._reason | [
"def",
"reason",
"(",
"self",
")",
":",
"return",
"self",
".",
"_reason"
] | https://github.com/kubernetes-client/python/blob/47b9da9de2d02b2b7a34fbe05afb44afd130d73a/kubernetes/client/models/v1alpha1_storage_version_condition.py#L147-L155 | |
NoGameNoLife00/mybolg | afe17ea5bfe405e33766e5682c43a4262232ee12 | libs/sqlalchemy/engine/result.py | python | ResultProxy.postfetch_cols | (self) | return self.context.postfetch_cols | Return ``postfetch_cols()`` from the underlying
:class:`.ExecutionContext`.
See :class:`.ExecutionContext` for details.
Raises :class:`~sqlalchemy.exc.InvalidRequestError` if the executed
statement is not a compiled expression construct
or is not an insert() or update() construct. | Return ``postfetch_cols()`` from the underlying
:class:`.ExecutionContext`. | [
"Return",
"postfetch_cols",
"()",
"from",
"the",
"underlying",
":",
"class",
":",
".",
"ExecutionContext",
"."
] | def postfetch_cols(self):
"""Return ``postfetch_cols()`` from the underlying
:class:`.ExecutionContext`.
See :class:`.ExecutionContext` for details.
Raises :class:`~sqlalchemy.exc.InvalidRequestError` if the executed
statement is not a compiled expression construct
or is not an insert() or update() construct.
"""
if not self.context.compiled:
raise exc.InvalidRequestError(
"Statement is not a compiled "
"expression construct.")
elif not self.context.isinsert and not self.context.isupdate:
raise exc.InvalidRequestError(
"Statement is not an insert() or update() "
"expression construct.")
return self.context.postfetch_cols | [
"def",
"postfetch_cols",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"context",
".",
"compiled",
":",
"raise",
"exc",
".",
"InvalidRequestError",
"(",
"\"Statement is not a compiled \"",
"\"expression construct.\"",
")",
"elif",
"not",
"self",
".",
"context",... | https://github.com/NoGameNoLife00/mybolg/blob/afe17ea5bfe405e33766e5682c43a4262232ee12/libs/sqlalchemy/engine/result.py#L669-L689 | |
YaoZeyuan/ZhihuHelp_archived | a0e4a7acd4512452022ce088fff2adc6f8d30195 | src/container/task_result.py | python | Question.__init__ | (self, question_info) | return | :type question_info : Question_Info | :type question_info : Question_Info | [
":",
"type",
"question_info",
":",
"Question_Info"
] | def __init__(self, question_info):
"""
:type question_info : Question_Info
"""
self.question_info = question_info
self.answer_list = [] # type: list[Answer_Info]
self.total_img_size_kb = 0
self.img_filename_list = []
self.question_content_img_size = 0
self.question_content_img_filename_list = []
return | [
"def",
"__init__",
"(",
"self",
",",
"question_info",
")",
":",
"self",
".",
"question_info",
"=",
"question_info",
"self",
".",
"answer_list",
"=",
"[",
"]",
"# type: list[Answer_Info]",
"self",
".",
"total_img_size_kb",
"=",
"0",
"self",
".",
"img_filename_lis... | https://github.com/YaoZeyuan/ZhihuHelp_archived/blob/a0e4a7acd4512452022ce088fff2adc6f8d30195/src/container/task_result.py#L22-L34 | |
mitre/caldera | 46429594584f3852d1f9353402407fdb7c1a8302 | app/service/event_svc.py | python | EventService.register_global_event_listener | (self, callback) | Register a global event listener that is fired when any event
is fired.
:param callback: Callback function
:type callback: function | Register a global event listener that is fired when any event
is fired. | [
"Register",
"a",
"global",
"event",
"listener",
"that",
"is",
"fired",
"when",
"any",
"event",
"is",
"fired",
"."
] | async def register_global_event_listener(self, callback):
"""
Register a global event listener that is fired when any event
is fired.
:param callback: Callback function
:type callback: function
"""
self.global_listeners.append(callback) | [
"async",
"def",
"register_global_event_listener",
"(",
"self",
",",
"callback",
")",
":",
"self",
".",
"global_listeners",
".",
"append",
"(",
"callback",
")"
] | https://github.com/mitre/caldera/blob/46429594584f3852d1f9353402407fdb7c1a8302/app/service/event_svc.py#L40-L48 | ||
FederatedAI/FATE | 32540492623568ecd1afcb367360133616e02fa3 | python/federatedml/feature/homo_feature_binning/homo_binning_base.py | python | SplitPointNode.set_aim_rank | (self, rank) | [] | def set_aim_rank(self, rank):
self.aim_rank = rank | [
"def",
"set_aim_rank",
"(",
"self",
",",
"rank",
")",
":",
"self",
".",
"aim_rank",
"=",
"rank"
] | https://github.com/FederatedAI/FATE/blob/32540492623568ecd1afcb367360133616e02fa3/python/federatedml/feature/homo_feature_binning/homo_binning_base.py#L40-L41 | ||||
rdiff-backup/rdiff-backup | 321e0cd6e5e47d4c158a0172e47ab38240a8b653 | src/rdiff_backup/backup.py | python | CacheCollatedPostProcess.close | (self) | Process the remaining elements in the cache | Process the remaining elements in the cache | [
"Process",
"the",
"remaining",
"elements",
"in",
"the",
"cache"
] | def close(self):
"""Process the remaining elements in the cache"""
while self.cache_indices:
self._shorten_cache()
while self.dir_perms_list:
dir_rp, perms = self.dir_perms_list.pop()
dir_rp.chmod(perms)
self.metawriter.close()
metadata.ManagerObj.ConvertMetaToDiff() | [
"def",
"close",
"(",
"self",
")",
":",
"while",
"self",
".",
"cache_indices",
":",
"self",
".",
"_shorten_cache",
"(",
")",
"while",
"self",
".",
"dir_perms_list",
":",
"dir_rp",
",",
"perms",
"=",
"self",
".",
"dir_perms_list",
".",
"pop",
"(",
")",
"... | https://github.com/rdiff-backup/rdiff-backup/blob/321e0cd6e5e47d4c158a0172e47ab38240a8b653/src/rdiff_backup/backup.py#L432-L440 | ||
apple/ccs-calendarserver | 13c706b985fb728b9aab42dc0fef85aae21921c3 | twistedcaldav/directory/util.py | python | transactionFromRequest | (request, newStore) | return transaction | Return the associated transaction from the given HTTP request, creating a
new one from the given data store if none has yet been associated.
Also, if the request was not previously associated with a transaction, add
a failsafe transaction-abort response filter to abort any transaction which
has not been committed or aborted by the resource which responds to the
request.
@param request: The request to inspect.
@type request: L{IRequest}
@param newStore: The store to create a transaction from.
@type newStore: L{IDataStore}
@return: a transaction that should be used to read and write data
associated with the request.
@rtype: L{ITransaction} (and possibly L{ICalendarTransaction} and
L{IAddressBookTransaction} as well. | Return the associated transaction from the given HTTP request, creating a
new one from the given data store if none has yet been associated. | [
"Return",
"the",
"associated",
"transaction",
"from",
"the",
"given",
"HTTP",
"request",
"creating",
"a",
"new",
"one",
"from",
"the",
"given",
"data",
"store",
"if",
"none",
"has",
"yet",
"been",
"associated",
"."
] | def transactionFromRequest(request, newStore):
"""
Return the associated transaction from the given HTTP request, creating a
new one from the given data store if none has yet been associated.
Also, if the request was not previously associated with a transaction, add
a failsafe transaction-abort response filter to abort any transaction which
has not been committed or aborted by the resource which responds to the
request.
@param request: The request to inspect.
@type request: L{IRequest}
@param newStore: The store to create a transaction from.
@type newStore: L{IDataStore}
@return: a transaction that should be used to read and write data
associated with the request.
@rtype: L{ITransaction} (and possibly L{ICalendarTransaction} and
L{IAddressBookTransaction} as well.
"""
transaction = getattr(request, TRANSACTION_KEY, None)
if transaction is None:
if hasattr(request, "authzUser") and request.authzUser is not None:
authz_uid = request.authzUser.record.uid
else:
authz_uid = None
transaction = newStore.newTransaction(repr(request), authz_uid=authz_uid)
def abortIfUncommitted(request, response):
try:
# TODO: missing 'yield' here. For formal correctness as per
# the interface, this should be allowed to be a Deferred. (The
# actual implementation still raises synchronously, so there's
# no bug currently.)
transaction.abort()
except AlreadyFinishedError:
pass
return response
abortIfUncommitted.handleErrors = True
request.addResponseFilter(abortIfUncommitted)
setattr(request, TRANSACTION_KEY, transaction)
return transaction | [
"def",
"transactionFromRequest",
"(",
"request",
",",
"newStore",
")",
":",
"transaction",
"=",
"getattr",
"(",
"request",
",",
"TRANSACTION_KEY",
",",
"None",
")",
"if",
"transaction",
"is",
"None",
":",
"if",
"hasattr",
"(",
"request",
",",
"\"authzUser\"",
... | https://github.com/apple/ccs-calendarserver/blob/13c706b985fb728b9aab42dc0fef85aae21921c3/twistedcaldav/directory/util.py#L73-L115 | |
matrix-org/synapse | 8e57584a5859a9002759963eb546d523d2498a01 | synapse/storage/databases/main/events.py | python | PersistEventsStore._handle_redaction | (self, txn, redacted_event_id) | Handles receiving a redaction and checking whether we need to remove
any redacted relations from the database.
Args:
txn
redacted_event_id (str): The event that was redacted. | Handles receiving a redaction and checking whether we need to remove
any redacted relations from the database. | [
"Handles",
"receiving",
"a",
"redaction",
"and",
"checking",
"whether",
"we",
"need",
"to",
"remove",
"any",
"redacted",
"relations",
"from",
"the",
"database",
"."
] | def _handle_redaction(self, txn, redacted_event_id):
"""Handles receiving a redaction and checking whether we need to remove
any redacted relations from the database.
Args:
txn
redacted_event_id (str): The event that was redacted.
"""
self.db_pool.simple_delete_txn(
txn, table="event_relations", keyvalues={"event_id": redacted_event_id}
) | [
"def",
"_handle_redaction",
"(",
"self",
",",
"txn",
",",
"redacted_event_id",
")",
":",
"self",
".",
"db_pool",
".",
"simple_delete_txn",
"(",
"txn",
",",
"table",
"=",
"\"event_relations\"",
",",
"keyvalues",
"=",
"{",
"\"event_id\"",
":",
"redacted_event_id",... | https://github.com/matrix-org/synapse/blob/8e57584a5859a9002759963eb546d523d2498a01/synapse/storage/databases/main/events.py#L1915-L1926 | ||
huggingface/transformers | 623b4f7c63f60cce917677ee704d6c93ee960b4b | src/transformers/models/ibert/modeling_ibert.py | python | IBertSelfOutput.__init__ | (self, config) | [] | def __init__(self, config):
super().__init__()
self.quant_mode = config.quant_mode
self.act_bit = 8
self.weight_bit = 8
self.bias_bit = 32
self.ln_input_bit = 22
self.ln_output_bit = 32
self.dense = QuantLinear(
config.hidden_size,
config.hidden_size,
bias=True,
weight_bit=self.weight_bit,
bias_bit=self.bias_bit,
quant_mode=self.quant_mode,
per_channel=True,
)
self.ln_input_act = QuantAct(self.ln_input_bit, quant_mode=self.quant_mode)
self.LayerNorm = IntLayerNorm(
config.hidden_size,
eps=config.layer_norm_eps,
output_bit=self.ln_output_bit,
quant_mode=self.quant_mode,
force_dequant=config.force_dequant,
)
self.output_activation = QuantAct(self.act_bit, quant_mode=self.quant_mode)
self.dropout = nn.Dropout(config.hidden_dropout_prob) | [
"def",
"__init__",
"(",
"self",
",",
"config",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
")",
"self",
".",
"quant_mode",
"=",
"config",
".",
"quant_mode",
"self",
".",
"act_bit",
"=",
"8",
"self",
".",
"weight_bit",
"=",
"8",
"self",
".",
... | https://github.com/huggingface/transformers/blob/623b4f7c63f60cce917677ee704d6c93ee960b4b/src/transformers/models/ibert/modeling_ibert.py#L321-L348 | ||||
stopstalk/stopstalk-deployment | 10c3ab44c4ece33ae515f6888c15033db2004bb1 | aws_lambda/spoj_aws_lambda_function/lambda_code/pip/_vendor/distlib/database.py | python | _Cache.add | (self, dist) | Add a distribution to the cache.
:param dist: The distribution to add. | Add a distribution to the cache.
:param dist: The distribution to add. | [
"Add",
"a",
"distribution",
"to",
"the",
"cache",
".",
":",
"param",
"dist",
":",
"The",
"distribution",
"to",
"add",
"."
] | def add(self, dist):
"""
Add a distribution to the cache.
:param dist: The distribution to add.
"""
if dist.path not in self.path:
self.path[dist.path] = dist
self.name.setdefault(dist.key, []).append(dist) | [
"def",
"add",
"(",
"self",
",",
"dist",
")",
":",
"if",
"dist",
".",
"path",
"not",
"in",
"self",
".",
"path",
":",
"self",
".",
"path",
"[",
"dist",
".",
"path",
"]",
"=",
"dist",
"self",
".",
"name",
".",
"setdefault",
"(",
"dist",
".",
"key"... | https://github.com/stopstalk/stopstalk-deployment/blob/10c3ab44c4ece33ae515f6888c15033db2004bb1/aws_lambda/spoj_aws_lambda_function/lambda_code/pip/_vendor/distlib/database.py#L64-L71 | ||
PreOS-Security/fwaudit | f38d8ace3c1be487edc2d66d689aa5bb9ff07f56 | fwaudit.py | python | return_hash_str_of_file | (path) | return hash_str | For a given file, return the sha256 hash string.
Returns a SHA256 hash string if successful, None if unsuccessful. | For a given file, return the sha256 hash string.
Returns a SHA256 hash string if successful, None if unsuccessful. | [
"For",
"a",
"given",
"file",
"return",
"the",
"sha256",
"hash",
"string",
".",
"Returns",
"a",
"SHA256",
"hash",
"string",
"if",
"successful",
"None",
"if",
"unsuccessful",
"."
] | def return_hash_str_of_file(path):
'''For a given file, return the sha256 hash string.
Returns a SHA256 hash string if successful, None if unsuccessful.'''
if is_none_or_null(path):
error('Filename to hash unspecified')
return None
if not path_exists(path):
error('File to hash does not exist: ' + path)
return None
debug('file to hash: ' + path)
hash_str = None
try:
with open(path, 'rb') as f:
buf = f.read()
h = hashlib.sha256(buf)
h.update(buf)
hash_str = h.hexdigest()
debug('hash: ' + hash_str)
except OSError as e:
critical(e, 'failed to hash file')
hash_str = None
sys.exc_info()
return hash_str | [
"def",
"return_hash_str_of_file",
"(",
"path",
")",
":",
"if",
"is_none_or_null",
"(",
"path",
")",
":",
"error",
"(",
"'Filename to hash unspecified'",
")",
"return",
"None",
"if",
"not",
"path_exists",
"(",
"path",
")",
":",
"error",
"(",
"'File to hash does n... | https://github.com/PreOS-Security/fwaudit/blob/f38d8ace3c1be487edc2d66d689aa5bb9ff07f56/fwaudit.py#L1669-L1692 | |
JaniceWuo/MovieRecommend | 4c86db64ca45598917d304f535413df3bc9fea65 | movierecommend/venv1/Lib/site-packages/pip-9.0.1-py3.6.egg/pip/_vendor/distlib/markers.py | python | Evaluator.do_attribute | (self, node) | return result | [] | def do_attribute(self, node):
if not isinstance(node.value, ast.Name):
valid = False
else:
key = self.get_attr_key(node)
valid = key in self.context or key in self.allowed_values
if not valid:
raise SyntaxError('invalid expression: %s' % key)
if key in self.context:
result = self.context[key]
else:
result = self.allowed_values[key]
return result | [
"def",
"do_attribute",
"(",
"self",
",",
"node",
")",
":",
"if",
"not",
"isinstance",
"(",
"node",
".",
"value",
",",
"ast",
".",
"Name",
")",
":",
"valid",
"=",
"False",
"else",
":",
"key",
"=",
"self",
".",
"get_attr_key",
"(",
"node",
")",
"vali... | https://github.com/JaniceWuo/MovieRecommend/blob/4c86db64ca45598917d304f535413df3bc9fea65/movierecommend/venv1/Lib/site-packages/pip-9.0.1-py3.6.egg/pip/_vendor/distlib/markers.py#L106-L118 | |||
Pymol-Scripts/Pymol-script-repo | bcd7bb7812dc6db1595953dfa4471fa15fb68c77 | modules/ADT/mglutil/util/tree.py | python | TreeNode.add_child | (self, child) | Add given node to children of self.
parent.add_child( node) adds node to children of parent.
This is done in the __init__ if parent is given when node
in instanciated (that's the prefered method). | Add given node to children of self. | [
"Add",
"given",
"node",
"to",
"children",
"of",
"self",
"."
] | def add_child(self, child):
"""Add given node to children of self.
parent.add_child( node) adds node to children of parent.
This is done in the __init__ if parent is given when node
in instanciated (that's the prefered method).
"""
self.children.append(child) | [
"def",
"add_child",
"(",
"self",
",",
"child",
")",
":",
"self",
".",
"children",
".",
"append",
"(",
"child",
")"
] | https://github.com/Pymol-Scripts/Pymol-script-repo/blob/bcd7bb7812dc6db1595953dfa4471fa15fb68c77/modules/ADT/mglutil/util/tree.py#L24-L31 | ||
tensorflow/transform | bc5c3da6aebe9c8780da806e7e8103959c242863 | tensorflow_transform/tf_metadata/schema_utils.py | python | _ragged_tensor_representation_as_feature_spec | (
name: str, tensor_representation: schema_pb2.TensorRepresentation,
feature_by_name: Dict[str, schema_pb2.Feature],
string_domains: Dict[str, common_types.DomainType]
) | return spec, domain | Returns a representation of a RaggedTensor as a feature spec. | Returns a representation of a RaggedTensor as a feature spec. | [
"Returns",
"a",
"representation",
"of",
"a",
"RaggedTensor",
"as",
"a",
"feature",
"spec",
"."
] | def _ragged_tensor_representation_as_feature_spec(
name: str, tensor_representation: schema_pb2.TensorRepresentation,
feature_by_name: Dict[str, schema_pb2.Feature],
string_domains: Dict[str, common_types.DomainType]
) -> Tuple[common_types.RaggedFeature, Optional[common_types.DomainType]]:
"""Returns a representation of a RaggedTensor as a feature spec."""
if not common_types.is_ragged_feature_available():
raise ValueError('RaggedFeature is not supported in TF 1.x.')
value_feature = pop_ragged_source_columns(name, tensor_representation,
feature_by_name)
spec = tensor_representation_util.CreateTfExampleParserConfig(
tensor_representation, value_feature.type)
domain = _get_domain(value_feature, string_domains)
return spec, domain | [
"def",
"_ragged_tensor_representation_as_feature_spec",
"(",
"name",
":",
"str",
",",
"tensor_representation",
":",
"schema_pb2",
".",
"TensorRepresentation",
",",
"feature_by_name",
":",
"Dict",
"[",
"str",
",",
"schema_pb2",
".",
"Feature",
"]",
",",
"string_domains... | https://github.com/tensorflow/transform/blob/bc5c3da6aebe9c8780da806e7e8103959c242863/tensorflow_transform/tf_metadata/schema_utils.py#L404-L418 | |
Tautulli/Tautulli | 2410eb33805aaac4bd1c5dad0f71e4f15afaf742 | lib/dateutil/relativedelta.py | python | relativedelta.__radd__ | (self, other) | return self.__add__(other) | [] | def __radd__(self, other):
return self.__add__(other) | [
"def",
"__radd__",
"(",
"self",
",",
"other",
")",
":",
"return",
"self",
".",
"__add__",
"(",
"other",
")"
] | https://github.com/Tautulli/Tautulli/blob/2410eb33805aaac4bd1c5dad0f71e4f15afaf742/lib/dateutil/relativedelta.py#L404-L405 | |||
OpenEndedGroup/Field | 4f7c8edfb01bb0ccc927b78d3c500f018a4ae37c | Contents/lib/python/shutil.py | python | copy | (src, dst) | Copy data and mode bits ("cp src dst").
The destination may be a directory. | Copy data and mode bits ("cp src dst"). | [
"Copy",
"data",
"and",
"mode",
"bits",
"(",
"cp",
"src",
"dst",
")",
"."
] | def copy(src, dst):
"""Copy data and mode bits ("cp src dst").
The destination may be a directory.
"""
if os.path.isdir(dst):
dst = os.path.join(dst, os.path.basename(src))
copyfile(src, dst)
copymode(src, dst) | [
"def",
"copy",
"(",
"src",
",",
"dst",
")",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"dst",
")",
":",
"dst",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dst",
",",
"os",
".",
"path",
".",
"basename",
"(",
"src",
")",
")",
"copyfile",
... | https://github.com/OpenEndedGroup/Field/blob/4f7c8edfb01bb0ccc927b78d3c500f018a4ae37c/Contents/lib/python/shutil.py#L77-L86 | ||
Cadene/tensorflow-model-zoo.torch | 990b10ffc22d4c8eacb2a502f20415b4f70c74c2 | models/research/syntaxnet/syntaxnet/util/check.py | python | NotIn | (key, container, message='', error=ValueError) | Raises an error if |key| is in |container|. | Raises an error if |key| is in |container|. | [
"Raises",
"an",
"error",
"if",
"|key|",
"is",
"in",
"|container|",
"."
] | def NotIn(key, container, message='', error=ValueError):
"""Raises an error if |key| is in |container|."""
if key in container:
raise error('Expected (%s) is not in (%s): %s' % (key, container, message)) | [
"def",
"NotIn",
"(",
"key",
",",
"container",
",",
"message",
"=",
"''",
",",
"error",
"=",
"ValueError",
")",
":",
"if",
"key",
"in",
"container",
":",
"raise",
"error",
"(",
"'Expected (%s) is not in (%s): %s'",
"%",
"(",
"key",
",",
"container",
",",
... | https://github.com/Cadene/tensorflow-model-zoo.torch/blob/990b10ffc22d4c8eacb2a502f20415b4f70c74c2/models/research/syntaxnet/syntaxnet/util/check.py#L93-L96 | ||
eliben/pyelftools | 8f7a0becaface09435c4374947548b7851e3d1a2 | elftools/dwarf/namelut.py | python | NameLUT.get_entries | (self) | return self._entries | Returns the parsed NameLUT entries. The returned object is a dictionary
with the symbol name as the key and NameLUTEntry(cu_ofs, die_ofs) as
the value.
This is useful when dealing with very large ELF files with millions of
entries. The returned entries can be pickled to a file and restored by
calling set_entries on subsequent loads. | Returns the parsed NameLUT entries. The returned object is a dictionary
with the symbol name as the key and NameLUTEntry(cu_ofs, die_ofs) as
the value. | [
"Returns",
"the",
"parsed",
"NameLUT",
"entries",
".",
"The",
"returned",
"object",
"is",
"a",
"dictionary",
"with",
"the",
"symbol",
"name",
"as",
"the",
"key",
"and",
"NameLUTEntry",
"(",
"cu_ofs",
"die_ofs",
")",
"as",
"the",
"value",
"."
] | def get_entries(self):
"""
Returns the parsed NameLUT entries. The returned object is a dictionary
with the symbol name as the key and NameLUTEntry(cu_ofs, die_ofs) as
the value.
This is useful when dealing with very large ELF files with millions of
entries. The returned entries can be pickled to a file and restored by
calling set_entries on subsequent loads.
"""
if self._entries is None:
self._entries, self._cu_headers = self._get_entries()
return self._entries | [
"def",
"get_entries",
"(",
"self",
")",
":",
"if",
"self",
".",
"_entries",
"is",
"None",
":",
"self",
".",
"_entries",
",",
"self",
".",
"_cu_headers",
"=",
"self",
".",
"_get_entries",
"(",
")",
"return",
"self",
".",
"_entries"
] | https://github.com/eliben/pyelftools/blob/8f7a0becaface09435c4374947548b7851e3d1a2/elftools/dwarf/namelut.py#L74-L86 | |
ReFirmLabs/binwalk | fa0c0bd59b8588814756942fe4cb5452e76c1dcd | src/binwalk/modules/extractor.py | python | Extractor.extract | (self, offset, description, file_name, size, name=None) | return (output_directory, fname, recurse, command_line) | Extract an embedded file from the target file, if it matches an extract rule.
Called automatically by Binwalk.scan().
@offset - Offset inside the target file to begin the extraction.
@description - Description of the embedded file to extract, as returned by libmagic.
@file_name - Path to the target file.
@size - Number of bytes to extract.
@name - Name to save the file as.
Returns the name of the extracted file (blank string if nothing was extracted). | Extract an embedded file from the target file, if it matches an extract rule.
Called automatically by Binwalk.scan(). | [
"Extract",
"an",
"embedded",
"file",
"from",
"the",
"target",
"file",
"if",
"it",
"matches",
"an",
"extract",
"rule",
".",
"Called",
"automatically",
"by",
"Binwalk",
".",
"scan",
"()",
"."
] | def extract(self, offset, description, file_name, size, name=None):
'''
Extract an embedded file from the target file, if it matches an extract rule.
Called automatically by Binwalk.scan().
@offset - Offset inside the target file to begin the extraction.
@description - Description of the embedded file to extract, as returned by libmagic.
@file_name - Path to the target file.
@size - Number of bytes to extract.
@name - Name to save the file as.
Returns the name of the extracted file (blank string if nothing was extracted).
'''
fname = ''
rule = None
recurse = False
command_line = ''
original_dir = os.getcwd()
rules = self.match(description)
file_path = os.path.realpath(file_name)
# No extraction rules for this file
if not rules:
binwalk.core.common.debug("No extraction rules found for '%s'" % description)
return (None, None, False, str(None))
else:
binwalk.core.common.debug("Found %d matching extraction rules" % len(rules))
# Generate the output directory name where extracted files will be stored
output_directory = self.build_output_directory(file_name)
# Extract to end of file if no size was specified
if not size:
size = file_size(file_path) - offset
if os.path.isfile(file_path):
binwalk.core.common.debug("Changing directory to: %s" % output_directory)
os.chdir(output_directory)
# Extract into subdirectories named by the offset
if self.extract_into_subdirs:
# Remove trailing L that is added by hex()
offset_dir = "0x%X" % offset
os.mkdir(offset_dir)
os.chdir(offset_dir)
# Loop through each extraction rule until one succeeds
for i in range(0, len(rules)):
rule = rules[i]
binwalk.core.common.debug("Processing extraction rule #%d (%s)" % (i, str(rule['cmd'])))
# Make sure we don't recurse into any extracted directories if
# instructed not to
if rule['recurse'] in [True, False]:
recurse = rule['recurse']
else:
recurse = True
binwalk.core.common.debug("Extracting %s[%d:] to %s" % (file_path, offset, name))
# Copy out the data to disk, if we haven't already
fname = self._dd(file_path, offset, size, rule['extension'], output_file_name=name)
# If there was a command specified for this rule, try to execute it.
# If execution fails, the next rule will be attempted.
if rule['cmd']:
# Note the hash of the original file; if --rm is specified and the
# extraction utility modifies the original file rather than creating
# a new one (AFAIK none currently do, but could happen in the future),
# we don't want to remove this file.
if self.remove_after_execute:
fname_md5 = file_md5(fname)
binwalk.core.common.debug("Executing extraction command %s" % (str(rule['cmd'])))
# Execute the specified command against the extracted file
if self.run_extractors:
(extract_ok, command_line) = self.execute(rule['cmd'], fname, rule['codes'])
else:
extract_ok = True
command_line = ''
binwalk.core.common.debug("Ran extraction command: %s" % command_line)
binwalk.core.common.debug("Extraction successful: %s" % extract_ok)
# Only clean up files if remove_after_execute was specified.
# Only clean up files if the file was extracted sucessfully, or if we've run
# out of extractors.
if self.remove_after_execute and (extract_ok == True or i == (len(rules) - 1)):
# Remove the original file that we extracted,
# if it has not been modified by the extractor.
try:
if file_md5(fname) == fname_md5:
os.unlink(fname)
except KeyboardInterrupt as e:
raise e
except Exception as e:
pass
# If the command executed OK, don't try any more rules
if extract_ok == True:
break
# Else, remove the extracted file if this isn't the last rule in the list.
# If it is the last rule, leave the file on disk for the
# user to examine.
elif i != (len(rules) - 1):
try:
os.unlink(fname)
except KeyboardInterrupt as e:
raise e
except Exception as e:
pass
# If there was no command to execute, just use the first rule
else:
break
binwalk.core.common.debug("Changing directory back to: %s" % original_dir)
os.chdir(original_dir)
return (output_directory, fname, recurse, command_line) | [
"def",
"extract",
"(",
"self",
",",
"offset",
",",
"description",
",",
"file_name",
",",
"size",
",",
"name",
"=",
"None",
")",
":",
"fname",
"=",
"''",
"rule",
"=",
"None",
"recurse",
"=",
"False",
"command_line",
"=",
"''",
"original_dir",
"=",
"os",... | https://github.com/ReFirmLabs/binwalk/blob/fa0c0bd59b8588814756942fe4cb5452e76c1dcd/src/binwalk/modules/extractor.py#L599-L722 | |
SINGROUP/dscribe | 79a13939d66bdc858865dc050b91be9debd3c06a | dscribe/descriptors/acsf.py | python | ACSF.g4_params | (self) | return self.acsf_wrapper.g4_params | [] | def g4_params(self):
return self.acsf_wrapper.g4_params | [
"def",
"g4_params",
"(",
"self",
")",
":",
"return",
"self",
".",
"acsf_wrapper",
".",
"g4_params"
] | https://github.com/SINGROUP/dscribe/blob/79a13939d66bdc858865dc050b91be9debd3c06a/dscribe/descriptors/acsf.py#L391-L392 | |||
cuthbertLab/music21 | bd30d4663e52955ed922c10fdf541419d8c67671 | music21/dynamics.py | python | dynamicStrFromDecimal | (n) | Given a decimal from 0 to 1, return a string representing a dynamic
with 0 being the softest (0.01 = 'ppp') and 1 being the loudest (0.9+ = 'fff')
0 returns "n" (niente), while ppp and fff are the loudest dynamics used.
>>> dynamics.dynamicStrFromDecimal(0.25)
'pp'
>>> dynamics.dynamicStrFromDecimal(1)
'fff' | Given a decimal from 0 to 1, return a string representing a dynamic
with 0 being the softest (0.01 = 'ppp') and 1 being the loudest (0.9+ = 'fff')
0 returns "n" (niente), while ppp and fff are the loudest dynamics used. | [
"Given",
"a",
"decimal",
"from",
"0",
"to",
"1",
"return",
"a",
"string",
"representing",
"a",
"dynamic",
"with",
"0",
"being",
"the",
"softest",
"(",
"0",
".",
"01",
"=",
"ppp",
")",
"and",
"1",
"being",
"the",
"loudest",
"(",
"0",
".",
"9",
"+",
... | def dynamicStrFromDecimal(n):
'''
Given a decimal from 0 to 1, return a string representing a dynamic
with 0 being the softest (0.01 = 'ppp') and 1 being the loudest (0.9+ = 'fff')
0 returns "n" (niente), while ppp and fff are the loudest dynamics used.
>>> dynamics.dynamicStrFromDecimal(0.25)
'pp'
>>> dynamics.dynamicStrFromDecimal(1)
'fff'
'''
if n is None or n <= 0:
return 'n'
elif n < 0.11:
return 'pppp'
elif n < 0.16:
return 'ppp'
elif n < 0.26:
return 'pp'
elif n < 0.36:
return 'p'
elif n < 0.5:
return 'mp'
elif n < 0.65:
return 'mf'
elif n < 0.8:
return 'f'
elif n < 0.9:
return 'ff'
else:
return 'fff' | [
"def",
"dynamicStrFromDecimal",
"(",
"n",
")",
":",
"if",
"n",
"is",
"None",
"or",
"n",
"<=",
"0",
":",
"return",
"'n'",
"elif",
"n",
"<",
"0.11",
":",
"return",
"'pppp'",
"elif",
"n",
"<",
"0.16",
":",
"return",
"'ppp'",
"elif",
"n",
"<",
"0.26",
... | https://github.com/cuthbertLab/music21/blob/bd30d4663e52955ed922c10fdf541419d8c67671/music21/dynamics.py#L55-L86 | ||
cylc/cylc-flow | 5ec221143476c7c616c156b74158edfbcd83794a | cylc/flow/xtrigger_mgr.py | python | XtriggerManager.get_xtrig_ctx | (self, itask: TaskProxy, label: str) | return ctx | Get a real function context from the template.
Args:
itask: task proxy
label: xtrigger label
Returns:
function context | Get a real function context from the template. | [
"Get",
"a",
"real",
"function",
"context",
"from",
"the",
"template",
"."
] | def get_xtrig_ctx(self, itask: TaskProxy, label: str) -> SubFuncContext:
"""Get a real function context from the template.
Args:
itask: task proxy
label: xtrigger label
Returns:
function context
"""
farg_templ = {
TMPL_TASK_CYCLE_POINT: str(itask.point),
TMPL_TASK_NAME: str(itask.tdef.name),
TMPL_TASK_IDENT: str(itask.identity)
}
farg_templ.update(self.farg_templ)
ctx = deepcopy(self.functx_map[label])
kwargs = {}
args = []
for val in ctx.func_args:
with suppress(TypeError):
val = val % farg_templ
args.append(val)
for key, val in ctx.func_kwargs.items():
with suppress(TypeError):
val = val % farg_templ
kwargs[key] = val
ctx.func_args = args
ctx.func_kwargs = kwargs
ctx.update_command(self.workflow_run_dir)
return ctx | [
"def",
"get_xtrig_ctx",
"(",
"self",
",",
"itask",
":",
"TaskProxy",
",",
"label",
":",
"str",
")",
"->",
"SubFuncContext",
":",
"farg_templ",
"=",
"{",
"TMPL_TASK_CYCLE_POINT",
":",
"str",
"(",
"itask",
".",
"point",
")",
",",
"TMPL_TASK_NAME",
":",
"str"... | https://github.com/cylc/cylc-flow/blob/5ec221143476c7c616c156b74158edfbcd83794a/cylc/flow/xtrigger_mgr.py#L234-L263 | |
lukewaite/alfred-gitlab | 954410d3c5a8ec9905f77ed1a8d988050e21d947 | src/workflow/workflow3.py | python | Variables.__init__ | (self, arg=None, **variables) | Create a new `Variables` object. | Create a new `Variables` object. | [
"Create",
"a",
"new",
"Variables",
"object",
"."
] | def __init__(self, arg=None, **variables):
"""Create a new `Variables` object."""
self.arg = arg
self.config = {}
super(Variables, self).__init__(**variables) | [
"def",
"__init__",
"(",
"self",
",",
"arg",
"=",
"None",
",",
"*",
"*",
"variables",
")",
":",
"self",
".",
"arg",
"=",
"arg",
"self",
".",
"config",
"=",
"{",
"}",
"super",
"(",
"Variables",
",",
"self",
")",
".",
"__init__",
"(",
"*",
"*",
"v... | https://github.com/lukewaite/alfred-gitlab/blob/954410d3c5a8ec9905f77ed1a8d988050e21d947/src/workflow/workflow3.py#L63-L67 | ||
Jenyay/outwiker | 50530cf7b3f71480bb075b2829bc0669773b835b | src/outwiker/utilites/actionsguicontroller.py | python | ActionsGUIController._onPageViewCreate | (self, page) | Обработка события после создания представления страницы | Обработка события после создания представления страницы | [
"Обработка",
"события",
"после",
"создания",
"представления",
"страницы"
] | def _onPageViewCreate(self, page):
"""Обработка события после создания представления страницы"""
assert self._application.mainWindow is not None
if self._isRequestedPageType(page):
self._createTools()
self._application.onPageModeChange += self._onTabChanged | [
"def",
"_onPageViewCreate",
"(",
"self",
",",
"page",
")",
":",
"assert",
"self",
".",
"_application",
".",
"mainWindow",
"is",
"not",
"None",
"if",
"self",
".",
"_isRequestedPageType",
"(",
"page",
")",
":",
"self",
".",
"_createTools",
"(",
")",
"self",
... | https://github.com/Jenyay/outwiker/blob/50530cf7b3f71480bb075b2829bc0669773b835b/src/outwiker/utilites/actionsguicontroller.py#L157-L163 | ||
coala/coala | 37af7fd5de3ed148b8096cfc80e4717fb840bf2c | coalib/processes/Processing.py | python | check_result_ignore | (result, ignore_ranges) | return False | Determines if the result has to be ignored.
Any result will be ignored if its origin matches any bear names and its
SourceRange overlaps with the ignore range.
Note that everything after a space in the origin will be cut away, so the
user can ignore results with an origin like `CSecurityBear (buffer)` with
just `# Ignore CSecurityBear`.
:param result: The result that needs to be checked.
:param ignore_ranges: A list of tuples, each containing a list of lower
cased affected bearnames and a SourceRange to
ignore. If any of the bearname lists is empty, it
is considered an ignore range for all bears.
This may be a list of globbed bear wildcards.
:return: True if the result has to be ignored. | Determines if the result has to be ignored. | [
"Determines",
"if",
"the",
"result",
"has",
"to",
"be",
"ignored",
"."
] | def check_result_ignore(result, ignore_ranges):
"""
Determines if the result has to be ignored.
Any result will be ignored if its origin matches any bear names and its
SourceRange overlaps with the ignore range.
Note that everything after a space in the origin will be cut away, so the
user can ignore results with an origin like `CSecurityBear (buffer)` with
just `# Ignore CSecurityBear`.
:param result: The result that needs to be checked.
:param ignore_ranges: A list of tuples, each containing a list of lower
cased affected bearnames and a SourceRange to
ignore. If any of the bearname lists is empty, it
is considered an ignore range for all bears.
This may be a list of globbed bear wildcards.
:return: True if the result has to be ignored.
"""
for bears, range in ignore_ranges:
orig = result.origin.lower().split(' ')[0]
if (result.overlaps(range) and
(len(bears) == 0 or orig in bears or fnmatch(orig, bears))):
return True
return False | [
"def",
"check_result_ignore",
"(",
"result",
",",
"ignore_ranges",
")",
":",
"for",
"bears",
",",
"range",
"in",
"ignore_ranges",
":",
"orig",
"=",
"result",
".",
"origin",
".",
"lower",
"(",
")",
".",
"split",
"(",
"' '",
")",
"[",
"0",
"]",
"if",
"... | https://github.com/coala/coala/blob/37af7fd5de3ed148b8096cfc80e4717fb840bf2c/coalib/processes/Processing.py#L183-L208 | |
ludwig-ai/ludwig | 36dc61b9634ffd48e4446abffc213653b2153724 | ludwig/models/ecd.py | python | build_outputs | (output_features_def: List[Dict[str, Any]], combiner: Combiner) | return output_features | Builds and returns output features in topological order. | Builds and returns output features in topological order. | [
"Builds",
"and",
"returns",
"output",
"features",
"in",
"topological",
"order",
"."
] | def build_outputs(output_features_def: List[Dict[str, Any]], combiner: Combiner) -> Dict[str, OutputFeature]:
"""Builds and returns output features in topological order."""
output_features_def = topological_sort_feature_dependencies(output_features_def)
output_features = {}
for output_feature_def in output_features_def:
# TODO(Justin): Check that the semantics of input_size align with what the combiner's output shape returns for
# seq2seq.
output_feature_def["input_size"] = combiner.output_shape[-1]
output_feature = build_single_output(output_feature_def, output_features)
output_features[output_feature_def[NAME]] = output_feature
return output_features | [
"def",
"build_outputs",
"(",
"output_features_def",
":",
"List",
"[",
"Dict",
"[",
"str",
",",
"Any",
"]",
"]",
",",
"combiner",
":",
"Combiner",
")",
"->",
"Dict",
"[",
"str",
",",
"OutputFeature",
"]",
":",
"output_features_def",
"=",
"topological_sort_fea... | https://github.com/ludwig-ai/ludwig/blob/36dc61b9634ffd48e4446abffc213653b2153724/ludwig/models/ecd.py#L281-L293 | |
nccgroup/umap2 | a428667306f6bbc51ca02370aaf84d58f1283756 | umap2/core/usb_device_capability.py | python | USBDeviceCapability.__init__ | (self, app, phy, cap_type, data) | :param app: Umap2 application
:param phy: Physical connection
:param cap_type: Capability type
:param data: the capability data (string) | :param app: Umap2 application
:param phy: Physical connection
:param cap_type: Capability type
:param data: the capability data (string) | [
":",
"param",
"app",
":",
"Umap2",
"application",
":",
"param",
"phy",
":",
"Physical",
"connection",
":",
"param",
"cap_type",
":",
"Capability",
"type",
":",
"param",
"data",
":",
"the",
"capability",
"data",
"(",
"string",
")"
] | def __init__(self, app, phy, cap_type, data):
'''
:param app: Umap2 application
:param phy: Physical connection
:param cap_type: Capability type
:param data: the capability data (string)
'''
super(USBDeviceCapability, self).__init__(app, phy)
self.cap_type = cap_type
self.cap_data = data | [
"def",
"__init__",
"(",
"self",
",",
"app",
",",
"phy",
",",
"cap_type",
",",
"data",
")",
":",
"super",
"(",
"USBDeviceCapability",
",",
"self",
")",
".",
"__init__",
"(",
"app",
",",
"phy",
")",
"self",
".",
"cap_type",
"=",
"cap_type",
"self",
"."... | https://github.com/nccgroup/umap2/blob/a428667306f6bbc51ca02370aaf84d58f1283756/umap2/core/usb_device_capability.py#L27-L36 | ||
vlachoudis/bCNC | 67126b4894dabf6579baf47af8d0f9b7de35e6e3 | bCNC/lib/tkExtra.py | python | bindClasses | (root) | [] | def bindClasses(root):
root.bind_class('Entry', '<Control-Key-a>', lambda e: e.widget.selection_range(0,END))
root.bind_class('Entry', '<<Paste>>', _entryPaste)
root.bind_class('Text', '<<Paste>>', _textPaste) | [
"def",
"bindClasses",
"(",
"root",
")",
":",
"root",
".",
"bind_class",
"(",
"'Entry'",
",",
"'<Control-Key-a>'",
",",
"lambda",
"e",
":",
"e",
".",
"widget",
".",
"selection_range",
"(",
"0",
",",
"END",
")",
")",
"root",
".",
"bind_class",
"(",
"'Ent... | https://github.com/vlachoudis/bCNC/blob/67126b4894dabf6579baf47af8d0f9b7de35e6e3/bCNC/lib/tkExtra.py#L286-L289 | ||||
armory3d/armory | 5a7d41e39710b658029abcc32627435a79b9c02d | blender/arm/lightmapper/utility/rectpack/packer.py | python | PackerOnline.__init__ | (self, pack_algo=MaxRectsBssf, rotation=True) | Arguments:
pack_algo (PackingAlgorithm): What packing algo to use
rotation (bool): Enable/Disable rectangle rotation | Arguments:
pack_algo (PackingAlgorithm): What packing algo to use
rotation (bool): Enable/Disable rectangle rotation | [
"Arguments",
":",
"pack_algo",
"(",
"PackingAlgorithm",
")",
":",
"What",
"packing",
"algo",
"to",
"use",
"rotation",
"(",
"bool",
")",
":",
"Enable",
"/",
"Disable",
"rectangle",
"rotation"
] | def __init__(self, pack_algo=MaxRectsBssf, rotation=True):
"""
Arguments:
pack_algo (PackingAlgorithm): What packing algo to use
rotation (bool): Enable/Disable rectangle rotation
"""
self._rotation = rotation
self._pack_algo = pack_algo
self.reset() | [
"def",
"__init__",
"(",
"self",
",",
"pack_algo",
"=",
"MaxRectsBssf",
",",
"rotation",
"=",
"True",
")",
":",
"self",
".",
"_rotation",
"=",
"rotation",
"self",
".",
"_pack_algo",
"=",
"pack_algo",
"self",
".",
"reset",
"(",
")"
] | https://github.com/armory3d/armory/blob/5a7d41e39710b658029abcc32627435a79b9c02d/blender/arm/lightmapper/utility/rectpack/packer.py#L191-L199 | ||
holzschu/Carnets | 44effb10ddfc6aa5c8b0687582a724ba82c6b547 | Library/lib/python3.7/site-packages/networkx/algorithms/centrality/subgraph_alg.py | python | estrada_index | (G) | return sum(subgraph_centrality(G).values()) | r"""Returns the Estrada index of a the graph G.
The Estrada Index is a topological index of folding or 3D "compactness" ([1]_).
Parameters
----------
G: graph
Returns
-------
estrada index: float
Raises
------
NetworkXError
If the graph is not undirected and simple.
Notes
-----
Let `G=(V,E)` be a simple undirected graph with `n` nodes and let
`\lambda_{1}\leq\lambda_{2}\leq\cdots\lambda_{n}`
be a non-increasing ordering of the eigenvalues of its adjacency
matrix `A`. The Estrada index is ([1]_, [2]_)
.. math::
EE(G)=\sum_{j=1}^n e^{\lambda _j}.
References
----------
.. [1] E. Estrada, "Characterization of 3D molecular structure",
Chem. Phys. Lett. 319, 713 (2000).
https://doi.org/10.1016/S0009-2614(00)00158-5
.. [2] José Antonio de la Peñaa, Ivan Gutman, Juan Rada,
"Estimating the Estrada index",
Linear Algebra and its Applications. 427, 1 (2007).
https://doi.org/10.1016/j.laa.2007.06.020
Examples
--------
>>> G=nx.Graph([(0,1),(1,2),(1,5),(5,4),(2,4),(2,3),(4,3),(3,6)])
>>> ei=nx.estrada_index(G) | r"""Returns the Estrada index of a the graph G. | [
"r",
"Returns",
"the",
"Estrada",
"index",
"of",
"a",
"the",
"graph",
"G",
"."
] | def estrada_index(G):
r"""Returns the Estrada index of a the graph G.
The Estrada Index is a topological index of folding or 3D "compactness" ([1]_).
Parameters
----------
G: graph
Returns
-------
estrada index: float
Raises
------
NetworkXError
If the graph is not undirected and simple.
Notes
-----
Let `G=(V,E)` be a simple undirected graph with `n` nodes and let
`\lambda_{1}\leq\lambda_{2}\leq\cdots\lambda_{n}`
be a non-increasing ordering of the eigenvalues of its adjacency
matrix `A`. The Estrada index is ([1]_, [2]_)
.. math::
EE(G)=\sum_{j=1}^n e^{\lambda _j}.
References
----------
.. [1] E. Estrada, "Characterization of 3D molecular structure",
Chem. Phys. Lett. 319, 713 (2000).
https://doi.org/10.1016/S0009-2614(00)00158-5
.. [2] José Antonio de la Peñaa, Ivan Gutman, Juan Rada,
"Estimating the Estrada index",
Linear Algebra and its Applications. 427, 1 (2007).
https://doi.org/10.1016/j.laa.2007.06.020
Examples
--------
>>> G=nx.Graph([(0,1),(1,2),(1,5),(5,4),(2,4),(2,3),(4,3),(3,6)])
>>> ei=nx.estrada_index(G)
"""
return sum(subgraph_centrality(G).values()) | [
"def",
"estrada_index",
"(",
"G",
")",
":",
"return",
"sum",
"(",
"subgraph_centrality",
"(",
"G",
")",
".",
"values",
"(",
")",
")"
] | https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/networkx/algorithms/centrality/subgraph_alg.py#L274-L317 | |
jkehler/awslambda-psycopg2 | c7b1b2f6382bbe5893d95c4e7f4b5ffdf05ab3b4 | with_ssl_support/psycopg2-3.7/extras.py | python | register_inet | (oid=None, conn_or_curs=None) | return _ext.INET | Create the INET type and an Inet adapter.
:param oid: oid for the PostgreSQL :sql:`inet` type, or 2-items sequence
with oids of the type and the array. If not specified, use PostgreSQL
standard oids.
:param conn_or_curs: where to register the typecaster. If not specified,
register it globally. | Create the INET type and an Inet adapter. | [
"Create",
"the",
"INET",
"type",
"and",
"an",
"Inet",
"adapter",
"."
] | def register_inet(oid=None, conn_or_curs=None):
"""Create the INET type and an Inet adapter.
:param oid: oid for the PostgreSQL :sql:`inet` type, or 2-items sequence
with oids of the type and the array. If not specified, use PostgreSQL
standard oids.
:param conn_or_curs: where to register the typecaster. If not specified,
register it globally.
"""
import warnings
warnings.warn(
"the inet adapter is deprecated, it's not very useful",
DeprecationWarning)
if not oid:
oid1 = 869
oid2 = 1041
elif isinstance(oid, (list, tuple)):
oid1, oid2 = oid
else:
oid1 = oid
oid2 = 1041
_ext.INET = _ext.new_type((oid1, ), "INET",
lambda data, cursor: data and Inet(data) or None)
_ext.INETARRAY = _ext.new_array_type((oid2, ), "INETARRAY", _ext.INET)
_ext.register_type(_ext.INET, conn_or_curs)
_ext.register_type(_ext.INETARRAY, conn_or_curs)
return _ext.INET | [
"def",
"register_inet",
"(",
"oid",
"=",
"None",
",",
"conn_or_curs",
"=",
"None",
")",
":",
"import",
"warnings",
"warnings",
".",
"warn",
"(",
"\"the inet adapter is deprecated, it's not very useful\"",
",",
"DeprecationWarning",
")",
"if",
"not",
"oid",
":",
"o... | https://github.com/jkehler/awslambda-psycopg2/blob/c7b1b2f6382bbe5893d95c4e7f4b5ffdf05ab3b4/with_ssl_support/psycopg2-3.7/extras.py#L721-L751 | |
enthought/traits | d22ce1f096e2a6f87c78d7f1bb5bf0abab1a18ff | traits/observation/expression.py | python | ObserverExpression.then | (self, expression) | return SeriesObserverExpression(self, expression) | Create a new expression by extending this expression with
the given expression.
e.g. ``trait("child").then( trait("age") | trait("number") )``
on an object matches ``child.age`` or ``child.number`` on the object.
Parameters
----------
expression : ObserverExpression
Returns
-------
new_expression : ObserverExpression | Create a new expression by extending this expression with
the given expression. | [
"Create",
"a",
"new",
"expression",
"by",
"extending",
"this",
"expression",
"with",
"the",
"given",
"expression",
"."
] | def then(self, expression):
""" Create a new expression by extending this expression with
the given expression.
e.g. ``trait("child").then( trait("age") | trait("number") )``
on an object matches ``child.age`` or ``child.number`` on the object.
Parameters
----------
expression : ObserverExpression
Returns
-------
new_expression : ObserverExpression
"""
return SeriesObserverExpression(self, expression) | [
"def",
"then",
"(",
"self",
",",
"expression",
")",
":",
"return",
"SeriesObserverExpression",
"(",
"self",
",",
"expression",
")"
] | https://github.com/enthought/traits/blob/d22ce1f096e2a6f87c78d7f1bb5bf0abab1a18ff/traits/observation/expression.py#L58-L73 | |
accel-brain/accel-brain-code | 86f489dc9be001a3bae6d053f48d6b57c0bedb95 | Accel-Brain-Base/accelbrainbase/observabledata/_mxnet/convolutional_neural_networks.py | python | ConvolutionalNeuralNetworks.get_init_deferred_flag | (self) | return self.__init_deferred_flag | getter for `bool` that means initialization in this class will be deferred or not. | getter for `bool` that means initialization in this class will be deferred or not. | [
"getter",
"for",
"bool",
"that",
"means",
"initialization",
"in",
"this",
"class",
"will",
"be",
"deferred",
"or",
"not",
"."
] | def get_init_deferred_flag(self):
''' getter for `bool` that means initialization in this class will be deferred or not.'''
return self.__init_deferred_flag | [
"def",
"get_init_deferred_flag",
"(",
"self",
")",
":",
"return",
"self",
".",
"__init_deferred_flag"
] | https://github.com/accel-brain/accel-brain-code/blob/86f489dc9be001a3bae6d053f48d6b57c0bedb95/Accel-Brain-Base/accelbrainbase/observabledata/_mxnet/convolutional_neural_networks.py#L515-L517 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.