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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
nabeel-oz/qlik-py-tools | 09d0cd232fadcaa926bb11cebb37d5ae3051bc86 | core/_utils.py | python | fillna | (df, method="zeros") | Fill empty values in a Data Frame with the chosen method.
Valid options for method are: zeros, mean, median, mode | Fill empty values in a Data Frame with the chosen method.
Valid options for method are: zeros, mean, median, mode | [
"Fill",
"empty",
"values",
"in",
"a",
"Data",
"Frame",
"with",
"the",
"chosen",
"method",
".",
"Valid",
"options",
"for",
"method",
"are",
":",
"zeros",
"mean",
"median",
"mode"
] | def fillna(df, method="zeros"):
"""
Fill empty values in a Data Frame with the chosen method.
Valid options for method are: zeros, mean, median, mode
"""
if method == "mean":
return df.fillna(df.mean())
elif method == "median":
return df.fillna(df.median())
elif method == "mode":
return df.fillna(df.mode().iloc[0])
elif method == "none":
return df
else:
return df.fillna(0) | [
"def",
"fillna",
"(",
"df",
",",
"method",
"=",
"\"zeros\"",
")",
":",
"if",
"method",
"==",
"\"mean\"",
":",
"return",
"df",
".",
"fillna",
"(",
"df",
".",
"mean",
"(",
")",
")",
"elif",
"method",
"==",
"\"median\"",
":",
"return",
"df",
".",
"fil... | https://github.com/nabeel-oz/qlik-py-tools/blob/09d0cd232fadcaa926bb11cebb37d5ae3051bc86/core/_utils.py#L97-L112 | ||
tobegit3hub/tensorflow_template_application | a2be179bf5e2624cdc3c0ed3cf8b5f7eff87777d | util.py | python | get_optimizer_by_name | (optimizer_name, learning_rate) | return optimizer | Get optimizer object by the optimizer name.
Args:
optimizer_name: Name of the optimizer.
learning_rate: The learning rate.
Return:
The optimizer object. | Get optimizer object by the optimizer name.
Args:
optimizer_name: Name of the optimizer.
learning_rate: The learning rate.
Return:
The optimizer object. | [
"Get",
"optimizer",
"object",
"by",
"the",
"optimizer",
"name",
".",
"Args",
":",
"optimizer_name",
":",
"Name",
"of",
"the",
"optimizer",
".",
"learning_rate",
":",
"The",
"learning",
"rate",
".",
"Return",
":",
"The",
"optimizer",
"object",
"."
] | def get_optimizer_by_name(optimizer_name, learning_rate):
"""
Get optimizer object by the optimizer name.
Args:
optimizer_name: Name of the optimizer.
learning_rate: The learning rate.
Return:
The optimizer object.
"""
logging.info("Use the optimizer: {}".format(optimizer_name))
if optimizer_name == "sgd":
optimizer = tf.train.GradientDescentOptimizer(learning_rate)
elif optimizer_name == "adadelta":
optimizer = tf.train.AdadeltaOptimizer(learning_rate)
elif optimizer_name == "adagrad":
optimizer = tf.train.AdagradOptimizer(learning_rate)
elif optimizer_name == "adam":
optimizer = tf.train.AdamOptimizer(learning_rate)
elif optimizer_name == "ftrl":
optimizer = tf.train.FtrlOptimizer(learning_rate)
elif optimizer_name == "rmsprop":
optimizer = tf.train.RMSPropOptimizer(learning_rate)
else:
optimizer = tf.train.GradientDescentOptimizer(learning_rate)
return optimizer | [
"def",
"get_optimizer_by_name",
"(",
"optimizer_name",
",",
"learning_rate",
")",
":",
"logging",
".",
"info",
"(",
"\"Use the optimizer: {}\"",
".",
"format",
"(",
"optimizer_name",
")",
")",
"if",
"optimizer_name",
"==",
"\"sgd\"",
":",
"optimizer",
"=",
"tf",
... | https://github.com/tobegit3hub/tensorflow_template_application/blob/a2be179bf5e2624cdc3c0ed3cf8b5f7eff87777d/util.py#L10-L37 | |
ireapps/census | 18de79ebc17bd3aae81f8fc269f4d73631c5d506 | censusweb/fabfile.py | python | setup_directories | () | Create directories necessary for deployment. | Create directories necessary for deployment. | [
"Create",
"directories",
"necessary",
"for",
"deployment",
"."
] | def setup_directories():
"""
Create directories necessary for deployment.
"""
run('mkdir -p %(path)s' % env) | [
"def",
"setup_directories",
"(",
")",
":",
"run",
"(",
"'mkdir -p %(path)s'",
"%",
"env",
")"
] | https://github.com/ireapps/census/blob/18de79ebc17bd3aae81f8fc269f4d73631c5d506/censusweb/fabfile.py#L98-L102 | ||
Chaffelson/nipyapi | d3b186fd701ce308c2812746d98af9120955e810 | nipyapi/nifi/models/remote_process_group_status_snapshot_dto.py | python | RemoteProcessGroupStatusSnapshotDTO.group_id | (self) | return self._group_id | Gets the group_id of this RemoteProcessGroupStatusSnapshotDTO.
The id of the parent process group the remote process group resides in.
:return: The group_id of this RemoteProcessGroupStatusSnapshotDTO.
:rtype: str | Gets the group_id of this RemoteProcessGroupStatusSnapshotDTO.
The id of the parent process group the remote process group resides in. | [
"Gets",
"the",
"group_id",
"of",
"this",
"RemoteProcessGroupStatusSnapshotDTO",
".",
"The",
"id",
"of",
"the",
"parent",
"process",
"group",
"the",
"remote",
"process",
"group",
"resides",
"in",
"."
] | def group_id(self):
"""
Gets the group_id of this RemoteProcessGroupStatusSnapshotDTO.
The id of the parent process group the remote process group resides in.
:return: The group_id of this RemoteProcessGroupStatusSnapshotDTO.
:rtype: str
"""
return self._group_id | [
"def",
"group_id",
"(",
"self",
")",
":",
"return",
"self",
".",
"_group_id"
] | https://github.com/Chaffelson/nipyapi/blob/d3b186fd701ce308c2812746d98af9120955e810/nipyapi/nifi/models/remote_process_group_status_snapshot_dto.py#L130-L138 | |
fake-name/ReadableWebProxy | ed5c7abe38706acc2684a1e6cd80242a03c5f010 | WebMirror/management/rss_parser_funcs/feed_parse_extract3AmsecretWordpressCom.py | python | extract3AmsecretWordpressCom | (item) | return False | Parser for '3amsecret.wordpress.com' | Parser for '3amsecret.wordpress.com' | [
"Parser",
"for",
"3amsecret",
".",
"wordpress",
".",
"com"
] | def extract3AmsecretWordpressCom(item):
'''
Parser for '3amsecret.wordpress.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('thwipb', 'the husband who is played broken', 'translated'),
('the husband who is played broken', 'the husband who is played broken', 'translated'),
('PRC', 'PRC', 'translated'),
('Loiterous', 'Loiterous', 'oel'),
]
for tagname, name, tl_type in tagmap:
if tagname in item['tags']:
return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)
return False | [
"def",
"extract3AmsecretWordpressCom",
"(",
"item",
")",
":",
"vol",
",",
"chp",
",",
"frag",
",",
"postfix",
"=",
"extractVolChapterFragmentPostfix",
"(",
"item",
"[",
"'title'",
"]",
")",
"if",
"not",
"(",
"chp",
"or",
"vol",
")",
"or",
"\"preview\"",
"i... | https://github.com/fake-name/ReadableWebProxy/blob/ed5c7abe38706acc2684a1e6cd80242a03c5f010/WebMirror/management/rss_parser_funcs/feed_parse_extract3AmsecretWordpressCom.py#L1-L22 | |
DataDog/integrations-core | 934674b29d94b70ccc008f76ea172d0cdae05e1e | nginx_ingress_controller/datadog_checks/nginx_ingress_controller/config_models/defaults.py | python | instance_ignore_metrics_by_labels | (field, value) | return get_default_field_value(field, value) | [] | def instance_ignore_metrics_by_labels(field, value):
return get_default_field_value(field, value) | [
"def",
"instance_ignore_metrics_by_labels",
"(",
"field",
",",
"value",
")",
":",
"return",
"get_default_field_value",
"(",
"field",
",",
"value",
")"
] | https://github.com/DataDog/integrations-core/blob/934674b29d94b70ccc008f76ea172d0cdae05e1e/nginx_ingress_controller/datadog_checks/nginx_ingress_controller/config_models/defaults.py#L97-L98 | |||
thebjorn/pydeps | 2c0b958b2f4dd6e00f59b37e63c218d53e6e1773 | pydeps/dot.py | python | pipe | (cmd, txt) | return Popen(
cmd2args(cmd),
stdout=subprocess.PIPE,
stdin=subprocess.PIPE,
shell=win32
).communicate(txt)[0] | Pipe `txt` into the command `cmd` and return the output. | Pipe `txt` into the command `cmd` and return the output. | [
"Pipe",
"txt",
"into",
"the",
"command",
"cmd",
"and",
"return",
"the",
"output",
"."
] | def pipe(cmd, txt):
"""Pipe `txt` into the command `cmd` and return the output.
"""
return Popen(
cmd2args(cmd),
stdout=subprocess.PIPE,
stdin=subprocess.PIPE,
shell=win32
).communicate(txt)[0] | [
"def",
"pipe",
"(",
"cmd",
",",
"txt",
")",
":",
"return",
"Popen",
"(",
"cmd2args",
"(",
"cmd",
")",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stdin",
"=",
"subprocess",
".",
"PIPE",
",",
"shell",
"=",
"win32",
")",
".",
"communicate",
... | https://github.com/thebjorn/pydeps/blob/2c0b958b2f4dd6e00f59b37e63c218d53e6e1773/pydeps/dot.py#L46-L54 | |
pklaus/ds1054z | e93669149d048813f24a1622f964725ddfa27add | ds1054z/__init__.py | python | DS1054Z.waveform_time_values | (self) | return tv | The timestamps that belong to the waveform samples accessed to
to be accessed beforehand.
Access this property only after fetching your waveform data,
otherwise the values will not be correct.
Will be fetched every time you access this property.
:return: sample timestamps (in seconds)
:rtype: list of float | The timestamps that belong to the waveform samples accessed to
to be accessed beforehand. | [
"The",
"timestamps",
"that",
"belong",
"to",
"the",
"waveform",
"samples",
"accessed",
"to",
"to",
"be",
"accessed",
"beforehand",
"."
] | def waveform_time_values(self):
"""
The timestamps that belong to the waveform samples accessed to
to be accessed beforehand.
Access this property only after fetching your waveform data,
otherwise the values will not be correct.
Will be fetched every time you access this property.
:return: sample timestamps (in seconds)
:rtype: list of float
"""
wp = self.waveform_preamble_dict
tv = []
for i in range(self.memory_depth_curr_waveform):
tv.append(wp['xinc'] * i + wp['xorig'])
return tv | [
"def",
"waveform_time_values",
"(",
"self",
")",
":",
"wp",
"=",
"self",
".",
"waveform_preamble_dict",
"tv",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"memory_depth_curr_waveform",
")",
":",
"tv",
".",
"append",
"(",
"wp",
"[",
"'xinc'... | https://github.com/pklaus/ds1054z/blob/e93669149d048813f24a1622f964725ddfa27add/ds1054z/__init__.py#L399-L416 | |
taolei87/rcnn | 7c45f497d4507047549480c2dc579866c76eec82 | code/rationale/ubuntu/rationale.py | python | Generator.ready | (self) | [] | def ready(self):
embedding_layer = self.embedding_layer
args = self.args
padding_id = self.padding_id
weights = self.weights
dropout = self.dropout = theano.shared(
np.float64(args.dropout).astype(theano.config.floatX)
)
# len*batch
x = self.x = T.imatrix()
n_d = args.hidden_dim2
n_e = embedding_layer.n_d
activation = get_activation_by_name(args.activation)
layers = self.layers = [ ]
layer_type = args.layer.lower()
for i in xrange(2):
if layer_type == "rcnn":
l = RCNN(
n_in = n_e,# if i == 0 else n_d,
n_out = n_d,
activation = activation,
order = args.order
)
elif layer_type == "lstm":
l = LSTM(
n_in = n_e,# if i == 0 else n_d,
n_out = n_d,
activation = activation
)
layers.append(l)
# len * batch
masks = T.cast(T.neq(x, padding_id), "float32")
#masks = masks.dimshuffle((0,1,"x"))
# (len*batch)*n_e
embs = embedding_layer.forward(x.ravel())
if weights is not None:
embs_w = weights[x.ravel()].dimshuffle((0,'x'))
embs = embs * embs_w
# len*batch*n_e
embs = embs.reshape((x.shape[0], x.shape[1], n_e))
embs = apply_dropout(embs, dropout)
self.word_embs = embs
flipped_embs = embs[::-1]
# len*bacth*n_d
h1 = layers[0].forward_all(embs)
h2 = layers[1].forward_all(flipped_embs)
h_final = T.concatenate([h1, h2[::-1]], axis=2)
h_final = apply_dropout(h_final, dropout)
size = n_d * 2
output_layer = self.output_layer = ZLayer(
n_in = size,
n_hidden = n_d,
activation = activation
)
# sample z given text (i.e. x)
z_pred, sample_updates = output_layer.sample_all(h_final)
# we are computing approximated gradient by sampling z;
# so should mark sampled z not part of the gradient propagation path
#
z_pred = self.z_pred = theano.gradient.disconnected_grad(z_pred)
self.sample_updates = sample_updates
print "z_pred", z_pred.ndim
self.p1 = T.sum(masks*z_pred) / (T.sum(masks) + 1e-8)
# len*batch*1
probs = output_layer.forward_all(h_final, z_pred)
print "probs", probs.ndim
logpz = - T.nnet.binary_crossentropy(probs, z_pred) * masks
logpz = self.logpz = logpz.reshape(x.shape)
probs = self.probs = probs.reshape(x.shape)
# batch
z = z_pred
self.zsum = T.sum(z, axis=0, dtype=theano.config.floatX)
self.zdiff = T.sum(T.abs_(z[1:]-z[:-1]), axis=0, dtype=theano.config.floatX)
params = self.params = [ ]
for l in layers + [ output_layer ]:
for p in l.params:
params.append(p)
nparams = sum(len(x.get_value(borrow=True).ravel()) \
for x in params)
say("total # parameters: {}\n".format(nparams))
l2_cost = None
for p in params:
if l2_cost is None:
l2_cost = T.sum(p**2)
else:
l2_cost = l2_cost + T.sum(p**2)
l2_cost = l2_cost * args.l2_reg
self.l2_cost = l2_cost | [
"def",
"ready",
"(",
"self",
")",
":",
"embedding_layer",
"=",
"self",
".",
"embedding_layer",
"args",
"=",
"self",
".",
"args",
"padding_id",
"=",
"self",
".",
"padding_id",
"weights",
"=",
"self",
".",
"weights",
"dropout",
"=",
"self",
".",
"dropout",
... | https://github.com/taolei87/rcnn/blob/7c45f497d4507047549480c2dc579866c76eec82/code/rationale/ubuntu/rationale.py#L29-L134 | ||||
mikf/gallery-dl | 58a7921b5c990f5072e2b55b4644d0574512d3e1 | gallery_dl/extractor/tumblr.py | python | TumblrAPI.posts | (self, blog, params) | Retrieve published posts | Retrieve published posts | [
"Retrieve",
"published",
"posts"
] | def posts(self, blog, params):
"""Retrieve published posts"""
params.update({"offset": 0, "limit": 50, "reblog_info": "true"})
if self.posts_type:
params["type"] = self.posts_type
if self.before:
params["before"] = self.before
while True:
data = self._call(blog, "posts", params)
self.BLOG_CACHE[blog] = data["blog"]
yield from data["posts"]
params["offset"] += params["limit"]
if params["offset"] >= data["total_posts"]:
return | [
"def",
"posts",
"(",
"self",
",",
"blog",
",",
"params",
")",
":",
"params",
".",
"update",
"(",
"{",
"\"offset\"",
":",
"0",
",",
"\"limit\"",
":",
"50",
",",
"\"reblog_info\"",
":",
"\"true\"",
"}",
")",
"if",
"self",
".",
"posts_type",
":",
"param... | https://github.com/mikf/gallery-dl/blob/58a7921b5c990f5072e2b55b4644d0574512d3e1/gallery_dl/extractor/tumblr.py#L348-L361 | ||
mdiazcl/fuzzbunch-debian | 2b76c2249ade83a389ae3badb12a1bd09901fd2c | windows/Resources/Python/Core/Lib/lib2to3/pytree.py | python | WildcardPattern._bare_name_matches | (self, nodes) | return (
count, r) | Special optimized matcher for bare_name. | Special optimized matcher for bare_name. | [
"Special",
"optimized",
"matcher",
"for",
"bare_name",
"."
] | def _bare_name_matches(self, nodes):
"""Special optimized matcher for bare_name."""
count = 0
r = {}
done = False
max = len(nodes)
while not done and count < max:
done = True
for leaf in self.content:
if leaf[0].match(nodes[count], r):
count += 1
done = False
break
r[self.name] = nodes[:count]
return (
count, r) | [
"def",
"_bare_name_matches",
"(",
"self",
",",
"nodes",
")",
":",
"count",
"=",
"0",
"r",
"=",
"{",
"}",
"done",
"=",
"False",
"max",
"=",
"len",
"(",
"nodes",
")",
"while",
"not",
"done",
"and",
"count",
"<",
"max",
":",
"done",
"=",
"True",
"fo... | https://github.com/mdiazcl/fuzzbunch-debian/blob/2b76c2249ade83a389ae3badb12a1bd09901fd2c/windows/Resources/Python/Core/Lib/lib2to3/pytree.py#L789-L805 | |
pyparallel/pyparallel | 11e8c6072d48c8f13641925d17b147bf36ee0ba3 | Lib/site-packages/qtconsole-4.1.0-py3.3.egg/qtconsole/completion_widget.py | python | CompletionWidget.eventFilter | (self, obj, event) | return super(CompletionWidget, self).eventFilter(obj, event) | Reimplemented to handle keyboard input and to auto-hide when the
text edit loses focus. | Reimplemented to handle keyboard input and to auto-hide when the
text edit loses focus. | [
"Reimplemented",
"to",
"handle",
"keyboard",
"input",
"and",
"to",
"auto",
"-",
"hide",
"when",
"the",
"text",
"edit",
"loses",
"focus",
"."
] | def eventFilter(self, obj, event):
""" Reimplemented to handle keyboard input and to auto-hide when the
text edit loses focus.
"""
if obj == self._text_edit:
etype = event.type()
if etype == QtCore.QEvent.KeyPress:
key, text = event.key(), event.text()
if key in (QtCore.Qt.Key_Return, QtCore.Qt.Key_Enter,
QtCore.Qt.Key_Tab):
self._complete_current()
return True
elif key == QtCore.Qt.Key_Escape:
self.hide()
return True
elif key in (QtCore.Qt.Key_Up, QtCore.Qt.Key_Down,
QtCore.Qt.Key_PageUp, QtCore.Qt.Key_PageDown,
QtCore.Qt.Key_Home, QtCore.Qt.Key_End):
self.keyPressEvent(event)
return True
elif etype == QtCore.QEvent.FocusOut:
self.hide()
return super(CompletionWidget, self).eventFilter(obj, event) | [
"def",
"eventFilter",
"(",
"self",
",",
"obj",
",",
"event",
")",
":",
"if",
"obj",
"==",
"self",
".",
"_text_edit",
":",
"etype",
"=",
"event",
".",
"type",
"(",
")",
"if",
"etype",
"==",
"QtCore",
".",
"QEvent",
".",
"KeyPress",
":",
"key",
",",
... | https://github.com/pyparallel/pyparallel/blob/11e8c6072d48c8f13641925d17b147bf36ee0ba3/Lib/site-packages/qtconsole-4.1.0-py3.3.egg/qtconsole/completion_widget.py#L35-L60 | |
PaddlePaddle/Research | 2da0bd6c72d60e9df403aff23a7802779561c4a1 | NLP/ACL2019-KTNET/reading_comprehension/src/tokenization.py | python | convert_to_unicode | (text) | Converts `text` to Unicode (if it's not already), assuming utf-8 input. | Converts `text` to Unicode (if it's not already), assuming utf-8 input. | [
"Converts",
"text",
"to",
"Unicode",
"(",
"if",
"it",
"s",
"not",
"already",
")",
"assuming",
"utf",
"-",
"8",
"input",
"."
] | def convert_to_unicode(text):
"""Converts `text` to Unicode (if it's not already), assuming utf-8 input."""
if six.PY3:
if isinstance(text, str):
return text
elif isinstance(text, bytes):
return text.decode("utf-8", "ignore")
else:
raise ValueError("Unsupported string type: %s" % (type(text)))
elif six.PY2:
if isinstance(text, str):
return text.decode("utf-8", "ignore")
elif isinstance(text, unicode):
return text
else:
raise ValueError("Unsupported string type: %s" % (type(text)))
else:
raise ValueError("Not running on Python2 or Python 3?") | [
"def",
"convert_to_unicode",
"(",
"text",
")",
":",
"if",
"six",
".",
"PY3",
":",
"if",
"isinstance",
"(",
"text",
",",
"str",
")",
":",
"return",
"text",
"elif",
"isinstance",
"(",
"text",
",",
"bytes",
")",
":",
"return",
"text",
".",
"decode",
"("... | https://github.com/PaddlePaddle/Research/blob/2da0bd6c72d60e9df403aff23a7802779561c4a1/NLP/ACL2019-KTNET/reading_comprehension/src/tokenization.py#L26-L43 | ||
andyzsf/TuShare | 92787ad0cd492614bdb6389b71a19c80d1c8c9ae | tushare/datayes/macro.py | python | Macro.RussiaDataClimateIndex | (self, indicID='', indicName='', beginDate='', endDate='', field='') | return _ret_data(code, result) | 包含俄罗斯景气指数数据,具体指标可参见API文档;历史数据从2009年开始,按月更新。 | 包含俄罗斯景气指数数据,具体指标可参见API文档;历史数据从2009年开始,按月更新。 | [
"包含俄罗斯景气指数数据,具体指标可参见API文档;历史数据从2009年开始,按月更新。"
] | def RussiaDataClimateIndex(self, indicID='', indicName='', beginDate='', endDate='', field=''):
"""
包含俄罗斯景气指数数据,具体指标可参见API文档;历史数据从2009年开始,按月更新。
"""
code, result = self.client.getData(vs.RUSSIADATACLIMATEINDEX%(indicID, indicName, beginDate, endDate, field))
return _ret_data(code, result) | [
"def",
"RussiaDataClimateIndex",
"(",
"self",
",",
"indicID",
"=",
"''",
",",
"indicName",
"=",
"''",
",",
"beginDate",
"=",
"''",
",",
"endDate",
"=",
"''",
",",
"field",
"=",
"''",
")",
":",
"code",
",",
"result",
"=",
"self",
".",
"client",
".",
... | https://github.com/andyzsf/TuShare/blob/92787ad0cd492614bdb6389b71a19c80d1c8c9ae/tushare/datayes/macro.py#L1739-L1744 | |
guardicore/monkey | 34ff8dabf7614b1d0cf3de38eb4dc77b2f73f623 | monkey/common/cmd/cmd_runner.py | python | CmdRunner.query_command | (self, command_id) | Queries the already run command for more info
:param command_id: The command ID to query
:return: Command info (in any format) | Queries the already run command for more info
:param command_id: The command ID to query
:return: Command info (in any format) | [
"Queries",
"the",
"already",
"run",
"command",
"for",
"more",
"info",
":",
"param",
"command_id",
":",
"The",
"command",
"ID",
"to",
"query",
":",
"return",
":",
"Command",
"info",
"(",
"in",
"any",
"format",
")"
] | def query_command(self, command_id):
"""
Queries the already run command for more info
:param command_id: The command ID to query
:return: Command info (in any format)
"""
raise NotImplementedError() | [
"def",
"query_command",
"(",
"self",
",",
"command_id",
")",
":",
"raise",
"NotImplementedError",
"(",
")"
] | https://github.com/guardicore/monkey/blob/34ff8dabf7614b1d0cf3de38eb4dc77b2f73f623/monkey/common/cmd/cmd_runner.py#L106-L112 | ||
jliphard/DeepEvolve | 38a760283f6986f157c978dc0697099366ca0f45 | genome.py | python | Genome.set_genes_random | (self) | Create a random genome. | Create a random genome. | [
"Create",
"a",
"random",
"genome",
"."
] | def set_genes_random(self):
"""Create a random genome."""
#print("set_genes_random")
self.parents = [0,0] #very sad - no parents :(
for key in self.all_possible_genes:
self.geneparam[key] = random.choice(self.all_possible_genes[key])
self.update_hash() | [
"def",
"set_genes_random",
"(",
"self",
")",
":",
"#print(\"set_genes_random\")",
"self",
".",
"parents",
"=",
"[",
"0",
",",
"0",
"]",
"#very sad - no parents :(",
"for",
"key",
"in",
"self",
".",
"all_possible_genes",
":",
"self",
".",
"geneparam",
"[",
"key... | https://github.com/jliphard/DeepEvolve/blob/38a760283f6986f157c978dc0697099366ca0f45/genome.py#L49-L57 | ||
CamDavidsonPilon/lifelines | 9be26a9a8720e8536e9828e954bb91d559a3016f | lifelines/fitters/cox_time_varying_fitter.py | python | CoxTimeVaryingFitter.fit | (
self,
df,
event_col,
start_col="start",
stop_col="stop",
weights_col=None,
id_col=None,
show_progress=False,
step_size=None,
robust=False,
strata=None,
initial_point=None,
formula: str = None,
) | return self | Fit the Cox Proportional Hazard model to a time varying dataset. Tied survival times
are handled using Efron's tie-method.
Parameters
-----------
df: DataFrame
a Pandas DataFrame with necessary columns `duration_col` and
`event_col`, plus other covariates. `duration_col` refers to
the lifetimes of the subjects. `event_col` refers to whether
the 'death' events was observed: 1 if observed, 0 else (censored).
event_col: string
the column in DataFrame that contains the subjects' death
observation. If left as None, assume all individuals are non-censored.
start_col: string
the column that contains the start of a subject's time period.
stop_col: string
the column that contains the end of a subject's time period.
weights_col: string, optional
the column that contains (possibly time-varying) weight of each subject-period row.
id_col: string, optional
A subject could have multiple rows in the DataFrame. This column contains
the unique identifier per subject. If not provided, it's up to the
user to make sure that there are no violations.
show_progress: since the fitter is iterative, show convergence
diagnostics.
robust: bool, optional (default: True)
Compute the robust errors using the Huber sandwich estimator, aka Wei-Lin estimate. This does not handle
ties, so if there are high number of ties, results may significantly differ. See
"The Robust Inference for the Cox Proportional Hazards Model", Journal of the American Statistical Association, Vol. 84, No. 408 (Dec., 1989), pp. 1074- 1078
step_size: float, optional
set an initial step size for the fitting algorithm.
strata: list or string, optional
specify a column or list of columns n to use in stratification. This is useful if a
categorical covariate does not obey the proportional hazard assumption. This
is used similar to the `strata` expression in R.
See http://courses.washington.edu/b515/l17.pdf.
initial_point: (d,) numpy array, optional
initialize the starting point of the iterative
algorithm. Default is the zero vector.
formula: str, optional
A R-like formula for transforming the covariates
Returns
--------
self: CoxTimeVaryingFitter
self, with additional properties like ``hazards_`` and ``print_summary`` | Fit the Cox Proportional Hazard model to a time varying dataset. Tied survival times
are handled using Efron's tie-method. | [
"Fit",
"the",
"Cox",
"Proportional",
"Hazard",
"model",
"to",
"a",
"time",
"varying",
"dataset",
".",
"Tied",
"survival",
"times",
"are",
"handled",
"using",
"Efron",
"s",
"tie",
"-",
"method",
"."
] | def fit(
self,
df,
event_col,
start_col="start",
stop_col="stop",
weights_col=None,
id_col=None,
show_progress=False,
step_size=None,
robust=False,
strata=None,
initial_point=None,
formula: str = None,
): # pylint: disable=too-many-arguments
"""
Fit the Cox Proportional Hazard model to a time varying dataset. Tied survival times
are handled using Efron's tie-method.
Parameters
-----------
df: DataFrame
a Pandas DataFrame with necessary columns `duration_col` and
`event_col`, plus other covariates. `duration_col` refers to
the lifetimes of the subjects. `event_col` refers to whether
the 'death' events was observed: 1 if observed, 0 else (censored).
event_col: string
the column in DataFrame that contains the subjects' death
observation. If left as None, assume all individuals are non-censored.
start_col: string
the column that contains the start of a subject's time period.
stop_col: string
the column that contains the end of a subject's time period.
weights_col: string, optional
the column that contains (possibly time-varying) weight of each subject-period row.
id_col: string, optional
A subject could have multiple rows in the DataFrame. This column contains
the unique identifier per subject. If not provided, it's up to the
user to make sure that there are no violations.
show_progress: since the fitter is iterative, show convergence
diagnostics.
robust: bool, optional (default: True)
Compute the robust errors using the Huber sandwich estimator, aka Wei-Lin estimate. This does not handle
ties, so if there are high number of ties, results may significantly differ. See
"The Robust Inference for the Cox Proportional Hazards Model", Journal of the American Statistical Association, Vol. 84, No. 408 (Dec., 1989), pp. 1074- 1078
step_size: float, optional
set an initial step size for the fitting algorithm.
strata: list or string, optional
specify a column or list of columns n to use in stratification. This is useful if a
categorical covariate does not obey the proportional hazard assumption. This
is used similar to the `strata` expression in R.
See http://courses.washington.edu/b515/l17.pdf.
initial_point: (d,) numpy array, optional
initialize the starting point of the iterative
algorithm. Default is the zero vector.
formula: str, optional
A R-like formula for transforming the covariates
Returns
--------
self: CoxTimeVaryingFitter
self, with additional properties like ``hazards_`` and ``print_summary``
"""
self.strata = coalesce(strata, self.strata)
self.robust = robust
if self.robust:
raise NotImplementedError("Not available yet.")
self.event_col = event_col
self.id_col = id_col
self.stop_col = stop_col
self.start_col = start_col
self.formula = formula
self._time_fit_was_called = datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S") + " UTC"
df = df.copy()
if not (event_col in df and start_col in df and stop_col in df):
raise KeyError("A column specified in the call to `fit` does not exist in the DataFrame provided.")
if weights_col is None:
self.weights_col = None
assert "__weights" not in df.columns, "__weights is an internal lifelines column, please rename your column first."
df["__weights"] = 1.0
else:
self.weights_col = weights_col
if (df[weights_col] <= 0).any():
raise ValueError("values in weights_col must be positive.")
df = df.rename(columns={event_col: "event", start_col: "start", stop_col: "stop", weights_col: "__weights"})
if self.strata is not None and self.id_col is not None:
df = df.set_index(_to_list(self.strata) + [id_col])
df = df.sort_index()
elif self.strata is not None and self.id_col is None:
df = df.set_index(_to_list(self.strata))
elif self.strata is None and self.id_col is not None:
df = df.set_index([id_col])
events, start, stop = (
pass_for_numeric_dtypes_or_raise_array(df.pop("event")).astype(bool),
df.pop("start"),
df.pop("stop"),
)
weights = df.pop("__weights").astype(float)
self.regressors = utils.CovariateParameterMappings({"beta_": self.formula}, df, force_no_intercept=True)
X = self.regressors.transform_df(df)["beta_"]
self._check_values(X, events, start, stop)
self._norm_mean = X.mean(0)
self._norm_std = X.std(0)
params_ = self._newton_rhaphson(
normalize(X, self._norm_mean, self._norm_std),
events,
start,
stop,
weights,
initial_point=initial_point,
show_progress=show_progress,
step_size=step_size,
)
self.params_ = pd.Series(params_, index=pd.Index(X.columns, name="covariate"), name="coef") / self._norm_std
self.variance_matrix_ = pd.DataFrame(-inv(self._hessian_) / np.outer(self._norm_std, self._norm_std), index=X.columns)
self.standard_errors_ = self._compute_standard_errors(
normalize(X, self._norm_mean, self._norm_std), events, start, stop, weights
)
self.confidence_intervals_ = self._compute_confidence_intervals()
self.baseline_cumulative_hazard_ = self._compute_cumulative_baseline_hazard(df, events, start, stop, weights)
self.baseline_survival_ = self._compute_baseline_survival()
self.event_observed = events
self.start_stop_and_events = pd.DataFrame({"event": events, "start": start, "stop": stop})
self.weights = weights
self._n_examples = X.shape[0]
self._n_unique = X.index.unique().shape[0]
return self | [
"def",
"fit",
"(",
"self",
",",
"df",
",",
"event_col",
",",
"start_col",
"=",
"\"start\"",
",",
"stop_col",
"=",
"\"stop\"",
",",
"weights_col",
"=",
"None",
",",
"id_col",
"=",
"None",
",",
"show_progress",
"=",
"False",
",",
"step_size",
"=",
"None",
... | https://github.com/CamDavidsonPilon/lifelines/blob/9be26a9a8720e8536e9828e954bb91d559a3016f/lifelines/fitters/cox_time_varying_fitter.py#L96-L236 | |
openedx/edx-platform | 68dd185a0ab45862a2a61e0f803d7e03d2be71b5 | lms/djangoapps/courseware/model_data.py | python | UserStateCache.set | (self, kvs_key, value) | Set the specified `kvs_key` to the field value `value`.
Arguments:
kvs_key (`DjangoKeyValueStore.Key`): The field value to delete
value: The field value to store | Set the specified `kvs_key` to the field value `value`. | [
"Set",
"the",
"specified",
"kvs_key",
"to",
"the",
"field",
"value",
"value",
"."
] | def set(self, kvs_key, value):
"""
Set the specified `kvs_key` to the field value `value`.
Arguments:
kvs_key (`DjangoKeyValueStore.Key`): The field value to delete
value: The field value to store
"""
self.set_many({kvs_key: value}) | [
"def",
"set",
"(",
"self",
",",
"kvs_key",
",",
"value",
")",
":",
"self",
".",
"set_many",
"(",
"{",
"kvs_key",
":",
"value",
"}",
")"
] | https://github.com/openedx/edx-platform/blob/68dd185a0ab45862a2a61e0f803d7e03d2be71b5/lms/djangoapps/courseware/model_data.py#L360-L368 | ||
bonfy/leetcode | aae6fbb9198aa866937ca66e6212b090e6f5e8c6 | solutions/0313-super-ugly-number/super-ugly-number.py | python | Solution.nthSuperUglyNumber | (self, n, primes) | return uglies[-1] | :type n: int
:type primes: List[int]
:rtype: int | :type n: int
:type primes: List[int]
:rtype: int | [
":",
"type",
"n",
":",
"int",
":",
"type",
"primes",
":",
"List",
"[",
"int",
"]",
":",
"rtype",
":",
"int"
] | def nthSuperUglyNumber(self, n, primes):
"""
:type n: int
:type primes: List[int]
:rtype: int
"""
uglies = [1]
def gen(prime):
for ugly in uglies:
yield ugly * prime
merged = heapq.merge(*map(gen, primes))
while len(uglies) < n:
ugly = next(merged)
if ugly != uglies[-1]:
uglies.append(ugly)
return uglies[-1] | [
"def",
"nthSuperUglyNumber",
"(",
"self",
",",
"n",
",",
"primes",
")",
":",
"uglies",
"=",
"[",
"1",
"]",
"def",
"gen",
"(",
"prime",
")",
":",
"for",
"ugly",
"in",
"uglies",
":",
"yield",
"ugly",
"*",
"prime",
"merged",
"=",
"heapq",
".",
"merge"... | https://github.com/bonfy/leetcode/blob/aae6fbb9198aa866937ca66e6212b090e6f5e8c6/solutions/0313-super-ugly-number/super-ugly-number.py#L28-L43 | |
axcore/tartube | 36dd493642923fe8b9190a41db596c30c043ae90 | tartube/config.py | python | FFmpegOptionsEditWin.on_video_drag_data_received | (self, widget, context, x, y, data, info,
time) | Called from callback in self.setup_videos_tab().
This function is required for detecting when the user drags and drops
data into the Videos tab.
If the data contains full paths to a video/audio file and/or URLs,
then we can search the media data registry, looking for matching
media.Video objects.
Those objects can then be added to self.video_list.
Args:
widget (mainwin.MainWin): The widget into which something has been
dragged
drag_context (GdkX11.X11DragContext): Data from the drag procedure
x, y (int): Where the drop happened
data (Gtk.SelectionData): The object to be filled with drag data
info (int): Info that has been registered with the target in the
Gtk.TargetList
time (int): A timestamp | Called from callback in self.setup_videos_tab(). | [
"Called",
"from",
"callback",
"in",
"self",
".",
"setup_videos_tab",
"()",
"."
] | def on_video_drag_data_received(self, widget, context, x, y, data, info,
time):
"""Called from callback in self.setup_videos_tab().
This function is required for detecting when the user drags and drops
data into the Videos tab.
If the data contains full paths to a video/audio file and/or URLs,
then we can search the media data registry, looking for matching
media.Video objects.
Those objects can then be added to self.video_list.
Args:
widget (mainwin.MainWin): The widget into which something has been
dragged
drag_context (GdkX11.X11DragContext): Data from the drag procedure
x, y (int): Where the drop happened
data (Gtk.SelectionData): The object to be filled with drag data
info (int): Info that has been registered with the target in the
Gtk.TargetList
time (int): A timestamp
"""
text = None
if info == 0:
text = data.get_text()
if text is not None:
# Hopefully, 'text' contains one or more valid URLs or paths to
# video/audio files
line_list = text.split('\n')
mod_list = []
for line in line_list:
mod_line = utils.strip_whitespace(urllib.parse.unquote(line))
if mod_line != '':
# On Linux, URLs are received as expected, but paths to
# media data files are received as 'file://PATH'
match = re.search('^file\:\/\/(.*)', mod_line)
if match:
mod_list.append(match.group(1))
else:
mod_list.append(mod_line)
# The True argument means to include 'dummy' media.Videos from the
# Classic Mode tab in the search
video_list = self.app_obj.retrieve_videos_from_db(mod_list, True)
# (Remember if the video list is currently empty, or not)
old_size = len(self.video_list)
# Add videos to the list, but don't add duplicates
for video_obj in video_list:
if not video_obj in self.video_list:
self.video_list.append(video_obj)
# Redraw the whole video list by calling this function, which also
# sorts self.video_list nicely
self.setup_videos_tab_update_treeview()
if old_size == 0 and self.video_list:
# Replace the 'OK' button with a 'Process files' button
self.ok_button.set_label(_('Process files'))
self.ok_button.set_tooltip_text(
_('Process the files with FFmpeg'),
)
self.ok_button.get_child().set_width_chars(15)
# Without this line, the user's cursor is permanently stuck in drag
# and drop mode
context.finish(True, False, time) | [
"def",
"on_video_drag_data_received",
"(",
"self",
",",
"widget",
",",
"context",
",",
"x",
",",
"y",
",",
"data",
",",
"info",
",",
"time",
")",
":",
"text",
"=",
"None",
"if",
"info",
"==",
"0",
":",
"text",
"=",
"data",
".",
"get_text",
"(",
")"... | https://github.com/axcore/tartube/blob/36dd493642923fe8b9190a41db596c30c043ae90/tartube/config.py#L12206-L12289 | ||
devitocodes/devito | 6abd441e3f5f091775ad332be6b95e017b8cbd16 | devito/ir/support/utils.py | python | Stencil.union | (cls, *dicts) | return output | Compute the union of a collection of Stencils. | Compute the union of a collection of Stencils. | [
"Compute",
"the",
"union",
"of",
"a",
"collection",
"of",
"Stencils",
"."
] | def union(cls, *dicts):
"""
Compute the union of a collection of Stencils.
"""
output = Stencil()
for i in dicts:
for k, v in i.items():
output[k] |= v
return output | [
"def",
"union",
"(",
"cls",
",",
"*",
"dicts",
")",
":",
"output",
"=",
"Stencil",
"(",
")",
"for",
"i",
"in",
"dicts",
":",
"for",
"k",
",",
"v",
"in",
"i",
".",
"items",
"(",
")",
":",
"output",
"[",
"k",
"]",
"|=",
"v",
"return",
"output"
... | https://github.com/devitocodes/devito/blob/6abd441e3f5f091775ad332be6b95e017b8cbd16/devito/ir/support/utils.py#L31-L39 | |
realpython/book2-exercises | cde325eac8e6d8cff2316601c2e5b36bb46af7d0 | web2py/venv/lib/python2.7/site-packages/pip/_vendor/requests/packages/urllib3/connection.py | python | HTTPConnection.request_chunked | (self, method, url, body=None, headers=None) | Alternative to the common request method, which sends the
body with chunked encoding and not as one block | Alternative to the common request method, which sends the
body with chunked encoding and not as one block | [
"Alternative",
"to",
"the",
"common",
"request",
"method",
"which",
"sends",
"the",
"body",
"with",
"chunked",
"encoding",
"and",
"not",
"as",
"one",
"block"
] | def request_chunked(self, method, url, body=None, headers=None):
"""
Alternative to the common request method, which sends the
body with chunked encoding and not as one block
"""
headers = HTTPHeaderDict(headers if headers is not None else {})
skip_accept_encoding = 'accept-encoding' in headers
self.putrequest(method, url, skip_accept_encoding=skip_accept_encoding)
for header, value in headers.items():
self.putheader(header, value)
if 'transfer-encoding' not in headers:
self.putheader('Transfer-Encoding', 'chunked')
self.endheaders()
if body is not None:
stringish_types = six.string_types + (six.binary_type,)
if isinstance(body, stringish_types):
body = (body,)
for chunk in body:
if not chunk:
continue
if not isinstance(chunk, six.binary_type):
chunk = chunk.encode('utf8')
len_str = hex(len(chunk))[2:]
self.send(len_str.encode('utf-8'))
self.send(b'\r\n')
self.send(chunk)
self.send(b'\r\n')
# After the if clause, to always have a closed body
self.send(b'0\r\n\r\n') | [
"def",
"request_chunked",
"(",
"self",
",",
"method",
",",
"url",
",",
"body",
"=",
"None",
",",
"headers",
"=",
"None",
")",
":",
"headers",
"=",
"HTTPHeaderDict",
"(",
"headers",
"if",
"headers",
"is",
"not",
"None",
"else",
"{",
"}",
")",
"skip_acce... | https://github.com/realpython/book2-exercises/blob/cde325eac8e6d8cff2316601c2e5b36bb46af7d0/web2py/venv/lib/python2.7/site-packages/pip/_vendor/requests/packages/urllib3/connection.py#L170-L200 | ||
sabri-zaki/EasY_HaCk | 2a39ac384dd0d6fc51c0dd22e8d38cece683fdb9 | .modules/.sqlmap/lib/core/option.py | python | _setAuthCred | () | Adds authentication credentials (if any) for current target to the password manager
(used by connection handler) | Adds authentication credentials (if any) for current target to the password manager
(used by connection handler) | [
"Adds",
"authentication",
"credentials",
"(",
"if",
"any",
")",
"for",
"current",
"target",
"to",
"the",
"password",
"manager",
"(",
"used",
"by",
"connection",
"handler",
")"
] | def _setAuthCred():
"""
Adds authentication credentials (if any) for current target to the password manager
(used by connection handler)
"""
if kb.passwordMgr and all(_ is not None for _ in (conf.scheme, conf.hostname, conf.port, conf.authUsername, conf.authPassword)):
kb.passwordMgr.add_password(None, "%s://%s:%d" % (conf.scheme, conf.hostname, conf.port), conf.authUsername, conf.authPassword) | [
"def",
"_setAuthCred",
"(",
")",
":",
"if",
"kb",
".",
"passwordMgr",
"and",
"all",
"(",
"_",
"is",
"not",
"None",
"for",
"_",
"in",
"(",
"conf",
".",
"scheme",
",",
"conf",
".",
"hostname",
",",
"conf",
".",
"port",
",",
"conf",
".",
"authUsername... | https://github.com/sabri-zaki/EasY_HaCk/blob/2a39ac384dd0d6fc51c0dd22e8d38cece683fdb9/.modules/.sqlmap/lib/core/option.py#L1137-L1144 | ||
khanhnamle1994/natural-language-processing | 01d450d5ac002b0156ef4cf93a07cb508c1bcdc5 | assignment1/.env/lib/python2.7/site-packages/numpy/ma/core.py | python | MaskedArray.iscontiguous | (self) | return self.flags['CONTIGUOUS'] | Return a boolean indicating whether the data is contiguous.
Parameters
----------
None
Examples
--------
>>> x = np.ma.array([1, 2, 3])
>>> x.iscontiguous()
True
`iscontiguous` returns one of the flags of the masked array:
>>> x.flags
C_CONTIGUOUS : True
F_CONTIGUOUS : True
OWNDATA : False
WRITEABLE : True
ALIGNED : True
UPDATEIFCOPY : False | Return a boolean indicating whether the data is contiguous. | [
"Return",
"a",
"boolean",
"indicating",
"whether",
"the",
"data",
"is",
"contiguous",
"."
] | def iscontiguous(self):
"""
Return a boolean indicating whether the data is contiguous.
Parameters
----------
None
Examples
--------
>>> x = np.ma.array([1, 2, 3])
>>> x.iscontiguous()
True
`iscontiguous` returns one of the flags of the masked array:
>>> x.flags
C_CONTIGUOUS : True
F_CONTIGUOUS : True
OWNDATA : False
WRITEABLE : True
ALIGNED : True
UPDATEIFCOPY : False
"""
return self.flags['CONTIGUOUS'] | [
"def",
"iscontiguous",
"(",
"self",
")",
":",
"return",
"self",
".",
"flags",
"[",
"'CONTIGUOUS'",
"]"
] | https://github.com/khanhnamle1994/natural-language-processing/blob/01d450d5ac002b0156ef4cf93a07cb508c1bcdc5/assignment1/.env/lib/python2.7/site-packages/numpy/ma/core.py#L4252-L4277 | |
facebookarchive/Instadrop | c9bb260bb9e3cbceba86fea4b05549e855d74a2d | oauth/oauth.py | python | OAuthServer.verify_request | (self, oauth_request) | return consumer, token, parameters | Verifies an api call and checks all the parameters. | Verifies an api call and checks all the parameters. | [
"Verifies",
"an",
"api",
"call",
"and",
"checks",
"all",
"the",
"parameters",
"."
] | def verify_request(self, oauth_request):
"""Verifies an api call and checks all the parameters."""
# -> consumer and token
version = self._get_version(oauth_request)
consumer = self._get_consumer(oauth_request)
# Get the access token.
token = self._get_token(oauth_request, 'access')
self._check_signature(oauth_request, consumer, token)
parameters = oauth_request.get_nonoauth_parameters()
return consumer, token, parameters | [
"def",
"verify_request",
"(",
"self",
",",
"oauth_request",
")",
":",
"# -> consumer and token",
"version",
"=",
"self",
".",
"_get_version",
"(",
"oauth_request",
")",
"consumer",
"=",
"self",
".",
"_get_consumer",
"(",
"oauth_request",
")",
"# Get the access token... | https://github.com/facebookarchive/Instadrop/blob/c9bb260bb9e3cbceba86fea4b05549e855d74a2d/oauth/oauth.py#L426-L435 | |
Gallopsled/pwntools | 1573957cc8b1957399b7cc9bfae0c6f80630d5d4 | pwnlib/tubes/process.py | python | process.cwd | (self) | return self._cwd | Directory that the process is working in.
Example:
>>> p = process('sh')
>>> p.sendline(b'cd /tmp; echo AAA')
>>> _ = p.recvuntil(b'AAA')
>>> p.cwd == '/tmp'
True
>>> p.sendline(b'cd /proc; echo BBB;')
>>> _ = p.recvuntil(b'BBB')
>>> p.cwd
'/proc' | Directory that the process is working in. | [
"Directory",
"that",
"the",
"process",
"is",
"working",
"in",
"."
] | def cwd(self):
"""Directory that the process is working in.
Example:
>>> p = process('sh')
>>> p.sendline(b'cd /tmp; echo AAA')
>>> _ = p.recvuntil(b'AAA')
>>> p.cwd == '/tmp'
True
>>> p.sendline(b'cd /proc; echo BBB;')
>>> _ = p.recvuntil(b'BBB')
>>> p.cwd
'/proc'
"""
try:
self._cwd = os.readlink('/proc/%i/cwd' % self.pid)
except Exception:
pass
return self._cwd | [
"def",
"cwd",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"_cwd",
"=",
"os",
".",
"readlink",
"(",
"'/proc/%i/cwd'",
"%",
"self",
".",
"pid",
")",
"except",
"Exception",
":",
"pass",
"return",
"self",
".",
"_cwd"
] | https://github.com/Gallopsled/pwntools/blob/1573957cc8b1957399b7cc9bfae0c6f80630d5d4/pwnlib/tubes/process.py#L485-L505 | |
plotly/plotly.py | cfad7862594b35965c0e000813bd7805e8494a5b | packages/python/plotly/plotly/graph_objs/_heatmap.py | python | Heatmap.x | (self) | return self["x"] | Sets the x coordinates.
The 'x' property is an array that may be specified as a tuple,
list, numpy array, or pandas Series
Returns
-------
numpy.ndarray | Sets the x coordinates.
The 'x' property is an array that may be specified as a tuple,
list, numpy array, or pandas Series | [
"Sets",
"the",
"x",
"coordinates",
".",
"The",
"x",
"property",
"is",
"an",
"array",
"that",
"may",
"be",
"specified",
"as",
"a",
"tuple",
"list",
"numpy",
"array",
"or",
"pandas",
"Series"
] | def x(self):
"""
Sets the x coordinates.
The 'x' property is an array that may be specified as a tuple,
list, numpy array, or pandas Series
Returns
-------
numpy.ndarray
"""
return self["x"] | [
"def",
"x",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"x\"",
"]"
] | https://github.com/plotly/plotly.py/blob/cfad7862594b35965c0e000813bd7805e8494a5b/packages/python/plotly/plotly/graph_objs/_heatmap.py#L1312-L1323 | |
aws/aws-sam-cli | 2aa7bf01b2e0b0864ef63b1898a8b30577443acc | samcli/lib/observability/cw_logs/cw_log_group_provider.py | python | LogGroupProvider.for_lambda_function | (function_name: str) | return "/aws/lambda/{}".format(function_name) | Returns the CloudWatch Log Group Name created by default for the AWS Lambda function with given name
Parameters
----------
function_name : str
Name of the Lambda function
Returns
-------
str
Default Log Group name used by this function | Returns the CloudWatch Log Group Name created by default for the AWS Lambda function with given name | [
"Returns",
"the",
"CloudWatch",
"Log",
"Group",
"Name",
"created",
"by",
"default",
"for",
"the",
"AWS",
"Lambda",
"function",
"with",
"given",
"name"
] | def for_lambda_function(function_name: str) -> str:
"""
Returns the CloudWatch Log Group Name created by default for the AWS Lambda function with given name
Parameters
----------
function_name : str
Name of the Lambda function
Returns
-------
str
Default Log Group name used by this function
"""
return "/aws/lambda/{}".format(function_name) | [
"def",
"for_lambda_function",
"(",
"function_name",
":",
"str",
")",
"->",
"str",
":",
"return",
"\"/aws/lambda/{}\"",
".",
"format",
"(",
"function_name",
")"
] | https://github.com/aws/aws-sam-cli/blob/2aa7bf01b2e0b0864ef63b1898a8b30577443acc/samcli/lib/observability/cw_logs/cw_log_group_provider.py#L39-L53 | |
celery/py-amqp | 557d98a7d27e171ce7b22e2e3a56baf805ad8e52 | amqp/abstract_channel.py | python | AbstractChannel.dispatch_method | (self, method_sig, payload, content) | [] | def dispatch_method(self, method_sig, payload, content):
if self.is_closing and method_sig not in (
self._ALLOWED_METHODS_WHEN_CLOSING
):
# When channel.close() was called we must ignore all methods except
# Channel.close and Channel.CloseOk
AMQP_LOGGER.warning(
IGNORED_METHOD_DURING_CHANNEL_CLOSE,
method_sig, self.channel_id
)
return
if content and \
self.auto_decode and \
hasattr(content, 'content_encoding'):
try:
content.body = content.body.decode(content.content_encoding)
except Exception:
pass
try:
amqp_method = self._METHODS[method_sig]
except KeyError:
raise AMQPNotImplementedError(
f'Unknown AMQP method {method_sig!r}')
try:
listeners = [self._callbacks[method_sig]]
except KeyError:
listeners = []
one_shot = None
try:
one_shot = self._pending.pop(method_sig)
except KeyError:
if not listeners:
return
args = []
if amqp_method.args:
args, _ = loads(amqp_method.args, payload, 4)
if amqp_method.content:
args.append(content)
for listener in listeners:
listener(*args)
if one_shot:
one_shot(method_sig, *args) | [
"def",
"dispatch_method",
"(",
"self",
",",
"method_sig",
",",
"payload",
",",
"content",
")",
":",
"if",
"self",
".",
"is_closing",
"and",
"method_sig",
"not",
"in",
"(",
"self",
".",
"_ALLOWED_METHODS_WHEN_CLOSING",
")",
":",
"# When channel.close() was called w... | https://github.com/celery/py-amqp/blob/557d98a7d27e171ce7b22e2e3a56baf805ad8e52/amqp/abstract_channel.py#L99-L146 | ||||
kozec/sc-controller | ce92c773b8b26f6404882e9209aff212c4053170 | scc/lib/enum.py | python | EnumMeta.__call__ | (cls, value, names=None, module=None, type=None, start=1) | return cls._create_(value, names, module=module, type=type, start=start) | Either returns an existing member, or creates a new enum class.
This method is used both when an enum class is given a value to match
to an enumeration member (i.e. Color(3)) and for the functional API
(i.e. Color = Enum('Color', names='red green blue')).
When used for the functional API: `module`, if set, will be stored in
the new class' __module__ attribute; `type`, if set, will be mixed in
as the first base class.
Note: if `module` is not set this routine will attempt to discover the
calling module by walking the frame stack; if this is unsuccessful
the resulting class will not be pickleable. | Either returns an existing member, or creates a new enum class. | [
"Either",
"returns",
"an",
"existing",
"member",
"or",
"creates",
"a",
"new",
"enum",
"class",
"."
] | def __call__(cls, value, names=None, module=None, type=None, start=1):
"""Either returns an existing member, or creates a new enum class.
This method is used both when an enum class is given a value to match
to an enumeration member (i.e. Color(3)) and for the functional API
(i.e. Color = Enum('Color', names='red green blue')).
When used for the functional API: `module`, if set, will be stored in
the new class' __module__ attribute; `type`, if set, will be mixed in
as the first base class.
Note: if `module` is not set this routine will attempt to discover the
calling module by walking the frame stack; if this is unsuccessful
the resulting class will not be pickleable.
"""
if names is None: # simple value lookup
return cls.__new__(cls, value)
# otherwise, functional API: we're creating a new Enum type
return cls._create_(value, names, module=module, type=type, start=start) | [
"def",
"__call__",
"(",
"cls",
",",
"value",
",",
"names",
"=",
"None",
",",
"module",
"=",
"None",
",",
"type",
"=",
"None",
",",
"start",
"=",
"1",
")",
":",
"if",
"names",
"is",
"None",
":",
"# simple value lookup",
"return",
"cls",
".",
"__new__"... | https://github.com/kozec/sc-controller/blob/ce92c773b8b26f6404882e9209aff212c4053170/scc/lib/enum.py#L362-L381 | |
conjure-up/conjure-up | d2bf8ab8e71ff01321d0e691a8d3e3833a047678 | conjureup/ui/widgets/step.py | python | StepForm.set_icon_state | (self, result_code) | updates status icon
Arguments:
icon: icon widget
result_code: 3 types of results, error, waiting, complete | updates status icon | [
"updates",
"status",
"icon"
] | def set_icon_state(self, result_code):
""" updates status icon
Arguments:
icon: icon widget
result_code: 3 types of results, error, waiting, complete
"""
if result_code == "error":
self.icon.set_text(
("error_icon", "\N{BLACK FLAG}"))
elif result_code == "waiting":
self.icon.set_text(
("pending_icon", "\N{HOURGLASS}"))
elif result_code == "active":
self.icon.set_text(
("success_icon", "\N{BALLOT BOX WITH CHECK}"))
else:
# NOTE: Should not get here, if we do make sure we account
# for that error type above.
self.icon.set_text(("error_icon", "?")) | [
"def",
"set_icon_state",
"(",
"self",
",",
"result_code",
")",
":",
"if",
"result_code",
"==",
"\"error\"",
":",
"self",
".",
"icon",
".",
"set_text",
"(",
"(",
"\"error_icon\"",
",",
"\"\\N{BLACK FLAG}\"",
")",
")",
"elif",
"result_code",
"==",
"\"waiting\"",... | https://github.com/conjure-up/conjure-up/blob/d2bf8ab8e71ff01321d0e691a8d3e3833a047678/conjureup/ui/widgets/step.py#L75-L94 | ||
mu-editor/mu | 5a5d7723405db588f67718a63a0ec0ecabebae33 | mu/interface/main.py | python | Window.remove_repl | (self) | Removes the REPL pane from the application. | Removes the REPL pane from the application. | [
"Removes",
"the",
"REPL",
"pane",
"from",
"the",
"application",
"."
] | def remove_repl(self):
"""
Removes the REPL pane from the application.
"""
if self.repl:
self._repl_area = self.dockWidgetArea(self.repl)
self.repl_pane = None
self.repl.setParent(None)
self.repl.deleteLater()
self.repl = None | [
"def",
"remove_repl",
"(",
"self",
")",
":",
"if",
"self",
".",
"repl",
":",
"self",
".",
"_repl_area",
"=",
"self",
".",
"dockWidgetArea",
"(",
"self",
".",
"repl",
")",
"self",
".",
"repl_pane",
"=",
"None",
"self",
".",
"repl",
".",
"setParent",
"... | https://github.com/mu-editor/mu/blob/5a5d7723405db588f67718a63a0ec0ecabebae33/mu/interface/main.py#L900-L909 | ||
hak5/nano-tetra-modules | aa43cb5e2338b8dbd12a75314104a34ba608263b | PortalAuth/includes/scripts/libs/requests/cookies.py | python | RequestsCookieJar.__getitem__ | (self, name) | return self._find_no_duplicates(name) | Dict-like __getitem__() for compatibility with client code. Throws
exception if there are more than one cookie with name. In that case,
use the more explicit get() method instead.
.. warning:: operation is O(n), not O(1). | Dict-like __getitem__() for compatibility with client code. Throws
exception if there are more than one cookie with name. In that case,
use the more explicit get() method instead. | [
"Dict",
"-",
"like",
"__getitem__",
"()",
"for",
"compatibility",
"with",
"client",
"code",
".",
"Throws",
"exception",
"if",
"there",
"are",
"more",
"than",
"one",
"cookie",
"with",
"name",
".",
"In",
"that",
"case",
"use",
"the",
"more",
"explicit",
"get... | def __getitem__(self, name):
"""Dict-like __getitem__() for compatibility with client code. Throws
exception if there are more than one cookie with name. In that case,
use the more explicit get() method instead.
.. warning:: operation is O(n), not O(1)."""
return self._find_no_duplicates(name) | [
"def",
"__getitem__",
"(",
"self",
",",
"name",
")",
":",
"return",
"self",
".",
"_find_no_duplicates",
"(",
"name",
")"
] | https://github.com/hak5/nano-tetra-modules/blob/aa43cb5e2338b8dbd12a75314104a34ba608263b/PortalAuth/includes/scripts/libs/requests/cookies.py#L275-L282 | |
Source-Python-Dev-Team/Source.Python | d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb | addons/source-python/packages/source-python/engines/sound.py | python | Sound._stop | (self, index, channel) | Stop a sound from being played (internal). | Stop a sound from being played (internal). | [
"Stop",
"a",
"sound",
"from",
"being",
"played",
"(",
"internal",
")",
"."
] | def _stop(self, index, channel):
"""Stop a sound from being played (internal)."""
engine_sound.stop_sound(index, channel, self.sample) | [
"def",
"_stop",
"(",
"self",
",",
"index",
",",
"channel",
")",
":",
"engine_sound",
".",
"stop_sound",
"(",
"index",
",",
"channel",
",",
"self",
".",
"sample",
")"
] | https://github.com/Source-Python-Dev-Team/Source.Python/blob/d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb/addons/source-python/packages/source-python/engines/sound.py#L312-L314 | ||
holzschu/Carnets | 44effb10ddfc6aa5c8b0687582a724ba82c6b547 | Library/lib/python3.7/site-packages/Pillow-6.0.0-py3.7-macosx-10.9-x86_64.egg/PIL/ImageStat.py | python | Stat._getsum | (self) | return v | Get sum of all pixels in each layer | Get sum of all pixels in each layer | [
"Get",
"sum",
"of",
"all",
"pixels",
"in",
"each",
"layer"
] | def _getsum(self):
"""Get sum of all pixels in each layer"""
v = []
for i in range(0, len(self.h), 256):
layerSum = 0.0
for j in range(256):
layerSum += j * self.h[i + j]
v.append(layerSum)
return v | [
"def",
"_getsum",
"(",
"self",
")",
":",
"v",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"self",
".",
"h",
")",
",",
"256",
")",
":",
"layerSum",
"=",
"0.0",
"for",
"j",
"in",
"range",
"(",
"256",
")",
":",
"layerS... | https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/Pillow-6.0.0-py3.7-macosx-10.9-x86_64.egg/PIL/ImageStat.py#L77-L86 | |
HiKapok/X-Detector | 1b19e15709635e007494648c4fb519b703a29d84 | xdet_v3_resnet_eval.py | python | xdet_model_fn | (features, labels, mode, params) | Our model_fn for ResNet to be used with our Estimator. | Our model_fn for ResNet to be used with our Estimator. | [
"Our",
"model_fn",
"for",
"ResNet",
"to",
"be",
"used",
"with",
"our",
"Estimator",
"."
] | def xdet_model_fn(features, labels, mode, params):
"""Our model_fn for ResNet to be used with our Estimator."""
num_anchors_list = labels['num_anchors_list']
num_feature_layers = len(num_anchors_list)
shape = labels['targets'][-1]
if mode != tf.estimator.ModeKeys.TRAIN:
org_image = labels['targets'][-2]
isdifficult = labels['targets'][-3]
bbox_img = labels['targets'][-4]
gbboxes_raw = labels['targets'][-5]
glabels_raw = labels['targets'][-6]
glabels = labels['targets'][:num_feature_layers][0]
gtargets = labels['targets'][num_feature_layers : 2 * num_feature_layers][0]
gscores = labels['targets'][2 * num_feature_layers : 3 * num_feature_layers][0]
with tf.variable_scope(params['model_scope'], default_name = None, values = [features], reuse=tf.AUTO_REUSE):
backbone = xdet_body_v3.xdet_resnet_v3(params['resnet_size'], params['data_format'])
body_cls_output, body_regress_output = backbone(inputs=features, is_training=(mode == tf.estimator.ModeKeys.TRAIN))
cls_pred, location_pred = xdet_body_v3.xdet_head(body_cls_output, body_regress_output, params['num_classes'], num_anchors_list[0], (mode == tf.estimator.ModeKeys.TRAIN), data_format=params['data_format'])
if params['data_format'] == 'channels_first':
cls_pred = tf.transpose(cls_pred, [0, 2, 3, 1])
location_pred = tf.transpose(location_pred, [0, 2, 3, 1])
#org_image = tf.transpose(org_image, [0, 2, 3, 1])
# batch size is 1
shape = tf.squeeze(shape, axis = 0)
glabels = tf.squeeze(glabels, axis = 0)
gtargets = tf.squeeze(gtargets, axis = 0)
gscores = tf.squeeze(gscores, axis = 0)
cls_pred = tf.squeeze(cls_pred, axis = 0)
location_pred = tf.squeeze(location_pred, axis = 0)
if mode != tf.estimator.ModeKeys.TRAIN:
org_image = tf.squeeze(org_image, axis = 0)
isdifficult = tf.squeeze(isdifficult, axis = 0)
gbboxes_raw = tf.squeeze(gbboxes_raw, axis = 0)
glabels_raw = tf.squeeze(glabels_raw, axis = 0)
bbox_img = tf.squeeze(bbox_img, axis = 0)
bboxes_pred = labels['decode_fn'](location_pred)#(tf.reshape(location_pred, location_pred.get_shape().as_list()[:-1] + [-1, 4]))#(location_pred)#
eval_ops, save_image_op = bboxes_eval(org_image, shape, bbox_img, cls_pred, bboxes_pred, glabels_raw, gbboxes_raw, isdifficult, params['num_classes'])
_ = tf.identity(save_image_op, name='save_image_with_bboxes_op')
cls_pred = tf.reshape(cls_pred, [-1, params['num_classes']])
location_pred = tf.reshape(location_pred, [-1, 4])
glabels = tf.reshape(glabels, [-1])
gscores = tf.reshape(gscores, [-1])
gtargets = tf.reshape(gtargets, [-1, 4])
# raw mask for positive > 0.5, and for negetive < 0.3
# each positive examples has one label
positive_mask = glabels > 0#tf.logical_and(glabels > 0, gscores > params['match_threshold'])
fpositive_mask = tf.cast(positive_mask, tf.float32)
n_positives = tf.reduce_sum(fpositive_mask)
batch_glabels = tf.reshape(glabels, [tf.shape(features)[0], -1])
batch_n_positives = tf.count_nonzero(batch_glabels, -1)
batch_negtive_mask = tf.equal(batch_glabels, 0)
batch_n_negtives = tf.count_nonzero(batch_negtive_mask, -1)
batch_n_neg_select = tf.cast(params['negative_ratio'] * tf.cast(batch_n_positives, tf.float32), tf.int32)
batch_n_neg_select = tf.minimum(batch_n_neg_select, tf.cast(batch_n_negtives, tf.int32))
# hard negative mining for classification
predictions_for_bg = tf.nn.softmax(tf.reshape(cls_pred, [tf.shape(features)[0], -1, params['num_classes']]))[:, :, 0]
prob_for_negtives = tf.where(batch_negtive_mask,
0. - predictions_for_bg,
# ignore all the positives
0. - tf.ones_like(predictions_for_bg))
topk_prob_for_bg, _ = tf.nn.top_k(prob_for_negtives, k=tf.shape(prob_for_negtives)[1])
score_at_k = tf.gather_nd(topk_prob_for_bg, tf.stack([tf.range(tf.shape(features)[0]), batch_n_neg_select - 1], axis=-1))
selected_neg_mask = prob_for_negtives >= tf.expand_dims(score_at_k, axis=-1)
negtive_mask = tf.reshape(tf.logical_and(batch_negtive_mask, selected_neg_mask), [-1])#tf.logical_and(tf.equal(glabels, 0), gscores > 0.)
#negtive_mask = tf.logical_and(tf.logical_and(tf.logical_not(positive_mask), gscores < params['neg_threshold']), gscores > 0.)
#negtive_mask = tf.logical_and(gscores < params['neg_threshold'], tf.logical_not(positive_mask))
# # random select negtive examples for classification
# selected_neg_mask = tf.random_uniform(tf.shape(gscores), minval=0, maxval=1.) < tf.where(
# tf.greater(n_negtives, 0),
# tf.divide(tf.cast(n_neg_to_select, tf.float32), n_negtives),
# tf.zeros_like(tf.cast(n_neg_to_select, tf.float32)),
# name='rand_select_negtive')
# include both selected negtive and all positive examples
final_mask = tf.stop_gradient(tf.logical_or(negtive_mask, positive_mask))
total_examples = tf.reduce_sum(tf.cast(final_mask, tf.float32))
# add mask for glabels and cls_pred here
glabels = tf.boolean_mask(tf.clip_by_value(glabels, 0, FLAGS.num_classes), tf.stop_gradient(final_mask))
cls_pred = tf.boolean_mask(cls_pred, tf.stop_gradient(final_mask))
location_pred = tf.boolean_mask(location_pred, tf.stop_gradient(positive_mask))
gtargets = tf.boolean_mask(gtargets, tf.stop_gradient(positive_mask))
# Calculate loss, which includes softmax cross entropy and L2 regularization.
cross_entropy = tf.cond(n_positives > 0., lambda: tf.losses.sparse_softmax_cross_entropy(labels=glabels, logits=cls_pred), lambda: 0.)
#cross_entropy = tf.losses.sparse_softmax_cross_entropy(labels=glabels, logits=cls_pred)
# Create a tensor named cross_entropy for logging purposes.
tf.identity(cross_entropy, name='cross_entropy_loss')
tf.summary.scalar('cross_entropy_loss', cross_entropy)
loc_loss = tf.cond(n_positives > 0., lambda: modified_smooth_l1(location_pred, tf.stop_gradient(gtargets), sigma=1.), lambda: tf.zeros_like(location_pred))
#loc_loss = modified_smooth_l1(location_pred, tf.stop_gradient(gtargets))
loc_loss = tf.reduce_mean(tf.reduce_sum(loc_loss, axis=-1))
loc_loss = tf.identity(loc_loss, name='location_loss')
tf.summary.scalar('location_loss', loc_loss)
tf.losses.add_loss(loc_loss)
with tf.control_dependencies([save_image_op]):
# Add weight decay to the loss. We exclude the batch norm variables because
# doing so leads to a small improvement in accuracy.
loss = cross_entropy + loc_loss + params['weight_decay'] * tf.add_n(
[tf.nn.l2_loss(v) for v in tf.trainable_variables()
if 'batch_normalization' not in v.name])
total_loss = tf.identity(loss, name='total_loss')
predictions = {
'classes': tf.argmax(cls_pred, axis=-1),
'probabilities': tf.reduce_max(tf.nn.softmax(cls_pred, name='softmax_tensor'), axis=-1),
'bboxes_predict': tf.reshape(bboxes_pred, [-1, 4]),
'saved_image_index': save_image_op }
summary_hook = tf.train.SummarySaverHook(
save_secs=FLAGS.save_summary_steps,
output_dir=FLAGS.model_dir,
summary_op=tf.summary.merge_all())
if mode == tf.estimator.ModeKeys.EVAL:
return tf.estimator.EstimatorSpec(mode=mode, predictions=predictions,
evaluation_hooks = [summary_hook],
loss=loss, eval_metric_ops=eval_ops)#=eval_ops)
else:
raise ValueError('This script only support predict mode!') | [
"def",
"xdet_model_fn",
"(",
"features",
",",
"labels",
",",
"mode",
",",
"params",
")",
":",
"num_anchors_list",
"=",
"labels",
"[",
"'num_anchors_list'",
"]",
"num_feature_layers",
"=",
"len",
"(",
"num_anchors_list",
")",
"shape",
"=",
"labels",
"[",
"'targ... | https://github.com/HiKapok/X-Detector/blob/1b19e15709635e007494648c4fb519b703a29d84/xdet_v3_resnet_eval.py#L304-L442 | ||
clinton-hall/nzbToMedia | 27669389216902d1085660167e7bda0bd8527ecf | libs/common/beets/mediafile.py | python | MediaFile._field_sort_name | (cls, name) | return name | Get a sort key for a field name that determines the order
fields should be written in.
Fields names are kept unchanged, unless they are instances of
:class:`DateItemField`, in which case `year`, `month`, and `day`
are replaced by `date0`, `date1`, and `date2`, respectively, to
make them appear in that order. | Get a sort key for a field name that determines the order
fields should be written in. | [
"Get",
"a",
"sort",
"key",
"for",
"a",
"field",
"name",
"that",
"determines",
"the",
"order",
"fields",
"should",
"be",
"written",
"in",
"."
] | def _field_sort_name(cls, name):
"""Get a sort key for a field name that determines the order
fields should be written in.
Fields names are kept unchanged, unless they are instances of
:class:`DateItemField`, in which case `year`, `month`, and `day`
are replaced by `date0`, `date1`, and `date2`, respectively, to
make them appear in that order.
"""
if isinstance(cls.__dict__[name], DateItemField):
name = re.sub('year', 'date0', name)
name = re.sub('month', 'date1', name)
name = re.sub('day', 'date2', name)
return name | [
"def",
"_field_sort_name",
"(",
"cls",
",",
"name",
")",
":",
"if",
"isinstance",
"(",
"cls",
".",
"__dict__",
"[",
"name",
"]",
",",
"DateItemField",
")",
":",
"name",
"=",
"re",
".",
"sub",
"(",
"'year'",
",",
"'date0'",
",",
"name",
")",
"name",
... | https://github.com/clinton-hall/nzbToMedia/blob/27669389216902d1085660167e7bda0bd8527ecf/libs/common/beets/mediafile.py#L1530-L1543 | |
qibinlou/SinaWeibo-Emotion-Classification | f336fc104abd68b0ec4180fe2ed80fafe49cb790 | transwarp/mail.py | python | smtp | (host, port=None, username=None, passwd=None, use_tls=False) | return (host, port, username, passwd, use_tls) | Generate a tuple that contains smtp info:
(host, port, username, passwd, use_tls).
e.g.:
('smtp.example.com', 25, 'user', 'passw0rd', False) | Generate a tuple that contains smtp info:
(host, port, username, passwd, use_tls).
e.g.:
('smtp.example.com', 25, 'user', 'passw0rd', False) | [
"Generate",
"a",
"tuple",
"that",
"contains",
"smtp",
"info",
":",
"(",
"host",
"port",
"username",
"passwd",
"use_tls",
")",
".",
"e",
".",
"g",
".",
":",
"(",
"smtp",
".",
"example",
".",
"com",
"25",
"user",
"passw0rd",
"False",
")"
] | def smtp(host, port=None, username=None, passwd=None, use_tls=False):
'''
Generate a tuple that contains smtp info:
(host, port, username, passwd, use_tls).
e.g.:
('smtp.example.com', 25, 'user', 'passw0rd', False)
'''
if port is None:
port = 465 if use_tls else 25
return (host, port, username, passwd, use_tls) | [
"def",
"smtp",
"(",
"host",
",",
"port",
"=",
"None",
",",
"username",
"=",
"None",
",",
"passwd",
"=",
"None",
",",
"use_tls",
"=",
"False",
")",
":",
"if",
"port",
"is",
"None",
":",
"port",
"=",
"465",
"if",
"use_tls",
"else",
"25",
"return",
... | https://github.com/qibinlou/SinaWeibo-Emotion-Classification/blob/f336fc104abd68b0ec4180fe2ed80fafe49cb790/transwarp/mail.py#L20-L29 | |
glue-viz/glue | 840b4c1364b0fa63bf67c914540c93dd71df41e1 | glue/core/data.py | python | Data.add_component_link | (self, link, label=None) | return dc | Shortcut method for generating a new
:class:`~glue.core.component.DerivedComponent` from a ComponentLink
object, and adding it to a data set.
Parameters
----------
link : :class:`~glue.core.component_link.ComponentLink`
The link to use to generate a new component
label : :class:`~glue.core.component_id.ComponentID` or str
The ComponentID or label to attach to.
Returns
-------
component : :class:`~glue.core.component.DerivedComponent`
The component that was added | Shortcut method for generating a new
:class:`~glue.core.component.DerivedComponent` from a ComponentLink
object, and adding it to a data set. | [
"Shortcut",
"method",
"for",
"generating",
"a",
"new",
":",
"class",
":",
"~glue",
".",
"core",
".",
"component",
".",
"DerivedComponent",
"from",
"a",
"ComponentLink",
"object",
"and",
"adding",
"it",
"to",
"a",
"data",
"set",
"."
] | def add_component_link(self, link, label=None):
"""
Shortcut method for generating a new
:class:`~glue.core.component.DerivedComponent` from a ComponentLink
object, and adding it to a data set.
Parameters
----------
link : :class:`~glue.core.component_link.ComponentLink`
The link to use to generate a new component
label : :class:`~glue.core.component_id.ComponentID` or str
The ComponentID or label to attach to.
Returns
-------
component : :class:`~glue.core.component.DerivedComponent`
The component that was added
"""
if label is not None:
if not isinstance(label, ComponentID):
label = ComponentID(label, parent=self)
link.set_to_id(label)
if link.get_to_id() is None:
raise TypeError("Cannot add component_link: "
"has no 'to' ComponentID")
for cid in link.get_from_ids():
if cid not in self.components:
raise ValueError("Can only add internal links with add_component_link "
"- use DataCollection.add_link to add inter-data links")
dc = DerivedComponent(self, link)
to_ = link.get_to_id()
self.add_component(dc, label=to_)
return dc | [
"def",
"add_component_link",
"(",
"self",
",",
"link",
",",
"label",
"=",
"None",
")",
":",
"if",
"label",
"is",
"not",
"None",
":",
"if",
"not",
"isinstance",
"(",
"label",
",",
"ComponentID",
")",
":",
"label",
"=",
"ComponentID",
"(",
"label",
",",
... | https://github.com/glue-viz/glue/blob/840b4c1364b0fa63bf67c914540c93dd71df41e1/glue/core/data.py#L1073-L1108 | |
HeinleinSupport/check_mk_extensions | aa7d7389b812ed00f91dad61d66fb676284897d8 | wireguard/lib/check_mk/base/plugins/agent_based/wireguard.py | python | discover_wireguard | (section) | [] | def discover_wireguard(section) -> DiscoveryResult:
for interface, peers in section.items():
yield Service(item='%s' % interface)
for peer, data in peers.items():
yield Service(item='%s Peer %s' % (interface, peer),
parameters={'allowed-ips': data['allowed-ips']}) | [
"def",
"discover_wireguard",
"(",
"section",
")",
"->",
"DiscoveryResult",
":",
"for",
"interface",
",",
"peers",
"in",
"section",
".",
"items",
"(",
")",
":",
"yield",
"Service",
"(",
"item",
"=",
"'%s'",
"%",
"interface",
")",
"for",
"peer",
",",
"data... | https://github.com/HeinleinSupport/check_mk_extensions/blob/aa7d7389b812ed00f91dad61d66fb676284897d8/wireguard/lib/check_mk/base/plugins/agent_based/wireguard.py#L61-L66 | ||||
openfisca/openfisca-france | 207a58191be6830716693f94d37846f1e5037b51 | openfisca_france/model/prelevements_obligatoires/impot_revenu/reductions_impot.py | python | rpinel.formula_2019_01_01 | (foyer_fiscal, period, parameters) | return reduc_invest_pinel_2019 + report | Investissement locatif privé - Dispositif Pinel
Depuis 2019 | Investissement locatif privé - Dispositif Pinel
Depuis 2019 | [
"Investissement",
"locatif",
"privé",
"-",
"Dispositif",
"Pinel",
"Depuis",
"2019"
] | def formula_2019_01_01(foyer_fiscal, period, parameters):
'''
Investissement locatif privé - Dispositif Pinel
Depuis 2019
'''
f7nb = foyer_fiscal('f7nb', period)
f7nc = foyer_fiscal('f7nc', period)
f7nd = foyer_fiscal('f7nd', period)
f7qi = foyer_fiscal('f7qi', period)
f7qj = foyer_fiscal('f7qj', period)
f7qk = foyer_fiscal('f7qk', period)
f7ql = foyer_fiscal('f7ql', period)
f7qm = foyer_fiscal('f7qm', period)
f7qn = foyer_fiscal('f7qn', period)
f7qo = foyer_fiscal('f7qo', period)
f7qp = foyer_fiscal('f7qp', period)
f7qr = foyer_fiscal('f7qr', period)
f7qs = foyer_fiscal('f7qs', period)
f7qt = foyer_fiscal('f7qt', period)
f7qu = foyer_fiscal('f7qu', period)
f7qw = foyer_fiscal('f7qw', period)
f7qx = foyer_fiscal('f7qx', period)
f7qy = foyer_fiscal('f7qy', period)
f7qq = foyer_fiscal('f7qq', period)
pinel_metropole_6ans = f7qi + f7qm + f7qr + f7qw
pinel_metropole_9ans = f7qj + f7qn + f7qs + f7qx
pinel_outremer_6ans = f7qk + f7qo + f7qt + f7qy
pinel_outremer_9ans = f7ql + f7qp + f7qu + f7qq
cases_report = {
2014: ['f7ai', 'f7bi', 'f7ci', 'f7di'],
2015: ['f7bz', 'f7cz', 'f7dz', 'f7ez'],
2016: ['f7qz', 'f7rz', 'f7sz', 'f7tz'],
2017: ['f7ra', 'f7rb', 'f7rc', 'f7rd'],
2018: ['f7re', 'f7rf', 'f7rg', 'f7rh'],
}
P = parameters(period).impot_revenu.reductions_impots.rpinel
max1 = max_(0, P.plafond - f7nd - pinel_outremer_9ans) # 2019 : plafond commun 'denormandie' et 'rpinel'
max2 = max_(0, max1 - f7nc - pinel_outremer_6ans)
max3 = max_(0, max2 - f7nb - pinel_metropole_9ans)
reduc_invest_pinel_2019 = around(
P.taux['outremer']['9_ans'] * min_(max_(0, P.plafond), pinel_outremer_9ans) / 9
+ P.taux['outremer']['6_ans'] * min_(max_(0, max1), pinel_outremer_6ans) / 6
+ P.taux['metropole']['9_ans'] * min_(max_(0, max2), pinel_metropole_9ans) / 9
+ P.taux['metropole']['6_ans'] * min_(max_(0, max3), pinel_metropole_6ans) / 6
)
annee_fiscale = period.start.year
range_year_report = list(set([year for year in range(2014, annee_fiscale)]) & set([year for year in cases_report.keys()]))
report = sum([foyer_fiscal(case, period) for year in range_year_report for case in cases_report[year]])
return reduc_invest_pinel_2019 + report | [
"def",
"formula_2019_01_01",
"(",
"foyer_fiscal",
",",
"period",
",",
"parameters",
")",
":",
"f7nb",
"=",
"foyer_fiscal",
"(",
"'f7nb'",
",",
"period",
")",
"f7nc",
"=",
"foyer_fiscal",
"(",
"'f7nc'",
",",
"period",
")",
"f7nd",
"=",
"foyer_fiscal",
"(",
... | https://github.com/openfisca/openfisca-france/blob/207a58191be6830716693f94d37846f1e5037b51/openfisca_france/model/prelevements_obligatoires/impot_revenu/reductions_impot.py#L4809-L4865 | |
biolab/orange3 | 41685e1c7b1d1babe680113685a2d44bcc9fec0b | Orange/widgets/unsupervised/owtsne.py | python | OWtSNE._add_controls | (self) | [] | def _add_controls(self):
self._add_controls_start_box()
super()._add_controls() | [
"def",
"_add_controls",
"(",
"self",
")",
":",
"self",
".",
"_add_controls_start_box",
"(",
")",
"super",
"(",
")",
".",
"_add_controls",
"(",
")"
] | https://github.com/biolab/orange3/blob/41685e1c7b1d1babe680113685a2d44bcc9fec0b/Orange/widgets/unsupervised/owtsne.py#L294-L296 | ||||
sympy/sympy | d822fcba181155b85ff2b29fe525adbafb22b448 | sympy/integrals/rubi/parsetools/generate_rules.py | python | generate_rules_from_downvalues | () | This function generate rules and saves in file. For more details,
see `https://github.com/sympy/sympy/wiki/Rubi-parsing-guide` | This function generate rules and saves in file. For more details,
see `https://github.com/sympy/sympy/wiki/Rubi-parsing-guide` | [
"This",
"function",
"generate",
"rules",
"and",
"saves",
"in",
"file",
".",
"For",
"more",
"details",
"see",
"https",
":",
"//",
"github",
".",
"com",
"/",
"sympy",
"/",
"sympy",
"/",
"wiki",
"/",
"Rubi",
"-",
"parsing",
"-",
"guide"
] | def generate_rules_from_downvalues():
"""
This function generate rules and saves in file. For more details,
see `https://github.com/sympy/sympy/wiki/Rubi-parsing-guide`
"""
cons_dict = {}
cons_index = 0
index = 0
cons = ''
input = ["Integrand_simplification.txt", "Linear_products.txt", "Quadratic_products.txt", "Binomial_products.txt",
"Trinomial_products.txt", "Miscellaneous_algebra.txt", "Piecewise_linear.txt", "Exponentials.txt", "Logarithms.txt",
"Sine.txt", "Tangent.txt", "Secant.txt", "Miscellaneous_trig.txt", "Inverse_trig.txt", "Hyperbolic.txt",
"Inverse_hyperbolic.txt", "Special_functions.txt", "Miscellaneous_integration.txt"]
output = ['integrand_simplification.py', 'linear_products.py', 'quadratic_products.py', 'binomial_products.py', 'trinomial_products.py',
'miscellaneous_algebraic.py' ,'piecewise_linear.py', 'exponential.py', 'logarithms.py', 'sine.py', 'tangent.py', 'secant.py', 'miscellaneous_trig.py',
'inverse_trig.py', 'hyperbolic.py', 'inverse_hyperbolic.py', 'special_functions.py', 'miscellaneous_integration.py']
for k in range(0, 18):
module_name = output[k][0:-3]
path_header = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
header = open(os.path.join(path_header, "header.py.txt")).read()
header = header.format(module_name)
with open(input[k]) as myfile:
fullform =myfile.read().replace('\n', '')
for i in temporary_variable_replacement:
fullform = fullform.replace(i, temporary_variable_replacement[i])
# Permanently rename these variables
for i in permanent_variable_replacement:
fullform = fullform.replace(i, permanent_variable_replacement[i])
rules = []
for i in parse_full_form(fullform): # separate all rules
if i[0] == 'RuleDelayed':
rules.append(i)
parsed = downvalues_rules(rules, header, cons_dict, cons_index, index)
result = parsed[0].strip() + '\n'
cons_index = parsed[1]
cons += parsed[2]
index = parsed[3]
# Replace temporary variables by actual values
for i in temporary_variable_replacement:
cons = cons.replace(temporary_variable_replacement[i], i)
result = result.replace(temporary_variable_replacement[i], i)
file = open(output[k],'w')
file.write(str(result))
file.close()
cons = "\n".join(header.split("\n")[:-2])+ '\n' + cons
constraints = open('constraints.py', 'w')
constraints.write(str(cons))
constraints.close() | [
"def",
"generate_rules_from_downvalues",
"(",
")",
":",
"cons_dict",
"=",
"{",
"}",
"cons_index",
"=",
"0",
"index",
"=",
"0",
"cons",
"=",
"''",
"input",
"=",
"[",
"\"Integrand_simplification.txt\"",
",",
"\"Linear_products.txt\"",
",",
"\"Quadratic_products.txt\""... | https://github.com/sympy/sympy/blob/d822fcba181155b85ff2b29fe525adbafb22b448/sympy/integrals/rubi/parsetools/generate_rules.py#L7-L59 | ||
dvlab-research/3DSSD | 8bc7605d4d3a6ec9051e7689e96a23bdac4c4cd9 | lib/utils/box_3d_utils.py | python | get_box3d_corners_helper_np | (centers, headings, sizes) | return corners_3d | Input: (N, 3), (N, ), (N, 3), Output: [N, 8, 3] | Input: (N, 3), (N, ), (N, 3), Output: [N, 8, 3] | [
"Input",
":",
"(",
"N",
"3",
")",
"(",
"N",
")",
"(",
"N",
"3",
")",
"Output",
":",
"[",
"N",
"8",
"3",
"]"
] | def get_box3d_corners_helper_np(centers, headings, sizes):
''' Input: (N, 3), (N, ), (N, 3), Output: [N, 8, 3]'''
N = centers.shape[0]
l = sizes[:, 0]
h = sizes[:, 1]
w = sizes[:, 2]
z = np.zeros_like(l)
x_corners = np.stack([l/2,l/2,-l/2,-l/2,l/2,l/2,-l/2,-l/2], axis=1) # (N,8)
y_corners = np.stack([z,z,z,z,-h,-h,-h,-h], axis=1) # (N,8)
z_corners = np.stack([w/2,-w/2,-w/2,w/2,w/2,-w/2,-w/2,w/2], axis=1) # (N,8)
corners = np.concatenate([np.expand_dims(x_corners,1), np.expand_dims(y_corners,1), np.expand_dims(z_corners,1)], axis=1) # (N,3,8)
#print x_corners, y_corners, z_corners
c = np.cos(headings)
s = np.sin(headings)
ones = np.ones([N], dtype=np.float32)
zeros = np.zeros([N], dtype=np.float32)
row1 = np.stack([c,zeros,s], axis=1) # (N,3)
row2 = np.stack([zeros,ones,zeros], axis=1)
row3 = np.stack([-s,zeros,c], axis=1)
R = np.concatenate([np.expand_dims(row1,1), np.expand_dims(row2,1), np.expand_dims(row3,1)], axis=1) # (N,3,3)
#print row1, row2, row3, R, N
corners_3d = np.matmul(R, corners) # (N,3,8)
corners_3d += np.tile(np.expand_dims(centers,2), [1,1,8]) # (N,3,8)
corners_3d = np.transpose(corners_3d, [0,2,1]) # (N,8,3)
return corners_3d | [
"def",
"get_box3d_corners_helper_np",
"(",
"centers",
",",
"headings",
",",
"sizes",
")",
":",
"N",
"=",
"centers",
".",
"shape",
"[",
"0",
"]",
"l",
"=",
"sizes",
"[",
":",
",",
"0",
"]",
"h",
"=",
"sizes",
"[",
":",
",",
"1",
"]",
"w",
"=",
"... | https://github.com/dvlab-research/3DSSD/blob/8bc7605d4d3a6ec9051e7689e96a23bdac4c4cd9/lib/utils/box_3d_utils.py#L62-L87 | |
tobegit3hub/deep_image_model | 8a53edecd9e00678b278bb10f6fb4bdb1e4ee25e | java_predict_client/src/main/proto/tensorflow/contrib/metrics/python/ops/metric_ops.py | python | streaming_mean_squared_error | (predictions, labels, weights=None,
metrics_collections=None,
updates_collections=None,
name=None) | return streaming_mean(squared_error, weights, metrics_collections,
updates_collections, name or 'mean_squared_error') | Computes the mean squared error between the labels and predictions.
The `streaming_mean_squared_error` function creates two local variables,
`total` and `count` that are used to compute the mean squared error.
This average is weighted by `weights`, and it is ultimately returned as
`mean_squared_error`: an idempotent operation that simply divides `total` by
`count`.
For estimation of the metric over a stream of data, the function creates an
`update_op` operation that updates these variables and returns the
`mean_squared_error`. Internally, a `squared_error` operation computes the
element-wise square of the difference between `predictions` and `labels`. Then
`update_op` increments `total` with the reduced sum of the product of
`weights` and `squared_error`, and it increments `count` with the reduced sum
of `weights`.
If `weights` is `None`, weights default to 1. Use weights of 0 to mask values.
Args:
predictions: A `Tensor` of arbitrary shape.
labels: A `Tensor` of the same shape as `predictions`.
weights: An optional `Tensor` whose shape is broadcastable to `predictions`.
metrics_collections: An optional list of collections that
`mean_squared_error` should be added to.
updates_collections: An optional list of collections that `update_op` should
be added to.
name: An optional variable_scope name.
Returns:
mean_squared_error: A tensor representing the current mean, the value of
`total` divided by `count`.
update_op: An operation that increments the `total` and `count` variables
appropriately and whose value matches `mean_squared_error`.
Raises:
ValueError: If `predictions` and `labels` have mismatched shapes, or if
`weights` is not `None` and its shape doesn't match `predictions`, or if
either `metrics_collections` or `updates_collections` are not a list or
tuple. | Computes the mean squared error between the labels and predictions. | [
"Computes",
"the",
"mean",
"squared",
"error",
"between",
"the",
"labels",
"and",
"predictions",
"."
] | def streaming_mean_squared_error(predictions, labels, weights=None,
metrics_collections=None,
updates_collections=None,
name=None):
"""Computes the mean squared error between the labels and predictions.
The `streaming_mean_squared_error` function creates two local variables,
`total` and `count` that are used to compute the mean squared error.
This average is weighted by `weights`, and it is ultimately returned as
`mean_squared_error`: an idempotent operation that simply divides `total` by
`count`.
For estimation of the metric over a stream of data, the function creates an
`update_op` operation that updates these variables and returns the
`mean_squared_error`. Internally, a `squared_error` operation computes the
element-wise square of the difference between `predictions` and `labels`. Then
`update_op` increments `total` with the reduced sum of the product of
`weights` and `squared_error`, and it increments `count` with the reduced sum
of `weights`.
If `weights` is `None`, weights default to 1. Use weights of 0 to mask values.
Args:
predictions: A `Tensor` of arbitrary shape.
labels: A `Tensor` of the same shape as `predictions`.
weights: An optional `Tensor` whose shape is broadcastable to `predictions`.
metrics_collections: An optional list of collections that
`mean_squared_error` should be added to.
updates_collections: An optional list of collections that `update_op` should
be added to.
name: An optional variable_scope name.
Returns:
mean_squared_error: A tensor representing the current mean, the value of
`total` divided by `count`.
update_op: An operation that increments the `total` and `count` variables
appropriately and whose value matches `mean_squared_error`.
Raises:
ValueError: If `predictions` and `labels` have mismatched shapes, or if
`weights` is not `None` and its shape doesn't match `predictions`, or if
either `metrics_collections` or `updates_collections` are not a list or
tuple.
"""
predictions, labels, weights = _remove_squeezable_dimensions(
predictions, labels, weights)
predictions.get_shape().assert_is_compatible_with(labels.get_shape())
squared_error = math_ops.square(labels - predictions)
return streaming_mean(squared_error, weights, metrics_collections,
updates_collections, name or 'mean_squared_error') | [
"def",
"streaming_mean_squared_error",
"(",
"predictions",
",",
"labels",
",",
"weights",
"=",
"None",
",",
"metrics_collections",
"=",
"None",
",",
"updates_collections",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"predictions",
",",
"labels",
",",
"wei... | https://github.com/tobegit3hub/deep_image_model/blob/8a53edecd9e00678b278bb10f6fb4bdb1e4ee25e/java_predict_client/src/main/proto/tensorflow/contrib/metrics/python/ops/metric_ops.py#L2303-L2352 | |
cloud-custodian/cloud-custodian | 1ce1deb2d0f0832d6eb8839ef74b4c9e397128de | tools/c7n_policystream/policystream.py | python | org_checkout | (organization, github_url, github_token, clone_dir,
verbose, filter, exclude) | return repos | Checkout repositories from a GitHub organization. | Checkout repositories from a GitHub organization. | [
"Checkout",
"repositories",
"from",
"a",
"GitHub",
"organization",
"."
] | def org_checkout(organization, github_url, github_token, clone_dir,
verbose, filter, exclude):
"""Checkout repositories from a GitHub organization."""
logging.basicConfig(
format="%(asctime)s: %(name)s:%(levelname)s %(message)s",
level=(verbose and logging.DEBUG or logging.INFO))
callbacks = pygit2.RemoteCallbacks(
pygit2.UserPass(github_token, 'x-oauth-basic'))
repos = []
for r in github_repos(organization, github_url, github_token):
if filter:
found = False
for f in filter:
if fnmatch(r['name'], f):
found = True
break
if not found:
continue
if exclude:
found = False
for e in exclude:
if fnmatch(r['name'], e):
found = True
break
if found:
continue
repo_path = os.path.join(clone_dir, r['name'])
repos.append(repo_path)
if not os.path.exists(repo_path):
log.debug("Cloning repo: %s/%s" % (organization, r['name']))
repo = pygit2.clone_repository(
r['url'], repo_path, callbacks=callbacks)
else:
repo = pygit2.Repository(repo_path)
if repo.status():
log.warning('repo %s not clean skipping update', r['name'])
continue
log.debug("Syncing repo: %s/%s" % (organization, r['name']))
pull(repo, callbacks)
return repos | [
"def",
"org_checkout",
"(",
"organization",
",",
"github_url",
",",
"github_token",
",",
"clone_dir",
",",
"verbose",
",",
"filter",
",",
"exclude",
")",
":",
"logging",
".",
"basicConfig",
"(",
"format",
"=",
"\"%(asctime)s: %(name)s:%(levelname)s %(message)s\"",
"... | https://github.com/cloud-custodian/cloud-custodian/blob/1ce1deb2d0f0832d6eb8839ef74b4c9e397128de/tools/c7n_policystream/policystream.py#L744-L787 | |
merenlab/anvio | 9b792e2cedc49ecb7c0bed768261595a0d87c012 | anvio/kegg.py | python | KeggMetabolismEstimator.estimate_for_genome | (self, kofam_gene_split_contig) | return genome_metabolism_superdict, genome_ko_superdict | This is the metabolism estimation function for a contigs DB that contains a single genome.
Assuming this contigs DB contains only one genome, it sends all of the splits and their kofam hits to the atomic
estimation function for processing. It then returns the metabolism and ko completion dictionaries for the genome, wrapped in the superdict format.
PARAMETERS
==========
kofam_gene_split_contig : list
(ko_num, gene_call_id, split, contig) tuples, one per KOfam hit in the splits we are considering
RETURNS
=======
genome_metabolism_dict : dictionary of dictionary of dictionaries
dictionary mapping genome name to its metabolism completeness dictionary
genome_ko_superdict : dictionary of dictionary of dictionaries
maps genome name to its KOfam hit dictionary | This is the metabolism estimation function for a contigs DB that contains a single genome. | [
"This",
"is",
"the",
"metabolism",
"estimation",
"function",
"for",
"a",
"contigs",
"DB",
"that",
"contains",
"a",
"single",
"genome",
"."
] | def estimate_for_genome(self, kofam_gene_split_contig):
"""This is the metabolism estimation function for a contigs DB that contains a single genome.
Assuming this contigs DB contains only one genome, it sends all of the splits and their kofam hits to the atomic
estimation function for processing. It then returns the metabolism and ko completion dictionaries for the genome, wrapped in the superdict format.
PARAMETERS
==========
kofam_gene_split_contig : list
(ko_num, gene_call_id, split, contig) tuples, one per KOfam hit in the splits we are considering
RETURNS
=======
genome_metabolism_dict : dictionary of dictionary of dictionaries
dictionary mapping genome name to its metabolism completeness dictionary
genome_ko_superdict : dictionary of dictionary of dictionaries
maps genome name to its KOfam hit dictionary
"""
genome_metabolism_superdict = {}
genome_ko_superdict = {}
# since all hits belong to one genome, we can take the UNIQUE splits from all the hits
splits_in_genome = list(set([tpl[2] for tpl in kofam_gene_split_contig]))
metabolism_dict_for_genome, ko_dict_for_genome = self.mark_kos_present_for_list_of_splits(kofam_gene_split_contig, split_list=splits_in_genome,
bin_name=self.contigs_db_project_name)
if not self.store_json_without_estimation:
genome_metabolism_superdict[self.contigs_db_project_name] = self.estimate_for_list_of_splits(metabolism_dict_for_genome, bin_name=self.contigs_db_project_name)
genome_ko_superdict[self.contigs_db_project_name] = ko_dict_for_genome
else:
genome_metabolism_superdict[self.contigs_db_project_name] = metabolism_dict_for_genome
genome_ko_superdict[self.contigs_db_project_name] = ko_dict_for_genome
# append to file
self.append_kegg_metabolism_superdicts(genome_metabolism_superdict, genome_ko_superdict)
return genome_metabolism_superdict, genome_ko_superdict | [
"def",
"estimate_for_genome",
"(",
"self",
",",
"kofam_gene_split_contig",
")",
":",
"genome_metabolism_superdict",
"=",
"{",
"}",
"genome_ko_superdict",
"=",
"{",
"}",
"# since all hits belong to one genome, we can take the UNIQUE splits from all the hits",
"splits_in_genome",
"... | https://github.com/merenlab/anvio/blob/9b792e2cedc49ecb7c0bed768261595a0d87c012/anvio/kegg.py#L3044-L3080 | |
owid/covid-19-data | 936aeae6cfbdc0163939ed7bd8ecdbb2582c0a92 | scripts/src/cowidev/vax/incremental/philippines.py | python | Philippines.export | (self) | [] | def export(self):
data = self.read().pipe(self.pipeline)
increment(
location=data["location"],
total_vaccinations=data["total_vaccinations"],
# people_vaccinated=data["people_vaccinated"],
people_fully_vaccinated=data["people_fully_vaccinated"],
total_boosters=data["total_boosters"],
date=data["date"],
source_url=data["source_url"],
vaccine=data["vaccine"],
) | [
"def",
"export",
"(",
"self",
")",
":",
"data",
"=",
"self",
".",
"read",
"(",
")",
".",
"pipe",
"(",
"self",
".",
"pipeline",
")",
"increment",
"(",
"location",
"=",
"data",
"[",
"\"location\"",
"]",
",",
"total_vaccinations",
"=",
"data",
"[",
"\"t... | https://github.com/owid/covid-19-data/blob/936aeae6cfbdc0163939ed7bd8ecdbb2582c0a92/scripts/src/cowidev/vax/incremental/philippines.py#L79-L90 | ||||
namlook/mongokit | 04f6cb2703a662c5beb9bd5a7d4dbec3f03d9c6d | mongokit/schema_document.py | python | SchemaDocument.__init__ | (self, doc=None, gen_skel=True, _gen_auth_types=True, _validate=True, lang='en', fallback_lang='en') | doc : a dictionary
gen_skel : if True, generate automatically the skeleton of the doc
filled with NoneType each time validate() is called. Note that
if doc is not {}, gen_skel is always False. If gen_skel is False,
default_values cannot be filled.
gen_auth_types: if True, generate automatically the self.authorized_types
attribute from self.authorized_types | doc : a dictionary
gen_skel : if True, generate automatically the skeleton of the doc
filled with NoneType each time validate() is called. Note that
if doc is not {}, gen_skel is always False. If gen_skel is False,
default_values cannot be filled.
gen_auth_types: if True, generate automatically the self.authorized_types
attribute from self.authorized_types | [
"doc",
":",
"a",
"dictionary",
"gen_skel",
":",
"if",
"True",
"generate",
"automatically",
"the",
"skeleton",
"of",
"the",
"doc",
"filled",
"with",
"NoneType",
"each",
"time",
"validate",
"()",
"is",
"called",
".",
"Note",
"that",
"if",
"doc",
"is",
"not",... | def __init__(self, doc=None, gen_skel=True, _gen_auth_types=True, _validate=True, lang='en', fallback_lang='en'):
"""
doc : a dictionary
gen_skel : if True, generate automatically the skeleton of the doc
filled with NoneType each time validate() is called. Note that
if doc is not {}, gen_skel is always False. If gen_skel is False,
default_values cannot be filled.
gen_auth_types: if True, generate automatically the self.authorized_types
attribute from self.authorized_types
"""
super(SchemaDocument, self).__init__()
if self.structure is None:
self.structure = {}
self._current_lang = lang
self._fallback_lang = fallback_lang
self.validation_errors = {}
# init
if doc:
for k, v in doc.iteritems():
self[k] = v
gen_skel = False
if gen_skel:
self.generate_skeleton()
if self.default_values:
self._set_default_fields(self, self.structure)
else:
self._process_custom_type('python', self, self.structure)
if self.use_dot_notation:
self.__generate_doted_dict(self, self.structure)
if self.i18n:
self._make_i18n() | [
"def",
"__init__",
"(",
"self",
",",
"doc",
"=",
"None",
",",
"gen_skel",
"=",
"True",
",",
"_gen_auth_types",
"=",
"True",
",",
"_validate",
"=",
"True",
",",
"lang",
"=",
"'en'",
",",
"fallback_lang",
"=",
"'en'",
")",
":",
"super",
"(",
"SchemaDocum... | https://github.com/namlook/mongokit/blob/04f6cb2703a662c5beb9bd5a7d4dbec3f03d9c6d/mongokit/schema_document.py#L349-L379 | ||
accel-brain/accel-brain-code | 86f489dc9be001a3bae6d053f48d6b57c0bedb95 | Accel-Brain-Base/accelbrainbase/observabledata/_mxnet/restrictedboltzmannmachines/deep_boltzmann_machines.py | python | DeepBoltzmannMachines.collect_params | (self, select=None) | return params_dict | Overrided `collect_params` in `mxnet.gluon.HybridBlok`. | Overrided `collect_params` in `mxnet.gluon.HybridBlok`. | [
"Overrided",
"collect_params",
"in",
"mxnet",
".",
"gluon",
".",
"HybridBlok",
"."
] | def collect_params(self, select=None):
'''
Overrided `collect_params` in `mxnet.gluon.HybridBlok`.
'''
params_dict = self.__rbm_list[0].collect_params(select)
for i in range(1, len(self.__rbm_list)):
params_dict.update(self.__rbm_list[i].collect_params(select))
return params_dict | [
"def",
"collect_params",
"(",
"self",
",",
"select",
"=",
"None",
")",
":",
"params_dict",
"=",
"self",
".",
"__rbm_list",
"[",
"0",
"]",
".",
"collect_params",
"(",
"select",
")",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"len",
"(",
"self",
".",
... | https://github.com/accel-brain/accel-brain-code/blob/86f489dc9be001a3bae6d053f48d6b57c0bedb95/Accel-Brain-Base/accelbrainbase/observabledata/_mxnet/restrictedboltzmannmachines/deep_boltzmann_machines.py#L128-L135 | |
memray/seq2seq-keyphrase | 9145c63ebdc4c3bc431f8091dc52547a46804012 | emolga/layers/attention.py | python | Attention.__call__ | (self, X, S,
Smask=None,
return_log=False,
Cov=None) | [] | def __call__(self, X, S,
Smask=None,
return_log=False,
Cov=None):
assert X.ndim + 1 == S.ndim, 'source should be one more dimension than target.'
# X is the decoder representation of t-1: (nb_samples, hidden_dims)
# S is the context vector, hidden representation of source text: (nb_samples, maxlen_s, context_dim)
# X_mask: mask, an array showing which elements in X are not 0 [nb_sample, max_len]
# Cov is the coverage vector (nb_samples, maxlen_s)
if X.ndim == 1:
X = X[None, :]
S = S[None, :, :]
if not Smask:
Smask = Smask[None, :]
Eng = dot(X[:, None, :], self.Wa) + dot(S, self.Ua) # Concat Attention by Bahdanau et al. 2015 (nb_samples, source_num, hidden_dims)
Eng = self.tanh(Eng)
# location aware by adding previous coverage information, let model learn how to handle coverage
if self.coverage:
Eng += dot(Cov[:, :, None], self.Ca) # (nb_samples, source_num, hidden_dims)
Eng = dot(Eng, self.va)
Eng = Eng[:, :, 0] # 3rd dim is 1, discard it (nb_samples, source_num)
if Smask is not None:
# I want to use mask!
EngSum = logSumExp(Eng, axis=1, mask=Smask)
if return_log:
return (Eng - EngSum) * Smask
else:
return T.exp(Eng - EngSum) * Smask
else:
if return_log:
return T.log(self.softmax(Eng))
else:
return self.softmax(Eng) | [
"def",
"__call__",
"(",
"self",
",",
"X",
",",
"S",
",",
"Smask",
"=",
"None",
",",
"return_log",
"=",
"False",
",",
"Cov",
"=",
"None",
")",
":",
"assert",
"X",
".",
"ndim",
"+",
"1",
"==",
"S",
".",
"ndim",
",",
"'source should be one more dimensio... | https://github.com/memray/seq2seq-keyphrase/blob/9145c63ebdc4c3bc431f8091dc52547a46804012/emolga/layers/attention.py#L42-L79 | ||||
pymc-devs/pymc | 38867dd19e96afb0ceccc8ccd74a9795f118dfe3 | pymc/model.py | python | Model.profile | (self, outs, *, n=1000, point=None, profile=True, **kwargs) | return f.profile | Compiles and profiles an Aesara function which returns ``outs`` and
takes values of model vars as a dict as an argument.
Parameters
----------
outs: Aesara variable or iterable of Aesara variables
n: int, default 1000
Number of iterations to run
point: point
Point to pass to the function
profile: True or ProfileStats
args, kwargs
Compilation args
Returns
-------
ProfileStats
Use .summary() to print stats. | Compiles and profiles an Aesara function which returns ``outs`` and
takes values of model vars as a dict as an argument. | [
"Compiles",
"and",
"profiles",
"an",
"Aesara",
"function",
"which",
"returns",
"outs",
"and",
"takes",
"values",
"of",
"model",
"vars",
"as",
"a",
"dict",
"as",
"an",
"argument",
"."
] | def profile(self, outs, *, n=1000, point=None, profile=True, **kwargs):
"""Compiles and profiles an Aesara function which returns ``outs`` and
takes values of model vars as a dict as an argument.
Parameters
----------
outs: Aesara variable or iterable of Aesara variables
n: int, default 1000
Number of iterations to run
point: point
Point to pass to the function
profile: True or ProfileStats
args, kwargs
Compilation args
Returns
-------
ProfileStats
Use .summary() to print stats.
"""
kwargs.setdefault("on_unused_input", "ignore")
f = self.compile_fn(outs, inputs=self.value_vars, point_fn=False, profile=profile, **kwargs)
if point is None:
point = self.recompute_initial_point()
for _ in range(n):
f(**point)
return f.profile | [
"def",
"profile",
"(",
"self",
",",
"outs",
",",
"*",
",",
"n",
"=",
"1000",
",",
"point",
"=",
"None",
",",
"profile",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
".",
"setdefault",
"(",
"\"on_unused_input\"",
",",
"\"ignore\"",
")",
... | https://github.com/pymc-devs/pymc/blob/38867dd19e96afb0ceccc8ccd74a9795f118dfe3/pymc/model.py#L1520-L1548 | |
deanishe/alfred-convert | 97407f4ec8dbca5abbc6952b2b56cf3918624177 | currencies/currencies_crypto.py | python | main | () | Generate list of cryptocurrencies with exchange rates. | Generate list of cryptocurrencies with exchange rates. | [
"Generate",
"list",
"of",
"cryptocurrencies",
"with",
"exchange",
"rates",
"."
] | def main():
"""Generate list of cryptocurrencies with exchange rates."""
r = requests.get(all_currencies_url)
r.raise_for_status()
data = r.json()
all_currencies = []
valid = []
invalid = set()
for k, d in data['Data'].items():
all_currencies.append(Currency(k, d['CoinName']))
print('%d total currencies' % len(all_currencies))
# for c in sorted(all_currencies):
for currencies in grouper(20, all_currencies):
url = base_url.format(reference_currency,
','.join([c.symbol for c in currencies]))
r = requests.get(url)
r.raise_for_status()
data = r.json()
for c in currencies:
if c.symbol in data:
valid.append(c)
print('[%s] OK' % c.symbol)
else:
invalid.add(c)
print('[%s] ERROR' % c.symbol)
sleep(0.3)
# valid = [c for c in all_currencies if c.symbol not in invalid]
with open(crypto_currencies_file, 'wb') as fp:
w = csv.writer(fp, delimiter='\t')
for c in sorted(valid, key=lambda t: t.symbol):
r = [c.symbol.encode('utf-8'), c.name.encode('utf-8')]
w.writerow(r) | [
"def",
"main",
"(",
")",
":",
"r",
"=",
"requests",
".",
"get",
"(",
"all_currencies_url",
")",
"r",
".",
"raise_for_status",
"(",
")",
"data",
"=",
"r",
".",
"json",
"(",
")",
"all_currencies",
"=",
"[",
"]",
"valid",
"=",
"[",
"]",
"invalid",
"="... | https://github.com/deanishe/alfred-convert/blob/97407f4ec8dbca5abbc6952b2b56cf3918624177/currencies/currencies_crypto.py#L56-L91 | ||
duo-labs/py_webauthn | fe97b9841328aa84559bd2a282c07d20145845c1 | webauthn/registration/formats/packed.py | python | verify_packed | (
*,
attestation_statement: AttestationStatement,
attestation_object: bytes,
client_data_json: bytes,
credential_public_key: bytes,
pem_root_certs_bytes: List[bytes],
) | return True | Verify a "packed" attestation statement
See https://www.w3.org/TR/webauthn-2/#sctn-packed-attestation | Verify a "packed" attestation statement | [
"Verify",
"a",
"packed",
"attestation",
"statement"
] | def verify_packed(
*,
attestation_statement: AttestationStatement,
attestation_object: bytes,
client_data_json: bytes,
credential_public_key: bytes,
pem_root_certs_bytes: List[bytes],
) -> bool:
"""Verify a "packed" attestation statement
See https://www.w3.org/TR/webauthn-2/#sctn-packed-attestation
"""
if not attestation_statement.sig:
raise InvalidRegistrationResponse(
"Attestation statement was missing signature (Packed)"
)
if not attestation_statement.alg:
raise InvalidRegistrationResponse(
"Attestation statement was missing algorithm (Packed)"
)
# Extract attStmt bytes from attestation_object
attestation_dict = cbor2.loads(attestation_object)
authenticator_data_bytes = attestation_dict["authData"]
# Generate a hash of client_data_json
client_data_hash = hashlib.sha256()
client_data_hash.update(client_data_json)
client_data_hash_bytes = client_data_hash.digest()
verification_data = b"".join(
[
authenticator_data_bytes,
client_data_hash_bytes,
]
)
if attestation_statement.x5c:
# Validate the certificate chain
try:
validate_certificate_chain(
x5c=attestation_statement.x5c,
pem_root_certs_bytes=pem_root_certs_bytes,
)
except InvalidCertificateChain as err:
raise InvalidRegistrationResponse(f"{err} (Packed)")
attestation_cert_bytes = attestation_statement.x5c[0]
attestation_cert = x509.load_der_x509_certificate(
attestation_cert_bytes, default_backend()
)
attestation_cert_pub_key = attestation_cert.public_key()
try:
verify_signature(
public_key=attestation_cert_pub_key,
signature_alg=attestation_statement.alg,
signature=attestation_statement.sig,
data=verification_data,
)
except InvalidSignature:
raise InvalidRegistrationResponse(
"Could not verify attestation statement signature (Packed)"
)
else:
# Self Attestation
decoded_pub_key = decode_credential_public_key(credential_public_key)
if decoded_pub_key.alg != attestation_statement.alg:
raise InvalidRegistrationResponse(
f"Credential public key alg {decoded_pub_key.alg} did not equal attestation statement alg {attestation_statement.alg}"
)
public_key = decoded_public_key_to_cryptography(decoded_pub_key)
try:
verify_signature(
public_key=public_key,
signature_alg=attestation_statement.alg,
signature=attestation_statement.sig,
data=verification_data,
)
except InvalidSignature:
raise InvalidRegistrationResponse(
"Could not verify attestation statement signature (Packed|Self)"
)
return True | [
"def",
"verify_packed",
"(",
"*",
",",
"attestation_statement",
":",
"AttestationStatement",
",",
"attestation_object",
":",
"bytes",
",",
"client_data_json",
":",
"bytes",
",",
"credential_public_key",
":",
"bytes",
",",
"pem_root_certs_bytes",
":",
"List",
"[",
"b... | https://github.com/duo-labs/py_webauthn/blob/fe97b9841328aa84559bd2a282c07d20145845c1/webauthn/registration/formats/packed.py#L22-L110 | |
Pylons/pylons | 8625d5af790560219c5114358611bc7e0edcf12f | scripts/go-pylons.py | python | find_wheels | (projects, search_dirs) | return wheels | Find wheels from which we can import PROJECTS.
Scan through SEARCH_DIRS for a wheel for each PROJECT in turn. Return
a list of the first wheel found for each PROJECT | Find wheels from which we can import PROJECTS. | [
"Find",
"wheels",
"from",
"which",
"we",
"can",
"import",
"PROJECTS",
"."
] | def find_wheels(projects, search_dirs):
"""Find wheels from which we can import PROJECTS.
Scan through SEARCH_DIRS for a wheel for each PROJECT in turn. Return
a list of the first wheel found for each PROJECT
"""
wheels = []
# Look through SEARCH_DIRS for the first suitable wheel. Don't bother
# about version checking here, as this is simply to get something we can
# then use to install the correct version.
for project in projects:
for dirname in search_dirs:
# This relies on only having "universal" wheels available.
# The pattern could be tightened to require -py2.py3-none-any.whl.
files = glob.glob(os.path.join(dirname, project + '-*.whl'))
if files:
wheels.append(os.path.abspath(files[0]))
break
else:
# We're out of luck, so quit with a suitable error
logger.fatal('Cannot find a wheel for %s' % (project,))
return wheels | [
"def",
"find_wheels",
"(",
"projects",
",",
"search_dirs",
")",
":",
"wheels",
"=",
"[",
"]",
"# Look through SEARCH_DIRS for the first suitable wheel. Don't bother",
"# about version checking here, as this is simply to get something we can",
"# then use to install the correct version.",... | https://github.com/Pylons/pylons/blob/8625d5af790560219c5114358611bc7e0edcf12f/scripts/go-pylons.py#L916-L940 | |
kubernetes-client/python | 47b9da9de2d02b2b7a34fbe05afb44afd130d73a | kubernetes/client/api/core_v1_api.py | python | CoreV1Api.list_namespaced_secret_with_http_info | (self, namespace, **kwargs) | return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/secrets', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1SecretList', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats) | list_namespaced_secret # noqa: E501
list or watch objects of kind Secret # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_namespaced_secret_with_http_info(namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1SecretList, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread. | list_namespaced_secret # noqa: E501 | [
"list_namespaced_secret",
"#",
"noqa",
":",
"E501"
] | def list_namespaced_secret_with_http_info(self, namespace, **kwargs): # noqa: E501
"""list_namespaced_secret # noqa: E501
list or watch objects of kind Secret # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_namespaced_secret_with_http_info(namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1SecretList, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'namespace',
'pretty',
'allow_watch_bookmarks',
'_continue',
'field_selector',
'label_selector',
'limit',
'resource_version',
'resource_version_match',
'timeout_seconds',
'watch'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method list_namespaced_secret" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `list_namespaced_secret`") # noqa: E501
collection_formats = {}
path_params = {}
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'allow_watch_bookmarks' in local_var_params and local_var_params['allow_watch_bookmarks'] is not None: # noqa: E501
query_params.append(('allowWatchBookmarks', local_var_params['allow_watch_bookmarks'])) # noqa: E501
if '_continue' in local_var_params and local_var_params['_continue'] is not None: # noqa: E501
query_params.append(('continue', local_var_params['_continue'])) # noqa: E501
if 'field_selector' in local_var_params and local_var_params['field_selector'] is not None: # noqa: E501
query_params.append(('fieldSelector', local_var_params['field_selector'])) # noqa: E501
if 'label_selector' in local_var_params and local_var_params['label_selector'] is not None: # noqa: E501
query_params.append(('labelSelector', local_var_params['label_selector'])) # noqa: E501
if 'limit' in local_var_params and local_var_params['limit'] is not None: # noqa: E501
query_params.append(('limit', local_var_params['limit'])) # noqa: E501
if 'resource_version' in local_var_params and local_var_params['resource_version'] is not None: # noqa: E501
query_params.append(('resourceVersion', local_var_params['resource_version'])) # noqa: E501
if 'resource_version_match' in local_var_params and local_var_params['resource_version_match'] is not None: # noqa: E501
query_params.append(('resourceVersionMatch', local_var_params['resource_version_match'])) # noqa: E501
if 'timeout_seconds' in local_var_params and local_var_params['timeout_seconds'] is not None: # noqa: E501
query_params.append(('timeoutSeconds', local_var_params['timeout_seconds'])) # noqa: E501
if 'watch' in local_var_params and local_var_params['watch'] is not None: # noqa: E501
query_params.append(('watch', local_var_params['watch'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/json;stream=watch', 'application/vnd.kubernetes.protobuf;stream=watch']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/secrets', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1SecretList', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats) | [
"def",
"list_namespaced_secret_with_http_info",
"(",
"self",
",",
"namespace",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"local_var_params",
"=",
"locals",
"(",
")",
"all_params",
"=",
"[",
"'namespace'",
",",
"'pretty'",
",",
"'allow_watch_bookmarks'",
"... | https://github.com/kubernetes-client/python/blob/47b9da9de2d02b2b7a34fbe05afb44afd130d73a/kubernetes/client/api/core_v1_api.py#L16081-L16208 | |
QCoDeS/Qcodes | 3cda2cef44812e2aa4672781f2423bf5f816f9f9 | qcodes/instrument_drivers/american_magnetics/AMI430.py | python | AMI430.set_field | (self,
value: float,
*,
block: bool = True,
perform_safety_check: bool = True) | Ramp to a certain field
Args:
value: Value to ramp to.
block: Whether to wait unit the field has finished setting
perform_safety_check: Whether to set the field via a parent
driver (if present), which might perform additional safety
checks. | Ramp to a certain field | [
"Ramp",
"to",
"a",
"certain",
"field"
] | def set_field(self,
value: float,
*,
block: bool = True,
perform_safety_check: bool = True) -> None:
"""
Ramp to a certain field
Args:
value: Value to ramp to.
block: Whether to wait unit the field has finished setting
perform_safety_check: Whether to set the field via a parent
driver (if present), which might perform additional safety
checks.
"""
# Check we aren't violating field limits
field_lim = float(self.ask("COIL?"))*self.current_limit()
if np.abs(value) > field_lim:
msg = 'Aborted _set_field; {} is higher than limit of {}'
raise ValueError(msg.format(value, field_lim))
# If part of a parent driver, set the value using that driver
if self._parent_instrument is not None and perform_safety_check:
self._parent_instrument._request_field_change(self, value)
return
# Check we can ramp
if not self._can_start_ramping():
raise AMI430Exception(f"Cannot ramp in current state: "
f"state is {self.ramping_state()}")
# Then, do the actual ramp
self.pause()
# Set the ramp target
self.write(f'CONF:FIELD:TARG {value}')
# If we have a persistent switch, make sure it is resistive
if self.switch_heater.enabled():
if not self.switch_heater.state():
raise AMI430Exception("Switch heater is not on")
self.ramp()
# Check if we want to block
if not block:
return
# Otherwise, wait until no longer ramping
self.log.debug(f'Starting blocking ramp of {self.name} to {value}')
exit_state = self.wait_while_ramping()
self.log.debug(f'Finished blocking ramp')
# If we are now holding, it was successful
if exit_state != 'holding':
msg = '_set_field({}) failed with state: {}'
raise AMI430Exception(msg.format(value, exit_state)) | [
"def",
"set_field",
"(",
"self",
",",
"value",
":",
"float",
",",
"*",
",",
"block",
":",
"bool",
"=",
"True",
",",
"perform_safety_check",
":",
"bool",
"=",
"True",
")",
"->",
"None",
":",
"# Check we aren't violating field limits",
"field_lim",
"=",
"float... | https://github.com/QCoDeS/Qcodes/blob/3cda2cef44812e2aa4672781f2423bf5f816f9f9/qcodes/instrument_drivers/american_magnetics/AMI430.py#L311-L364 | ||
jython/jython3 | def4f8ec47cb7a9c799ea4c745f12badf92c5769 | lib-python/3.5.1/poplib.py | python | POP3.quit | (self) | return resp | Signoff: commit changes on server, unlock mailbox, close connection. | Signoff: commit changes on server, unlock mailbox, close connection. | [
"Signoff",
":",
"commit",
"changes",
"on",
"server",
"unlock",
"mailbox",
"close",
"connection",
"."
] | def quit(self):
"""Signoff: commit changes on server, unlock mailbox, close connection."""
resp = self._shortcmd('QUIT')
self.close()
return resp | [
"def",
"quit",
"(",
"self",
")",
":",
"resp",
"=",
"self",
".",
"_shortcmd",
"(",
"'QUIT'",
")",
"self",
".",
"close",
"(",
")",
"return",
"resp"
] | https://github.com/jython/jython3/blob/def4f8ec47cb7a9c799ea4c745f12badf92c5769/lib-python/3.5.1/poplib.py#L272-L276 | |
VirtueSecurity/aws-extender | d123b7e1a845847709ba3a481f11996bddc68a1c | BappModules/docutils/statemachine.py | python | StateMachine.run | (self, input_lines, input_offset=0, context=None,
input_source=None, initial_state=None) | return results | Run the state machine on `input_lines`. Return results (a list).
Reset `self.line_offset` and `self.current_state`. Run the
beginning-of-file transition. Input one line at a time and check for a
matching transition. If a match is found, call the transition method
and possibly change the state. Store the context returned by the
transition method to be passed on to the next transition matched.
Accumulate the results returned by the transition methods in a list.
Run the end-of-file transition. Finally, return the accumulated
results.
Parameters:
- `input_lines`: a list of strings without newlines, or `StringList`.
- `input_offset`: the line offset of `input_lines` from the beginning
of the file.
- `context`: application-specific storage.
- `input_source`: name or path of source of `input_lines`.
- `initial_state`: name of initial state. | Run the state machine on `input_lines`. Return results (a list). | [
"Run",
"the",
"state",
"machine",
"on",
"input_lines",
".",
"Return",
"results",
"(",
"a",
"list",
")",
"."
] | def run(self, input_lines, input_offset=0, context=None,
input_source=None, initial_state=None):
"""
Run the state machine on `input_lines`. Return results (a list).
Reset `self.line_offset` and `self.current_state`. Run the
beginning-of-file transition. Input one line at a time and check for a
matching transition. If a match is found, call the transition method
and possibly change the state. Store the context returned by the
transition method to be passed on to the next transition matched.
Accumulate the results returned by the transition methods in a list.
Run the end-of-file transition. Finally, return the accumulated
results.
Parameters:
- `input_lines`: a list of strings without newlines, or `StringList`.
- `input_offset`: the line offset of `input_lines` from the beginning
of the file.
- `context`: application-specific storage.
- `input_source`: name or path of source of `input_lines`.
- `initial_state`: name of initial state.
"""
self.runtime_init()
if isinstance(input_lines, StringList):
self.input_lines = input_lines
else:
self.input_lines = StringList(input_lines, source=input_source)
self.input_offset = input_offset
self.line_offset = -1
self.current_state = initial_state or self.initial_state
if self.debug:
print >>self._stderr, (
u'\nStateMachine.run: input_lines (line_offset=%s):\n| %s'
% (self.line_offset, u'\n| '.join(self.input_lines)))
transitions = None
results = []
state = self.get_state()
try:
if self.debug:
print >>self._stderr, '\nStateMachine.run: bof transition'
context, result = state.bof(context)
results.extend(result)
while True:
try:
try:
self.next_line()
if self.debug:
source, offset = self.input_lines.info(
self.line_offset)
print >>self._stderr, (
u'\nStateMachine.run: line (source=%r, '
u'offset=%r):\n| %s'
% (source, offset, self.line))
context, next_state, result = self.check_line(
context, state, transitions)
except EOFError:
if self.debug:
print >>self._stderr, (
'\nStateMachine.run: %s.eof transition'
% state.__class__.__name__)
result = state.eof(context)
results.extend(result)
break
else:
results.extend(result)
except TransitionCorrection, exception:
self.previous_line() # back up for another try
transitions = (exception.args[0],)
if self.debug:
print >>self._stderr, (
'\nStateMachine.run: TransitionCorrection to '
'state "%s", transition %s.'
% (state.__class__.__name__, transitions[0]))
continue
except StateCorrection, exception:
self.previous_line() # back up for another try
next_state = exception.args[0]
if len(exception.args) == 1:
transitions = None
else:
transitions = (exception.args[1],)
if self.debug:
print >>self._stderr, (
'\nStateMachine.run: StateCorrection to state '
'"%s", transition %s.'
% (next_state, transitions[0]))
else:
transitions = None
state = self.get_state(next_state)
except:
if self.debug:
self.error()
raise
self.observers = []
return results | [
"def",
"run",
"(",
"self",
",",
"input_lines",
",",
"input_offset",
"=",
"0",
",",
"context",
"=",
"None",
",",
"input_source",
"=",
"None",
",",
"initial_state",
"=",
"None",
")",
":",
"self",
".",
"runtime_init",
"(",
")",
"if",
"isinstance",
"(",
"i... | https://github.com/VirtueSecurity/aws-extender/blob/d123b7e1a845847709ba3a481f11996bddc68a1c/BappModules/docutils/statemachine.py#L184-L279 | |
mkusner/grammarVAE | ffffe272a8cf1772578dfc92254c55c224cddc02 | Theano-master/theano/tensor/extra_ops.py | python | fill_diagonal | (a, val) | return fill_diagonal_(a, val) | Returns a copy of an array with all
elements of the main diagonal set to a specified scalar value.
.. versionadded:: 0.6
Parameters
----------
a
Rectangular array of at least two dimensions.
val
Scalar value to fill the diagonal whose type must be
compatible with that of array 'a' (i.e. 'val' cannot be viewed
as an upcast of 'a').
Returns
-------
array
An array identical to 'a' except that its main diagonal
is filled with scalar 'val'. (For an array 'a' with a.ndim >=
2, the main diagonal is the list of locations a[i, i, ..., i]
(i.e. with indices all identical).)
Support rectangular matrix and tensor with more than 2 dimensions
if the later have all dimensions are equals. | Returns a copy of an array with all
elements of the main diagonal set to a specified scalar value. | [
"Returns",
"a",
"copy",
"of",
"an",
"array",
"with",
"all",
"elements",
"of",
"the",
"main",
"diagonal",
"set",
"to",
"a",
"specified",
"scalar",
"value",
"."
] | def fill_diagonal(a, val):
"""
Returns a copy of an array with all
elements of the main diagonal set to a specified scalar value.
.. versionadded:: 0.6
Parameters
----------
a
Rectangular array of at least two dimensions.
val
Scalar value to fill the diagonal whose type must be
compatible with that of array 'a' (i.e. 'val' cannot be viewed
as an upcast of 'a').
Returns
-------
array
An array identical to 'a' except that its main diagonal
is filled with scalar 'val'. (For an array 'a' with a.ndim >=
2, the main diagonal is the list of locations a[i, i, ..., i]
(i.e. with indices all identical).)
Support rectangular matrix and tensor with more than 2 dimensions
if the later have all dimensions are equals.
"""
return fill_diagonal_(a, val) | [
"def",
"fill_diagonal",
"(",
"a",
",",
"val",
")",
":",
"return",
"fill_diagonal_",
"(",
"a",
",",
"val",
")"
] | https://github.com/mkusner/grammarVAE/blob/ffffe272a8cf1772578dfc92254c55c224cddc02/Theano-master/theano/tensor/extra_ops.py#L888-L918 | |
NetEaseGame/iOS-private-api-checker | c9dc24bda7398c0d33553dce2c968d308ee968e7 | db/sqlite_utils.py | python | SqliteHandler.exec_select | (self, sql, params = ()) | ps:执行查询类型的sql语句 | ps:执行查询类型的sql语句 | [
"ps:执行查询类型的sql语句"
] | def exec_select(self, sql, params = ()):
'''
ps:执行查询类型的sql语句
'''
try:
self.cursor.execute(sql, params)
result_set = self.cursor.fetchall()
return result_set
except Exception, e:
print e
return False | [
"def",
"exec_select",
"(",
"self",
",",
"sql",
",",
"params",
"=",
"(",
")",
")",
":",
"try",
":",
"self",
".",
"cursor",
".",
"execute",
"(",
"sql",
",",
"params",
")",
"result_set",
"=",
"self",
".",
"cursor",
".",
"fetchall",
"(",
")",
"return",... | https://github.com/NetEaseGame/iOS-private-api-checker/blob/c9dc24bda7398c0d33553dce2c968d308ee968e7/db/sqlite_utils.py#L44-L54 | ||
facebookresearch/Detectron | 1809dd41c1ffc881c0d6b1c16ea38d08894f8b6d | detectron/utils/keypoints.py | python | scores_to_probs | (scores) | return scores | Transforms CxHxW of scores to probabilities spatially. | Transforms CxHxW of scores to probabilities spatially. | [
"Transforms",
"CxHxW",
"of",
"scores",
"to",
"probabilities",
"spatially",
"."
] | def scores_to_probs(scores):
"""Transforms CxHxW of scores to probabilities spatially."""
channels = scores.shape[0]
for c in range(channels):
temp = scores[c, :, :]
max_score = temp.max()
temp = np.exp(temp - max_score) / np.sum(np.exp(temp - max_score))
scores[c, :, :] = temp
return scores | [
"def",
"scores_to_probs",
"(",
"scores",
")",
":",
"channels",
"=",
"scores",
".",
"shape",
"[",
"0",
"]",
"for",
"c",
"in",
"range",
"(",
"channels",
")",
":",
"temp",
"=",
"scores",
"[",
"c",
",",
":",
",",
":",
"]",
"max_score",
"=",
"temp",
"... | https://github.com/facebookresearch/Detectron/blob/1809dd41c1ffc881c0d6b1c16ea38d08894f8b6d/detectron/utils/keypoints.py#L214-L222 | |
cloudera/hue | 23f02102d4547c17c32bd5ea0eb24e9eadd657a4 | desktop/core/ext-py/pyOpenSSL-17.5.0/src/OpenSSL/crypto.py | python | Revoked.get_rev_date | (self) | return _get_asn1_time(dt) | Get the revocation timestamp.
:return: The timestamp of the revocation, as ASN.1 TIME.
:rtype: bytes | Get the revocation timestamp. | [
"Get",
"the",
"revocation",
"timestamp",
"."
] | def get_rev_date(self):
"""
Get the revocation timestamp.
:return: The timestamp of the revocation, as ASN.1 TIME.
:rtype: bytes
"""
dt = _lib.X509_REVOKED_get0_revocationDate(self._revoked)
return _get_asn1_time(dt) | [
"def",
"get_rev_date",
"(",
"self",
")",
":",
"dt",
"=",
"_lib",
".",
"X509_REVOKED_get0_revocationDate",
"(",
"self",
".",
"_revoked",
")",
"return",
"_get_asn1_time",
"(",
"dt",
")"
] | https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/pyOpenSSL-17.5.0/src/OpenSSL/crypto.py#L2098-L2106 | |
linxid/Machine_Learning_Study_Path | 558e82d13237114bbb8152483977806fc0c222af | Machine Learning In Action/Chapter4-NaiveBayes/venv/Lib/site-packages/setuptools/dist.py | python | check_nsp | (dist, attr, value) | Verify that namespace packages are valid | Verify that namespace packages are valid | [
"Verify",
"that",
"namespace",
"packages",
"are",
"valid"
] | def check_nsp(dist, attr, value):
"""Verify that namespace packages are valid"""
ns_packages = value
assert_string_list(dist, attr, ns_packages)
for nsp in ns_packages:
if not dist.has_contents_for(nsp):
raise DistutilsSetupError(
"Distribution contains no modules or packages for " +
"namespace package %r" % nsp
)
parent, sep, child = nsp.rpartition('.')
if parent and parent not in ns_packages:
distutils.log.warn(
"WARNING: %r is declared as a package namespace, but %r"
" is not: please correct this in setup.py", nsp, parent
) | [
"def",
"check_nsp",
"(",
"dist",
",",
"attr",
",",
"value",
")",
":",
"ns_packages",
"=",
"value",
"assert_string_list",
"(",
"dist",
",",
"attr",
",",
"ns_packages",
")",
"for",
"nsp",
"in",
"ns_packages",
":",
"if",
"not",
"dist",
".",
"has_contents_for"... | https://github.com/linxid/Machine_Learning_Study_Path/blob/558e82d13237114bbb8152483977806fc0c222af/Machine Learning In Action/Chapter4-NaiveBayes/venv/Lib/site-packages/setuptools/dist.py#L120-L135 | ||
HonglinChu/SiamTrackers | 8471660b14f970578a43f077b28207d44a27e867 | SiamBAN/SiamBAN/siamban/utils/bbox.py | python | get_min_max_bbox | (region) | return cx, cy, w, h | convert region to (cx, cy, w, h) that represent by mim-max box | convert region to (cx, cy, w, h) that represent by mim-max box | [
"convert",
"region",
"to",
"(",
"cx",
"cy",
"w",
"h",
")",
"that",
"represent",
"by",
"mim",
"-",
"max",
"box"
] | def get_min_max_bbox(region):
""" convert region to (cx, cy, w, h) that represent by mim-max box
"""
nv = region.size
if nv == 8:
cx = np.mean(region[0::2])
cy = np.mean(region[1::2])
x1 = min(region[0::2])
x2 = max(region[0::2])
y1 = min(region[1::2])
y2 = max(region[1::2])
w = x2 - x1
h = y2 - y1
else:
x = region[0]
y = region[1]
w = region[2]
h = region[3]
cx = x + w / 2
cy = y + h / 2
return cx, cy, w, h | [
"def",
"get_min_max_bbox",
"(",
"region",
")",
":",
"nv",
"=",
"region",
".",
"size",
"if",
"nv",
"==",
"8",
":",
"cx",
"=",
"np",
".",
"mean",
"(",
"region",
"[",
"0",
":",
":",
"2",
"]",
")",
"cy",
"=",
"np",
".",
"mean",
"(",
"region",
"["... | https://github.com/HonglinChu/SiamTrackers/blob/8471660b14f970578a43f077b28207d44a27e867/SiamBAN/SiamBAN/siamban/utils/bbox.py#L136-L156 | |
selfboot/LeetCode | 473c0c5451651140d75cbd143309c51cd8fe1cf1 | BinarySearch/153_FindMinimumInRotatedSortedArray.py | python | Solution.findMin | (self, nums) | return nums[left] | [] | def findMin(self, nums):
# assert(nums)
left = 0
right = len(nums) - 1
# Make sure right is always in the right rotated part.
# Left can be either in the left part or the minimum part.
# So, when left and right is the same finally, we find the minimum.
while left < right:
# When there is no rotate, just return self.nums[start]
if nums[left] < nums[right]:
return nums[left]
mid = (left + right) / 2
# mid is in the left part, so move the left point to mid+1.
# finally left will reach to the minimum element.
if nums[left] <= nums[mid]:
left = mid + 1
else:
right = mid
return nums[left] | [
"def",
"findMin",
"(",
"self",
",",
"nums",
")",
":",
"# assert(nums)",
"left",
"=",
"0",
"right",
"=",
"len",
"(",
"nums",
")",
"-",
"1",
"# Make sure right is always in the right rotated part.",
"# Left can be either in the left part or the minimum part.",
"# So, when l... | https://github.com/selfboot/LeetCode/blob/473c0c5451651140d75cbd143309c51cd8fe1cf1/BinarySearch/153_FindMinimumInRotatedSortedArray.py#L6-L25 | |||
zynga/jasy | 8a2ec2c2ca3f6c0f73cba4306e581c89b30f1b18 | jasy/env/Task.py | python | printTasks | (indent=16) | Prints out a list of all avaible tasks and their descriptions | Prints out a list of all avaible tasks and their descriptions | [
"Prints",
"out",
"a",
"list",
"of",
"all",
"avaible",
"tasks",
"and",
"their",
"descriptions"
] | def printTasks(indent=16):
"""Prints out a list of all avaible tasks and their descriptions"""
for name in sorted(__taskRegistry):
obj = __taskRegistry[name]
formattedName = name
if obj.__doc__:
space = (indent - len(name)) * " "
print(" %s: %s%s" % (formattedName, space, Console.colorize(obj.__doc__, "magenta")))
else:
print(" %s" % formattedName)
if obj.availableArgs or obj.hasFlexArgs:
text = ""
if obj.availableArgs:
text += Util.hyphenate("--%s <var>" % " <var> --".join(obj.availableArgs))
if obj.hasFlexArgs:
if text:
text += " ..."
else:
text += "--<name> <var>"
print(" %s" % (Console.colorize(text, "grey"))) | [
"def",
"printTasks",
"(",
"indent",
"=",
"16",
")",
":",
"for",
"name",
"in",
"sorted",
"(",
"__taskRegistry",
")",
":",
"obj",
"=",
"__taskRegistry",
"[",
"name",
"]",
"formattedName",
"=",
"name",
"if",
"obj",
".",
"__doc__",
":",
"space",
"=",
"(",
... | https://github.com/zynga/jasy/blob/8a2ec2c2ca3f6c0f73cba4306e581c89b30f1b18/jasy/env/Task.py#L147-L171 | ||
theotherp/nzbhydra | 4b03d7f769384b97dfc60dade4806c0fc987514e | libs/cookielib.py | python | deepvalues | (mapping) | Iterates over nested mapping, depth-first, in sorted order by key. | Iterates over nested mapping, depth-first, in sorted order by key. | [
"Iterates",
"over",
"nested",
"mapping",
"depth",
"-",
"first",
"in",
"sorted",
"order",
"by",
"key",
"."
] | def deepvalues(mapping):
"""Iterates over nested mapping, depth-first, in sorted order by key."""
values = vals_sorted_by_key(mapping)
for obj in values:
mapping = False
try:
obj.items
except AttributeError:
pass
else:
mapping = True
for subobj in deepvalues(obj):
yield subobj
if not mapping:
yield obj | [
"def",
"deepvalues",
"(",
"mapping",
")",
":",
"values",
"=",
"vals_sorted_by_key",
"(",
"mapping",
")",
"for",
"obj",
"in",
"values",
":",
"mapping",
"=",
"False",
"try",
":",
"obj",
".",
"items",
"except",
"AttributeError",
":",
"pass",
"else",
":",
"m... | https://github.com/theotherp/nzbhydra/blob/4b03d7f769384b97dfc60dade4806c0fc987514e/libs/cookielib.py#L1196-L1210 | ||
IronLanguages/ironpython3 | 7a7bb2a872eeab0d1009fc8a6e24dca43f65b693 | Src/StdLib/Lib/shelve.py | python | Shelf.__contains__ | (self, key) | return key.encode(self.keyencoding) in self.dict | [] | def __contains__(self, key):
return key.encode(self.keyencoding) in self.dict | [
"def",
"__contains__",
"(",
"self",
",",
"key",
")",
":",
"return",
"key",
".",
"encode",
"(",
"self",
".",
"keyencoding",
")",
"in",
"self",
".",
"dict"
] | https://github.com/IronLanguages/ironpython3/blob/7a7bb2a872eeab0d1009fc8a6e24dca43f65b693/Src/StdLib/Lib/shelve.py#L101-L102 | |||
glutanimate/cloze-overlapper | 9eabb6a9d2a6807595478647fd968e8e4bac86fc | src/cloze_overlapper/libaddon/anki/configmanager.py | python | ConfigManager.all | (self) | return self._config | Implements evaluation of self.all
Returns the values of all config storages currently managed
by the config manager instance.
Returns:
dict -- Dictionary of all config values | Implements evaluation of self.all | [
"Implements",
"evaluation",
"of",
"self",
".",
"all"
] | def all(self):
"""
Implements evaluation of self.all
Returns the values of all config storages currently managed
by the config manager instance.
Returns:
dict -- Dictionary of all config values
"""
for storage in self._storages.values():
if not storage["loaded"]:
self.load()
break
return self._config | [
"def",
"all",
"(",
"self",
")",
":",
"for",
"storage",
"in",
"self",
".",
"_storages",
".",
"values",
"(",
")",
":",
"if",
"not",
"storage",
"[",
"\"loaded\"",
"]",
":",
"self",
".",
"load",
"(",
")",
"break",
"return",
"self",
".",
"_config"
] | https://github.com/glutanimate/cloze-overlapper/blob/9eabb6a9d2a6807595478647fd968e8e4bac86fc/src/cloze_overlapper/libaddon/anki/configmanager.py#L250-L264 | |
theotherp/nzbhydra | 4b03d7f769384b97dfc60dade4806c0fc987514e | libs/requests/cookies.py | python | RequestsCookieJar.__getstate__ | (self) | return state | Unlike a normal CookieJar, this class is pickleable. | Unlike a normal CookieJar, this class is pickleable. | [
"Unlike",
"a",
"normal",
"CookieJar",
"this",
"class",
"is",
"pickleable",
"."
] | def __getstate__(self):
"""Unlike a normal CookieJar, this class is pickleable."""
state = self.__dict__.copy()
# remove the unpickleable RLock object
state.pop('_cookies_lock')
return state | [
"def",
"__getstate__",
"(",
"self",
")",
":",
"state",
"=",
"self",
".",
"__dict__",
".",
"copy",
"(",
")",
"# remove the unpickleable RLock object",
"state",
".",
"pop",
"(",
"'_cookies_lock'",
")",
"return",
"state"
] | https://github.com/theotherp/nzbhydra/blob/4b03d7f769384b97dfc60dade4806c0fc987514e/libs/requests/cookies.py#L402-L407 | |
pyqt/examples | 843bb982917cecb2350b5f6d7f42c9b7fb142ec1 | src/pyqt-official/graphicsview/embeddeddialogs/embeddeddialogs_rc.py | python | qInitResources | () | [] | def qInitResources():
QtCore.qRegisterResourceData(0x01, qt_resource_struct, qt_resource_name, qt_resource_data) | [
"def",
"qInitResources",
"(",
")",
":",
"QtCore",
".",
"qRegisterResourceData",
"(",
"0x01",
",",
"qt_resource_struct",
",",
"qt_resource_name",
",",
"qt_resource_data",
")"
] | https://github.com/pyqt/examples/blob/843bb982917cecb2350b5f6d7f42c9b7fb142ec1/src/pyqt-official/graphicsview/embeddeddialogs/embeddeddialogs_rc.py#L1951-L1952 | ||||
Azure/azure-devops-cli-extension | 11334cd55806bef0b99c3bee5a438eed71e44037 | azure-devops/azext_devops/devops_sdk/v5_1/release/release_client.py | python | ReleaseClient.update_release_resource | (self, release_update_metadata, project, release_id) | return self._deserialize('Release', response) | UpdateReleaseResource.
Update few properties of a release.
:param :class:`<ReleaseUpdateMetadata> <azure.devops.v5_1.release.models.ReleaseUpdateMetadata>` release_update_metadata: Properties of release to update.
:param str project: Project ID or project name
:param int release_id: Id of the release to update.
:rtype: :class:`<Release> <azure.devops.v5_1.release.models.Release>` | UpdateReleaseResource.
Update few properties of a release.
:param :class:`<ReleaseUpdateMetadata> <azure.devops.v5_1.release.models.ReleaseUpdateMetadata>` release_update_metadata: Properties of release to update.
:param str project: Project ID or project name
:param int release_id: Id of the release to update.
:rtype: :class:`<Release> <azure.devops.v5_1.release.models.Release>` | [
"UpdateReleaseResource",
".",
"Update",
"few",
"properties",
"of",
"a",
"release",
".",
":",
"param",
":",
"class",
":",
"<ReleaseUpdateMetadata",
">",
"<azure",
".",
"devops",
".",
"v5_1",
".",
"release",
".",
"models",
".",
"ReleaseUpdateMetadata",
">",
"rel... | def update_release_resource(self, release_update_metadata, project, release_id):
"""UpdateReleaseResource.
Update few properties of a release.
:param :class:`<ReleaseUpdateMetadata> <azure.devops.v5_1.release.models.ReleaseUpdateMetadata>` release_update_metadata: Properties of release to update.
:param str project: Project ID or project name
:param int release_id: Id of the release to update.
:rtype: :class:`<Release> <azure.devops.v5_1.release.models.Release>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if release_id is not None:
route_values['releaseId'] = self._serialize.url('release_id', release_id, 'int')
content = self._serialize.body(release_update_metadata, 'ReleaseUpdateMetadata')
response = self._send(http_method='PATCH',
location_id='a166fde7-27ad-408e-ba75-703c2cc9d500',
version='5.1',
route_values=route_values,
content=content)
return self._deserialize('Release', response) | [
"def",
"update_release_resource",
"(",
"self",
",",
"release_update_metadata",
",",
"project",
",",
"release_id",
")",
":",
"route_values",
"=",
"{",
"}",
"if",
"project",
"is",
"not",
"None",
":",
"route_values",
"[",
"'project'",
"]",
"=",
"self",
".",
"_s... | https://github.com/Azure/azure-devops-cli-extension/blob/11334cd55806bef0b99c3bee5a438eed71e44037/azure-devops/azext_devops/devops_sdk/v5_1/release/release_client.py#L867-L886 | |
CLUEbenchmark/CLUE | 5bd39732734afecb490cf18a5212e692dbf2c007 | baselines/models/roberta_wwm_ext/tokenization.py | python | BasicTokenizer._tokenize_chinese_chars | (self, text) | return "".join(output) | Adds whitespace around any CJK character. | Adds whitespace around any CJK character. | [
"Adds",
"whitespace",
"around",
"any",
"CJK",
"character",
"."
] | def _tokenize_chinese_chars(self, text):
"""Adds whitespace around any CJK character."""
output = []
for char in text:
cp = ord(char)
if self._is_chinese_char(cp):
output.append(" ")
output.append(char)
output.append(" ")
else:
output.append(char)
return "".join(output) | [
"def",
"_tokenize_chinese_chars",
"(",
"self",
",",
"text",
")",
":",
"output",
"=",
"[",
"]",
"for",
"char",
"in",
"text",
":",
"cp",
"=",
"ord",
"(",
"char",
")",
"if",
"self",
".",
"_is_chinese_char",
"(",
"cp",
")",
":",
"output",
".",
"append",
... | https://github.com/CLUEbenchmark/CLUE/blob/5bd39732734afecb490cf18a5212e692dbf2c007/baselines/models/roberta_wwm_ext/tokenization.py#L251-L262 | |
bwohlberg/sporco | df67462abcf83af6ab1961bcb0d51b87a66483fa | sporco/admm/tvl2.py | python | TVL2Deconv.xstep | (self) | r"""Minimise Augmented Lagrangian with respect to
:math:`\mathbf{x}`. | r"""Minimise Augmented Lagrangian with respect to
:math:`\mathbf{x}`. | [
"r",
"Minimise",
"Augmented",
"Lagrangian",
"with",
"respect",
"to",
":",
"math",
":",
"\\",
"mathbf",
"{",
"x",
"}",
"."
] | def xstep(self):
r"""Minimise Augmented Lagrangian with respect to
:math:`\mathbf{x}`.
"""
b = self.AHSf + self.rho*np.sum(
np.conj(self.Gf)*self.fftn(self.Y-self.U, axes=self.axes),
axis=self.Y.ndim-1)
self.Xf = b / (self.AHAf + self.rho*self.GHGf)
self.X = self.ifftn(self.Xf, self.axsz, axes=self.axes)
if self.opt['LinSolveCheck']:
ax = (self.AHAf + self.rho*self.GHGf)*self.Xf
self.xrrs = rrs(ax, b)
else:
self.xrrs = None | [
"def",
"xstep",
"(",
"self",
")",
":",
"b",
"=",
"self",
".",
"AHSf",
"+",
"self",
".",
"rho",
"*",
"np",
".",
"sum",
"(",
"np",
".",
"conj",
"(",
"self",
".",
"Gf",
")",
"*",
"self",
".",
"fftn",
"(",
"self",
".",
"Y",
"-",
"self",
".",
... | https://github.com/bwohlberg/sporco/blob/df67462abcf83af6ab1961bcb0d51b87a66483fa/sporco/admm/tvl2.py#L594-L609 | ||
facebookresearch/pytorch_GAN_zoo | b75dee40918caabb4fe7ec561522717bf096a8cb | models/trainer/progressive_gan_trainer.py | python | ProgressiveGANTrainer.initModel | (self) | r"""
Initialize the GAN model. | r"""
Initialize the GAN model. | [
"r",
"Initialize",
"the",
"GAN",
"model",
"."
] | def initModel(self):
r"""
Initialize the GAN model.
"""
config = {key: value for key, value in vars(self.modelConfig).items()}
config["depthScale0"] = self.modelConfig.depthScales[0]
self.model = ProgressiveGAN(useGPU=self.useGPU, **config) | [
"def",
"initModel",
"(",
"self",
")",
":",
"config",
"=",
"{",
"key",
":",
"value",
"for",
"key",
",",
"value",
"in",
"vars",
"(",
"self",
".",
"modelConfig",
")",
".",
"items",
"(",
")",
"}",
"config",
"[",
"\"depthScale0\"",
"]",
"=",
"self",
"."... | https://github.com/facebookresearch/pytorch_GAN_zoo/blob/b75dee40918caabb4fe7ec561522717bf096a8cb/models/trainer/progressive_gan_trainer.py#L67-L74 | ||
alanhamlett/pip-update-requirements | ce875601ef278c8ce00ad586434a978731525561 | pur/packages/pip/_vendor/distlib/manifest.py | python | Manifest.__init__ | (self, base=None) | Initialise an instance.
:param base: The base directory to explore under. | Initialise an instance. | [
"Initialise",
"an",
"instance",
"."
] | def __init__(self, base=None):
"""
Initialise an instance.
:param base: The base directory to explore under.
"""
self.base = os.path.abspath(os.path.normpath(base or os.getcwd()))
self.prefix = self.base + os.sep
self.allfiles = None
self.files = set() | [
"def",
"__init__",
"(",
"self",
",",
"base",
"=",
"None",
")",
":",
"self",
".",
"base",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"normpath",
"(",
"base",
"or",
"os",
".",
"getcwd",
"(",
")",
")",
")",
"self",
".",
... | https://github.com/alanhamlett/pip-update-requirements/blob/ce875601ef278c8ce00ad586434a978731525561/pur/packages/pip/_vendor/distlib/manifest.py#L42-L51 | ||
NTMC-Community/MatchZoo-py | 0e5c04e1e948aa9277abd5c85ff99d9950d8527f | matchzoo/auto/preparer/prepare.py | python | prepare | (
task: BaseTask,
model_class: typing.Type[BaseModel],
data_pack: mz.DataPack,
callback: typing.Optional[BaseCallback] = None,
preprocessor: typing.Optional[BasePreprocessor] = None,
embedding: typing.Optional['mz.Embedding'] = None,
config: typing.Optional[dict] = None,
) | return preparer.prepare(
model_class=model_class,
data_pack=data_pack,
callback=callback,
preprocessor=preprocessor,
embedding=embedding
) | A simple shorthand for using :class:`matchzoo.Preparer`.
`config` is used to control specific behaviors. The default `config`
will be updated accordingly if a `config` dictionary is passed. e.g. to
override the default `bin_size`, pass `config={'bin_size': 15}`.
:param task: Task.
:param model_class: Model class.
:param data_pack: DataPack used to fit the preprocessor.
:param callback: Callback used to padding a batch.
(default: the default callback of `model_class`)
:param preprocessor: Preprocessor used to fit the `data_pack`.
(default: the default preprocessor of `model_class`)
:param embedding: Embedding to build a embedding matrix. If not set,
then a correctly shaped randomized matrix will be built.
:param config: Configuration of specific behaviors. (default: return
value of `mz.Preparer.get_default_config()`)
:return: A tuple of `(model, preprocessor, data_generator_builder,
embedding_matrix)`. | A simple shorthand for using :class:`matchzoo.Preparer`. | [
"A",
"simple",
"shorthand",
"for",
"using",
":",
"class",
":",
"matchzoo",
".",
"Preparer",
"."
] | def prepare(
task: BaseTask,
model_class: typing.Type[BaseModel],
data_pack: mz.DataPack,
callback: typing.Optional[BaseCallback] = None,
preprocessor: typing.Optional[BasePreprocessor] = None,
embedding: typing.Optional['mz.Embedding'] = None,
config: typing.Optional[dict] = None,
):
"""
A simple shorthand for using :class:`matchzoo.Preparer`.
`config` is used to control specific behaviors. The default `config`
will be updated accordingly if a `config` dictionary is passed. e.g. to
override the default `bin_size`, pass `config={'bin_size': 15}`.
:param task: Task.
:param model_class: Model class.
:param data_pack: DataPack used to fit the preprocessor.
:param callback: Callback used to padding a batch.
(default: the default callback of `model_class`)
:param preprocessor: Preprocessor used to fit the `data_pack`.
(default: the default preprocessor of `model_class`)
:param embedding: Embedding to build a embedding matrix. If not set,
then a correctly shaped randomized matrix will be built.
:param config: Configuration of specific behaviors. (default: return
value of `mz.Preparer.get_default_config()`)
:return: A tuple of `(model, preprocessor, data_generator_builder,
embedding_matrix)`.
"""
preparer = Preparer(task=task, config=config)
return preparer.prepare(
model_class=model_class,
data_pack=data_pack,
callback=callback,
preprocessor=preprocessor,
embedding=embedding
) | [
"def",
"prepare",
"(",
"task",
":",
"BaseTask",
",",
"model_class",
":",
"typing",
".",
"Type",
"[",
"BaseModel",
"]",
",",
"data_pack",
":",
"mz",
".",
"DataPack",
",",
"callback",
":",
"typing",
".",
"Optional",
"[",
"BaseCallback",
"]",
"=",
"None",
... | https://github.com/NTMC-Community/MatchZoo-py/blob/0e5c04e1e948aa9277abd5c85ff99d9950d8527f/matchzoo/auto/preparer/prepare.py#L11-L50 | |
kuri65536/python-for-android | 26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891 | python-build/python-libs/xmpppy/xmpp/transports.py | python | TLS.FeaturesHandler | (self, conn, feats) | Used to analyse server <features/> tag for TLS support.
If TLS is supported starts the encryption negotiation. Used internally | Used to analyse server <features/> tag for TLS support.
If TLS is supported starts the encryption negotiation. Used internally | [
"Used",
"to",
"analyse",
"server",
"<features",
"/",
">",
"tag",
"for",
"TLS",
"support",
".",
"If",
"TLS",
"is",
"supported",
"starts",
"the",
"encryption",
"negotiation",
".",
"Used",
"internally"
] | def FeaturesHandler(self, conn, feats):
""" Used to analyse server <features/> tag for TLS support.
If TLS is supported starts the encryption negotiation. Used internally"""
if not feats.getTag('starttls',namespace=NS_TLS):
self.DEBUG("TLS unsupported by remote server.",'warn')
return
self.DEBUG("TLS supported by remote server. Requesting TLS start.",'ok')
self._owner.RegisterHandlerOnce('proceed',self.StartTLSHandler,xmlns=NS_TLS)
self._owner.RegisterHandlerOnce('failure',self.StartTLSHandler,xmlns=NS_TLS)
self._owner.Connection.send('<starttls xmlns="%s"/>'%NS_TLS)
raise NodeProcessed | [
"def",
"FeaturesHandler",
"(",
"self",
",",
"conn",
",",
"feats",
")",
":",
"if",
"not",
"feats",
".",
"getTag",
"(",
"'starttls'",
",",
"namespace",
"=",
"NS_TLS",
")",
":",
"self",
".",
"DEBUG",
"(",
"\"TLS unsupported by remote server.\"",
",",
"'warn'",
... | https://github.com/kuri65536/python-for-android/blob/26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891/python-build/python-libs/xmpppy/xmpp/transports.py#L295-L305 | ||
marian-margeta/gait-recognition | a9d1a738d4ca9c37355e0de4768a32c5f040d7fc | torchfile.py | python | add_tensor_reader | (typename, dtype) | [] | def add_tensor_reader(typename, dtype):
def read_tensor_generic(reader, version):
# source:
# https://github.com/torch/torch7/blob/master/generic/Tensor.c#L1243
ndim = reader.read_int()
# read size:
size = reader.read_long_array(ndim)
# read stride:
stride = reader.read_long_array(ndim)
# storage offset:
storage_offset = reader.read_long() - 1
# read storage:
storage = reader.read_obj()
if storage is None or ndim == 0 or len(size) == 0 or len(stride) == 0:
# empty torch tensor
return np.empty((0), dtype=dtype)
# convert stride to numpy style (i.e. in bytes)
stride = [storage.dtype.itemsize * x for x in stride]
# create numpy array that indexes into the storage:
return np.lib.stride_tricks.as_strided(
storage[storage_offset:],
shape=size,
strides=stride)
torch_readers[typename] = read_tensor_generic | [
"def",
"add_tensor_reader",
"(",
"typename",
",",
"dtype",
")",
":",
"def",
"read_tensor_generic",
"(",
"reader",
",",
"version",
")",
":",
"# source:",
"# https://github.com/torch/torch7/blob/master/generic/Tensor.c#L1243",
"ndim",
"=",
"reader",
".",
"read_int",
"(",
... | https://github.com/marian-margeta/gait-recognition/blob/a9d1a738d4ca9c37355e0de4768a32c5f040d7fc/torchfile.py#L102-L129 | ||||
python/cpython | e13cdca0f5224ec4e23bdd04bb3120506964bc8b | Lib/idlelib/run.py | python | capture_warnings | (capture) | Replace warning.showwarning with idle_showwarning_subproc, or reverse. | Replace warning.showwarning with idle_showwarning_subproc, or reverse. | [
"Replace",
"warning",
".",
"showwarning",
"with",
"idle_showwarning_subproc",
"or",
"reverse",
"."
] | def capture_warnings(capture):
"Replace warning.showwarning with idle_showwarning_subproc, or reverse."
global _warnings_showwarning
if capture:
if _warnings_showwarning is None:
_warnings_showwarning = warnings.showwarning
warnings.showwarning = idle_showwarning_subproc
else:
if _warnings_showwarning is not None:
warnings.showwarning = _warnings_showwarning
_warnings_showwarning = None | [
"def",
"capture_warnings",
"(",
"capture",
")",
":",
"global",
"_warnings_showwarning",
"if",
"capture",
":",
"if",
"_warnings_showwarning",
"is",
"None",
":",
"_warnings_showwarning",
"=",
"warnings",
".",
"showwarning",
"warnings",
".",
"showwarning",
"=",
"idle_s... | https://github.com/python/cpython/blob/e13cdca0f5224ec4e23bdd04bb3120506964bc8b/Lib/idlelib/run.py#L80-L91 | ||
aroberge/friendly | 0b82326ba1cb982f8612885ac60957f095d7476f | friendly/token_utils.py | python | Token.is_operator | (self) | return self.type == py_tokenize.OP | Returns true if the token is of type OP | Returns true if the token is of type OP | [
"Returns",
"true",
"if",
"the",
"token",
"is",
"of",
"type",
"OP"
] | def is_operator(self):
"""Returns true if the token is of type OP"""
return self.type == py_tokenize.OP | [
"def",
"is_operator",
"(",
"self",
")",
":",
"return",
"self",
".",
"type",
"==",
"py_tokenize",
".",
"OP"
] | https://github.com/aroberge/friendly/blob/0b82326ba1cb982f8612885ac60957f095d7476f/friendly/token_utils.py#L107-L109 | |
volatilityfoundation/volatility | a438e768194a9e05eb4d9ee9338b881c0fa25937 | volatility/plugins/linux/process_info.py | python | read_int_list | ( start, end, addr_space) | return int_list(read_addr_range(start, end, addr_space), end - start) | Read a number of pages and split it into integers.
@param start: Start address
@param end: End address
@param addr_space: The virtual address space
@return: a list of integers. | Read a number of pages and split it into integers. | [
"Read",
"a",
"number",
"of",
"pages",
"and",
"split",
"it",
"into",
"integers",
"."
] | def read_int_list( start, end, addr_space):
"""
Read a number of pages and split it into integers.
@param start: Start address
@param end: End address
@param addr_space: The virtual address space
@return: a list of integers.
"""
return int_list(read_addr_range(start, end, addr_space), end - start) | [
"def",
"read_int_list",
"(",
"start",
",",
"end",
",",
"addr_space",
")",
":",
"return",
"int_list",
"(",
"read_addr_range",
"(",
"start",
",",
"end",
",",
"addr_space",
")",
",",
"end",
"-",
"start",
")"
] | https://github.com/volatilityfoundation/volatility/blob/a438e768194a9e05eb4d9ee9338b881c0fa25937/volatility/plugins/linux/process_info.py#L136-L145 | |
PokemonGoF/PokemonGo-Bot-Desktop | 4bfa94f0183406c6a86f93645eff7abd3ad4ced8 | build/pywin/Lib/pkgutil.py | python | iter_modules | (path=None, prefix='') | Yields (module_loader, name, ispkg) for all submodules on path,
or, if path is None, all top-level modules on sys.path.
'path' should be either None or a list of paths to look for
modules in.
'prefix' is a string to output on the front of every module name
on output. | Yields (module_loader, name, ispkg) for all submodules on path,
or, if path is None, all top-level modules on sys.path. | [
"Yields",
"(",
"module_loader",
"name",
"ispkg",
")",
"for",
"all",
"submodules",
"on",
"path",
"or",
"if",
"path",
"is",
"None",
"all",
"top",
"-",
"level",
"modules",
"on",
"sys",
".",
"path",
"."
] | def iter_modules(path=None, prefix=''):
"""Yields (module_loader, name, ispkg) for all submodules on path,
or, if path is None, all top-level modules on sys.path.
'path' should be either None or a list of paths to look for
modules in.
'prefix' is a string to output on the front of every module name
on output.
"""
if path is None:
importers = iter_importers()
else:
importers = map(get_importer, path)
yielded = {}
for i in importers:
for name, ispkg in iter_importer_modules(i, prefix):
if name not in yielded:
yielded[name] = 1
yield i, name, ispkg | [
"def",
"iter_modules",
"(",
"path",
"=",
"None",
",",
"prefix",
"=",
"''",
")",
":",
"if",
"path",
"is",
"None",
":",
"importers",
"=",
"iter_importers",
"(",
")",
"else",
":",
"importers",
"=",
"map",
"(",
"get_importer",
",",
"path",
")",
"yielded",
... | https://github.com/PokemonGoF/PokemonGo-Bot-Desktop/blob/4bfa94f0183406c6a86f93645eff7abd3ad4ced8/build/pywin/Lib/pkgutil.py#L129-L150 | ||
gem/oq-engine | 1bdb88f3914e390abcbd285600bfd39477aae47c | openquake/hazardlib/geo/surface/planar.py | python | PlanarSurface.get_middle_point | (self) | return Point(lon, lat, depth) | Compute middle point from surface's corners coordinates. Calls
:meth:`openquake.hazardlib.geo.utils.get_middle_point` | Compute middle point from surface's corners coordinates. Calls
:meth:`openquake.hazardlib.geo.utils.get_middle_point` | [
"Compute",
"middle",
"point",
"from",
"surface",
"s",
"corners",
"coordinates",
".",
"Calls",
":",
"meth",
":",
"openquake",
".",
"hazardlib",
".",
"geo",
".",
"utils",
".",
"get_middle_point"
] | def get_middle_point(self):
"""
Compute middle point from surface's corners coordinates. Calls
:meth:`openquake.hazardlib.geo.utils.get_middle_point`
"""
# compute middle point between upper left and bottom right corners
lon, lat = geo_utils.get_middle_point(self.corner_lons[0],
self.corner_lats[0],
self.corner_lons[3],
self.corner_lats[3])
depth = (self.corner_depths[0] + self.corner_depths[3]) / 2.
return Point(lon, lat, depth) | [
"def",
"get_middle_point",
"(",
"self",
")",
":",
"# compute middle point between upper left and bottom right corners",
"lon",
",",
"lat",
"=",
"geo_utils",
".",
"get_middle_point",
"(",
"self",
".",
"corner_lons",
"[",
"0",
"]",
",",
"self",
".",
"corner_lats",
"["... | https://github.com/gem/oq-engine/blob/1bdb88f3914e390abcbd285600bfd39477aae47c/openquake/hazardlib/geo/surface/planar.py#L664-L676 | |
maas/maas | db2f89970c640758a51247c59bf1ec6f60cf4ab5 | src/maasserver/node_action.py | python | Acquire._execute | (self) | See `NodeAction.execute`. | See `NodeAction.execute`. | [
"See",
"NodeAction",
".",
"execute",
"."
] | def _execute(self):
"""See `NodeAction.execute`."""
with locks.node_acquire:
try:
self.node.acquire(self.user)
except ValidationError as e:
raise NodeActionError(e) | [
"def",
"_execute",
"(",
"self",
")",
":",
"with",
"locks",
".",
"node_acquire",
":",
"try",
":",
"self",
".",
"node",
".",
"acquire",
"(",
"self",
".",
"user",
")",
"except",
"ValidationError",
"as",
"e",
":",
"raise",
"NodeActionError",
"(",
"e",
")"
... | https://github.com/maas/maas/blob/db2f89970c640758a51247c59bf1ec6f60cf4ab5/src/maasserver/node_action.py#L469-L475 | ||
CGATOxford/cgat | 326aad4694bdfae8ddc194171bb5d73911243947 | CGAT/TreeTools.py | python | GetTaxonomicNames | (tree) | return GetTaxa(tree) | get list of taxa. | get list of taxa. | [
"get",
"list",
"of",
"taxa",
"."
] | def GetTaxonomicNames(tree):
"""get list of taxa."""
return GetTaxa(tree) | [
"def",
"GetTaxonomicNames",
"(",
"tree",
")",
":",
"return",
"GetTaxa",
"(",
"tree",
")"
] | https://github.com/CGATOxford/cgat/blob/326aad4694bdfae8ddc194171bb5d73911243947/CGAT/TreeTools.py#L184-L186 | |
pyparallel/pyparallel | 11e8c6072d48c8f13641925d17b147bf36ee0ba3 | Lib/site-packages/pip-7.1.2-py3.3.egg/pip/_vendor/pkg_resources/__init__.py | python | Environment.best_match | (self, req, working_set, installer=None) | return self.obtain(req, installer) | Find distribution best matching `req` and usable on `working_set`
This calls the ``find(req)`` method of the `working_set` to see if a
suitable distribution is already active. (This may raise
``VersionConflict`` if an unsuitable version of the project is already
active in the specified `working_set`.) If a suitable distribution
isn't active, this method returns the newest distribution in the
environment that meets the ``Requirement`` in `req`. If no suitable
distribution is found, and `installer` is supplied, then the result of
calling the environment's ``obtain(req, installer)`` method will be
returned. | Find distribution best matching `req` and usable on `working_set` | [
"Find",
"distribution",
"best",
"matching",
"req",
"and",
"usable",
"on",
"working_set"
] | def best_match(self, req, working_set, installer=None):
"""Find distribution best matching `req` and usable on `working_set`
This calls the ``find(req)`` method of the `working_set` to see if a
suitable distribution is already active. (This may raise
``VersionConflict`` if an unsuitable version of the project is already
active in the specified `working_set`.) If a suitable distribution
isn't active, this method returns the newest distribution in the
environment that meets the ``Requirement`` in `req`. If no suitable
distribution is found, and `installer` is supplied, then the result of
calling the environment's ``obtain(req, installer)`` method will be
returned.
"""
dist = working_set.find(req)
if dist is not None:
return dist
for dist in self[req.key]:
if dist in req:
return dist
# try to download/install
return self.obtain(req, installer) | [
"def",
"best_match",
"(",
"self",
",",
"req",
",",
"working_set",
",",
"installer",
"=",
"None",
")",
":",
"dist",
"=",
"working_set",
".",
"find",
"(",
"req",
")",
"if",
"dist",
"is",
"not",
"None",
":",
"return",
"dist",
"for",
"dist",
"in",
"self"... | https://github.com/pyparallel/pyparallel/blob/11e8c6072d48c8f13641925d17b147bf36ee0ba3/Lib/site-packages/pip-7.1.2-py3.3.egg/pip/_vendor/pkg_resources/__init__.py#L1055-L1075 | |
holzschu/Carnets | 44effb10ddfc6aa5c8b0687582a724ba82c6b547 | Library/lib/python3.7/site-packages/astropy-4.0-py3.7-macosx-10.9-x86_64.egg/astropy/table/bst.py | python | BST.range_nodes | (self, lower, upper, bounds=(True, True)) | return self._range(lower, upper, op1, op2, self.root, []) | Return nodes in the given range. | Return nodes in the given range. | [
"Return",
"nodes",
"in",
"the",
"given",
"range",
"."
] | def range_nodes(self, lower, upper, bounds=(True, True)):
'''
Return nodes in the given range.
'''
if self.root is None:
return []
# op1 is <= or <, op2 is >= or >
op1 = operator.le if bounds[0] else operator.lt
op2 = operator.ge if bounds[1] else operator.gt
return self._range(lower, upper, op1, op2, self.root, []) | [
"def",
"range_nodes",
"(",
"self",
",",
"lower",
",",
"upper",
",",
"bounds",
"=",
"(",
"True",
",",
"True",
")",
")",
":",
"if",
"self",
".",
"root",
"is",
"None",
":",
"return",
"[",
"]",
"# op1 is <= or <, op2 is >= or >",
"op1",
"=",
"operator",
".... | https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/astropy-4.0-py3.7-macosx-10.9-x86_64.egg/astropy/table/bst.py#L408-L417 | |
krintoxi/NoobSec-Toolkit | 38738541cbc03cedb9a3b3ed13b629f781ad64f6 | NoobSecToolkit /scripts/sshbackdoors/backdoors/shell/pupy/pupy/pupylib/PupyJob.py | python | PupyJob.interactive_wait | (self) | return False | [] | def interactive_wait(self):
while True:
if self.is_finished():
break
time.sleep(0.1)
if self.error_happened.is_set():
return True
return False | [
"def",
"interactive_wait",
"(",
"self",
")",
":",
"while",
"True",
":",
"if",
"self",
".",
"is_finished",
"(",
")",
":",
"break",
"time",
".",
"sleep",
"(",
"0.1",
")",
"if",
"self",
".",
"error_happened",
".",
"is_set",
"(",
")",
":",
"return",
"Tru... | https://github.com/krintoxi/NoobSec-Toolkit/blob/38738541cbc03cedb9a3b3ed13b629f781ad64f6/NoobSecToolkit /scripts/sshbackdoors/backdoors/shell/pupy/pupy/pupylib/PupyJob.py#L156-L163 | |||
plotly/plotly.py | cfad7862594b35965c0e000813bd7805e8494a5b | packages/python/plotly/plotly/graph_objs/histogram2d/_colorbar.py | python | ColorBar.ticktext | (self) | return self["ticktext"] | Sets the text displayed at the ticks position via `tickvals`.
Only has an effect if `tickmode` is set to "array". Used with
`tickvals`.
The 'ticktext' property is an array that may be specified as a tuple,
list, numpy array, or pandas Series
Returns
-------
numpy.ndarray | Sets the text displayed at the ticks position via `tickvals`.
Only has an effect if `tickmode` is set to "array". Used with
`tickvals`.
The 'ticktext' property is an array that may be specified as a tuple,
list, numpy array, or pandas Series | [
"Sets",
"the",
"text",
"displayed",
"at",
"the",
"ticks",
"position",
"via",
"tickvals",
".",
"Only",
"has",
"an",
"effect",
"if",
"tickmode",
"is",
"set",
"to",
"array",
".",
"Used",
"with",
"tickvals",
".",
"The",
"ticktext",
"property",
"is",
"an",
"a... | def ticktext(self):
"""
Sets the text displayed at the ticks position via `tickvals`.
Only has an effect if `tickmode` is set to "array". Used with
`tickvals`.
The 'ticktext' property is an array that may be specified as a tuple,
list, numpy array, or pandas Series
Returns
-------
numpy.ndarray
"""
return self["ticktext"] | [
"def",
"ticktext",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"ticktext\"",
"]"
] | https://github.com/plotly/plotly.py/blob/cfad7862594b35965c0e000813bd7805e8494a5b/packages/python/plotly/plotly/graph_objs/histogram2d/_colorbar.py#L1040-L1053 | |
riptideio/pymodbus | c5772b35ae3f29d1947f3ab453d8d00df846459f | pymodbus/diag_message.py | python | ForceListenOnlyModeRequest.execute | (self, *args) | return ForceListenOnlyModeResponse() | Execute the diagnostic request on the given device
:returns: The initialized response message | Execute the diagnostic request on the given device | [
"Execute",
"the",
"diagnostic",
"request",
"on",
"the",
"given",
"device"
] | def execute(self, *args):
''' Execute the diagnostic request on the given device
:returns: The initialized response message
'''
_MCB.ListenOnly = True
return ForceListenOnlyModeResponse() | [
"def",
"execute",
"(",
"self",
",",
"*",
"args",
")",
":",
"_MCB",
".",
"ListenOnly",
"=",
"True",
"return",
"ForceListenOnlyModeResponse",
"(",
")"
] | https://github.com/riptideio/pymodbus/blob/c5772b35ae3f29d1947f3ab453d8d00df846459f/pymodbus/diag_message.py#L348-L354 | |
home-assistant/core | 265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1 | homeassistant/components/shelly/config_flow.py | python | ConfigFlow.async_step_confirm_discovery | (
self, user_input: dict[str, Any] | None = None
) | return self.async_show_form(
step_id="confirm_discovery",
description_placeholders={
"model": get_model_name(self.info),
"host": self.host,
},
errors=errors,
) | Handle discovery confirm. | Handle discovery confirm. | [
"Handle",
"discovery",
"confirm",
"."
] | async def async_step_confirm_discovery(
self, user_input: dict[str, Any] | None = None
) -> FlowResult:
"""Handle discovery confirm."""
errors: dict[str, str] = {}
if user_input is not None:
return self.async_create_entry(
title=self.device_info["title"],
data={
"host": self.host,
CONF_SLEEP_PERIOD: self.device_info[CONF_SLEEP_PERIOD],
"model": self.device_info["model"],
"gen": self.device_info["gen"],
},
)
self._set_confirm_only()
return self.async_show_form(
step_id="confirm_discovery",
description_placeholders={
"model": get_model_name(self.info),
"host": self.host,
},
errors=errors,
) | [
"async",
"def",
"async_step_confirm_discovery",
"(",
"self",
",",
"user_input",
":",
"dict",
"[",
"str",
",",
"Any",
"]",
"|",
"None",
"=",
"None",
")",
"->",
"FlowResult",
":",
"errors",
":",
"dict",
"[",
"str",
",",
"str",
"]",
"=",
"{",
"}",
"if",... | https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/shelly/config_flow.py#L216-L241 | |
saltstack/salt | fae5bc757ad0f1716483ce7ae180b451545c2058 | salt/runners/virt.py | python | vm_info | (name, quiet=False) | return _find_vm(name, data, quiet) | Return the information on the named VM | Return the information on the named VM | [
"Return",
"the",
"information",
"on",
"the",
"named",
"VM"
] | def vm_info(name, quiet=False):
"""
Return the information on the named VM
"""
data = query(quiet=True)
return _find_vm(name, data, quiet) | [
"def",
"vm_info",
"(",
"name",
",",
"quiet",
"=",
"False",
")",
":",
"data",
"=",
"query",
"(",
"quiet",
"=",
"True",
")",
"return",
"_find_vm",
"(",
"name",
",",
"data",
",",
"quiet",
")"
] | https://github.com/saltstack/salt/blob/fae5bc757ad0f1716483ce7ae180b451545c2058/salt/runners/virt.py#L326-L331 | |
atomistic-machine-learning/schnetpack | dacf6076d43509dfd8b6694a846ac8453ae39b5e | src/schnetpack/interfaces/ase_interface.py | python | AseInterface.run_md | (self, steps) | Perform a molecular dynamics simulation using the settings specified
upon initializing the class.
Args:
steps (int): Number of simulation steps performed | Perform a molecular dynamics simulation using the settings specified
upon initializing the class. | [
"Perform",
"a",
"molecular",
"dynamics",
"simulation",
"using",
"the",
"settings",
"specified",
"upon",
"initializing",
"the",
"class",
"."
] | def run_md(self, steps):
"""
Perform a molecular dynamics simulation using the settings specified
upon initializing the class.
Args:
steps (int): Number of simulation steps performed
"""
if not self.dynamics:
raise AttributeError(
"Dynamics need to be initialized using the" " 'setup_md' function"
)
self.dynamics.run(steps) | [
"def",
"run_md",
"(",
"self",
",",
"steps",
")",
":",
"if",
"not",
"self",
".",
"dynamics",
":",
"raise",
"AttributeError",
"(",
"\"Dynamics need to be initialized using the\"",
"\" 'setup_md' function\"",
")",
"self",
".",
"dynamics",
".",
"run",
"(",
"steps",
... | https://github.com/atomistic-machine-learning/schnetpack/blob/dacf6076d43509dfd8b6694a846ac8453ae39b5e/src/schnetpack/interfaces/ase_interface.py#L329-L342 | ||
triaquae/triaquae | bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9 | TriAquae/models/Centos_5.9/paramiko/transport.py | python | Transport.get_security_options | (self) | return SecurityOptions(self) | Return a L{SecurityOptions} object which can be used to tweak the
encryption algorithms this transport will permit, and the order of
preference for them.
@return: an object that can be used to change the preferred algorithms
for encryption, digest (hash), public key, and key exchange.
@rtype: L{SecurityOptions} | Return a L{SecurityOptions} object which can be used to tweak the
encryption algorithms this transport will permit, and the order of
preference for them. | [
"Return",
"a",
"L",
"{",
"SecurityOptions",
"}",
"object",
"which",
"can",
"be",
"used",
"to",
"tweak",
"the",
"encryption",
"algorithms",
"this",
"transport",
"will",
"permit",
"and",
"the",
"order",
"of",
"preference",
"for",
"them",
"."
] | def get_security_options(self):
"""
Return a L{SecurityOptions} object which can be used to tweak the
encryption algorithms this transport will permit, and the order of
preference for them.
@return: an object that can be used to change the preferred algorithms
for encryption, digest (hash), public key, and key exchange.
@rtype: L{SecurityOptions}
"""
return SecurityOptions(self) | [
"def",
"get_security_options",
"(",
"self",
")",
":",
"return",
"SecurityOptions",
"(",
"self",
")"
] | https://github.com/triaquae/triaquae/blob/bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9/TriAquae/models/Centos_5.9/paramiko/transport.py#L407-L417 | |
JiYou/openstack | 8607dd488bde0905044b303eb6e52bdea6806923 | chap19/monitor/monitor/monitor/openstack/common/rpc/amqp.py | python | call | (conf, context, topic, msg, timeout, connection_pool) | return rv[-1] | Sends a message on a topic and wait for a response. | Sends a message on a topic and wait for a response. | [
"Sends",
"a",
"message",
"on",
"a",
"topic",
"and",
"wait",
"for",
"a",
"response",
"."
] | def call(conf, context, topic, msg, timeout, connection_pool):
"""Sends a message on a topic and wait for a response."""
rv = multicall(conf, context, topic, msg, timeout, connection_pool)
# NOTE(vish): return the last result from the multicall
rv = list(rv)
if not rv:
return
return rv[-1] | [
"def",
"call",
"(",
"conf",
",",
"context",
",",
"topic",
",",
"msg",
",",
"timeout",
",",
"connection_pool",
")",
":",
"rv",
"=",
"multicall",
"(",
"conf",
",",
"context",
",",
"topic",
",",
"msg",
",",
"timeout",
",",
"connection_pool",
")",
"# NOTE(... | https://github.com/JiYou/openstack/blob/8607dd488bde0905044b303eb6e52bdea6806923/chap19/monitor/monitor/monitor/openstack/common/rpc/amqp.py#L609-L616 | |
Azure/azure-devops-cli-extension | 11334cd55806bef0b99c3bee5a438eed71e44037 | azure-devops/azext_devops/devops_sdk/v6_0/work_item_tracking/work_item_tracking_client.py | python | WorkItemTrackingClient.get_comment_reactions | (self, project, work_item_id, comment_id) | return self._deserialize('[CommentReaction]', self._unwrap_collection(response)) | GetCommentReactions.
[Preview API] Gets reactions of a comment.
:param str project: Project ID or project name
:param int work_item_id: WorkItem ID
:param int comment_id: Comment ID
:rtype: [CommentReaction] | GetCommentReactions.
[Preview API] Gets reactions of a comment.
:param str project: Project ID or project name
:param int work_item_id: WorkItem ID
:param int comment_id: Comment ID
:rtype: [CommentReaction] | [
"GetCommentReactions",
".",
"[",
"Preview",
"API",
"]",
"Gets",
"reactions",
"of",
"a",
"comment",
".",
":",
"param",
"str",
"project",
":",
"Project",
"ID",
"or",
"project",
"name",
":",
"param",
"int",
"work_item_id",
":",
"WorkItem",
"ID",
":",
"param",... | def get_comment_reactions(self, project, work_item_id, comment_id):
"""GetCommentReactions.
[Preview API] Gets reactions of a comment.
:param str project: Project ID or project name
:param int work_item_id: WorkItem ID
:param int comment_id: Comment ID
:rtype: [CommentReaction]
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if work_item_id is not None:
route_values['workItemId'] = self._serialize.url('work_item_id', work_item_id, 'int')
if comment_id is not None:
route_values['commentId'] = self._serialize.url('comment_id', comment_id, 'int')
response = self._send(http_method='GET',
location_id='f6cb3f27-1028-4851-af96-887e570dc21f',
version='6.0-preview.1',
route_values=route_values)
return self._deserialize('[CommentReaction]', self._unwrap_collection(response)) | [
"def",
"get_comment_reactions",
"(",
"self",
",",
"project",
",",
"work_item_id",
",",
"comment_id",
")",
":",
"route_values",
"=",
"{",
"}",
"if",
"project",
"is",
"not",
"None",
":",
"route_values",
"[",
"'project'",
"]",
"=",
"self",
".",
"_serialize",
... | https://github.com/Azure/azure-devops-cli-extension/blob/11334cd55806bef0b99c3bee5a438eed71e44037/azure-devops/azext_devops/devops_sdk/v6_0/work_item_tracking/work_item_tracking_client.py#L545-L564 | |
naftaliharris/tauthon | 5587ceec329b75f7caf6d65a036db61ac1bae214 | Lib/ftplib.py | python | FTP.sendeprt | (self, host, port) | return self.voidcmd(cmd) | Send an EPRT command with the current host and the given port number. | Send an EPRT command with the current host and the given port number. | [
"Send",
"an",
"EPRT",
"command",
"with",
"the",
"current",
"host",
"and",
"the",
"given",
"port",
"number",
"."
] | def sendeprt(self, host, port):
'''Send an EPRT command with the current host and the given port number.'''
af = 0
if self.af == socket.AF_INET:
af = 1
if self.af == socket.AF_INET6:
af = 2
if af == 0:
raise error_proto, 'unsupported address family'
fields = ['', repr(af), host, repr(port), '']
cmd = 'EPRT ' + '|'.join(fields)
return self.voidcmd(cmd) | [
"def",
"sendeprt",
"(",
"self",
",",
"host",
",",
"port",
")",
":",
"af",
"=",
"0",
"if",
"self",
".",
"af",
"==",
"socket",
".",
"AF_INET",
":",
"af",
"=",
"1",
"if",
"self",
".",
"af",
"==",
"socket",
".",
"AF_INET6",
":",
"af",
"=",
"2",
"... | https://github.com/naftaliharris/tauthon/blob/5587ceec329b75f7caf6d65a036db61ac1bae214/Lib/ftplib.py#L270-L281 | |
fonttools/fonttools | 892322aaff6a89bea5927379ec06bc0da3dfb7df | Lib/fontTools/ufoLib/utils.py | python | _VersionTupleEnumMixin.default | (cls) | return max(cls.__members__.values()) | [] | def default(cls):
# get the latest defined version (i.e. the max of all versions)
return max(cls.__members__.values()) | [
"def",
"default",
"(",
"cls",
")",
":",
"# get the latest defined version (i.e. the max of all versions)",
"return",
"max",
"(",
"cls",
".",
"__members__",
".",
"values",
"(",
")",
")"
] | https://github.com/fonttools/fonttools/blob/892322aaff6a89bea5927379ec06bc0da3dfb7df/Lib/fontTools/ufoLib/utils.py#L63-L65 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.