nwo
stringlengths 5
86
| sha
stringlengths 40
40
| path
stringlengths 4
189
| language
stringclasses 1
value | identifier
stringlengths 1
94
| parameters
stringlengths 2
4.03k
| argument_list
stringclasses 1
value | return_statement
stringlengths 0
11.5k
| docstring
stringlengths 1
33.2k
| docstring_summary
stringlengths 0
5.15k
| docstring_tokens
sequence | function
stringlengths 34
151k
| function_tokens
sequence | url
stringlengths 90
278
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
google/syzygy | 8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5 | third_party/numpy/files/numpy/distutils/system_info.py | python | system_info.check_libs | (self,lib_dir,libs,opt_libs =[]) | return info | If static or shared libraries are available then return
their info dictionary.
Checks for all libraries as shared libraries first, then
static (or vice versa if self.search_static_first is True). | If static or shared libraries are available then return
their info dictionary. | [
"If",
"static",
"or",
"shared",
"libraries",
"are",
"available",
"then",
"return",
"their",
"info",
"dictionary",
"."
] | def check_libs(self,lib_dir,libs,opt_libs =[]):
"""If static or shared libraries are available then return
their info dictionary.
Checks for all libraries as shared libraries first, then
static (or vice versa if self.search_static_first is True).
"""
exts = self.library_extensions()
info = None
for ext in exts:
info = self._check_libs(lib_dir,libs,opt_libs,[ext])
if info is not None:
break
if not info:
log.info(' libraries %s not found in %s', ','.join(libs), lib_dir)
return info | [
"def",
"check_libs",
"(",
"self",
",",
"lib_dir",
",",
"libs",
",",
"opt_libs",
"=",
"[",
"]",
")",
":",
"exts",
"=",
"self",
".",
"library_extensions",
"(",
")",
"info",
"=",
"None",
"for",
"ext",
"in",
"exts",
":",
"info",
"=",
"self",
".",
"_check_libs",
"(",
"lib_dir",
",",
"libs",
",",
"opt_libs",
",",
"[",
"ext",
"]",
")",
"if",
"info",
"is",
"not",
"None",
":",
"break",
"if",
"not",
"info",
":",
"log",
".",
"info",
"(",
"' libraries %s not found in %s'",
",",
"','",
".",
"join",
"(",
"libs",
")",
",",
"lib_dir",
")",
"return",
"info"
] | https://github.com/google/syzygy/blob/8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5/third_party/numpy/files/numpy/distutils/system_info.py#L582-L597 |
|
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | current/tools/inspector_protocol/jinja2/environment.py | python | Environment.get_or_select_template | (self, template_name_or_list,
parent=None, globals=None) | return self.select_template(template_name_or_list, parent, globals) | Does a typecheck and dispatches to :meth:`select_template`
if an iterable of template names is given, otherwise to
:meth:`get_template`.
.. versionadded:: 2.3 | Does a typecheck and dispatches to :meth:`select_template`
if an iterable of template names is given, otherwise to
:meth:`get_template`. | [
"Does",
"a",
"typecheck",
"and",
"dispatches",
"to",
":",
"meth",
":",
"select_template",
"if",
"an",
"iterable",
"of",
"template",
"names",
"is",
"given",
"otherwise",
"to",
":",
"meth",
":",
"get_template",
"."
] | def get_or_select_template(self, template_name_or_list,
parent=None, globals=None):
"""Does a typecheck and dispatches to :meth:`select_template`
if an iterable of template names is given, otherwise to
:meth:`get_template`.
.. versionadded:: 2.3
"""
if isinstance(template_name_or_list, string_types):
return self.get_template(template_name_or_list, parent, globals)
elif isinstance(template_name_or_list, Template):
return template_name_or_list
return self.select_template(template_name_or_list, parent, globals) | [
"def",
"get_or_select_template",
"(",
"self",
",",
"template_name_or_list",
",",
"parent",
"=",
"None",
",",
"globals",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"template_name_or_list",
",",
"string_types",
")",
":",
"return",
"self",
".",
"get_template",
"(",
"template_name_or_list",
",",
"parent",
",",
"globals",
")",
"elif",
"isinstance",
"(",
"template_name_or_list",
",",
"Template",
")",
":",
"return",
"template_name_or_list",
"return",
"self",
".",
"select_template",
"(",
"template_name_or_list",
",",
"parent",
",",
"globals",
")"
] | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/current/tools/inspector_protocol/jinja2/environment.py#L860-L872 |
|
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_misc.py | python | DateTime.__gt__ | (*args, **kwargs) | return _misc_.DateTime___gt__(*args, **kwargs) | __gt__(self, DateTime other) -> bool | __gt__(self, DateTime other) -> bool | [
"__gt__",
"(",
"self",
"DateTime",
"other",
")",
"-",
">",
"bool"
] | def __gt__(*args, **kwargs):
"""__gt__(self, DateTime other) -> bool"""
return _misc_.DateTime___gt__(*args, **kwargs) | [
"def",
"__gt__",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"DateTime___gt__",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_misc.py#L4114-L4116 |
|
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/python/ops/array_ops.py | python | _EditDistanceShape | (op) | return [tensor_shape.unknown_shape()] | Shape function for the EditDistance op. | Shape function for the EditDistance op. | [
"Shape",
"function",
"for",
"the",
"EditDistance",
"op",
"."
] | def _EditDistanceShape(op):
"""Shape function for the EditDistance op."""
hypothesis_shape = tensor_util.constant_value(op.inputs[2])
truth_shape = tensor_util.constant_value(op.inputs[5])
if hypothesis_shape is not None and truth_shape is not None:
if len(hypothesis_shape) != len(truth_shape):
raise ValueError(
"Inconsistent ranks in hypothesis and truth. Saw shapes: %s and %s" %
(str(hypothesis_shape), str(truth_shape)))
return [tensor_shape.TensorShape(
[max(h, t) for h, t in zip(hypothesis_shape[:-1], truth_shape[:-1])])]
return [tensor_shape.unknown_shape()] | [
"def",
"_EditDistanceShape",
"(",
"op",
")",
":",
"hypothesis_shape",
"=",
"tensor_util",
".",
"constant_value",
"(",
"op",
".",
"inputs",
"[",
"2",
"]",
")",
"truth_shape",
"=",
"tensor_util",
".",
"constant_value",
"(",
"op",
".",
"inputs",
"[",
"5",
"]",
")",
"if",
"hypothesis_shape",
"is",
"not",
"None",
"and",
"truth_shape",
"is",
"not",
"None",
":",
"if",
"len",
"(",
"hypothesis_shape",
")",
"!=",
"len",
"(",
"truth_shape",
")",
":",
"raise",
"ValueError",
"(",
"\"Inconsistent ranks in hypothesis and truth. Saw shapes: %s and %s\"",
"%",
"(",
"str",
"(",
"hypothesis_shape",
")",
",",
"str",
"(",
"truth_shape",
")",
")",
")",
"return",
"[",
"tensor_shape",
".",
"TensorShape",
"(",
"[",
"max",
"(",
"h",
",",
"t",
")",
"for",
"h",
",",
"t",
"in",
"zip",
"(",
"hypothesis_shape",
"[",
":",
"-",
"1",
"]",
",",
"truth_shape",
"[",
":",
"-",
"1",
"]",
")",
"]",
")",
"]",
"return",
"[",
"tensor_shape",
".",
"unknown_shape",
"(",
")",
"]"
] | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/python/ops/array_ops.py#L2225-L2237 |
|
cinder/Cinder | e83f5bb9c01a63eec20168d02953a0879e5100f7 | docs/libs/bs4/builder/_lxml.py | python | LXMLTreeBuilder.test_fragment_to_document | (self, fragment) | return u'<html><body>%s</body></html>' % fragment | See `TreeBuilder`. | See `TreeBuilder`. | [
"See",
"TreeBuilder",
"."
] | def test_fragment_to_document(self, fragment):
"""See `TreeBuilder`."""
return u'<html><body>%s</body></html>' % fragment | [
"def",
"test_fragment_to_document",
"(",
"self",
",",
"fragment",
")",
":",
"return",
"u'<html><body>%s</body></html>'",
"%",
"fragment"
] | https://github.com/cinder/Cinder/blob/e83f5bb9c01a63eec20168d02953a0879e5100f7/docs/libs/bs4/builder/_lxml.py#L231-L233 |
|
Harick1/caffe-yolo | eea92bf3ddfe4d0ff6b0b3ba9b15c029a83ed9a3 | python/caffe/draw.py | python | get_layer_label | (layer, rankdir) | return node_label | Define node label based on layer type.
Parameters
----------
layer : ?
rankdir : {'LR', 'TB', 'BT'}
Direction of graph layout.
Returns
-------
string :
A label for the current layer | Define node label based on layer type. | [
"Define",
"node",
"label",
"based",
"on",
"layer",
"type",
"."
] | def get_layer_label(layer, rankdir):
"""Define node label based on layer type.
Parameters
----------
layer : ?
rankdir : {'LR', 'TB', 'BT'}
Direction of graph layout.
Returns
-------
string :
A label for the current layer
"""
if rankdir in ('TB', 'BT'):
# If graph orientation is vertical, horizontal space is free and
# vertical space is not; separate words with spaces
separator = ' '
else:
# If graph orientation is horizontal, vertical space is free and
# horizontal space is not; separate words with newlines
separator = '\\n'
if layer.type == 'Convolution' or layer.type == 'Deconvolution':
# Outer double quotes needed or else colon characters don't parse
# properly
node_label = '"%s%s(%s)%skernel size: %d%sstride: %d%spad: %d"' %\
(layer.name,
separator,
layer.type,
separator,
layer.convolution_param.kernel_size[0] if len(layer.convolution_param.kernel_size._values) else 1,
separator,
layer.convolution_param.stride[0] if len(layer.convolution_param.stride._values) else 1,
separator,
layer.convolution_param.pad[0] if len(layer.convolution_param.pad._values) else 0)
elif layer.type == 'Pooling':
pooling_types_dict = get_pooling_types_dict()
node_label = '"%s%s(%s %s)%skernel size: %d%sstride: %d%spad: %d"' %\
(layer.name,
separator,
pooling_types_dict[layer.pooling_param.pool],
layer.type,
separator,
layer.pooling_param.kernel_size,
separator,
layer.pooling_param.stride,
separator,
layer.pooling_param.pad)
else:
node_label = '"%s%s(%s)"' % (layer.name, separator, layer.type)
return node_label | [
"def",
"get_layer_label",
"(",
"layer",
",",
"rankdir",
")",
":",
"if",
"rankdir",
"in",
"(",
"'TB'",
",",
"'BT'",
")",
":",
"# If graph orientation is vertical, horizontal space is free and",
"# vertical space is not; separate words with spaces",
"separator",
"=",
"' '",
"else",
":",
"# If graph orientation is horizontal, vertical space is free and",
"# horizontal space is not; separate words with newlines",
"separator",
"=",
"'\\\\n'",
"if",
"layer",
".",
"type",
"==",
"'Convolution'",
"or",
"layer",
".",
"type",
"==",
"'Deconvolution'",
":",
"# Outer double quotes needed or else colon characters don't parse",
"# properly",
"node_label",
"=",
"'\"%s%s(%s)%skernel size: %d%sstride: %d%spad: %d\"'",
"%",
"(",
"layer",
".",
"name",
",",
"separator",
",",
"layer",
".",
"type",
",",
"separator",
",",
"layer",
".",
"convolution_param",
".",
"kernel_size",
"[",
"0",
"]",
"if",
"len",
"(",
"layer",
".",
"convolution_param",
".",
"kernel_size",
".",
"_values",
")",
"else",
"1",
",",
"separator",
",",
"layer",
".",
"convolution_param",
".",
"stride",
"[",
"0",
"]",
"if",
"len",
"(",
"layer",
".",
"convolution_param",
".",
"stride",
".",
"_values",
")",
"else",
"1",
",",
"separator",
",",
"layer",
".",
"convolution_param",
".",
"pad",
"[",
"0",
"]",
"if",
"len",
"(",
"layer",
".",
"convolution_param",
".",
"pad",
".",
"_values",
")",
"else",
"0",
")",
"elif",
"layer",
".",
"type",
"==",
"'Pooling'",
":",
"pooling_types_dict",
"=",
"get_pooling_types_dict",
"(",
")",
"node_label",
"=",
"'\"%s%s(%s %s)%skernel size: %d%sstride: %d%spad: %d\"'",
"%",
"(",
"layer",
".",
"name",
",",
"separator",
",",
"pooling_types_dict",
"[",
"layer",
".",
"pooling_param",
".",
"pool",
"]",
",",
"layer",
".",
"type",
",",
"separator",
",",
"layer",
".",
"pooling_param",
".",
"kernel_size",
",",
"separator",
",",
"layer",
".",
"pooling_param",
".",
"stride",
",",
"separator",
",",
"layer",
".",
"pooling_param",
".",
"pad",
")",
"else",
":",
"node_label",
"=",
"'\"%s%s(%s)\"'",
"%",
"(",
"layer",
".",
"name",
",",
"separator",
",",
"layer",
".",
"type",
")",
"return",
"node_label"
] | https://github.com/Harick1/caffe-yolo/blob/eea92bf3ddfe4d0ff6b0b3ba9b15c029a83ed9a3/python/caffe/draw.py#L62-L114 |
|
JarveeLee/SynthText_Chinese_version | 4b2cbc7d14741f21d0bb17966a339ab3574b09a8 | synthgen.py | python | viz_masks | (fignum,rgb,seg,depth,label) | img,depth,seg are images of the same size.
visualizes depth masks for top NOBJ objects. | img,depth,seg are images of the same size.
visualizes depth masks for top NOBJ objects. | [
"img",
"depth",
"seg",
"are",
"images",
"of",
"the",
"same",
"size",
".",
"visualizes",
"depth",
"masks",
"for",
"top",
"NOBJ",
"objects",
"."
] | def viz_masks(fignum,rgb,seg,depth,label):
"""
img,depth,seg are images of the same size.
visualizes depth masks for top NOBJ objects.
"""
def mean_seg(rgb,seg,label):
mim = np.zeros_like(rgb)
for i in np.unique(seg.flat):
mask = seg==i
col = np.mean(rgb[mask,:],axis=0)
mim[mask,:] = col[None,None,:]
mim[seg==0,:] = 0
return mim
mim = mean_seg(rgb,seg,label)
img = rgb.copy()
for i,idx in enumerate(label):
mask = seg==idx
rgb_rand = (255*np.random.rand(3)).astype('uint8')
img[mask] = rgb_rand[None,None,:]
#import scipy
# scipy.misc.imsave('seg.png', mim)
# scipy.misc.imsave('depth.png', depth)
# scipy.misc.imsave('txt.png', rgb)
# scipy.misc.imsave('reg.png', img)
plt.close(fignum)
plt.figure(fignum)
ims = [rgb,mim,depth,img]
for i in xrange(len(ims)):
plt.subplot(2,2,i+1)
plt.imshow(ims[i])
print 'shape shows',ims[i].shape
plt.show(block=False) | [
"def",
"viz_masks",
"(",
"fignum",
",",
"rgb",
",",
"seg",
",",
"depth",
",",
"label",
")",
":",
"def",
"mean_seg",
"(",
"rgb",
",",
"seg",
",",
"label",
")",
":",
"mim",
"=",
"np",
".",
"zeros_like",
"(",
"rgb",
")",
"for",
"i",
"in",
"np",
".",
"unique",
"(",
"seg",
".",
"flat",
")",
":",
"mask",
"=",
"seg",
"==",
"i",
"col",
"=",
"np",
".",
"mean",
"(",
"rgb",
"[",
"mask",
",",
":",
"]",
",",
"axis",
"=",
"0",
")",
"mim",
"[",
"mask",
",",
":",
"]",
"=",
"col",
"[",
"None",
",",
"None",
",",
":",
"]",
"mim",
"[",
"seg",
"==",
"0",
",",
":",
"]",
"=",
"0",
"return",
"mim",
"mim",
"=",
"mean_seg",
"(",
"rgb",
",",
"seg",
",",
"label",
")",
"img",
"=",
"rgb",
".",
"copy",
"(",
")",
"for",
"i",
",",
"idx",
"in",
"enumerate",
"(",
"label",
")",
":",
"mask",
"=",
"seg",
"==",
"idx",
"rgb_rand",
"=",
"(",
"255",
"*",
"np",
".",
"random",
".",
"rand",
"(",
"3",
")",
")",
".",
"astype",
"(",
"'uint8'",
")",
"img",
"[",
"mask",
"]",
"=",
"rgb_rand",
"[",
"None",
",",
"None",
",",
":",
"]",
"#import scipy",
"# scipy.misc.imsave('seg.png', mim)",
"# scipy.misc.imsave('depth.png', depth)",
"# scipy.misc.imsave('txt.png', rgb)",
"# scipy.misc.imsave('reg.png', img)",
"plt",
".",
"close",
"(",
"fignum",
")",
"plt",
".",
"figure",
"(",
"fignum",
")",
"ims",
"=",
"[",
"rgb",
",",
"mim",
",",
"depth",
",",
"img",
"]",
"for",
"i",
"in",
"xrange",
"(",
"len",
"(",
"ims",
")",
")",
":",
"plt",
".",
"subplot",
"(",
"2",
",",
"2",
",",
"i",
"+",
"1",
")",
"plt",
".",
"imshow",
"(",
"ims",
"[",
"i",
"]",
")",
"print",
"'shape shows'",
",",
"ims",
"[",
"i",
"]",
".",
"shape",
"plt",
".",
"show",
"(",
"block",
"=",
"False",
")"
] | https://github.com/JarveeLee/SynthText_Chinese_version/blob/4b2cbc7d14741f21d0bb17966a339ab3574b09a8/synthgen.py#L290-L325 |
||
OGRECave/ogre-next | 287307980e6de8910f04f3cc0994451b075071fd | Tools/Wings3DExporter/mesh.py | python | Mesh.triangulate | (self) | triangulate polygons | triangulate polygons | [
"triangulate",
"polygons"
] | def triangulate(self):
"triangulate polygons"
print "tesselating..."
self.gltris = []
self.tri_materials = []
for i in range(len(self.glfaces)):
face = self.glfaces[i]
mat = self.face_materials[i]
if len(face) == 3:
self.gltris.append(face)
self.tri_materials.append(mat)
else:
verts = map(lambda vindex: Vector(self.glverts[vindex].pos), face)
# triangulate using ear clipping method
tris = pgon.triangulate(verts)
for tri in tris:
A, B, C = map(lambda pindex: face[pindex], tri)
self.gltris.append([A, B, C])
self.tri_materials.append(mat) | [
"def",
"triangulate",
"(",
"self",
")",
":",
"print",
"\"tesselating...\"",
"self",
".",
"gltris",
"=",
"[",
"]",
"self",
".",
"tri_materials",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"glfaces",
")",
")",
":",
"face",
"=",
"self",
".",
"glfaces",
"[",
"i",
"]",
"mat",
"=",
"self",
".",
"face_materials",
"[",
"i",
"]",
"if",
"len",
"(",
"face",
")",
"==",
"3",
":",
"self",
".",
"gltris",
".",
"append",
"(",
"face",
")",
"self",
".",
"tri_materials",
".",
"append",
"(",
"mat",
")",
"else",
":",
"verts",
"=",
"map",
"(",
"lambda",
"vindex",
":",
"Vector",
"(",
"self",
".",
"glverts",
"[",
"vindex",
"]",
".",
"pos",
")",
",",
"face",
")",
"# triangulate using ear clipping method",
"tris",
"=",
"pgon",
".",
"triangulate",
"(",
"verts",
")",
"for",
"tri",
"in",
"tris",
":",
"A",
",",
"B",
",",
"C",
"=",
"map",
"(",
"lambda",
"pindex",
":",
"face",
"[",
"pindex",
"]",
",",
"tri",
")",
"self",
".",
"gltris",
".",
"append",
"(",
"[",
"A",
",",
"B",
",",
"C",
"]",
")",
"self",
".",
"tri_materials",
".",
"append",
"(",
"mat",
")"
] | https://github.com/OGRECave/ogre-next/blob/287307980e6de8910f04f3cc0994451b075071fd/Tools/Wings3DExporter/mesh.py#L332-L354 |
||
olliw42/storm32bgc | 99d62a6130ae2950514022f50eb669c45a8cc1ba | old/betacopter/old/betacopter36dev-v005/modules/uavcan/libuavcan/dsdl_compiler/libuavcan_dsdl_compiler/pyratemp.py | python | TemplateParseError.__init__ | (self, err, errpos) | :Parameters:
- `err`: error-message or exception to wrap
- `errpos`: ``(filename,row,col)`` where the error occured. | :Parameters:
- `err`: error-message or exception to wrap
- `errpos`: ``(filename,row,col)`` where the error occured. | [
":",
"Parameters",
":",
"-",
"err",
":",
"error",
"-",
"message",
"or",
"exception",
"to",
"wrap",
"-",
"errpos",
":",
"(",
"filename",
"row",
"col",
")",
"where",
"the",
"error",
"occured",
"."
] | def __init__(self, err, errpos):
"""
:Parameters:
- `err`: error-message or exception to wrap
- `errpos`: ``(filename,row,col)`` where the error occured.
"""
self.err = err
self.filename, self.row, self.col = errpos
TemplateException.__init__(self) | [
"def",
"__init__",
"(",
"self",
",",
"err",
",",
"errpos",
")",
":",
"self",
".",
"err",
"=",
"err",
"self",
".",
"filename",
",",
"self",
".",
"row",
",",
"self",
".",
"col",
"=",
"errpos",
"TemplateException",
".",
"__init__",
"(",
"self",
")"
] | https://github.com/olliw42/storm32bgc/blob/99d62a6130ae2950514022f50eb669c45a8cc1ba/old/betacopter/old/betacopter36dev-v005/modules/uavcan/libuavcan/dsdl_compiler/libuavcan_dsdl_compiler/pyratemp.py#L338-L346 |
||
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/python/training/basic_session_run_hooks.py | python | FinalOpsHook.__init__ | (self, final_ops, final_ops_feed_dict=None) | Initializes `FinalOpHook` with ops to run at the end of the session.
Args:
final_ops: A single `Tensor`, a list of `Tensors` or a dictionary of
names to `Tensors`.
final_ops_feed_dict: A feed dictionary to use when running
`final_ops_dict`. | Initializes `FinalOpHook` with ops to run at the end of the session. | [
"Initializes",
"FinalOpHook",
"with",
"ops",
"to",
"run",
"at",
"the",
"end",
"of",
"the",
"session",
"."
] | def __init__(self, final_ops, final_ops_feed_dict=None):
"""Initializes `FinalOpHook` with ops to run at the end of the session.
Args:
final_ops: A single `Tensor`, a list of `Tensors` or a dictionary of
names to `Tensors`.
final_ops_feed_dict: A feed dictionary to use when running
`final_ops_dict`.
"""
self._final_ops = final_ops
self._final_ops_feed_dict = final_ops_feed_dict
self._final_ops_values = None | [
"def",
"__init__",
"(",
"self",
",",
"final_ops",
",",
"final_ops_feed_dict",
"=",
"None",
")",
":",
"self",
".",
"_final_ops",
"=",
"final_ops",
"self",
".",
"_final_ops_feed_dict",
"=",
"final_ops_feed_dict",
"self",
".",
"_final_ops_values",
"=",
"None"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/training/basic_session_run_hooks.py#L713-L724 |
||
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/ops/array_ops.py | python | size_v2 | (input, out_type=dtypes.int32, name=None) | return size(input, name, out_type) | Returns the size of a tensor.
See also `tf.shape`.
Returns a 0-D `Tensor` representing the number of elements in `input`
of type `out_type`. Defaults to tf.int32.
For example:
>>> t = tf.constant([[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]]])
>>> tf.size(t)
<tf.Tensor: shape=(), dtype=int32, numpy=12>
Args:
input: A `Tensor` or `SparseTensor`.
name: A name for the operation (optional).
out_type: (Optional) The specified non-quantized numeric output type of the
operation. Defaults to `tf.int32`.
Returns:
A `Tensor` of type `out_type`. Defaults to `tf.int32`.
@compatibility(numpy)
Equivalent to np.size()
@end_compatibility | Returns the size of a tensor. | [
"Returns",
"the",
"size",
"of",
"a",
"tensor",
"."
] | def size_v2(input, out_type=dtypes.int32, name=None):
# pylint: disable=redefined-builtin
"""Returns the size of a tensor.
See also `tf.shape`.
Returns a 0-D `Tensor` representing the number of elements in `input`
of type `out_type`. Defaults to tf.int32.
For example:
>>> t = tf.constant([[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]]])
>>> tf.size(t)
<tf.Tensor: shape=(), dtype=int32, numpy=12>
Args:
input: A `Tensor` or `SparseTensor`.
name: A name for the operation (optional).
out_type: (Optional) The specified non-quantized numeric output type of the
operation. Defaults to `tf.int32`.
Returns:
A `Tensor` of type `out_type`. Defaults to `tf.int32`.
@compatibility(numpy)
Equivalent to np.size()
@end_compatibility
"""
return size(input, name, out_type) | [
"def",
"size_v2",
"(",
"input",
",",
"out_type",
"=",
"dtypes",
".",
"int32",
",",
"name",
"=",
"None",
")",
":",
"# pylint: disable=redefined-builtin",
"return",
"size",
"(",
"input",
",",
"name",
",",
"out_type",
")"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/array_ops.py#L723-L752 |
|
apple/swift | 469f72fdae2ea828b3b6c0d7d62d7e4cf98c4893 | utils/swift_build_support/swift_build_support/build_script_invocation.py | python | BuildScriptInvocation.compute_host_specific_variables | (self) | return options | compute_host_specific_variables(args) -> dict
Compute the host-specific options, organized as a dictionary keyed by
host of options. | compute_host_specific_variables(args) -> dict | [
"compute_host_specific_variables",
"(",
"args",
")",
"-",
">",
"dict"
] | def compute_host_specific_variables(self):
"""compute_host_specific_variables(args) -> dict
Compute the host-specific options, organized as a dictionary keyed by
host of options.
"""
args = self.args
args.build_root = self.workspace.build_root
options = {}
for host_target in [args.host_target] + args.cross_compile_hosts:
# Compute the host specific configuration.
try:
config = HostSpecificConfiguration(host_target, args)
except argparse.ArgumentError as e:
exit_rejecting_arguments(six.text_type(e))
# Convert into `build-script-impl` style variables.
options[host_target] = {
"SWIFT_SDKS": " ".join(sorted(
config.sdks_to_configure)),
"SWIFT_STDLIB_TARGETS": " ".join(
config.swift_stdlib_build_targets),
"SWIFT_BENCHMARK_TARGETS": " ".join(
config.swift_benchmark_build_targets),
"SWIFT_RUN_BENCHMARK_TARGETS": " ".join(
config.swift_benchmark_run_targets),
"SWIFT_TEST_TARGETS": " ".join(
config.swift_test_run_targets),
"SWIFT_FLAGS": config.swift_flags,
"SWIFT_TARGET_CMAKE_OPTIONS": config.cmake_options,
}
return options | [
"def",
"compute_host_specific_variables",
"(",
"self",
")",
":",
"args",
"=",
"self",
".",
"args",
"args",
".",
"build_root",
"=",
"self",
".",
"workspace",
".",
"build_root",
"options",
"=",
"{",
"}",
"for",
"host_target",
"in",
"[",
"args",
".",
"host_target",
"]",
"+",
"args",
".",
"cross_compile_hosts",
":",
"# Compute the host specific configuration.",
"try",
":",
"config",
"=",
"HostSpecificConfiguration",
"(",
"host_target",
",",
"args",
")",
"except",
"argparse",
".",
"ArgumentError",
"as",
"e",
":",
"exit_rejecting_arguments",
"(",
"six",
".",
"text_type",
"(",
"e",
")",
")",
"# Convert into `build-script-impl` style variables.",
"options",
"[",
"host_target",
"]",
"=",
"{",
"\"SWIFT_SDKS\"",
":",
"\" \"",
".",
"join",
"(",
"sorted",
"(",
"config",
".",
"sdks_to_configure",
")",
")",
",",
"\"SWIFT_STDLIB_TARGETS\"",
":",
"\" \"",
".",
"join",
"(",
"config",
".",
"swift_stdlib_build_targets",
")",
",",
"\"SWIFT_BENCHMARK_TARGETS\"",
":",
"\" \"",
".",
"join",
"(",
"config",
".",
"swift_benchmark_build_targets",
")",
",",
"\"SWIFT_RUN_BENCHMARK_TARGETS\"",
":",
"\" \"",
".",
"join",
"(",
"config",
".",
"swift_benchmark_run_targets",
")",
",",
"\"SWIFT_TEST_TARGETS\"",
":",
"\" \"",
".",
"join",
"(",
"config",
".",
"swift_test_run_targets",
")",
",",
"\"SWIFT_FLAGS\"",
":",
"config",
".",
"swift_flags",
",",
"\"SWIFT_TARGET_CMAKE_OPTIONS\"",
":",
"config",
".",
"cmake_options",
",",
"}",
"return",
"options"
] | https://github.com/apple/swift/blob/469f72fdae2ea828b3b6c0d7d62d7e4cf98c4893/utils/swift_build_support/swift_build_support/build_script_invocation.py#L482-L516 |
|
wesnoth/wesnoth | 6ccac5a5e8ff75303c9190c0da60580925cb32c0 | data/tools/wesnoth/wmltools3.py | python | directory_namespace | (path) | Go from directory to namespace. | Go from directory to namespace. | [
"Go",
"from",
"directory",
"to",
"namespace",
"."
] | def directory_namespace(path):
"Go from directory to namespace."
if path.startswith("data/core/"):
return "core"
elif path.startswith("data/campaigns/"):
return path.split("/")[2]
else:
return None | [
"def",
"directory_namespace",
"(",
"path",
")",
":",
"if",
"path",
".",
"startswith",
"(",
"\"data/core/\"",
")",
":",
"return",
"\"core\"",
"elif",
"path",
".",
"startswith",
"(",
"\"data/campaigns/\"",
")",
":",
"return",
"path",
".",
"split",
"(",
"\"/\"",
")",
"[",
"2",
"]",
"else",
":",
"return",
"None"
] | https://github.com/wesnoth/wesnoth/blob/6ccac5a5e8ff75303c9190c0da60580925cb32c0/data/tools/wesnoth/wmltools3.py#L1086-L1093 |
||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/ipython/py2/IPython/core/display.py | python | DisplayHandle.update | (self, obj, **kwargs) | Update existing displays with my id
Parameters
----------
obj:
object to display
**kwargs:
additional keyword arguments passed to update_display | Update existing displays with my id
Parameters
----------
obj:
object to display
**kwargs:
additional keyword arguments passed to update_display | [
"Update",
"existing",
"displays",
"with",
"my",
"id",
"Parameters",
"----------",
"obj",
":",
"object",
"to",
"display",
"**",
"kwargs",
":",
"additional",
"keyword",
"arguments",
"passed",
"to",
"update_display"
] | def update(self, obj, **kwargs):
"""Update existing displays with my id
Parameters
----------
obj:
object to display
**kwargs:
additional keyword arguments passed to update_display
"""
update_display(obj, display_id=self.display_id, **kwargs) | [
"def",
"update",
"(",
"self",
",",
"obj",
",",
"*",
"*",
"kwargs",
")",
":",
"update_display",
"(",
"obj",
",",
"display_id",
"=",
"self",
".",
"display_id",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py2/IPython/core/display.py#L384-L395 |
||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/pickle.py | python | decode_long | (data) | return int.from_bytes(data, byteorder='little', signed=True) | r"""Decode a long from a two's complement little-endian binary string.
>>> decode_long(b'')
0
>>> decode_long(b"\xff\x00")
255
>>> decode_long(b"\xff\x7f")
32767
>>> decode_long(b"\x00\xff")
-256
>>> decode_long(b"\x00\x80")
-32768
>>> decode_long(b"\x80")
-128
>>> decode_long(b"\x7f")
127 | r"""Decode a long from a two's complement little-endian binary string. | [
"r",
"Decode",
"a",
"long",
"from",
"a",
"two",
"s",
"complement",
"little",
"-",
"endian",
"binary",
"string",
"."
] | def decode_long(data):
r"""Decode a long from a two's complement little-endian binary string.
>>> decode_long(b'')
0
>>> decode_long(b"\xff\x00")
255
>>> decode_long(b"\xff\x7f")
32767
>>> decode_long(b"\x00\xff")
-256
>>> decode_long(b"\x00\x80")
-32768
>>> decode_long(b"\x80")
-128
>>> decode_long(b"\x7f")
127
"""
return int.from_bytes(data, byteorder='little', signed=True) | [
"def",
"decode_long",
"(",
"data",
")",
":",
"return",
"int",
".",
"from_bytes",
"(",
"data",
",",
"byteorder",
"=",
"'little'",
",",
"signed",
"=",
"True",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/pickle.py#L349-L367 |
|
pyne/pyne | 0c2714d7c0d1b5e20be6ae6527da2c660dd6b1b3 | pyne/xs/data_source.py | python | DataSource.shield_weights | (self, num_dens, temp) | Builds the weights used during the self shielding calculations.
Parameters
----------
mat : array of floats.
A map of the number densities of each of the nuclides of the material for
which self-shielding is being calculated.
data_source: pyne data_source
Contains the cross section information for the isotopes in the material
that is experiencing the self shielding. | Builds the weights used during the self shielding calculations.
Parameters
----------
mat : array of floats.
A map of the number densities of each of the nuclides of the material for
which self-shielding is being calculated.
data_source: pyne data_source
Contains the cross section information for the isotopes in the material
that is experiencing the self shielding. | [
"Builds",
"the",
"weights",
"used",
"during",
"the",
"self",
"shielding",
"calculations",
".",
"Parameters",
"----------",
"mat",
":",
"array",
"of",
"floats",
".",
"A",
"map",
"of",
"the",
"number",
"densities",
"of",
"each",
"of",
"the",
"nuclides",
"of",
"the",
"material",
"for",
"which",
"self",
"-",
"shielding",
"is",
"being",
"calculated",
".",
"data_source",
":",
"pyne",
"data_source",
"Contains",
"the",
"cross",
"section",
"information",
"for",
"the",
"isotopes",
"in",
"the",
"material",
"that",
"is",
"experiencing",
"the",
"self",
"shielding",
"."
] | def shield_weights(self, num_dens, temp):
"""Builds the weights used during the self shielding calculations.
Parameters
----------
mat : array of floats.
A map of the number densities of each of the nuclides of the material for
which self-shielding is being calculated.
data_source: pyne data_source
Contains the cross section information for the isotopes in the material
that is experiencing the self shielding.
"""
reactions = {}
for i in num_dens:
rx = self.reaction(i, 'total', temp)
reactions[i] = 0.0 if rx is None else rx
weights = {}
for i in num_dens:
weights[i] = 0.0
for j in reactions:
if j != i:
weights[i] += num_dens[j]*reactions[j]
weights[i] = 1.0/(weights[i]/num_dens[i] + reactions[i])
self.slf_shld_wgts = weights | [
"def",
"shield_weights",
"(",
"self",
",",
"num_dens",
",",
"temp",
")",
":",
"reactions",
"=",
"{",
"}",
"for",
"i",
"in",
"num_dens",
":",
"rx",
"=",
"self",
".",
"reaction",
"(",
"i",
",",
"'total'",
",",
"temp",
")",
"reactions",
"[",
"i",
"]",
"=",
"0.0",
"if",
"rx",
"is",
"None",
"else",
"rx",
"weights",
"=",
"{",
"}",
"for",
"i",
"in",
"num_dens",
":",
"weights",
"[",
"i",
"]",
"=",
"0.0",
"for",
"j",
"in",
"reactions",
":",
"if",
"j",
"!=",
"i",
":",
"weights",
"[",
"i",
"]",
"+=",
"num_dens",
"[",
"j",
"]",
"*",
"reactions",
"[",
"j",
"]",
"weights",
"[",
"i",
"]",
"=",
"1.0",
"/",
"(",
"weights",
"[",
"i",
"]",
"/",
"num_dens",
"[",
"i",
"]",
"+",
"reactions",
"[",
"i",
"]",
")",
"self",
".",
"slf_shld_wgts",
"=",
"weights"
] | https://github.com/pyne/pyne/blob/0c2714d7c0d1b5e20be6ae6527da2c660dd6b1b3/pyne/xs/data_source.py#L227-L249 |
||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/AWSPythonSDK/1.5.8/boto3/__init__.py | python | resource | (*args, **kwargs) | return _get_default_session().resource(*args, **kwargs) | Create a resource service client by name using the default session.
See :py:meth:`boto3.session.Session.resource`. | Create a resource service client by name using the default session. | [
"Create",
"a",
"resource",
"service",
"client",
"by",
"name",
"using",
"the",
"default",
"session",
"."
] | def resource(*args, **kwargs):
"""
Create a resource service client by name using the default session.
See :py:meth:`boto3.session.Session.resource`.
"""
return _get_default_session().resource(*args, **kwargs) | [
"def",
"resource",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_get_default_session",
"(",
")",
".",
"resource",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/boto3/__init__.py#L86-L92 |
|
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/telemetry/third_party/altgraph/altgraph/GraphAlgo.py | python | _priorityDictionary.__setitem__ | (self,key,val) | Change value stored in dictionary and add corresponding pair to heap.
Rebuilds the heap if the number of deleted items gets large, to avoid memory leakage. | Change value stored in dictionary and add corresponding pair to heap.
Rebuilds the heap if the number of deleted items gets large, to avoid memory leakage. | [
"Change",
"value",
"stored",
"in",
"dictionary",
"and",
"add",
"corresponding",
"pair",
"to",
"heap",
".",
"Rebuilds",
"the",
"heap",
"if",
"the",
"number",
"of",
"deleted",
"items",
"gets",
"large",
"to",
"avoid",
"memory",
"leakage",
"."
] | def __setitem__(self,key,val):
'''
Change value stored in dictionary and add corresponding pair to heap.
Rebuilds the heap if the number of deleted items gets large, to avoid memory leakage.
'''
dict.__setitem__(self,key,val)
heap = self.__heap
if len(heap) > 2 * len(self):
self.__heap = [(v,k) for k,v in self.iteritems()]
self.__heap.sort() # builtin sort probably faster than O(n)-time heapify
else:
newPair = (val,key)
insertionPoint = len(heap)
heap.append(None)
while insertionPoint > 0 and newPair < heap[(insertionPoint-1)//2]:
heap[insertionPoint] = heap[(insertionPoint-1)//2]
insertionPoint = (insertionPoint-1)//2
heap[insertionPoint] = newPair | [
"def",
"__setitem__",
"(",
"self",
",",
"key",
",",
"val",
")",
":",
"dict",
".",
"__setitem__",
"(",
"self",
",",
"key",
",",
"val",
")",
"heap",
"=",
"self",
".",
"__heap",
"if",
"len",
"(",
"heap",
")",
">",
"2",
"*",
"len",
"(",
"self",
")",
":",
"self",
".",
"__heap",
"=",
"[",
"(",
"v",
",",
"k",
")",
"for",
"k",
",",
"v",
"in",
"self",
".",
"iteritems",
"(",
")",
"]",
"self",
".",
"__heap",
".",
"sort",
"(",
")",
"# builtin sort probably faster than O(n)-time heapify",
"else",
":",
"newPair",
"=",
"(",
"val",
",",
"key",
")",
"insertionPoint",
"=",
"len",
"(",
"heap",
")",
"heap",
".",
"append",
"(",
"None",
")",
"while",
"insertionPoint",
">",
"0",
"and",
"newPair",
"<",
"heap",
"[",
"(",
"insertionPoint",
"-",
"1",
")",
"//",
"2",
"]",
":",
"heap",
"[",
"insertionPoint",
"]",
"=",
"heap",
"[",
"(",
"insertionPoint",
"-",
"1",
")",
"//",
"2",
"]",
"insertionPoint",
"=",
"(",
"insertionPoint",
"-",
"1",
")",
"//",
"2",
"heap",
"[",
"insertionPoint",
"]",
"=",
"newPair"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/third_party/altgraph/altgraph/GraphAlgo.py#L122-L139 |
||
Chia-Network/bls-signatures | a61089d653fa3653ac94452c73e97efcd461bdf2 | python-impl/ec.py | python | scalar_mult_jacobian | (c, p1: JacobianPoint, ec=default_ec, FE=Fq) | return result | Double and add, see
https://en.wikipedia.org/wiki/Elliptic_curve_point_multiplication | Double and add, see
https://en.wikipedia.org/wiki/Elliptic_curve_point_multiplication | [
"Double",
"and",
"add",
"see",
"https",
":",
"//",
"en",
".",
"wikipedia",
".",
"org",
"/",
"wiki",
"/",
"Elliptic_curve_point_multiplication"
] | def scalar_mult_jacobian(c, p1: JacobianPoint, ec=default_ec, FE=Fq) -> JacobianPoint:
"""
Double and add, see
https://en.wikipedia.org/wiki/Elliptic_curve_point_multiplication
"""
if isinstance(c, FE):
c = c.value
if p1.infinity or c % ec.q == 0:
return JacobianPoint(FE.one(ec.q), FE.one(ec.q), FE.zero(ec.q), True, ec)
result = JacobianPoint(FE.one(ec.q), FE.one(ec.q), FE.zero(ec.q), True, ec)
addend = p1
while c > 0:
if c & 1:
result += addend
# double point
addend += addend
c = c >> 1
return result | [
"def",
"scalar_mult_jacobian",
"(",
"c",
",",
"p1",
":",
"JacobianPoint",
",",
"ec",
"=",
"default_ec",
",",
"FE",
"=",
"Fq",
")",
"->",
"JacobianPoint",
":",
"if",
"isinstance",
"(",
"c",
",",
"FE",
")",
":",
"c",
"=",
"c",
".",
"value",
"if",
"p1",
".",
"infinity",
"or",
"c",
"%",
"ec",
".",
"q",
"==",
"0",
":",
"return",
"JacobianPoint",
"(",
"FE",
".",
"one",
"(",
"ec",
".",
"q",
")",
",",
"FE",
".",
"one",
"(",
"ec",
".",
"q",
")",
",",
"FE",
".",
"zero",
"(",
"ec",
".",
"q",
")",
",",
"True",
",",
"ec",
")",
"result",
"=",
"JacobianPoint",
"(",
"FE",
".",
"one",
"(",
"ec",
".",
"q",
")",
",",
"FE",
".",
"one",
"(",
"ec",
".",
"q",
")",
",",
"FE",
".",
"zero",
"(",
"ec",
".",
"q",
")",
",",
"True",
",",
"ec",
")",
"addend",
"=",
"p1",
"while",
"c",
">",
"0",
":",
"if",
"c",
"&",
"1",
":",
"result",
"+=",
"addend",
"# double point",
"addend",
"+=",
"addend",
"c",
"=",
"c",
">>",
"1",
"return",
"result"
] | https://github.com/Chia-Network/bls-signatures/blob/a61089d653fa3653ac94452c73e97efcd461bdf2/python-impl/ec.py#L449-L467 |
|
polserver/polserver | b34a9de0e14cb16f1e0d358710a797ad4e42ebdc | lib/google-benchmark/tools/gbench/util.py | python | check_input_file | (filename) | return ftype | Classify the file named by 'filename' and return the classification.
If the file is classified as 'IT_Invalid' print an error message and exit
the program. | Classify the file named by 'filename' and return the classification.
If the file is classified as 'IT_Invalid' print an error message and exit
the program. | [
"Classify",
"the",
"file",
"named",
"by",
"filename",
"and",
"return",
"the",
"classification",
".",
"If",
"the",
"file",
"is",
"classified",
"as",
"IT_Invalid",
"print",
"an",
"error",
"message",
"and",
"exit",
"the",
"program",
"."
] | def check_input_file(filename):
"""
Classify the file named by 'filename' and return the classification.
If the file is classified as 'IT_Invalid' print an error message and exit
the program.
"""
ftype, msg = classify_input_file(filename)
if ftype == IT_Invalid:
print "Invalid input file: %s" % msg
sys.exit(1)
return ftype | [
"def",
"check_input_file",
"(",
"filename",
")",
":",
"ftype",
",",
"msg",
"=",
"classify_input_file",
"(",
"filename",
")",
"if",
"ftype",
"==",
"IT_Invalid",
":",
"print",
"\"Invalid input file: %s\"",
"%",
"msg",
"sys",
".",
"exit",
"(",
"1",
")",
"return",
"ftype"
] | https://github.com/polserver/polserver/blob/b34a9de0e14cb16f1e0d358710a797ad4e42ebdc/lib/google-benchmark/tools/gbench/util.py#L75-L85 |
|
google/llvm-propeller | 45c226984fe8377ebfb2ad7713c680d652ba678d | clang/utils/check_cfc/check_cfc.py | python | flip_dash_g | (args) | Search for -g in args. If it exists then return args without. If not then
add it. | Search for -g in args. If it exists then return args without. If not then
add it. | [
"Search",
"for",
"-",
"g",
"in",
"args",
".",
"If",
"it",
"exists",
"then",
"return",
"args",
"without",
".",
"If",
"not",
"then",
"add",
"it",
"."
] | def flip_dash_g(args):
"""Search for -g in args. If it exists then return args without. If not then
add it."""
if '-g' in args:
# Return args without any -g
return [x for x in args if x != '-g']
else:
# No -g, add one
return args + ['-g'] | [
"def",
"flip_dash_g",
"(",
"args",
")",
":",
"if",
"'-g'",
"in",
"args",
":",
"# Return args without any -g",
"return",
"[",
"x",
"for",
"x",
"in",
"args",
"if",
"x",
"!=",
"'-g'",
"]",
"else",
":",
"# No -g, add one",
"return",
"args",
"+",
"[",
"'-g'",
"]"
] | https://github.com/google/llvm-propeller/blob/45c226984fe8377ebfb2ad7713c680d652ba678d/clang/utils/check_cfc/check_cfc.py#L111-L119 |
||
TGAC/KAT | e8870331de2b4bb0a1b3b91c6afb8fb9d59e9216 | deps/boost/tools/build/src/build/build_request.py | python | __x_product_aux | (property_sets, seen_features) | Returns non-conflicting combinations of property sets.
property_sets is a list of PropertySet instances. seen_features is a set of Property
instances.
Returns a tuple of:
- list of lists of Property instances, such that within each list, no two Property instance
have the same feature, and no Property is for feature in seen_features.
- set of features we saw in property_sets | Returns non-conflicting combinations of property sets. | [
"Returns",
"non",
"-",
"conflicting",
"combinations",
"of",
"property",
"sets",
"."
] | def __x_product_aux (property_sets, seen_features):
"""Returns non-conflicting combinations of property sets.
property_sets is a list of PropertySet instances. seen_features is a set of Property
instances.
Returns a tuple of:
- list of lists of Property instances, such that within each list, no two Property instance
have the same feature, and no Property is for feature in seen_features.
- set of features we saw in property_sets
"""
assert is_iterable_typed(property_sets, property_set.PropertySet)
assert isinstance(seen_features, set)
if not property_sets:
return ([], set())
properties = property_sets[0].all()
these_features = set()
for p in property_sets[0].non_free():
these_features.add(p.feature)
# Note: the algorithm as implemented here, as in original Jam code, appears to
# detect conflicts based on features, not properties. For example, if command
# line build request say:
#
# <a>1/<b>1 c<1>/<b>1
#
# It will decide that those two property sets conflict, because they both specify
# a value for 'b' and will not try building "<a>1 <c1> <b1>", but rather two
# different property sets. This is a topic for future fixing, maybe.
if these_features & seen_features:
(inner_result, inner_seen) = __x_product_aux(property_sets[1:], seen_features)
return (inner_result, inner_seen | these_features)
else:
result = []
(inner_result, inner_seen) = __x_product_aux(property_sets[1:], seen_features | these_features)
if inner_result:
for inner in inner_result:
result.append(properties + inner)
else:
result.append(properties)
if inner_seen & these_features:
# Some of elements in property_sets[1:] conflict with elements of property_sets[0],
# Try again, this time omitting elements of property_sets[0]
(inner_result2, inner_seen2) = __x_product_aux(property_sets[1:], seen_features)
result.extend(inner_result2)
return (result, inner_seen | these_features) | [
"def",
"__x_product_aux",
"(",
"property_sets",
",",
"seen_features",
")",
":",
"assert",
"is_iterable_typed",
"(",
"property_sets",
",",
"property_set",
".",
"PropertySet",
")",
"assert",
"isinstance",
"(",
"seen_features",
",",
"set",
")",
"if",
"not",
"property_sets",
":",
"return",
"(",
"[",
"]",
",",
"set",
"(",
")",
")",
"properties",
"=",
"property_sets",
"[",
"0",
"]",
".",
"all",
"(",
")",
"these_features",
"=",
"set",
"(",
")",
"for",
"p",
"in",
"property_sets",
"[",
"0",
"]",
".",
"non_free",
"(",
")",
":",
"these_features",
".",
"add",
"(",
"p",
".",
"feature",
")",
"# Note: the algorithm as implemented here, as in original Jam code, appears to",
"# detect conflicts based on features, not properties. For example, if command",
"# line build request say:",
"#",
"# <a>1/<b>1 c<1>/<b>1",
"#",
"# It will decide that those two property sets conflict, because they both specify",
"# a value for 'b' and will not try building \"<a>1 <c1> <b1>\", but rather two",
"# different property sets. This is a topic for future fixing, maybe.",
"if",
"these_features",
"&",
"seen_features",
":",
"(",
"inner_result",
",",
"inner_seen",
")",
"=",
"__x_product_aux",
"(",
"property_sets",
"[",
"1",
":",
"]",
",",
"seen_features",
")",
"return",
"(",
"inner_result",
",",
"inner_seen",
"|",
"these_features",
")",
"else",
":",
"result",
"=",
"[",
"]",
"(",
"inner_result",
",",
"inner_seen",
")",
"=",
"__x_product_aux",
"(",
"property_sets",
"[",
"1",
":",
"]",
",",
"seen_features",
"|",
"these_features",
")",
"if",
"inner_result",
":",
"for",
"inner",
"in",
"inner_result",
":",
"result",
".",
"append",
"(",
"properties",
"+",
"inner",
")",
"else",
":",
"result",
".",
"append",
"(",
"properties",
")",
"if",
"inner_seen",
"&",
"these_features",
":",
"# Some of elements in property_sets[1:] conflict with elements of property_sets[0],",
"# Try again, this time omitting elements of property_sets[0]",
"(",
"inner_result2",
",",
"inner_seen2",
")",
"=",
"__x_product_aux",
"(",
"property_sets",
"[",
"1",
":",
"]",
",",
"seen_features",
")",
"result",
".",
"extend",
"(",
"inner_result2",
")",
"return",
"(",
"result",
",",
"inner_seen",
"|",
"these_features",
")"
] | https://github.com/TGAC/KAT/blob/e8870331de2b4bb0a1b3b91c6afb8fb9d59e9216/deps/boost/tools/build/src/build/build_request.py#L39-L91 |
||
mongodb/mongo | d8ff665343ad29cf286ee2cf4a1960d29371937b | buildscripts/idl/idl/errors.py | python | ParserErrorCollection.__init__ | (self) | Initialize ParserErrorCollection. | Initialize ParserErrorCollection. | [
"Initialize",
"ParserErrorCollection",
"."
] | def __init__(self):
# type: () -> None
"""Initialize ParserErrorCollection."""
self._errors = [] | [
"def",
"__init__",
"(",
"self",
")",
":",
"# type: () -> None",
"self",
".",
"_errors",
"=",
"[",
"]"
] | https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/idl/idl/errors.py#L175-L178 |
||
y123456yz/reading-and-annotate-mongodb-3.6 | 93280293672ca7586dc24af18132aa61e4ed7fcf | mongo/buildscripts/buildlogger.py | python | run_and_echo | (command) | return proc.returncode | this just calls the command, and returns its return code,
allowing stdout and stderr to work as normal. it is used
as a fallback when environment variables or python
dependencies cannot be configured, or when the logging
webapp is unavailable, etc | this just calls the command, and returns its return code,
allowing stdout and stderr to work as normal. it is used
as a fallback when environment variables or python
dependencies cannot be configured, or when the logging
webapp is unavailable, etc | [
"this",
"just",
"calls",
"the",
"command",
"and",
"returns",
"its",
"return",
"code",
"allowing",
"stdout",
"and",
"stderr",
"to",
"work",
"as",
"normal",
".",
"it",
"is",
"used",
"as",
"a",
"fallback",
"when",
"environment",
"variables",
"or",
"python",
"dependencies",
"cannot",
"be",
"configured",
"or",
"when",
"the",
"logging",
"webapp",
"is",
"unavailable",
"etc"
] | def run_and_echo(command):
"""
this just calls the command, and returns its return code,
allowing stdout and stderr to work as normal. it is used
as a fallback when environment variables or python
dependencies cannot be configured, or when the logging
webapp is unavailable, etc
"""
proc = subprocess.Popen(command)
# We write the pid of the spawned process as the first line of buildlogger.py's stdout because
# smoke.py expects to use it to terminate processes individually if already running inside a job
# object.
sys.stdout.write("[buildlogger.py] pid: %d\n" % (proc.pid))
sys.stdout.flush()
def handle_sigterm(signum, frame):
try:
proc.send_signal(signum)
except AttributeError:
os.kill(proc.pid, signum)
orig_handler = signal.signal(signal.SIGTERM, handle_sigterm)
proc.wait()
signal.signal(signal.SIGTERM, orig_handler)
return proc.returncode | [
"def",
"run_and_echo",
"(",
"command",
")",
":",
"proc",
"=",
"subprocess",
".",
"Popen",
"(",
"command",
")",
"# We write the pid of the spawned process as the first line of buildlogger.py's stdout because",
"# smoke.py expects to use it to terminate processes individually if already running inside a job",
"# object.",
"sys",
".",
"stdout",
".",
"write",
"(",
"\"[buildlogger.py] pid: %d\\n\"",
"%",
"(",
"proc",
".",
"pid",
")",
")",
"sys",
".",
"stdout",
".",
"flush",
"(",
")",
"def",
"handle_sigterm",
"(",
"signum",
",",
"frame",
")",
":",
"try",
":",
"proc",
".",
"send_signal",
"(",
"signum",
")",
"except",
"AttributeError",
":",
"os",
".",
"kill",
"(",
"proc",
".",
"pid",
",",
"signum",
")",
"orig_handler",
"=",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGTERM",
",",
"handle_sigterm",
")",
"proc",
".",
"wait",
"(",
")",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGTERM",
",",
"orig_handler",
")",
"return",
"proc",
".",
"returncode"
] | https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/buildscripts/buildlogger.py#L215-L241 |
|
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/graphy/graphy/backends/google_chart_api/encoders.py | python | BarChartEncoder.__init__ | (self, chart, style=None) | Construct a new BarChartEncoder.
Args:
style: DEPRECATED. Set style on the chart object itself. | Construct a new BarChartEncoder. | [
"Construct",
"a",
"new",
"BarChartEncoder",
"."
] | def __init__(self, chart, style=None):
"""Construct a new BarChartEncoder.
Args:
style: DEPRECATED. Set style on the chart object itself.
"""
super(BarChartEncoder, self).__init__(chart)
if style is not None:
warnings.warn(self.__STYLE_DEPRECATION, DeprecationWarning, stacklevel=2)
chart.style = style | [
"def",
"__init__",
"(",
"self",
",",
"chart",
",",
"style",
"=",
"None",
")",
":",
"super",
"(",
"BarChartEncoder",
",",
"self",
")",
".",
"__init__",
"(",
"chart",
")",
"if",
"style",
"is",
"not",
"None",
":",
"warnings",
".",
"warn",
"(",
"self",
".",
"__STYLE_DEPRECATION",
",",
"DeprecationWarning",
",",
"stacklevel",
"=",
"2",
")",
"chart",
".",
"style",
"=",
"style"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/graphy/graphy/backends/google_chart_api/encoders.py#L254-L263 |
||
facebookarchive/LogDevice | ce7726050edc49a1e15d9160e81c890736b779e2 | logdevice/ops/ldquery/py/lib.py | python | Cursor.complete | (self) | return self._result.metadata.success | Returns True if the result is not-partial due to trimming or
failures on the server side. | Returns True if the result is not-partial due to trimming or
failures on the server side. | [
"Returns",
"True",
"if",
"the",
"result",
"is",
"not",
"-",
"partial",
"due",
"to",
"trimming",
"or",
"failures",
"on",
"the",
"server",
"side",
"."
] | def complete(self):
"""
Returns True if the result is not-partial due to trimming or
failures on the server side.
"""
return self._result.metadata.success | [
"def",
"complete",
"(",
"self",
")",
":",
"return",
"self",
".",
"_result",
".",
"metadata",
".",
"success"
] | https://github.com/facebookarchive/LogDevice/blob/ce7726050edc49a1e15d9160e81c890736b779e2/logdevice/ops/ldquery/py/lib.py#L136-L141 |
|
cvxpy/cvxpy | 5165b4fb750dfd237de8659383ef24b4b2e33aaf | cvxpy/problems/param_prob.py | python | ParamProb.is_mixed_integer | (self) | Is the problem mixed-integer? | Is the problem mixed-integer? | [
"Is",
"the",
"problem",
"mixed",
"-",
"integer?"
] | def is_mixed_integer(self) -> bool:
"""Is the problem mixed-integer?"""
raise NotImplementedError() | [
"def",
"is_mixed_integer",
"(",
"self",
")",
"->",
"bool",
":",
"raise",
"NotImplementedError",
"(",
")"
] | https://github.com/cvxpy/cvxpy/blob/5165b4fb750dfd237de8659383ef24b4b2e33aaf/cvxpy/problems/param_prob.py#L28-L30 |
||
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/AddonManager/AddonManager.py | python | CommandAddonManager.enable_updates | (self, number_of_updates: int) | enables the update button | enables the update button | [
"enables",
"the",
"update",
"button"
] | def enable_updates(self, number_of_updates: int) -> None:
"""enables the update button"""
if number_of_updates:
s = translate(
"AddonsInstaller", "Apply {} update(s)", "", number_of_updates
)
self.dialog.buttonUpdateAll.setText(s.format(number_of_updates))
self.dialog.buttonUpdateAll.setEnabled(True)
else:
self.dialog.buttonUpdateAll.setText(
translate("AddonsInstaller", "No updates available")
)
self.dialog.buttonUpdateAll.setEnabled(False) | [
"def",
"enable_updates",
"(",
"self",
",",
"number_of_updates",
":",
"int",
")",
"->",
"None",
":",
"if",
"number_of_updates",
":",
"s",
"=",
"translate",
"(",
"\"AddonsInstaller\"",
",",
"\"Apply {} update(s)\"",
",",
"\"\"",
",",
"number_of_updates",
")",
"self",
".",
"dialog",
".",
"buttonUpdateAll",
".",
"setText",
"(",
"s",
".",
"format",
"(",
"number_of_updates",
")",
")",
"self",
".",
"dialog",
".",
"buttonUpdateAll",
".",
"setEnabled",
"(",
"True",
")",
"else",
":",
"self",
".",
"dialog",
".",
"buttonUpdateAll",
".",
"setText",
"(",
"translate",
"(",
"\"AddonsInstaller\"",
",",
"\"No updates available\"",
")",
")",
"self",
".",
"dialog",
".",
"buttonUpdateAll",
".",
"setEnabled",
"(",
"False",
")"
] | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/AddonManager/AddonManager.py#L761-L774 |
||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/configparser.py | python | RawConfigParser._read | (self, fp, fpname) | Parse a sectioned configuration file.
Each section in a configuration file contains a header, indicated by
a name in square brackets (`[]'), plus key/value options, indicated by
`name' and `value' delimited with a specific substring (`=' or `:' by
default).
Values can span multiple lines, as long as they are indented deeper
than the first line of the value. Depending on the parser's mode, blank
lines may be treated as parts of multiline values or ignored.
Configuration files may include comments, prefixed by specific
characters (`#' and `;' by default). Comments may appear on their own
in an otherwise empty line or may be entered in lines holding values or
section names. | Parse a sectioned configuration file. | [
"Parse",
"a",
"sectioned",
"configuration",
"file",
"."
] | def _read(self, fp, fpname):
"""Parse a sectioned configuration file.
Each section in a configuration file contains a header, indicated by
a name in square brackets (`[]'), plus key/value options, indicated by
`name' and `value' delimited with a specific substring (`=' or `:' by
default).
Values can span multiple lines, as long as they are indented deeper
than the first line of the value. Depending on the parser's mode, blank
lines may be treated as parts of multiline values or ignored.
Configuration files may include comments, prefixed by specific
characters (`#' and `;' by default). Comments may appear on their own
in an otherwise empty line or may be entered in lines holding values or
section names.
"""
elements_added = set()
cursect = None # None, or a dictionary
sectname = None
optname = None
lineno = 0
indent_level = 0
e = None # None, or an exception
for lineno, line in enumerate(fp, start=1):
comment_start = sys.maxsize
# strip inline comments
inline_prefixes = {p: -1 for p in self._inline_comment_prefixes}
while comment_start == sys.maxsize and inline_prefixes:
next_prefixes = {}
for prefix, index in inline_prefixes.items():
index = line.find(prefix, index+1)
if index == -1:
continue
next_prefixes[prefix] = index
if index == 0 or (index > 0 and line[index-1].isspace()):
comment_start = min(comment_start, index)
inline_prefixes = next_prefixes
# strip full line comments
for prefix in self._comment_prefixes:
if line.strip().startswith(prefix):
comment_start = 0
break
if comment_start == sys.maxsize:
comment_start = None
value = line[:comment_start].strip()
if not value:
if self._empty_lines_in_values:
# add empty line to the value, but only if there was no
# comment on the line
if (comment_start is None and
cursect is not None and
optname and
cursect[optname] is not None):
cursect[optname].append('') # newlines added at join
else:
# empty line marks end of value
indent_level = sys.maxsize
continue
# continuation line?
first_nonspace = self.NONSPACECRE.search(line)
cur_indent_level = first_nonspace.start() if first_nonspace else 0
if (cursect is not None and optname and
cur_indent_level > indent_level):
cursect[optname].append(value)
# a section header or option header?
else:
indent_level = cur_indent_level
# is it a section header?
mo = self.SECTCRE.match(value)
if mo:
sectname = mo.group('header')
if sectname in self._sections:
if self._strict and sectname in elements_added:
raise DuplicateSectionError(sectname, fpname,
lineno)
cursect = self._sections[sectname]
elements_added.add(sectname)
elif sectname == self.default_section:
cursect = self._defaults
else:
cursect = self._dict()
self._sections[sectname] = cursect
self._proxies[sectname] = SectionProxy(self, sectname)
elements_added.add(sectname)
# So sections can't start with a continuation line
optname = None
# no section header in the file?
elif cursect is None:
raise MissingSectionHeaderError(fpname, lineno, line)
# an option line?
else:
mo = self._optcre.match(value)
if mo:
optname, vi, optval = mo.group('option', 'vi', 'value')
if not optname:
e = self._handle_error(e, fpname, lineno, line)
optname = self.optionxform(optname.rstrip())
if (self._strict and
(sectname, optname) in elements_added):
raise DuplicateOptionError(sectname, optname,
fpname, lineno)
elements_added.add((sectname, optname))
# This check is fine because the OPTCRE cannot
# match if it would set optval to None
if optval is not None:
optval = optval.strip()
cursect[optname] = [optval]
else:
# valueless option handling
cursect[optname] = None
else:
# a non-fatal parsing error occurred. set up the
# exception but keep going. the exception will be
# raised at the end of the file and will contain a
# list of all bogus lines
e = self._handle_error(e, fpname, lineno, line)
self._join_multiline_values()
# if any parsing errors occurred, raise an exception
if e:
raise e | [
"def",
"_read",
"(",
"self",
",",
"fp",
",",
"fpname",
")",
":",
"elements_added",
"=",
"set",
"(",
")",
"cursect",
"=",
"None",
"# None, or a dictionary",
"sectname",
"=",
"None",
"optname",
"=",
"None",
"lineno",
"=",
"0",
"indent_level",
"=",
"0",
"e",
"=",
"None",
"# None, or an exception",
"for",
"lineno",
",",
"line",
"in",
"enumerate",
"(",
"fp",
",",
"start",
"=",
"1",
")",
":",
"comment_start",
"=",
"sys",
".",
"maxsize",
"# strip inline comments",
"inline_prefixes",
"=",
"{",
"p",
":",
"-",
"1",
"for",
"p",
"in",
"self",
".",
"_inline_comment_prefixes",
"}",
"while",
"comment_start",
"==",
"sys",
".",
"maxsize",
"and",
"inline_prefixes",
":",
"next_prefixes",
"=",
"{",
"}",
"for",
"prefix",
",",
"index",
"in",
"inline_prefixes",
".",
"items",
"(",
")",
":",
"index",
"=",
"line",
".",
"find",
"(",
"prefix",
",",
"index",
"+",
"1",
")",
"if",
"index",
"==",
"-",
"1",
":",
"continue",
"next_prefixes",
"[",
"prefix",
"]",
"=",
"index",
"if",
"index",
"==",
"0",
"or",
"(",
"index",
">",
"0",
"and",
"line",
"[",
"index",
"-",
"1",
"]",
".",
"isspace",
"(",
")",
")",
":",
"comment_start",
"=",
"min",
"(",
"comment_start",
",",
"index",
")",
"inline_prefixes",
"=",
"next_prefixes",
"# strip full line comments",
"for",
"prefix",
"in",
"self",
".",
"_comment_prefixes",
":",
"if",
"line",
".",
"strip",
"(",
")",
".",
"startswith",
"(",
"prefix",
")",
":",
"comment_start",
"=",
"0",
"break",
"if",
"comment_start",
"==",
"sys",
".",
"maxsize",
":",
"comment_start",
"=",
"None",
"value",
"=",
"line",
"[",
":",
"comment_start",
"]",
".",
"strip",
"(",
")",
"if",
"not",
"value",
":",
"if",
"self",
".",
"_empty_lines_in_values",
":",
"# add empty line to the value, but only if there was no",
"# comment on the line",
"if",
"(",
"comment_start",
"is",
"None",
"and",
"cursect",
"is",
"not",
"None",
"and",
"optname",
"and",
"cursect",
"[",
"optname",
"]",
"is",
"not",
"None",
")",
":",
"cursect",
"[",
"optname",
"]",
".",
"append",
"(",
"''",
")",
"# newlines added at join",
"else",
":",
"# empty line marks end of value",
"indent_level",
"=",
"sys",
".",
"maxsize",
"continue",
"# continuation line?",
"first_nonspace",
"=",
"self",
".",
"NONSPACECRE",
".",
"search",
"(",
"line",
")",
"cur_indent_level",
"=",
"first_nonspace",
".",
"start",
"(",
")",
"if",
"first_nonspace",
"else",
"0",
"if",
"(",
"cursect",
"is",
"not",
"None",
"and",
"optname",
"and",
"cur_indent_level",
">",
"indent_level",
")",
":",
"cursect",
"[",
"optname",
"]",
".",
"append",
"(",
"value",
")",
"# a section header or option header?",
"else",
":",
"indent_level",
"=",
"cur_indent_level",
"# is it a section header?",
"mo",
"=",
"self",
".",
"SECTCRE",
".",
"match",
"(",
"value",
")",
"if",
"mo",
":",
"sectname",
"=",
"mo",
".",
"group",
"(",
"'header'",
")",
"if",
"sectname",
"in",
"self",
".",
"_sections",
":",
"if",
"self",
".",
"_strict",
"and",
"sectname",
"in",
"elements_added",
":",
"raise",
"DuplicateSectionError",
"(",
"sectname",
",",
"fpname",
",",
"lineno",
")",
"cursect",
"=",
"self",
".",
"_sections",
"[",
"sectname",
"]",
"elements_added",
".",
"add",
"(",
"sectname",
")",
"elif",
"sectname",
"==",
"self",
".",
"default_section",
":",
"cursect",
"=",
"self",
".",
"_defaults",
"else",
":",
"cursect",
"=",
"self",
".",
"_dict",
"(",
")",
"self",
".",
"_sections",
"[",
"sectname",
"]",
"=",
"cursect",
"self",
".",
"_proxies",
"[",
"sectname",
"]",
"=",
"SectionProxy",
"(",
"self",
",",
"sectname",
")",
"elements_added",
".",
"add",
"(",
"sectname",
")",
"# So sections can't start with a continuation line",
"optname",
"=",
"None",
"# no section header in the file?",
"elif",
"cursect",
"is",
"None",
":",
"raise",
"MissingSectionHeaderError",
"(",
"fpname",
",",
"lineno",
",",
"line",
")",
"# an option line?",
"else",
":",
"mo",
"=",
"self",
".",
"_optcre",
".",
"match",
"(",
"value",
")",
"if",
"mo",
":",
"optname",
",",
"vi",
",",
"optval",
"=",
"mo",
".",
"group",
"(",
"'option'",
",",
"'vi'",
",",
"'value'",
")",
"if",
"not",
"optname",
":",
"e",
"=",
"self",
".",
"_handle_error",
"(",
"e",
",",
"fpname",
",",
"lineno",
",",
"line",
")",
"optname",
"=",
"self",
".",
"optionxform",
"(",
"optname",
".",
"rstrip",
"(",
")",
")",
"if",
"(",
"self",
".",
"_strict",
"and",
"(",
"sectname",
",",
"optname",
")",
"in",
"elements_added",
")",
":",
"raise",
"DuplicateOptionError",
"(",
"sectname",
",",
"optname",
",",
"fpname",
",",
"lineno",
")",
"elements_added",
".",
"add",
"(",
"(",
"sectname",
",",
"optname",
")",
")",
"# This check is fine because the OPTCRE cannot",
"# match if it would set optval to None",
"if",
"optval",
"is",
"not",
"None",
":",
"optval",
"=",
"optval",
".",
"strip",
"(",
")",
"cursect",
"[",
"optname",
"]",
"=",
"[",
"optval",
"]",
"else",
":",
"# valueless option handling",
"cursect",
"[",
"optname",
"]",
"=",
"None",
"else",
":",
"# a non-fatal parsing error occurred. set up the",
"# exception but keep going. the exception will be",
"# raised at the end of the file and will contain a",
"# list of all bogus lines",
"e",
"=",
"self",
".",
"_handle_error",
"(",
"e",
",",
"fpname",
",",
"lineno",
",",
"line",
")",
"self",
".",
"_join_multiline_values",
"(",
")",
"# if any parsing errors occurred, raise an exception",
"if",
"e",
":",
"raise",
"e"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/configparser.py#L990-L1110 |
||
cms-sw/cmssw | fd9de012d503d3405420bcbeec0ec879baa57cf2 | Validation/RecoTrack/python/plotting/ntupleDataFormat.py | python | _TrackingParticleMatchAdaptor.bestMatchingTrackingParticleFromFirstHit | (self) | return TrackingParticle(self._tree, idx) | Returns best-matching TrackingParticle, even for fake tracks, or None if there is no best-matching TrackingParticle.
Best-matching is defined as the one with largest number of
hits matched to the hits of a track (>= 3) starting from the
beginning of the track. If there are many fulfilling the same
number of hits, "a first TP" is chosen (a bit arbitrary, but
should be rare". | Returns best-matching TrackingParticle, even for fake tracks, or None if there is no best-matching TrackingParticle. | [
"Returns",
"best",
"-",
"matching",
"TrackingParticle",
"even",
"for",
"fake",
"tracks",
"or",
"None",
"if",
"there",
"is",
"no",
"best",
"-",
"matching",
"TrackingParticle",
"."
] | def bestMatchingTrackingParticleFromFirstHit(self):
"""Returns best-matching TrackingParticle, even for fake tracks, or None if there is no best-matching TrackingParticle.
Best-matching is defined as the one with largest number of
hits matched to the hits of a track (>= 3) starting from the
beginning of the track. If there are many fulfilling the same
number of hits, "a first TP" is chosen (a bit arbitrary, but
should be rare".
"""
idx = self.bestFromFirstHitSimTrkIdx()
if idx < 0:
return None
return TrackingParticle(self._tree, idx) | [
"def",
"bestMatchingTrackingParticleFromFirstHit",
"(",
"self",
")",
":",
"idx",
"=",
"self",
".",
"bestFromFirstHitSimTrkIdx",
"(",
")",
"if",
"idx",
"<",
"0",
":",
"return",
"None",
"return",
"TrackingParticle",
"(",
"self",
".",
"_tree",
",",
"idx",
")"
] | https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/Validation/RecoTrack/python/plotting/ntupleDataFormat.py#L350-L362 |
|
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/setuptools/py2/setuptools/archive_util.py | python | unpack_directory | (filename, extract_dir, progress_filter=default_filter) | Unpack" a directory, using the same interface as for archives
Raises ``UnrecognizedFormat`` if `filename` is not a directory | Unpack" a directory, using the same interface as for archives | [
"Unpack",
"a",
"directory",
"using",
"the",
"same",
"interface",
"as",
"for",
"archives"
] | def unpack_directory(filename, extract_dir, progress_filter=default_filter):
""""Unpack" a directory, using the same interface as for archives
Raises ``UnrecognizedFormat`` if `filename` is not a directory
"""
if not os.path.isdir(filename):
raise UnrecognizedFormat("%s is not a directory" % filename)
paths = {
filename: ('', extract_dir),
}
for base, dirs, files in os.walk(filename):
src, dst = paths[base]
for d in dirs:
paths[os.path.join(base, d)] = src + d + '/', os.path.join(dst, d)
for f in files:
target = os.path.join(dst, f)
target = progress_filter(src + f, target)
if not target:
# skip non-files
continue
ensure_directory(target)
f = os.path.join(base, f)
shutil.copyfile(f, target)
shutil.copystat(f, target) | [
"def",
"unpack_directory",
"(",
"filename",
",",
"extract_dir",
",",
"progress_filter",
"=",
"default_filter",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"filename",
")",
":",
"raise",
"UnrecognizedFormat",
"(",
"\"%s is not a directory\"",
"%",
"filename",
")",
"paths",
"=",
"{",
"filename",
":",
"(",
"''",
",",
"extract_dir",
")",
",",
"}",
"for",
"base",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"filename",
")",
":",
"src",
",",
"dst",
"=",
"paths",
"[",
"base",
"]",
"for",
"d",
"in",
"dirs",
":",
"paths",
"[",
"os",
".",
"path",
".",
"join",
"(",
"base",
",",
"d",
")",
"]",
"=",
"src",
"+",
"d",
"+",
"'/'",
",",
"os",
".",
"path",
".",
"join",
"(",
"dst",
",",
"d",
")",
"for",
"f",
"in",
"files",
":",
"target",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dst",
",",
"f",
")",
"target",
"=",
"progress_filter",
"(",
"src",
"+",
"f",
",",
"target",
")",
"if",
"not",
"target",
":",
"# skip non-files",
"continue",
"ensure_directory",
"(",
"target",
")",
"f",
"=",
"os",
".",
"path",
".",
"join",
"(",
"base",
",",
"f",
")",
"shutil",
".",
"copyfile",
"(",
"f",
",",
"target",
")",
"shutil",
".",
"copystat",
"(",
"f",
",",
"target",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py2/setuptools/archive_util.py#L63-L87 |
||
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/fitting_widgets/general_fitting/general_fitting_presenter.py | python | GeneralFittingPresenter.handle_fitting_mode_changed | (self) | Handle when the fitting mode is changed to or from simultaneous fitting. | Handle when the fitting mode is changed to or from simultaneous fitting. | [
"Handle",
"when",
"the",
"fitting",
"mode",
"is",
"changed",
"to",
"or",
"from",
"simultaneous",
"fitting",
"."
] | def handle_fitting_mode_changed(self) -> None:
"""Handle when the fitting mode is changed to or from simultaneous fitting."""
self.model.simultaneous_fitting_mode = self.view.simultaneous_fitting_mode
self.switch_fitting_mode_in_view()
self.update_fit_functions_in_model_from_view()
# Triggers handle_dataset_name_changed
self.update_dataset_names_in_view_and_model()
self.automatically_update_function_name()
self.reset_fit_status_and_chi_squared_information()
self.clear_undo_data()
self.fitting_mode_changed_notifier.notify_subscribers()
self.fit_function_changed_notifier.notify_subscribers() | [
"def",
"handle_fitting_mode_changed",
"(",
"self",
")",
"->",
"None",
":",
"self",
".",
"model",
".",
"simultaneous_fitting_mode",
"=",
"self",
".",
"view",
".",
"simultaneous_fitting_mode",
"self",
".",
"switch_fitting_mode_in_view",
"(",
")",
"self",
".",
"update_fit_functions_in_model_from_view",
"(",
")",
"# Triggers handle_dataset_name_changed",
"self",
".",
"update_dataset_names_in_view_and_model",
"(",
")",
"self",
".",
"automatically_update_function_name",
"(",
")",
"self",
".",
"reset_fit_status_and_chi_squared_information",
"(",
")",
"self",
".",
"clear_undo_data",
"(",
")",
"self",
".",
"fitting_mode_changed_notifier",
".",
"notify_subscribers",
"(",
")",
"self",
".",
"fit_function_changed_notifier",
".",
"notify_subscribers",
"(",
")"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/fitting_widgets/general_fitting/general_fitting_presenter.py#L42-L58 |
||
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/ops/composite/multitype_ops/div_impl.py | python | _tensor_div_tuple | (x, y) | return F.tensor_div(x, y) | Tensor divided by tuple.
Args:
x (Tensor): x
y (Tuple): The dtype is same as x.
Returns:
Tensor, has the same dtype as x. | Tensor divided by tuple. | [
"Tensor",
"divided",
"by",
"tuple",
"."
] | def _tensor_div_tuple(x, y):
"""
Tensor divided by tuple.
Args:
x (Tensor): x
y (Tuple): The dtype is same as x.
Returns:
Tensor, has the same dtype as x.
"""
y = utils.sequence_to_tensor(y, x.dtype)
return F.tensor_div(x, y) | [
"def",
"_tensor_div_tuple",
"(",
"x",
",",
"y",
")",
":",
"y",
"=",
"utils",
".",
"sequence_to_tensor",
"(",
"y",
",",
"x",
".",
"dtype",
")",
"return",
"F",
".",
"tensor_div",
"(",
"x",
",",
"y",
")"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/composite/multitype_ops/div_impl.py#L107-L119 |
|
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/eager/def_function.py | python | Function._initialize | (self, args, kwds, add_initializers_to=None) | Initializes, on the first call.
Creates two `Function`s, one that will allow creation of variables
and one that won't.
Additionally runs a trace for the `Function` that allows creation
of variables.
Args:
args: Arguments to the underlying python callable.
kwds: Keyword arguments to the python callable.
add_initializers_to: Where to collect variable initializers, if not None. | Initializes, on the first call. | [
"Initializes",
"on",
"the",
"first",
"call",
"."
] | def _initialize(self, args, kwds, add_initializers_to=None):
"""Initializes, on the first call.
Creates two `Function`s, one that will allow creation of variables
and one that won't.
Additionally runs a trace for the `Function` that allows creation
of variables.
Args:
args: Arguments to the underlying python callable.
kwds: Keyword arguments to the python callable.
add_initializers_to: Where to collect variable initializers, if not None.
"""
created_variables = []
lifted_initializer_graph = func_graph_module.FuncGraph("initializer")
def variable_capturing_scope(unused_next_creator, **kwds):
"""Creates UnliftedInitializerVariables and saves references to them."""
v = UnliftedInitializerVariable(
add_initializers_to=add_initializers_to,
lifted_initializer_graph=lifted_initializer_graph, **kwds)
created_variables.append(weakref.ref(v))
return v
self._created_variables = created_variables
self._stateful_fn = self._defun_with_scope(variable_capturing_scope)
self._stateful_fn._name = self._name # pylint: disable=protected-access
# Force the definition of the function for these arguments
self._lifted_initializer_graph = lifted_initializer_graph
self._graph_deleter = FunctionDeleter(self._lifted_initializer_graph)
self._concrete_stateful_fn = (
self._stateful_fn._get_concrete_function_internal_garbage_collected( # pylint: disable=protected-access
*args, **kwds))
def invalid_creator_scope(*unused_args, **unused_kwds):
"""Disables variable creation."""
raise ValueError(
"tf.function-decorated function tried to create "
"variables on non-first call.")
self._stateless_fn = self._defun_with_scope(invalid_creator_scope)
self._stateless_fn._name = self._name | [
"def",
"_initialize",
"(",
"self",
",",
"args",
",",
"kwds",
",",
"add_initializers_to",
"=",
"None",
")",
":",
"created_variables",
"=",
"[",
"]",
"lifted_initializer_graph",
"=",
"func_graph_module",
".",
"FuncGraph",
"(",
"\"initializer\"",
")",
"def",
"variable_capturing_scope",
"(",
"unused_next_creator",
",",
"*",
"*",
"kwds",
")",
":",
"\"\"\"Creates UnliftedInitializerVariables and saves references to them.\"\"\"",
"v",
"=",
"UnliftedInitializerVariable",
"(",
"add_initializers_to",
"=",
"add_initializers_to",
",",
"lifted_initializer_graph",
"=",
"lifted_initializer_graph",
",",
"*",
"*",
"kwds",
")",
"created_variables",
".",
"append",
"(",
"weakref",
".",
"ref",
"(",
"v",
")",
")",
"return",
"v",
"self",
".",
"_created_variables",
"=",
"created_variables",
"self",
".",
"_stateful_fn",
"=",
"self",
".",
"_defun_with_scope",
"(",
"variable_capturing_scope",
")",
"self",
".",
"_stateful_fn",
".",
"_name",
"=",
"self",
".",
"_name",
"# pylint: disable=protected-access",
"# Force the definition of the function for these arguments",
"self",
".",
"_lifted_initializer_graph",
"=",
"lifted_initializer_graph",
"self",
".",
"_graph_deleter",
"=",
"FunctionDeleter",
"(",
"self",
".",
"_lifted_initializer_graph",
")",
"self",
".",
"_concrete_stateful_fn",
"=",
"(",
"self",
".",
"_stateful_fn",
".",
"_get_concrete_function_internal_garbage_collected",
"(",
"# pylint: disable=protected-access",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
")",
"def",
"invalid_creator_scope",
"(",
"*",
"unused_args",
",",
"*",
"*",
"unused_kwds",
")",
":",
"\"\"\"Disables variable creation.\"\"\"",
"raise",
"ValueError",
"(",
"\"tf.function-decorated function tried to create \"",
"\"variables on non-first call.\"",
")",
"self",
".",
"_stateless_fn",
"=",
"self",
".",
"_defun_with_scope",
"(",
"invalid_creator_scope",
")",
"self",
".",
"_stateless_fn",
".",
"_name",
"=",
"self",
".",
"_name"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/eager/def_function.py#L358-L401 |
||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py2/scipy/signal/_peak_finding.py | python | _select_by_peak_threshold | (x, peaks, tmin, tmax) | return keep, stacked_thresholds[0], stacked_thresholds[1] | Evaluate which peaks fulfill the threshold condition.
Parameters
----------
x : ndarray
A one-dimensional array which is indexable by `peaks`.
peaks : ndarray
Indices of peaks in `x`.
tmin, tmax : scalar or ndarray or None
Minimal and / or maximal required thresholds. If supplied as ndarrays
their size must match `peaks`. ``None`` is interpreted as an open
border.
Returns
-------
keep : bool
A boolean mask evaluating to true where `peaks` fulfill the threshold
condition.
left_thresholds, right_thresholds : ndarray
Array matching `peak` containing the thresholds of each peak on
both sides.
Notes
-----
.. versionadded:: 1.1.0 | Evaluate which peaks fulfill the threshold condition. | [
"Evaluate",
"which",
"peaks",
"fulfill",
"the",
"threshold",
"condition",
"."
] | def _select_by_peak_threshold(x, peaks, tmin, tmax):
"""
Evaluate which peaks fulfill the threshold condition.
Parameters
----------
x : ndarray
A one-dimensional array which is indexable by `peaks`.
peaks : ndarray
Indices of peaks in `x`.
tmin, tmax : scalar or ndarray or None
Minimal and / or maximal required thresholds. If supplied as ndarrays
their size must match `peaks`. ``None`` is interpreted as an open
border.
Returns
-------
keep : bool
A boolean mask evaluating to true where `peaks` fulfill the threshold
condition.
left_thresholds, right_thresholds : ndarray
Array matching `peak` containing the thresholds of each peak on
both sides.
Notes
-----
.. versionadded:: 1.1.0
"""
# Stack thresholds on both sides to make min / max operations easier:
# tmin is compared with the smaller, and tmax with the greater thresold to
# each peak's side
stacked_thresholds = np.vstack([x[peaks] - x[peaks - 1],
x[peaks] - x[peaks + 1]])
keep = np.ones(peaks.size, dtype=bool)
if tmin is not None:
min_thresholds = np.min(stacked_thresholds, axis=0)
keep &= (tmin <= min_thresholds)
if tmax is not None:
max_thresholds = np.max(stacked_thresholds, axis=0)
keep &= (max_thresholds <= tmax)
return keep, stacked_thresholds[0], stacked_thresholds[1] | [
"def",
"_select_by_peak_threshold",
"(",
"x",
",",
"peaks",
",",
"tmin",
",",
"tmax",
")",
":",
"# Stack thresholds on both sides to make min / max operations easier:",
"# tmin is compared with the smaller, and tmax with the greater thresold to",
"# each peak's side",
"stacked_thresholds",
"=",
"np",
".",
"vstack",
"(",
"[",
"x",
"[",
"peaks",
"]",
"-",
"x",
"[",
"peaks",
"-",
"1",
"]",
",",
"x",
"[",
"peaks",
"]",
"-",
"x",
"[",
"peaks",
"+",
"1",
"]",
"]",
")",
"keep",
"=",
"np",
".",
"ones",
"(",
"peaks",
".",
"size",
",",
"dtype",
"=",
"bool",
")",
"if",
"tmin",
"is",
"not",
"None",
":",
"min_thresholds",
"=",
"np",
".",
"min",
"(",
"stacked_thresholds",
",",
"axis",
"=",
"0",
")",
"keep",
"&=",
"(",
"tmin",
"<=",
"min_thresholds",
")",
"if",
"tmax",
"is",
"not",
"None",
":",
"max_thresholds",
"=",
"np",
".",
"max",
"(",
"stacked_thresholds",
",",
"axis",
"=",
"0",
")",
"keep",
"&=",
"(",
"max_thresholds",
"<=",
"tmax",
")",
"return",
"keep",
",",
"stacked_thresholds",
"[",
"0",
"]",
",",
"stacked_thresholds",
"[",
"1",
"]"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/signal/_peak_finding.py#L681-L723 |
|
sdhash/sdhash | b9eff63e4e5867e910f41fd69032bbb1c94a2a5e | external/tools/build/v2/build/property_set.py | python | PropertySet.get | (self, feature) | return self.feature_map_.get(feature, []) | Returns all values of 'feature'. | Returns all values of 'feature'. | [
"Returns",
"all",
"values",
"of",
"feature",
"."
] | def get (self, feature):
""" Returns all values of 'feature'.
"""
if type(feature) == type([]):
feature = feature[0]
if not isinstance(feature, b2.build.feature.Feature):
feature = b2.build.feature.get(feature)
if not self.feature_map_:
self.feature_map_ = {}
for v in self.all_:
if not self.feature_map_.has_key(v.feature()):
self.feature_map_[v.feature()] = []
self.feature_map_[v.feature()].append(v.value())
return self.feature_map_.get(feature, []) | [
"def",
"get",
"(",
"self",
",",
"feature",
")",
":",
"if",
"type",
"(",
"feature",
")",
"==",
"type",
"(",
"[",
"]",
")",
":",
"feature",
"=",
"feature",
"[",
"0",
"]",
"if",
"not",
"isinstance",
"(",
"feature",
",",
"b2",
".",
"build",
".",
"feature",
".",
"Feature",
")",
":",
"feature",
"=",
"b2",
".",
"build",
".",
"feature",
".",
"get",
"(",
"feature",
")",
"if",
"not",
"self",
".",
"feature_map_",
":",
"self",
".",
"feature_map_",
"=",
"{",
"}",
"for",
"v",
"in",
"self",
".",
"all_",
":",
"if",
"not",
"self",
".",
"feature_map_",
".",
"has_key",
"(",
"v",
".",
"feature",
"(",
")",
")",
":",
"self",
".",
"feature_map_",
"[",
"v",
".",
"feature",
"(",
")",
"]",
"=",
"[",
"]",
"self",
".",
"feature_map_",
"[",
"v",
".",
"feature",
"(",
")",
"]",
".",
"append",
"(",
"v",
".",
"value",
"(",
")",
")",
"return",
"self",
".",
"feature_map_",
".",
"get",
"(",
"feature",
",",
"[",
"]",
")"
] | https://github.com/sdhash/sdhash/blob/b9eff63e4e5867e910f41fd69032bbb1c94a2a5e/external/tools/build/v2/build/property_set.py#L416-L432 |
|
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/polynomial/hermite.py | python | _normed_hermite_n | (x, n) | return c0 + c1*x*np.sqrt(2) | Evaluate a normalized Hermite polynomial.
Compute the value of the normalized Hermite polynomial of degree ``n``
at the points ``x``.
Parameters
----------
x : ndarray of double.
Points at which to evaluate the function
n : int
Degree of the normalized Hermite function to be evaluated.
Returns
-------
values : ndarray
The shape of the return value is described above.
Notes
-----
.. versionadded:: 1.10.0
This function is needed for finding the Gauss points and integration
weights for high degrees. The values of the standard Hermite functions
overflow when n >= 207. | Evaluate a normalized Hermite polynomial. | [
"Evaluate",
"a",
"normalized",
"Hermite",
"polynomial",
"."
] | def _normed_hermite_n(x, n):
"""
Evaluate a normalized Hermite polynomial.
Compute the value of the normalized Hermite polynomial of degree ``n``
at the points ``x``.
Parameters
----------
x : ndarray of double.
Points at which to evaluate the function
n : int
Degree of the normalized Hermite function to be evaluated.
Returns
-------
values : ndarray
The shape of the return value is described above.
Notes
-----
.. versionadded:: 1.10.0
This function is needed for finding the Gauss points and integration
weights for high degrees. The values of the standard Hermite functions
overflow when n >= 207.
"""
if n == 0:
return np.full(x.shape, 1/np.sqrt(np.sqrt(np.pi)))
c0 = 0.
c1 = 1./np.sqrt(np.sqrt(np.pi))
nd = float(n)
for i in range(n - 1):
tmp = c0
c0 = -c1*np.sqrt((nd - 1.)/nd)
c1 = tmp + c1*x*np.sqrt(2./nd)
nd = nd - 1.0
return c0 + c1*x*np.sqrt(2) | [
"def",
"_normed_hermite_n",
"(",
"x",
",",
"n",
")",
":",
"if",
"n",
"==",
"0",
":",
"return",
"np",
".",
"full",
"(",
"x",
".",
"shape",
",",
"1",
"/",
"np",
".",
"sqrt",
"(",
"np",
".",
"sqrt",
"(",
"np",
".",
"pi",
")",
")",
")",
"c0",
"=",
"0.",
"c1",
"=",
"1.",
"/",
"np",
".",
"sqrt",
"(",
"np",
".",
"sqrt",
"(",
"np",
".",
"pi",
")",
")",
"nd",
"=",
"float",
"(",
"n",
")",
"for",
"i",
"in",
"range",
"(",
"n",
"-",
"1",
")",
":",
"tmp",
"=",
"c0",
"c0",
"=",
"-",
"c1",
"*",
"np",
".",
"sqrt",
"(",
"(",
"nd",
"-",
"1.",
")",
"/",
"nd",
")",
"c1",
"=",
"tmp",
"+",
"c1",
"*",
"x",
"*",
"np",
".",
"sqrt",
"(",
"2.",
"/",
"nd",
")",
"nd",
"=",
"nd",
"-",
"1.0",
"return",
"c0",
"+",
"c1",
"*",
"x",
"*",
"np",
".",
"sqrt",
"(",
"2",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/polynomial/hermite.py#L1485-L1525 |
|
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/six.py | python | add_metaclass | (metaclass) | return wrapper | Class decorator for creating a class with a metaclass. | Class decorator for creating a class with a metaclass. | [
"Class",
"decorator",
"for",
"creating",
"a",
"class",
"with",
"a",
"metaclass",
"."
] | def add_metaclass(metaclass):
"""Class decorator for creating a class with a metaclass."""
def wrapper(cls):
orig_vars = cls.__dict__.copy()
slots = orig_vars.get('__slots__')
if slots is not None:
if isinstance(slots, str):
slots = [slots]
for slots_var in slots:
orig_vars.pop(slots_var)
orig_vars.pop('__dict__', None)
orig_vars.pop('__weakref__', None)
return metaclass(cls.__name__, cls.__bases__, orig_vars)
return wrapper | [
"def",
"add_metaclass",
"(",
"metaclass",
")",
":",
"def",
"wrapper",
"(",
"cls",
")",
":",
"orig_vars",
"=",
"cls",
".",
"__dict__",
".",
"copy",
"(",
")",
"slots",
"=",
"orig_vars",
".",
"get",
"(",
"'__slots__'",
")",
"if",
"slots",
"is",
"not",
"None",
":",
"if",
"isinstance",
"(",
"slots",
",",
"str",
")",
":",
"slots",
"=",
"[",
"slots",
"]",
"for",
"slots_var",
"in",
"slots",
":",
"orig_vars",
".",
"pop",
"(",
"slots_var",
")",
"orig_vars",
".",
"pop",
"(",
"'__dict__'",
",",
"None",
")",
"orig_vars",
".",
"pop",
"(",
"'__weakref__'",
",",
"None",
")",
"return",
"metaclass",
"(",
"cls",
".",
"__name__",
",",
"cls",
".",
"__bases__",
",",
"orig_vars",
")",
"return",
"wrapper"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/six.py#L801-L814 |
|
Slicer/SlicerGitSVNArchive | 65e92bb16c2b32ea47a1a66bee71f238891ee1ca | Modules/Scripted/DICOMPlugins/DICOMScalarVolumePlugin.py | python | DICOMScalarVolumePluginClass.loadFilesWithSeriesReader | (self,imageIOName,files,name) | return(volumeNode) | Explicitly use the named imageIO to perform the loading | Explicitly use the named imageIO to perform the loading | [
"Explicitly",
"use",
"the",
"named",
"imageIO",
"to",
"perform",
"the",
"loading"
] | def loadFilesWithSeriesReader(self,imageIOName,files,name):
""" Explicitly use the named imageIO to perform the loading
"""
reader = vtkITK.vtkITKArchetypeImageSeriesScalarReader()
reader.SetArchetype(files[0]);
for f in files:
reader.AddFileName(f)
reader.SetSingleFile(0);
reader.SetOutputScalarTypeToNative()
reader.SetDesiredCoordinateOrientationToNative()
reader.SetUseNativeOriginOn()
if imageIOName == "GDCM":
reader.SetDICOMImageIOApproachToGDCM()
elif imageIOName == "DCMTK":
reader.SetDICOMImageIOApproachToDCMTK()
else:
raise Exception("Invalid imageIOName of %s" % imageIOName)
logging.info("Loading with imageIOName: %s" % imageIOName)
reader.Update()
slicer.modules.reader = reader
if reader.GetErrorCode() != vtk.vtkErrorCode.NoError:
errorStrings = (imageIOName, vtk.vtkErrorCode.GetStringFromErrorCode(reader.GetErrorCode()))
logging.error("Could not read scalar volume using %s approach. Error is: %s" % errorStrings)
return
imageChangeInformation = vtk.vtkImageChangeInformation()
imageChangeInformation.SetInputConnection(reader.GetOutputPort())
imageChangeInformation.SetOutputSpacing( 1, 1, 1 )
imageChangeInformation.SetOutputOrigin( 0, 0, 0 )
imageChangeInformation.Update()
name = slicer.mrmlScene.GenerateUniqueName(name)
volumeNode = slicer.mrmlScene.AddNewNodeByClass("vtkMRMLScalarVolumeNode", name)
volumeNode.SetAndObserveImageData(imageChangeInformation.GetOutputDataObject(0))
slicer.vtkMRMLVolumeArchetypeStorageNode.SetMetaDataDictionaryFromReader(volumeNode, reader)
volumeNode.SetRASToIJKMatrix(reader.GetRasToIjkMatrix())
volumeNode.CreateDefaultDisplayNodes()
slicer.modules.DICOMInstance.reader = reader
slicer.modules.DICOMInstance.imageChangeInformation = imageChangeInformation
return(volumeNode) | [
"def",
"loadFilesWithSeriesReader",
"(",
"self",
",",
"imageIOName",
",",
"files",
",",
"name",
")",
":",
"reader",
"=",
"vtkITK",
".",
"vtkITKArchetypeImageSeriesScalarReader",
"(",
")",
"reader",
".",
"SetArchetype",
"(",
"files",
"[",
"0",
"]",
")",
"for",
"f",
"in",
"files",
":",
"reader",
".",
"AddFileName",
"(",
"f",
")",
"reader",
".",
"SetSingleFile",
"(",
"0",
")",
"reader",
".",
"SetOutputScalarTypeToNative",
"(",
")",
"reader",
".",
"SetDesiredCoordinateOrientationToNative",
"(",
")",
"reader",
".",
"SetUseNativeOriginOn",
"(",
")",
"if",
"imageIOName",
"==",
"\"GDCM\"",
":",
"reader",
".",
"SetDICOMImageIOApproachToGDCM",
"(",
")",
"elif",
"imageIOName",
"==",
"\"DCMTK\"",
":",
"reader",
".",
"SetDICOMImageIOApproachToDCMTK",
"(",
")",
"else",
":",
"raise",
"Exception",
"(",
"\"Invalid imageIOName of %s\"",
"%",
"imageIOName",
")",
"logging",
".",
"info",
"(",
"\"Loading with imageIOName: %s\"",
"%",
"imageIOName",
")",
"reader",
".",
"Update",
"(",
")",
"slicer",
".",
"modules",
".",
"reader",
"=",
"reader",
"if",
"reader",
".",
"GetErrorCode",
"(",
")",
"!=",
"vtk",
".",
"vtkErrorCode",
".",
"NoError",
":",
"errorStrings",
"=",
"(",
"imageIOName",
",",
"vtk",
".",
"vtkErrorCode",
".",
"GetStringFromErrorCode",
"(",
"reader",
".",
"GetErrorCode",
"(",
")",
")",
")",
"logging",
".",
"error",
"(",
"\"Could not read scalar volume using %s approach. Error is: %s\"",
"%",
"errorStrings",
")",
"return",
"imageChangeInformation",
"=",
"vtk",
".",
"vtkImageChangeInformation",
"(",
")",
"imageChangeInformation",
".",
"SetInputConnection",
"(",
"reader",
".",
"GetOutputPort",
"(",
")",
")",
"imageChangeInformation",
".",
"SetOutputSpacing",
"(",
"1",
",",
"1",
",",
"1",
")",
"imageChangeInformation",
".",
"SetOutputOrigin",
"(",
"0",
",",
"0",
",",
"0",
")",
"imageChangeInformation",
".",
"Update",
"(",
")",
"name",
"=",
"slicer",
".",
"mrmlScene",
".",
"GenerateUniqueName",
"(",
"name",
")",
"volumeNode",
"=",
"slicer",
".",
"mrmlScene",
".",
"AddNewNodeByClass",
"(",
"\"vtkMRMLScalarVolumeNode\"",
",",
"name",
")",
"volumeNode",
".",
"SetAndObserveImageData",
"(",
"imageChangeInformation",
".",
"GetOutputDataObject",
"(",
"0",
")",
")",
"slicer",
".",
"vtkMRMLVolumeArchetypeStorageNode",
".",
"SetMetaDataDictionaryFromReader",
"(",
"volumeNode",
",",
"reader",
")",
"volumeNode",
".",
"SetRASToIJKMatrix",
"(",
"reader",
".",
"GetRasToIjkMatrix",
"(",
")",
")",
"volumeNode",
".",
"CreateDefaultDisplayNodes",
"(",
")",
"slicer",
".",
"modules",
".",
"DICOMInstance",
".",
"reader",
"=",
"reader",
"slicer",
".",
"modules",
".",
"DICOMInstance",
".",
"imageChangeInformation",
"=",
"imageChangeInformation",
"return",
"(",
"volumeNode",
")"
] | https://github.com/Slicer/SlicerGitSVNArchive/blob/65e92bb16c2b32ea47a1a66bee71f238891ee1ca/Modules/Scripted/DICOMPlugins/DICOMScalarVolumePlugin.py#L300-L344 |
|
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/boto/boto/ec2/securitygroup.py | python | SecurityGroup.copy_to_region | (self, region, name=None, dry_run=False) | return sg | Create a copy of this security group in another region.
Note that the new security group will be a separate entity
and will not stay in sync automatically after the copy
operation.
:type region: :class:`boto.ec2.regioninfo.RegionInfo`
:param region: The region to which this security group will be copied.
:type name: string
:param name: The name of the copy. If not supplied, the copy
will have the same name as this security group.
:rtype: :class:`boto.ec2.securitygroup.SecurityGroup`
:return: The new security group. | Create a copy of this security group in another region.
Note that the new security group will be a separate entity
and will not stay in sync automatically after the copy
operation. | [
"Create",
"a",
"copy",
"of",
"this",
"security",
"group",
"in",
"another",
"region",
".",
"Note",
"that",
"the",
"new",
"security",
"group",
"will",
"be",
"a",
"separate",
"entity",
"and",
"will",
"not",
"stay",
"in",
"sync",
"automatically",
"after",
"the",
"copy",
"operation",
"."
] | def copy_to_region(self, region, name=None, dry_run=False):
"""
Create a copy of this security group in another region.
Note that the new security group will be a separate entity
and will not stay in sync automatically after the copy
operation.
:type region: :class:`boto.ec2.regioninfo.RegionInfo`
:param region: The region to which this security group will be copied.
:type name: string
:param name: The name of the copy. If not supplied, the copy
will have the same name as this security group.
:rtype: :class:`boto.ec2.securitygroup.SecurityGroup`
:return: The new security group.
"""
if region.name == self.region:
raise BotoClientError('Unable to copy to the same Region')
conn_params = self.connection.get_params()
rconn = region.connect(**conn_params)
sg = rconn.create_security_group(
name or self.name,
self.description,
dry_run=dry_run
)
source_groups = []
for rule in self.rules:
for grant in rule.grants:
grant_nom = grant.name or grant.group_id
if grant_nom:
if grant_nom not in source_groups:
source_groups.append(grant_nom)
sg.authorize(None, None, None, None, grant,
dry_run=dry_run)
else:
sg.authorize(rule.ip_protocol, rule.from_port, rule.to_port,
grant.cidr_ip, dry_run=dry_run)
return sg | [
"def",
"copy_to_region",
"(",
"self",
",",
"region",
",",
"name",
"=",
"None",
",",
"dry_run",
"=",
"False",
")",
":",
"if",
"region",
".",
"name",
"==",
"self",
".",
"region",
":",
"raise",
"BotoClientError",
"(",
"'Unable to copy to the same Region'",
")",
"conn_params",
"=",
"self",
".",
"connection",
".",
"get_params",
"(",
")",
"rconn",
"=",
"region",
".",
"connect",
"(",
"*",
"*",
"conn_params",
")",
"sg",
"=",
"rconn",
".",
"create_security_group",
"(",
"name",
"or",
"self",
".",
"name",
",",
"self",
".",
"description",
",",
"dry_run",
"=",
"dry_run",
")",
"source_groups",
"=",
"[",
"]",
"for",
"rule",
"in",
"self",
".",
"rules",
":",
"for",
"grant",
"in",
"rule",
".",
"grants",
":",
"grant_nom",
"=",
"grant",
".",
"name",
"or",
"grant",
".",
"group_id",
"if",
"grant_nom",
":",
"if",
"grant_nom",
"not",
"in",
"source_groups",
":",
"source_groups",
".",
"append",
"(",
"grant_nom",
")",
"sg",
".",
"authorize",
"(",
"None",
",",
"None",
",",
"None",
",",
"None",
",",
"grant",
",",
"dry_run",
"=",
"dry_run",
")",
"else",
":",
"sg",
".",
"authorize",
"(",
"rule",
".",
"ip_protocol",
",",
"rule",
".",
"from_port",
",",
"rule",
".",
"to_port",
",",
"grant",
".",
"cidr_ip",
",",
"dry_run",
"=",
"dry_run",
")",
"return",
"sg"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/ec2/securitygroup.py#L250-L288 |
|
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/python/ops/sparse_ops.py | python | sparse_merge | (sp_ids, sp_values, vocab_size, name=None,
already_sorted=False) | Combines a batch of feature ids and values into a single `SparseTensor`.
The most common use case for this function occurs when feature ids and
their corresponding values are stored in `Example` protos on disk.
`parse_example` will return a batch of ids and a batch of values, and this
function joins them into a single logical `SparseTensor` for use in
functions such as `sparse_tensor_dense_matmul`, `sparse_to_dense`, etc.
The `SparseTensor` returned by this function has the following properties:
- `indices` is equivalent to `sp_ids.indices` with the last
dimension discarded and replaced with `sp_ids.values`.
- `values` is simply `sp_values.values`.
- If `sp_ids.shape = [D0, D1, ..., Dn, K]`, then
`output.shape = [D0, D1, ..., Dn, vocab_size]`.
For example, consider the following feature vectors:
```python
vector1 = [-3, 0, 0, 0, 0, 0]
vector2 = [ 0, 1, 0, 4, 1, 0]
vector3 = [ 5, 0, 0, 9, 0, 0]
```
These might be stored sparsely in the following Example protos by storing
only the feature ids (column number if the vectors are treated as a matrix)
of the non-zero elements and the corresponding values:
```python
examples = [Example(features={
"ids": Feature(int64_list=Int64List(value=[0])),
"values": Feature(float_list=FloatList(value=[-3]))}),
Example(features={
"ids": Feature(int64_list=Int64List(value=[1, 4, 3])),
"values": Feature(float_list=FloatList(value=[1, 1, 4]))}),
Example(features={
"ids": Feature(int64_list=Int64List(value=[0, 3])),
"values": Feature(float_list=FloatList(value=[5, 9]))})]
```
The result of calling parse_example on these examples will produce a
dictionary with entries for "ids" and "values". Passing those two objects
to this function along with vocab_size=6, will produce a `SparseTensor` that
sparsely represents all three instances. Namely, the `indices` property will
contain the coordinates of the non-zero entries in the feature matrix (the
first dimension is the row number in the matrix, i.e., the index within the
batch, and the second dimension is the column number, i.e., the feature id);
`values` will contain the actual values. `shape` will be the shape of the
original matrix, i.e., (3, 6). For our example above, the output will be
equal to:
```python
SparseTensor(indices=[[0, 0], [1, 1], [1, 3], [1, 4], [2, 0], [2, 3]],
values=[-3, 1, 4, 1, 5, 9],
shape=[3, 6])
```
Args:
sp_ids: A `SparseTensor` with `values` property of type `int32`
or `int64`.
sp_values: A`SparseTensor` of any type.
vocab_size: A scalar `int64` Tensor (or Python int) containing the new size
of the last dimension, `all(0 <= sp_ids.values < vocab_size)`.
name: A name prefix for the returned tensors (optional)
already_sorted: A boolean to specify whether the per-batch values in
`sp_values` are already sorted. If so skip sorting, False by default
(optional).
Returns:
A `SparseTensor` compactly representing a batch of feature ids and values,
useful for passing to functions that expect such a `SparseTensor`.
Raises:
TypeError: If `sp_ids` or `sp_values` are not a `SparseTensor`. | Combines a batch of feature ids and values into a single `SparseTensor`. | [
"Combines",
"a",
"batch",
"of",
"feature",
"ids",
"and",
"values",
"into",
"a",
"single",
"SparseTensor",
"."
] | def sparse_merge(sp_ids, sp_values, vocab_size, name=None,
already_sorted=False):
"""Combines a batch of feature ids and values into a single `SparseTensor`.
The most common use case for this function occurs when feature ids and
their corresponding values are stored in `Example` protos on disk.
`parse_example` will return a batch of ids and a batch of values, and this
function joins them into a single logical `SparseTensor` for use in
functions such as `sparse_tensor_dense_matmul`, `sparse_to_dense`, etc.
The `SparseTensor` returned by this function has the following properties:
- `indices` is equivalent to `sp_ids.indices` with the last
dimension discarded and replaced with `sp_ids.values`.
- `values` is simply `sp_values.values`.
- If `sp_ids.shape = [D0, D1, ..., Dn, K]`, then
`output.shape = [D0, D1, ..., Dn, vocab_size]`.
For example, consider the following feature vectors:
```python
vector1 = [-3, 0, 0, 0, 0, 0]
vector2 = [ 0, 1, 0, 4, 1, 0]
vector3 = [ 5, 0, 0, 9, 0, 0]
```
These might be stored sparsely in the following Example protos by storing
only the feature ids (column number if the vectors are treated as a matrix)
of the non-zero elements and the corresponding values:
```python
examples = [Example(features={
"ids": Feature(int64_list=Int64List(value=[0])),
"values": Feature(float_list=FloatList(value=[-3]))}),
Example(features={
"ids": Feature(int64_list=Int64List(value=[1, 4, 3])),
"values": Feature(float_list=FloatList(value=[1, 1, 4]))}),
Example(features={
"ids": Feature(int64_list=Int64List(value=[0, 3])),
"values": Feature(float_list=FloatList(value=[5, 9]))})]
```
The result of calling parse_example on these examples will produce a
dictionary with entries for "ids" and "values". Passing those two objects
to this function along with vocab_size=6, will produce a `SparseTensor` that
sparsely represents all three instances. Namely, the `indices` property will
contain the coordinates of the non-zero entries in the feature matrix (the
first dimension is the row number in the matrix, i.e., the index within the
batch, and the second dimension is the column number, i.e., the feature id);
`values` will contain the actual values. `shape` will be the shape of the
original matrix, i.e., (3, 6). For our example above, the output will be
equal to:
```python
SparseTensor(indices=[[0, 0], [1, 1], [1, 3], [1, 4], [2, 0], [2, 3]],
values=[-3, 1, 4, 1, 5, 9],
shape=[3, 6])
```
Args:
sp_ids: A `SparseTensor` with `values` property of type `int32`
or `int64`.
sp_values: A`SparseTensor` of any type.
vocab_size: A scalar `int64` Tensor (or Python int) containing the new size
of the last dimension, `all(0 <= sp_ids.values < vocab_size)`.
name: A name prefix for the returned tensors (optional)
already_sorted: A boolean to specify whether the per-batch values in
`sp_values` are already sorted. If so skip sorting, False by default
(optional).
Returns:
A `SparseTensor` compactly representing a batch of feature ids and values,
useful for passing to functions that expect such a `SparseTensor`.
Raises:
TypeError: If `sp_ids` or `sp_values` are not a `SparseTensor`.
"""
sp_ids = _convert_to_sparse_tensor(sp_ids)
sp_values = _convert_to_sparse_tensor(sp_values)
with ops.name_scope(name, "SparseMerge", [sp_ids, sp_values]):
indices_shape = array_ops.shape(sp_ids.indices)
rank = indices_shape[1]
ids = sp_ids.values
if ids.dtype != dtypes.int64:
ids = math_ops.cast(ids, dtypes.int64)
# Slice off the last dimension of indices, then tack on the ids
indices_columns_to_preserve = array_ops.slice(
sp_ids.indices, [0, 0], array_ops.pack([-1, rank - 1]))
new_indices = array_ops.concat(1, [indices_columns_to_preserve,
array_ops.reshape(ids, [-1, 1])])
new_values = sp_values.values
new_shape = array_ops.concat(
0,
[array_ops.slice(sp_ids.shape, [0], array_ops.expand_dims(rank - 1, 0)),
math_ops.cast(array_ops.pack([vocab_size]), dtypes.int64)])
result = ops.SparseTensor(new_indices, new_values, new_shape)
return result if already_sorted else sparse_reorder(result) | [
"def",
"sparse_merge",
"(",
"sp_ids",
",",
"sp_values",
",",
"vocab_size",
",",
"name",
"=",
"None",
",",
"already_sorted",
"=",
"False",
")",
":",
"sp_ids",
"=",
"_convert_to_sparse_tensor",
"(",
"sp_ids",
")",
"sp_values",
"=",
"_convert_to_sparse_tensor",
"(",
"sp_values",
")",
"with",
"ops",
".",
"name_scope",
"(",
"name",
",",
"\"SparseMerge\"",
",",
"[",
"sp_ids",
",",
"sp_values",
"]",
")",
":",
"indices_shape",
"=",
"array_ops",
".",
"shape",
"(",
"sp_ids",
".",
"indices",
")",
"rank",
"=",
"indices_shape",
"[",
"1",
"]",
"ids",
"=",
"sp_ids",
".",
"values",
"if",
"ids",
".",
"dtype",
"!=",
"dtypes",
".",
"int64",
":",
"ids",
"=",
"math_ops",
".",
"cast",
"(",
"ids",
",",
"dtypes",
".",
"int64",
")",
"# Slice off the last dimension of indices, then tack on the ids",
"indices_columns_to_preserve",
"=",
"array_ops",
".",
"slice",
"(",
"sp_ids",
".",
"indices",
",",
"[",
"0",
",",
"0",
"]",
",",
"array_ops",
".",
"pack",
"(",
"[",
"-",
"1",
",",
"rank",
"-",
"1",
"]",
")",
")",
"new_indices",
"=",
"array_ops",
".",
"concat",
"(",
"1",
",",
"[",
"indices_columns_to_preserve",
",",
"array_ops",
".",
"reshape",
"(",
"ids",
",",
"[",
"-",
"1",
",",
"1",
"]",
")",
"]",
")",
"new_values",
"=",
"sp_values",
".",
"values",
"new_shape",
"=",
"array_ops",
".",
"concat",
"(",
"0",
",",
"[",
"array_ops",
".",
"slice",
"(",
"sp_ids",
".",
"shape",
",",
"[",
"0",
"]",
",",
"array_ops",
".",
"expand_dims",
"(",
"rank",
"-",
"1",
",",
"0",
")",
")",
",",
"math_ops",
".",
"cast",
"(",
"array_ops",
".",
"pack",
"(",
"[",
"vocab_size",
"]",
")",
",",
"dtypes",
".",
"int64",
")",
"]",
")",
"result",
"=",
"ops",
".",
"SparseTensor",
"(",
"new_indices",
",",
"new_values",
",",
"new_shape",
")",
"return",
"result",
"if",
"already_sorted",
"else",
"sparse_reorder",
"(",
"result",
")"
] | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/ops/sparse_ops.py#L754-L855 |
||
OSGeo/gdal | 3748fc4ba4fba727492774b2b908a2130c864a83 | swig/python/osgeo/ogr.py | python | FeatureDefn.IsStyleIgnored | (self, *args) | return _ogr.FeatureDefn_IsStyleIgnored(self, *args) | r"""
IsStyleIgnored(FeatureDefn self) -> int
int
OGR_FD_IsStyleIgnored(OGRFeatureDefnH hDefn)
Determine whether the style can be omitted when fetching features.
This function is the same as the C++ method
OGRFeatureDefn::IsStyleIgnored().
Parameters:
-----------
hDefn: handle to the feature definition on which OGRFeature are based
on.
ignore state | r"""
IsStyleIgnored(FeatureDefn self) -> int
int
OGR_FD_IsStyleIgnored(OGRFeatureDefnH hDefn) | [
"r",
"IsStyleIgnored",
"(",
"FeatureDefn",
"self",
")",
"-",
">",
"int",
"int",
"OGR_FD_IsStyleIgnored",
"(",
"OGRFeatureDefnH",
"hDefn",
")"
] | def IsStyleIgnored(self, *args):
r"""
IsStyleIgnored(FeatureDefn self) -> int
int
OGR_FD_IsStyleIgnored(OGRFeatureDefnH hDefn)
Determine whether the style can be omitted when fetching features.
This function is the same as the C++ method
OGRFeatureDefn::IsStyleIgnored().
Parameters:
-----------
hDefn: handle to the feature definition on which OGRFeature are based
on.
ignore state
"""
return _ogr.FeatureDefn_IsStyleIgnored(self, *args) | [
"def",
"IsStyleIgnored",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"_ogr",
".",
"FeatureDefn_IsStyleIgnored",
"(",
"self",
",",
"*",
"args",
")"
] | https://github.com/OSGeo/gdal/blob/3748fc4ba4fba727492774b2b908a2130c864a83/swig/python/osgeo/ogr.py#L4870-L4889 |
|
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/docview.py | python | DocChildFrame.GetDocument | (self) | return self._childDocument | Returns the document associated with this frame. | Returns the document associated with this frame. | [
"Returns",
"the",
"document",
"associated",
"with",
"this",
"frame",
"."
] | def GetDocument(self):
"""
Returns the document associated with this frame.
"""
return self._childDocument | [
"def",
"GetDocument",
"(",
"self",
")",
":",
"return",
"self",
".",
"_childDocument"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/docview.py#L2582-L2586 |
|
xhzdeng/crpn | a5aef0f80dbe486103123f740c634fb01e6cc9a1 | caffe-fast-rcnn/python/draw_net.py | python | parse_args | () | return args | Parse input arguments | Parse input arguments | [
"Parse",
"input",
"arguments"
] | def parse_args():
"""Parse input arguments
"""
parser = ArgumentParser(description=__doc__,
formatter_class=ArgumentDefaultsHelpFormatter)
parser.add_argument('input_net_proto_file',
help='Input network prototxt file')
parser.add_argument('output_image_file',
help='Output image file')
parser.add_argument('--rankdir',
help=('One of TB (top-bottom, i.e., vertical), '
'RL (right-left, i.e., horizontal), or another '
'valid dot option; see '
'http://www.graphviz.org/doc/info/'
'attrs.html#k:rankdir'),
default='LR')
parser.add_argument('--phase',
help=('Which network phase to draw: can be TRAIN, '
'TEST, or ALL. If ALL, then all layers are drawn '
'regardless of phase.'),
default="ALL")
args = parser.parse_args()
return args | [
"def",
"parse_args",
"(",
")",
":",
"parser",
"=",
"ArgumentParser",
"(",
"description",
"=",
"__doc__",
",",
"formatter_class",
"=",
"ArgumentDefaultsHelpFormatter",
")",
"parser",
".",
"add_argument",
"(",
"'input_net_proto_file'",
",",
"help",
"=",
"'Input network prototxt file'",
")",
"parser",
".",
"add_argument",
"(",
"'output_image_file'",
",",
"help",
"=",
"'Output image file'",
")",
"parser",
".",
"add_argument",
"(",
"'--rankdir'",
",",
"help",
"=",
"(",
"'One of TB (top-bottom, i.e., vertical), '",
"'RL (right-left, i.e., horizontal), or another '",
"'valid dot option; see '",
"'http://www.graphviz.org/doc/info/'",
"'attrs.html#k:rankdir'",
")",
",",
"default",
"=",
"'LR'",
")",
"parser",
".",
"add_argument",
"(",
"'--phase'",
",",
"help",
"=",
"(",
"'Which network phase to draw: can be TRAIN, '",
"'TEST, or ALL. If ALL, then all layers are drawn '",
"'regardless of phase.'",
")",
",",
"default",
"=",
"\"ALL\"",
")",
"args",
"=",
"parser",
".",
"parse_args",
"(",
")",
"return",
"args"
] | https://github.com/xhzdeng/crpn/blob/a5aef0f80dbe486103123f740c634fb01e6cc9a1/caffe-fast-rcnn/python/draw_net.py#L13-L38 |
|
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/python/ops/array_grad.py | python | _UnpackGrad | (op, *grads) | return array_ops.pack(grads, axis=op.get_attr("axis")) | Gradient for unpack op. | Gradient for unpack op. | [
"Gradient",
"for",
"unpack",
"op",
"."
] | def _UnpackGrad(op, *grads):
"""Gradient for unpack op."""
return array_ops.pack(grads, axis=op.get_attr("axis")) | [
"def",
"_UnpackGrad",
"(",
"op",
",",
"*",
"grads",
")",
":",
"return",
"array_ops",
".",
"pack",
"(",
"grads",
",",
"axis",
"=",
"op",
".",
"get_attr",
"(",
"\"axis\"",
")",
")"
] | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/python/ops/array_grad.py#L37-L39 |
|
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | chrome/tools/webforms_aggregator.py | python | WorkerThread.__init__ | (self, url) | Creates _url and page_found attri to populate urls_with_no_reg_page file.
Used after thread's termination for the creation of a file with a list of
the urls for which a registration page wasn't found.
Args:
url: will be used as an argument to create a Crawler object later. | Creates _url and page_found attri to populate urls_with_no_reg_page file. | [
"Creates",
"_url",
"and",
"page_found",
"attri",
"to",
"populate",
"urls_with_no_reg_page",
"file",
"."
] | def __init__(self, url):
"""Creates _url and page_found attri to populate urls_with_no_reg_page file.
Used after thread's termination for the creation of a file with a list of
the urls for which a registration page wasn't found.
Args:
url: will be used as an argument to create a Crawler object later.
"""
threading.Thread.__init__(self)
self._url = url
self.page_found = False | [
"def",
"__init__",
"(",
"self",
",",
"url",
")",
":",
"threading",
".",
"Thread",
".",
"__init__",
"(",
"self",
")",
"self",
".",
"_url",
"=",
"url",
"self",
".",
"page_found",
"=",
"False"
] | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/chrome/tools/webforms_aggregator.py#L597-L608 |
||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py2/sklearn/linear_model/passive_aggressive.py | python | PassiveAggressiveRegressor.partial_fit | (self, X, y) | return self._partial_fit(X, y, alpha=1.0, C=self.C,
loss="epsilon_insensitive",
learning_rate=lr, n_iter=1,
sample_weight=None,
coef_init=None, intercept_init=None) | Fit linear model with Passive Aggressive algorithm.
Parameters
----------
X : {array-like, sparse matrix}, shape = [n_samples, n_features]
Subset of training data
y : numpy array of shape [n_samples]
Subset of target values
Returns
-------
self : returns an instance of self. | Fit linear model with Passive Aggressive algorithm. | [
"Fit",
"linear",
"model",
"with",
"Passive",
"Aggressive",
"algorithm",
"."
] | def partial_fit(self, X, y):
"""Fit linear model with Passive Aggressive algorithm.
Parameters
----------
X : {array-like, sparse matrix}, shape = [n_samples, n_features]
Subset of training data
y : numpy array of shape [n_samples]
Subset of target values
Returns
-------
self : returns an instance of self.
"""
lr = "pa1" if self.loss == "epsilon_insensitive" else "pa2"
return self._partial_fit(X, y, alpha=1.0, C=self.C,
loss="epsilon_insensitive",
learning_rate=lr, n_iter=1,
sample_weight=None,
coef_init=None, intercept_init=None) | [
"def",
"partial_fit",
"(",
"self",
",",
"X",
",",
"y",
")",
":",
"lr",
"=",
"\"pa1\"",
"if",
"self",
".",
"loss",
"==",
"\"epsilon_insensitive\"",
"else",
"\"pa2\"",
"return",
"self",
".",
"_partial_fit",
"(",
"X",
",",
"y",
",",
"alpha",
"=",
"1.0",
",",
"C",
"=",
"self",
".",
"C",
",",
"loss",
"=",
"\"epsilon_insensitive\"",
",",
"learning_rate",
"=",
"lr",
",",
"n_iter",
"=",
"1",
",",
"sample_weight",
"=",
"None",
",",
"coef_init",
"=",
"None",
",",
"intercept_init",
"=",
"None",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/linear_model/passive_aggressive.py#L251-L271 |
|
hakuna-m/wubiuefi | caec1af0a09c78fd5a345180ada1fe45e0c63493 | src/urlgrabber/keepalive.py | python | KeepAliveHandler._request_closed | (self, request, host, connection) | tells us that this request is now closed and the the
connection is ready for another request | tells us that this request is now closed and the the
connection is ready for another request | [
"tells",
"us",
"that",
"this",
"request",
"is",
"now",
"closed",
"and",
"the",
"the",
"connection",
"is",
"ready",
"for",
"another",
"request"
] | def _request_closed(self, request, host, connection):
"""tells us that this request is now closed and the the
connection is ready for another request"""
self._cm.set_ready(connection, 1) | [
"def",
"_request_closed",
"(",
"self",
",",
"request",
",",
"host",
",",
"connection",
")",
":",
"self",
".",
"_cm",
".",
"set_ready",
"(",
"connection",
",",
"1",
")"
] | https://github.com/hakuna-m/wubiuefi/blob/caec1af0a09c78fd5a345180ada1fe45e0c63493/src/urlgrabber/keepalive.py#L202-L205 |
||
kristjankorjus/Replicating-DeepMind | 68539394e792b34a4d6b430a2eb73b8b8f91d8db | Hybrid/src/ai/cc_layers.py | python | shuffle_pool_unshuffle | (input_layer, *args, **kwargs) | return l_c01b | The Krizhevskhy max pooling layer only supports square input. This function provides
a workaround that uses Theano's own max pooling op, flanked by two shuffling operations:
c01b to bc01 before pooling, and bc01 to c01b afterwards. | The Krizhevskhy max pooling layer only supports square input. This function provides
a workaround that uses Theano's own max pooling op, flanked by two shuffling operations:
c01b to bc01 before pooling, and bc01 to c01b afterwards. | [
"The",
"Krizhevskhy",
"max",
"pooling",
"layer",
"only",
"supports",
"square",
"input",
".",
"This",
"function",
"provides",
"a",
"workaround",
"that",
"uses",
"Theano",
"s",
"own",
"max",
"pooling",
"op",
"flanked",
"by",
"two",
"shuffling",
"operations",
":",
"c01b",
"to",
"bc01",
"before",
"pooling",
"and",
"bc01",
"to",
"c01b",
"afterwards",
"."
] | def shuffle_pool_unshuffle(input_layer, *args, **kwargs):
"""
The Krizhevskhy max pooling layer only supports square input. This function provides
a workaround that uses Theano's own max pooling op, flanked by two shuffling operations:
c01b to bc01 before pooling, and bc01 to c01b afterwards.
"""
l_bc01 = ShuffleC01BToBC01Layer(input_layer)
l_pool = layers.Pooling2DLayer(l_bc01, *args, **kwargs)
l_c01b = ShuffleBC01ToC01BLayer(l_pool)
return l_c01b | [
"def",
"shuffle_pool_unshuffle",
"(",
"input_layer",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"l_bc01",
"=",
"ShuffleC01BToBC01Layer",
"(",
"input_layer",
")",
"l_pool",
"=",
"layers",
".",
"Pooling2DLayer",
"(",
"l_bc01",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"l_c01b",
"=",
"ShuffleBC01ToC01BLayer",
"(",
"l_pool",
")",
"return",
"l_c01b"
] | https://github.com/kristjankorjus/Replicating-DeepMind/blob/68539394e792b34a4d6b430a2eb73b8b8f91d8db/Hybrid/src/ai/cc_layers.py#L377-L387 |
|
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/jsonschema/_utils.py | python | extras_msg | (extras) | return ", ".join(repr(extra) for extra in extras), verb | Create an error message for extra items or properties. | Create an error message for extra items or properties. | [
"Create",
"an",
"error",
"message",
"for",
"extra",
"items",
"or",
"properties",
"."
] | def extras_msg(extras):
"""
Create an error message for extra items or properties.
"""
if len(extras) == 1:
verb = "was"
else:
verb = "were"
return ", ".join(repr(extra) for extra in extras), verb | [
"def",
"extras_msg",
"(",
"extras",
")",
":",
"if",
"len",
"(",
"extras",
")",
"==",
"1",
":",
"verb",
"=",
"\"was\"",
"else",
":",
"verb",
"=",
"\"were\"",
"return",
"\", \"",
".",
"join",
"(",
"repr",
"(",
"extra",
")",
"for",
"extra",
"in",
"extras",
")",
",",
"verb"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/jsonschema/_utils.py#L103-L112 |
|
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/webapp2/webapp2_extras/security.py | python | hash_password | (password, method, salt=None, pepper=None) | return h.hexdigest() | Hashes a password.
Supports plaintext without salt, unsalted and salted passwords. In case
salted passwords are used hmac is used.
:param password:
The password to be hashed.
:param method:
A method from ``hashlib``, e.g., `sha1` or `md5`, or `plain`.
:param salt:
A random salt string.
:param pepper:
A secret constant stored in the application code.
:returns:
A hashed password.
This function was ported and adapted from `Werkzeug`_. | Hashes a password. | [
"Hashes",
"a",
"password",
"."
] | def hash_password(password, method, salt=None, pepper=None):
"""Hashes a password.
Supports plaintext without salt, unsalted and salted passwords. In case
salted passwords are used hmac is used.
:param password:
The password to be hashed.
:param method:
A method from ``hashlib``, e.g., `sha1` or `md5`, or `plain`.
:param salt:
A random salt string.
:param pepper:
A secret constant stored in the application code.
:returns:
A hashed password.
This function was ported and adapted from `Werkzeug`_.
"""
password = webapp2._to_utf8(password)
if method == 'plain':
return password
method = getattr(hashlib, method, None)
if not method:
return None
if salt:
h = hmac.new(webapp2._to_utf8(salt), password, method)
else:
h = method(password)
if pepper:
h = hmac.new(webapp2._to_utf8(pepper), h.hexdigest(), method)
return h.hexdigest() | [
"def",
"hash_password",
"(",
"password",
",",
"method",
",",
"salt",
"=",
"None",
",",
"pepper",
"=",
"None",
")",
":",
"password",
"=",
"webapp2",
".",
"_to_utf8",
"(",
"password",
")",
"if",
"method",
"==",
"'plain'",
":",
"return",
"password",
"method",
"=",
"getattr",
"(",
"hashlib",
",",
"method",
",",
"None",
")",
"if",
"not",
"method",
":",
"return",
"None",
"if",
"salt",
":",
"h",
"=",
"hmac",
".",
"new",
"(",
"webapp2",
".",
"_to_utf8",
"(",
"salt",
")",
",",
"password",
",",
"method",
")",
"else",
":",
"h",
"=",
"method",
"(",
"password",
")",
"if",
"pepper",
":",
"h",
"=",
"hmac",
".",
"new",
"(",
"webapp2",
".",
"_to_utf8",
"(",
"pepper",
")",
",",
"h",
".",
"hexdigest",
"(",
")",
",",
"method",
")",
"return",
"h",
".",
"hexdigest",
"(",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/webapp2/webapp2_extras/security.py#L155-L190 |
|
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/_pyio.py | python | IOBase.fileno | (self) | Returns underlying file descriptor (an int) if one exists.
An OSError is raised if the IO object does not use a file descriptor. | Returns underlying file descriptor (an int) if one exists. | [
"Returns",
"underlying",
"file",
"descriptor",
"(",
"an",
"int",
")",
"if",
"one",
"exists",
"."
] | def fileno(self):
"""Returns underlying file descriptor (an int) if one exists.
An OSError is raised if the IO object does not use a file descriptor.
"""
self._unsupported("fileno") | [
"def",
"fileno",
"(",
"self",
")",
":",
"self",
".",
"_unsupported",
"(",
"\"fileno\"",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/_pyio.py#L461-L466 |
||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib2to3/pytree.py | python | Leaf.__init__ | (self, type, value,
context=None,
prefix=None,
fixers_applied=[]) | Initializer.
Takes a type constant (a token number < 256), a string value, and an
optional context keyword argument. | Initializer. | [
"Initializer",
"."
] | def __init__(self, type, value,
context=None,
prefix=None,
fixers_applied=[]):
"""
Initializer.
Takes a type constant (a token number < 256), a string value, and an
optional context keyword argument.
"""
assert 0 <= type < 256, type
if context is not None:
self._prefix, (self.lineno, self.column) = context
self.type = type
self.value = value
if prefix is not None:
self._prefix = prefix
self.fixers_applied = fixers_applied[:] | [
"def",
"__init__",
"(",
"self",
",",
"type",
",",
"value",
",",
"context",
"=",
"None",
",",
"prefix",
"=",
"None",
",",
"fixers_applied",
"=",
"[",
"]",
")",
":",
"assert",
"0",
"<=",
"type",
"<",
"256",
",",
"type",
"if",
"context",
"is",
"not",
"None",
":",
"self",
".",
"_prefix",
",",
"(",
"self",
".",
"lineno",
",",
"self",
".",
"column",
")",
"=",
"context",
"self",
".",
"type",
"=",
"type",
"self",
".",
"value",
"=",
"value",
"if",
"prefix",
"is",
"not",
"None",
":",
"self",
".",
"_prefix",
"=",
"prefix",
"self",
".",
"fixers_applied",
"=",
"fixers_applied",
"[",
":",
"]"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib2to3/pytree.py#L360-L377 |
||
arangodb/arangodb | 0d658689c7d1b721b314fa3ca27d38303e1570c8 | 3rdParty/V8/gyp/generator/xcodeproj_file.py | python | XCObject.Children | (self) | return children | Returns a list of all of this object's owned (strong) children. | Returns a list of all of this object's owned (strong) children. | [
"Returns",
"a",
"list",
"of",
"all",
"of",
"this",
"object",
"s",
"owned",
"(",
"strong",
")",
"children",
"."
] | def Children(self):
"""Returns a list of all of this object's owned (strong) children."""
children = []
for property, attributes in self._schema.items():
(is_list, property_type, is_strong) = attributes[0:3]
if is_strong and property in self._properties:
if not is_list:
children.append(self._properties[property])
else:
children.extend(self._properties[property])
return children | [
"def",
"Children",
"(",
"self",
")",
":",
"children",
"=",
"[",
"]",
"for",
"property",
",",
"attributes",
"in",
"self",
".",
"_schema",
".",
"items",
"(",
")",
":",
"(",
"is_list",
",",
"property_type",
",",
"is_strong",
")",
"=",
"attributes",
"[",
"0",
":",
"3",
"]",
"if",
"is_strong",
"and",
"property",
"in",
"self",
".",
"_properties",
":",
"if",
"not",
"is_list",
":",
"children",
".",
"append",
"(",
"self",
".",
"_properties",
"[",
"property",
"]",
")",
"else",
":",
"children",
".",
"extend",
"(",
"self",
".",
"_properties",
"[",
"property",
"]",
")",
"return",
"children"
] | https://github.com/arangodb/arangodb/blob/0d658689c7d1b721b314fa3ca27d38303e1570c8/3rdParty/V8/gyp/generator/xcodeproj_file.py#L479-L490 |
|
cornell-zhang/heterocl | 6d9e4b4acc2ee2707b2d25b27298c0335bccedfd | python/heterocl/tvm/contrib/graph_runtime.py | python | GraphModule.__getitem__ | (self, key) | return self.module[key] | Get internal module function
Parameters
----------
key : str
The key to the module. | Get internal module function | [
"Get",
"internal",
"module",
"function"
] | def __getitem__(self, key):
"""Get internal module function
Parameters
----------
key : str
The key to the module.
"""
return self.module[key] | [
"def",
"__getitem__",
"(",
"self",
",",
"key",
")",
":",
"return",
"self",
".",
"module",
"[",
"key",
"]"
] | https://github.com/cornell-zhang/heterocl/blob/6d9e4b4acc2ee2707b2d25b27298c0335bccedfd/python/heterocl/tvm/contrib/graph_runtime.py#L155-L163 |
|
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | build/android/gyp/locale_pak_resources.py | python | ComputeMappings | (sources) | return mappings, lang_to_locale_map | Computes the mappings of sources -> resources.
Returns a tuple of:
- mappings: List of (src, dest) paths
- lang_to_locale_map: Map of language -> list of resource names
e.g. "en" -> ["en_gb.lpak"] | Computes the mappings of sources -> resources. | [
"Computes",
"the",
"mappings",
"of",
"sources",
"-",
">",
"resources",
"."
] | def ComputeMappings(sources):
"""Computes the mappings of sources -> resources.
Returns a tuple of:
- mappings: List of (src, dest) paths
- lang_to_locale_map: Map of language -> list of resource names
e.g. "en" -> ["en_gb.lpak"]
"""
lang_to_locale_map = collections.defaultdict(list)
mappings = []
for src_path in sources:
basename = os.path.basename(src_path)
name = os.path.splitext(basename)[0]
res_name = ToResourceFileName(basename)
if name == 'en-US':
dest_dir = 'raw'
else:
# Chrome's uses different region mapping logic from Android, so include
# all regions for each language.
android_locale = _CHROME_TO_ANDROID_LOCALE_MAP.get(name, name)
lang = android_locale[0:2]
dest_dir = 'raw-' + lang
lang_to_locale_map[lang].append(res_name)
mappings.append((src_path, os.path.join(dest_dir, res_name)))
return mappings, lang_to_locale_map | [
"def",
"ComputeMappings",
"(",
"sources",
")",
":",
"lang_to_locale_map",
"=",
"collections",
".",
"defaultdict",
"(",
"list",
")",
"mappings",
"=",
"[",
"]",
"for",
"src_path",
"in",
"sources",
":",
"basename",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"src_path",
")",
"name",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"basename",
")",
"[",
"0",
"]",
"res_name",
"=",
"ToResourceFileName",
"(",
"basename",
")",
"if",
"name",
"==",
"'en-US'",
":",
"dest_dir",
"=",
"'raw'",
"else",
":",
"# Chrome's uses different region mapping logic from Android, so include",
"# all regions for each language.",
"android_locale",
"=",
"_CHROME_TO_ANDROID_LOCALE_MAP",
".",
"get",
"(",
"name",
",",
"name",
")",
"lang",
"=",
"android_locale",
"[",
"0",
":",
"2",
"]",
"dest_dir",
"=",
"'raw-'",
"+",
"lang",
"lang_to_locale_map",
"[",
"lang",
"]",
".",
"append",
"(",
"res_name",
")",
"mappings",
".",
"append",
"(",
"(",
"src_path",
",",
"os",
".",
"path",
".",
"join",
"(",
"dest_dir",
",",
"res_name",
")",
")",
")",
"return",
"mappings",
",",
"lang_to_locale_map"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/build/android/gyp/locale_pak_resources.py#L55-L79 |
|
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/indexes/base.py | python | Index._get_attributes_dict | (self) | return {k: getattr(self, k, None) for k in self._attributes} | Return an attributes dict for my class. | Return an attributes dict for my class. | [
"Return",
"an",
"attributes",
"dict",
"for",
"my",
"class",
"."
] | def _get_attributes_dict(self):
"""
Return an attributes dict for my class.
"""
return {k: getattr(self, k, None) for k in self._attributes} | [
"def",
"_get_attributes_dict",
"(",
"self",
")",
":",
"return",
"{",
"k",
":",
"getattr",
"(",
"self",
",",
"k",
",",
"None",
")",
"for",
"k",
"in",
"self",
".",
"_attributes",
"}"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/indexes/base.py#L505-L509 |
|
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/setuptools/command/easy_install.py | python | _first_line_re | () | return re.compile(first_line_re.pattern.decode()) | Return a regular expression based on first_line_re suitable for matching
strings. | Return a regular expression based on first_line_re suitable for matching
strings. | [
"Return",
"a",
"regular",
"expression",
"based",
"on",
"first_line_re",
"suitable",
"for",
"matching",
"strings",
"."
] | def _first_line_re():
"""
Return a regular expression based on first_line_re suitable for matching
strings.
"""
if isinstance(first_line_re.pattern, str):
return first_line_re
# first_line_re in Python >=3.1.4 and >=3.2.1 is a bytes pattern.
return re.compile(first_line_re.pattern.decode()) | [
"def",
"_first_line_re",
"(",
")",
":",
"if",
"isinstance",
"(",
"first_line_re",
".",
"pattern",
",",
"str",
")",
":",
"return",
"first_line_re",
"# first_line_re in Python >=3.1.4 and >=3.2.1 is a bytes pattern.",
"return",
"re",
".",
"compile",
"(",
"first_line_re",
".",
"pattern",
".",
"decode",
"(",
")",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/setuptools/command/easy_install.py#L1723-L1732 |
|
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_core.py | python | PyApp.SetMacExitMenuItemId | (*args, **kwargs) | return _core_.PyApp_SetMacExitMenuItemId(*args, **kwargs) | SetMacExitMenuItemId(long val) | SetMacExitMenuItemId(long val) | [
"SetMacExitMenuItemId",
"(",
"long",
"val",
")"
] | def SetMacExitMenuItemId(*args, **kwargs):
"""SetMacExitMenuItemId(long val)"""
return _core_.PyApp_SetMacExitMenuItemId(*args, **kwargs) | [
"def",
"SetMacExitMenuItemId",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"PyApp_SetMacExitMenuItemId",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L8180-L8182 |
|
hpi-xnor/BMXNet-v2 | af2b1859eafc5c721b1397cef02f946aaf2ce20d | python/mxnet/autograd.py | python | is_recording | () | return curr.value | Get status on recording/not recording.
Returns
-------
Current state of recording. | Get status on recording/not recording. | [
"Get",
"status",
"on",
"recording",
"/",
"not",
"recording",
"."
] | def is_recording():
"""Get status on recording/not recording.
Returns
-------
Current state of recording.
"""
curr = ctypes.c_bool()
check_call(_LIB.MXAutogradIsRecording(ctypes.byref(curr)))
return curr.value | [
"def",
"is_recording",
"(",
")",
":",
"curr",
"=",
"ctypes",
".",
"c_bool",
"(",
")",
"check_call",
"(",
"_LIB",
".",
"MXAutogradIsRecording",
"(",
"ctypes",
".",
"byref",
"(",
"curr",
")",
")",
")",
"return",
"curr",
".",
"value"
] | https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/python/mxnet/autograd.py#L70-L79 |
|
bigartm/bigartm | 47e37f982de87aa67bfd475ff1f39da696b181b3 | 3rdparty/protobuf-3.0.0/gmock/scripts/fuse_gmock_files.py | python | FuseGMockAllCcToFile | (gmock_root, output_file) | Scans folder gmock_root to fuse gmock-all.cc into output_file. | Scans folder gmock_root to fuse gmock-all.cc into output_file. | [
"Scans",
"folder",
"gmock_root",
"to",
"fuse",
"gmock",
"-",
"all",
".",
"cc",
"into",
"output_file",
"."
] | def FuseGMockAllCcToFile(gmock_root, output_file):
"""Scans folder gmock_root to fuse gmock-all.cc into output_file."""
processed_files = sets.Set()
def ProcessFile(gmock_source_file):
"""Processes the given gmock source file."""
# We don't process the same #included file twice.
if gmock_source_file in processed_files:
return
processed_files.add(gmock_source_file)
# Reads each line in the given gmock source file.
for line in file(os.path.join(gmock_root, gmock_source_file), 'r'):
m = INCLUDE_GMOCK_FILE_REGEX.match(line)
if m:
# It's '#include "gmock/foo.h"'. We treat it as '#include
# "gmock/gmock.h"', as all other gmock headers are being fused
# into gmock.h and cannot be #included directly.
# There is no need to #include "gmock/gmock.h" more than once.
if not GMOCK_H_SEED in processed_files:
processed_files.add(GMOCK_H_SEED)
output_file.write('#include "%s"\n' % (GMOCK_H_OUTPUT,))
else:
m = gtest.INCLUDE_GTEST_FILE_REGEX.match(line)
if m:
# It's '#include "gtest/..."'.
# There is no need to #include gtest.h as it has been
# #included by gtest-all.cc.
pass
else:
m = gtest.INCLUDE_SRC_FILE_REGEX.match(line)
if m:
# It's '#include "src/foo"' - let's process it recursively.
ProcessFile(m.group(1))
else:
# Otherwise we copy the line unchanged to the output file.
output_file.write(line)
ProcessFile(GMOCK_ALL_CC_SEED) | [
"def",
"FuseGMockAllCcToFile",
"(",
"gmock_root",
",",
"output_file",
")",
":",
"processed_files",
"=",
"sets",
".",
"Set",
"(",
")",
"def",
"ProcessFile",
"(",
"gmock_source_file",
")",
":",
"\"\"\"Processes the given gmock source file.\"\"\"",
"# We don't process the same #included file twice.",
"if",
"gmock_source_file",
"in",
"processed_files",
":",
"return",
"processed_files",
".",
"add",
"(",
"gmock_source_file",
")",
"# Reads each line in the given gmock source file.",
"for",
"line",
"in",
"file",
"(",
"os",
".",
"path",
".",
"join",
"(",
"gmock_root",
",",
"gmock_source_file",
")",
",",
"'r'",
")",
":",
"m",
"=",
"INCLUDE_GMOCK_FILE_REGEX",
".",
"match",
"(",
"line",
")",
"if",
"m",
":",
"# It's '#include \"gmock/foo.h\"'. We treat it as '#include",
"# \"gmock/gmock.h\"', as all other gmock headers are being fused",
"# into gmock.h and cannot be #included directly.",
"# There is no need to #include \"gmock/gmock.h\" more than once.",
"if",
"not",
"GMOCK_H_SEED",
"in",
"processed_files",
":",
"processed_files",
".",
"add",
"(",
"GMOCK_H_SEED",
")",
"output_file",
".",
"write",
"(",
"'#include \"%s\"\\n'",
"%",
"(",
"GMOCK_H_OUTPUT",
",",
")",
")",
"else",
":",
"m",
"=",
"gtest",
".",
"INCLUDE_GTEST_FILE_REGEX",
".",
"match",
"(",
"line",
")",
"if",
"m",
":",
"# It's '#include \"gtest/...\"'.",
"# There is no need to #include gtest.h as it has been",
"# #included by gtest-all.cc.",
"pass",
"else",
":",
"m",
"=",
"gtest",
".",
"INCLUDE_SRC_FILE_REGEX",
".",
"match",
"(",
"line",
")",
"if",
"m",
":",
"# It's '#include \"src/foo\"' - let's process it recursively.",
"ProcessFile",
"(",
"m",
".",
"group",
"(",
"1",
")",
")",
"else",
":",
"# Otherwise we copy the line unchanged to the output file.",
"output_file",
".",
"write",
"(",
"line",
")",
"ProcessFile",
"(",
"GMOCK_ALL_CC_SEED",
")"
] | https://github.com/bigartm/bigartm/blob/47e37f982de87aa67bfd475ff1f39da696b181b3/3rdparty/protobuf-3.0.0/gmock/scripts/fuse_gmock_files.py#L159-L201 |
||
smilehao/xlua-framework | a03801538be2b0e92d39332d445b22caca1ef61f | ConfigData/trunk/tools/protobuf-2.5.0/protobuf-2.5.0/python/build/lib/google/protobuf/message.py | python | Message.MergeFromString | (self, serialized) | Merges serialized protocol buffer data into this message.
When we find a field in |serialized| that is already present
in this message:
- If it's a "repeated" field, we append to the end of our list.
- Else, if it's a scalar, we overwrite our field.
- Else, (it's a nonrepeated composite), we recursively merge
into the existing composite.
TODO(robinson): Document handling of unknown fields.
Args:
serialized: Any object that allows us to call buffer(serialized)
to access a string of bytes using the buffer interface.
TODO(robinson): When we switch to a helper, this will return None.
Returns:
The number of bytes read from |serialized|.
For non-group messages, this will always be len(serialized),
but for messages which are actually groups, this will
generally be less than len(serialized), since we must
stop when we reach an END_GROUP tag. Note that if
we *do* stop because of an END_GROUP tag, the number
of bytes returned does not include the bytes
for the END_GROUP tag information. | Merges serialized protocol buffer data into this message. | [
"Merges",
"serialized",
"protocol",
"buffer",
"data",
"into",
"this",
"message",
"."
] | def MergeFromString(self, serialized):
"""Merges serialized protocol buffer data into this message.
When we find a field in |serialized| that is already present
in this message:
- If it's a "repeated" field, we append to the end of our list.
- Else, if it's a scalar, we overwrite our field.
- Else, (it's a nonrepeated composite), we recursively merge
into the existing composite.
TODO(robinson): Document handling of unknown fields.
Args:
serialized: Any object that allows us to call buffer(serialized)
to access a string of bytes using the buffer interface.
TODO(robinson): When we switch to a helper, this will return None.
Returns:
The number of bytes read from |serialized|.
For non-group messages, this will always be len(serialized),
but for messages which are actually groups, this will
generally be less than len(serialized), since we must
stop when we reach an END_GROUP tag. Note that if
we *do* stop because of an END_GROUP tag, the number
of bytes returned does not include the bytes
for the END_GROUP tag information.
"""
raise NotImplementedError | [
"def",
"MergeFromString",
"(",
"self",
",",
"serialized",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/smilehao/xlua-framework/blob/a03801538be2b0e92d39332d445b22caca1ef61f/ConfigData/trunk/tools/protobuf-2.5.0/protobuf-2.5.0/python/build/lib/google/protobuf/message.py#L149-L177 |
||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/botocore/signers.py | python | RequestSigner._choose_signer | (self, operation_name, signing_type, context) | return signature_version | Allow setting the signature version via the choose-signer event.
A value of `botocore.UNSIGNED` means no signing will be performed.
:param operation_name: The operation to sign.
:param signing_type: The type of signing that the signer is to be used
for.
:return: The signature version to sign with. | Allow setting the signature version via the choose-signer event.
A value of `botocore.UNSIGNED` means no signing will be performed. | [
"Allow",
"setting",
"the",
"signature",
"version",
"via",
"the",
"choose",
"-",
"signer",
"event",
".",
"A",
"value",
"of",
"botocore",
".",
"UNSIGNED",
"means",
"no",
"signing",
"will",
"be",
"performed",
"."
] | def _choose_signer(self, operation_name, signing_type, context):
"""
Allow setting the signature version via the choose-signer event.
A value of `botocore.UNSIGNED` means no signing will be performed.
:param operation_name: The operation to sign.
:param signing_type: The type of signing that the signer is to be used
for.
:return: The signature version to sign with.
"""
signing_type_suffix_map = {
'presign-post': '-presign-post',
'presign-url': '-query'
}
suffix = signing_type_suffix_map.get(signing_type, '')
signature_version = self._signature_version
if signature_version is not botocore.UNSIGNED and not \
signature_version.endswith(suffix):
signature_version += suffix
handler, response = self._event_emitter.emit_until_response(
'choose-signer.{0}.{1}'.format(
self._service_id.hyphenize(), operation_name),
signing_name=self._signing_name, region_name=self._region_name,
signature_version=signature_version, context=context)
if response is not None:
signature_version = response
# The suffix needs to be checked again in case we get an improper
# signature version from choose-signer.
if signature_version is not botocore.UNSIGNED and not \
signature_version.endswith(suffix):
signature_version += suffix
return signature_version | [
"def",
"_choose_signer",
"(",
"self",
",",
"operation_name",
",",
"signing_type",
",",
"context",
")",
":",
"signing_type_suffix_map",
"=",
"{",
"'presign-post'",
":",
"'-presign-post'",
",",
"'presign-url'",
":",
"'-query'",
"}",
"suffix",
"=",
"signing_type_suffix_map",
".",
"get",
"(",
"signing_type",
",",
"''",
")",
"signature_version",
"=",
"self",
".",
"_signature_version",
"if",
"signature_version",
"is",
"not",
"botocore",
".",
"UNSIGNED",
"and",
"not",
"signature_version",
".",
"endswith",
"(",
"suffix",
")",
":",
"signature_version",
"+=",
"suffix",
"handler",
",",
"response",
"=",
"self",
".",
"_event_emitter",
".",
"emit_until_response",
"(",
"'choose-signer.{0}.{1}'",
".",
"format",
"(",
"self",
".",
"_service_id",
".",
"hyphenize",
"(",
")",
",",
"operation_name",
")",
",",
"signing_name",
"=",
"self",
".",
"_signing_name",
",",
"region_name",
"=",
"self",
".",
"_region_name",
",",
"signature_version",
"=",
"signature_version",
",",
"context",
"=",
"context",
")",
"if",
"response",
"is",
"not",
"None",
":",
"signature_version",
"=",
"response",
"# The suffix needs to be checked again in case we get an improper",
"# signature version from choose-signer.",
"if",
"signature_version",
"is",
"not",
"botocore",
".",
"UNSIGNED",
"and",
"not",
"signature_version",
".",
"endswith",
"(",
"suffix",
")",
":",
"signature_version",
"+=",
"suffix",
"return",
"signature_version"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/botocore/signers.py#L162-L197 |
|
thalium/icebox | 99d147d5b9269222225443ce171b4fd46d8985d4 | third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py | python | uCSIsOldItalic | (code) | return ret | Check whether the character is part of OldItalic UCS Block | Check whether the character is part of OldItalic UCS Block | [
"Check",
"whether",
"the",
"character",
"is",
"part",
"of",
"OldItalic",
"UCS",
"Block"
] | def uCSIsOldItalic(code):
"""Check whether the character is part of OldItalic UCS Block """
ret = libxml2mod.xmlUCSIsOldItalic(code)
return ret | [
"def",
"uCSIsOldItalic",
"(",
"code",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlUCSIsOldItalic",
"(",
"code",
")",
"return",
"ret"
] | https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py#L2796-L2799 |
|
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/setuptools/command/easy_install.py | python | is_python_script | (script_text, filename) | return False | Is this text, as a whole, a Python script? (as opposed to shell/bat/etc. | Is this text, as a whole, a Python script? (as opposed to shell/bat/etc. | [
"Is",
"this",
"text",
"as",
"a",
"whole",
"a",
"Python",
"script?",
"(",
"as",
"opposed",
"to",
"shell",
"/",
"bat",
"/",
"etc",
"."
] | def is_python_script(script_text, filename):
"""Is this text, as a whole, a Python script? (as opposed to shell/bat/etc.
"""
if filename.endswith('.py') or filename.endswith('.pyw'):
return True # extension says it's Python
if is_python(script_text, filename):
return True # it's syntactically valid Python
if script_text.startswith('#!'):
# It begins with a '#!' line, so check if 'python' is in it somewhere
return 'python' in script_text.splitlines()[0].lower()
return False | [
"def",
"is_python_script",
"(",
"script_text",
",",
"filename",
")",
":",
"if",
"filename",
".",
"endswith",
"(",
"'.py'",
")",
"or",
"filename",
".",
"endswith",
"(",
"'.pyw'",
")",
":",
"return",
"True",
"# extension says it's Python",
"if",
"is_python",
"(",
"script_text",
",",
"filename",
")",
":",
"return",
"True",
"# it's syntactically valid Python",
"if",
"script_text",
".",
"startswith",
"(",
"'#!'",
")",
":",
"# It begins with a '#!' line, so check if 'python' is in it somewhere",
"return",
"'python'",
"in",
"script_text",
".",
"splitlines",
"(",
")",
"[",
"0",
"]",
".",
"lower",
"(",
")",
"return",
"False"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/setuptools/command/easy_install.py#L1931-L1942 |
|
gimli-org/gimli | 17aa2160de9b15ababd9ef99e89b1bc3277bbb23 | pygimli/viewer/pv/show3d.py | python | Show3D.updateScalarBar | (self) | When user set limits are made and finished/accepted the color bar
needs to change. | When user set limits are made and finished/accepted the color bar
needs to change. | [
"When",
"user",
"set",
"limits",
"are",
"made",
"and",
"finished",
"/",
"accepted",
"the",
"color",
"bar",
"needs",
"to",
"change",
"."
] | def updateScalarBar(self):
"""
When user set limits are made and finished/accepted the color bar
needs to change.
"""
cmin = float(self.toolbar.spbx_cmin.value())
cmax = float(self.toolbar.spbx_cmax.value())
if cmax >= cmin:
# get the active scalar/parameter that is displayed currently
param = self.mesh.active_scalars_name
# update the user extrema
if not self.toolbar.btn_global_limits.isChecked():
self.data[param]['user']['min'] = cmin
self.data[param]['user']['max'] = cmax
# NOTE: has no effect on the displayed vtk
# pg._d("RESET SCALAR BAR LIMITS")
self.plotter.update_scalar_bar_range([cmin, cmax])
self.plotter.update() | [
"def",
"updateScalarBar",
"(",
"self",
")",
":",
"cmin",
"=",
"float",
"(",
"self",
".",
"toolbar",
".",
"spbx_cmin",
".",
"value",
"(",
")",
")",
"cmax",
"=",
"float",
"(",
"self",
".",
"toolbar",
".",
"spbx_cmax",
".",
"value",
"(",
")",
")",
"if",
"cmax",
">=",
"cmin",
":",
"# get the active scalar/parameter that is displayed currently",
"param",
"=",
"self",
".",
"mesh",
".",
"active_scalars_name",
"# update the user extrema",
"if",
"not",
"self",
".",
"toolbar",
".",
"btn_global_limits",
".",
"isChecked",
"(",
")",
":",
"self",
".",
"data",
"[",
"param",
"]",
"[",
"'user'",
"]",
"[",
"'min'",
"]",
"=",
"cmin",
"self",
".",
"data",
"[",
"param",
"]",
"[",
"'user'",
"]",
"[",
"'max'",
"]",
"=",
"cmax",
"# NOTE: has no effect on the displayed vtk",
"# pg._d(\"RESET SCALAR BAR LIMITS\")",
"self",
".",
"plotter",
".",
"update_scalar_bar_range",
"(",
"[",
"cmin",
",",
"cmax",
"]",
")",
"self",
".",
"plotter",
".",
"update",
"(",
")"
] | https://github.com/gimli-org/gimli/blob/17aa2160de9b15ababd9ef99e89b1bc3277bbb23/pygimli/viewer/pv/show3d.py#L332-L350 |
||
mongodb/mongo | d8ff665343ad29cf286ee2cf4a1960d29371937b | src/third_party/wiredtiger/src/docs/tools/doxypy.py | python | Doxypy.stopCommentSearch | (self, match) | Stops a comment search.
Closes the current commentblock, resets the triggering line and
appends the current line to the output. | Stops a comment search.
Closes the current commentblock, resets the triggering line and
appends the current line to the output. | [
"Stops",
"a",
"comment",
"search",
".",
"Closes",
"the",
"current",
"commentblock",
"resets",
"the",
"triggering",
"line",
"and",
"appends",
"the",
"current",
"line",
"to",
"the",
"output",
"."
] | def stopCommentSearch(self, match):
"""Stops a comment search.
Closes the current commentblock, resets the triggering line and
appends the current line to the output.
"""
if options.debug:
print("# CALLBACK: stopCommentSearch" , file=sys.stderr)
self.__closeComment()
self.defclass = []
self.output.append(self.fsm.current_input) | [
"def",
"stopCommentSearch",
"(",
"self",
",",
"match",
")",
":",
"if",
"options",
".",
"debug",
":",
"print",
"(",
"\"# CALLBACK: stopCommentSearch\"",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"self",
".",
"__closeComment",
"(",
")",
"self",
".",
"defclass",
"=",
"[",
"]",
"self",
".",
"output",
".",
"append",
"(",
"self",
".",
"fsm",
".",
"current_input",
")"
] | https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/src/third_party/wiredtiger/src/docs/tools/doxypy.py#L249-L260 |
||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/distlib/index.py | python | PackageIndex.upload_documentation | (self, metadata, doc_dir) | return self.send_request(request) | Upload documentation to the index.
:param metadata: A :class:`Metadata` instance defining at least a name
and version number for the documentation to be
uploaded.
:param doc_dir: The pathname of the directory which contains the
documentation. This should be the directory that
contains the ``index.html`` for the documentation.
:return: The HTTP response received from PyPI upon submission of the
request. | Upload documentation to the index. | [
"Upload",
"documentation",
"to",
"the",
"index",
"."
] | def upload_documentation(self, metadata, doc_dir):
"""
Upload documentation to the index.
:param metadata: A :class:`Metadata` instance defining at least a name
and version number for the documentation to be
uploaded.
:param doc_dir: The pathname of the directory which contains the
documentation. This should be the directory that
contains the ``index.html`` for the documentation.
:return: The HTTP response received from PyPI upon submission of the
request.
"""
self.check_credentials()
if not os.path.isdir(doc_dir):
raise DistlibException('not a directory: %r' % doc_dir)
fn = os.path.join(doc_dir, 'index.html')
if not os.path.exists(fn):
raise DistlibException('not found: %r' % fn)
metadata.validate()
name, version = metadata.name, metadata.version
zip_data = zip_dir(doc_dir).getvalue()
fields = [(':action', 'doc_upload'),
('name', name), ('version', version)]
files = [('content', name, zip_data)]
request = self.encode_request(fields, files)
return self.send_request(request) | [
"def",
"upload_documentation",
"(",
"self",
",",
"metadata",
",",
"doc_dir",
")",
":",
"self",
".",
"check_credentials",
"(",
")",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"doc_dir",
")",
":",
"raise",
"DistlibException",
"(",
"'not a directory: %r'",
"%",
"doc_dir",
")",
"fn",
"=",
"os",
".",
"path",
".",
"join",
"(",
"doc_dir",
",",
"'index.html'",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"fn",
")",
":",
"raise",
"DistlibException",
"(",
"'not found: %r'",
"%",
"fn",
")",
"metadata",
".",
"validate",
"(",
")",
"name",
",",
"version",
"=",
"metadata",
".",
"name",
",",
"metadata",
".",
"version",
"zip_data",
"=",
"zip_dir",
"(",
"doc_dir",
")",
".",
"getvalue",
"(",
")",
"fields",
"=",
"[",
"(",
"':action'",
",",
"'doc_upload'",
")",
",",
"(",
"'name'",
",",
"name",
")",
",",
"(",
"'version'",
",",
"version",
")",
"]",
"files",
"=",
"[",
"(",
"'content'",
",",
"name",
",",
"zip_data",
")",
"]",
"request",
"=",
"self",
".",
"encode_request",
"(",
"fields",
",",
"files",
")",
"return",
"self",
".",
"send_request",
"(",
"request",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/distlib/index.py#L296-L322 |
|
hpi-xnor/BMXNet-v2 | af2b1859eafc5c721b1397cef02f946aaf2ce20d | example/cnn_chinese_text_classification/text_cnn.py | python | data_iter | (batch_size, num_embed, pre_trained_word2vec=False) | return train_set, valid, sentences_size, embedded_size, vocabulary_size | Construct data iter
Parameters
----------
batch_size: int
num_embed: int
pre_trained_word2vec: boolean
identify the pre-trained layers or not
Returns
----------
train_set: DataIter
Train DataIter
valid: DataIter
Valid DataIter
sentences_size: int
array dimensions
embedded_size: int
array dimensions
vocab_size: int
array dimensions | Construct data iter
Parameters
----------
batch_size: int
num_embed: int
pre_trained_word2vec: boolean
identify the pre-trained layers or not
Returns
----------
train_set: DataIter
Train DataIter
valid: DataIter
Valid DataIter
sentences_size: int
array dimensions
embedded_size: int
array dimensions
vocab_size: int
array dimensions | [
"Construct",
"data",
"iter",
"Parameters",
"----------",
"batch_size",
":",
"int",
"num_embed",
":",
"int",
"pre_trained_word2vec",
":",
"boolean",
"identify",
"the",
"pre",
"-",
"trained",
"layers",
"or",
"not",
"Returns",
"----------",
"train_set",
":",
"DataIter",
"Train",
"DataIter",
"valid",
":",
"DataIter",
"Valid",
"DataIter",
"sentences_size",
":",
"int",
"array",
"dimensions",
"embedded_size",
":",
"int",
"array",
"dimensions",
"vocab_size",
":",
"int",
"array",
"dimensions"
] | def data_iter(batch_size, num_embed, pre_trained_word2vec=False):
"""Construct data iter
Parameters
----------
batch_size: int
num_embed: int
pre_trained_word2vec: boolean
identify the pre-trained layers or not
Returns
----------
train_set: DataIter
Train DataIter
valid: DataIter
Valid DataIter
sentences_size: int
array dimensions
embedded_size: int
array dimensions
vocab_size: int
array dimensions
"""
logger.info('Loading data...')
if pre_trained_word2vec:
word2vec = data_helpers.load_pretrained_word2vec('data/rt.vec')
x, y = data_helpers.load_data_with_word2vec(word2vec)
# reshape for convolution input
x = np.reshape(x, (x.shape[0], 1, x.shape[1], x.shape[2]))
embedded_size = x.shape[-1]
sentences_size = x.shape[2]
vocabulary_size = -1
else:
x, y, vocab, vocab_inv = data_helpers.load_data()
embedded_size = num_embed
sentences_size = x.shape[1]
vocabulary_size = len(vocab)
# randomly shuffle data
np.random.seed(10)
shuffle_indices = np.random.permutation(np.arange(len(y)))
x_shuffled = x[shuffle_indices]
y_shuffled = y[shuffle_indices]
# split train/valid set
x_train, x_dev = x_shuffled[:-1000], x_shuffled[-1000:]
y_train, y_dev = y_shuffled[:-1000], y_shuffled[-1000:]
logger.info('Train/Valid split: %d/%d', len(y_train), len(y_dev))
logger.info('train shape: %(shape)s', {'shape': x_train.shape})
logger.info('valid shape: %(shape)s', {'shape': x_dev.shape})
logger.info('sentence max words: %(shape)s', {'shape': sentences_size})
logger.info('embedding size: %(msg)s', {'msg': embedded_size})
logger.info('vocab size: %(msg)s', {'msg': vocabulary_size})
train_set = mx.io.NDArrayIter(
x_train, y_train, batch_size, shuffle=True)
valid = mx.io.NDArrayIter(
x_dev, y_dev, batch_size)
return train_set, valid, sentences_size, embedded_size, vocabulary_size | [
"def",
"data_iter",
"(",
"batch_size",
",",
"num_embed",
",",
"pre_trained_word2vec",
"=",
"False",
")",
":",
"logger",
".",
"info",
"(",
"'Loading data...'",
")",
"if",
"pre_trained_word2vec",
":",
"word2vec",
"=",
"data_helpers",
".",
"load_pretrained_word2vec",
"(",
"'data/rt.vec'",
")",
"x",
",",
"y",
"=",
"data_helpers",
".",
"load_data_with_word2vec",
"(",
"word2vec",
")",
"# reshape for convolution input",
"x",
"=",
"np",
".",
"reshape",
"(",
"x",
",",
"(",
"x",
".",
"shape",
"[",
"0",
"]",
",",
"1",
",",
"x",
".",
"shape",
"[",
"1",
"]",
",",
"x",
".",
"shape",
"[",
"2",
"]",
")",
")",
"embedded_size",
"=",
"x",
".",
"shape",
"[",
"-",
"1",
"]",
"sentences_size",
"=",
"x",
".",
"shape",
"[",
"2",
"]",
"vocabulary_size",
"=",
"-",
"1",
"else",
":",
"x",
",",
"y",
",",
"vocab",
",",
"vocab_inv",
"=",
"data_helpers",
".",
"load_data",
"(",
")",
"embedded_size",
"=",
"num_embed",
"sentences_size",
"=",
"x",
".",
"shape",
"[",
"1",
"]",
"vocabulary_size",
"=",
"len",
"(",
"vocab",
")",
"# randomly shuffle data",
"np",
".",
"random",
".",
"seed",
"(",
"10",
")",
"shuffle_indices",
"=",
"np",
".",
"random",
".",
"permutation",
"(",
"np",
".",
"arange",
"(",
"len",
"(",
"y",
")",
")",
")",
"x_shuffled",
"=",
"x",
"[",
"shuffle_indices",
"]",
"y_shuffled",
"=",
"y",
"[",
"shuffle_indices",
"]",
"# split train/valid set",
"x_train",
",",
"x_dev",
"=",
"x_shuffled",
"[",
":",
"-",
"1000",
"]",
",",
"x_shuffled",
"[",
"-",
"1000",
":",
"]",
"y_train",
",",
"y_dev",
"=",
"y_shuffled",
"[",
":",
"-",
"1000",
"]",
",",
"y_shuffled",
"[",
"-",
"1000",
":",
"]",
"logger",
".",
"info",
"(",
"'Train/Valid split: %d/%d'",
",",
"len",
"(",
"y_train",
")",
",",
"len",
"(",
"y_dev",
")",
")",
"logger",
".",
"info",
"(",
"'train shape: %(shape)s'",
",",
"{",
"'shape'",
":",
"x_train",
".",
"shape",
"}",
")",
"logger",
".",
"info",
"(",
"'valid shape: %(shape)s'",
",",
"{",
"'shape'",
":",
"x_dev",
".",
"shape",
"}",
")",
"logger",
".",
"info",
"(",
"'sentence max words: %(shape)s'",
",",
"{",
"'shape'",
":",
"sentences_size",
"}",
")",
"logger",
".",
"info",
"(",
"'embedding size: %(msg)s'",
",",
"{",
"'msg'",
":",
"embedded_size",
"}",
")",
"logger",
".",
"info",
"(",
"'vocab size: %(msg)s'",
",",
"{",
"'msg'",
":",
"vocabulary_size",
"}",
")",
"train_set",
"=",
"mx",
".",
"io",
".",
"NDArrayIter",
"(",
"x_train",
",",
"y_train",
",",
"batch_size",
",",
"shuffle",
"=",
"True",
")",
"valid",
"=",
"mx",
".",
"io",
".",
"NDArrayIter",
"(",
"x_dev",
",",
"y_dev",
",",
"batch_size",
")",
"return",
"train_set",
",",
"valid",
",",
"sentences_size",
",",
"embedded_size",
",",
"vocabulary_size"
] | https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/example/cnn_chinese_text_classification/text_cnn.py#L102-L158 |
|
gimli-org/gimli | 17aa2160de9b15ababd9ef99e89b1bc3277bbb23 | doc/examples/2_seismics/plot_03_rays_layered_and_gradient_models.py | python | analyticalSolutionGradient | (x, a=1000, b=100) | return np.minimum(tdirect, trefrac) | Analytical solution for gradient model. | Analytical solution for gradient model. | [
"Analytical",
"solution",
"for",
"gradient",
"model",
"."
] | def analyticalSolutionGradient(x, a=1000, b=100):
"""Analytical solution for gradient model."""
tdirect = np.abs(x) / a # direct wave
tmp = 1 + ((b**2 * np.abs(x)**2) / (2 * a**2))
trefrac = np.abs(b**-1 * np.arccosh(tmp))
return np.minimum(tdirect, trefrac) | [
"def",
"analyticalSolutionGradient",
"(",
"x",
",",
"a",
"=",
"1000",
",",
"b",
"=",
"100",
")",
":",
"tdirect",
"=",
"np",
".",
"abs",
"(",
"x",
")",
"/",
"a",
"# direct wave",
"tmp",
"=",
"1",
"+",
"(",
"(",
"b",
"**",
"2",
"*",
"np",
".",
"abs",
"(",
"x",
")",
"**",
"2",
")",
"/",
"(",
"2",
"*",
"a",
"**",
"2",
")",
")",
"trefrac",
"=",
"np",
".",
"abs",
"(",
"b",
"**",
"-",
"1",
"*",
"np",
".",
"arccosh",
"(",
"tmp",
")",
")",
"return",
"np",
".",
"minimum",
"(",
"tdirect",
",",
"trefrac",
")"
] | https://github.com/gimli-org/gimli/blob/17aa2160de9b15ababd9ef99e89b1bc3277bbb23/doc/examples/2_seismics/plot_03_rays_layered_and_gradient_models.py#L96-L101 |
|
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/richtext.py | python | TextBoxAttr.GetPadding | (*args) | return _richtext.TextBoxAttr_GetPadding(*args) | GetPadding(self) -> TextAttrDimensions
GetPadding(self) -> TextAttrDimensions | GetPadding(self) -> TextAttrDimensions
GetPadding(self) -> TextAttrDimensions | [
"GetPadding",
"(",
"self",
")",
"-",
">",
"TextAttrDimensions",
"GetPadding",
"(",
"self",
")",
"-",
">",
"TextAttrDimensions"
] | def GetPadding(*args):
"""
GetPadding(self) -> TextAttrDimensions
GetPadding(self) -> TextAttrDimensions
"""
return _richtext.TextBoxAttr_GetPadding(*args) | [
"def",
"GetPadding",
"(",
"*",
"args",
")",
":",
"return",
"_richtext",
".",
"TextBoxAttr_GetPadding",
"(",
"*",
"args",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/richtext.py#L698-L703 |
|
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/ros_comm/roscpp/rosbuild/scripts/msg_gen.py | python | write_constant_declaration | (s, constant) | Write a constant value as a static member
@param s: The stream to write to
@type s: stream
@param constant: The constant
@type constant: roslib.msgs.Constant | Write a constant value as a static member | [
"Write",
"a",
"constant",
"value",
"as",
"a",
"static",
"member"
] | def write_constant_declaration(s, constant):
"""
Write a constant value as a static member
@param s: The stream to write to
@type s: stream
@param constant: The constant
@type constant: roslib.msgs.Constant
"""
# integral types get their declarations as enums to allow use at compile time
if (constant.type in ['byte', 'int8', 'int16', 'int32', 'int64', 'char', 'uint8', 'uint16', 'uint32', 'uint64']):
s.write(' enum { %s = %s };\n'%(constant.name, constant.val))
else:
s.write(' static const %s %s;\n'%(msg_type_to_cpp(constant.type), constant.name)) | [
"def",
"write_constant_declaration",
"(",
"s",
",",
"constant",
")",
":",
"# integral types get their declarations as enums to allow use at compile time",
"if",
"(",
"constant",
".",
"type",
"in",
"[",
"'byte'",
",",
"'int8'",
",",
"'int16'",
",",
"'int32'",
",",
"'int64'",
",",
"'char'",
",",
"'uint8'",
",",
"'uint16'",
",",
"'uint32'",
",",
"'uint64'",
"]",
")",
":",
"s",
".",
"write",
"(",
"' enum { %s = %s };\\n'",
"%",
"(",
"constant",
".",
"name",
",",
"constant",
".",
"val",
")",
")",
"else",
":",
"s",
".",
"write",
"(",
"' static const %s %s;\\n'",
"%",
"(",
"msg_type_to_cpp",
"(",
"constant",
".",
"type",
")",
",",
"constant",
".",
"name",
")",
")"
] | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/ros_comm/roscpp/rosbuild/scripts/msg_gen.py#L371-L385 |
||
seqan/seqan | f5f658343c366c9c3d44ba358ffc9317e78a09ed | util/py_lib/seqan/dox/write_html.py | python | escapeAnchor | (name) | return name | Escape a name such that it is safe to use for anchors. | Escape a name such that it is safe to use for anchors. | [
"Escape",
"a",
"name",
"such",
"that",
"it",
"is",
"safe",
"to",
"use",
"for",
"anchors",
"."
] | def escapeAnchor(name):
"""Escape a name such that it is safe to use for anchors."""
return name | [
"def",
"escapeAnchor",
"(",
"name",
")",
":",
"return",
"name"
] | https://github.com/seqan/seqan/blob/f5f658343c366c9c3d44ba358ffc9317e78a09ed/util/py_lib/seqan/dox/write_html.py#L36-L38 |
|
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/share/gdb/python/gdb/command/explore.py | python | Explorer.init_env | () | Initializes the Explorer environment.
This function should be invoked before starting any exploration. If
invoked before an exploration, it need not be invoked for subsequent
explorations. | Initializes the Explorer environment.
This function should be invoked before starting any exploration. If
invoked before an exploration, it need not be invoked for subsequent
explorations. | [
"Initializes",
"the",
"Explorer",
"environment",
".",
"This",
"function",
"should",
"be",
"invoked",
"before",
"starting",
"any",
"exploration",
".",
"If",
"invoked",
"before",
"an",
"exploration",
"it",
"need",
"not",
"be",
"invoked",
"for",
"subsequent",
"explorations",
"."
] | def init_env():
"""Initializes the Explorer environment.
This function should be invoked before starting any exploration. If
invoked before an exploration, it need not be invoked for subsequent
explorations.
"""
Explorer.type_code_to_explorer_map = {
gdb.TYPE_CODE_CHAR : ScalarExplorer,
gdb.TYPE_CODE_INT : ScalarExplorer,
gdb.TYPE_CODE_BOOL : ScalarExplorer,
gdb.TYPE_CODE_FLT : ScalarExplorer,
gdb.TYPE_CODE_VOID : ScalarExplorer,
gdb.TYPE_CODE_ENUM : ScalarExplorer,
gdb.TYPE_CODE_STRUCT : CompoundExplorer,
gdb.TYPE_CODE_UNION : CompoundExplorer,
gdb.TYPE_CODE_PTR : PointerExplorer,
gdb.TYPE_CODE_REF : ReferenceExplorer,
gdb.TYPE_CODE_TYPEDEF : TypedefExplorer,
gdb.TYPE_CODE_ARRAY : ArrayExplorer
} | [
"def",
"init_env",
"(",
")",
":",
"Explorer",
".",
"type_code_to_explorer_map",
"=",
"{",
"gdb",
".",
"TYPE_CODE_CHAR",
":",
"ScalarExplorer",
",",
"gdb",
".",
"TYPE_CODE_INT",
":",
"ScalarExplorer",
",",
"gdb",
".",
"TYPE_CODE_BOOL",
":",
"ScalarExplorer",
",",
"gdb",
".",
"TYPE_CODE_FLT",
":",
"ScalarExplorer",
",",
"gdb",
".",
"TYPE_CODE_VOID",
":",
"ScalarExplorer",
",",
"gdb",
".",
"TYPE_CODE_ENUM",
":",
"ScalarExplorer",
",",
"gdb",
".",
"TYPE_CODE_STRUCT",
":",
"CompoundExplorer",
",",
"gdb",
".",
"TYPE_CODE_UNION",
":",
"CompoundExplorer",
",",
"gdb",
".",
"TYPE_CODE_PTR",
":",
"PointerExplorer",
",",
"gdb",
".",
"TYPE_CODE_REF",
":",
"ReferenceExplorer",
",",
"gdb",
".",
"TYPE_CODE_TYPEDEF",
":",
"TypedefExplorer",
",",
"gdb",
".",
"TYPE_CODE_ARRAY",
":",
"ArrayExplorer",
"}"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/share/gdb/python/gdb/command/explore.py#L118-L137 |
||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/lib2to3/pytree.py | python | Node._eq | (self, other) | return (self.type, self.children) == (other.type, other.children) | Compare two nodes for equality. | Compare two nodes for equality. | [
"Compare",
"two",
"nodes",
"for",
"equality",
"."
] | def _eq(self, other):
"""Compare two nodes for equality."""
return (self.type, self.children) == (other.type, other.children) | [
"def",
"_eq",
"(",
"self",
",",
"other",
")",
":",
"return",
"(",
"self",
".",
"type",
",",
"self",
".",
"children",
")",
"==",
"(",
"other",
".",
"type",
",",
"other",
".",
"children",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/lib2to3/pytree.py#L285-L287 |
|
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_core.py | python | SizerItem.CalcMin | (*args, **kwargs) | return _core_.SizerItem_CalcMin(*args, **kwargs) | CalcMin(self) -> Size
Calculates the minimum desired size for the item, including any space
needed by borders. | CalcMin(self) -> Size | [
"CalcMin",
"(",
"self",
")",
"-",
">",
"Size"
] | def CalcMin(*args, **kwargs):
"""
CalcMin(self) -> Size
Calculates the minimum desired size for the item, including any space
needed by borders.
"""
return _core_.SizerItem_CalcMin(*args, **kwargs) | [
"def",
"CalcMin",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"SizerItem_CalcMin",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L14068-L14075 |
|
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/extern/aui/framemanager.py | python | AuiManager.DestroyHintWindow | (self) | Destroys the standard wxAUI hint window. | Destroys the standard wxAUI hint window. | [
"Destroys",
"the",
"standard",
"wxAUI",
"hint",
"window",
"."
] | def DestroyHintWindow(self):
""" Destroys the standard wxAUI hint window. """
if self._hint_window:
self._hint_window.Destroy()
self._hint_window = None | [
"def",
"DestroyHintWindow",
"(",
"self",
")",
":",
"if",
"self",
".",
"_hint_window",
":",
"self",
".",
"_hint_window",
".",
"Destroy",
"(",
")",
"self",
".",
"_hint_window",
"=",
"None"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/extern/aui/framemanager.py#L4563-L4569 |
||
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Draft/draftguitools/gui_trackers.py | python | arcTracker.setCenter | (self, cen) | Set the center point. | Set the center point. | [
"Set",
"the",
"center",
"point",
"."
] | def setCenter(self, cen):
"""Set the center point."""
self.trans.translation.setValue([cen.x, cen.y, cen.z]) | [
"def",
"setCenter",
"(",
"self",
",",
"cen",
")",
":",
"self",
".",
"trans",
".",
"translation",
".",
"setValue",
"(",
"[",
"cen",
".",
"x",
",",
"cen",
".",
"y",
",",
"cen",
".",
"z",
"]",
")"
] | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Draft/draftguitools/gui_trackers.py#L555-L557 |
||
milvus-io/milvus | 3b1030de2b6c39e3512833e97f6044d63eb24237 | internal/core/build-support/cpplint.py | python | FileInfo.FullName | (self) | return os.path.abspath(self._filename).replace('\\', '/') | Make Windows paths like Unix. | Make Windows paths like Unix. | [
"Make",
"Windows",
"paths",
"like",
"Unix",
"."
] | def FullName(self):
"""Make Windows paths like Unix."""
return os.path.abspath(self._filename).replace('\\', '/') | [
"def",
"FullName",
"(",
"self",
")",
":",
"return",
"os",
".",
"path",
".",
"abspath",
"(",
"self",
".",
"_filename",
")",
".",
"replace",
"(",
"'\\\\'",
",",
"'/'",
")"
] | https://github.com/milvus-io/milvus/blob/3b1030de2b6c39e3512833e97f6044d63eb24237/internal/core/build-support/cpplint.py#L1560-L1562 |
|
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_misc.py | python | ConfigBase.SetRecordDefaults | (*args, **kwargs) | return _misc_.ConfigBase_SetRecordDefaults(*args, **kwargs) | SetRecordDefaults(self, bool doIt=True)
Set whether the config objec should record default values. | SetRecordDefaults(self, bool doIt=True) | [
"SetRecordDefaults",
"(",
"self",
"bool",
"doIt",
"=",
"True",
")"
] | def SetRecordDefaults(*args, **kwargs):
"""
SetRecordDefaults(self, bool doIt=True)
Set whether the config objec should record default values.
"""
return _misc_.ConfigBase_SetRecordDefaults(*args, **kwargs) | [
"def",
"SetRecordDefaults",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"ConfigBase_SetRecordDefaults",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_misc.py#L3389-L3395 |
|
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/scipy/spatial/kdtree.py | python | Rectangle.max_distance_rectangle | (self, other, p=2.) | return minkowski_distance(0, np.maximum(self.maxes-other.mins,other.maxes-self.mins),p) | Compute the maximum distance between points in the two hyperrectangles.
Parameters
----------
other : hyperrectangle
Input.
p : float, optional
Input. | Compute the maximum distance between points in the two hyperrectangles. | [
"Compute",
"the",
"maximum",
"distance",
"between",
"points",
"in",
"the",
"two",
"hyperrectangles",
"."
] | def max_distance_rectangle(self, other, p=2.):
"""
Compute the maximum distance between points in the two hyperrectangles.
Parameters
----------
other : hyperrectangle
Input.
p : float, optional
Input.
"""
return minkowski_distance(0, np.maximum(self.maxes-other.mins,other.maxes-self.mins),p) | [
"def",
"max_distance_rectangle",
"(",
"self",
",",
"other",
",",
"p",
"=",
"2.",
")",
":",
"return",
"minkowski_distance",
"(",
"0",
",",
"np",
".",
"maximum",
"(",
"self",
".",
"maxes",
"-",
"other",
".",
"mins",
",",
"other",
".",
"maxes",
"-",
"self",
".",
"mins",
")",
",",
"p",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/spatial/kdtree.py#L161-L173 |
|
google/or-tools | 2cb85b4eead4c38e1c54b48044f92087cf165bce | ortools/sat/python/cp_model.py | python | CpModel.AddDivisionEquality | (self, target, num, denom) | return ct | Adds `target == num // denom` (integer division rounded towards 0). | Adds `target == num // denom` (integer division rounded towards 0). | [
"Adds",
"target",
"==",
"num",
"//",
"denom",
"(",
"integer",
"division",
"rounded",
"towards",
"0",
")",
"."
] | def AddDivisionEquality(self, target, num, denom):
"""Adds `target == num // denom` (integer division rounded towards 0)."""
ct = Constraint(self.__model.constraints)
model_ct = self.__model.constraints[ct.Index()]
model_ct.int_div.exprs.append(self.ParseLinearExpression(num))
model_ct.int_div.exprs.append(self.ParseLinearExpression(denom))
model_ct.int_div.target.CopyFrom(self.ParseLinearExpression(target))
return ct | [
"def",
"AddDivisionEquality",
"(",
"self",
",",
"target",
",",
"num",
",",
"denom",
")",
":",
"ct",
"=",
"Constraint",
"(",
"self",
".",
"__model",
".",
"constraints",
")",
"model_ct",
"=",
"self",
".",
"__model",
".",
"constraints",
"[",
"ct",
".",
"Index",
"(",
")",
"]",
"model_ct",
".",
"int_div",
".",
"exprs",
".",
"append",
"(",
"self",
".",
"ParseLinearExpression",
"(",
"num",
")",
")",
"model_ct",
".",
"int_div",
".",
"exprs",
".",
"append",
"(",
"self",
".",
"ParseLinearExpression",
"(",
"denom",
")",
")",
"model_ct",
".",
"int_div",
".",
"target",
".",
"CopyFrom",
"(",
"self",
".",
"ParseLinearExpression",
"(",
"target",
")",
")",
"return",
"ct"
] | https://github.com/google/or-tools/blob/2cb85b4eead4c38e1c54b48044f92087cf165bce/ortools/sat/python/cp_model.py#L1514-L1521 |
|
baidu/bigflow | 449245016c0df7d1252e85581e588bfc60cefad3 | bigflow_python/python/bigflow/serde.py | python | IntSerde.__init__ | (self) | init | init | [
"init"
] | def __init__(self):
""" init """
super(IntSerde, self).__init__() | [
"def",
"__init__",
"(",
"self",
")",
":",
"super",
"(",
"IntSerde",
",",
"self",
")",
".",
"__init__",
"(",
")"
] | https://github.com/baidu/bigflow/blob/449245016c0df7d1252e85581e588bfc60cefad3/bigflow_python/python/bigflow/serde.py#L162-L164 |
||
flexflow/FlexFlow | 581fad8ba8d10a16a3102ee2b406b0319586df24 | examples/python/keras/candle_uno/generic_utils.py | python | func_dump | (func) | return code, defaults, closure | Serialize user defined function. | Serialize user defined function. | [
"Serialize",
"user",
"defined",
"function",
"."
] | def func_dump(func):
""" Serialize user defined function. """
code = marshal.dumps(func.__code__).decode('raw_unicode_escape')
defaults = func.__defaults__
if func.__closure__:
closure = tuple(c.cell_contents for c in func.__closure__)
else:
closure = None
return code, defaults, closure | [
"def",
"func_dump",
"(",
"func",
")",
":",
"code",
"=",
"marshal",
".",
"dumps",
"(",
"func",
".",
"__code__",
")",
".",
"decode",
"(",
"'raw_unicode_escape'",
")",
"defaults",
"=",
"func",
".",
"__defaults__",
"if",
"func",
".",
"__closure__",
":",
"closure",
"=",
"tuple",
"(",
"c",
".",
"cell_contents",
"for",
"c",
"in",
"func",
".",
"__closure__",
")",
"else",
":",
"closure",
"=",
"None",
"return",
"code",
",",
"defaults",
",",
"closure"
] | https://github.com/flexflow/FlexFlow/blob/581fad8ba8d10a16a3102ee2b406b0319586df24/examples/python/keras/candle_uno/generic_utils.py#L41-L49 |
|
cyberbotics/webots | af7fa7d68dcf7b4550f1f2e132092b41e83698fc | scripts/image_tools/images/hdr.py | python | HDR.load_from_file | (cls, filename) | return hdr | Parse the HDR file. | Parse the HDR file. | [
"Parse",
"the",
"HDR",
"file",
"."
] | def load_from_file(cls, filename):
"""Parse the HDR file."""
# HDR Format Specifications: http://paulbourke.net/dataformats/pic/
#
# Typical header:
# #?RADIANCE
# SOFTWARE=gegl 0.4.12
# FORMAT=32-bit_rle_rgbe
#
# -Y 1024 +X 2048
# Data
hdr = HDR()
data = []
header = False
with open(filename, "rb") as f:
while True:
line = ''
c = f.read(1).decode('ascii')
while c != '\n':
line += c
c = f.read(1).decode('ascii')
# Case: Empty lines
if line == '' or (len(line) == 1 and ord(line[0]) == 10):
continue
# Case: header
m = re.match(r'^#\?RADIANCE$', line)
if m:
header = True
continue
# Case: Size
m = re.match(r'^(.)(.)\s(\d+)\s(.)(.)\s(\d+)$', line)
if m:
hdr.rotated = m.group(2) == 'X'
hdr.xFlipped = m.group(1 if hdr.rotated else 4) == '-'
hdr.yFlipped = m.group(4 if hdr.rotated else 1) == '+'
hdr.width = int(m.group(6))
hdr.height = int(m.group(3))
break
# Case: ignored header entries
if line.startswith('FORMAT=') or \
line.startswith('EXPOSURE=') or \
line.startswith('COLORCORR=') or \
line.startswith('SOFTWARE=') or \
line.startswith('PIXASPECT=') or \
line.startswith('VIEW=') or \
line.startswith('PRIMARIES=') or \
line.startswith('GAMMA=') or \
line.startswith('# '):
continue
break
# Case: Data
data = f.read()
assert header, 'Invalid header.'
assert 4 * hdr.width * hdr.height == len(data) and len(data) > 0, \
'Invalid dimensions (expected dimension: 4x%dx%d, get %d floats)' % (hdr.width, hdr.height, len(data))
assert not (hdr.rotated or hdr.xFlipped or hdr.yFlipped), 'Flip or rotation flags are not supported.'
# Convert data to floats
hdr.data = [0.0] * (3 * hdr.width * hdr.height)
for i in range(hdr.width * hdr.height):
r = float(data[4 * i])
g = float(data[4 * i + 1])
b = float(data[4 * i + 2])
e = pow(2.0, float(data[4 * i + 3]) - 128.0 + 8.0)
hdr.data[3 * i] = pow(r * e, 1.0 / GAMMA) / 255.0
hdr.data[3 * i + 1] = pow(g * e, 1.0 / GAMMA) / 255.0
hdr.data[3 * i + 2] = pow(b * e, 1.0 / GAMMA) / 255.0
return hdr | [
"def",
"load_from_file",
"(",
"cls",
",",
"filename",
")",
":",
"# HDR Format Specifications: http://paulbourke.net/dataformats/pic/",
"#",
"# Typical header:",
"# #?RADIANCE",
"# SOFTWARE=gegl 0.4.12",
"# FORMAT=32-bit_rle_rgbe",
"#",
"# -Y 1024 +X 2048",
"# Data",
"hdr",
"=",
"HDR",
"(",
")",
"data",
"=",
"[",
"]",
"header",
"=",
"False",
"with",
"open",
"(",
"filename",
",",
"\"rb\"",
")",
"as",
"f",
":",
"while",
"True",
":",
"line",
"=",
"''",
"c",
"=",
"f",
".",
"read",
"(",
"1",
")",
".",
"decode",
"(",
"'ascii'",
")",
"while",
"c",
"!=",
"'\\n'",
":",
"line",
"+=",
"c",
"c",
"=",
"f",
".",
"read",
"(",
"1",
")",
".",
"decode",
"(",
"'ascii'",
")",
"# Case: Empty lines",
"if",
"line",
"==",
"''",
"or",
"(",
"len",
"(",
"line",
")",
"==",
"1",
"and",
"ord",
"(",
"line",
"[",
"0",
"]",
")",
"==",
"10",
")",
":",
"continue",
"# Case: header",
"m",
"=",
"re",
".",
"match",
"(",
"r'^#\\?RADIANCE$'",
",",
"line",
")",
"if",
"m",
":",
"header",
"=",
"True",
"continue",
"# Case: Size",
"m",
"=",
"re",
".",
"match",
"(",
"r'^(.)(.)\\s(\\d+)\\s(.)(.)\\s(\\d+)$'",
",",
"line",
")",
"if",
"m",
":",
"hdr",
".",
"rotated",
"=",
"m",
".",
"group",
"(",
"2",
")",
"==",
"'X'",
"hdr",
".",
"xFlipped",
"=",
"m",
".",
"group",
"(",
"1",
"if",
"hdr",
".",
"rotated",
"else",
"4",
")",
"==",
"'-'",
"hdr",
".",
"yFlipped",
"=",
"m",
".",
"group",
"(",
"4",
"if",
"hdr",
".",
"rotated",
"else",
"1",
")",
"==",
"'+'",
"hdr",
".",
"width",
"=",
"int",
"(",
"m",
".",
"group",
"(",
"6",
")",
")",
"hdr",
".",
"height",
"=",
"int",
"(",
"m",
".",
"group",
"(",
"3",
")",
")",
"break",
"# Case: ignored header entries",
"if",
"line",
".",
"startswith",
"(",
"'FORMAT='",
")",
"or",
"line",
".",
"startswith",
"(",
"'EXPOSURE='",
")",
"or",
"line",
".",
"startswith",
"(",
"'COLORCORR='",
")",
"or",
"line",
".",
"startswith",
"(",
"'SOFTWARE='",
")",
"or",
"line",
".",
"startswith",
"(",
"'PIXASPECT='",
")",
"or",
"line",
".",
"startswith",
"(",
"'VIEW='",
")",
"or",
"line",
".",
"startswith",
"(",
"'PRIMARIES='",
")",
"or",
"line",
".",
"startswith",
"(",
"'GAMMA='",
")",
"or",
"line",
".",
"startswith",
"(",
"'# '",
")",
":",
"continue",
"break",
"# Case: Data",
"data",
"=",
"f",
".",
"read",
"(",
")",
"assert",
"header",
",",
"'Invalid header.'",
"assert",
"4",
"*",
"hdr",
".",
"width",
"*",
"hdr",
".",
"height",
"==",
"len",
"(",
"data",
")",
"and",
"len",
"(",
"data",
")",
">",
"0",
",",
"'Invalid dimensions (expected dimension: 4x%dx%d, get %d floats)'",
"%",
"(",
"hdr",
".",
"width",
",",
"hdr",
".",
"height",
",",
"len",
"(",
"data",
")",
")",
"assert",
"not",
"(",
"hdr",
".",
"rotated",
"or",
"hdr",
".",
"xFlipped",
"or",
"hdr",
".",
"yFlipped",
")",
",",
"'Flip or rotation flags are not supported.'",
"# Convert data to floats",
"hdr",
".",
"data",
"=",
"[",
"0.0",
"]",
"*",
"(",
"3",
"*",
"hdr",
".",
"width",
"*",
"hdr",
".",
"height",
")",
"for",
"i",
"in",
"range",
"(",
"hdr",
".",
"width",
"*",
"hdr",
".",
"height",
")",
":",
"r",
"=",
"float",
"(",
"data",
"[",
"4",
"*",
"i",
"]",
")",
"g",
"=",
"float",
"(",
"data",
"[",
"4",
"*",
"i",
"+",
"1",
"]",
")",
"b",
"=",
"float",
"(",
"data",
"[",
"4",
"*",
"i",
"+",
"2",
"]",
")",
"e",
"=",
"pow",
"(",
"2.0",
",",
"float",
"(",
"data",
"[",
"4",
"*",
"i",
"+",
"3",
"]",
")",
"-",
"128.0",
"+",
"8.0",
")",
"hdr",
".",
"data",
"[",
"3",
"*",
"i",
"]",
"=",
"pow",
"(",
"r",
"*",
"e",
",",
"1.0",
"/",
"GAMMA",
")",
"/",
"255.0",
"hdr",
".",
"data",
"[",
"3",
"*",
"i",
"+",
"1",
"]",
"=",
"pow",
"(",
"g",
"*",
"e",
",",
"1.0",
"/",
"GAMMA",
")",
"/",
"255.0",
"hdr",
".",
"data",
"[",
"3",
"*",
"i",
"+",
"2",
"]",
"=",
"pow",
"(",
"b",
"*",
"e",
",",
"1.0",
"/",
"GAMMA",
")",
"/",
"255.0",
"return",
"hdr"
] | https://github.com/cyberbotics/webots/blob/af7fa7d68dcf7b4550f1f2e132092b41e83698fc/scripts/image_tools/images/hdr.py#L32-L102 |
|
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Draft/draftguitools/gui_snaps.py | python | Draft_Snap_Parallel.GetResources | (self) | return {'Pixmap': 'Snap_Parallel',
'MenuText': QT_TRANSLATE_NOOP("Draft_Snap_Parallel", "Parallel"),
'ToolTip': QT_TRANSLATE_NOOP("Draft_Snap_Parallel", "Set snapping to a direction that is parallel to an edge.")} | Set icon, menu and tooltip. | Set icon, menu and tooltip. | [
"Set",
"icon",
"menu",
"and",
"tooltip",
"."
] | def GetResources(self):
"""Set icon, menu and tooltip."""
return {'Pixmap': 'Snap_Parallel',
'MenuText': QT_TRANSLATE_NOOP("Draft_Snap_Parallel", "Parallel"),
'ToolTip': QT_TRANSLATE_NOOP("Draft_Snap_Parallel", "Set snapping to a direction that is parallel to an edge.")} | [
"def",
"GetResources",
"(",
"self",
")",
":",
"return",
"{",
"'Pixmap'",
":",
"'Snap_Parallel'",
",",
"'MenuText'",
":",
"QT_TRANSLATE_NOOP",
"(",
"\"Draft_Snap_Parallel\"",
",",
"\"Parallel\"",
")",
",",
"'ToolTip'",
":",
"QT_TRANSLATE_NOOP",
"(",
"\"Draft_Snap_Parallel\"",
",",
"\"Set snapping to a direction that is parallel to an edge.\"",
")",
"}"
] | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Draft/draftguitools/gui_snaps.py#L279-L284 |
|
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py2/scipy/optimize/optimize.py | python | brent | (func, args=(), brack=None, tol=1.48e-8, full_output=0, maxiter=500) | Given a function of one-variable and a possible bracket, return
the local minimum of the function isolated to a fractional precision
of tol.
Parameters
----------
func : callable f(x,*args)
Objective function.
args : tuple, optional
Additional arguments (if present).
brack : tuple, optional
Either a triple (xa,xb,xc) where xa<xb<xc and func(xb) <
func(xa), func(xc) or a pair (xa,xb) which are used as a
starting interval for a downhill bracket search (see
`bracket`). Providing the pair (xa,xb) does not always mean
the obtained solution will satisfy xa<=x<=xb.
tol : float, optional
Stop if between iteration change is less than `tol`.
full_output : bool, optional
If True, return all output args (xmin, fval, iter,
funcalls).
maxiter : int, optional
Maximum number of iterations in solution.
Returns
-------
xmin : ndarray
Optimum point.
fval : float
Optimum value.
iter : int
Number of iterations.
funcalls : int
Number of objective function evaluations made.
See also
--------
minimize_scalar: Interface to minimization algorithms for scalar
univariate functions. See the 'Brent' `method` in particular.
Notes
-----
Uses inverse parabolic interpolation when possible to speed up
convergence of golden section method.
Does not ensure that the minimum lies in the range specified by
`brack`. See `fminbound`.
Examples
--------
We illustrate the behaviour of the function when `brack` is of
size 2 and 3 respectively. In the case where `brack` is of the
form (xa,xb), we can see for the given values, the output need
not necessarily lie in the range (xa,xb).
>>> def f(x):
... return x**2
>>> from scipy import optimize
>>> minimum = optimize.brent(f,brack=(1,2))
>>> minimum
0.0
>>> minimum = optimize.brent(f,brack=(-1,0.5,2))
>>> minimum
-2.7755575615628914e-17 | Given a function of one-variable and a possible bracket, return
the local minimum of the function isolated to a fractional precision
of tol. | [
"Given",
"a",
"function",
"of",
"one",
"-",
"variable",
"and",
"a",
"possible",
"bracket",
"return",
"the",
"local",
"minimum",
"of",
"the",
"function",
"isolated",
"to",
"a",
"fractional",
"precision",
"of",
"tol",
"."
] | def brent(func, args=(), brack=None, tol=1.48e-8, full_output=0, maxiter=500):
"""
Given a function of one-variable and a possible bracket, return
the local minimum of the function isolated to a fractional precision
of tol.
Parameters
----------
func : callable f(x,*args)
Objective function.
args : tuple, optional
Additional arguments (if present).
brack : tuple, optional
Either a triple (xa,xb,xc) where xa<xb<xc and func(xb) <
func(xa), func(xc) or a pair (xa,xb) which are used as a
starting interval for a downhill bracket search (see
`bracket`). Providing the pair (xa,xb) does not always mean
the obtained solution will satisfy xa<=x<=xb.
tol : float, optional
Stop if between iteration change is less than `tol`.
full_output : bool, optional
If True, return all output args (xmin, fval, iter,
funcalls).
maxiter : int, optional
Maximum number of iterations in solution.
Returns
-------
xmin : ndarray
Optimum point.
fval : float
Optimum value.
iter : int
Number of iterations.
funcalls : int
Number of objective function evaluations made.
See also
--------
minimize_scalar: Interface to minimization algorithms for scalar
univariate functions. See the 'Brent' `method` in particular.
Notes
-----
Uses inverse parabolic interpolation when possible to speed up
convergence of golden section method.
Does not ensure that the minimum lies in the range specified by
`brack`. See `fminbound`.
Examples
--------
We illustrate the behaviour of the function when `brack` is of
size 2 and 3 respectively. In the case where `brack` is of the
form (xa,xb), we can see for the given values, the output need
not necessarily lie in the range (xa,xb).
>>> def f(x):
... return x**2
>>> from scipy import optimize
>>> minimum = optimize.brent(f,brack=(1,2))
>>> minimum
0.0
>>> minimum = optimize.brent(f,brack=(-1,0.5,2))
>>> minimum
-2.7755575615628914e-17
"""
options = {'xtol': tol,
'maxiter': maxiter}
res = _minimize_scalar_brent(func, brack, args, **options)
if full_output:
return res['x'], res['fun'], res['nit'], res['nfev']
else:
return res['x'] | [
"def",
"brent",
"(",
"func",
",",
"args",
"=",
"(",
")",
",",
"brack",
"=",
"None",
",",
"tol",
"=",
"1.48e-8",
",",
"full_output",
"=",
"0",
",",
"maxiter",
"=",
"500",
")",
":",
"options",
"=",
"{",
"'xtol'",
":",
"tol",
",",
"'maxiter'",
":",
"maxiter",
"}",
"res",
"=",
"_minimize_scalar_brent",
"(",
"func",
",",
"brack",
",",
"args",
",",
"*",
"*",
"options",
")",
"if",
"full_output",
":",
"return",
"res",
"[",
"'x'",
"]",
",",
"res",
"[",
"'fun'",
"]",
",",
"res",
"[",
"'nit'",
"]",
",",
"res",
"[",
"'nfev'",
"]",
"else",
":",
"return",
"res",
"[",
"'x'",
"]"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/optimize/optimize.py#L2011-L2087 |
||
eventql/eventql | 7ca0dbb2e683b525620ea30dc40540a22d5eb227 | deps/3rdparty/spidermonkey/mozjs/python/mozbuild/mozbuild/preprocessor.py | python | Expression.evaluate | (self, context) | return opmap[self.e.type](self.e) | Evaluate the expression with the given context | Evaluate the expression with the given context | [
"Evaluate",
"the",
"expression",
"with",
"the",
"given",
"context"
] | def evaluate(self, context):
"""
Evaluate the expression with the given context
"""
# Helper function to evaluate __get_equality results
def eval_equality(tok):
left = opmap[tok[0].type](tok[0])
right = opmap[tok[2].type](tok[2])
rv = left == right
if tok[1].value == '!=':
rv = not rv
return rv
# Helper function to evaluate __get_logical_and and __get_logical_or results
def eval_logical_op(tok):
left = opmap[tok[0].type](tok[0])
right = opmap[tok[2].type](tok[2])
if tok[1].value == '&&':
return left and right
elif tok[1].value == '||':
return left or right
raise Expression.ParseError, self
# Mapping from token types to evaluator functions
# Apart from (non-)equality, all these can be simple lambda forms.
opmap = {
'logical_op': eval_logical_op,
'equality': eval_equality,
'not': lambda tok: not opmap[tok[0].type](tok[0]),
'string': lambda tok: context[tok.value],
'defined': lambda tok: tok.value in context,
'int': lambda tok: tok.value}
return opmap[self.e.type](self.e); | [
"def",
"evaluate",
"(",
"self",
",",
"context",
")",
":",
"# Helper function to evaluate __get_equality results",
"def",
"eval_equality",
"(",
"tok",
")",
":",
"left",
"=",
"opmap",
"[",
"tok",
"[",
"0",
"]",
".",
"type",
"]",
"(",
"tok",
"[",
"0",
"]",
")",
"right",
"=",
"opmap",
"[",
"tok",
"[",
"2",
"]",
".",
"type",
"]",
"(",
"tok",
"[",
"2",
"]",
")",
"rv",
"=",
"left",
"==",
"right",
"if",
"tok",
"[",
"1",
"]",
".",
"value",
"==",
"'!='",
":",
"rv",
"=",
"not",
"rv",
"return",
"rv",
"# Helper function to evaluate __get_logical_and and __get_logical_or results",
"def",
"eval_logical_op",
"(",
"tok",
")",
":",
"left",
"=",
"opmap",
"[",
"tok",
"[",
"0",
"]",
".",
"type",
"]",
"(",
"tok",
"[",
"0",
"]",
")",
"right",
"=",
"opmap",
"[",
"tok",
"[",
"2",
"]",
".",
"type",
"]",
"(",
"tok",
"[",
"2",
"]",
")",
"if",
"tok",
"[",
"1",
"]",
".",
"value",
"==",
"'&&'",
":",
"return",
"left",
"and",
"right",
"elif",
"tok",
"[",
"1",
"]",
".",
"value",
"==",
"'||'",
":",
"return",
"left",
"or",
"right",
"raise",
"Expression",
".",
"ParseError",
",",
"self",
"# Mapping from token types to evaluator functions",
"# Apart from (non-)equality, all these can be simple lambda forms.",
"opmap",
"=",
"{",
"'logical_op'",
":",
"eval_logical_op",
",",
"'equality'",
":",
"eval_equality",
",",
"'not'",
":",
"lambda",
"tok",
":",
"not",
"opmap",
"[",
"tok",
"[",
"0",
"]",
".",
"type",
"]",
"(",
"tok",
"[",
"0",
"]",
")",
",",
"'string'",
":",
"lambda",
"tok",
":",
"context",
"[",
"tok",
".",
"value",
"]",
",",
"'defined'",
":",
"lambda",
"tok",
":",
"tok",
".",
"value",
"in",
"context",
",",
"'int'",
":",
"lambda",
"tok",
":",
"tok",
".",
"value",
"}",
"return",
"opmap",
"[",
"self",
".",
"e",
".",
"type",
"]",
"(",
"self",
".",
"e",
")"
] | https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/python/mozbuild/mozbuild/preprocessor.py#L179-L212 |
|
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/third_party/lib_aarch64/python2.7/dist-packages/yaml/__init__.py | python | add_multi_representer | (data_type, multi_representer, Dumper=Dumper) | Add a representer for the given type.
Multi-representer is a function accepting a Dumper instance
and an instance of the given data type or subtype
and producing the corresponding representation node. | Add a representer for the given type.
Multi-representer is a function accepting a Dumper instance
and an instance of the given data type or subtype
and producing the corresponding representation node. | [
"Add",
"a",
"representer",
"for",
"the",
"given",
"type",
".",
"Multi",
"-",
"representer",
"is",
"a",
"function",
"accepting",
"a",
"Dumper",
"instance",
"and",
"an",
"instance",
"of",
"the",
"given",
"data",
"type",
"or",
"subtype",
"and",
"producing",
"the",
"corresponding",
"representation",
"node",
"."
] | def add_multi_representer(data_type, multi_representer, Dumper=Dumper):
"""
Add a representer for the given type.
Multi-representer is a function accepting a Dumper instance
and an instance of the given data type or subtype
and producing the corresponding representation node.
"""
Dumper.add_multi_representer(data_type, multi_representer) | [
"def",
"add_multi_representer",
"(",
"data_type",
",",
"multi_representer",
",",
"Dumper",
"=",
"Dumper",
")",
":",
"Dumper",
".",
"add_multi_representer",
"(",
"data_type",
",",
"multi_representer",
")"
] | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_aarch64/python2.7/dist-packages/yaml/__init__.py#L267-L274 |
||
openweave/openweave-core | 11ceb6b7efd39fe05de7f79229247a5774d56766 | src/device-manager/python/weave-device-mgr.py | python | DeviceMgrCmd.do_stopsystemtest | (self, line) | stop-system-test
Stop system test on a device. | stop-system-test | [
"stop",
"-",
"system",
"-",
"test"
] | def do_stopsystemtest(self, line):
"""
stop-system-test
Stop system test on a device.
"""
args = shlex.split(line)
if (len(args) != 0):
print("Usage:")
self.do_help('stop-system-test')
return
try:
self.devMgr.StopSystemTest()
except WeaveStack.WeaveStackException as ex:
print(str(ex))
return
print("Stop system test complete") | [
"def",
"do_stopsystemtest",
"(",
"self",
",",
"line",
")",
":",
"args",
"=",
"shlex",
".",
"split",
"(",
"line",
")",
"if",
"(",
"len",
"(",
"args",
")",
"!=",
"0",
")",
":",
"print",
"(",
"\"Usage:\"",
")",
"self",
".",
"do_help",
"(",
"'stop-system-test'",
")",
"return",
"try",
":",
"self",
".",
"devMgr",
".",
"StopSystemTest",
"(",
")",
"except",
"WeaveStack",
".",
"WeaveStackException",
"as",
"ex",
":",
"print",
"(",
"str",
"(",
"ex",
")",
")",
"return",
"print",
"(",
"\"Stop system test complete\"",
")"
] | https://github.com/openweave/openweave-core/blob/11ceb6b7efd39fe05de7f79229247a5774d56766/src/device-manager/python/weave-device-mgr.py#L2493-L2513 |
||
kamyu104/LeetCode-Solutions | 77605708a927ea3b85aee5a479db733938c7c211 | Python/avoid-flood-in-the-city.py | python | Solution.avoidFlood | (self, rains) | return result if not min_heap else [] | :type rains: List[int]
:rtype: List[int] | :type rains: List[int]
:rtype: List[int] | [
":",
"type",
"rains",
":",
"List",
"[",
"int",
"]",
":",
"rtype",
":",
"List",
"[",
"int",
"]"
] | def avoidFlood(self, rains):
"""
:type rains: List[int]
:rtype: List[int]
"""
lookup = collections.defaultdict(list)
i = len(rains)-1
for lake in reversed(rains):
lookup[lake].append(i)
i -= 1
result, min_heap = [], []
for i, lake in enumerate(rains):
if lake:
if len(lookup[lake]) >= 2:
lookup[lake].pop()
heapq.heappush(min_heap, lookup[lake][-1])
result.append(-1)
elif min_heap:
j = heapq.heappop(min_heap)
if j < i:
return []
result.append(rains[j])
else:
result.append(1)
return result if not min_heap else [] | [
"def",
"avoidFlood",
"(",
"self",
",",
"rains",
")",
":",
"lookup",
"=",
"collections",
".",
"defaultdict",
"(",
"list",
")",
"i",
"=",
"len",
"(",
"rains",
")",
"-",
"1",
"for",
"lake",
"in",
"reversed",
"(",
"rains",
")",
":",
"lookup",
"[",
"lake",
"]",
".",
"append",
"(",
"i",
")",
"i",
"-=",
"1",
"result",
",",
"min_heap",
"=",
"[",
"]",
",",
"[",
"]",
"for",
"i",
",",
"lake",
"in",
"enumerate",
"(",
"rains",
")",
":",
"if",
"lake",
":",
"if",
"len",
"(",
"lookup",
"[",
"lake",
"]",
")",
">=",
"2",
":",
"lookup",
"[",
"lake",
"]",
".",
"pop",
"(",
")",
"heapq",
".",
"heappush",
"(",
"min_heap",
",",
"lookup",
"[",
"lake",
"]",
"[",
"-",
"1",
"]",
")",
"result",
".",
"append",
"(",
"-",
"1",
")",
"elif",
"min_heap",
":",
"j",
"=",
"heapq",
".",
"heappop",
"(",
"min_heap",
")",
"if",
"j",
"<",
"i",
":",
"return",
"[",
"]",
"result",
".",
"append",
"(",
"rains",
"[",
"j",
"]",
")",
"else",
":",
"result",
".",
"append",
"(",
"1",
")",
"return",
"result",
"if",
"not",
"min_heap",
"else",
"[",
"]"
] | https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/avoid-flood-in-the-city.py#L9-L33 |
|
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/delayedresult.py | python | PreProcessChain.addSub | (self, callable, *args, **kwargs) | Add a sub-callable, ie a `callable(result, *args, **kwargs)`
that returns a transformed result to the previously added
sub-callable (or the handler given at construction, if this is
the first call to addSub). | Add a sub-callable, ie a `callable(result, *args, **kwargs)`
that returns a transformed result to the previously added
sub-callable (or the handler given at construction, if this is
the first call to addSub). | [
"Add",
"a",
"sub",
"-",
"callable",
"ie",
"a",
"callable",
"(",
"result",
"*",
"args",
"**",
"kwargs",
")",
"that",
"returns",
"a",
"transformed",
"result",
"to",
"the",
"previously",
"added",
"sub",
"-",
"callable",
"(",
"or",
"the",
"handler",
"given",
"at",
"construction",
"if",
"this",
"is",
"the",
"first",
"call",
"to",
"addSub",
")",
"."
] | def addSub(self, callable, *args, **kwargs):
"""Add a sub-callable, ie a `callable(result, *args, **kwargs)`
that returns a transformed result to the previously added
sub-callable (or the handler given at construction, if this is
the first call to addSub). """
self.__chain.append( Handler(callable, *args, **kwargs) ) | [
"def",
"addSub",
"(",
"self",
",",
"callable",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"__chain",
".",
"append",
"(",
"Handler",
"(",
"callable",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/delayedresult.py#L365-L370 |
||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/rnn/python/ops/rnn_cell.py | python | AttentionCellWrapper.__init__ | (self,
cell,
attn_length,
attn_size=None,
attn_vec_size=None,
input_size=None,
state_is_tuple=True,
reuse=None) | Create a cell with attention.
Args:
cell: an RNNCell, an attention is added to it.
attn_length: integer, the size of an attention window.
attn_size: integer, the size of an attention vector. Equal to
cell.output_size by default.
attn_vec_size: integer, the number of convolutional features calculated
on attention state and a size of the hidden layer built from
base cell state. Equal attn_size to by default.
input_size: integer, the size of a hidden linear layer,
built from inputs and attention. Derived from the input tensor
by default.
state_is_tuple: If True, accepted and returned states are n-tuples, where
`n = len(cells)`. By default (False), the states are all
concatenated along the column axis.
reuse: (optional) Python boolean describing whether to reuse variables
in an existing scope. If not `True`, and the existing scope already has
the given variables, an error is raised.
Raises:
TypeError: if cell is not an RNNCell.
ValueError: if cell returns a state tuple but the flag
`state_is_tuple` is `False` or if attn_length is zero or less. | Create a cell with attention. | [
"Create",
"a",
"cell",
"with",
"attention",
"."
] | def __init__(self,
cell,
attn_length,
attn_size=None,
attn_vec_size=None,
input_size=None,
state_is_tuple=True,
reuse=None):
"""Create a cell with attention.
Args:
cell: an RNNCell, an attention is added to it.
attn_length: integer, the size of an attention window.
attn_size: integer, the size of an attention vector. Equal to
cell.output_size by default.
attn_vec_size: integer, the number of convolutional features calculated
on attention state and a size of the hidden layer built from
base cell state. Equal attn_size to by default.
input_size: integer, the size of a hidden linear layer,
built from inputs and attention. Derived from the input tensor
by default.
state_is_tuple: If True, accepted and returned states are n-tuples, where
`n = len(cells)`. By default (False), the states are all
concatenated along the column axis.
reuse: (optional) Python boolean describing whether to reuse variables
in an existing scope. If not `True`, and the existing scope already has
the given variables, an error is raised.
Raises:
TypeError: if cell is not an RNNCell.
ValueError: if cell returns a state tuple but the flag
`state_is_tuple` is `False` or if attn_length is zero or less.
"""
super(AttentionCellWrapper, self).__init__(_reuse=reuse)
rnn_cell_impl.assert_like_rnncell("cell", cell)
if nest.is_sequence(cell.state_size) and not state_is_tuple:
raise ValueError(
"Cell returns tuple of states, but the flag "
"state_is_tuple is not set. State size is: %s" % str(cell.state_size))
if attn_length <= 0:
raise ValueError(
"attn_length should be greater than zero, got %s" % str(attn_length))
if not state_is_tuple:
logging.warn("%s: Using a concatenated state is slower and will soon be "
"deprecated. Use state_is_tuple=True.", self)
if attn_size is None:
attn_size = cell.output_size
if attn_vec_size is None:
attn_vec_size = attn_size
self._state_is_tuple = state_is_tuple
self._cell = cell
self._attn_vec_size = attn_vec_size
self._input_size = input_size
self._attn_size = attn_size
self._attn_length = attn_length
self._reuse = reuse
self._linear1 = None
self._linear2 = None
self._linear3 = None | [
"def",
"__init__",
"(",
"self",
",",
"cell",
",",
"attn_length",
",",
"attn_size",
"=",
"None",
",",
"attn_vec_size",
"=",
"None",
",",
"input_size",
"=",
"None",
",",
"state_is_tuple",
"=",
"True",
",",
"reuse",
"=",
"None",
")",
":",
"super",
"(",
"AttentionCellWrapper",
",",
"self",
")",
".",
"__init__",
"(",
"_reuse",
"=",
"reuse",
")",
"rnn_cell_impl",
".",
"assert_like_rnncell",
"(",
"\"cell\"",
",",
"cell",
")",
"if",
"nest",
".",
"is_sequence",
"(",
"cell",
".",
"state_size",
")",
"and",
"not",
"state_is_tuple",
":",
"raise",
"ValueError",
"(",
"\"Cell returns tuple of states, but the flag \"",
"\"state_is_tuple is not set. State size is: %s\"",
"%",
"str",
"(",
"cell",
".",
"state_size",
")",
")",
"if",
"attn_length",
"<=",
"0",
":",
"raise",
"ValueError",
"(",
"\"attn_length should be greater than zero, got %s\"",
"%",
"str",
"(",
"attn_length",
")",
")",
"if",
"not",
"state_is_tuple",
":",
"logging",
".",
"warn",
"(",
"\"%s: Using a concatenated state is slower and will soon be \"",
"\"deprecated. Use state_is_tuple=True.\"",
",",
"self",
")",
"if",
"attn_size",
"is",
"None",
":",
"attn_size",
"=",
"cell",
".",
"output_size",
"if",
"attn_vec_size",
"is",
"None",
":",
"attn_vec_size",
"=",
"attn_size",
"self",
".",
"_state_is_tuple",
"=",
"state_is_tuple",
"self",
".",
"_cell",
"=",
"cell",
"self",
".",
"_attn_vec_size",
"=",
"attn_vec_size",
"self",
".",
"_input_size",
"=",
"input_size",
"self",
".",
"_attn_size",
"=",
"attn_size",
"self",
".",
"_attn_length",
"=",
"attn_length",
"self",
".",
"_reuse",
"=",
"reuse",
"self",
".",
"_linear1",
"=",
"None",
"self",
".",
"_linear2",
"=",
"None",
"self",
".",
"_linear3",
"=",
"None"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/rnn/python/ops/rnn_cell.py#L1121-L1179 |
||
panda3d/panda3d | 833ad89ebad58395d0af0b7ec08538e5e4308265 | direct/src/distributed/ClientRepositoryBase.py | python | ClientRepositoryBase.getObjectsOfClass | (self, objClass) | return doDict | returns dict of doId:object, containing all objects
that inherit from 'class'. returned dict is safely mutable. | returns dict of doId:object, containing all objects
that inherit from 'class'. returned dict is safely mutable. | [
"returns",
"dict",
"of",
"doId",
":",
"object",
"containing",
"all",
"objects",
"that",
"inherit",
"from",
"class",
".",
"returned",
"dict",
"is",
"safely",
"mutable",
"."
] | def getObjectsOfClass(self, objClass):
""" returns dict of doId:object, containing all objects
that inherit from 'class'. returned dict is safely mutable. """
doDict = {}
for doId, do in self.doId2do.items():
if isinstance(do, objClass):
doDict[doId] = do
return doDict | [
"def",
"getObjectsOfClass",
"(",
"self",
",",
"objClass",
")",
":",
"doDict",
"=",
"{",
"}",
"for",
"doId",
",",
"do",
"in",
"self",
".",
"doId2do",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"do",
",",
"objClass",
")",
":",
"doDict",
"[",
"doId",
"]",
"=",
"do",
"return",
"doDict"
] | https://github.com/panda3d/panda3d/blob/833ad89ebad58395d0af0b7ec08538e5e4308265/direct/src/distributed/ClientRepositoryBase.py#L516-L523 |
|
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_misc.py | python | CustomDataObject.GetData | (*args, **kwargs) | return _misc_.CustomDataObject_GetData(*args, **kwargs) | GetData(self) -> String
Returns the data bytes from the data object as a string. | GetData(self) -> String | [
"GetData",
"(",
"self",
")",
"-",
">",
"String"
] | def GetData(*args, **kwargs):
"""
GetData(self) -> String
Returns the data bytes from the data object as a string.
"""
return _misc_.CustomDataObject_GetData(*args, **kwargs) | [
"def",
"GetData",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"CustomDataObject_GetData",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_misc.py#L5398-L5404 |
|
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/numpy/py3/numpy/lib/scimath.py | python | _fix_int_lt_zero | (x) | return x | Convert `x` to double if it has real, negative components.
Otherwise, output is just the array version of the input (via asarray).
Parameters
----------
x : array_like
Returns
-------
array
Examples
--------
>>> np.lib.scimath._fix_int_lt_zero([1,2])
array([1, 2])
>>> np.lib.scimath._fix_int_lt_zero([-1,2])
array([-1., 2.]) | Convert `x` to double if it has real, negative components. | [
"Convert",
"x",
"to",
"double",
"if",
"it",
"has",
"real",
"negative",
"components",
"."
] | def _fix_int_lt_zero(x):
"""Convert `x` to double if it has real, negative components.
Otherwise, output is just the array version of the input (via asarray).
Parameters
----------
x : array_like
Returns
-------
array
Examples
--------
>>> np.lib.scimath._fix_int_lt_zero([1,2])
array([1, 2])
>>> np.lib.scimath._fix_int_lt_zero([-1,2])
array([-1., 2.])
"""
x = asarray(x)
if any(isreal(x) & (x < 0)):
x = x * 1.0
return x | [
"def",
"_fix_int_lt_zero",
"(",
"x",
")",
":",
"x",
"=",
"asarray",
"(",
"x",
")",
"if",
"any",
"(",
"isreal",
"(",
"x",
")",
"&",
"(",
"x",
"<",
"0",
")",
")",
":",
"x",
"=",
"x",
"*",
"1.0",
"return",
"x"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py3/numpy/lib/scimath.py#L141-L165 |
|
google/zetasql | c2240edf7f20df40c1c810b520b5a3aab9626a97 | zetasql/resolved_ast/gen_resolved_ast.py | python | Field | (name,
ctype,
tag_id,
vector=False,
ignorable=NOT_IGNORABLE,
is_constructor_arg=True,
is_optional_constructor_arg=False,
to_string_method=None,
java_to_string_method=None,
comment=None,
propagate_order=False) | return {
'ctype': ctype,
'java_type': java_type,
'full_java_type': full_java_type,
'nullable_java_type': nullable_java_type,
'java_default': java_default,
'cpp_default': cpp_default,
'tag_id': tag_id,
'member_name': member_name, # member variable name
'name': name, # name without trailing underscore
'comment': CleanIndent(comment, prefix=' // '),
'javadoc': JavaDoc(comment, indent=4),
'member_accessor': member_accessor,
'member_type': member_type,
'proto_type': proto_type,
'optional_or_repeated': optional_or_repeated,
'has_proto_setter': has_proto_setter,
'setter_arg_type': setter_arg_type,
'maybe_ptr_setter_arg_type': maybe_ptr_setter_arg_type,
'scoped_setter_arg_type': scoped_setter_arg_type,
'getter_return_type': getter_return_type,
'release_return_type': release_return_type,
'is_vector': vector,
'element_getter_return_type': element_getter_return_type,
'element_arg_type': element_arg_type,
'element_storage_type': element_storage_type,
'element_unwrapper': element_unwrapper,
'is_node_ptr': is_node_type and not vector,
'is_node_vector': is_node_type and vector,
'is_enum_vector': is_enum and vector,
'is_move_only': is_move_only,
'is_not_ignorable': ignorable == NOT_IGNORABLE,
'is_ignorable_default': ignorable == IGNORABLE_DEFAULT,
'is_constructor_arg': is_constructor_arg,
'is_optional_constructor_arg': is_optional_constructor_arg,
'to_string_method': to_string_method,
'java_to_string_method': java_to_string_method,
'propagate_order': propagate_order,
'not_serialize_if_default': not_serialize_if_default
} | Make a field to put in a node class.
Args:
name: field name
ctype: c++ type for this field
Should be a ScalarType like an int, string or enum type,
or the name of a node class type (e.g. ResolvedProjectScan).
Cannot be a pointer type, and should not include modifiers like
const.
tag_id: unique tag number for the proto field. This should never change or
be reused.
vector: True if this field is a vector of ctype. (Not supported for
scalars.)
ignorable: one of the IGNORABLE enums above.
is_constructor_arg: True if this field should be in the constructor's
argument list.
is_optional_constructor_arg: True if node class should have two
constructors, and this field should be present
in one of them and absent in another. Requires:
is_constructor_arg=True.
to_string_method: Override the default ToStringImpl method used to print
this object.
java_to_string_method: Override the default to_string_method method used for
java.
comment: Comment text for this field. Text will be stripped and
de-indented.
propagate_order: If true, this field and the parent node must both be
ResolvedScan subclasses, and the is_ordered property of
the field will be propagated to the containing scan.
Returns:
The newly created field.
Raises:
RuntimeError: If an error is detected in one or more arguments. | Make a field to put in a node class. | [
"Make",
"a",
"field",
"to",
"put",
"in",
"a",
"node",
"class",
"."
] | def Field(name,
ctype,
tag_id,
vector=False,
ignorable=NOT_IGNORABLE,
is_constructor_arg=True,
is_optional_constructor_arg=False,
to_string_method=None,
java_to_string_method=None,
comment=None,
propagate_order=False):
"""Make a field to put in a node class.
Args:
name: field name
ctype: c++ type for this field
Should be a ScalarType like an int, string or enum type,
or the name of a node class type (e.g. ResolvedProjectScan).
Cannot be a pointer type, and should not include modifiers like
const.
tag_id: unique tag number for the proto field. This should never change or
be reused.
vector: True if this field is a vector of ctype. (Not supported for
scalars.)
ignorable: one of the IGNORABLE enums above.
is_constructor_arg: True if this field should be in the constructor's
argument list.
is_optional_constructor_arg: True if node class should have two
constructors, and this field should be present
in one of them and absent in another. Requires:
is_constructor_arg=True.
to_string_method: Override the default ToStringImpl method used to print
this object.
java_to_string_method: Override the default to_string_method method used for
java.
comment: Comment text for this field. Text will be stripped and
de-indented.
propagate_order: If true, this field and the parent node must both be
ResolvedScan subclasses, and the is_ordered property of
the field will be propagated to the containing scan.
Returns:
The newly created field.
Raises:
RuntimeError: If an error is detected in one or more arguments.
"""
assert tag_id > 1, tag_id
assert ignorable in (IGNORABLE, NOT_IGNORABLE, IGNORABLE_DEFAULT)
member_name = name + '_'
if vector:
assert name.endswith('_list') or name.endswith('_path'), (
'Vector fields should normally be named <x>_list or <x>_path: %s' %
name)
# C++ code requires a large number of variations of the same type declaration.
# These are:
# member_type - type of the class member
# member_accessor - get the member variable, unwrapping unique_ptr if needed
# setter_arg_type - type when passed to constructor or setter method.
# maybe_ptr_setter_arg_type - type when passed to constructor or setter
# method as a bare pointer which transfers
# ownership.
# getter_return_type - type returned from a getter method
# release_return_type - type returned from a release method, or None to
# indicate there should be no release() method.
# element_arg_type - for vectors, the element type for get/set methods
# element_storage_type - for vectors, the type inside the vector.
# element_getter_return_type - for vectors, the return type for get/set
# methods returning a specific element.
# element_unwrapper - '.get()', if necessary, to unwrap unique_ptrs.
# is_move_only - setters must use std::move instead of assign/copy as
# for anything wrapped in a unique_ptr/vector<unique_ptr>.
if isinstance(ctype, ScalarType):
is_node_type = False
member_type = ctype.ctype
proto_type = ctype.proto_type
has_proto_setter = ctype.has_proto_setter
java_default = ctype.java_default
cpp_default = ctype.cpp_default
nullable_java_type = ctype.java_reference_type
member_accessor = member_name
element_arg_type = None
element_storage_type = None
element_getter_return_type = None
element_unwrapper = ''
release_return_type = None
is_enum = ctype.is_enum
is_move_only = False
not_serialize_if_default = ctype.not_serialize_if_default
if ctype.passed_by_reference:
setter_arg_type = 'const %s&' % member_type
getter_return_type = 'const %s&' % member_type
else:
setter_arg_type = member_type
getter_return_type = ctype.ctype
if vector:
element_arg_type = ctype.ctype
element_getter_return_type = getter_return_type
element_storage_type = ctype.ctype
member_type = 'std::vector<%s>' % ctype.ctype
setter_arg_type = 'const %s&' % member_type
getter_return_type = setter_arg_type
java_type = ctype.java_reference_type
java_default = 'ImmutableList.of()'
else:
java_type = ctype.java_type
java_default = ctype.java_default
# For scalars, these are always the same
maybe_ptr_setter_arg_type = setter_arg_type
else:
# Non-scalars should all be node types (possibly node vectors).
assert 'const' not in ctype, ctype
assert '*' not in ctype, ctype
if not ctype.startswith(NODE_NAME_PREFIX):
raise RuntimeError('Invalid field type: %s' % (ctype,))
is_node_type = True
has_proto_setter = False
element_pointer_type = 'const %s*' % ctype
element_storage_type = 'std::unique_ptr<const %s>' % ctype
element_unwrapper = '.get()'
proto_type = '%sProto' % ctype
java_type = ctype
nullable_java_type = ctype
is_enum = False
is_move_only = True
not_serialize_if_default = False
cpp_default = ''
if vector:
element_arg_type = element_pointer_type
element_getter_return_type = element_pointer_type
member_type = 'std::vector<%s>' % element_storage_type
maybe_ptr_setter_arg_type = (
'const std::vector<%s>&' % element_pointer_type)
getter_return_type = 'const %s&' % member_type
release_return_type = 'std::vector<%s>' % element_pointer_type
member_accessor = member_name
java_default = 'ImmutableList.of()'
else:
member_type = element_storage_type
maybe_ptr_setter_arg_type = element_pointer_type
getter_return_type = element_pointer_type
release_return_type = element_pointer_type
element_arg_type = None
element_storage_type = None
element_getter_return_type = None
member_accessor = member_name + '.get()'
if is_constructor_arg and not is_optional_constructor_arg:
java_default = None
else:
java_default = 'null'
# For node vector, we use std::move, which requires setters = member.
setter_arg_type = member_type
if vector:
optional_or_repeated = 'repeated'
full_java_type = 'ImmutableList<%s>' % java_type
nullable_java_type = full_java_type
else:
optional_or_repeated = 'optional'
full_java_type = java_type
if not to_string_method:
to_string_method = 'ToStringImpl'
if not java_to_string_method:
java_to_string_method = to_string_method[0].lower() + to_string_method[1:]
if is_enum:
scoped_setter_arg_type = ctype.scoped_ctype
else:
scoped_setter_arg_type = setter_arg_type
if not is_constructor_arg:
if java_default is None:
raise RuntimeError(
'Field %s must either be a constructor arg, or have a java_default. ctype:\n%s'
% (
name,
ctype,
))
if is_optional_constructor_arg:
raise RuntimeError(
'Field %s must be a constructor arg if it has is_optional_constructor_arg=True'
% (name,))
return {
'ctype': ctype,
'java_type': java_type,
'full_java_type': full_java_type,
'nullable_java_type': nullable_java_type,
'java_default': java_default,
'cpp_default': cpp_default,
'tag_id': tag_id,
'member_name': member_name, # member variable name
'name': name, # name without trailing underscore
'comment': CleanIndent(comment, prefix=' // '),
'javadoc': JavaDoc(comment, indent=4),
'member_accessor': member_accessor,
'member_type': member_type,
'proto_type': proto_type,
'optional_or_repeated': optional_or_repeated,
'has_proto_setter': has_proto_setter,
'setter_arg_type': setter_arg_type,
'maybe_ptr_setter_arg_type': maybe_ptr_setter_arg_type,
'scoped_setter_arg_type': scoped_setter_arg_type,
'getter_return_type': getter_return_type,
'release_return_type': release_return_type,
'is_vector': vector,
'element_getter_return_type': element_getter_return_type,
'element_arg_type': element_arg_type,
'element_storage_type': element_storage_type,
'element_unwrapper': element_unwrapper,
'is_node_ptr': is_node_type and not vector,
'is_node_vector': is_node_type and vector,
'is_enum_vector': is_enum and vector,
'is_move_only': is_move_only,
'is_not_ignorable': ignorable == NOT_IGNORABLE,
'is_ignorable_default': ignorable == IGNORABLE_DEFAULT,
'is_constructor_arg': is_constructor_arg,
'is_optional_constructor_arg': is_optional_constructor_arg,
'to_string_method': to_string_method,
'java_to_string_method': java_to_string_method,
'propagate_order': propagate_order,
'not_serialize_if_default': not_serialize_if_default
} | [
"def",
"Field",
"(",
"name",
",",
"ctype",
",",
"tag_id",
",",
"vector",
"=",
"False",
",",
"ignorable",
"=",
"NOT_IGNORABLE",
",",
"is_constructor_arg",
"=",
"True",
",",
"is_optional_constructor_arg",
"=",
"False",
",",
"to_string_method",
"=",
"None",
",",
"java_to_string_method",
"=",
"None",
",",
"comment",
"=",
"None",
",",
"propagate_order",
"=",
"False",
")",
":",
"assert",
"tag_id",
">",
"1",
",",
"tag_id",
"assert",
"ignorable",
"in",
"(",
"IGNORABLE",
",",
"NOT_IGNORABLE",
",",
"IGNORABLE_DEFAULT",
")",
"member_name",
"=",
"name",
"+",
"'_'",
"if",
"vector",
":",
"assert",
"name",
".",
"endswith",
"(",
"'_list'",
")",
"or",
"name",
".",
"endswith",
"(",
"'_path'",
")",
",",
"(",
"'Vector fields should normally be named <x>_list or <x>_path: %s'",
"%",
"name",
")",
"# C++ code requires a large number of variations of the same type declaration.",
"# These are:",
"# member_type - type of the class member",
"# member_accessor - get the member variable, unwrapping unique_ptr if needed",
"# setter_arg_type - type when passed to constructor or setter method.",
"# maybe_ptr_setter_arg_type - type when passed to constructor or setter",
"# method as a bare pointer which transfers",
"# ownership.",
"# getter_return_type - type returned from a getter method",
"# release_return_type - type returned from a release method, or None to",
"# indicate there should be no release() method.",
"# element_arg_type - for vectors, the element type for get/set methods",
"# element_storage_type - for vectors, the type inside the vector.",
"# element_getter_return_type - for vectors, the return type for get/set",
"# methods returning a specific element.",
"# element_unwrapper - '.get()', if necessary, to unwrap unique_ptrs.",
"# is_move_only - setters must use std::move instead of assign/copy as",
"# for anything wrapped in a unique_ptr/vector<unique_ptr>.",
"if",
"isinstance",
"(",
"ctype",
",",
"ScalarType",
")",
":",
"is_node_type",
"=",
"False",
"member_type",
"=",
"ctype",
".",
"ctype",
"proto_type",
"=",
"ctype",
".",
"proto_type",
"has_proto_setter",
"=",
"ctype",
".",
"has_proto_setter",
"java_default",
"=",
"ctype",
".",
"java_default",
"cpp_default",
"=",
"ctype",
".",
"cpp_default",
"nullable_java_type",
"=",
"ctype",
".",
"java_reference_type",
"member_accessor",
"=",
"member_name",
"element_arg_type",
"=",
"None",
"element_storage_type",
"=",
"None",
"element_getter_return_type",
"=",
"None",
"element_unwrapper",
"=",
"''",
"release_return_type",
"=",
"None",
"is_enum",
"=",
"ctype",
".",
"is_enum",
"is_move_only",
"=",
"False",
"not_serialize_if_default",
"=",
"ctype",
".",
"not_serialize_if_default",
"if",
"ctype",
".",
"passed_by_reference",
":",
"setter_arg_type",
"=",
"'const %s&'",
"%",
"member_type",
"getter_return_type",
"=",
"'const %s&'",
"%",
"member_type",
"else",
":",
"setter_arg_type",
"=",
"member_type",
"getter_return_type",
"=",
"ctype",
".",
"ctype",
"if",
"vector",
":",
"element_arg_type",
"=",
"ctype",
".",
"ctype",
"element_getter_return_type",
"=",
"getter_return_type",
"element_storage_type",
"=",
"ctype",
".",
"ctype",
"member_type",
"=",
"'std::vector<%s>'",
"%",
"ctype",
".",
"ctype",
"setter_arg_type",
"=",
"'const %s&'",
"%",
"member_type",
"getter_return_type",
"=",
"setter_arg_type",
"java_type",
"=",
"ctype",
".",
"java_reference_type",
"java_default",
"=",
"'ImmutableList.of()'",
"else",
":",
"java_type",
"=",
"ctype",
".",
"java_type",
"java_default",
"=",
"ctype",
".",
"java_default",
"# For scalars, these are always the same",
"maybe_ptr_setter_arg_type",
"=",
"setter_arg_type",
"else",
":",
"# Non-scalars should all be node types (possibly node vectors).",
"assert",
"'const'",
"not",
"in",
"ctype",
",",
"ctype",
"assert",
"'*'",
"not",
"in",
"ctype",
",",
"ctype",
"if",
"not",
"ctype",
".",
"startswith",
"(",
"NODE_NAME_PREFIX",
")",
":",
"raise",
"RuntimeError",
"(",
"'Invalid field type: %s'",
"%",
"(",
"ctype",
",",
")",
")",
"is_node_type",
"=",
"True",
"has_proto_setter",
"=",
"False",
"element_pointer_type",
"=",
"'const %s*'",
"%",
"ctype",
"element_storage_type",
"=",
"'std::unique_ptr<const %s>'",
"%",
"ctype",
"element_unwrapper",
"=",
"'.get()'",
"proto_type",
"=",
"'%sProto'",
"%",
"ctype",
"java_type",
"=",
"ctype",
"nullable_java_type",
"=",
"ctype",
"is_enum",
"=",
"False",
"is_move_only",
"=",
"True",
"not_serialize_if_default",
"=",
"False",
"cpp_default",
"=",
"''",
"if",
"vector",
":",
"element_arg_type",
"=",
"element_pointer_type",
"element_getter_return_type",
"=",
"element_pointer_type",
"member_type",
"=",
"'std::vector<%s>'",
"%",
"element_storage_type",
"maybe_ptr_setter_arg_type",
"=",
"(",
"'const std::vector<%s>&'",
"%",
"element_pointer_type",
")",
"getter_return_type",
"=",
"'const %s&'",
"%",
"member_type",
"release_return_type",
"=",
"'std::vector<%s>'",
"%",
"element_pointer_type",
"member_accessor",
"=",
"member_name",
"java_default",
"=",
"'ImmutableList.of()'",
"else",
":",
"member_type",
"=",
"element_storage_type",
"maybe_ptr_setter_arg_type",
"=",
"element_pointer_type",
"getter_return_type",
"=",
"element_pointer_type",
"release_return_type",
"=",
"element_pointer_type",
"element_arg_type",
"=",
"None",
"element_storage_type",
"=",
"None",
"element_getter_return_type",
"=",
"None",
"member_accessor",
"=",
"member_name",
"+",
"'.get()'",
"if",
"is_constructor_arg",
"and",
"not",
"is_optional_constructor_arg",
":",
"java_default",
"=",
"None",
"else",
":",
"java_default",
"=",
"'null'",
"# For node vector, we use std::move, which requires setters = member.",
"setter_arg_type",
"=",
"member_type",
"if",
"vector",
":",
"optional_or_repeated",
"=",
"'repeated'",
"full_java_type",
"=",
"'ImmutableList<%s>'",
"%",
"java_type",
"nullable_java_type",
"=",
"full_java_type",
"else",
":",
"optional_or_repeated",
"=",
"'optional'",
"full_java_type",
"=",
"java_type",
"if",
"not",
"to_string_method",
":",
"to_string_method",
"=",
"'ToStringImpl'",
"if",
"not",
"java_to_string_method",
":",
"java_to_string_method",
"=",
"to_string_method",
"[",
"0",
"]",
".",
"lower",
"(",
")",
"+",
"to_string_method",
"[",
"1",
":",
"]",
"if",
"is_enum",
":",
"scoped_setter_arg_type",
"=",
"ctype",
".",
"scoped_ctype",
"else",
":",
"scoped_setter_arg_type",
"=",
"setter_arg_type",
"if",
"not",
"is_constructor_arg",
":",
"if",
"java_default",
"is",
"None",
":",
"raise",
"RuntimeError",
"(",
"'Field %s must either be a constructor arg, or have a java_default. ctype:\\n%s'",
"%",
"(",
"name",
",",
"ctype",
",",
")",
")",
"if",
"is_optional_constructor_arg",
":",
"raise",
"RuntimeError",
"(",
"'Field %s must be a constructor arg if it has is_optional_constructor_arg=True'",
"%",
"(",
"name",
",",
")",
")",
"return",
"{",
"'ctype'",
":",
"ctype",
",",
"'java_type'",
":",
"java_type",
",",
"'full_java_type'",
":",
"full_java_type",
",",
"'nullable_java_type'",
":",
"nullable_java_type",
",",
"'java_default'",
":",
"java_default",
",",
"'cpp_default'",
":",
"cpp_default",
",",
"'tag_id'",
":",
"tag_id",
",",
"'member_name'",
":",
"member_name",
",",
"# member variable name",
"'name'",
":",
"name",
",",
"# name without trailing underscore",
"'comment'",
":",
"CleanIndent",
"(",
"comment",
",",
"prefix",
"=",
"' // '",
")",
",",
"'javadoc'",
":",
"JavaDoc",
"(",
"comment",
",",
"indent",
"=",
"4",
")",
",",
"'member_accessor'",
":",
"member_accessor",
",",
"'member_type'",
":",
"member_type",
",",
"'proto_type'",
":",
"proto_type",
",",
"'optional_or_repeated'",
":",
"optional_or_repeated",
",",
"'has_proto_setter'",
":",
"has_proto_setter",
",",
"'setter_arg_type'",
":",
"setter_arg_type",
",",
"'maybe_ptr_setter_arg_type'",
":",
"maybe_ptr_setter_arg_type",
",",
"'scoped_setter_arg_type'",
":",
"scoped_setter_arg_type",
",",
"'getter_return_type'",
":",
"getter_return_type",
",",
"'release_return_type'",
":",
"release_return_type",
",",
"'is_vector'",
":",
"vector",
",",
"'element_getter_return_type'",
":",
"element_getter_return_type",
",",
"'element_arg_type'",
":",
"element_arg_type",
",",
"'element_storage_type'",
":",
"element_storage_type",
",",
"'element_unwrapper'",
":",
"element_unwrapper",
",",
"'is_node_ptr'",
":",
"is_node_type",
"and",
"not",
"vector",
",",
"'is_node_vector'",
":",
"is_node_type",
"and",
"vector",
",",
"'is_enum_vector'",
":",
"is_enum",
"and",
"vector",
",",
"'is_move_only'",
":",
"is_move_only",
",",
"'is_not_ignorable'",
":",
"ignorable",
"==",
"NOT_IGNORABLE",
",",
"'is_ignorable_default'",
":",
"ignorable",
"==",
"IGNORABLE_DEFAULT",
",",
"'is_constructor_arg'",
":",
"is_constructor_arg",
",",
"'is_optional_constructor_arg'",
":",
"is_optional_constructor_arg",
",",
"'to_string_method'",
":",
"to_string_method",
",",
"'java_to_string_method'",
":",
"java_to_string_method",
",",
"'propagate_order'",
":",
"propagate_order",
",",
"'not_serialize_if_default'",
":",
"not_serialize_if_default",
"}"
] | https://github.com/google/zetasql/blob/c2240edf7f20df40c1c810b520b5a3aab9626a97/zetasql/resolved_ast/gen_resolved_ast.py#L223-L452 |
|
macchina-io/macchina.io | ef24ba0e18379c3dd48fb84e6dbf991101cb8db0 | platform/JS/V8/v8/third_party/jinja2/environment.py | python | Environment.compile_expression | (self, source, undefined_to_none=True) | return TemplateExpression(template, undefined_to_none) | A handy helper method that returns a callable that accepts keyword
arguments that appear as variables in the expression. If called it
returns the result of the expression.
This is useful if applications want to use the same rules as Jinja
in template "configuration files" or similar situations.
Example usage:
>>> env = Environment()
>>> expr = env.compile_expression('foo == 42')
>>> expr(foo=23)
False
>>> expr(foo=42)
True
Per default the return value is converted to `None` if the
expression returns an undefined value. This can be changed
by setting `undefined_to_none` to `False`.
>>> env.compile_expression('var')() is None
True
>>> env.compile_expression('var', undefined_to_none=False)()
Undefined
.. versionadded:: 2.1 | A handy helper method that returns a callable that accepts keyword
arguments that appear as variables in the expression. If called it
returns the result of the expression. | [
"A",
"handy",
"helper",
"method",
"that",
"returns",
"a",
"callable",
"that",
"accepts",
"keyword",
"arguments",
"that",
"appear",
"as",
"variables",
"in",
"the",
"expression",
".",
"If",
"called",
"it",
"returns",
"the",
"result",
"of",
"the",
"expression",
"."
] | def compile_expression(self, source, undefined_to_none=True):
"""A handy helper method that returns a callable that accepts keyword
arguments that appear as variables in the expression. If called it
returns the result of the expression.
This is useful if applications want to use the same rules as Jinja
in template "configuration files" or similar situations.
Example usage:
>>> env = Environment()
>>> expr = env.compile_expression('foo == 42')
>>> expr(foo=23)
False
>>> expr(foo=42)
True
Per default the return value is converted to `None` if the
expression returns an undefined value. This can be changed
by setting `undefined_to_none` to `False`.
>>> env.compile_expression('var')() is None
True
>>> env.compile_expression('var', undefined_to_none=False)()
Undefined
.. versionadded:: 2.1
"""
parser = Parser(self, source, state='variable')
exc_info = None
try:
expr = parser.parse_expression()
if not parser.stream.eos:
raise TemplateSyntaxError('chunk after expression',
parser.stream.current.lineno,
None, None)
expr.set_environment(self)
except TemplateSyntaxError:
exc_info = sys.exc_info()
if exc_info is not None:
self.handle_exception(exc_info, source_hint=source)
body = [nodes.Assign(nodes.Name('result', 'store'), expr, lineno=1)]
template = self.from_string(nodes.Template(body, lineno=1))
return TemplateExpression(template, undefined_to_none) | [
"def",
"compile_expression",
"(",
"self",
",",
"source",
",",
"undefined_to_none",
"=",
"True",
")",
":",
"parser",
"=",
"Parser",
"(",
"self",
",",
"source",
",",
"state",
"=",
"'variable'",
")",
"exc_info",
"=",
"None",
"try",
":",
"expr",
"=",
"parser",
".",
"parse_expression",
"(",
")",
"if",
"not",
"parser",
".",
"stream",
".",
"eos",
":",
"raise",
"TemplateSyntaxError",
"(",
"'chunk after expression'",
",",
"parser",
".",
"stream",
".",
"current",
".",
"lineno",
",",
"None",
",",
"None",
")",
"expr",
".",
"set_environment",
"(",
"self",
")",
"except",
"TemplateSyntaxError",
":",
"exc_info",
"=",
"sys",
".",
"exc_info",
"(",
")",
"if",
"exc_info",
"is",
"not",
"None",
":",
"self",
".",
"handle_exception",
"(",
"exc_info",
",",
"source_hint",
"=",
"source",
")",
"body",
"=",
"[",
"nodes",
".",
"Assign",
"(",
"nodes",
".",
"Name",
"(",
"'result'",
",",
"'store'",
")",
",",
"expr",
",",
"lineno",
"=",
"1",
")",
"]",
"template",
"=",
"self",
".",
"from_string",
"(",
"nodes",
".",
"Template",
"(",
"body",
",",
"lineno",
"=",
"1",
")",
")",
"return",
"TemplateExpression",
"(",
"template",
",",
"undefined_to_none",
")"
] | https://github.com/macchina-io/macchina.io/blob/ef24ba0e18379c3dd48fb84e6dbf991101cb8db0/platform/JS/V8/v8/third_party/jinja2/environment.py#L567-L610 |
|
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/botocore/session.py | python | Session.__init__ | (self, session_vars=None, event_hooks=None,
include_builtin_handlers=True, profile=None) | Create a new Session object.
:type session_vars: dict
:param session_vars: A dictionary that is used to override some or all
of the environment variables associated with this session. The
key/value pairs defined in this dictionary will override the
corresponding variables defined in ``SESSION_VARIABLES``.
:type event_hooks: BaseEventHooks
:param event_hooks: The event hooks object to use. If one is not
provided, an event hooks object will be automatically created
for you.
:type include_builtin_handlers: bool
:param include_builtin_handlers: Indicates whether or not to
automatically register builtin handlers.
:type profile: str
:param profile: The name of the profile to use for this
session. Note that the profile can only be set when
the session is created. | Create a new Session object. | [
"Create",
"a",
"new",
"Session",
"object",
"."
] | def __init__(self, session_vars=None, event_hooks=None,
include_builtin_handlers=True, profile=None):
"""
Create a new Session object.
:type session_vars: dict
:param session_vars: A dictionary that is used to override some or all
of the environment variables associated with this session. The
key/value pairs defined in this dictionary will override the
corresponding variables defined in ``SESSION_VARIABLES``.
:type event_hooks: BaseEventHooks
:param event_hooks: The event hooks object to use. If one is not
provided, an event hooks object will be automatically created
for you.
:type include_builtin_handlers: bool
:param include_builtin_handlers: Indicates whether or not to
automatically register builtin handlers.
:type profile: str
:param profile: The name of the profile to use for this
session. Note that the profile can only be set when
the session is created.
"""
if event_hooks is None:
self._original_handler = HierarchicalEmitter()
else:
self._original_handler = event_hooks
self._events = EventAliaser(self._original_handler)
if include_builtin_handlers:
self._register_builtin_handlers(self._events)
self.user_agent_name = 'Botocore'
self.user_agent_version = __version__
self.user_agent_extra = ''
# The _profile attribute is just used to cache the value
# of the current profile to avoid going through the normal
# config lookup process each access time.
self._profile = None
self._config = None
self._credentials = None
self._profile_map = None
# This is a dict that stores per session specific config variable
# overrides via set_config_variable().
self._session_instance_vars = {}
if profile is not None:
self._session_instance_vars['profile'] = profile
self._client_config = None
self._last_client_region_used = None
self._components = ComponentLocator()
self._internal_components = ComponentLocator()
self._register_components()
self.session_var_map = SessionVarDict(self, self.SESSION_VARIABLES)
if session_vars is not None:
self.session_var_map.update(session_vars) | [
"def",
"__init__",
"(",
"self",
",",
"session_vars",
"=",
"None",
",",
"event_hooks",
"=",
"None",
",",
"include_builtin_handlers",
"=",
"True",
",",
"profile",
"=",
"None",
")",
":",
"if",
"event_hooks",
"is",
"None",
":",
"self",
".",
"_original_handler",
"=",
"HierarchicalEmitter",
"(",
")",
"else",
":",
"self",
".",
"_original_handler",
"=",
"event_hooks",
"self",
".",
"_events",
"=",
"EventAliaser",
"(",
"self",
".",
"_original_handler",
")",
"if",
"include_builtin_handlers",
":",
"self",
".",
"_register_builtin_handlers",
"(",
"self",
".",
"_events",
")",
"self",
".",
"user_agent_name",
"=",
"'Botocore'",
"self",
".",
"user_agent_version",
"=",
"__version__",
"self",
".",
"user_agent_extra",
"=",
"''",
"# The _profile attribute is just used to cache the value",
"# of the current profile to avoid going through the normal",
"# config lookup process each access time.",
"self",
".",
"_profile",
"=",
"None",
"self",
".",
"_config",
"=",
"None",
"self",
".",
"_credentials",
"=",
"None",
"self",
".",
"_profile_map",
"=",
"None",
"# This is a dict that stores per session specific config variable",
"# overrides via set_config_variable().",
"self",
".",
"_session_instance_vars",
"=",
"{",
"}",
"if",
"profile",
"is",
"not",
"None",
":",
"self",
".",
"_session_instance_vars",
"[",
"'profile'",
"]",
"=",
"profile",
"self",
".",
"_client_config",
"=",
"None",
"self",
".",
"_last_client_region_used",
"=",
"None",
"self",
".",
"_components",
"=",
"ComponentLocator",
"(",
")",
"self",
".",
"_internal_components",
"=",
"ComponentLocator",
"(",
")",
"self",
".",
"_register_components",
"(",
")",
"self",
".",
"session_var_map",
"=",
"SessionVarDict",
"(",
"self",
",",
"self",
".",
"SESSION_VARIABLES",
")",
"if",
"session_vars",
"is",
"not",
"None",
":",
"self",
".",
"session_var_map",
".",
"update",
"(",
"session_vars",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/botocore/session.py#L73-L128 |
||
TimoSaemann/caffe-segnet-cudnn5 | abcf30dca449245e101bf4ced519f716177f0885 | scripts/cpp_lint.py | python | ParseArguments | (args) | return filenames | Parses the command line arguments.
This may set the output format and verbosity level as side-effects.
Args:
args: The command line arguments:
Returns:
The list of filenames to lint. | Parses the command line arguments. | [
"Parses",
"the",
"command",
"line",
"arguments",
"."
] | def ParseArguments(args):
"""Parses the command line arguments.
This may set the output format and verbosity level as side-effects.
Args:
args: The command line arguments:
Returns:
The list of filenames to lint.
"""
try:
(opts, filenames) = getopt.getopt(args, '', ['help', 'output=', 'verbose=',
'counting=',
'filter=',
'root=',
'linelength=',
'extensions='])
except getopt.GetoptError:
PrintUsage('Invalid arguments.')
verbosity = _VerboseLevel()
output_format = _OutputFormat()
filters = ''
counting_style = ''
for (opt, val) in opts:
if opt == '--help':
PrintUsage(None)
elif opt == '--output':
if val not in ('emacs', 'vs7', 'eclipse'):
PrintUsage('The only allowed output formats are emacs, vs7 and eclipse.')
output_format = val
elif opt == '--verbose':
verbosity = int(val)
elif opt == '--filter':
filters = val
if not filters:
PrintCategories()
elif opt == '--counting':
if val not in ('total', 'toplevel', 'detailed'):
PrintUsage('Valid counting options are total, toplevel, and detailed')
counting_style = val
elif opt == '--root':
global _root
_root = val
elif opt == '--linelength':
global _line_length
try:
_line_length = int(val)
except ValueError:
PrintUsage('Line length must be digits.')
elif opt == '--extensions':
global _valid_extensions
try:
_valid_extensions = set(val.split(','))
except ValueError:
PrintUsage('Extensions must be comma separated list.')
if not filenames:
PrintUsage('No files were specified.')
_SetOutputFormat(output_format)
_SetVerboseLevel(verbosity)
_SetFilters(filters)
_SetCountingStyle(counting_style)
return filenames | [
"def",
"ParseArguments",
"(",
"args",
")",
":",
"try",
":",
"(",
"opts",
",",
"filenames",
")",
"=",
"getopt",
".",
"getopt",
"(",
"args",
",",
"''",
",",
"[",
"'help'",
",",
"'output='",
",",
"'verbose='",
",",
"'counting='",
",",
"'filter='",
",",
"'root='",
",",
"'linelength='",
",",
"'extensions='",
"]",
")",
"except",
"getopt",
".",
"GetoptError",
":",
"PrintUsage",
"(",
"'Invalid arguments.'",
")",
"verbosity",
"=",
"_VerboseLevel",
"(",
")",
"output_format",
"=",
"_OutputFormat",
"(",
")",
"filters",
"=",
"''",
"counting_style",
"=",
"''",
"for",
"(",
"opt",
",",
"val",
")",
"in",
"opts",
":",
"if",
"opt",
"==",
"'--help'",
":",
"PrintUsage",
"(",
"None",
")",
"elif",
"opt",
"==",
"'--output'",
":",
"if",
"val",
"not",
"in",
"(",
"'emacs'",
",",
"'vs7'",
",",
"'eclipse'",
")",
":",
"PrintUsage",
"(",
"'The only allowed output formats are emacs, vs7 and eclipse.'",
")",
"output_format",
"=",
"val",
"elif",
"opt",
"==",
"'--verbose'",
":",
"verbosity",
"=",
"int",
"(",
"val",
")",
"elif",
"opt",
"==",
"'--filter'",
":",
"filters",
"=",
"val",
"if",
"not",
"filters",
":",
"PrintCategories",
"(",
")",
"elif",
"opt",
"==",
"'--counting'",
":",
"if",
"val",
"not",
"in",
"(",
"'total'",
",",
"'toplevel'",
",",
"'detailed'",
")",
":",
"PrintUsage",
"(",
"'Valid counting options are total, toplevel, and detailed'",
")",
"counting_style",
"=",
"val",
"elif",
"opt",
"==",
"'--root'",
":",
"global",
"_root",
"_root",
"=",
"val",
"elif",
"opt",
"==",
"'--linelength'",
":",
"global",
"_line_length",
"try",
":",
"_line_length",
"=",
"int",
"(",
"val",
")",
"except",
"ValueError",
":",
"PrintUsage",
"(",
"'Line length must be digits.'",
")",
"elif",
"opt",
"==",
"'--extensions'",
":",
"global",
"_valid_extensions",
"try",
":",
"_valid_extensions",
"=",
"set",
"(",
"val",
".",
"split",
"(",
"','",
")",
")",
"except",
"ValueError",
":",
"PrintUsage",
"(",
"'Extensions must be comma separated list.'",
")",
"if",
"not",
"filenames",
":",
"PrintUsage",
"(",
"'No files were specified.'",
")",
"_SetOutputFormat",
"(",
"output_format",
")",
"_SetVerboseLevel",
"(",
"verbosity",
")",
"_SetFilters",
"(",
"filters",
")",
"_SetCountingStyle",
"(",
"counting_style",
")",
"return",
"filenames"
] | https://github.com/TimoSaemann/caffe-segnet-cudnn5/blob/abcf30dca449245e101bf4ced519f716177f0885/scripts/cpp_lint.py#L4779-L4846 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.