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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
skyfielders/python-skyfield | 0e68757a5c1081f784c58fd7a76635c6deb98451 | skyfield/nutationlib.py | python | equation_of_the_equinoxes_complimentary_terms | (jd_tt) | return c_terms | Compute the complementary terms of the equation of the equinoxes.
`jd_tt` - Terrestrial Time: Julian date float, or NumPy array of floats | Compute the complementary terms of the equation of the equinoxes. | [
"Compute",
"the",
"complementary",
"terms",
"of",
"the",
"equation",
"of",
"the",
"equinoxes",
"."
] | def equation_of_the_equinoxes_complimentary_terms(jd_tt):
"""Compute the complementary terms of the equation of the equinoxes.
`jd_tt` - Terrestrial Time: Julian date float, or NumPy array of floats
"""
# Interval between fundamental epoch J2000.0 and current date.
t = (jd_tt - T0) / 36525.0
# Build array for intermediate results.
shape = getattr(jd_tt, 'shape', ())
fa = zeros((14,) if shape == () else (14, shape[0]))
# Mean Anomaly of the Moon.
fa[0] = ((485868.249036 +
(715923.2178 +
( 31.8792 +
( 0.051635 +
( -0.00024470)
* t) * t) * t) * t) * ASEC2RAD
+ (1325.0*t % 1.0) * tau)
# Mean Anomaly of the Sun.
fa[1] = ((1287104.793048 +
(1292581.0481 +
( -0.5532 +
( +0.000136 +
( -0.00001149)
* t) * t) * t) * t) * ASEC2RAD
+ (99.0*t % 1.0) * tau)
# Mean Longitude of the Moon minus Mean Longitude of the Ascending
# Node of the Moon.
fa[2] = (( 335779.526232 +
( 295262.8478 +
( -12.7512 +
( -0.001037 +
( 0.00000417)
* t) * t) * t) * t) * ASEC2RAD
+ (1342.0*t % 1.0) * tau)
# Mean Elongation of the Moon from the Sun.
fa[3] = ((1072260.703692 +
(1105601.2090 +
( -6.3706 +
( 0.006593 +
( -0.00003169)
* t) * t) * t) * t) * ASEC2RAD
+ (1236.0*t % 1.0) * tau)
# Mean Longitude of the Ascending Node of the Moon.
fa[4] = (( 450160.398036 +
(-482890.5431 +
( 7.4722 +
( 0.007702 +
( -0.00005939)
* t) * t) * t) * t) * ASEC2RAD
+ (-5.0*t % 1.0) * tau)
fa[ 5] = (4.402608842 + 2608.7903141574 * t)
fa[ 6] = (3.176146697 + 1021.3285546211 * t)
fa[ 7] = (1.753470314 + 628.3075849991 * t)
fa[ 8] = (6.203480913 + 334.0612426700 * t)
fa[ 9] = (0.599546497 + 52.9690962641 * t)
fa[10] = (0.874016757 + 21.3299104960 * t)
fa[11] = (5.481293872 + 7.4781598567 * t)
fa[12] = (5.311886287 + 3.8133035638 * t)
fa[13] = (0.024381750 + 0.00000538691 * t) * t
fa %= tau
# Evaluate the complementary terms.
a = ke1.dot(fa)
c_terms = se1_0 * sin(a)
c_terms += se1_1 * cos(a)
c_terms *= t
a = ke0_t.dot(fa)
c_terms += se0_t_0.dot(sin(a))
c_terms += se0_t_1.dot(cos(a))
c_terms *= ASEC2RAD
return c_terms | [
"def",
"equation_of_the_equinoxes_complimentary_terms",
"(",
"jd_tt",
")",
":",
"# Interval between fundamental epoch J2000.0 and current date.",
"t",
"=",
"(",
"jd_tt",
"-",
"T0",
")",
"/",
"36525.0",
"# Build array for intermediate results.",
"shape",
"=",
"getattr",
"(",
... | https://github.com/skyfielders/python-skyfield/blob/0e68757a5c1081f784c58fd7a76635c6deb98451/skyfield/nutationlib.py#L93-L183 | |
rgs1/zk_shell | ab4223c8f165a32b7f652932329b0880e43b9922 | zk_shell/shell.py | python | Shell.do_set_acls | (self, params) | \x1b[1mNAME\x1b[0m
set_acls - Sets ACLs for a given path
\x1b[1mSYNOPSIS\x1b[0m
set_acls <path> <acls> [recursive]
\x1b[1mOPTIONS\x1b[0m
* recursive: recursively set the acls on the children
\x1b[1mEXAMPLES\x1b[0m
> set_acls /some/path 'world:anyone:r digest:user:aRxISyaKnTP2+OZ9OmQLkq04bvo=:cdrwa'
> set_acls /some/path 'world:anyone:r username_password:user:p@ass0rd:cdrwa'
> set_acls /path 'world:anyone:r' true | \x1b[1mNAME\x1b[0m
set_acls - Sets ACLs for a given path | [
"\\",
"x1b",
"[",
"1mNAME",
"\\",
"x1b",
"[",
"0m",
"set_acls",
"-",
"Sets",
"ACLs",
"for",
"a",
"given",
"path"
] | def do_set_acls(self, params):
"""
\x1b[1mNAME\x1b[0m
set_acls - Sets ACLs for a given path
\x1b[1mSYNOPSIS\x1b[0m
set_acls <path> <acls> [recursive]
\x1b[1mOPTIONS\x1b[0m
* recursive: recursively set the acls on the children
\x1b[1mEXAMPLES\x1b[0m
> set_acls /some/path 'world:anyone:r digest:user:aRxISyaKnTP2+OZ9OmQLkq04bvo=:cdrwa'
> set_acls /some/path 'world:anyone:r username_password:user:p@ass0rd:cdrwa'
> set_acls /path 'world:anyone:r' true
"""
try:
acls = ACLReader.extract(shlex.split(params.acls))
except ACLReader.BadACL as ex:
self.show_output("Failed to set ACLs: %s.", ex)
return
def set_acls(path):
try:
self._zk.set_acls(path, acls)
except (NoNodeError, BadVersionError, InvalidACLError, ZookeeperError) as ex:
self.show_output("Failed to set ACLs: %s. Error: %s", str(acls), str(ex))
if params.recursive:
for cpath, _ in self._zk.tree(params.path, 0, full_path=True):
set_acls(cpath)
set_acls(params.path) | [
"def",
"do_set_acls",
"(",
"self",
",",
"params",
")",
":",
"try",
":",
"acls",
"=",
"ACLReader",
".",
"extract",
"(",
"shlex",
".",
"split",
"(",
"params",
".",
"acls",
")",
")",
"except",
"ACLReader",
".",
"BadACL",
"as",
"ex",
":",
"self",
".",
... | https://github.com/rgs1/zk_shell/blob/ab4223c8f165a32b7f652932329b0880e43b9922/zk_shell/shell.py#L328-L361 | ||
mit-han-lab/once-for-all | 4f6fce3652ee4553ea811d38f32f90ac8b1bc378 | ofa/imagenet_classification/elastic_nn/modules/dynamic_layers.py | python | DynamicMBConvLayer.in_channels | (self) | return max(self.in_channel_list) | [] | def in_channels(self):
return max(self.in_channel_list) | [
"def",
"in_channels",
"(",
"self",
")",
":",
"return",
"max",
"(",
"self",
".",
"in_channel_list",
")"
] | https://github.com/mit-han-lab/once-for-all/blob/4f6fce3652ee4553ea811d38f32f90ac8b1bc378/ofa/imagenet_classification/elastic_nn/modules/dynamic_layers.py#L194-L195 | |||
gecko984/supervenn | 3a29b931a986ab1a80eed940f766b31c117a530d | supervenn/_algorithms.py | python | break_into_chunks | (sets) | return dict(chunks_dict) | Let us have a collection {S_1, ..., S_n} of finite sets and U be the union of all these sets.
For a given subset C = {i_1, ..., i_k} of indices {1, ..., n}, define the 'chunk', corresponding to C, as the set
of elements of U, that belong to S_i_1, ..., S_i_k, but not to any of the other sets.
For example, for a collection of two sets {S_1, S_2}, there can be max three chunks: S_1 - S_2, S_2 - S_1, S1 & S_2.
For three sets, there can be max 7 chunks (imagine a generic three-way Venn diagram and count how many different
area colors it can have).
In general, the number of possible non-empty chunks for a collection of n sets is equal to min(|U|, 2^n - 1).
Any chunk either lies completely inside any or completely outside any of the sets S_1, ... S_n.
This function takes a list of sets as its only argument and returns a dict with frozensets of indices as keys and
chunks as values.
:param sets: list of sets
:return: chunks_dict - dict with frozensets as keys and sets as values. | Let us have a collection {S_1, ..., S_n} of finite sets and U be the union of all these sets.
For a given subset C = {i_1, ..., i_k} of indices {1, ..., n}, define the 'chunk', corresponding to C, as the set
of elements of U, that belong to S_i_1, ..., S_i_k, but not to any of the other sets.
For example, for a collection of two sets {S_1, S_2}, there can be max three chunks: S_1 - S_2, S_2 - S_1, S1 & S_2.
For three sets, there can be max 7 chunks (imagine a generic three-way Venn diagram and count how many different
area colors it can have).
In general, the number of possible non-empty chunks for a collection of n sets is equal to min(|U|, 2^n - 1).
Any chunk either lies completely inside any or completely outside any of the sets S_1, ... S_n. | [
"Let",
"us",
"have",
"a",
"collection",
"{",
"S_1",
"...",
"S_n",
"}",
"of",
"finite",
"sets",
"and",
"U",
"be",
"the",
"union",
"of",
"all",
"these",
"sets",
".",
"For",
"a",
"given",
"subset",
"C",
"=",
"{",
"i_1",
"...",
"i_k",
"}",
"of",
"ind... | def break_into_chunks(sets):
"""
Let us have a collection {S_1, ..., S_n} of finite sets and U be the union of all these sets.
For a given subset C = {i_1, ..., i_k} of indices {1, ..., n}, define the 'chunk', corresponding to C, as the set
of elements of U, that belong to S_i_1, ..., S_i_k, but not to any of the other sets.
For example, for a collection of two sets {S_1, S_2}, there can be max three chunks: S_1 - S_2, S_2 - S_1, S1 & S_2.
For three sets, there can be max 7 chunks (imagine a generic three-way Venn diagram and count how many different
area colors it can have).
In general, the number of possible non-empty chunks for a collection of n sets is equal to min(|U|, 2^n - 1).
Any chunk either lies completely inside any or completely outside any of the sets S_1, ... S_n.
This function takes a list of sets as its only argument and returns a dict with frozensets of indices as keys and
chunks as values.
:param sets: list of sets
:return: chunks_dict - dict with frozensets as keys and sets as values.
"""
if not sets:
raise ValueError('Sets list is empty.')
all_items = set.union(*sets)
if not all_items:
raise ValueError('All sets are empty')
# Each chunk is characterized by its occurrence pattern, which is a unique subset of indices of our sets.
# E.g. chunk with signature {1, 2, 5} is exactly the set of items such that they belong to sets 1, 2, 5, and
# don't belong to any of the other sets.
# Build a dict with signatures as keys (as frozensets), and lists of items as values,
chunks_dict = defaultdict(set)
for item in all_items:
occurrence_pattern = frozenset({i for i, set_ in enumerate(sets) if item in set_})
chunks_dict[occurrence_pattern].add(item)
return dict(chunks_dict) | [
"def",
"break_into_chunks",
"(",
"sets",
")",
":",
"if",
"not",
"sets",
":",
"raise",
"ValueError",
"(",
"'Sets list is empty.'",
")",
"all_items",
"=",
"set",
".",
"union",
"(",
"*",
"sets",
")",
"if",
"not",
"all_items",
":",
"raise",
"ValueError",
"(",
... | https://github.com/gecko984/supervenn/blob/3a29b931a986ab1a80eed940f766b31c117a530d/supervenn/_algorithms.py#L162-L194 | |
araffin/robotics-rl-srl | eae7c1ab310c79662f6e68c0d255e08641037ffa | real_robots/omnirobot_utils/marker_finder.py | python | MakerFinder.setMarkerCode | (self, marker_id, marker_code, real_length) | TODO
:param marker_id:
:param marker_code:
:param real_length: (int)
:return: | TODO
:param marker_id:
:param marker_code:
:param real_length: (int)
:return: | [
"TODO",
":",
"param",
"marker_id",
":",
":",
"param",
"marker_code",
":",
":",
"param",
"real_length",
":",
"(",
"int",
")",
":",
"return",
":"
] | def setMarkerCode(self, marker_id, marker_code, real_length):
"""
TODO
:param marker_id:
:param marker_code:
:param real_length: (int)
:return:
"""
self.marker_code[marker_id] = np.zeros((4, marker_code.shape[0], marker_code.shape[1]))
self.marker_code[marker_id][0, :, :] = marker_code
for i in range(1, 4):
self.marker_code[marker_id][i, :, :] = rotateMatrix90(self.marker_code[marker_id][i-1, :, :])
self.marker_rows, self.marker_cols = 90, 90
self.marker_square_pts = np.float32([[0, 0], [0, self.marker_cols], [self.marker_rows, self.marker_cols],
[self.marker_rows, 0]]).reshape(-1, 1, 2)
self.marker_real_corners = np.float32([[0, 0, 0], [0, real_length, 0], [real_length, real_length, 0],
[real_length, 0, 0]]) \
- np.float32([real_length/2.0, real_length/2.0, 0])
self.marker_real_corners = self.marker_real_corners.reshape(-1, 1, 3) | [
"def",
"setMarkerCode",
"(",
"self",
",",
"marker_id",
",",
"marker_code",
",",
"real_length",
")",
":",
"self",
".",
"marker_code",
"[",
"marker_id",
"]",
"=",
"np",
".",
"zeros",
"(",
"(",
"4",
",",
"marker_code",
".",
"shape",
"[",
"0",
"]",
",",
... | https://github.com/araffin/robotics-rl-srl/blob/eae7c1ab310c79662f6e68c0d255e08641037ffa/real_robots/omnirobot_utils/marker_finder.py#L52-L71 | ||
openhatch/oh-mainline | ce29352a034e1223141dcc2f317030bbc3359a51 | vendor/packages/whoosh/src/whoosh/sorting.py | python | Facets.add_query | (self, name, querydict, **kwargs) | return self | Adds a :class:`QueryFacet` under the given ``name``.
:param name: a name for the facet.
:param querydict: a dictionary mapping keys to
:class:`whoosh.query.Query` objects. | Adds a :class:`QueryFacet` under the given ``name``.
:param name: a name for the facet.
:param querydict: a dictionary mapping keys to
:class:`whoosh.query.Query` objects. | [
"Adds",
"a",
":",
"class",
":",
"QueryFacet",
"under",
"the",
"given",
"name",
".",
":",
"param",
"name",
":",
"a",
"name",
"for",
"the",
"facet",
".",
":",
"param",
"querydict",
":",
"a",
"dictionary",
"mapping",
"keys",
"to",
":",
"class",
":",
"wh... | def add_query(self, name, querydict, **kwargs):
"""Adds a :class:`QueryFacet` under the given ``name``.
:param name: a name for the facet.
:param querydict: a dictionary mapping keys to
:class:`whoosh.query.Query` objects.
"""
self.facets[name] = QueryFacet(querydict, **kwargs)
return self | [
"def",
"add_query",
"(",
"self",
",",
"name",
",",
"querydict",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"facets",
"[",
"name",
"]",
"=",
"QueryFacet",
"(",
"querydict",
",",
"*",
"*",
"kwargs",
")",
"return",
"self"
] | https://github.com/openhatch/oh-mainline/blob/ce29352a034e1223141dcc2f317030bbc3359a51/vendor/packages/whoosh/src/whoosh/sorting.py#L781-L790 | |
openai/jukebox | 08efbbc1d4ed1a3cef96e08a931944c8b4d63bb3 | tensorboardX/tensorboardX/caffe2_graph.py | python | _filter_ops | (ops, filter_fn, perform_filter) | return new_ops | Filter unwanted operators based on criteria in 'filter_fn'.
Args:
ops: List of Caffe2 operators to filter
filter_fn: Criteria function for whether inputs/outputs in an operator
should be filtered.
perform_filter: Boolean passed from _operators_to_graph_def specifying
whether to filter operators
Returns:
new_ops: Subset of ops containing a subset of their inputs and outputs. | Filter unwanted operators based on criteria in 'filter_fn'. | [
"Filter",
"unwanted",
"operators",
"based",
"on",
"criteria",
"in",
"filter_fn",
"."
] | def _filter_ops(ops, filter_fn, perform_filter):
'''
Filter unwanted operators based on criteria in 'filter_fn'.
Args:
ops: List of Caffe2 operators to filter
filter_fn: Criteria function for whether inputs/outputs in an operator
should be filtered.
perform_filter: Boolean passed from _operators_to_graph_def specifying
whether to filter operators
Returns:
new_ops: Subset of ops containing a subset of their inputs and outputs.
'''
if not perform_filter:
return ops
new_ops = []
for op in ops:
inputs = list(op.input)
outputs = list(op.output)
del op.input[:]
del op.output[:]
new_inputs = [i for i in inputs if filter_fn(i)]
new_outputs = [o for o in outputs if filter_fn(o)]
# Only add the op if output is not empty
if new_outputs:
op.input.extend(new_inputs)
op.output.extend(new_outputs)
new_ops.append(op)
return new_ops | [
"def",
"_filter_ops",
"(",
"ops",
",",
"filter_fn",
",",
"perform_filter",
")",
":",
"if",
"not",
"perform_filter",
":",
"return",
"ops",
"new_ops",
"=",
"[",
"]",
"for",
"op",
"in",
"ops",
":",
"inputs",
"=",
"list",
"(",
"op",
".",
"input",
")",
"o... | https://github.com/openai/jukebox/blob/08efbbc1d4ed1a3cef96e08a931944c8b4d63bb3/tensorboardX/tensorboardX/caffe2_graph.py#L593-L625 | |
IronLanguages/main | a949455434b1fda8c783289e897e78a9a0caabb5 | External.LCA_RESTRICTED/Languages/CPython/27/Lib/wsgiref/util.py | python | guess_scheme | (environ) | Return a guess for whether 'wsgi.url_scheme' should be 'http' or 'https' | Return a guess for whether 'wsgi.url_scheme' should be 'http' or 'https' | [
"Return",
"a",
"guess",
"for",
"whether",
"wsgi",
".",
"url_scheme",
"should",
"be",
"http",
"or",
"https"
] | def guess_scheme(environ):
"""Return a guess for whether 'wsgi.url_scheme' should be 'http' or 'https'
"""
if environ.get("HTTPS") in ('yes','on','1'):
return 'https'
else:
return 'http' | [
"def",
"guess_scheme",
"(",
"environ",
")",
":",
"if",
"environ",
".",
"get",
"(",
"\"HTTPS\"",
")",
"in",
"(",
"'yes'",
",",
"'on'",
",",
"'1'",
")",
":",
"return",
"'https'",
"else",
":",
"return",
"'http'"
] | https://github.com/IronLanguages/main/blob/a949455434b1fda8c783289e897e78a9a0caabb5/External.LCA_RESTRICTED/Languages/CPython/27/Lib/wsgiref/util.py#L35-L41 | ||
corenel/pytorch-adda | 96f2689dd418ef275fcd0b057e5dff89be5762c5 | utils.py | python | init_weights | (layer) | Init weights for layers w.r.t. the original paper. | Init weights for layers w.r.t. the original paper. | [
"Init",
"weights",
"for",
"layers",
"w",
".",
"r",
".",
"t",
".",
"the",
"original",
"paper",
"."
] | def init_weights(layer):
"""Init weights for layers w.r.t. the original paper."""
layer_name = layer.__class__.__name__
if layer_name.find("Conv") != -1:
layer.weight.data.normal_(0.0, 0.02)
elif layer_name.find("BatchNorm") != -1:
layer.weight.data.normal_(1.0, 0.02)
layer.bias.data.fill_(0) | [
"def",
"init_weights",
"(",
"layer",
")",
":",
"layer_name",
"=",
"layer",
".",
"__class__",
".",
"__name__",
"if",
"layer_name",
".",
"find",
"(",
"\"Conv\"",
")",
"!=",
"-",
"1",
":",
"layer",
".",
"weight",
".",
"data",
".",
"normal_",
"(",
"0.0",
... | https://github.com/corenel/pytorch-adda/blob/96f2689dd418ef275fcd0b057e5dff89be5762c5/utils.py#L34-L41 | ||
rizar/attention-lvcsr | 1ae52cafdd8419874846f9544a299eef9c758f3b | libs/Theano/theano/tensor/nnet/blocksparse.py | python | SparseBlockGemv.make_node | (self, o, W, h, inputIdx, outputIdx) | return Apply(self, [o, W, h, inputIdx, outputIdx], [o.type()]) | Compute the dot product of the specified pieces of vectors
and matrices.
The parameter types are actually their expected shapes
relative to each other.
Parameters
----------
o : batch, oWin, oSize
output vector
W : iBlocks, oBlocks, iSize, oSize
weight matrix
h : batch, iWin, iSize
input from lower layer (sparse)
inputIdx : batch, iWin
indexes of the input blocks
outputIdx : batch, oWin
indexes of the output blocks
Returns
-------
(batch, oWin, oSize)
dot(W[i, j], h[i]) + o[j]
Notes
-----
- `batch` is the number of examples in a minibatch (batch size).
- `iBlocks` is the total number of blocks in the input (from lower
layer).
- `iSize` is the size of each of these input blocks.
- `iWin` is the number of blocks that will be used as inputs. Which
blocks will be used is specified in `inputIdx`.
- `oBlocks` is the number or possible output blocks.
- `oSize` is the size of each of these output blocks.
- `oWin` is the number of output blocks that will actually be computed.
Which blocks will be computed is specified in `outputIdx`. | Compute the dot product of the specified pieces of vectors
and matrices. | [
"Compute",
"the",
"dot",
"product",
"of",
"the",
"specified",
"pieces",
"of",
"vectors",
"and",
"matrices",
"."
] | def make_node(self, o, W, h, inputIdx, outputIdx):
"""
Compute the dot product of the specified pieces of vectors
and matrices.
The parameter types are actually their expected shapes
relative to each other.
Parameters
----------
o : batch, oWin, oSize
output vector
W : iBlocks, oBlocks, iSize, oSize
weight matrix
h : batch, iWin, iSize
input from lower layer (sparse)
inputIdx : batch, iWin
indexes of the input blocks
outputIdx : batch, oWin
indexes of the output blocks
Returns
-------
(batch, oWin, oSize)
dot(W[i, j], h[i]) + o[j]
Notes
-----
- `batch` is the number of examples in a minibatch (batch size).
- `iBlocks` is the total number of blocks in the input (from lower
layer).
- `iSize` is the size of each of these input blocks.
- `iWin` is the number of blocks that will be used as inputs. Which
blocks will be used is specified in `inputIdx`.
- `oBlocks` is the number or possible output blocks.
- `oSize` is the size of each of these output blocks.
- `oWin` is the number of output blocks that will actually be computed.
Which blocks will be computed is specified in `outputIdx`.
"""
o = theano.tensor.as_tensor_variable(o)
W = theano.tensor.as_tensor_variable(W)
h = theano.tensor.as_tensor_variable(h)
inputIdx = theano.tensor.as_tensor_variable(inputIdx)
outputIdx = theano.tensor.as_tensor_variable(outputIdx)
if o.ndim != 3:
raise TypeError('The output o must be a 2D tensor')
if W.ndim != 4:
raise TypeError('The weight matrix W must be a 4D tensor')
if h.ndim != 3:
raise TypeError('The input h must be a 3D tensor')
if inputIdx.ndim != 2:
raise TypeError('The input indices inputIdx must be a 2D tensor')
if outputIdx.ndim != 2:
raise TypeError('The output indices outputIdx must be a 2D tensor')
assert inputIdx.type.dtype in discrete_dtypes
assert outputIdx.type.dtype in discrete_dtypes
return Apply(self, [o, W, h, inputIdx, outputIdx], [o.type()]) | [
"def",
"make_node",
"(",
"self",
",",
"o",
",",
"W",
",",
"h",
",",
"inputIdx",
",",
"outputIdx",
")",
":",
"o",
"=",
"theano",
".",
"tensor",
".",
"as_tensor_variable",
"(",
"o",
")",
"W",
"=",
"theano",
".",
"tensor",
".",
"as_tensor_variable",
"("... | https://github.com/rizar/attention-lvcsr/blob/1ae52cafdd8419874846f9544a299eef9c758f3b/libs/Theano/theano/tensor/nnet/blocksparse.py#L34-L94 | |
burness/tensorflow-101 | c775a54af86542940e6e69b7d90d8d7e8aa9aeb9 | serving/predict_pb2.py | python | PredictionServiceStub.__init__ | (self, channel) | Constructor.
Args:
channel: A grpc.Channel. | Constructor. | [
"Constructor",
"."
] | def __init__(self, channel):
"""Constructor.
Args:
channel: A grpc.Channel.
"""
self.Predict = channel.unary_unary(
'/tensorflow.serving.PredictionService/Predict',
request_serializer=PredictRequest.SerializeToString,
response_deserializer=PredictResponse.FromString,
) | [
"def",
"__init__",
"(",
"self",
",",
"channel",
")",
":",
"self",
".",
"Predict",
"=",
"channel",
".",
"unary_unary",
"(",
"'/tensorflow.serving.PredictionService/Predict'",
",",
"request_serializer",
"=",
"PredictRequest",
".",
"SerializeToString",
",",
"response_des... | https://github.com/burness/tensorflow-101/blob/c775a54af86542940e6e69b7d90d8d7e8aa9aeb9/serving/predict_pb2.py#L221-L231 | ||
pymedusa/Medusa | 1405fbb6eb8ef4d20fcca24c32ddca52b11f0f38 | ext/jsonrpclib/jsonrpc.py | python | Fault.__init__ | (
self,
code=-32000,
message="Server error",
rpcid=None,
config=jsonrpclib.config.DEFAULT,
data=None,
) | Sets up the error description
:param code: Fault code
:param message: Associated message
:param rpcid: Request ID
:param config: A JSONRPClib Config instance
:param data: Extra information added to an error description | Sets up the error description | [
"Sets",
"up",
"the",
"error",
"description"
] | def __init__(
self,
code=-32000,
message="Server error",
rpcid=None,
config=jsonrpclib.config.DEFAULT,
data=None,
):
"""
Sets up the error description
:param code: Fault code
:param message: Associated message
:param rpcid: Request ID
:param config: A JSONRPClib Config instance
:param data: Extra information added to an error description
"""
self.faultCode = code
self.faultString = message
self.rpcid = rpcid
self.config = config
self.data = data | [
"def",
"__init__",
"(",
"self",
",",
"code",
"=",
"-",
"32000",
",",
"message",
"=",
"\"Server error\"",
",",
"rpcid",
"=",
"None",
",",
"config",
"=",
"jsonrpclib",
".",
"config",
".",
"DEFAULT",
",",
"data",
"=",
"None",
",",
")",
":",
"self",
".",... | https://github.com/pymedusa/Medusa/blob/1405fbb6eb8ef4d20fcca24c32ddca52b11f0f38/ext/jsonrpclib/jsonrpc.py#L1068-L1089 | ||
hthuwal/sign-language-gesture-recognition | 23419bb6193a601f2165063d9bc8b51f7a48004a | retrain.py | python | run_bottleneck_on_image | (sess, image_data, image_data_tensor,
decoded_image_tensor, resized_input_tensor,
bottleneck_tensor) | return bottleneck_values | Runs inference on an image to extract the 'bottleneck' summary layer.
Args:
sess: Current active TensorFlow Session.
image_data: String of raw JPEG data.
image_data_tensor: Input data layer in the graph.
decoded_image_tensor: Output of initial image resizing and preprocessing.
resized_input_tensor: The input node of the recognition graph.
bottleneck_tensor: Layer before the final softmax.
Returns:
Numpy array of bottleneck values. | Runs inference on an image to extract the 'bottleneck' summary layer. | [
"Runs",
"inference",
"on",
"an",
"image",
"to",
"extract",
"the",
"bottleneck",
"summary",
"layer",
"."
] | def run_bottleneck_on_image(sess, image_data, image_data_tensor,
decoded_image_tensor, resized_input_tensor,
bottleneck_tensor):
"""Runs inference on an image to extract the 'bottleneck' summary layer.
Args:
sess: Current active TensorFlow Session.
image_data: String of raw JPEG data.
image_data_tensor: Input data layer in the graph.
decoded_image_tensor: Output of initial image resizing and preprocessing.
resized_input_tensor: The input node of the recognition graph.
bottleneck_tensor: Layer before the final softmax.
Returns:
Numpy array of bottleneck values.
"""
# First decode the JPEG image, resize it, and rescale the pixel values.
resized_input_values = sess.run(decoded_image_tensor,
{image_data_tensor: image_data})
# Then run it through the recognition network.
bottleneck_values = sess.run(bottleneck_tensor,
{resized_input_tensor: resized_input_values})
bottleneck_values = np.squeeze(bottleneck_values)
return bottleneck_values | [
"def",
"run_bottleneck_on_image",
"(",
"sess",
",",
"image_data",
",",
"image_data_tensor",
",",
"decoded_image_tensor",
",",
"resized_input_tensor",
",",
"bottleneck_tensor",
")",
":",
"# First decode the JPEG image, resize it, and rescale the pixel values.",
"resized_input_values... | https://github.com/hthuwal/sign-language-gesture-recognition/blob/23419bb6193a601f2165063d9bc8b51f7a48004a/retrain.py#L314-L337 | |
reahl/reahl | 86aac47c3a9b5b98e9f77dad4939034a02d54d46 | reahl-component/reahl/component/modelinterface.py | python | ValidationConstraint.value | (self) | return self.field.user_input | The current value which failed validation. | The current value which failed validation. | [
"The",
"current",
"value",
"which",
"failed",
"validation",
"."
] | def value(self):
"""The current value which failed validation."""
return self.field.user_input | [
"def",
"value",
"(",
"self",
")",
":",
"return",
"self",
".",
"field",
".",
"user_input"
] | https://github.com/reahl/reahl/blob/86aac47c3a9b5b98e9f77dad4939034a02d54d46/reahl-component/reahl/component/modelinterface.py#L348-L350 | |
BMW-InnovationLab/BMW-TensorFlow-Training-GUI | 4f10d1f00f9ac312ca833e5b28fd0f8952cfee17 | training_api/research/slim/nets/lenet.py | python | lenet | (images, num_classes=10, is_training=False,
dropout_keep_prob=0.5,
prediction_fn=slim.softmax,
scope='LeNet') | return logits, end_points | Creates a variant of the LeNet model.
Note that since the output is a set of 'logits', the values fall in the
interval of (-infinity, infinity). Consequently, to convert the outputs to a
probability distribution over the characters, one will need to convert them
using the softmax function:
logits = lenet.lenet(images, is_training=False)
probabilities = tf.nn.softmax(logits)
predictions = tf.argmax(logits, 1)
Args:
images: A batch of `Tensors` of size [batch_size, height, width, channels].
num_classes: the number of classes in the dataset. If 0 or None, the logits
layer is omitted and the input features to the logits layer are returned
instead.
is_training: specifies whether or not we're currently training the model.
This variable will determine the behaviour of the dropout layer.
dropout_keep_prob: the percentage of activation values that are retained.
prediction_fn: a function to get predictions out of logits.
scope: Optional variable_scope.
Returns:
net: a 2D Tensor with the logits (pre-softmax activations) if num_classes
is a non-zero integer, or the inon-dropped-out nput to the logits layer
if num_classes is 0 or None.
end_points: a dictionary from components of the network to the corresponding
activation. | Creates a variant of the LeNet model. | [
"Creates",
"a",
"variant",
"of",
"the",
"LeNet",
"model",
"."
] | def lenet(images, num_classes=10, is_training=False,
dropout_keep_prob=0.5,
prediction_fn=slim.softmax,
scope='LeNet'):
"""Creates a variant of the LeNet model.
Note that since the output is a set of 'logits', the values fall in the
interval of (-infinity, infinity). Consequently, to convert the outputs to a
probability distribution over the characters, one will need to convert them
using the softmax function:
logits = lenet.lenet(images, is_training=False)
probabilities = tf.nn.softmax(logits)
predictions = tf.argmax(logits, 1)
Args:
images: A batch of `Tensors` of size [batch_size, height, width, channels].
num_classes: the number of classes in the dataset. If 0 or None, the logits
layer is omitted and the input features to the logits layer are returned
instead.
is_training: specifies whether or not we're currently training the model.
This variable will determine the behaviour of the dropout layer.
dropout_keep_prob: the percentage of activation values that are retained.
prediction_fn: a function to get predictions out of logits.
scope: Optional variable_scope.
Returns:
net: a 2D Tensor with the logits (pre-softmax activations) if num_classes
is a non-zero integer, or the inon-dropped-out nput to the logits layer
if num_classes is 0 or None.
end_points: a dictionary from components of the network to the corresponding
activation.
"""
end_points = {}
with tf.variable_scope(scope, 'LeNet', [images]):
net = end_points['conv1'] = slim.conv2d(images, 32, [5, 5], scope='conv1')
net = end_points['pool1'] = slim.max_pool2d(net, [2, 2], 2, scope='pool1')
net = end_points['conv2'] = slim.conv2d(net, 64, [5, 5], scope='conv2')
net = end_points['pool2'] = slim.max_pool2d(net, [2, 2], 2, scope='pool2')
net = slim.flatten(net)
end_points['Flatten'] = net
net = end_points['fc3'] = slim.fully_connected(net, 1024, scope='fc3')
if not num_classes:
return net, end_points
net = end_points['dropout3'] = slim.dropout(
net, dropout_keep_prob, is_training=is_training, scope='dropout3')
logits = end_points['Logits'] = slim.fully_connected(
net, num_classes, activation_fn=None, scope='fc4')
end_points['Predictions'] = prediction_fn(logits, scope='Predictions')
return logits, end_points | [
"def",
"lenet",
"(",
"images",
",",
"num_classes",
"=",
"10",
",",
"is_training",
"=",
"False",
",",
"dropout_keep_prob",
"=",
"0.5",
",",
"prediction_fn",
"=",
"slim",
".",
"softmax",
",",
"scope",
"=",
"'LeNet'",
")",
":",
"end_points",
"=",
"{",
"}",
... | https://github.com/BMW-InnovationLab/BMW-TensorFlow-Training-GUI/blob/4f10d1f00f9ac312ca833e5b28fd0f8952cfee17/training_api/research/slim/nets/lenet.py#L26-L79 | |
angr/angr | 4b04d56ace135018083d36d9083805be8146688b | angr/state_plugins/sim_action.py | python | SimActionExit._copy_objects | (self, c) | [] | def _copy_objects(self, c):
c.exit_type = self.exit_type
c.target = self._copy_object(self.target)
c.condition = self._copy_object(self.condition) | [
"def",
"_copy_objects",
"(",
"self",
",",
"c",
")",
":",
"c",
".",
"exit_type",
"=",
"self",
".",
"exit_type",
"c",
".",
"target",
"=",
"self",
".",
"_copy_object",
"(",
"self",
".",
"target",
")",
"c",
".",
"condition",
"=",
"self",
".",
"_copy_obje... | https://github.com/angr/angr/blob/4b04d56ace135018083d36d9083805be8146688b/angr/state_plugins/sim_action.py#L131-L134 | ||||
jameskermode/f90wrap | 6a6021d3d8c01125e13ecd0ef8faa52f19e5be3e | f90wrap/fortran.py | python | iter_fields | (node) | Yield a tuple of ``(fieldname, value)`` for each field in ``node._fields``
that is present on *node*. | Yield a tuple of ``(fieldname, value)`` for each field in ``node._fields``
that is present on *node*. | [
"Yield",
"a",
"tuple",
"of",
"(",
"fieldname",
"value",
")",
"for",
"each",
"field",
"in",
"node",
".",
"_fields",
"that",
"is",
"present",
"on",
"*",
"node",
"*",
"."
] | def iter_fields(node):
"""
Yield a tuple of ``(fieldname, value)`` for each field in ``node._fields``
that is present on *node*.
"""
for field in node._fields:
try:
yield (field, getattr(node, field))
except AttributeError:
pass | [
"def",
"iter_fields",
"(",
"node",
")",
":",
"for",
"field",
"in",
"node",
".",
"_fields",
":",
"try",
":",
"yield",
"(",
"field",
",",
"getattr",
"(",
"node",
",",
"field",
")",
")",
"except",
"AttributeError",
":",
"pass"
] | https://github.com/jameskermode/f90wrap/blob/6a6021d3d8c01125e13ecd0ef8faa52f19e5be3e/f90wrap/fortran.py#L388-L397 | ||
pantsbuild/pex | 473c6ac732ed4bc338b4b20a9ec930d1d722c9b4 | pex/vendor/_vendored/pip/pip/_vendor/ipaddress.py | python | IPv6Address.is_global | (self) | return not self.is_private | Test if this address is allocated for public networks.
Returns:
A boolean, true if the address is not reserved per
iana-ipv6-special-registry. | Test if this address is allocated for public networks. | [
"Test",
"if",
"this",
"address",
"is",
"allocated",
"for",
"public",
"networks",
"."
] | def is_global(self):
"""Test if this address is allocated for public networks.
Returns:
A boolean, true if the address is not reserved per
iana-ipv6-special-registry.
"""
return not self.is_private | [
"def",
"is_global",
"(",
"self",
")",
":",
"return",
"not",
"self",
".",
"is_private"
] | https://github.com/pantsbuild/pex/blob/473c6ac732ed4bc338b4b20a9ec930d1d722c9b4/pex/vendor/_vendored/pip/pip/_vendor/ipaddress.py#L2103-L2111 | |
postgres/pgadmin4 | 374c5e952fa594d749fadf1f88076c1cba8c5f64 | web/pgadmin/tools/grant_wizard/__init__.py | python | GrantWizardModule.get_exposed_url_endpoints | (self) | return [
'grant_wizard.acl', 'grant_wizard.objects', 'grant_wizard.apply',
'grant_wizard.modified_sql'
] | Returns:
list: URL endpoints for grant-wizard module | Returns:
list: URL endpoints for grant-wizard module | [
"Returns",
":",
"list",
":",
"URL",
"endpoints",
"for",
"grant",
"-",
"wizard",
"module"
] | def get_exposed_url_endpoints(self):
"""
Returns:
list: URL endpoints for grant-wizard module
"""
return [
'grant_wizard.acl', 'grant_wizard.objects', 'grant_wizard.apply',
'grant_wizard.modified_sql'
] | [
"def",
"get_exposed_url_endpoints",
"(",
"self",
")",
":",
"return",
"[",
"'grant_wizard.acl'",
",",
"'grant_wizard.objects'",
",",
"'grant_wizard.apply'",
",",
"'grant_wizard.modified_sql'",
"]"
] | https://github.com/postgres/pgadmin4/blob/374c5e952fa594d749fadf1f88076c1cba8c5f64/web/pgadmin/tools/grant_wizard/__init__.py#L88-L96 | |
moraes/tipfy | 20cc0dab85f5433e399ae2d948d2b32dad051d66 | tipfy/appengine/acl.py | python | AclRules.set_cache | (cls, cache_key, spec) | Sets a memcache value.
:param cache_key:
The Cache key.
:param spec:
Value to be saved. | Sets a memcache value. | [
"Sets",
"a",
"memcache",
"value",
"."
] | def set_cache(cls, cache_key, spec):
"""Sets a memcache value.
:param cache_key:
The Cache key.
:param spec:
Value to be saved.
"""
_rules_map[cache_key] = spec
memcache.set(cache_key, spec, namespace=cls.__name__) | [
"def",
"set_cache",
"(",
"cls",
",",
"cache_key",
",",
"spec",
")",
":",
"_rules_map",
"[",
"cache_key",
"]",
"=",
"spec",
"memcache",
".",
"set",
"(",
"cache_key",
",",
"spec",
",",
"namespace",
"=",
"cls",
".",
"__name__",
")"
] | https://github.com/moraes/tipfy/blob/20cc0dab85f5433e399ae2d948d2b32dad051d66/tipfy/appengine/acl.py#L224-L233 | ||
exaile/exaile | a7b58996c5c15b3aa7b9975ac13ee8f784ef4689 | xlgui/icons.py | python | IconManager.pixbuf_from_icon_name | (
self, icon_name: str, size: Union[int, Gtk.IconSize] = Gtk.IconSize.BUTTON
) | return None | Generates a pixbuf from an icon name
:param icon_name: an icon name
:param size: the size of the icon, will be
tried to converted to a GTK icon size
:returns: the generated pixbuf | Generates a pixbuf from an icon name | [
"Generates",
"a",
"pixbuf",
"from",
"an",
"icon",
"name"
] | def pixbuf_from_icon_name(
self, icon_name: str, size: Union[int, Gtk.IconSize] = Gtk.IconSize.BUTTON
) -> Optional[GdkPixbuf.Pixbuf]:
"""
Generates a pixbuf from an icon name
:param icon_name: an icon name
:param size: the size of the icon, will be
tried to converted to a GTK icon size
:returns: the generated pixbuf
"""
if isinstance(size, Gtk.IconSize):
icon_size = Gtk.icon_size_lookup(size)
size = icon_size[1]
if icon_name.endswith('-symbolic'):
fallback_name = icon_name[:-9]
else:
fallback_name = icon_name + '-symbolic'
icon_info = self.icon_theme.choose_icon(
[icon_name, fallback_name],
size,
Gtk.IconLookupFlags.USE_BUILTIN | Gtk.IconLookupFlags.FORCE_SIZE,
)
if icon_info:
try:
return icon_info.load_icon()
except GLib.GError as e:
logger.warning('Failed to load icon "%s": %s', icon_name, e.message)
else:
logger.warning('Icon "%s" not found', icon_name)
return None | [
"def",
"pixbuf_from_icon_name",
"(",
"self",
",",
"icon_name",
":",
"str",
",",
"size",
":",
"Union",
"[",
"int",
",",
"Gtk",
".",
"IconSize",
"]",
"=",
"Gtk",
".",
"IconSize",
".",
"BUTTON",
")",
"->",
"Optional",
"[",
"GdkPixbuf",
".",
"Pixbuf",
"]",... | https://github.com/exaile/exaile/blob/a7b58996c5c15b3aa7b9975ac13ee8f784ef4689/xlgui/icons.py#L625-L659 | |
home-assistant/core | 265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1 | homeassistant/components/input_datetime/__init__.py | python | InputDatetime.capability_attributes | (self) | return {
CONF_HAS_DATE: self.has_date,
CONF_HAS_TIME: self.has_time,
} | Return the capability attributes. | Return the capability attributes. | [
"Return",
"the",
"capability",
"attributes",
"."
] | def capability_attributes(self) -> dict:
"""Return the capability attributes."""
return {
CONF_HAS_DATE: self.has_date,
CONF_HAS_TIME: self.has_time,
} | [
"def",
"capability_attributes",
"(",
"self",
")",
"->",
"dict",
":",
"return",
"{",
"CONF_HAS_DATE",
":",
"self",
".",
"has_date",
",",
"CONF_HAS_TIME",
":",
"self",
".",
"has_time",
",",
"}"
] | https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/input_datetime/__init__.py#L339-L344 | |
SymbiFlow/symbiflow-arch-defs | f38793112ff78a06de9f1e3269bd22543e29729f | ice40/utils/ice40_import_routing_from_icebox.py | python | group_hlc_name | (group) | return list(hlcnames.keys())[0] | Get the HLC "global name" from a group local names. | Get the HLC "global name" from a group local names. | [
"Get",
"the",
"HLC",
"global",
"name",
"from",
"a",
"group",
"local",
"names",
"."
] | def group_hlc_name(group):
"""Get the HLC "global name" from a group local names."""
assert_type(group, list)
global ic
hlcnames = defaultdict(int)
hlcnames_details = []
for ipos, localnames in group:
for name in localnames:
assert_type(ipos, PositionIcebox)
hlcname = icebox_asc2hlc.translate_netname(
*ipos, ic.max_x - 1, ic.max_y - 1, name
)
if hlcname != name:
hlcnames_details.append((ipos, name, hlcname))
hlcnames[hlcname] += 1
if not hlcnames:
return None
if len(hlcnames) > 1:
logging.warn("Multiple HLC names (%s) found group %s", hlcnames, group)
filtered_hlcnames = {k: v for k, v in hlcnames.items() if v > 1}
if not filtered_hlcnames:
return None
if len(filtered_hlcnames) != 1:
logging.warn(
"Skipping as conflicting names for %s (%s)", hlcnames,
hlcnames_details
)
return None
hlcnames = filtered_hlcnames
assert len(hlcnames) == 1, (hlcnames, hlcnames_details)
return list(hlcnames.keys())[0] | [
"def",
"group_hlc_name",
"(",
"group",
")",
":",
"assert_type",
"(",
"group",
",",
"list",
")",
"global",
"ic",
"hlcnames",
"=",
"defaultdict",
"(",
"int",
")",
"hlcnames_details",
"=",
"[",
"]",
"for",
"ipos",
",",
"localnames",
"in",
"group",
":",
"for... | https://github.com/SymbiFlow/symbiflow-arch-defs/blob/f38793112ff78a06de9f1e3269bd22543e29729f/ice40/utils/ice40_import_routing_from_icebox.py#L223-L257 | |
danielgtaylor/python-betterproto | 6dd7baa26cd9930b0013d0f6f0b7eaf84541deed | src/betterproto/casing.py | python | camel_case | (value: str, strict: bool = True) | return lowercase_first(pascal_case(value, strict=strict)) | Capitalize all words except first and remove symbols.
Parameters
-----------
value: :class:`str`
The value to convert.
strict: :class:`bool`
Whether or not to output only alphanumeric characters.
Returns
--------
:class:`str`
The value in camelCase. | Capitalize all words except first and remove symbols. | [
"Capitalize",
"all",
"words",
"except",
"first",
"and",
"remove",
"symbols",
"."
] | def camel_case(value: str, strict: bool = True) -> str:
"""
Capitalize all words except first and remove symbols.
Parameters
-----------
value: :class:`str`
The value to convert.
strict: :class:`bool`
Whether or not to output only alphanumeric characters.
Returns
--------
:class:`str`
The value in camelCase.
"""
return lowercase_first(pascal_case(value, strict=strict)) | [
"def",
"camel_case",
"(",
"value",
":",
"str",
",",
"strict",
":",
"bool",
"=",
"True",
")",
"->",
"str",
":",
"return",
"lowercase_first",
"(",
"pascal_case",
"(",
"value",
",",
"strict",
"=",
"strict",
")",
")"
] | https://github.com/danielgtaylor/python-betterproto/blob/6dd7baa26cd9930b0013d0f6f0b7eaf84541deed/src/betterproto/casing.py#L100-L116 | |
Chaffelson/nipyapi | d3b186fd701ce308c2812746d98af9120955e810 | nipyapi/nifi/models/label_dto.py | python | LabelDTO.position | (self) | return self._position | Gets the position of this LabelDTO.
The position of this component in the UI if applicable.
:return: The position of this LabelDTO.
:rtype: PositionDTO | Gets the position of this LabelDTO.
The position of this component in the UI if applicable. | [
"Gets",
"the",
"position",
"of",
"this",
"LabelDTO",
".",
"The",
"position",
"of",
"this",
"component",
"in",
"the",
"UI",
"if",
"applicable",
"."
] | def position(self):
"""
Gets the position of this LabelDTO.
The position of this component in the UI if applicable.
:return: The position of this LabelDTO.
:rtype: PositionDTO
"""
return self._position | [
"def",
"position",
"(",
"self",
")",
":",
"return",
"self",
".",
"_position"
] | https://github.com/Chaffelson/nipyapi/blob/d3b186fd701ce308c2812746d98af9120955e810/nipyapi/nifi/models/label_dto.py#L156-L164 | |
microsoft/MPNet | 081523a788c1556f28dd90cbc629810f48b083fb | pretraining/fairseq/tasks/fairseq_task.py | python | FairseqTask.train_step | (self, sample, model, criterion, optimizer, ignore_grad=False) | return loss, sample_size, logging_output | Do forward and backward, and return the loss as computed by *criterion*
for the given *model* and *sample*.
Args:
sample (dict): the mini-batch. The format is defined by the
:class:`~fairseq.data.FairseqDataset`.
model (~fairseq.models.BaseFairseqModel): the model
criterion (~fairseq.criterions.FairseqCriterion): the criterion
optimizer (~fairseq.optim.FairseqOptimizer): the optimizer
ignore_grad (bool): multiply loss by 0 if this is set to True
Returns:
tuple:
- the loss
- the sample size, which is used as the denominator for the
gradient
- logging outputs to display while training | Do forward and backward, and return the loss as computed by *criterion*
for the given *model* and *sample*. | [
"Do",
"forward",
"and",
"backward",
"and",
"return",
"the",
"loss",
"as",
"computed",
"by",
"*",
"criterion",
"*",
"for",
"the",
"given",
"*",
"model",
"*",
"and",
"*",
"sample",
"*",
"."
] | def train_step(self, sample, model, criterion, optimizer, ignore_grad=False):
"""
Do forward and backward, and return the loss as computed by *criterion*
for the given *model* and *sample*.
Args:
sample (dict): the mini-batch. The format is defined by the
:class:`~fairseq.data.FairseqDataset`.
model (~fairseq.models.BaseFairseqModel): the model
criterion (~fairseq.criterions.FairseqCriterion): the criterion
optimizer (~fairseq.optim.FairseqOptimizer): the optimizer
ignore_grad (bool): multiply loss by 0 if this is set to True
Returns:
tuple:
- the loss
- the sample size, which is used as the denominator for the
gradient
- logging outputs to display while training
"""
model.train()
loss, sample_size, logging_output = criterion(model, sample)
if ignore_grad:
loss *= 0
optimizer.backward(loss)
return loss, sample_size, logging_output | [
"def",
"train_step",
"(",
"self",
",",
"sample",
",",
"model",
",",
"criterion",
",",
"optimizer",
",",
"ignore_grad",
"=",
"False",
")",
":",
"model",
".",
"train",
"(",
")",
"loss",
",",
"sample_size",
",",
"logging_output",
"=",
"criterion",
"(",
"mod... | https://github.com/microsoft/MPNet/blob/081523a788c1556f28dd90cbc629810f48b083fb/pretraining/fairseq/tasks/fairseq_task.py#L221-L246 | |
selfteaching/selfteaching-python-camp | 9982ee964b984595e7d664b07c389cddaf158f1e | 19100205/Ceasar1978/pip-19.0.3/src/pip/_vendor/requests/models.py | python | Response.text | (self) | return content | Content of the response, in unicode.
If Response.encoding is None, encoding will be guessed using
``chardet``.
The encoding of the response content is determined based solely on HTTP
headers, following RFC 2616 to the letter. If you can take advantage of
non-HTTP knowledge to make a better guess at the encoding, you should
set ``r.encoding`` appropriately before accessing this property. | Content of the response, in unicode. | [
"Content",
"of",
"the",
"response",
"in",
"unicode",
"."
] | def text(self):
"""Content of the response, in unicode.
If Response.encoding is None, encoding will be guessed using
``chardet``.
The encoding of the response content is determined based solely on HTTP
headers, following RFC 2616 to the letter. If you can take advantage of
non-HTTP knowledge to make a better guess at the encoding, you should
set ``r.encoding`` appropriately before accessing this property.
"""
# Try charset from content-type
content = None
encoding = self.encoding
if not self.content:
return str('')
# Fallback to auto-detected encoding.
if self.encoding is None:
encoding = self.apparent_encoding
# Decode unicode from given encoding.
try:
content = str(self.content, encoding, errors='replace')
except (LookupError, TypeError):
# A LookupError is raised if the encoding was not found which could
# indicate a misspelling or similar mistake.
#
# A TypeError can be raised if encoding is None
#
# So we try blindly encoding.
content = str(self.content, errors='replace')
return content | [
"def",
"text",
"(",
"self",
")",
":",
"# Try charset from content-type",
"content",
"=",
"None",
"encoding",
"=",
"self",
".",
"encoding",
"if",
"not",
"self",
".",
"content",
":",
"return",
"str",
"(",
"''",
")",
"# Fallback to auto-detected encoding.",
"if",
... | https://github.com/selfteaching/selfteaching-python-camp/blob/9982ee964b984595e7d664b07c389cddaf158f1e/19100205/Ceasar1978/pip-19.0.3/src/pip/_vendor/requests/models.py#L836-L871 | |
pymedusa/Medusa | 1405fbb6eb8ef4d20fcca24c32ddca52b11f0f38 | ext/boto/sqs/queue.py | python | Queue.get_timeout | (self) | return int(a['VisibilityTimeout']) | Get the visibility timeout for the queue.
:rtype: int
:return: The number of seconds as an integer. | Get the visibility timeout for the queue. | [
"Get",
"the",
"visibility",
"timeout",
"for",
"the",
"queue",
"."
] | def get_timeout(self):
"""
Get the visibility timeout for the queue.
:rtype: int
:return: The number of seconds as an integer.
"""
a = self.get_attributes('VisibilityTimeout')
return int(a['VisibilityTimeout']) | [
"def",
"get_timeout",
"(",
"self",
")",
":",
"a",
"=",
"self",
".",
"get_attributes",
"(",
"'VisibilityTimeout'",
")",
"return",
"int",
"(",
"a",
"[",
"'VisibilityTimeout'",
"]",
")"
] | https://github.com/pymedusa/Medusa/blob/1405fbb6eb8ef4d20fcca24c32ddca52b11f0f38/ext/boto/sqs/queue.py#L171-L179 | |
tp4a/teleport | 1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad | server/www/packages/packages-windows/x86/cryptography/x509/extensions.py | python | Extension.__hash__ | (self) | return hash((self.oid, self.critical, self.value)) | [] | def __hash__(self):
return hash((self.oid, self.critical, self.value)) | [
"def",
"__hash__",
"(",
"self",
")",
":",
"return",
"hash",
"(",
"(",
"self",
".",
"oid",
",",
"self",
".",
"critical",
",",
"self",
".",
"value",
")",
")"
] | https://github.com/tp4a/teleport/blob/1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad/server/www/packages/packages-windows/x86/cryptography/x509/extensions.py#L1197-L1198 | |||
mpatacchiola/dissecting-reinforcement-learning | 38660b0a0d5aed077a46acb4bcb2013565304d9c | src/6/inverted-pendulum/inverted_pendulum.py | python | InvertedPendulum.__init__ | (self, pole_mass=2.0, cart_mass=8.0, pole_lenght=0.5, delta_t=0.1) | Create a new pendulum object.
It is possible to pass the parameter of the simulation.
@param pole_mass: the mass of the pole (default 2.0 Kg)
@param cart_mass: the mass of the cart (default 8.0 Kg)
@param pole_lenght: the lenght of the pole (default 0.5 m)
@param delta_t: the time step in seconds (default 0.1 s) | Create a new pendulum object.
It is possible to pass the parameter of the simulation. | [
"Create",
"a",
"new",
"pendulum",
"object",
".",
"It",
"is",
"possible",
"to",
"pass",
"the",
"parameter",
"of",
"the",
"simulation",
"."
] | def __init__(self, pole_mass=2.0, cart_mass=8.0, pole_lenght=0.5, delta_t=0.1):
""" Create a new pendulum object.
It is possible to pass the parameter of the simulation.
@param pole_mass: the mass of the pole (default 2.0 Kg)
@param cart_mass: the mass of the cart (default 8.0 Kg)
@param pole_lenght: the lenght of the pole (default 0.5 m)
@param delta_t: the time step in seconds (default 0.1 s)
"""
self.angle_list = list()
self.gravity = 9.8
self.delta_t = delta_t
self.pole_mass = pole_mass
self.cart_mass = cart_mass
self.pole_lenght = pole_lenght
self.angle_t = np.random.normal(0, 0.05) # radians (vertical position)
self.angular_velocity_t = 0.0
self.alpha = 1.0 / (self.pole_mass + self.cart_mass) | [
"def",
"__init__",
"(",
"self",
",",
"pole_mass",
"=",
"2.0",
",",
"cart_mass",
"=",
"8.0",
",",
"pole_lenght",
"=",
"0.5",
",",
"delta_t",
"=",
"0.1",
")",
":",
"self",
".",
"angle_list",
"=",
"list",
"(",
")",
"self",
".",
"gravity",
"=",
"9.8",
... | https://github.com/mpatacchiola/dissecting-reinforcement-learning/blob/38660b0a0d5aed077a46acb4bcb2013565304d9c/src/6/inverted-pendulum/inverted_pendulum.py#L34-L51 | ||
demisto/content | 5c664a65b992ac8ca90ac3f11b1b2cdf11ee9b07 | Packs/SafeNet_Trusted_Access/Integrations/SafeNetTrustedAccess/SafeNetTrustedAccess.py | python | get_application_list_sta_command | (client: Client, args: Dict[str, Any]) | return CommandResults(
readable_output=tableToMarkdown("List of applications in the tenant :", response, headers=header_sequence,
headerTransform=pascalToSpace, removeNull=True),
outputs_prefix='STA.APPLICATION',
outputs_key_field=['id'],
outputs=response
) | Function for sta-get-application-list command. Get list of all the applications in the tenant. | Function for sta-get-application-list command. Get list of all the applications in the tenant. | [
"Function",
"for",
"sta",
"-",
"get",
"-",
"application",
"-",
"list",
"command",
".",
"Get",
"list",
"of",
"all",
"the",
"applications",
"in",
"the",
"tenant",
"."
] | def get_application_list_sta_command(client: Client, args: Dict[str, Any]) -> CommandResults:
""" Function for sta-get-application-list command. Get list of all the applications in the tenant. """
response = client.get_application_list_sta(limit=args.get('limit'))
if not response:
return CommandResults(
readable_output=NO_RESULT_MSG,
)
header_sequence = ["id", "name", "status"]
return CommandResults(
readable_output=tableToMarkdown("List of applications in the tenant :", response, headers=header_sequence,
headerTransform=pascalToSpace, removeNull=True),
outputs_prefix='STA.APPLICATION',
outputs_key_field=['id'],
outputs=response
) | [
"def",
"get_application_list_sta_command",
"(",
"client",
":",
"Client",
",",
"args",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
")",
"->",
"CommandResults",
":",
"response",
"=",
"client",
".",
"get_application_list_sta",
"(",
"limit",
"=",
"args",
".",
"get... | https://github.com/demisto/content/blob/5c664a65b992ac8ca90ac3f11b1b2cdf11ee9b07/Packs/SafeNet_Trusted_Access/Integrations/SafeNetTrustedAccess/SafeNetTrustedAccess.py#L1063-L1078 | |
hatRiot/zarp | 2e772350a01c2aeed3f4da9685cd0cc5d6b3ecad | src/lib/scapy/layers/tftp.py | python | TFTP_RRQ.answers | (self, other) | return 0 | [] | def answers(self, other):
return 0 | [
"def",
"answers",
"(",
"self",
",",
"other",
")",
":",
"return",
"0"
] | https://github.com/hatRiot/zarp/blob/2e772350a01c2aeed3f4da9685cd0cc5d6b3ecad/src/lib/scapy/layers/tftp.py#L27-L28 | |||
WikidPad/WikidPad | 558109638807bc76b4672922686e416ab2d5f79c | WikidPad/lib/pwiki/DocPages.py | python | DocPage.setEditorText | (self, text, dirty=True) | Just set editor text. Derived class overwrites this to set flags | Just set editor text. Derived class overwrites this to set flags | [
"Just",
"set",
"editor",
"text",
".",
"Derived",
"class",
"overwrites",
"this",
"to",
"set",
"flags"
] | def setEditorText(self, text, dirty=True):
"""
Just set editor text. Derived class overwrites this to set flags
"""
with self.textOperationLock:
self.editorText = text
self.livePageAst = None | [
"def",
"setEditorText",
"(",
"self",
",",
"text",
",",
"dirty",
"=",
"True",
")",
":",
"with",
"self",
".",
"textOperationLock",
":",
"self",
".",
"editorText",
"=",
"text",
"self",
".",
"livePageAst",
"=",
"None"
] | https://github.com/WikidPad/WikidPad/blob/558109638807bc76b4672922686e416ab2d5f79c/WikidPad/lib/pwiki/DocPages.py#L82-L88 | ||
openshift/openshift-tools | 1188778e728a6e4781acf728123e5b356380fe6f | openshift/installer/vendored/openshift-ansible-3.11.28-1/roles/lib_vendored_deps/library/oc_group.py | python | OpenShiftCLIConfig.stringify | (self, ascommalist='') | return rval | return the options hash as cli params in a string
if ascommalist is set to the name of a key, and
the value of that key is a dict, format the dict
as a list of comma delimited key=value pairs | return the options hash as cli params in a string
if ascommalist is set to the name of a key, and
the value of that key is a dict, format the dict
as a list of comma delimited key=value pairs | [
"return",
"the",
"options",
"hash",
"as",
"cli",
"params",
"in",
"a",
"string",
"if",
"ascommalist",
"is",
"set",
"to",
"the",
"name",
"of",
"a",
"key",
"and",
"the",
"value",
"of",
"that",
"key",
"is",
"a",
"dict",
"format",
"the",
"dict",
"as",
"a"... | def stringify(self, ascommalist=''):
''' return the options hash as cli params in a string
if ascommalist is set to the name of a key, and
the value of that key is a dict, format the dict
as a list of comma delimited key=value pairs '''
rval = []
for key in sorted(self.config_options.keys()):
data = self.config_options[key]
if data['include'] \
and (data['value'] is not None or isinstance(data['value'], int)):
if key == ascommalist:
val = ','.join(['{}={}'.format(kk, vv) for kk, vv in sorted(data['value'].items())])
else:
val = data['value']
rval.append('--{}={}'.format(key.replace('_', '-'), val))
return rval | [
"def",
"stringify",
"(",
"self",
",",
"ascommalist",
"=",
"''",
")",
":",
"rval",
"=",
"[",
"]",
"for",
"key",
"in",
"sorted",
"(",
"self",
".",
"config_options",
".",
"keys",
"(",
")",
")",
":",
"data",
"=",
"self",
".",
"config_options",
"[",
"ke... | https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.11.28-1/roles/lib_vendored_deps/library/oc_group.py#L1426-L1442 | |
cloudera/impyla | 0c736af4cad2bade9b8e313badc08ec50e81c948 | impala/_thrift_gen/hive_metastore/ThriftHiveMetastore.py | python | revoke_role_result.__eq__ | (self, other) | return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ | [] | def __eq__(self, other):
return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ | [
"def",
"__eq__",
"(",
"self",
",",
"other",
")",
":",
"return",
"isinstance",
"(",
"other",
",",
"self",
".",
"__class__",
")",
"and",
"self",
".",
"__dict__",
"==",
"other",
".",
"__dict__"
] | https://github.com/cloudera/impyla/blob/0c736af4cad2bade9b8e313badc08ec50e81c948/impala/_thrift_gen/hive_metastore/ThriftHiveMetastore.py#L29007-L29008 | |||
jgagneastro/coffeegrindsize | 22661ebd21831dba4cf32bfc6ba59fe3d49f879c | App/dist/coffeegrindsize.app/Contents/Resources/lib/python3.7/scipy/sparse/compressed.py | python | _cs_matrix._major_index_fancy | (self, idx) | return self.__class__((res_data, res_indices, res_indptr),
shape=new_shape, copy=False) | Index along the major axis where idx is an array of ints. | Index along the major axis where idx is an array of ints. | [
"Index",
"along",
"the",
"major",
"axis",
"where",
"idx",
"is",
"an",
"array",
"of",
"ints",
"."
] | def _major_index_fancy(self, idx):
"""Index along the major axis where idx is an array of ints.
"""
idx_dtype = self.indices.dtype
indices = np.asarray(idx, dtype=idx_dtype).ravel()
_, N = self._swap(self.shape)
M = len(indices)
new_shape = self._swap((M, N))
if M == 0:
return self.__class__(new_shape)
row_nnz = np.diff(self.indptr)
idx_dtype = self.indices.dtype
res_indptr = np.zeros(M+1, dtype=idx_dtype)
np.cumsum(row_nnz[idx], out=res_indptr[1:])
nnz = res_indptr[-1]
res_indices = np.empty(nnz, dtype=idx_dtype)
res_data = np.empty(nnz, dtype=self.dtype)
csr_row_index(M, indices, self.indptr, self.indices, self.data,
res_indices, res_data)
return self.__class__((res_data, res_indices, res_indptr),
shape=new_shape, copy=False) | [
"def",
"_major_index_fancy",
"(",
"self",
",",
"idx",
")",
":",
"idx_dtype",
"=",
"self",
".",
"indices",
".",
"dtype",
"indices",
"=",
"np",
".",
"asarray",
"(",
"idx",
",",
"dtype",
"=",
"idx_dtype",
")",
".",
"ravel",
"(",
")",
"_",
",",
"N",
"=... | https://github.com/jgagneastro/coffeegrindsize/blob/22661ebd21831dba4cf32bfc6ba59fe3d49f879c/App/dist/coffeegrindsize.app/Contents/Resources/lib/python3.7/scipy/sparse/compressed.py#L675-L699 | |
JustinhoCHN/SRGAN_Wasserstein | 08cb76028880f95cbeea1353c5bfc5b2b356ae83 | tensorlayer/files.py | python | load_wmt_en_fr_dataset | (path='data/wmt_en_fr/') | return train_path, dev_path | It will download English-to-French translation data from the WMT'15
Website (10^9-French-English corpus), and the 2013 news test from
the same site as development set.
Returns the directories of training data and test data.
Parameters
----------
path : string
Path to download data to, defaults to data/wmt_en_fr/
References
----------
- Code modified from /tensorflow/models/rnn/translation/data_utils.py
Notes
-----
Usually, it will take a long time to download this dataset. | It will download English-to-French translation data from the WMT'15
Website (10^9-French-English corpus), and the 2013 news test from
the same site as development set.
Returns the directories of training data and test data. | [
"It",
"will",
"download",
"English",
"-",
"to",
"-",
"French",
"translation",
"data",
"from",
"the",
"WMT",
"15",
"Website",
"(",
"10^9",
"-",
"French",
"-",
"English",
"corpus",
")",
"and",
"the",
"2013",
"news",
"test",
"from",
"the",
"same",
"site",
... | def load_wmt_en_fr_dataset(path='data/wmt_en_fr/'):
"""It will download English-to-French translation data from the WMT'15
Website (10^9-French-English corpus), and the 2013 news test from
the same site as development set.
Returns the directories of training data and test data.
Parameters
----------
path : string
Path to download data to, defaults to data/wmt_en_fr/
References
----------
- Code modified from /tensorflow/models/rnn/translation/data_utils.py
Notes
-----
Usually, it will take a long time to download this dataset.
"""
# URLs for WMT data.
_WMT_ENFR_TRAIN_URL = "http://www.statmt.org/wmt10/"
_WMT_ENFR_DEV_URL = "http://www.statmt.org/wmt15/"
def gunzip_file(gz_path, new_path):
"""Unzips from gz_path into new_path."""
print("Unpacking %s to %s" % (gz_path, new_path))
with gzip.open(gz_path, "rb") as gz_file:
with open(new_path, "wb") as new_file:
for line in gz_file:
new_file.write(line)
def get_wmt_enfr_train_set(path):
"""Download the WMT en-fr training corpus to directory unless it's there."""
filename = "training-giga-fren.tar"
maybe_download_and_extract(filename, path, _WMT_ENFR_TRAIN_URL, extract=True)
train_path = os.path.join(path, "giga-fren.release2.fixed")
gunzip_file(train_path + ".fr.gz", train_path + ".fr")
gunzip_file(train_path + ".en.gz", train_path + ".en")
return train_path
def get_wmt_enfr_dev_set(path):
"""Download the WMT en-fr training corpus to directory unless it's there."""
filename = "dev-v2.tgz"
dev_file = maybe_download_and_extract(filename, path, _WMT_ENFR_DEV_URL, extract=False)
dev_name = "newstest2013"
dev_path = os.path.join(path, "newstest2013")
if not (gfile.Exists(dev_path + ".fr") and gfile.Exists(dev_path + ".en")):
print("Extracting tgz file %s" % dev_file)
with tarfile.open(dev_file, "r:gz") as dev_tar:
fr_dev_file = dev_tar.getmember("dev/" + dev_name + ".fr")
en_dev_file = dev_tar.getmember("dev/" + dev_name + ".en")
fr_dev_file.name = dev_name + ".fr" # Extract without "dev/" prefix.
en_dev_file.name = dev_name + ".en"
dev_tar.extract(fr_dev_file, path)
dev_tar.extract(en_dev_file, path)
return dev_path
print("Load or Download WMT English-to-French translation > {}".format(path))
train_path = get_wmt_enfr_train_set(path)
dev_path = get_wmt_enfr_dev_set(path)
return train_path, dev_path | [
"def",
"load_wmt_en_fr_dataset",
"(",
"path",
"=",
"'data/wmt_en_fr/'",
")",
":",
"# URLs for WMT data.",
"_WMT_ENFR_TRAIN_URL",
"=",
"\"http://www.statmt.org/wmt10/\"",
"_WMT_ENFR_DEV_URL",
"=",
"\"http://www.statmt.org/wmt15/\"",
"def",
"gunzip_file",
"(",
"gz_path",
",",
"... | https://github.com/JustinhoCHN/SRGAN_Wasserstein/blob/08cb76028880f95cbeea1353c5bfc5b2b356ae83/tensorlayer/files.py#L444-L506 | |
Kismuz/btgym | 7fb3316e67f1d7a17c620630fb62fb29428b2cec | btgym/envs/base.py | python | BTgymEnv.close | (self) | Implementation of OpenAI Gym env.close method.
Puts BTgym server in Control Mode. | Implementation of OpenAI Gym env.close method.
Puts BTgym server in Control Mode. | [
"Implementation",
"of",
"OpenAI",
"Gym",
"env",
".",
"close",
"method",
".",
"Puts",
"BTgym",
"server",
"in",
"Control",
"Mode",
"."
] | def close(self):
"""
Implementation of OpenAI Gym env.close method.
Puts BTgym server in Control Mode.
"""
self.log.debug('close.call()')
self._stop_server()
self._stop_data_server()
self.log.info('Environment closed.') | [
"def",
"close",
"(",
"self",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'close.call()'",
")",
"self",
".",
"_stop_server",
"(",
")",
"self",
".",
"_stop_data_server",
"(",
")",
"self",
".",
"log",
".",
"info",
"(",
"'Environment closed.'",
")"
] | https://github.com/Kismuz/btgym/blob/7fb3316e67f1d7a17c620630fb62fb29428b2cec/btgym/envs/base.py#L839-L847 | ||
andreikop/enki | 3170059e5cb46dcc77d7fb1457c38a8a5f13af66 | enki/plugins/preview/__init__.py | python | Plugin._onDockShown | (self) | Dock has been shown by user. Change Enabled option | Dock has been shown by user. Change Enabled option | [
"Dock",
"has",
"been",
"shown",
"by",
"user",
".",
"Change",
"Enabled",
"option"
] | def _onDockShown(self):
"""Dock has been shown by user. Change Enabled option
"""
if not core.config()['Preview']['Enabled']:
core.config()['Preview']['Enabled'] = True
core.config().flush() | [
"def",
"_onDockShown",
"(",
"self",
")",
":",
"if",
"not",
"core",
".",
"config",
"(",
")",
"[",
"'Preview'",
"]",
"[",
"'Enabled'",
"]",
":",
"core",
".",
"config",
"(",
")",
"[",
"'Preview'",
"]",
"[",
"'Enabled'",
"]",
"=",
"True",
"core",
".",
... | https://github.com/andreikop/enki/blob/3170059e5cb46dcc77d7fb1457c38a8a5f13af66/enki/plugins/preview/__init__.py#L526-L531 | ||
saulpw/visidata | 577f34127c09116e3cbe1fcb3f67d54484785ae7 | visidata/cmdlog.py | python | delay | (vd, factor=1) | return acquired or not vd.paused | returns True if delay satisfied | returns True if delay satisfied | [
"returns",
"True",
"if",
"delay",
"satisfied"
] | def delay(vd, factor=1):
'returns True if delay satisfied'
acquired = vd.semaphore.acquire(timeout=options.replay_wait*factor if not vd.paused else None)
return acquired or not vd.paused | [
"def",
"delay",
"(",
"vd",
",",
"factor",
"=",
"1",
")",
":",
"acquired",
"=",
"vd",
".",
"semaphore",
".",
"acquire",
"(",
"timeout",
"=",
"options",
".",
"replay_wait",
"*",
"factor",
"if",
"not",
"vd",
".",
"paused",
"else",
"None",
")",
"return",... | https://github.com/saulpw/visidata/blob/577f34127c09116e3cbe1fcb3f67d54484785ae7/visidata/cmdlog.py#L282-L285 | |
pret/pokemon-reverse-engineering-tools | 5e0715f2579adcfeb683448c9a7826cfd3afa57d | pokemontools/crystal.py | python | Connection.__init__ | (self, address, direction=None, map_group=None, map_id=None, debug=True, smh=None) | [] | def __init__(self, address, direction=None, map_group=None, map_id=None, debug=True, smh=None):
self.address = address
self.direction = direction.lower()
self.map_group = map_group
self.map_id = map_id
self.debug = debug
self.smh = smh
self.last_address = address + self.size
connections.append(self)
self.parse() | [
"def",
"__init__",
"(",
"self",
",",
"address",
",",
"direction",
"=",
"None",
",",
"map_group",
"=",
"None",
",",
"map_id",
"=",
"None",
",",
"debug",
"=",
"True",
",",
"smh",
"=",
"None",
")",
":",
"self",
".",
"address",
"=",
"address",
"self",
... | https://github.com/pret/pokemon-reverse-engineering-tools/blob/5e0715f2579adcfeb683448c9a7826cfd3afa57d/pokemontools/crystal.py#L5084-L5094 | ||||
topydo/topydo | 57d7577c987515d4b49d5500f666da29080ca3c2 | topydo/lib/ListFormat.py | python | _unescape_percent_sign | (p_str) | return unescaped_str | Strips backslashes from escaped percent signs in p_str. | Strips backslashes from escaped percent signs in p_str. | [
"Strips",
"backslashes",
"from",
"escaped",
"percent",
"signs",
"in",
"p_str",
"."
] | def _unescape_percent_sign(p_str):
""" Strips backslashes from escaped percent signs in p_str. """
unescaped_str = re.sub(r'\\%', '%', p_str)
return unescaped_str | [
"def",
"_unescape_percent_sign",
"(",
"p_str",
")",
":",
"unescaped_str",
"=",
"re",
".",
"sub",
"(",
"r'\\\\%'",
",",
"'%'",
",",
"p_str",
")",
"return",
"unescaped_str"
] | https://github.com/topydo/topydo/blob/57d7577c987515d4b49d5500f666da29080ca3c2/topydo/lib/ListFormat.py#L87-L91 | |
fossasia/x-mario-center | fe67afe28d995dcf4e2498e305825a4859566172 | build/lib.linux-i686-2.7/softwarecenter/db/database.py | python | StoreDatabase.get_query_list_from_search_entry | (self, search_term,
category_query=None) | return SearchQuery([pkg_query, fuzzy_query]) | get xapian.Query from a search term string and a limit the
search to the given category | get xapian.Query from a search term string and a limit the
search to the given category | [
"get",
"xapian",
".",
"Query",
"from",
"a",
"search",
"term",
"string",
"and",
"a",
"limit",
"the",
"search",
"to",
"the",
"given",
"category"
] | def get_query_list_from_search_entry(self, search_term,
category_query=None):
""" get xapian.Query from a search term string and a limit the
search to the given category
"""
def _add_category_to_query(query):
""" helper that adds the current category to the query"""
if not category_query:
return query
return xapian.Query(xapian.Query.OP_AND,
category_query,
query)
# empty query returns a query that matches nothing (for performance
# reasons)
if search_term == "" and category_query is None:
return SearchQuery(xapian.Query())
# we cheat and return a match-all query for single letter searches
if len(search_term) < 2:
return SearchQuery(_add_category_to_query(xapian.Query("")))
# check if there is a ":" in the search, if so, it means the user
# is using a xapian prefix like "pkg:" or "mime:" and in this case
# we do not want to alter the search term (as application is in the
# greylist but a common mime-type prefix)
if not ":" in search_term:
# filter query by greylist (to avoid overly generic search terms)
orig_search_term = search_term
for item in self.SEARCH_GREYLIST_STR.split(";"):
(search_term, n) = re.subn('\\b%s\\b' % item, '', search_term)
if n:
LOG.debug("greylist changed search term: '%s'" %
search_term)
# restore query if it was just greylist words
if search_term == '':
LOG.debug("grey-list replaced all terms, restoring")
search_term = orig_search_term
# we have to strip the leading and trailing whitespaces to avoid having
# different results for e.g. 'font ' and 'font' (LP: #506419)
search_term = search_term.strip()
# get a pkg query
if "," in search_term:
pkg_query = get_query_for_pkgnames(search_term.split(","))
else:
pkg_query = xapian.Query()
for term in search_term.split():
pkg_query = xapian.Query(xapian.Query.OP_OR,
xapian.Query("XP" + term),
pkg_query)
pkg_query = _add_category_to_query(pkg_query)
# get a search query
if not ':' in search_term: # ie, not a mimetype query
# we need this to work around xapian oddness
search_term = search_term.replace('-', '_')
fuzzy_query = self.xapian_parser.parse_query(search_term,
xapian.QueryParser.FLAG_PARTIAL |
xapian.QueryParser.FLAG_BOOLEAN)
# if the query size goes out of hand, omit the FLAG_PARTIAL
# (LP: #634449)
if fuzzy_query.get_length() > 1000:
fuzzy_query = self.xapian_parser.parse_query(search_term,
xapian.QueryParser.FLAG_BOOLEAN)
# now add categories
fuzzy_query = _add_category_to_query(fuzzy_query)
return SearchQuery([pkg_query, fuzzy_query]) | [
"def",
"get_query_list_from_search_entry",
"(",
"self",
",",
"search_term",
",",
"category_query",
"=",
"None",
")",
":",
"def",
"_add_category_to_query",
"(",
"query",
")",
":",
"\"\"\" helper that adds the current category to the query\"\"\"",
"if",
"not",
"category_query... | https://github.com/fossasia/x-mario-center/blob/fe67afe28d995dcf4e2498e305825a4859566172/build/lib.linux-i686-2.7/softwarecenter/db/database.py#L290-L354 | |
psychopy/psychopy | 01b674094f38d0e0bd51c45a6f66f671d7041696 | psychopy/visual/elementarray.py | python | ElementArrayStim.setFieldPos | (self, value, operation='', log=None) | Usually you can use 'stim.attribute = value' syntax instead,
but use this method if you need to suppress the log message. | Usually you can use 'stim.attribute = value' syntax instead,
but use this method if you need to suppress the log message. | [
"Usually",
"you",
"can",
"use",
"stim",
".",
"attribute",
"=",
"value",
"syntax",
"instead",
"but",
"use",
"this",
"method",
"if",
"you",
"need",
"to",
"suppress",
"the",
"log",
"message",
"."
] | def setFieldPos(self, value, operation='', log=None):
"""Usually you can use 'stim.attribute = value' syntax instead,
but use this method if you need to suppress the log message.
"""
setAttribute(self, 'fieldPos', value, log, operation) | [
"def",
"setFieldPos",
"(",
"self",
",",
"value",
",",
"operation",
"=",
"''",
",",
"log",
"=",
"None",
")",
":",
"setAttribute",
"(",
"self",
",",
"'fieldPos'",
",",
"value",
",",
"log",
",",
"operation",
")"
] | https://github.com/psychopy/psychopy/blob/01b674094f38d0e0bd51c45a6f66f671d7041696/psychopy/visual/elementarray.py#L475-L479 | ||
elyra-ai/elyra | 5bb2009a7c475bda63f1cc2767eb8c4dfba9a239 | elyra/pipeline/pipeline_definition.py | python | PipelineDefinition.schema_version | (self) | return self._pipeline_definition.get('version') | The schema used by the Pipeline definition
:return: the version | The schema used by the Pipeline definition
:return: the version | [
"The",
"schema",
"used",
"by",
"the",
"Pipeline",
"definition",
":",
"return",
":",
"the",
"version"
] | def schema_version(self) -> str:
"""
The schema used by the Pipeline definition
:return: the version
"""
return self._pipeline_definition.get('version') | [
"def",
"schema_version",
"(",
"self",
")",
"->",
"str",
":",
"return",
"self",
".",
"_pipeline_definition",
".",
"get",
"(",
"'version'",
")"
] | https://github.com/elyra-ai/elyra/blob/5bb2009a7c475bda63f1cc2767eb8c4dfba9a239/elyra/pipeline/pipeline_definition.py#L321-L326 | |
bsmali4/xssfork | 515b45dfb0edb9263da544ad91fc1cb5f410bfd1 | thirdparty/requests/utils.py | python | requote_uri | (uri) | return quote(unquote_unreserved(uri), safe="!#$%&'()*+,/:;=?@[]~") | Re-quote the given URI.
This function passes the given URI through an unquote/quote cycle to
ensure that it is fully and consistently quoted. | Re-quote the given URI. | [
"Re",
"-",
"quote",
"the",
"given",
"URI",
"."
] | def requote_uri(uri):
"""Re-quote the given URI.
This function passes the given URI through an unquote/quote cycle to
ensure that it is fully and consistently quoted.
"""
# Unquote only the unreserved characters
# Then quote only illegal characters (do not quote reserved, unreserved,
# or '%')
return quote(unquote_unreserved(uri), safe="!#$%&'()*+,/:;=?@[]~") | [
"def",
"requote_uri",
"(",
"uri",
")",
":",
"# Unquote only the unreserved characters",
"# Then quote only illegal characters (do not quote reserved, unreserved,",
"# or '%')",
"return",
"quote",
"(",
"unquote_unreserved",
"(",
"uri",
")",
",",
"safe",
"=",
"\"!#$%&'()*+,/:;=?@... | https://github.com/bsmali4/xssfork/blob/515b45dfb0edb9263da544ad91fc1cb5f410bfd1/thirdparty/requests/utils.py#L407-L416 | |
SublimeCodeIntel/SublimeCodeIntel | 904e14f95b1a8d1d795f76d80f6a79d0edfc17ce | settings.py | python | Settings.get | (self, setting, default=None) | return self.settings.get(setting, default) | Return a plugin setting, defaulting to default if not found. | Return a plugin setting, defaulting to default if not found. | [
"Return",
"a",
"plugin",
"setting",
"defaulting",
"to",
"default",
"if",
"not",
"found",
"."
] | def get(self, setting, default=None):
"""Return a plugin setting, defaulting to default if not found."""
return self.settings.get(setting, default) | [
"def",
"get",
"(",
"self",
",",
"setting",
",",
"default",
"=",
"None",
")",
":",
"return",
"self",
".",
"settings",
".",
"get",
"(",
"setting",
",",
"default",
")"
] | https://github.com/SublimeCodeIntel/SublimeCodeIntel/blob/904e14f95b1a8d1d795f76d80f6a79d0edfc17ce/settings.py#L35-L37 | |
SCSSoftware/BlenderTools | 96f323d3bdf2d8cb8ed7f882dcdf036277a802dd | addon/io_scs_tools/internals/shaders/eut2/decalshadow/__init__.py | python | Decalshadow.init | (node_tree) | Initialize node tree with links for this shader.
:param node_tree: node tree on which this shader should be created
:type node_tree: bpy.types.NodeTree | Initialize node tree with links for this shader. | [
"Initialize",
"node",
"tree",
"with",
"links",
"for",
"this",
"shader",
"."
] | def init(node_tree):
"""Initialize node tree with links for this shader.
:param node_tree: node tree on which this shader should be created
:type node_tree: bpy.types.NodeTree
"""
# init parent
Shadowmap.init(node_tree) | [
"def",
"init",
"(",
"node_tree",
")",
":",
"# init parent",
"Shadowmap",
".",
"init",
"(",
"node_tree",
")"
] | https://github.com/SCSSoftware/BlenderTools/blob/96f323d3bdf2d8cb8ed7f882dcdf036277a802dd/addon/io_scs_tools/internals/shaders/eut2/decalshadow/__init__.py#L31-L39 | ||
yaqwsx/KiKit | 14de7f60b64e6d03ce638e78d279915d09bb9ac7 | kikit/stencil.py | python | makeTopRegister | (board, jigFrameSize, jigThickness, pcbThickness,
outerBorder=fromMm(3), innerBorder=fromMm(1),
tolerance=fromMm(0.05)) | return makeRegister(board, jigFrameSize, jigThickness, pcbThickness,
outerBorder, innerBorder, tolerance, True) | Create a SolidPython representation of the top register | Create a SolidPython representation of the top register | [
"Create",
"a",
"SolidPython",
"representation",
"of",
"the",
"top",
"register"
] | def makeTopRegister(board, jigFrameSize, jigThickness, pcbThickness,
outerBorder=fromMm(3), innerBorder=fromMm(1),
tolerance=fromMm(0.05)):
"""
Create a SolidPython representation of the top register
"""
return makeRegister(board, jigFrameSize, jigThickness, pcbThickness,
outerBorder, innerBorder, tolerance, True) | [
"def",
"makeTopRegister",
"(",
"board",
",",
"jigFrameSize",
",",
"jigThickness",
",",
"pcbThickness",
",",
"outerBorder",
"=",
"fromMm",
"(",
"3",
")",
",",
"innerBorder",
"=",
"fromMm",
"(",
"1",
")",
",",
"tolerance",
"=",
"fromMm",
"(",
"0.05",
")",
... | https://github.com/yaqwsx/KiKit/blob/14de7f60b64e6d03ce638e78d279915d09bb9ac7/kikit/stencil.py#L261-L268 | |
khanhnamle1994/natural-language-processing | 01d450d5ac002b0156ef4cf93a07cb508c1bcdc5 | assignment1/.env/lib/python2.7/site-packages/numpy/ma/core.py | python | make_mask_none | (newshape, dtype=None) | return result | Return a boolean mask of the given shape, filled with False.
This function returns a boolean ndarray with all entries False, that can
be used in common mask manipulations. If a complex dtype is specified, the
type of each field is converted to a boolean type.
Parameters
----------
newshape : tuple
A tuple indicating the shape of the mask.
dtype : {None, dtype}, optional
If None, use a MaskType instance. Otherwise, use a new datatype with
the same fields as `dtype`, converted to boolean types.
Returns
-------
result : ndarray
An ndarray of appropriate shape and dtype, filled with False.
See Also
--------
make_mask : Create a boolean mask from an array.
make_mask_descr : Construct a dtype description list from a given dtype.
Examples
--------
>>> import numpy.ma as ma
>>> ma.make_mask_none((3,))
array([False, False, False], dtype=bool)
Defining a more complex dtype.
>>> dtype = np.dtype({'names':['foo', 'bar'],
'formats':[np.float32, np.int]})
>>> dtype
dtype([('foo', '<f4'), ('bar', '<i4')])
>>> ma.make_mask_none((3,), dtype=dtype)
array([(False, False), (False, False), (False, False)],
dtype=[('foo', '|b1'), ('bar', '|b1')]) | Return a boolean mask of the given shape, filled with False. | [
"Return",
"a",
"boolean",
"mask",
"of",
"the",
"given",
"shape",
"filled",
"with",
"False",
"."
] | def make_mask_none(newshape, dtype=None):
"""
Return a boolean mask of the given shape, filled with False.
This function returns a boolean ndarray with all entries False, that can
be used in common mask manipulations. If a complex dtype is specified, the
type of each field is converted to a boolean type.
Parameters
----------
newshape : tuple
A tuple indicating the shape of the mask.
dtype : {None, dtype}, optional
If None, use a MaskType instance. Otherwise, use a new datatype with
the same fields as `dtype`, converted to boolean types.
Returns
-------
result : ndarray
An ndarray of appropriate shape and dtype, filled with False.
See Also
--------
make_mask : Create a boolean mask from an array.
make_mask_descr : Construct a dtype description list from a given dtype.
Examples
--------
>>> import numpy.ma as ma
>>> ma.make_mask_none((3,))
array([False, False, False], dtype=bool)
Defining a more complex dtype.
>>> dtype = np.dtype({'names':['foo', 'bar'],
'formats':[np.float32, np.int]})
>>> dtype
dtype([('foo', '<f4'), ('bar', '<i4')])
>>> ma.make_mask_none((3,), dtype=dtype)
array([(False, False), (False, False), (False, False)],
dtype=[('foo', '|b1'), ('bar', '|b1')])
"""
if dtype is None:
result = np.zeros(newshape, dtype=MaskType)
else:
result = np.zeros(newshape, dtype=make_mask_descr(dtype))
return result | [
"def",
"make_mask_none",
"(",
"newshape",
",",
"dtype",
"=",
"None",
")",
":",
"if",
"dtype",
"is",
"None",
":",
"result",
"=",
"np",
".",
"zeros",
"(",
"newshape",
",",
"dtype",
"=",
"MaskType",
")",
"else",
":",
"result",
"=",
"np",
".",
"zeros",
... | https://github.com/khanhnamle1994/natural-language-processing/blob/01d450d5ac002b0156ef4cf93a07cb508c1bcdc5/assignment1/.env/lib/python2.7/site-packages/numpy/ma/core.py#L1520-L1567 | |
PINTO0309/PINTO_model_zoo | 2924acda7a7d541d8712efd7cc4fd1c61ef5bddd | 082_MediaPipe_Meet_Segmentation/03_segm_lite_v681_tflite_to_pb_saved_model.py | python | make_graph | (ops, op_types, interpreter) | [] | def make_graph(ops, op_types, interpreter):
height = 96
width = 160
tensors = {}
input_details = interpreter.get_input_details()
# output_details = interpreter.get_output_details()
print(input_details)
for input_detail in input_details:
tensors[input_detail['index']] = tf.placeholder(
dtype=input_detail['dtype'],
shape=input_detail['shape'],
name=input_detail['name'])
for op in ops:
print('@@@@@@@@@@@@@@ op:', op)
op_type = op_types[op['opcode_index']]
if op_type == 'CONV_2D':
input_tensor = tensors[op['inputs'][0]]
weights = tensors[op['inputs'][1]].transpose(1,2,3,0)
bias = tensors[op['inputs'][2]]
output_detail = interpreter._get_tensor_details(op['outputs'][0])
options = op['builtin_options']
output_tensor = tf.nn.conv2d(
input_tensor,
weights,
strides=[1, options['stride_h'], options['stride_w'], 1],
padding=options['padding'],
dilations=[
1, options['dilation_h_factor'],
options['dilation_w_factor'], 1
],
name=output_detail['name'] + '/conv2d')
output_tensor = tf.add(
output_tensor, bias, name=output_detail['name'])
if output_detail['name'].split('/')[-1]=='Relu6':
output_tensor = tf.nn.relu6(output_tensor)
tensors[output_detail['index']] = output_tensor
elif op_type == 'DEPTHWISE_CONV_2D':
output_detail = interpreter._get_tensor_details(op['outputs'][0])
input_tensor = tensors[op['inputs'][0]]
weights = tensors[op['inputs'][1]].transpose(1,2,3,0)
bias = tensors[op['inputs'][2]]
options = op['builtin_options']
output_tensor = tf.nn.depthwise_conv2d(
input_tensor,
weights,
strides=[1, options['stride_h'], options['stride_w'], 1],
padding=options['padding'],
# dilations=[1, options['dilation_h_factor'], options['dilation_w_factor'], 1],
name=output_detail['name'] + '/depthwise_conv2d')
output_tensor = tf.add(output_tensor, bias, name=output_detail['name'])
tensors[output_detail['index']] = output_tensor
elif op_type == 'MAX_POOL_2D':
input_tensor = tensors[op['inputs'][0]]
output_detail = interpreter._get_tensor_details(op['outputs'][0])
options = op['builtin_options']
output_tensor = tf.nn.max_pool(
input_tensor,
ksize=[
1, options['filter_height'], options['filter_width'], 1
],
strides=[1, options['stride_h'], options['stride_w'], 1],
padding=options['padding'],
name=output_detail['name'])
tensors[output_detail['index']] = output_tensor
elif op_type == 'PAD':
input_tensor = tensors[op['inputs'][0]]
output_detail = interpreter._get_tensor_details(op['outputs'][0])
paddings_detail = interpreter._get_tensor_details(op['inputs'][1])
paddings_array = interpreter.get_tensor(paddings_detail['index'])
paddings = tf.Variable(
paddings_array, name=paddings_detail['name'])
output_tensor = tf.pad(
input_tensor, paddings, name=output_detail['name'])
tensors[output_detail['index']] = output_tensor
elif op_type == 'RELU':
output_detail = interpreter._get_tensor_details(op['outputs'][0])
input_tensor = tensors[op['inputs'][0]]
output_tensor = tf.nn.relu(input_tensor, name=output_detail['name'])
tensors[output_detail['index']] = output_tensor
elif op_type == 'PRELU':
output_detail = interpreter._get_tensor_details(op['outputs'][0])
input_tensor = tensors[op['inputs'][0]]
alpha_detail = interpreter._get_tensor_details(op['inputs'][1])
alpha_array = interpreter.get_tensor(alpha_detail['index'])
with tf.variable_scope(name_or_scope=output_detail['name']):
alphas = tf.Variable(alpha_array, name=alpha_detail['name'])
output_tensor = tf.maximum(alphas * input_tensor, input_tensor)
tensors[output_detail['index']] = output_tensor
elif op_type == 'RELU6':
output_detail = interpreter._get_tensor_details(op['outputs'][0])
input_tensor = tensors[op['inputs'][0]]
output_tensor = tf.nn.relu6(input_tensor, name=output_detail['name'])
tensors[output_detail['index']] = output_tensor
elif op_type == 'RESHAPE':
input_tensor = tensors[op['inputs'][0]]
output_detail = interpreter._get_tensor_details(op['outputs'][0])
options = op['builtin_options']
output_tensor = tf.reshape(input_tensor, options['new_shape'], name=output_detail['name'])
tensors[output_detail['index']] = output_tensor
elif op_type == 'ADD':
output_detail = interpreter._get_tensor_details(op['outputs'][0])
input_tensor_0 = tensors[op['inputs'][0]]
try:
input_tensor_1 = tensors[op['inputs'][1]]
except:
param = interpreter._get_tensor_details(op['inputs'][1])
input_tensor_1 = interpreter.get_tensor(param['index'])
output_tensor = tf.add(input_tensor_0, input_tensor_1, name=output_detail['name'])
if output_detail['name'].split('/')[-1]=='Relu6':
output_tensor = tf.nn.relu6(output_tensor)
tensors[output_detail['index']] = output_tensor
elif op_type == 'CONCATENATION':
output_detail = interpreter._get_tensor_details(op['outputs'][0])
input_tensor_0 = tensors[op['inputs'][0]]
input_tensor_1 = tensors[op['inputs'][1]]
try:
input_tensor_2 = tensors[op['inputs'][2]]
options = op['builtin_options']
output_tensor = tf.concat([input_tensor_0, input_tensor_1, input_tensor_2],
options['axis'],
name=output_detail['name'])
except:
options = op['builtin_options']
output_tensor = tf.concat([input_tensor_0, input_tensor_1],
options['axis'],
name=output_detail['name'])
tensors[output_detail['index']] = output_tensor
elif op_type == 'LOGISTIC':
output_detail = interpreter._get_tensor_details(op['outputs'][0])
input_tensor = tensors[op['inputs'][0]]
output_tensor = tf.math.sigmoid(input_tensor, name=output_detail['name'])
tensors[output_detail['index']] = output_tensor
elif op_type == 'TRANSPOSE_CONV':
input_tensor = tensors[op['inputs'][2]]
weights_detail = interpreter._get_tensor_details(op['inputs'][1])
output_shape_detail = interpreter._get_tensor_details(op['inputs'][0])
output_detail = interpreter._get_tensor_details(op['outputs'][0])
weights_array = interpreter.get_tensor(weights_detail['index'])
weights_array = np.transpose(weights_array, (1, 2, 0, 3))
output_shape_array = interpreter.get_tensor(output_shape_detail['index'])
weights = tf.Variable(weights_array, name=weights_detail['name'])
shape = tf.Variable(output_shape_array, name=output_shape_detail['name'])
options = op['builtin_options']
output_tensor = tf.nn.conv2d_transpose(input_tensor,
weights,
shape,
[1, options['stride_h'], options['stride_w'], 1],
padding=options['padding'],
name=output_detail['name'] + '/conv2d_transpose')
tensors[output_detail['index']] = output_tensor
elif op_type == 'MUL':
output_detail = interpreter._get_tensor_details(op['outputs'][0])
input_tensor_0 = tensors[op['inputs'][0]]
input_tensor_1 = None
try:
input_tensor_1 = tensors[op['inputs'][1]]
except:
param = interpreter._get_tensor_details(op['inputs'][1])
input_tensor_1 = interpreter.get_tensor(param['index'])
output_tensor = tf.multiply(input_tensor_0, input_tensor_1, name=output_detail['name'])
tensors[output_detail['index']] = output_tensor
elif op_type == 'HARD_SWISH':
output_detail = interpreter._get_tensor_details(op['outputs'][0])
input_tensor = tensors[op['inputs'][0]]
output_tensor = optimizing_hardswish_for_edgetpu(input_tensor, name=output_detail['name'])
tensors[output_detail['index']] = output_tensor
elif op_type == 'AVERAGE_POOL_2D':
output_detail = interpreter._get_tensor_details(op['outputs'][0])
input_tensor = tensors[op['inputs'][0]]
options = op['builtin_options']
pool_size = [options['filter_height'], options['filter_width']]
strides = [options['stride_h'], options['stride_w']]
padding = options['padding']
output_tensor = tf.keras.layers.AveragePooling2D(pool_size=pool_size,
strides=strides,
padding=padding,
name=output_detail['name'])(input_tensor)
tensors[output_detail['index']] = output_tensor
elif op_type == 'FULLY_CONNECTED':
output_detail = interpreter._get_tensor_details(op['outputs'][0])
input_tensor = tensors[op['inputs'][0]]
weights = tensors[op['inputs'][1]].transpose(1,0)
bias = tensors[op['inputs'][2]]
output_shape_detail = interpreter._get_tensor_details(op['inputs'][0])
output_shape_array = interpreter.get_tensor(output_shape_detail['index'])
output_tensor = tf.keras.layers.Dense(units=output_shape_array.shape[3],
use_bias=True,
kernel_initializer=tf.keras.initializers.Constant(weights),
bias_initializer=tf.keras.initializers.Constant(bias))(input_tensor)
tensors[output_detail['index']] = output_tensor
elif op_type == 'RESIZE_BILINEAR':
output_detail = interpreter._get_tensor_details(op['outputs'][0])
input_tensor = tensors[op['inputs'][0]]
size_detail = interpreter._get_tensor_details(op['inputs'][1])
size = interpreter.get_tensor(size_detail['index'])
size_height = size[0]
size_width = size[1]
def upsampling2d_bilinear(x, size_height, size_width):
if optimizing_for_edgetpu_flg:
return tf.image.resize_bilinear(x, (size_height, size_width))
else:
return tfv2.image.resize(x, [size_height, size_width], method='bilinear')
output_tensor = tf.keras.layers.Lambda(upsampling2d_bilinear, arguments={'size_height': size_height, 'size_width': size_width})(input_tensor)
tensors[output_detail['index']] = output_tensor
elif op_type == 'DEQUANTIZE':
output_detail = interpreter._get_tensor_details(op['outputs'][0])
weights_detail = interpreter._get_tensor_details(op['inputs'][0])
weights = interpreter.get_tensor(weights_detail['index'])
output_tensor = weights.astype(np.float32)
tensors[output_detail['index']] = output_tensor
else:
raise ValueError(op_type)
# Convolution2DTransposeBias
input_tensor = tensors[241]
weights = np.load('weights/segment_Kernel').transpose(1,2,0,3).astype(np.float32)
bias = np.load('weights/segment_Bias').astype(np.float32)
custom_trans = tf.nn.conv2d_transpose(input=input_tensor,
filters=weights,
output_shape=[1, height, width, 2],
strides=[2, 2],
padding='SAME',
dilations=[1, 1])
output_tensor = tf.math.add(custom_trans, bias, name='segment')
tensors[999] = output_tensor | [
"def",
"make_graph",
"(",
"ops",
",",
"op_types",
",",
"interpreter",
")",
":",
"height",
"=",
"96",
"width",
"=",
"160",
"tensors",
"=",
"{",
"}",
"input_details",
"=",
"interpreter",
".",
"get_input_details",
"(",
")",
"# output_details = interpreter.get_outpu... | https://github.com/PINTO0309/PINTO_model_zoo/blob/2924acda7a7d541d8712efd7cc4fd1c61ef5bddd/082_MediaPipe_Meet_Segmentation/03_segm_lite_v681_tflite_to_pb_saved_model.py#L54-L288 | ||||
HeinleinSupport/check_mk_extensions | aa7d7389b812ed00f91dad61d66fb676284897d8 | dir_size/web/plugins/wato/dir_size.py | python | _parameter_valuespec_dir_size | () | return Transform(
Dictionary(
title = _("Limits"),
help = _("Size of all files and subdirectories"),
elements = [
( 'levels_upper',
Tuple(
title = _('Upper levels for the total size'),
elements = [
Filesize(title = _("Warning at")),
Filesize(title = _("Critical at")),
],
)),
],
required_keys = [ "levels_upper" ],
),
forth = transform_dir_size_rules,
) | [] | def _parameter_valuespec_dir_size():
return Transform(
Dictionary(
title = _("Limits"),
help = _("Size of all files and subdirectories"),
elements = [
( 'levels_upper',
Tuple(
title = _('Upper levels for the total size'),
elements = [
Filesize(title = _("Warning at")),
Filesize(title = _("Critical at")),
],
)),
],
required_keys = [ "levels_upper" ],
),
forth = transform_dir_size_rules,
) | [
"def",
"_parameter_valuespec_dir_size",
"(",
")",
":",
"return",
"Transform",
"(",
"Dictionary",
"(",
"title",
"=",
"_",
"(",
"\"Limits\"",
")",
",",
"help",
"=",
"_",
"(",
"\"Size of all files and subdirectories\"",
")",
",",
"elements",
"=",
"[",
"(",
"'leve... | https://github.com/HeinleinSupport/check_mk_extensions/blob/aa7d7389b812ed00f91dad61d66fb676284897d8/dir_size/web/plugins/wato/dir_size.py#L39-L57 | |||
openstack/manila | 142990edc027e14839d5deaf4954dd6fc88de15e | manila/share/drivers/quobyte/quobyte.py | python | QuobyteShareDriver.delete_share | (self, context, share, share_server=None) | Delete the corresponding Quobyte volume. | Delete the corresponding Quobyte volume. | [
"Delete",
"the",
"corresponding",
"Quobyte",
"volume",
"."
] | def delete_share(self, context, share, share_server=None):
"""Delete the corresponding Quobyte volume."""
volume_uuid = self._resolve_volume_name(share['name'],
share['project_id'])
if not volume_uuid:
LOG.warning("No volume found for "
"share %(project_id)s/%(name)s",
{"project_id": share['project_id'],
"name": share['name']})
return
if self.configuration.quobyte_delete_shares:
self.rpc.call('deleteVolume', {'volume_uuid': volume_uuid})
else:
self.rpc.call('exportVolume', {"volume_uuid": volume_uuid,
"remove_export": True,
}) | [
"def",
"delete_share",
"(",
"self",
",",
"context",
",",
"share",
",",
"share_server",
"=",
"None",
")",
":",
"volume_uuid",
"=",
"self",
".",
"_resolve_volume_name",
"(",
"share",
"[",
"'name'",
"]",
",",
"share",
"[",
"'project_id'",
"]",
")",
"if",
"n... | https://github.com/openstack/manila/blob/142990edc027e14839d5deaf4954dd6fc88de15e/manila/share/drivers/quobyte/quobyte.py#L260-L276 | ||
adamcharnock/lightbus | 5e7069da06cd37a8131e8c592ee957ccb73603d5 | lightbus/message.py | python | Message.__init__ | (self, id: str = "", native_id: str = None) | [] | def __init__(self, id: str = "", native_id: str = None):
self.id = id or str(uuid1())
self.native_id = native_id | [
"def",
"__init__",
"(",
"self",
",",
"id",
":",
"str",
"=",
"\"\"",
",",
"native_id",
":",
"str",
"=",
"None",
")",
":",
"self",
".",
"id",
"=",
"id",
"or",
"str",
"(",
"uuid1",
"(",
")",
")",
"self",
".",
"native_id",
"=",
"native_id"
] | https://github.com/adamcharnock/lightbus/blob/5e7069da06cd37a8131e8c592ee957ccb73603d5/lightbus/message.py#L14-L16 | ||||
sahana/eden | 1696fa50e90ce967df69f66b571af45356cc18da | modules/s3/s3validators.py | python | IS_NOT_ONE_OF.validate | (self, value, record_id=None) | return value | Validator
Args:
value: the input value
record_id: the current record ID
Returns:
value | Validator | [
"Validator"
] | def validate(self, value, record_id=None):
"""
Validator
Args:
value: the input value
record_id: the current record ID
Returns:
value
"""
value = str(value)
if not value.strip():
# Empty => error
raise ValidationError(translate(self.error_message))
allowed_override = self.allowed_override
if allowed_override and value in allowed_override:
# Uniqueness-requirement overridden
return value
# Establish table and field
tablename, fieldname = str(self.field).split(".")
dbset = self.dbset
table = dbset.db[tablename]
field = table[fieldname]
if self.skip_imports and current.response.s3.bulk and not field.unique:
# Uniqueness-requirement to be enforced by deduplicate
# (which can't take effect if we reject the value here)
return value
# Does the table allow archiving ("soft-delete")?
archived = "deleted" in table
# Does the table use multiple columns as key?
if record_id is None:
record_id = self.record_id
keys = list(record_id.keys()) if isinstance(record_id, dict) else None
# Build duplicate query
# => if the field has a unique-constraint, we must include
# archived ("soft-deleted") records, otherwise the
# validator will pass, but the DB-write will crash
query = (field == value)
if not field.unique and archived:
query = (table["deleted"] == False) & query
# Limit the fields we extract to just keys+deleted
fields = []
if keys:
fields = [table[k] for k in keys]
else:
fields = [table._id]
if archived:
fields.append(table.deleted)
# Find conflict
row = dbset(query).select(limitby=(0, 1), *fields).first()
if row:
if keys:
# Keyed table
for f in keys:
if str(getattr(row, f)) != str(record_id[f]):
ValidationError(translate(self.error_message))
elif str(row[table._id.name]) != str(record_id):
if archived and row.deleted and field.type in ("string", "text"):
# Table supports archiving, and the conflicting
# record is "deleted" => try updating the archived
# record by appending a random tag to the field value
import random
tagged = "%s.[%s]" % (value,
"".join(random.choice("abcdefghijklmnopqrstuvwxyz")
for _ in range(8))
)
try:
row.update_record(**{fieldname: tagged})
except Exception:
# Failed => nothing else we can try
ValidationError(translate(self.error_message))
else:
raise ValidationError(translate(self.error_message))
return value | [
"def",
"validate",
"(",
"self",
",",
"value",
",",
"record_id",
"=",
"None",
")",
":",
"value",
"=",
"str",
"(",
"value",
")",
"if",
"not",
"value",
".",
"strip",
"(",
")",
":",
"# Empty => error",
"raise",
"ValidationError",
"(",
"translate",
"(",
"se... | https://github.com/sahana/eden/blob/1696fa50e90ce967df69f66b571af45356cc18da/modules/s3/s3validators.py#L1311-L1397 | |
tp4a/teleport | 1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad | server/www/packages/packages-darwin/x64/PIL/IcoImagePlugin.py | python | IcoImageFile.load_seek | (self) | [] | def load_seek(self):
# Flag the ImageFile.Parser so that it
# just does all the decode at the end.
pass | [
"def",
"load_seek",
"(",
"self",
")",
":",
"# Flag the ImageFile.Parser so that it",
"# just does all the decode at the end.",
"pass"
] | https://github.com/tp4a/teleport/blob/1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad/server/www/packages/packages-darwin/x64/PIL/IcoImagePlugin.py#L274-L277 | ||||
omz/PythonistaAppTemplate | f560f93f8876d82a21d108977f90583df08d55af | PythonistaAppTemplate/PythonistaKit.framework/pylib_ext/matplotlib/font_manager.py | python | findSystemFonts | (fontpaths=None, fontext='ttf') | return [fname for fname in fontfiles.iterkeys() if os.path.exists(fname)] | Search for fonts in the specified font paths. If no paths are
given, will use a standard set of system paths, as well as the
list of fonts tracked by fontconfig if fontconfig is installed and
available. A list of TrueType fonts are returned by default with
AFM fonts as an option. | Search for fonts in the specified font paths. If no paths are
given, will use a standard set of system paths, as well as the
list of fonts tracked by fontconfig if fontconfig is installed and
available. A list of TrueType fonts are returned by default with
AFM fonts as an option. | [
"Search",
"for",
"fonts",
"in",
"the",
"specified",
"font",
"paths",
".",
"If",
"no",
"paths",
"are",
"given",
"will",
"use",
"a",
"standard",
"set",
"of",
"system",
"paths",
"as",
"well",
"as",
"the",
"list",
"of",
"fonts",
"tracked",
"by",
"fontconfig"... | def findSystemFonts(fontpaths=None, fontext='ttf'):
"""
Search for fonts in the specified font paths. If no paths are
given, will use a standard set of system paths, as well as the
list of fonts tracked by fontconfig if fontconfig is installed and
available. A list of TrueType fonts are returned by default with
AFM fonts as an option.
"""
fontfiles = {}
fontexts = get_fontext_synonyms(fontext)
if fontpaths is None:
if sys.platform == 'win32':
fontdir = win32FontDirectory()
fontpaths = [fontdir]
# now get all installed fonts directly...
for f in win32InstalledFonts(fontdir):
base, ext = os.path.splitext(f)
if len(ext)>1 and ext[1:].lower() in fontexts:
fontfiles[f] = 1
else:
fontpaths = X11FontDirectories
# check for OS X & load its fonts if present
if sys.platform == 'darwin':
for f in OSXInstalledFonts(fontext=fontext):
fontfiles[f] = 1
for f in get_fontconfig_fonts(fontext):
fontfiles[f] = 1
elif isinstance(fontpaths, (str, unicode)):
fontpaths = [fontpaths]
for path in fontpaths:
files = list_fonts(path, fontexts)
for fname in files:
fontfiles[os.path.abspath(fname)] = 1
return [fname for fname in fontfiles.iterkeys() if os.path.exists(fname)] | [
"def",
"findSystemFonts",
"(",
"fontpaths",
"=",
"None",
",",
"fontext",
"=",
"'ttf'",
")",
":",
"fontfiles",
"=",
"{",
"}",
"fontexts",
"=",
"get_fontext_synonyms",
"(",
"fontext",
")",
"if",
"fontpaths",
"is",
"None",
":",
"if",
"sys",
".",
"platform",
... | https://github.com/omz/PythonistaAppTemplate/blob/f560f93f8876d82a21d108977f90583df08d55af/PythonistaAppTemplate/PythonistaKit.framework/pylib_ext/matplotlib/font_manager.py#L291-L329 | |
chainer/chainer-chemistry | efe323aa21f63a815130d673781e7cca1ccb72d2 | chainer_chemistry/dataset/preprocessors/wle_io.py | python | create_datasets | (atom_arrays, adj_arrays, teach_signals, wle_arrays=None) | return output_datasets | Expand the atomic_num_arrays with the expanded labels,
then return valid datasets (tuple of NumpyTupleDataset)
Args:
atom_arrays: 3-tuple of list of lists.
atom_arrays[i][j][k] is the id of an atom
i: train/val/test
j: index of a sample (i.e. molcule)
k: index of an atom
adj_arrays: list of list of numpy.array, all mol's adjacnecy tensors
teach_signals: list of list of numpy.array,
all teacher (supervision) signals
wle_arrays: None (for WLE) or 3-tuple of list of lists (for CWLE and GWLE).
Returns: 3 tuple of valid datasets (train/vel/test) in NumpyTuppleDataset | Expand the atomic_num_arrays with the expanded labels,
then return valid datasets (tuple of NumpyTupleDataset) | [
"Expand",
"the",
"atomic_num_arrays",
"with",
"the",
"expanded",
"labels",
"then",
"return",
"valid",
"datasets",
"(",
"tuple",
"of",
"NumpyTupleDataset",
")"
] | def create_datasets(atom_arrays, adj_arrays, teach_signals, wle_arrays=None):
"""
Expand the atomic_num_arrays with the expanded labels,
then return valid datasets (tuple of NumpyTupleDataset)
Args:
atom_arrays: 3-tuple of list of lists.
atom_arrays[i][j][k] is the id of an atom
i: train/val/test
j: index of a sample (i.e. molcule)
k: index of an atom
adj_arrays: list of list of numpy.array, all mol's adjacnecy tensors
teach_signals: list of list of numpy.array,
all teacher (supervision) signals
wle_arrays: None (for WLE) or 3-tuple of list of lists (for CWLE and GWLE).
Returns: 3 tuple of valid datasets (train/vel/test) in NumpyTuppleDataset
"""
output_datasets = []
# ToDo: try another indexing: e.g. orignal node label + extneions
assert len(atom_arrays) == len(adj_arrays) == len(teach_signals)
if wle_arrays is not None:
assert len(atom_arrays) == len(wle_arrays)
for i in range(len(atom_arrays)):
# We have swaped the axes 0 and 1 for adj-arrays. re-swap
set_adj_arrays = np.array(adj_arrays[i])
for m in range(len(set_adj_arrays)):
set_adj_arrays[m] = np.swapaxes(set_adj_arrays[m], 0, 1)
if wle_arrays is None:
dataset = NumpyTupleDataset(np.array(atom_arrays[i]),
set_adj_arrays,
np.array(teach_signals[i]))
else:
dataset = NumpyTupleDataset(np.array(atom_arrays[i]),
set_adj_arrays,
np.array(wle_arrays[i]),
np.array(teach_signals[i]))
output_datasets.append(dataset)
# end expanded-for
return output_datasets | [
"def",
"create_datasets",
"(",
"atom_arrays",
",",
"adj_arrays",
",",
"teach_signals",
",",
"wle_arrays",
"=",
"None",
")",
":",
"output_datasets",
"=",
"[",
"]",
"# ToDo: try another indexing: e.g. orignal node label + extneions",
"assert",
"len",
"(",
"atom_arrays",
"... | https://github.com/chainer/chainer-chemistry/blob/efe323aa21f63a815130d673781e7cca1ccb72d2/chainer_chemistry/dataset/preprocessors/wle_io.py#L10-L54 | |
home-assistant/core | 265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1 | homeassistant/components/isy994/sensor.py | python | ISYSensorVariableEntity.__init__ | (self, vname: str, vobj: object) | Initialize the ISY994 binary sensor program. | Initialize the ISY994 binary sensor program. | [
"Initialize",
"the",
"ISY994",
"binary",
"sensor",
"program",
"."
] | def __init__(self, vname: str, vobj: object) -> None:
"""Initialize the ISY994 binary sensor program."""
super().__init__(vobj)
self._name = vname | [
"def",
"__init__",
"(",
"self",
",",
"vname",
":",
"str",
",",
"vobj",
":",
"object",
")",
"->",
"None",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"vobj",
")",
"self",
".",
"_name",
"=",
"vname"
] | https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/isy994/sensor.py#L110-L113 | ||
zhl2008/awd-platform | 0416b31abea29743387b10b3914581fbe8e7da5e | web_flaskbb/lib/python2.7/site-packages/pip/_vendor/distlib/metadata.py | python | LegacyMetadata.__iter__ | (self) | [] | def __iter__(self):
for key in self.keys():
yield key | [
"def",
"__iter__",
"(",
"self",
")",
":",
"for",
"key",
"in",
"self",
".",
"keys",
"(",
")",
":",
"yield",
"key"
] | https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/pip/_vendor/distlib/metadata.py#L634-L636 | ||||
cloudera/hue | 23f02102d4547c17c32bd5ea0eb24e9eadd657a4 | desktop/core/ext-py/celery-4.2.1/celery/utils/time.py | python | adjust_timestamp | (ts, offset, here=utcoffset) | return ts - (offset - here()) * 3600 | Adjust timestamp based on provided utcoffset. | Adjust timestamp based on provided utcoffset. | [
"Adjust",
"timestamp",
"based",
"on",
"provided",
"utcoffset",
"."
] | def adjust_timestamp(ts, offset, here=utcoffset):
"""Adjust timestamp based on provided utcoffset."""
return ts - (offset - here()) * 3600 | [
"def",
"adjust_timestamp",
"(",
"ts",
",",
"offset",
",",
"here",
"=",
"utcoffset",
")",
":",
"return",
"ts",
"-",
"(",
"offset",
"-",
"here",
"(",
")",
")",
"*",
"3600"
] | https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/celery-4.2.1/celery/utils/time.py#L387-L389 | |
evennia/evennia | fa79110ba6b219932f22297838e8ac72ebc0be0e | evennia/utils/logger.py | python | log_file | (msg, filename="game.log") | Arbitrary file logger using threads.
Args:
msg (str): String to append to logfile.
filename (str, optional): Defaults to 'game.log'. All logs
will appear in the logs directory and log entries will start
on new lines following datetime info. | Arbitrary file logger using threads. | [
"Arbitrary",
"file",
"logger",
"using",
"threads",
"."
] | def log_file(msg, filename="game.log"):
"""
Arbitrary file logger using threads.
Args:
msg (str): String to append to logfile.
filename (str, optional): Defaults to 'game.log'. All logs
will appear in the logs directory and log entries will start
on new lines following datetime info.
"""
def callback(filehandle, msg):
"""Writing to file and flushing result"""
msg = "\n%s [-] %s" % (timeformat(), msg.strip())
filehandle.write(msg)
# since we don't close the handle, we need to flush
# manually or log file won't be written to until the
# write buffer is full.
filehandle.flush()
def errback(failure):
"""Catching errors to normal log"""
log_trace()
# save to server/logs/ directory
filehandle = _open_log_file(filename)
if filehandle:
deferToThread(callback, filehandle, msg).addErrback(errback) | [
"def",
"log_file",
"(",
"msg",
",",
"filename",
"=",
"\"game.log\"",
")",
":",
"def",
"callback",
"(",
"filehandle",
",",
"msg",
")",
":",
"\"\"\"Writing to file and flushing result\"\"\"",
"msg",
"=",
"\"\\n%s [-] %s\"",
"%",
"(",
"timeformat",
"(",
")",
",",
... | https://github.com/evennia/evennia/blob/fa79110ba6b219932f22297838e8ac72ebc0be0e/evennia/utils/logger.py#L453-L481 | ||
gepd/Deviot | 150caea06108369b30210eb287a580fcff4904af | libraries/pyserial/serialutil.py | python | SerialBase.rs485_mode | (self) | return self._rs485_mode | \
Enable RS485 mode and apply new settings, set to None to disable.
See serial.rs485.RS485Settings for more info about the value. | \
Enable RS485 mode and apply new settings, set to None to disable.
See serial.rs485.RS485Settings for more info about the value. | [
"\\",
"Enable",
"RS485",
"mode",
"and",
"apply",
"new",
"settings",
"set",
"to",
"None",
"to",
"disable",
".",
"See",
"serial",
".",
"rs485",
".",
"RS485Settings",
"for",
"more",
"info",
"about",
"the",
"value",
"."
] | def rs485_mode(self):
"""\
Enable RS485 mode and apply new settings, set to None to disable.
See serial.rs485.RS485Settings for more info about the value.
"""
return self._rs485_mode | [
"def",
"rs485_mode",
"(",
"self",
")",
":",
"return",
"self",
".",
"_rs485_mode"
] | https://github.com/gepd/Deviot/blob/150caea06108369b30210eb287a580fcff4904af/libraries/pyserial/serialutil.py#L485-L490 | |
edfungus/Crouton | ada98b3930192938a48909072b45cb84b945f875 | clients/python_clients/venv/lib/python2.7/site-packages/pip/_vendor/requests/models.py | python | PreparedRequest.prepare_auth | (self, auth, url='') | Prepares the given HTTP auth data. | Prepares the given HTTP auth data. | [
"Prepares",
"the",
"given",
"HTTP",
"auth",
"data",
"."
] | def prepare_auth(self, auth, url=''):
"""Prepares the given HTTP auth data."""
# If no Auth is explicitly provided, extract it from the URL first.
if auth is None:
url_auth = get_auth_from_url(self.url)
auth = url_auth if any(url_auth) else None
if auth:
if isinstance(auth, tuple) and len(auth) == 2:
# special-case basic HTTP auth
auth = HTTPBasicAuth(*auth)
# Allow auth to make its changes.
r = auth(self)
# Update self to reflect the auth changes.
self.__dict__.update(r.__dict__)
# Recompute Content-Length
self.prepare_content_length(self.body) | [
"def",
"prepare_auth",
"(",
"self",
",",
"auth",
",",
"url",
"=",
"''",
")",
":",
"# If no Auth is explicitly provided, extract it from the URL first.",
"if",
"auth",
"is",
"None",
":",
"url_auth",
"=",
"get_auth_from_url",
"(",
"self",
".",
"url",
")",
"auth",
... | https://github.com/edfungus/Crouton/blob/ada98b3930192938a48909072b45cb84b945f875/clients/python_clients/venv/lib/python2.7/site-packages/pip/_vendor/requests/models.py#L482-L502 | ||
zhl2008/awd-platform | 0416b31abea29743387b10b3914581fbe8e7da5e | web_hxb2/lib/python3.5/site-packages/wagtail_bak/wagtailforms/forms.py | python | FormBuilder.create_multiselect_field | (self, field, options) | return django.forms.MultipleChoiceField(**options) | [] | def create_multiselect_field(self, field, options):
options['choices'] = map(
lambda x: (x.strip(), x.strip()),
field.choices.split(',')
)
return django.forms.MultipleChoiceField(**options) | [
"def",
"create_multiselect_field",
"(",
"self",
",",
"field",
",",
"options",
")",
":",
"options",
"[",
"'choices'",
"]",
"=",
"map",
"(",
"lambda",
"x",
":",
"(",
"x",
".",
"strip",
"(",
")",
",",
"x",
".",
"strip",
"(",
")",
")",
",",
"field",
... | https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/wagtail_bak/wagtailforms/forms.py#L55-L60 | |||
GNS3/gns3-server | aff06572d4173df945ad29ea8feb274f7885d9e4 | gns3server/compute/dynamips/nodes/router.py | python | Router.dynamips_id | (self) | return self._dynamips_id | Returns the Dynamips VM ID.
:return: Dynamips VM identifier | Returns the Dynamips VM ID. | [
"Returns",
"the",
"Dynamips",
"VM",
"ID",
"."
] | def dynamips_id(self):
"""
Returns the Dynamips VM ID.
:return: Dynamips VM identifier
"""
return self._dynamips_id | [
"def",
"dynamips_id",
"(",
"self",
")",
":",
"return",
"self",
".",
"_dynamips_id"
] | https://github.com/GNS3/gns3-server/blob/aff06572d4173df945ad29ea8feb274f7885d9e4/gns3server/compute/dynamips/nodes/router.py#L199-L206 | |
mozilla/moztrap | 93b34a4cd21c9e08f73d3b1a7630cd873f8418a0 | moztrap/view/lists/actions.py | python | actions | (model, allowed_actions, permission=None, fall_through=False) | return decorator | View decorator for handling single-model actions on manage list pages.
Handles any POST keys named "action-method", where "method" must be in
``allowed_actions``. The value of the key should be an ID of a ``model``,
and "method" will be called on it, with any errors handled.
By default, any "POST" request will be redirected back to the same URL
(unless it's an AJAX request, in which case it sets the request method to
GET and clears POST data, which has a similar effect without actually doing
a redirect). If ``fall_through`` is set to True, the redirect/method-switch
will only occur if an action was found in the POST data (allowing this
decorator to be used with views that also do normal non-actions form
handling.) | View decorator for handling single-model actions on manage list pages. | [
"View",
"decorator",
"for",
"handling",
"single",
"-",
"model",
"actions",
"on",
"manage",
"list",
"pages",
"."
] | def actions(model, allowed_actions, permission=None, fall_through=False):
"""
View decorator for handling single-model actions on manage list pages.
Handles any POST keys named "action-method", where "method" must be in
``allowed_actions``. The value of the key should be an ID of a ``model``,
and "method" will be called on it, with any errors handled.
By default, any "POST" request will be redirected back to the same URL
(unless it's an AJAX request, in which case it sets the request method to
GET and clears POST data, which has a similar effect without actually doing
a redirect). If ``fall_through`` is set to True, the redirect/method-switch
will only occur if an action was found in the POST data (allowing this
decorator to be used with views that also do normal non-actions form
handling.)
"""
def decorator(view_func):
@wraps(view_func)
def _wrapped_view(request, *args, **kwargs):
if request.method == "POST":
action_taken = False
action_data = get_action(request.POST)
if action_data:
action, obj_id = action_data
if action in allowed_actions:
if permission and not request.user.has_perm(permission):
return HttpResponseForbidden(
"You do not have permission for this action.")
try:
obj = model._base_manager.get(pk=obj_id)
except model.DoesNotExist:
pass
else:
getattr(obj, action)(user=request.user)
action_taken = True
if action_taken or not fall_through:
if request.is_ajax():
request.method = "GET"
request.POST = {}
else:
return redirect(request.get_full_path())
return view_func(request, *args, **kwargs)
return _wrapped_view
return decorator | [
"def",
"actions",
"(",
"model",
",",
"allowed_actions",
",",
"permission",
"=",
"None",
",",
"fall_through",
"=",
"False",
")",
":",
"def",
"decorator",
"(",
"view_func",
")",
":",
"@",
"wraps",
"(",
"view_func",
")",
"def",
"_wrapped_view",
"(",
"request"... | https://github.com/mozilla/moztrap/blob/93b34a4cd21c9e08f73d3b1a7630cd873f8418a0/moztrap/view/lists/actions.py#L12-L58 | |
Azure/azure-cli | 6c1b085a0910c6c2139006fcbd8ade44006eb6dd | src/azure-cli/azure/cli/command_modules/sql/custom.py | python | _get_identity_object_from_type | (
assignIdentityIsPresent,
resourceIdentityType,
userAssignedIdentities,
existingResourceIdentity) | return identityResult | Gets the resource identity type. | Gets the resource identity type. | [
"Gets",
"the",
"resource",
"identity",
"type",
"."
] | def _get_identity_object_from_type(
assignIdentityIsPresent,
resourceIdentityType,
userAssignedIdentities,
existingResourceIdentity):
'''
Gets the resource identity type.
'''
identityResult = None
if resourceIdentityType is not None and resourceIdentityType == ResourceIdType.none.value:
identityResult = ResourceIdentity(type=ResourceIdType.none.value)
return identityResult
if assignIdentityIsPresent and resourceIdentityType is not None:
# When UMI is of type SystemAssigned,UserAssigned
if resourceIdentityType == ResourceIdType.system_assigned_user_assigned.value:
umiDict = None
if userAssignedIdentities is None:
raise CLIError('"The list of user assigned identity ids needs to be passed if the'
'IdentityType is UserAssigned or SystemAssignedUserAssigned.')
if existingResourceIdentity is not None and existingResourceIdentity.user_assigned_identities is not None:
identityResult = _get_sys_assigned_user_assigned_identity(userAssignedIdentities,
existingResourceIdentity)
# Create scenarios
else:
for identity in userAssignedIdentities:
if umiDict is None:
umiDict = {identity: UserIdentity()}
else:
umiDict[identity] = UserIdentity() # pylint: disable=unsupported-assignment-operation
identityResult = ResourceIdentity(type=ResourceIdType.system_assigned_user_assigned.value,
user_assigned_identities=umiDict)
# When UMI is of type UserAssigned
if resourceIdentityType == ResourceIdType.user_assigned.value:
umiDict = None
if userAssignedIdentities is None:
raise CLIError('"The list of user assigned identity ids needs to be passed if the '
'IdentityType is UserAssigned or SystemAssignedUserAssigned.')
if existingResourceIdentity is not None and existingResourceIdentity.user_assigned_identities is not None:
identityResult = _get__user_assigned_identity(userAssignedIdentities, existingResourceIdentity)
else:
for identity in userAssignedIdentities:
if umiDict is None:
umiDict = {identity: UserIdentity()}
else:
umiDict[identity] = UserIdentity() # pylint: disable=unsupported-assignment-operation
identityResult = ResourceIdentity(type=ResourceIdType.user_assigned.value,
user_assigned_identities=umiDict)
elif assignIdentityIsPresent:
identityResult = ResourceIdentity(type=ResourceIdType.system_assigned.value)
if assignIdentityIsPresent is False and existingResourceIdentity is not None:
identityResult = existingResourceIdentity
print(identityResult)
return identityResult | [
"def",
"_get_identity_object_from_type",
"(",
"assignIdentityIsPresent",
",",
"resourceIdentityType",
",",
"userAssignedIdentities",
",",
"existingResourceIdentity",
")",
":",
"identityResult",
"=",
"None",
"if",
"resourceIdentityType",
"is",
"not",
"None",
"and",
"resource... | https://github.com/Azure/azure-cli/blob/6c1b085a0910c6c2139006fcbd8ade44006eb6dd/src/azure-cli/azure/cli/command_modules/sql/custom.py#L425-L489 | |
igraph/python-igraph | e9f83e8af08f24ea025596e745917197d8b44d94 | src/igraph/utils.py | python | safemax | (iterable, default=0) | Safer variant of ``max()`` that returns a default value if the iterable
is empty.
Example:
>>> safemax([-5, 6, 4])
6
>>> safemax([])
0
>>> safemax((), 2)
2 | Safer variant of ``max()`` that returns a default value if the iterable
is empty. | [
"Safer",
"variant",
"of",
"max",
"()",
"that",
"returns",
"a",
"default",
"value",
"if",
"the",
"iterable",
"is",
"empty",
"."
] | def safemax(iterable, default=0):
"""Safer variant of ``max()`` that returns a default value if the iterable
is empty.
Example:
>>> safemax([-5, 6, 4])
6
>>> safemax([])
0
>>> safemax((), 2)
2
"""
it = iter(iterable)
try:
first = next(it)
except StopIteration:
return default
else:
return max(chain([first], it)) | [
"def",
"safemax",
"(",
"iterable",
",",
"default",
"=",
"0",
")",
":",
"it",
"=",
"iter",
"(",
"iterable",
")",
"try",
":",
"first",
"=",
"next",
"(",
"it",
")",
"except",
"StopIteration",
":",
"return",
"default",
"else",
":",
"return",
"max",
"(",
... | https://github.com/igraph/python-igraph/blob/e9f83e8af08f24ea025596e745917197d8b44d94/src/igraph/utils.py#L362-L381 | ||
chen0040/keras-english-resume-parser-and-analyzer | 900f4a5afab53e1ae80b90ffecff964d8347c9c4 | keras_en_parser_and_analyzer/library/classifiers/ffn.py | python | WordVecGloveFFN.get_architecture_file_path | (model_dir_path) | return model_dir_path + '/' + WordVecGloveFFN.model_name + '_architecture.json' | [] | def get_architecture_file_path(model_dir_path):
return model_dir_path + '/' + WordVecGloveFFN.model_name + '_architecture.json' | [
"def",
"get_architecture_file_path",
"(",
"model_dir_path",
")",
":",
"return",
"model_dir_path",
"+",
"'/'",
"+",
"WordVecGloveFFN",
".",
"model_name",
"+",
"'_architecture.json'"
] | https://github.com/chen0040/keras-english-resume-parser-and-analyzer/blob/900f4a5afab53e1ae80b90ffecff964d8347c9c4/keras_en_parser_and_analyzer/library/classifiers/ffn.py#L36-L37 | |||
morganstanley/treadmill | f18267c665baf6def4374d21170198f63ff1cde4 | lib/python/treadmill/services/_linux_base_service.py | python | LinuxResourceService._run_events | (loop_poll, loop_timeout, loop_callbacks) | return any(results) | Wait for events up to `loop_timeout` and execute each of the
registered handlers.
:returns ``bool``:
True is any of the callbacks returned True | Wait for events up to `loop_timeout` and execute each of the
registered handlers. | [
"Wait",
"for",
"events",
"up",
"to",
"loop_timeout",
"and",
"execute",
"each",
"of",
"the",
"registered",
"handlers",
"."
] | def _run_events(loop_poll, loop_timeout, loop_callbacks):
"""Wait for events up to `loop_timeout` and execute each of the
registered handlers.
:returns ``bool``:
True is any of the callbacks returned True
"""
pending_callbacks = []
try:
# poll timeout is in milliseconds
for (fd, _event) in loop_poll.poll(loop_timeout * 1000):
fd_data = loop_callbacks[fd]
_LOGGER.debug('Event on %r: %r', fd, fd_data)
pending_callbacks.append(
fd_data['callback']
)
except select.error as err:
# Ignore signal interruptions
if six.PY2:
# pylint: disable=W1624,E1136,indexing-exception
if err[0] != errno.EINTR:
raise
else:
if err.errno != errno.EINTR:
raise
results = [
callback()
for callback in pending_callbacks
]
return any(results) | [
"def",
"_run_events",
"(",
"loop_poll",
",",
"loop_timeout",
",",
"loop_callbacks",
")",
":",
"pending_callbacks",
"=",
"[",
"]",
"try",
":",
"# poll timeout is in milliseconds",
"for",
"(",
"fd",
",",
"_event",
")",
"in",
"loop_poll",
".",
"poll",
"(",
"loop_... | https://github.com/morganstanley/treadmill/blob/f18267c665baf6def4374d21170198f63ff1cde4/lib/python/treadmill/services/_linux_base_service.py#L225-L258 | |
travisgoodspeed/goodfet | 1750cc1e8588af5470385e52fa098ca7364c2863 | client/GoodFETCC.py | python | GoodFETCC.test | (self) | [] | def test(self):
self.CCreleasecpu();
self.CChaltcpu();
#print "Status: %s" % self.CCstatusstr();
#Grab ident three times, should be equal.
ident1=self.CCident();
ident2=self.CCident();
ident3=self.CCident();
if(ident1!=ident2 or ident2!=ident3):
print "Error, repeated ident attempts unequal."
print "%04x, %04x, %04x" % (ident1, ident2, ident3);
#Single step, printing PC.
print "Tracing execution at startup."
for i in range(1,15):
pc=self.CCgetPC();
byte=self.CCpeekcodebyte(i);
#print "PC=%04x, %02x" % (pc, byte);
self.CCstep_instr();
print "Verifying that debugging a NOP doesn't affect the PC."
for i in range(1,15):
pc=self.CCgetPC();
self.CCdebuginstr([0x00]);
if(pc!=self.CCgetPC()):
print "ERROR: PC changed during CCdebuginstr([NOP])!";
print "Checking pokes to XRAM."
for i in range(self.execbuf,self.execbuf+0x20):
self.CCpokedatabyte(i,0xde);
if(self.CCpeekdatabyte(i)!=0xde):
print "Error in XDATA at 0x%04x" % i;
#print "Status: %s." % self.CCstatusstr();
#Exit debugger
self.stop();
print "Done."; | [
"def",
"test",
"(",
"self",
")",
":",
"self",
".",
"CCreleasecpu",
"(",
")",
"self",
".",
"CChaltcpu",
"(",
")",
"#print \"Status: %s\" % self.CCstatusstr();",
"#Grab ident three times, should be equal.",
"ident1",
"=",
"self",
".",
"CCident",
"(",
")",
"ident2",
... | https://github.com/travisgoodspeed/goodfet/blob/1750cc1e8588af5470385e52fa098ca7364c2863/client/GoodFETCC.py#L703-L740 | ||||
DxCx/plugin.video.9anime | 34358c2f701e5ddf19d3276926374a16f63f7b6a | resources/lib/ui/pyjsparser/pyjsparserdata.py | python | isKeyword | (w) | return w in KEYWORDS | [] | def isKeyword(w):
# 'const' is specialized as Keyword in V8.
# 'yield' and 'let' are for compatibility with SpiderMonkey and ES.next.
# Some others are from future reserved words.
return w in KEYWORDS | [
"def",
"isKeyword",
"(",
"w",
")",
":",
"# 'const' is specialized as Keyword in V8.",
"# 'yield' and 'let' are for compatibility with SpiderMonkey and ES.next.",
"# Some others are from future reserved words.",
"return",
"w",
"in",
"KEYWORDS"
] | https://github.com/DxCx/plugin.video.9anime/blob/34358c2f701e5ddf19d3276926374a16f63f7b6a/resources/lib/ui/pyjsparser/pyjsparserdata.py#L289-L293 | |||
microsoft/unilm | 65f15af2a307ebb64cfb25adf54375b002e6fe8d | xtune/src/transformers/commands/serving.py | python | ServeCommand.detokenize | (
self,
tokens_ids: List[int] = Body(None, embed=True),
skip_special_tokens: bool = Body(False, embed=True),
cleanup_tokenization_spaces: bool = Body(True, embed=True),
) | Detokenize the provided tokens ids to readable text:
- **tokens_ids**: List of tokens ids
- **skip_special_tokens**: Flag indicating to not try to decode special tokens
- **cleanup_tokenization_spaces**: Flag indicating to remove all leading/trailing spaces and intermediate ones. | Detokenize the provided tokens ids to readable text:
- **tokens_ids**: List of tokens ids
- **skip_special_tokens**: Flag indicating to not try to decode special tokens
- **cleanup_tokenization_spaces**: Flag indicating to remove all leading/trailing spaces and intermediate ones. | [
"Detokenize",
"the",
"provided",
"tokens",
"ids",
"to",
"readable",
"text",
":",
"-",
"**",
"tokens_ids",
"**",
":",
"List",
"of",
"tokens",
"ids",
"-",
"**",
"skip_special_tokens",
"**",
":",
"Flag",
"indicating",
"to",
"not",
"try",
"to",
"decode",
"spec... | def detokenize(
self,
tokens_ids: List[int] = Body(None, embed=True),
skip_special_tokens: bool = Body(False, embed=True),
cleanup_tokenization_spaces: bool = Body(True, embed=True),
):
"""
Detokenize the provided tokens ids to readable text:
- **tokens_ids**: List of tokens ids
- **skip_special_tokens**: Flag indicating to not try to decode special tokens
- **cleanup_tokenization_spaces**: Flag indicating to remove all leading/trailing spaces and intermediate ones.
"""
try:
decoded_str = self._pipeline.tokenizer.decode(tokens_ids, skip_special_tokens, cleanup_tokenization_spaces)
return ServeDeTokenizeResult(model="", text=decoded_str)
except Exception as e:
raise HTTPException(status_code=500, detail={"model": "", "error": str(e)}) | [
"def",
"detokenize",
"(",
"self",
",",
"tokens_ids",
":",
"List",
"[",
"int",
"]",
"=",
"Body",
"(",
"None",
",",
"embed",
"=",
"True",
")",
",",
"skip_special_tokens",
":",
"bool",
"=",
"Body",
"(",
"False",
",",
"embed",
"=",
"True",
")",
",",
"c... | https://github.com/microsoft/unilm/blob/65f15af2a307ebb64cfb25adf54375b002e6fe8d/xtune/src/transformers/commands/serving.py#L180-L196 | ||
vaexio/vaex | 6c1571f4f1ac030eb7128c1b35b2ccbb5dd29cac | packages/vaex-core/vaex/__init__.py | python | from_scalars | (**kwargs) | return from_arrays(**{k: np.array([v]) for k, v in kwargs.items()}) | Similar to from_arrays, but convenient for a DataFrame of length 1.
Example:
>>> import vaex
>>> df = vaex.from_scalars(x=1, y=2)
:rtype: DataFrame | Similar to from_arrays, but convenient for a DataFrame of length 1. | [
"Similar",
"to",
"from_arrays",
"but",
"convenient",
"for",
"a",
"DataFrame",
"of",
"length",
"1",
"."
] | def from_scalars(**kwargs):
"""Similar to from_arrays, but convenient for a DataFrame of length 1.
Example:
>>> import vaex
>>> df = vaex.from_scalars(x=1, y=2)
:rtype: DataFrame
"""
import numpy as np
return from_arrays(**{k: np.array([v]) for k, v in kwargs.items()}) | [
"def",
"from_scalars",
"(",
"*",
"*",
"kwargs",
")",
":",
"import",
"numpy",
"as",
"np",
"return",
"from_arrays",
"(",
"*",
"*",
"{",
"k",
":",
"np",
".",
"array",
"(",
"[",
"v",
"]",
")",
"for",
"k",
",",
"v",
"in",
"kwargs",
".",
"items",
"("... | https://github.com/vaexio/vaex/blob/6c1571f4f1ac030eb7128c1b35b2ccbb5dd29cac/packages/vaex-core/vaex/__init__.py#L393-L404 | |
naftaliharris/tauthon | 5587ceec329b75f7caf6d65a036db61ac1bae214 | Lib/wsgiref/headers.py | python | Headers.add_header | (self, _name, _value, **_params) | Extended header setting.
_name is the header field to add. keyword arguments can be used to set
additional parameters for the header field, with underscores converted
to dashes. Normally the parameter will be added as key="value" unless
value is None, in which case only the key will be added.
Example:
h.add_header('content-disposition', 'attachment', filename='bud.gif')
Note that unlike the corresponding 'email.message' method, this does
*not* handle '(charset, language, value)' tuples: all values must be
strings or None. | Extended header setting. | [
"Extended",
"header",
"setting",
"."
] | def add_header(self, _name, _value, **_params):
"""Extended header setting.
_name is the header field to add. keyword arguments can be used to set
additional parameters for the header field, with underscores converted
to dashes. Normally the parameter will be added as key="value" unless
value is None, in which case only the key will be added.
Example:
h.add_header('content-disposition', 'attachment', filename='bud.gif')
Note that unlike the corresponding 'email.message' method, this does
*not* handle '(charset, language, value)' tuples: all values must be
strings or None.
"""
parts = []
if _value is not None:
parts.append(_value)
for k, v in _params.items():
if v is None:
parts.append(k.replace('_', '-'))
else:
parts.append(_formatparam(k.replace('_', '-'), v))
self._headers.append((_name, "; ".join(parts))) | [
"def",
"add_header",
"(",
"self",
",",
"_name",
",",
"_value",
",",
"*",
"*",
"_params",
")",
":",
"parts",
"=",
"[",
"]",
"if",
"_value",
"is",
"not",
"None",
":",
"parts",
".",
"append",
"(",
"_value",
")",
"for",
"k",
",",
"v",
"in",
"_params"... | https://github.com/naftaliharris/tauthon/blob/5587ceec329b75f7caf6d65a036db61ac1bae214/Lib/wsgiref/headers.py#L145-L169 | ||
zhl2008/awd-platform | 0416b31abea29743387b10b3914581fbe8e7da5e | web_flaskbb/lib/python2.7/site-packages/mistune.py | python | Renderer.image | (self, src, title, text) | return '%s>' % html | Rendering a image with title and text.
:param src: source link of the image.
:param title: title text of the image.
:param text: alt text of the image. | Rendering a image with title and text. | [
"Rendering",
"a",
"image",
"with",
"title",
"and",
"text",
"."
] | def image(self, src, title, text):
"""Rendering a image with title and text.
:param src: source link of the image.
:param title: title text of the image.
:param text: alt text of the image.
"""
src = escape_link(src)
text = escape(text, quote=True)
if title:
title = escape(title, quote=True)
html = '<img src="%s" alt="%s" title="%s"' % (src, text, title)
else:
html = '<img src="%s" alt="%s"' % (src, text)
if self.options.get('use_xhtml'):
return '%s />' % html
return '%s>' % html | [
"def",
"image",
"(",
"self",
",",
"src",
",",
"title",
",",
"text",
")",
":",
"src",
"=",
"escape_link",
"(",
"src",
")",
"text",
"=",
"escape",
"(",
"text",
",",
"quote",
"=",
"True",
")",
"if",
"title",
":",
"title",
"=",
"escape",
"(",
"title"... | https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/mistune.py#L868-L884 | |
CGCookie/retopoflow | 3d8b3a47d1d661f99ab0aeb21d31370bf15de35e | retopoflow/rfmesh/rfmesh.py | python | RFMesh.obj_viewport_unhide | (self) | [] | def obj_viewport_unhide(self): self.obj_viewport_hide_set(False) | [
"def",
"obj_viewport_unhide",
"(",
"self",
")",
":",
"self",
".",
"obj_viewport_hide_set",
"(",
"False",
")"
] | https://github.com/CGCookie/retopoflow/blob/3d8b3a47d1d661f99ab0aeb21d31370bf15de35e/retopoflow/rfmesh/rfmesh.py#L267-L267 | ||||
JiYou/openstack | 8607dd488bde0905044b303eb6e52bdea6806923 | packages/source/cinder/cinder/openstack/common/rpc/amqp.py | python | multicall | (conf, context, topic, msg, timeout, connection_pool) | return wait_msg | Make a call that returns multiple times. | Make a call that returns multiple times. | [
"Make",
"a",
"call",
"that",
"returns",
"multiple",
"times",
"."
] | def multicall(conf, context, topic, msg, timeout, connection_pool):
"""Make a call that returns multiple times."""
# TODO(pekowski): Remove all these comments in Havana.
# For amqp_rpc_single_reply_queue = False,
# Can't use 'with' for multicall, as it returns an iterator
# that will continue to use the connection. When it's done,
# connection.close() will get called which will put it back into
# the pool
# For amqp_rpc_single_reply_queue = True,
# The 'with' statement is mandatory for closing the connection
LOG.debug(_('Making synchronous call on %s ...'), topic)
msg_id = uuid.uuid4().hex
msg.update({'_msg_id': msg_id})
LOG.debug(_('MSG_ID is %s') % (msg_id))
_add_unique_id(msg)
pack_context(msg, context)
# TODO(pekowski): Remove this flag and the code under the if clause
# in Havana.
if not conf.amqp_rpc_single_reply_queue:
conn = ConnectionContext(conf, connection_pool)
wait_msg = MulticallWaiter(conf, conn, timeout)
conn.declare_direct_consumer(msg_id, wait_msg)
conn.topic_send(topic, rpc_common.serialize_msg(msg), timeout)
else:
with _reply_proxy_create_sem:
if not connection_pool.reply_proxy:
connection_pool.reply_proxy = ReplyProxy(conf, connection_pool)
msg.update({'_reply_q': connection_pool.reply_proxy.get_reply_q()})
wait_msg = MulticallProxyWaiter(conf, msg_id, timeout, connection_pool)
with ConnectionContext(conf, connection_pool) as conn:
conn.topic_send(topic, rpc_common.serialize_msg(msg), timeout)
return wait_msg | [
"def",
"multicall",
"(",
"conf",
",",
"context",
",",
"topic",
",",
"msg",
",",
"timeout",
",",
"connection_pool",
")",
":",
"# TODO(pekowski): Remove all these comments in Havana.",
"# For amqp_rpc_single_reply_queue = False,",
"# Can't use 'with' for multicall, as it returns an... | https://github.com/JiYou/openstack/blob/8607dd488bde0905044b303eb6e52bdea6806923/packages/source/cinder/cinder/openstack/common/rpc/amqp.py#L574-L606 | |
microsoft/unilm | 65f15af2a307ebb64cfb25adf54375b002e6fe8d | unilm-v1/src/cnndm/bs_pyrouge.py | python | Rouge155.write_config_static | (system_dir, system_filename_pattern,
model_dir, model_filename_pattern,
config_file_path, system_id=None) | Write the ROUGE configuration file, which is basically a list
of system summary files and their corresponding model summary
files.
pyrouge uses regular expressions to automatically find the
matching model summary files for a given system summary file
(cf. docstrings for system_filename_pattern and
model_filename_pattern).
system_dir: Path of directory containing
system summaries.
system_filename_pattern: Regex string for matching
system summary filenames.
model_dir: Path of directory containing
model summaries.
model_filename_pattern: Regex string for matching model
summary filenames.
config_file_path: Path of the configuration file.
system_id: Optional system ID string which
will appear in the ROUGE output. | Write the ROUGE configuration file, which is basically a list
of system summary files and their corresponding model summary
files. | [
"Write",
"the",
"ROUGE",
"configuration",
"file",
"which",
"is",
"basically",
"a",
"list",
"of",
"system",
"summary",
"files",
"and",
"their",
"corresponding",
"model",
"summary",
"files",
"."
] | def write_config_static(system_dir, system_filename_pattern,
model_dir, model_filename_pattern,
config_file_path, system_id=None):
"""
Write the ROUGE configuration file, which is basically a list
of system summary files and their corresponding model summary
files.
pyrouge uses regular expressions to automatically find the
matching model summary files for a given system summary file
(cf. docstrings for system_filename_pattern and
model_filename_pattern).
system_dir: Path of directory containing
system summaries.
system_filename_pattern: Regex string for matching
system summary filenames.
model_dir: Path of directory containing
model summaries.
model_filename_pattern: Regex string for matching model
summary filenames.
config_file_path: Path of the configuration file.
system_id: Optional system ID string which
will appear in the ROUGE output.
"""
system_filenames = [f for f in os.listdir(system_dir)]
system_models_tuples = []
system_filename_pattern = re.compile(system_filename_pattern)
for system_filename in sorted(system_filenames):
match = system_filename_pattern.match(system_filename)
if match:
id = match.groups(0)[0]
model_filenames = [model_filename_pattern.replace('#ID#', id)]
# model_filenames = Rouge155.__get_model_filenames_for_id(
# id, model_dir, model_filename_pattern)
system_models_tuples.append(
(system_filename, sorted(model_filenames)))
if not system_models_tuples:
raise Exception(
"Did not find any files matching the pattern {} "
"in the system summaries directory {}.".format(
system_filename_pattern.pattern, system_dir))
with codecs.open(config_file_path, 'w', encoding='utf-8') as f:
f.write('<ROUGE-EVAL version="1.55">')
for task_id, (system_filename, model_filenames) in enumerate(
system_models_tuples, start=1):
eval_string = Rouge155.__get_eval_string(
task_id, system_id,
system_dir, system_filename,
model_dir, model_filenames)
f.write(eval_string)
f.write("</ROUGE-EVAL>") | [
"def",
"write_config_static",
"(",
"system_dir",
",",
"system_filename_pattern",
",",
"model_dir",
",",
"model_filename_pattern",
",",
"config_file_path",
",",
"system_id",
"=",
"None",
")",
":",
"system_filenames",
"=",
"[",
"f",
"for",
"f",
"in",
"os",
".",
"l... | https://github.com/microsoft/unilm/blob/65f15af2a307ebb64cfb25adf54375b002e6fe8d/unilm-v1/src/cnndm/bs_pyrouge.py#L271-L326 | ||
MediaBrowser/plugin.video.emby | 71162fc7704656833d8b228dc9014f88742215b1 | libraries/requests/packages/urllib3/packages/ordered_dict.py | python | OrderedDict.values | (self) | return [self[key] for key in self] | od.values() -> list of values in od | od.values() -> list of values in od | [
"od",
".",
"values",
"()",
"-",
">",
"list",
"of",
"values",
"in",
"od"
] | def values(self):
'od.values() -> list of values in od'
return [self[key] for key in self] | [
"def",
"values",
"(",
"self",
")",
":",
"return",
"[",
"self",
"[",
"key",
"]",
"for",
"key",
"in",
"self",
"]"
] | https://github.com/MediaBrowser/plugin.video.emby/blob/71162fc7704656833d8b228dc9014f88742215b1/libraries/requests/packages/urllib3/packages/ordered_dict.py#L120-L122 | |
mrJean1/PyGeodesy | 7da5ca71aa3edb7bc49e219e0b8190686e1a7965 | pygeodesy/utily.py | python | atan2b | (y, x) | return d | Return C{atan2(B{y}, B{x})} in degrees M{[0..+360]}.
@see: Function L{pygeodesy.atan2d}. | Return C{atan2(B{y}, B{x})} in degrees M{[0..+360]}. | [
"Return",
"C",
"{",
"atan2",
"(",
"B",
"{",
"y",
"}",
"B",
"{",
"x",
"}",
")",
"}",
"in",
"degrees",
"M",
"{",
"[",
"0",
"..",
"+",
"360",
"]",
"}",
"."
] | def atan2b(y, x):
'''Return C{atan2(B{y}, B{x})} in degrees M{[0..+360]}.
@see: Function L{pygeodesy.atan2d}.
'''
d = atan2d(y, x)
if d < 0:
d += _360_0
return d | [
"def",
"atan2b",
"(",
"y",
",",
"x",
")",
":",
"d",
"=",
"atan2d",
"(",
"y",
",",
"x",
")",
"if",
"d",
"<",
"0",
":",
"d",
"+=",
"_360_0",
"return",
"d"
] | https://github.com/mrJean1/PyGeodesy/blob/7da5ca71aa3edb7bc49e219e0b8190686e1a7965/pygeodesy/utily.py#L79-L87 | |
makerbot/ReplicatorG | d6f2b07785a5a5f1e172fb87cb4303b17c575d5d | skein_engines/skeinforge-35/skeinforge_application/skeinforge_plugins/craft_plugins/raft.py | python | RaftSkein.addEmptyLayerSupport | ( self, boundaryLayerIndex ) | Add support material to a layer if it is empty. | Add support material to a layer if it is empty. | [
"Add",
"support",
"material",
"to",
"a",
"layer",
"if",
"it",
"is",
"empty",
"."
] | def addEmptyLayerSupport( self, boundaryLayerIndex ):
"Add support material to a layer if it is empty."
supportLayer = SupportLayer( [] )
self.supportLayers.append( supportLayer )
if len( self.boundaryLayers[ boundaryLayerIndex ].loops ) > 0:
return
aboveXIntersectionsTable = {}
euclidean.addXIntersectionsFromLoopsForTable( self.getInsetLoopsAbove( boundaryLayerIndex ), aboveXIntersectionsTable, self.interfaceStep )
belowXIntersectionsTable = {}
euclidean.addXIntersectionsFromLoopsForTable( self.getInsetLoopsBelow( boundaryLayerIndex ), belowXIntersectionsTable, self.interfaceStep )
supportLayer.xIntersectionsTable = euclidean.getIntersectionOfXIntersectionsTables( [ aboveXIntersectionsTable, belowXIntersectionsTable ] ) | [
"def",
"addEmptyLayerSupport",
"(",
"self",
",",
"boundaryLayerIndex",
")",
":",
"supportLayer",
"=",
"SupportLayer",
"(",
"[",
"]",
")",
"self",
".",
"supportLayers",
".",
"append",
"(",
"supportLayer",
")",
"if",
"len",
"(",
"self",
".",
"boundaryLayers",
... | https://github.com/makerbot/ReplicatorG/blob/d6f2b07785a5a5f1e172fb87cb4303b17c575d5d/skein_engines/skeinforge-35/skeinforge_application/skeinforge_plugins/craft_plugins/raft.py#L463-L473 | ||
andyzsf/TuShare | 92787ad0cd492614bdb6389b71a19c80d1c8c9ae | tushare/futures/ctp/futures/__init__.py | python | TraderApi.OnRspOrderAction | (self, pInputOrderAction, pRspInfo, nRequestID, bIsLast) | 报单操作请求响应 | 报单操作请求响应 | [
"报单操作请求响应"
] | def OnRspOrderAction(self, pInputOrderAction, pRspInfo, nRequestID, bIsLast):
"""报单操作请求响应""" | [
"def",
"OnRspOrderAction",
"(",
"self",
",",
"pInputOrderAction",
",",
"pRspInfo",
",",
"nRequestID",
",",
"bIsLast",
")",
":"
] | https://github.com/andyzsf/TuShare/blob/92787ad0cd492614bdb6389b71a19c80d1c8c9ae/tushare/futures/ctp/futures/__init__.py#L412-L413 | ||
ermongroup/ncsn | 7f27f4a16471d20a0af3be8b8b4c2ec57c8a0bc1 | models/pix2pix.py | python | GANLoss.__call__ | (self, prediction, target_is_real) | return loss | Calculate loss given Discriminator's output and grount truth labels.
Parameters:
prediction (tensor) - - tpyically the prediction output from a discriminator
target_is_real (bool) - - if the ground truth label is for real images or fake images
Returns:
the calculated loss. | Calculate loss given Discriminator's output and grount truth labels. | [
"Calculate",
"loss",
"given",
"Discriminator",
"s",
"output",
"and",
"grount",
"truth",
"labels",
"."
] | def __call__(self, prediction, target_is_real):
"""Calculate loss given Discriminator's output and grount truth labels.
Parameters:
prediction (tensor) - - tpyically the prediction output from a discriminator
target_is_real (bool) - - if the ground truth label is for real images or fake images
Returns:
the calculated loss.
"""
if self.gan_mode in ['lsgan', 'vanilla']:
target_tensor = self.get_target_tensor(prediction, target_is_real)
loss = self.loss(prediction, target_tensor)
elif self.gan_mode == 'wgangp':
if target_is_real:
loss = -prediction.mean()
else:
loss = prediction.mean()
return loss | [
"def",
"__call__",
"(",
"self",
",",
"prediction",
",",
"target_is_real",
")",
":",
"if",
"self",
".",
"gan_mode",
"in",
"[",
"'lsgan'",
",",
"'vanilla'",
"]",
":",
"target_tensor",
"=",
"self",
".",
"get_target_tensor",
"(",
"prediction",
",",
"target_is_re... | https://github.com/ermongroup/ncsn/blob/7f27f4a16471d20a0af3be8b8b4c2ec57c8a0bc1/models/pix2pix.py#L254-L272 | |
holzschu/Carnets | 44effb10ddfc6aa5c8b0687582a724ba82c6b547 | Library/lib/python3.7/site-packages/sympy/core/expr.py | python | Expr.as_coeff_Add | (self, rational=False) | return S.Zero, self | Efficiently extract the coefficient of a summation. | Efficiently extract the coefficient of a summation. | [
"Efficiently",
"extract",
"the",
"coefficient",
"of",
"a",
"summation",
"."
] | def as_coeff_Add(self, rational=False):
"""Efficiently extract the coefficient of a summation. """
return S.Zero, self | [
"def",
"as_coeff_Add",
"(",
"self",
",",
"rational",
"=",
"False",
")",
":",
"return",
"S",
".",
"Zero",
",",
"self"
] | https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/sympy/core/expr.py#L3320-L3322 | |
reviewboard/reviewboard | 7395902e4c181bcd1d633f61105012ffb1d18e1b | contrib/internal/prepare-dev.py | python | install_git_hooks | () | Install a post-checkout hook to delete pyc files. | Install a post-checkout hook to delete pyc files. | [
"Install",
"a",
"post",
"-",
"checkout",
"hook",
"to",
"delete",
"pyc",
"files",
"."
] | def install_git_hooks():
"""Install a post-checkout hook to delete pyc files."""
console.header('Setting up your Git tree')
console.print(
'Your Git tree will be set up with a default post-checkout hook '
'that clears any compiled Python files when switching branches.')
try:
gitdir = (
subprocess.check_output(['git', 'rev-parse', '--git-common-dir'])
.decode('utf-8')
.strip()
)
except subprocess.CalledProcessError:
console.error('Could not determine git directory. Are you in a '
'checkout?')
return
hook_path = os.path.join(gitdir, 'hooks', 'post-checkout')
exc_mask = stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH
try:
statinfo = os.stat(hook_path)
except OSError:
# The file does not exist.
statinfo = None
if statinfo:
# The file exists. We need to determine if we should write to it.
if statinfo.st_size != 0 and statinfo.st_mode & exc_mask:
# The file is non-empty and executable, which means this *isn't*
# the default hook that git installs when you create a new
# repository.
#
# Let's check the hook's contents to see if its a hook we installed
# previously or if the user has already set up their own hook.
with open(hook_path, 'r') as f:
contents = f.read()
if contents != _POST_CHECKOUT:
console.error(
'The hook "%(hook_path)s" already exists and differs '
'from the hook we would install. The existing hook '
'will be left alone.'
'\n'
'If you want this hook installed, please add the '
'following to that file:'
'\n'
'%(script)s'
% {
'hook_path': hook_path,
'script': '\n'.join(_POST_CHECKOUT.split('\n')[1:]),
})
return
# At this point we know we are safe to write to the hook file. This is
# because one of the following is true:
#
# 1. The hook file does not exist.
# 2. The hook file exists but is empty.
# 3. The hook file exists but is non-executable (i.e., it contains a
# sample git hook).
with open(hook_path, 'w') as f:
f.write(_POST_CHECKOUT)
os.fchmod(f.fileno(), 0o740)
console.print('The post-checkout hook has been installed.') | [
"def",
"install_git_hooks",
"(",
")",
":",
"console",
".",
"header",
"(",
"'Setting up your Git tree'",
")",
"console",
".",
"print",
"(",
"'Your Git tree will be set up with a default post-checkout hook '",
"'that clears any compiled Python files when switching branches.'",
")",
... | https://github.com/reviewboard/reviewboard/blob/7395902e4c181bcd1d633f61105012ffb1d18e1b/contrib/internal/prepare-dev.py#L101-L170 | ||
mozillazg/pypy | 2ff5cd960c075c991389f842c6d59e71cf0cb7d0 | lib-python/2.7/pydoc.py | python | gui | () | Graphical interface (starts web server and pops up a control window). | Graphical interface (starts web server and pops up a control window). | [
"Graphical",
"interface",
"(",
"starts",
"web",
"server",
"and",
"pops",
"up",
"a",
"control",
"window",
")",
"."
] | def gui():
"""Graphical interface (starts web server and pops up a control window)."""
class GUI:
def __init__(self, window, port=7464):
self.window = window
self.server = None
self.scanner = None
import Tkinter
self.server_frm = Tkinter.Frame(window)
self.title_lbl = Tkinter.Label(self.server_frm,
text='Starting server...\n ')
self.open_btn = Tkinter.Button(self.server_frm,
text='open browser', command=self.open, state='disabled')
self.quit_btn = Tkinter.Button(self.server_frm,
text='quit serving', command=self.quit, state='disabled')
self.search_frm = Tkinter.Frame(window)
self.search_lbl = Tkinter.Label(self.search_frm, text='Search for')
self.search_ent = Tkinter.Entry(self.search_frm)
self.search_ent.bind('<Return>', self.search)
self.stop_btn = Tkinter.Button(self.search_frm,
text='stop', pady=0, command=self.stop, state='disabled')
if sys.platform == 'win32':
# Trying to hide and show this button crashes under Windows.
self.stop_btn.pack(side='right')
self.window.title('pydoc')
self.window.protocol('WM_DELETE_WINDOW', self.quit)
self.title_lbl.pack(side='top', fill='x')
self.open_btn.pack(side='left', fill='x', expand=1)
self.quit_btn.pack(side='right', fill='x', expand=1)
self.server_frm.pack(side='top', fill='x')
self.search_lbl.pack(side='left')
self.search_ent.pack(side='right', fill='x', expand=1)
self.search_frm.pack(side='top', fill='x')
self.search_ent.focus_set()
font = ('helvetica', sys.platform == 'win32' and 8 or 10)
self.result_lst = Tkinter.Listbox(window, font=font, height=6)
self.result_lst.bind('<Button-1>', self.select)
self.result_lst.bind('<Double-Button-1>', self.goto)
self.result_scr = Tkinter.Scrollbar(window,
orient='vertical', command=self.result_lst.yview)
self.result_lst.config(yscrollcommand=self.result_scr.set)
self.result_frm = Tkinter.Frame(window)
self.goto_btn = Tkinter.Button(self.result_frm,
text='go to selected', command=self.goto)
self.hide_btn = Tkinter.Button(self.result_frm,
text='hide results', command=self.hide)
self.goto_btn.pack(side='left', fill='x', expand=1)
self.hide_btn.pack(side='right', fill='x', expand=1)
self.window.update()
self.minwidth = self.window.winfo_width()
self.minheight = self.window.winfo_height()
self.bigminheight = (self.server_frm.winfo_reqheight() +
self.search_frm.winfo_reqheight() +
self.result_lst.winfo_reqheight() +
self.result_frm.winfo_reqheight())
self.bigwidth, self.bigheight = self.minwidth, self.bigminheight
self.expanded = 0
self.window.wm_geometry('%dx%d' % (self.minwidth, self.minheight))
self.window.wm_minsize(self.minwidth, self.minheight)
self.window.tk.willdispatch()
import threading
threading.Thread(
target=serve, args=(port, self.ready, self.quit)).start()
def ready(self, server):
self.server = server
self.title_lbl.config(
text='Python documentation server at\n' + server.url)
self.open_btn.config(state='normal')
self.quit_btn.config(state='normal')
def open(self, event=None, url=None):
url = url or self.server.url
try:
import webbrowser
webbrowser.open(url)
except ImportError: # pre-webbrowser.py compatibility
if sys.platform == 'win32':
os.system('start "%s"' % url)
else:
rc = os.system('netscape -remote "openURL(%s)" &' % url)
if rc: os.system('netscape "%s" &' % url)
def quit(self, event=None):
if self.server:
self.server.quit = 1
self.window.quit()
def search(self, event=None):
key = self.search_ent.get()
self.stop_btn.pack(side='right')
self.stop_btn.config(state='normal')
self.search_lbl.config(text='Searching for "%s"...' % key)
self.search_ent.forget()
self.search_lbl.pack(side='left')
self.result_lst.delete(0, 'end')
self.goto_btn.config(state='disabled')
self.expand()
import threading
if self.scanner:
self.scanner.quit = 1
self.scanner = ModuleScanner()
def onerror(modname):
pass
threading.Thread(target=self.scanner.run,
args=(self.update, key, self.done),
kwargs=dict(onerror=onerror)).start()
def update(self, path, modname, desc):
if modname[-9:] == '.__init__':
modname = modname[:-9] + ' (package)'
self.result_lst.insert('end',
modname + ' - ' + (desc or '(no description)'))
def stop(self, event=None):
if self.scanner:
self.scanner.quit = 1
self.scanner = None
def done(self):
self.scanner = None
self.search_lbl.config(text='Search for')
self.search_lbl.pack(side='left')
self.search_ent.pack(side='right', fill='x', expand=1)
if sys.platform != 'win32': self.stop_btn.forget()
self.stop_btn.config(state='disabled')
def select(self, event=None):
self.goto_btn.config(state='normal')
def goto(self, event=None):
selection = self.result_lst.curselection()
if selection:
modname = split(self.result_lst.get(selection[0]))[0]
self.open(url=self.server.url + modname + '.html')
def collapse(self):
if not self.expanded: return
self.result_frm.forget()
self.result_scr.forget()
self.result_lst.forget()
self.bigwidth = self.window.winfo_width()
self.bigheight = self.window.winfo_height()
self.window.wm_geometry('%dx%d' % (self.minwidth, self.minheight))
self.window.wm_minsize(self.minwidth, self.minheight)
self.expanded = 0
def expand(self):
if self.expanded: return
self.result_frm.pack(side='bottom', fill='x')
self.result_scr.pack(side='right', fill='y')
self.result_lst.pack(side='top', fill='both', expand=1)
self.window.wm_geometry('%dx%d' % (self.bigwidth, self.bigheight))
self.window.wm_minsize(self.minwidth, self.bigminheight)
self.expanded = 1
def hide(self, event=None):
self.stop()
self.collapse()
import Tkinter
try:
root = Tkinter.Tk()
# Tk will crash if pythonw.exe has an XP .manifest
# file and the root has is not destroyed explicitly.
# If the problem is ever fixed in Tk, the explicit
# destroy can go.
try:
gui = GUI(root)
root.mainloop()
finally:
root.destroy()
except KeyboardInterrupt:
pass | [
"def",
"gui",
"(",
")",
":",
"class",
"GUI",
":",
"def",
"__init__",
"(",
"self",
",",
"window",
",",
"port",
"=",
"7464",
")",
":",
"self",
".",
"window",
"=",
"window",
"self",
".",
"server",
"=",
"None",
"self",
".",
"scanner",
"=",
"None",
"i... | https://github.com/mozillazg/pypy/blob/2ff5cd960c075c991389f842c6d59e71cf0cb7d0/lib-python/2.7/pydoc.py#L2149-L2331 | ||
OmniSharp/omnisharp-sublime | 19baf3c4d350193af0f8da1ae5a8df0fa6cded61 | lib/view/_view.py | python | rowwidth | (view, row) | return view.rowcol(view.line(view.text_point(row, 0)).end())[1] + 1 | Returns the 1-based number of characters of ``row`` in ``view``. | Returns the 1-based number of characters of ``row`` in ``view``. | [
"Returns",
"the",
"1",
"-",
"based",
"number",
"of",
"characters",
"of",
"row",
"in",
"view",
"."
] | def rowwidth(view, row):
"""Returns the 1-based number of characters of ``row`` in ``view``.
"""
return view.rowcol(view.line(view.text_point(row, 0)).end())[1] + 1 | [
"def",
"rowwidth",
"(",
"view",
",",
"row",
")",
":",
"return",
"view",
".",
"rowcol",
"(",
"view",
".",
"line",
"(",
"view",
".",
"text_point",
"(",
"row",
",",
"0",
")",
")",
".",
"end",
"(",
")",
")",
"[",
"1",
"]",
"+",
"1"
] | https://github.com/OmniSharp/omnisharp-sublime/blob/19baf3c4d350193af0f8da1ae5a8df0fa6cded61/lib/view/_view.py#L141-L144 | |
yeti-platform/yeti | fcd3ee3d3d064df772d0392c20c22aad2bc4c8e6 | extras/yeti_to_elasticsearch.py | python | YetiFeedSender.__init__ | (
self,
elastic_index,
excluded_feeds=set(),
mongo_client=None,
mongo_hostname="localhost",
elastic_instance=None,
elastic_hostname=None,
elastic_port=9200,
elastic_user=None,
elastic_pass=None,
elastic_use_ssl=None,
elastic_verify_certs=None,
) | This class connects to YETI's MongoDB and to Elasticsearch.
It parses the observable collection in YETI's MongoDB and sends to Elasticsearch.
:param elastic_index: Elastic Stack index name.
:param excluded_feeds: Set that includes feeds to exclude from indexing.
:param mongo_client: Mongodb client.
:param mongo_hostname: Mongodb hostname.
:param elastic_instance: Elastic Stack connection instance.
:param elastic_hostname: Elastic Stack hostname.
:param elastic_port: Elastic Stack indexing port.
:param elastic_user: Elastic Stack user.
:param elastic_pass: Elastic Stack password.
:param elastic_use_ssl: Boolean. Flag to determine if the connection to Elastic Stack should use SSL.
:param elastic_verify_certs: Boolean. Flag to determine if the connection to Elastic Stack should verify the certificate. | This class connects to YETI's MongoDB and to Elasticsearch.
It parses the observable collection in YETI's MongoDB and sends to Elasticsearch.
:param elastic_index: Elastic Stack index name.
:param excluded_feeds: Set that includes feeds to exclude from indexing.
:param mongo_client: Mongodb client.
:param mongo_hostname: Mongodb hostname.
:param elastic_instance: Elastic Stack connection instance.
:param elastic_hostname: Elastic Stack hostname.
:param elastic_port: Elastic Stack indexing port.
:param elastic_user: Elastic Stack user.
:param elastic_pass: Elastic Stack password.
:param elastic_use_ssl: Boolean. Flag to determine if the connection to Elastic Stack should use SSL.
:param elastic_verify_certs: Boolean. Flag to determine if the connection to Elastic Stack should verify the certificate. | [
"This",
"class",
"connects",
"to",
"YETI",
"s",
"MongoDB",
"and",
"to",
"Elasticsearch",
".",
"It",
"parses",
"the",
"observable",
"collection",
"in",
"YETI",
"s",
"MongoDB",
"and",
"sends",
"to",
"Elasticsearch",
".",
":",
"param",
"elastic_index",
":",
"El... | def __init__(
self,
elastic_index,
excluded_feeds=set(),
mongo_client=None,
mongo_hostname="localhost",
elastic_instance=None,
elastic_hostname=None,
elastic_port=9200,
elastic_user=None,
elastic_pass=None,
elastic_use_ssl=None,
elastic_verify_certs=None,
):
"""
This class connects to YETI's MongoDB and to Elasticsearch.
It parses the observable collection in YETI's MongoDB and sends to Elasticsearch.
:param elastic_index: Elastic Stack index name.
:param excluded_feeds: Set that includes feeds to exclude from indexing.
:param mongo_client: Mongodb client.
:param mongo_hostname: Mongodb hostname.
:param elastic_instance: Elastic Stack connection instance.
:param elastic_hostname: Elastic Stack hostname.
:param elastic_port: Elastic Stack indexing port.
:param elastic_user: Elastic Stack user.
:param elastic_pass: Elastic Stack password.
:param elastic_use_ssl: Boolean. Flag to determine if the connection to Elastic Stack should use SSL.
:param elastic_verify_certs: Boolean. Flag to determine if the connection to Elastic Stack should verify the certificate.
"""
self.elastic_index = elastic_index
self.excluded_feeds = excluded_feeds
if mongo_client:
self.mongo_client = mongo_client
else:
mongo_hostname = mongo_hostname
self.create_mongo_connection(mongo_hostname)
if elastic_instance:
self.elastic_instance = elastic_instance
else:
elastic_hostname = elastic_hostname
elastic_port = elastic_port
elastic_user = elastic_user
elastic_pass = elastic_pass
elastic_use_ssl = elastic_use_ssl
elastic_verify_certs = elastic_verify_certs
self.create_elastic_connection(
elastic_hostname,
elastic_port,
use_ssl=elastic_use_ssl,
verify_certs=elastic_verify_certs,
username=elastic_user,
password=elastic_pass,
) | [
"def",
"__init__",
"(",
"self",
",",
"elastic_index",
",",
"excluded_feeds",
"=",
"set",
"(",
")",
",",
"mongo_client",
"=",
"None",
",",
"mongo_hostname",
"=",
"\"localhost\"",
",",
"elastic_instance",
"=",
"None",
",",
"elastic_hostname",
"=",
"None",
",",
... | https://github.com/yeti-platform/yeti/blob/fcd3ee3d3d064df772d0392c20c22aad2bc4c8e6/extras/yeti_to_elasticsearch.py#L45-L101 | ||
Kismuz/btgym | 7fb3316e67f1d7a17c620630fb62fb29428b2cec | btgym/research/model_based/aac.py | python | AMLDG.start | (self, sess, summary_writer, **kwargs) | Executes all initializing operations,
starts environment runner[s].
Supposed to be called by parent worker just before training loop starts.
Args:
sess: tf session object.
kwargs: not used by default. | Executes all initializing operations,
starts environment runner[s].
Supposed to be called by parent worker just before training loop starts. | [
"Executes",
"all",
"initializing",
"operations",
"starts",
"environment",
"runner",
"[",
"s",
"]",
".",
"Supposed",
"to",
"be",
"called",
"by",
"parent",
"worker",
"just",
"before",
"training",
"loop",
"starts",
"."
] | def start(self, sess, summary_writer, **kwargs):
"""
Executes all initializing operations,
starts environment runner[s].
Supposed to be called by parent worker just before training loop starts.
Args:
sess: tf session object.
kwargs: not used by default.
"""
try:
# Copy weights from global to local:
sess.run(self.critic_aac.sync_pi)
sess.run(self.actor_aac.sync_pi)
# Start thread_runners:
self.critic_aac._start_runners( # master first
sess,
summary_writer,
init_context=None,
data_sample_config=self.critic_aac.get_sample_config(mode=1)
)
self.actor_aac._start_runners(
sess,
summary_writer,
init_context=None,
data_sample_config=self.actor_aac.get_sample_config(mode=0)
)
self.summary_writer = summary_writer
self.log.notice('Runners started.')
except:
msg = 'start() exception occurred' + \
'\n\nPress `Ctrl-C` or jupyter:[Kernel]->[Interrupt] for clean exit.\n'
self.log.exception(msg)
raise RuntimeError(msg) | [
"def",
"start",
"(",
"self",
",",
"sess",
",",
"summary_writer",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"# Copy weights from global to local:",
"sess",
".",
"run",
"(",
"self",
".",
"critic_aac",
".",
"sync_pi",
")",
"sess",
".",
"run",
"(",
"sel... | https://github.com/Kismuz/btgym/blob/7fb3316e67f1d7a17c620630fb62fb29428b2cec/btgym/research/model_based/aac.py#L328-L364 | ||
malllabiisc/CompGCN | 3b06f5fec42526faa81afc158df9e64a8382982c | model/compgcn_conv.py | python | CompGCNConv.update | (self, aggr_out) | return aggr_out | [] | def update(self, aggr_out):
return aggr_out | [
"def",
"update",
"(",
"self",
",",
"aggr_out",
")",
":",
"return",
"aggr_out"
] | https://github.com/malllabiisc/CompGCN/blob/3b06f5fec42526faa81afc158df9e64a8382982c/model/compgcn_conv.py#L69-L70 | |||
partho-maple/coding-interview-gym | f9b28916da31935a27900794cfb8b91be3b38b9b | leetcode.com/python/278_First_Bad_Version.py | python | Solution.firstBadVersion | (self, n) | return left | :type n: int
:rtype: int | :type n: int
:rtype: int | [
":",
"type",
"n",
":",
"int",
":",
"rtype",
":",
"int"
] | def firstBadVersion(self, n):
"""
:type n: int
:rtype: int
"""
left, right = 0, n
while left < right:
mid = (left + right) // 2
isBad = isBadVersion(mid)
if isBad:
right = mid
else:
left = mid + 1
return left | [
"def",
"firstBadVersion",
"(",
"self",
",",
"n",
")",
":",
"left",
",",
"right",
"=",
"0",
",",
"n",
"while",
"left",
"<",
"right",
":",
"mid",
"=",
"(",
"left",
"+",
"right",
")",
"//",
"2",
"isBad",
"=",
"isBadVersion",
"(",
"mid",
")",
"if",
... | https://github.com/partho-maple/coding-interview-gym/blob/f9b28916da31935a27900794cfb8b91be3b38b9b/leetcode.com/python/278_First_Bad_Version.py#L7-L20 | |
tp4a/teleport | 1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad | server/www/packages/packages-linux/x64/tornado/web.py | python | StaticFileHandler.should_return_304 | (self) | return False | Returns True if the headers indicate that we should return 304.
.. versionadded:: 3.1 | Returns True if the headers indicate that we should return 304. | [
"Returns",
"True",
"if",
"the",
"headers",
"indicate",
"that",
"we",
"should",
"return",
"304",
"."
] | def should_return_304(self) -> bool:
"""Returns True if the headers indicate that we should return 304.
.. versionadded:: 3.1
"""
# If client sent If-None-Match, use it, ignore If-Modified-Since
if self.request.headers.get("If-None-Match"):
return self.check_etag_header()
# Check the If-Modified-Since, and don't send the result if the
# content has not been modified
ims_value = self.request.headers.get("If-Modified-Since")
if ims_value is not None:
date_tuple = email.utils.parsedate(ims_value)
if date_tuple is not None:
if_since = datetime.datetime(*date_tuple[:6])
assert self.modified is not None
if if_since >= self.modified:
return True
return False | [
"def",
"should_return_304",
"(",
"self",
")",
"->",
"bool",
":",
"# If client sent If-None-Match, use it, ignore If-Modified-Since",
"if",
"self",
".",
"request",
".",
"headers",
".",
"get",
"(",
"\"If-None-Match\"",
")",
":",
"return",
"self",
".",
"check_etag_header... | https://github.com/tp4a/teleport/blob/1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad/server/www/packages/packages-linux/x64/tornado/web.py#L2699-L2719 | |
leapcode/bitmask_client | d2fe20df24fc6eaf146fa5ce1e847de6ab515688 | src/leap/bitmask/gui/passwordwindow.py | python | PasswordWindow._change_password | (self) | TRIGGERS:
self.ui.buttonBox.accepted
Changes the user's password if the inputboxes are correctly filled. | TRIGGERS:
self.ui.buttonBox.accepted | [
"TRIGGERS",
":",
"self",
".",
"ui",
".",
"buttonBox",
".",
"accepted"
] | def _change_password(self):
"""
TRIGGERS:
self.ui.buttonBox.accepted
Changes the user's password if the inputboxes are correctly filled.
"""
current_password = self.ui.current_password_lineedit.text()
new_password = self.ui.new_password_lineedit.text()
new_password2 = self.ui.new_password_confirmation_lineedit.text()
self._enable_password_widgets(True)
if len(current_password) == 0:
self.flash_error(self.tr("Password is empty."))
self.ui.current_password_lineedit.setFocus()
return
ok, msg, field = password_checks(self.account.username, new_password,
new_password2)
if not ok:
self.flash_error(msg)
if field == 'new_password':
self.ui.new_password_lineedit.setFocus()
elif field == 'new_password_confirmation':
self.ui.new_password_confirmation_lineedit.setFocus()
return
self._enable_password_widgets(False)
self.app.backend.user_change_password(
current_password=current_password,
new_password=new_password) | [
"def",
"_change_password",
"(",
"self",
")",
":",
"current_password",
"=",
"self",
".",
"ui",
".",
"current_password_lineedit",
".",
"text",
"(",
")",
"new_password",
"=",
"self",
".",
"ui",
".",
"new_password_lineedit",
".",
"text",
"(",
")",
"new_password2",... | https://github.com/leapcode/bitmask_client/blob/d2fe20df24fc6eaf146fa5ce1e847de6ab515688/src/leap/bitmask/gui/passwordwindow.py#L152-L183 | ||
mozillazg/pypy | 2ff5cd960c075c991389f842c6d59e71cf0cb7d0 | lib-python/2.7/traceback.py | python | _format_final_exc_line | (etype, value, _encoding=None) | return line | Return a list of a single line -- normal case for format_exception_only | Return a list of a single line -- normal case for format_exception_only | [
"Return",
"a",
"list",
"of",
"a",
"single",
"line",
"--",
"normal",
"case",
"for",
"format_exception_only"
] | def _format_final_exc_line(etype, value, _encoding=None):
"""Return a list of a single line -- normal case for format_exception_only"""
valuestr = _some_str(value, _encoding)
if value is None or not valuestr:
line = "%s\n" % etype
else:
line = "%s: %s\n" % (etype, valuestr)
return line | [
"def",
"_format_final_exc_line",
"(",
"etype",
",",
"value",
",",
"_encoding",
"=",
"None",
")",
":",
"valuestr",
"=",
"_some_str",
"(",
"value",
",",
"_encoding",
")",
"if",
"value",
"is",
"None",
"or",
"not",
"valuestr",
":",
"line",
"=",
"\"%s\\n\"",
... | https://github.com/mozillazg/pypy/blob/2ff5cd960c075c991389f842c6d59e71cf0cb7d0/lib-python/2.7/traceback.py#L203-L210 | |
zhl2008/awd-platform | 0416b31abea29743387b10b3914581fbe8e7da5e | web_flaskbb/Python-2.7.9/Lib/pkgutil.py | python | ImpLoader._get_delegate | (self) | return ImpImporter(self.filename).find_module('__init__') | [] | def _get_delegate(self):
return ImpImporter(self.filename).find_module('__init__') | [
"def",
"_get_delegate",
"(",
"self",
")",
":",
"return",
"ImpImporter",
"(",
"self",
".",
"filename",
")",
".",
"find_module",
"(",
"'__init__'",
")"
] | https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/Python-2.7.9/Lib/pkgutil.py#L314-L315 | |||
PaddlePaddle/PaddleSpeech | 26524031d242876b7fdb71582b0b3a7ea45c7d9d | paddlespeech/s2t/decoders/beam_search/beam_search.py | python | BeamSearch.search | (self, running_hyps: List[Hypothesis],
x: paddle.Tensor) | return best_hyps | Search new tokens for running hypotheses and encoded speech x.
Args:
running_hyps (List[Hypothesis]): Running hypotheses on beam
x (paddle.Tensor): Encoded speech feature (T, D)
Returns:
List[Hypotheses]: Best sorted hypotheses | Search new tokens for running hypotheses and encoded speech x. | [
"Search",
"new",
"tokens",
"for",
"running",
"hypotheses",
"and",
"encoded",
"speech",
"x",
"."
] | def search(self, running_hyps: List[Hypothesis],
x: paddle.Tensor) -> List[Hypothesis]:
"""Search new tokens for running hypotheses and encoded speech x.
Args:
running_hyps (List[Hypothesis]): Running hypotheses on beam
x (paddle.Tensor): Encoded speech feature (T, D)
Returns:
List[Hypotheses]: Best sorted hypotheses
"""
best_hyps = []
part_ids = paddle.arange(self.n_vocab) # no pre-beam
for hyp in running_hyps:
# scoring
weighted_scores = paddle.zeros([self.n_vocab], dtype=x.dtype)
scores, states = self.score_full(hyp, x)
for k in self.full_scorers:
weighted_scores += self.weights[k] * scores[k]
# partial scoring
if self.do_pre_beam:
pre_beam_scores = (weighted_scores
if self.pre_beam_score_key == "full" else
scores[self.pre_beam_score_key])
part_ids = paddle.topk(pre_beam_scores, self.pre_beam_size)[1]
part_scores, part_states = self.score_partial(hyp, part_ids, x)
for k in self.part_scorers:
weighted_scores[part_ids] += self.weights[k] * part_scores[k]
# add previous hyp score
weighted_scores += hyp.score
# update hyps
for j, part_j in zip(*self.beam(weighted_scores, part_ids)):
# `part_j` is `j` relative id in `part_scores`
# will be (2 x beam at most)
best_hyps.append(
Hypothesis(
score=weighted_scores[j],
yseq=self.append_token(hyp.yseq, j),
scores=self.merge_scores(hyp.scores, scores, j,
part_scores, part_j),
states=self.merge_states(states, part_states, part_j),
))
# sort and prune 2 x beam -> beam
best_hyps = sorted(
best_hyps, key=lambda x: x.score,
reverse=True)[:min(len(best_hyps), self.beam_size)]
return best_hyps | [
"def",
"search",
"(",
"self",
",",
"running_hyps",
":",
"List",
"[",
"Hypothesis",
"]",
",",
"x",
":",
"paddle",
".",
"Tensor",
")",
"->",
"List",
"[",
"Hypothesis",
"]",
":",
"best_hyps",
"=",
"[",
"]",
"part_ids",
"=",
"paddle",
".",
"arange",
"(",... | https://github.com/PaddlePaddle/PaddleSpeech/blob/26524031d242876b7fdb71582b0b3a7ea45c7d9d/paddlespeech/s2t/decoders/beam_search/beam_search.py#L301-L350 | |
khanhnamle1994/natural-language-processing | 01d450d5ac002b0156ef4cf93a07cb508c1bcdc5 | assignment1/.env/lib/python2.7/site-packages/pip/_vendor/pkg_resources/__init__.py | python | get_default_cache | () | return (
os.environ.get('PYTHON_EGG_CACHE')
or appdirs.user_cache_dir(appname='Python-Eggs')
) | Return the ``PYTHON_EGG_CACHE`` environment variable
or a platform-relevant user cache dir for an app
named "Python-Eggs". | Return the ``PYTHON_EGG_CACHE`` environment variable
or a platform-relevant user cache dir for an app
named "Python-Eggs". | [
"Return",
"the",
"PYTHON_EGG_CACHE",
"environment",
"variable",
"or",
"a",
"platform",
"-",
"relevant",
"user",
"cache",
"dir",
"for",
"an",
"app",
"named",
"Python",
"-",
"Eggs",
"."
] | def get_default_cache():
"""
Return the ``PYTHON_EGG_CACHE`` environment variable
or a platform-relevant user cache dir for an app
named "Python-Eggs".
"""
return (
os.environ.get('PYTHON_EGG_CACHE')
or appdirs.user_cache_dir(appname='Python-Eggs')
) | [
"def",
"get_default_cache",
"(",
")",
":",
"return",
"(",
"os",
".",
"environ",
".",
"get",
"(",
"'PYTHON_EGG_CACHE'",
")",
"or",
"appdirs",
".",
"user_cache_dir",
"(",
"appname",
"=",
"'Python-Eggs'",
")",
")"
] | https://github.com/khanhnamle1994/natural-language-processing/blob/01d450d5ac002b0156ef4cf93a07cb508c1bcdc5/assignment1/.env/lib/python2.7/site-packages/pip/_vendor/pkg_resources/__init__.py#L1361-L1370 | |
chainer/chainer | e9da1423255c58c37be9733f51b158aa9b39dc93 | chainer/__init__.py | python | is_debug | () | return bool(config.__getattr__('debug')) | Returns if the debug mode is enabled or not in the current thread.
Returns:
bool: ``True`` if the debug mode is enabled. | Returns if the debug mode is enabled or not in the current thread. | [
"Returns",
"if",
"the",
"debug",
"mode",
"is",
"enabled",
"or",
"not",
"in",
"the",
"current",
"thread",
"."
] | def is_debug():
"""Returns if the debug mode is enabled or not in the current thread.
Returns:
bool: ``True`` if the debug mode is enabled.
"""
return bool(config.__getattr__('debug')) | [
"def",
"is_debug",
"(",
")",
":",
"return",
"bool",
"(",
"config",
".",
"__getattr__",
"(",
"'debug'",
")",
")"
] | https://github.com/chainer/chainer/blob/e9da1423255c58c37be9733f51b158aa9b39dc93/chainer/__init__.py#L240-L246 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.