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
list
function
stringlengths
34
151k
function_tokens
list
url
stringlengths
90
278
CaoWGG/TensorRT-YOLOv4
4d7c2edce99e8794a4cb4ea3540d51ce91158a36
onnx-tensorrt/third_party/onnx/onnx/__init__.py
python
_serialize
(proto)
Serialize a in-memory proto to bytes @params proto is a in-memory proto, such as a ModelProto, TensorProto, etc @return Serialized proto in bytes
Serialize a in-memory proto to bytes
[ "Serialize", "a", "in", "-", "memory", "proto", "to", "bytes" ]
def _serialize(proto): # type: (Union[bytes, google.protobuf.message.Message]) -> bytes ''' Serialize a in-memory proto to bytes @params proto is a in-memory proto, such as a ModelProto, TensorProto, etc @return Serialized proto in bytes ''' if isinstance(proto, bytes): return proto elif hasattr(proto, 'SerializeToString') and callable(proto.SerializeToString): result = proto.SerializeToString() return result else: raise ValueError('No SerializeToString method is detected. ' 'neither proto is a str.\ntype is {}'.format(type(proto)))
[ "def", "_serialize", "(", "proto", ")", ":", "# type: (Union[bytes, google.protobuf.message.Message]) -> bytes", "if", "isinstance", "(", "proto", ",", "bytes", ")", ":", "return", "proto", "elif", "hasattr", "(", "proto", ",", "'SerializeToString'", ")", "and", "callable", "(", "proto", ".", "SerializeToString", ")", ":", "result", "=", "proto", ".", "SerializeToString", "(", ")", "return", "result", "else", ":", "raise", "ValueError", "(", "'No SerializeToString method is detected. '", "'neither proto is a str.\\ntype is {}'", ".", "format", "(", "type", "(", "proto", ")", ")", ")" ]
https://github.com/CaoWGG/TensorRT-YOLOv4/blob/4d7c2edce99e8794a4cb4ea3540d51ce91158a36/onnx-tensorrt/third_party/onnx/onnx/__init__.py#L40-L57
BSVino/DoubleAction
c550b168a3e919926c198c30240f506538b92e75
mp/src/thirdparty/protobuf-2.3.0/python/google/protobuf/internal/containers.py
python
BaseContainer.__getitem__
(self, key)
return self._values[key]
Retrieves item by the specified key.
Retrieves item by the specified key.
[ "Retrieves", "item", "by", "the", "specified", "key", "." ]
def __getitem__(self, key): """Retrieves item by the specified key.""" return self._values[key]
[ "def", "__getitem__", "(", "self", ",", "key", ")", ":", "return", "self", ".", "_values", "[", "key", "]" ]
https://github.com/BSVino/DoubleAction/blob/c550b168a3e919926c198c30240f506538b92e75/mp/src/thirdparty/protobuf-2.3.0/python/google/protobuf/internal/containers.py#L62-L64
plaidml/plaidml
f3c6681db21460e5fdc11ae651d6d7b6c27f8262
mlperf/pycoco.py
python
COCO.info
(self)
Print information about the annotation file. :return:
Print information about the annotation file. :return:
[ "Print", "information", "about", "the", "annotation", "file", ".", ":", "return", ":" ]
def info(self): """ Print information about the annotation file. :return: """ for key, value in self.dataset['info'].items(): print('{}: {}'.format(key, value))
[ "def", "info", "(", "self", ")", ":", "for", "key", ",", "value", "in", "self", ".", "dataset", "[", "'info'", "]", ".", "items", "(", ")", ":", "print", "(", "'{}: {}'", ".", "format", "(", "key", ",", "value", ")", ")" ]
https://github.com/plaidml/plaidml/blob/f3c6681db21460e5fdc11ae651d6d7b6c27f8262/mlperf/pycoco.py#L123-L129
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/targets/arrayobj.py
python
get_sort_func
(kind, is_float, is_argsort=False)
Get a sort implementation of the given kind.
Get a sort implementation of the given kind.
[ "Get", "a", "sort", "implementation", "of", "the", "given", "kind", "." ]
def get_sort_func(kind, is_float, is_argsort=False): """ Get a sort implementation of the given kind. """ key = kind, is_float, is_argsort try: return _sorts[key] except KeyError: if kind == 'quicksort': sort = quicksort.make_jit_quicksort( lt=lt_floats if is_float else None, is_argsort=is_argsort) func = sort.run_quicksort elif kind == 'mergesort': sort = mergesort.make_jit_mergesort( lt=lt_floats if is_float else None, is_argsort=is_argsort) func = sort.run_mergesort _sorts[key] = func return func
[ "def", "get_sort_func", "(", "kind", ",", "is_float", ",", "is_argsort", "=", "False", ")", ":", "key", "=", "kind", ",", "is_float", ",", "is_argsort", "try", ":", "return", "_sorts", "[", "key", "]", "except", "KeyError", ":", "if", "kind", "==", "'quicksort'", ":", "sort", "=", "quicksort", ".", "make_jit_quicksort", "(", "lt", "=", "lt_floats", "if", "is_float", "else", "None", ",", "is_argsort", "=", "is_argsort", ")", "func", "=", "sort", ".", "run_quicksort", "elif", "kind", "==", "'mergesort'", ":", "sort", "=", "mergesort", ".", "make_jit_mergesort", "(", "lt", "=", "lt_floats", "if", "is_float", "else", "None", ",", "is_argsort", "=", "is_argsort", ")", "func", "=", "sort", ".", "run_mergesort", "_sorts", "[", "key", "]", "=", "func", "return", "func" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/targets/arrayobj.py#L4894-L4913
Tencent/TNN
7acca99f54c55747b415a4c57677403eebc7b706
third_party/flatbuffers/python/flatbuffers/table.py
python
Table.Union
(self, t2, off)
Union initializes any Table-derived type to point to the union at the given offset.
Union initializes any Table-derived type to point to the union at the given offset.
[ "Union", "initializes", "any", "Table", "-", "derived", "type", "to", "point", "to", "the", "union", "at", "the", "given", "offset", "." ]
def Union(self, t2, off): """Union initializes any Table-derived type to point to the union at the given offset.""" assert type(t2) is Table N.enforce_number(off, N.UOffsetTFlags) off += self.Pos t2.Pos = off + self.Get(N.UOffsetTFlags, off) t2.Bytes = self.Bytes
[ "def", "Union", "(", "self", ",", "t2", ",", "off", ")", ":", "assert", "type", "(", "t2", ")", "is", "Table", "N", ".", "enforce_number", "(", "off", ",", "N", ".", "UOffsetTFlags", ")", "off", "+=", "self", ".", "Pos", "t2", ".", "Pos", "=", "off", "+", "self", ".", "Get", "(", "N", ".", "UOffsetTFlags", ",", "off", ")", "t2", ".", "Bytes", "=", "self", ".", "Bytes" ]
https://github.com/Tencent/TNN/blob/7acca99f54c55747b415a4c57677403eebc7b706/third_party/flatbuffers/python/flatbuffers/table.py#L77-L85
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/stat.py
python
S_ISWHT
(mode)
return False
Return True if mode is from a whiteout.
Return True if mode is from a whiteout.
[ "Return", "True", "if", "mode", "is", "from", "a", "whiteout", "." ]
def S_ISWHT(mode): """Return True if mode is from a whiteout.""" return False
[ "def", "S_ISWHT", "(", "mode", ")", ":", "return", "False" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/stat.py#L86-L88
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Code/Tools/waf-1.7.13/waflib/extras/codelite.py
python
vsnode.get_waf
(self)
return '%s/%s' % (self.ctx.srcnode.abspath(), getattr(self.ctx, 'waf_command', 'waf'))
Override in subclasses...
Override in subclasses...
[ "Override", "in", "subclasses", "..." ]
def get_waf(self): """ Override in subclasses... """ return '%s/%s' % (self.ctx.srcnode.abspath(), getattr(self.ctx, 'waf_command', 'waf'))
[ "def", "get_waf", "(", "self", ")", ":", "return", "'%s/%s'", "%", "(", "self", ".", "ctx", ".", "srcnode", ".", "abspath", "(", ")", ",", "getattr", "(", "self", ".", "ctx", ",", "'waf_command'", ",", "'waf'", ")", ")" ]
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Code/Tools/waf-1.7.13/waflib/extras/codelite.py#L402-L406
apache/singa
93fd9da72694e68bfe3fb29d0183a65263d238a1
python/singa/autograd.py
python
add
(a, b)
return Add()(a, b)[0]
Return `a+b`, where a and b are Tensor.
Return `a+b`, where a and b are Tensor.
[ "Return", "a", "+", "b", "where", "a", "and", "b", "are", "Tensor", "." ]
def add(a, b): """ Return `a+b`, where a and b are Tensor. """ return Add()(a, b)[0]
[ "def", "add", "(", "a", ",", "b", ")", ":", "return", "Add", "(", ")", "(", "a", ",", "b", ")", "[", "0", "]" ]
https://github.com/apache/singa/blob/93fd9da72694e68bfe3fb29d0183a65263d238a1/python/singa/autograd.py#L894-L898
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/swagger_spec_validator/validator12.py
python
validate_resource_listing
(resource_listing)
Validate a Resource Listing (§5.1). :param resource_listing: a dictionary respresentation of a Resource Listing. Note that you will have to invoke `validate_api_declaration` on each linked API Declaration. :returns: `None` in case of success, otherwise raises an exception. :raises: :py:class:`swagger_spec_validator.SwaggerValidationError` :raises: :py:class:`jsonschema.exceptions.ValidationError`
Validate a Resource Listing (§5.1).
[ "Validate", "a", "Resource", "Listing", "(", "§5", ".", "1", ")", "." ]
def validate_resource_listing(resource_listing): """Validate a Resource Listing (§5.1). :param resource_listing: a dictionary respresentation of a Resource Listing. Note that you will have to invoke `validate_api_declaration` on each linked API Declaration. :returns: `None` in case of success, otherwise raises an exception. :raises: :py:class:`swagger_spec_validator.SwaggerValidationError` :raises: :py:class:`jsonschema.exceptions.ValidationError` """ validate_json(resource_listing, 'schemas/v1.2/resourceListing.json')
[ "def", "validate_resource_listing", "(", "resource_listing", ")", ":", "validate_json", "(", "resource_listing", ",", "'schemas/v1.2/resourceListing.json'", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/swagger_spec_validator/validator12.py#L236-L249
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
scripts/abins/input/textparser.py
python
TextParser.file_end
(self, file_obj=None)
Checks end of the text file. :param file_obj: file object which was open in "r" mode :returns: True if end of file, otherwise False
Checks end of the text file. :param file_obj: file object which was open in "r" mode :returns: True if end of file, otherwise False
[ "Checks", "end", "of", "the", "text", "file", ".", ":", "param", "file_obj", ":", "file", "object", "which", "was", "open", "in", "r", "mode", ":", "returns", ":", "True", "if", "end", "of", "file", "otherwise", "False" ]
def file_end(self, file_obj=None): """ Checks end of the text file. :param file_obj: file object which was open in "r" mode :returns: True if end of file, otherwise False """ pos = file_obj.tell() potential_end = file_obj.read(ONE_CHARACTER) if potential_end == EOF: return True else: file_obj.seek(pos) return False
[ "def", "file_end", "(", "self", ",", "file_obj", "=", "None", ")", ":", "pos", "=", "file_obj", ".", "tell", "(", ")", "potential_end", "=", "file_obj", ".", "read", "(", "ONE_CHARACTER", ")", "if", "potential_end", "==", "EOF", ":", "return", "True", "else", ":", "file_obj", ".", "seek", "(", "pos", ")", "return", "False" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/abins/input/textparser.py#L76-L88
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/ops/nn_grad.py
python
_SparseSoftmaxCrossEntropyWithLogitsGrad
(op, grad_0, _)
return _BroadcastMul(grad_0, sparse_softmax_grad_without_gradient), None
Gradient function for SparseSoftmaxCrossEntropyWithLogits.
Gradient function for SparseSoftmaxCrossEntropyWithLogits.
[ "Gradient", "function", "for", "SparseSoftmaxCrossEntropyWithLogits", "." ]
def _SparseSoftmaxCrossEntropyWithLogitsGrad(op, grad_0, _): """Gradient function for SparseSoftmaxCrossEntropyWithLogits.""" # grad_0 is the backprop for cost, and we multiply it with the gradients # (which is output[1]) # There is no gradient for the labels # # Currently there is no way to take the second derivative of this op # due to the fused implementation's interaction with tf.gradients(), # so we make sure we prevent silently incorrect results by raising # an error if the second derivative is requested via prevent_gradient. sparse_softmax_grad_without_gradient = array_ops.prevent_gradient( op.outputs[1], message="Currently there is no way to take the second " "derivative of sparse_softmax_cross_entropy_with_logits due to the fused " "implementation's interaction with tf.gradients()") return _BroadcastMul(grad_0, sparse_softmax_grad_without_gradient), None
[ "def", "_SparseSoftmaxCrossEntropyWithLogitsGrad", "(", "op", ",", "grad_0", ",", "_", ")", ":", "# grad_0 is the backprop for cost, and we multiply it with the gradients", "# (which is output[1])", "# There is no gradient for the labels", "#", "# Currently there is no way to take the second derivative of this op", "# due to the fused implementation's interaction with tf.gradients(),", "# so we make sure we prevent silently incorrect results by raising", "# an error if the second derivative is requested via prevent_gradient.", "sparse_softmax_grad_without_gradient", "=", "array_ops", ".", "prevent_gradient", "(", "op", ".", "outputs", "[", "1", "]", ",", "message", "=", "\"Currently there is no way to take the second \"", "\"derivative of sparse_softmax_cross_entropy_with_logits due to the fused \"", "\"implementation's interaction with tf.gradients()\"", ")", "return", "_BroadcastMul", "(", "grad_0", ",", "sparse_softmax_grad_without_gradient", ")", ",", "None" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/ops/nn_grad.py#L451-L465
DanielSWolf/rhubarb-lip-sync
5cface0af3b6e4e58c0b829c51561d784fb9f52f
rhubarb/lib/pocketsphinx-rev13216/src/gst-plugin/livedemo.py
python
DemoApp.init_gui
(self)
Initialize the GUI components
Initialize the GUI components
[ "Initialize", "the", "GUI", "components" ]
def init_gui(self): """Initialize the GUI components""" self.window = gtk.Window() self.window.connect("delete-event", gtk.main_quit) self.window.set_default_size(400,200) self.window.set_border_width(10) vbox = gtk.VBox() self.textbuf = gtk.TextBuffer() self.text = gtk.TextView(buffer=self.textbuf) self.text.set_wrap_mode(gtk.WRAP_WORD) vbox.pack_start(self.text) self.button = gtk.ToggleButton("Speak") self.button.connect('clicked', self.button_clicked) vbox.pack_start(self.button, False, False, 5) self.window.add(vbox) self.window.show_all()
[ "def", "init_gui", "(", "self", ")", ":", "self", ".", "window", "=", "gtk", ".", "Window", "(", ")", "self", ".", "window", ".", "connect", "(", "\"delete-event\"", ",", "gtk", ".", "main_quit", ")", "self", ".", "window", ".", "set_default_size", "(", "400", ",", "200", ")", "self", ".", "window", ".", "set_border_width", "(", "10", ")", "vbox", "=", "gtk", ".", "VBox", "(", ")", "self", ".", "textbuf", "=", "gtk", ".", "TextBuffer", "(", ")", "self", ".", "text", "=", "gtk", ".", "TextView", "(", "buffer", "=", "self", ".", "textbuf", ")", "self", ".", "text", ".", "set_wrap_mode", "(", "gtk", ".", "WRAP_WORD", ")", "vbox", ".", "pack_start", "(", "self", ".", "text", ")", "self", ".", "button", "=", "gtk", ".", "ToggleButton", "(", "\"Speak\"", ")", "self", ".", "button", ".", "connect", "(", "'clicked'", ",", "self", ".", "button_clicked", ")", "vbox", ".", "pack_start", "(", "self", ".", "button", ",", "False", ",", "False", ",", "5", ")", "self", ".", "window", ".", "add", "(", "vbox", ")", "self", ".", "window", ".", "show_all", "(", ")" ]
https://github.com/DanielSWolf/rhubarb-lip-sync/blob/5cface0af3b6e4e58c0b829c51561d784fb9f52f/rhubarb/lib/pocketsphinx-rev13216/src/gst-plugin/livedemo.py#L33-L48
wy1iu/LargeMargin_Softmax_Loss
c3e9f20e4f16e2b4daf7d358a614366b9b39a6ec
scripts/cpp_lint.py
python
_SetOutputFormat
(output_format)
Sets the module's output format.
Sets the module's output format.
[ "Sets", "the", "module", "s", "output", "format", "." ]
def _SetOutputFormat(output_format): """Sets the module's output format.""" _cpplint_state.SetOutputFormat(output_format)
[ "def", "_SetOutputFormat", "(", "output_format", ")", ":", "_cpplint_state", ".", "SetOutputFormat", "(", "output_format", ")" ]
https://github.com/wy1iu/LargeMargin_Softmax_Loss/blob/c3e9f20e4f16e2b4daf7d358a614366b9b39a6ec/scripts/cpp_lint.py#L772-L774
1989Ryan/Semantic_SLAM
0284b3f832ca431c494f9c134fe46c40ec86ee38
Third_Part/PSPNet_Keras_tensorflow/caffe-tensorflow/kaffe/tensorflow/network.py
python
Network.make_var
(self, name, shape)
return tf.get_variable(name, shape, trainable=self.trainable)
Creates a new TensorFlow variable.
Creates a new TensorFlow variable.
[ "Creates", "a", "new", "TensorFlow", "variable", "." ]
def make_var(self, name, shape): '''Creates a new TensorFlow variable.''' return tf.get_variable(name, shape, trainable=self.trainable)
[ "def", "make_var", "(", "self", ",", "name", ",", "shape", ")", ":", "return", "tf", ".", "get_variable", "(", "name", ",", "shape", ",", "trainable", "=", "self", ".", "trainable", ")" ]
https://github.com/1989Ryan/Semantic_SLAM/blob/0284b3f832ca431c494f9c134fe46c40ec86ee38/Third_Part/PSPNet_Keras_tensorflow/caffe-tensorflow/kaffe/tensorflow/network.py#L96-L98
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/ipaddress.py
python
_BaseV6._compress_hextets
(cls, hextets)
return hextets
Compresses a list of hextets. Compresses a list of strings, replacing the longest continuous sequence of "0" in the list with "" and adding empty strings at the beginning or at the end of the string such that subsequently calling ":".join(hextets) will produce the compressed version of the IPv6 address. Args: hextets: A list of strings, the hextets to compress. Returns: A list of strings.
Compresses a list of hextets.
[ "Compresses", "a", "list", "of", "hextets", "." ]
def _compress_hextets(cls, hextets): """Compresses a list of hextets. Compresses a list of strings, replacing the longest continuous sequence of "0" in the list with "" and adding empty strings at the beginning or at the end of the string such that subsequently calling ":".join(hextets) will produce the compressed version of the IPv6 address. Args: hextets: A list of strings, the hextets to compress. Returns: A list of strings. """ best_doublecolon_start = -1 best_doublecolon_len = 0 doublecolon_start = -1 doublecolon_len = 0 for index, hextet in enumerate(hextets): if hextet == '0': doublecolon_len += 1 if doublecolon_start == -1: # Start of a sequence of zeros. doublecolon_start = index if doublecolon_len > best_doublecolon_len: # This is the longest sequence of zeros so far. best_doublecolon_len = doublecolon_len best_doublecolon_start = doublecolon_start else: doublecolon_len = 0 doublecolon_start = -1 if best_doublecolon_len > 1: best_doublecolon_end = (best_doublecolon_start + best_doublecolon_len) # For zeros at the end of the address. if best_doublecolon_end == len(hextets): hextets += [''] hextets[best_doublecolon_start:best_doublecolon_end] = [''] # For zeros at the beginning of the address. if best_doublecolon_start == 0: hextets = [''] + hextets return hextets
[ "def", "_compress_hextets", "(", "cls", ",", "hextets", ")", ":", "best_doublecolon_start", "=", "-", "1", "best_doublecolon_len", "=", "0", "doublecolon_start", "=", "-", "1", "doublecolon_len", "=", "0", "for", "index", ",", "hextet", "in", "enumerate", "(", "hextets", ")", ":", "if", "hextet", "==", "'0'", ":", "doublecolon_len", "+=", "1", "if", "doublecolon_start", "==", "-", "1", ":", "# Start of a sequence of zeros.", "doublecolon_start", "=", "index", "if", "doublecolon_len", ">", "best_doublecolon_len", ":", "# This is the longest sequence of zeros so far.", "best_doublecolon_len", "=", "doublecolon_len", "best_doublecolon_start", "=", "doublecolon_start", "else", ":", "doublecolon_len", "=", "0", "doublecolon_start", "=", "-", "1", "if", "best_doublecolon_len", ">", "1", ":", "best_doublecolon_end", "=", "(", "best_doublecolon_start", "+", "best_doublecolon_len", ")", "# For zeros at the end of the address.", "if", "best_doublecolon_end", "==", "len", "(", "hextets", ")", ":", "hextets", "+=", "[", "''", "]", "hextets", "[", "best_doublecolon_start", ":", "best_doublecolon_end", "]", "=", "[", "''", "]", "# For zeros at the beginning of the address.", "if", "best_doublecolon_start", "==", "0", ":", "hextets", "=", "[", "''", "]", "+", "hextets", "return", "hextets" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/ipaddress.py#L1756-L1801
SequoiaDB/SequoiaDB
2894ed7e5bd6fe57330afc900cf76d0ff0df9f64
tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py
python
xmlNode.listGetRawString
(self, doc, inLine)
return ret
Builds the string equivalent to the text contained in the Node list made of TEXTs and ENTITY_REFs, contrary to xmlNodeListGetString() this function doesn't do any character encoding handling.
Builds the string equivalent to the text contained in the Node list made of TEXTs and ENTITY_REFs, contrary to xmlNodeListGetString() this function doesn't do any character encoding handling.
[ "Builds", "the", "string", "equivalent", "to", "the", "text", "contained", "in", "the", "Node", "list", "made", "of", "TEXTs", "and", "ENTITY_REFs", "contrary", "to", "xmlNodeListGetString", "()", "this", "function", "doesn", "t", "do", "any", "character", "encoding", "handling", "." ]
def listGetRawString(self, doc, inLine): """Builds the string equivalent to the text contained in the Node list made of TEXTs and ENTITY_REFs, contrary to xmlNodeListGetString() this function doesn't do any character encoding handling. """ if doc is None: doc__o = None else: doc__o = doc._o ret = libxml2mod.xmlNodeListGetRawString(doc__o, self._o, inLine) return ret
[ "def", "listGetRawString", "(", "self", ",", "doc", ",", "inLine", ")", ":", "if", "doc", "is", "None", ":", "doc__o", "=", "None", "else", ":", "doc__o", "=", "doc", ".", "_o", "ret", "=", "libxml2mod", ".", "xmlNodeListGetRawString", "(", "doc__o", ",", "self", ".", "_o", ",", "inLine", ")", "return", "ret" ]
https://github.com/SequoiaDB/SequoiaDB/blob/2894ed7e5bd6fe57330afc900cf76d0ff0df9f64/tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py#L3280-L3288
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_windows.py
python
PrintData.__init__
(self, *args)
__init__(self) -> PrintData __init__(self, PrintData data) -> PrintData
__init__(self) -> PrintData __init__(self, PrintData data) -> PrintData
[ "__init__", "(", "self", ")", "-", ">", "PrintData", "__init__", "(", "self", "PrintData", "data", ")", "-", ">", "PrintData" ]
def __init__(self, *args): """ __init__(self) -> PrintData __init__(self, PrintData data) -> PrintData """ _windows_.PrintData_swiginit(self,_windows_.new_PrintData(*args))
[ "def", "__init__", "(", "self", ",", "*", "args", ")", ":", "_windows_", ".", "PrintData_swiginit", "(", "self", ",", "_windows_", ".", "new_PrintData", "(", "*", "args", ")", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_windows.py#L4702-L4707
domino-team/openwrt-cc
8b181297c34d14d3ca521cc9f31430d561dbc688
package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/analyzer.py
python
_GenerateTargets
(data, target_list, target_dicts, toplevel_dir, files, build_files)
return name_to_target, matching_targets, roots & build_file_targets
Returns a tuple of the following: . A dictionary mapping from fully qualified name to Target. . A list of the targets that have a source file in |files|. . Targets that constitute the 'all' target. See description at top of file for details on the 'all' target. This sets the |match_status| of the targets that contain any of the source files in |files| to MATCH_STATUS_MATCHES. |toplevel_dir| is the root of the source tree.
Returns a tuple of the following: . A dictionary mapping from fully qualified name to Target. . A list of the targets that have a source file in |files|. . Targets that constitute the 'all' target. See description at top of file for details on the 'all' target. This sets the |match_status| of the targets that contain any of the source files in |files| to MATCH_STATUS_MATCHES. |toplevel_dir| is the root of the source tree.
[ "Returns", "a", "tuple", "of", "the", "following", ":", ".", "A", "dictionary", "mapping", "from", "fully", "qualified", "name", "to", "Target", ".", ".", "A", "list", "of", "the", "targets", "that", "have", "a", "source", "file", "in", "|files|", ".", ".", "Targets", "that", "constitute", "the", "all", "target", ".", "See", "description", "at", "top", "of", "file", "for", "details", "on", "the", "all", "target", ".", "This", "sets", "the", "|match_status|", "of", "the", "targets", "that", "contain", "any", "of", "the", "source", "files", "in", "|files|", "to", "MATCH_STATUS_MATCHES", ".", "|toplevel_dir|", "is", "the", "root", "of", "the", "source", "tree", "." ]
def _GenerateTargets(data, target_list, target_dicts, toplevel_dir, files, build_files): """Returns a tuple of the following: . A dictionary mapping from fully qualified name to Target. . A list of the targets that have a source file in |files|. . Targets that constitute the 'all' target. See description at top of file for details on the 'all' target. This sets the |match_status| of the targets that contain any of the source files in |files| to MATCH_STATUS_MATCHES. |toplevel_dir| is the root of the source tree.""" # Maps from target name to Target. name_to_target = {} # Targets that matched. matching_targets = [] # Queue of targets to visit. targets_to_visit = target_list[:] # Maps from build file to a boolean indicating whether the build file is in # |files|. build_file_in_files = {} # Root targets across all files. roots = set() # Set of Targets in |build_files|. build_file_targets = set() while len(targets_to_visit) > 0: target_name = targets_to_visit.pop() created_target, target = _GetOrCreateTargetByName(name_to_target, target_name) if created_target: roots.add(target) elif target.visited: continue target.visited = True target.requires_build = _DoesTargetTypeRequireBuild( target_dicts[target_name]) target_type = target_dicts[target_name]['type'] target.is_executable = target_type == 'executable' target.is_static_library = target_type == 'static_library' target.is_or_has_linked_ancestor = (target_type == 'executable' or target_type == 'shared_library') build_file = gyp.common.ParseQualifiedTarget(target_name)[0] if not build_file in build_file_in_files: build_file_in_files[build_file] = \ _WasBuildFileModified(build_file, data, files, toplevel_dir) if build_file in build_files: build_file_targets.add(target) # If a build file (or any of its included files) is modified we assume all # targets in the file are modified. if build_file_in_files[build_file]: print 'matching target from modified build file', target_name target.match_status = MATCH_STATUS_MATCHES matching_targets.append(target) else: sources = _ExtractSources(target_name, target_dicts[target_name], toplevel_dir) for source in sources: if _ToGypPath(os.path.normpath(source)) in files: print 'target', target_name, 'matches', source target.match_status = MATCH_STATUS_MATCHES matching_targets.append(target) break # Add dependencies to visit as well as updating back pointers for deps. for dep in target_dicts[target_name].get('dependencies', []): targets_to_visit.append(dep) created_dep_target, dep_target = _GetOrCreateTargetByName(name_to_target, dep) if not created_dep_target: roots.discard(dep_target) target.deps.add(dep_target) dep_target.back_deps.add(target) return name_to_target, matching_targets, roots & build_file_targets
[ "def", "_GenerateTargets", "(", "data", ",", "target_list", ",", "target_dicts", ",", "toplevel_dir", ",", "files", ",", "build_files", ")", ":", "# Maps from target name to Target.", "name_to_target", "=", "{", "}", "# Targets that matched.", "matching_targets", "=", "[", "]", "# Queue of targets to visit.", "targets_to_visit", "=", "target_list", "[", ":", "]", "# Maps from build file to a boolean indicating whether the build file is in", "# |files|.", "build_file_in_files", "=", "{", "}", "# Root targets across all files.", "roots", "=", "set", "(", ")", "# Set of Targets in |build_files|.", "build_file_targets", "=", "set", "(", ")", "while", "len", "(", "targets_to_visit", ")", ">", "0", ":", "target_name", "=", "targets_to_visit", ".", "pop", "(", ")", "created_target", ",", "target", "=", "_GetOrCreateTargetByName", "(", "name_to_target", ",", "target_name", ")", "if", "created_target", ":", "roots", ".", "add", "(", "target", ")", "elif", "target", ".", "visited", ":", "continue", "target", ".", "visited", "=", "True", "target", ".", "requires_build", "=", "_DoesTargetTypeRequireBuild", "(", "target_dicts", "[", "target_name", "]", ")", "target_type", "=", "target_dicts", "[", "target_name", "]", "[", "'type'", "]", "target", ".", "is_executable", "=", "target_type", "==", "'executable'", "target", ".", "is_static_library", "=", "target_type", "==", "'static_library'", "target", ".", "is_or_has_linked_ancestor", "=", "(", "target_type", "==", "'executable'", "or", "target_type", "==", "'shared_library'", ")", "build_file", "=", "gyp", ".", "common", ".", "ParseQualifiedTarget", "(", "target_name", ")", "[", "0", "]", "if", "not", "build_file", "in", "build_file_in_files", ":", "build_file_in_files", "[", "build_file", "]", "=", "_WasBuildFileModified", "(", "build_file", ",", "data", ",", "files", ",", "toplevel_dir", ")", "if", "build_file", "in", "build_files", ":", "build_file_targets", ".", "add", "(", "target", ")", "# If a build file (or any of its included files) is modified we assume all", "# targets in the file are modified.", "if", "build_file_in_files", "[", "build_file", "]", ":", "print", "'matching target from modified build file'", ",", "target_name", "target", ".", "match_status", "=", "MATCH_STATUS_MATCHES", "matching_targets", ".", "append", "(", "target", ")", "else", ":", "sources", "=", "_ExtractSources", "(", "target_name", ",", "target_dicts", "[", "target_name", "]", ",", "toplevel_dir", ")", "for", "source", "in", "sources", ":", "if", "_ToGypPath", "(", "os", ".", "path", ".", "normpath", "(", "source", ")", ")", "in", "files", ":", "print", "'target'", ",", "target_name", ",", "'matches'", ",", "source", "target", ".", "match_status", "=", "MATCH_STATUS_MATCHES", "matching_targets", ".", "append", "(", "target", ")", "break", "# Add dependencies to visit as well as updating back pointers for deps.", "for", "dep", "in", "target_dicts", "[", "target_name", "]", ".", "get", "(", "'dependencies'", ",", "[", "]", ")", ":", "targets_to_visit", ".", "append", "(", "dep", ")", "created_dep_target", ",", "dep_target", "=", "_GetOrCreateTargetByName", "(", "name_to_target", ",", "dep", ")", "if", "not", "created_dep_target", ":", "roots", ".", "discard", "(", "dep_target", ")", "target", ".", "deps", ".", "add", "(", "dep_target", ")", "dep_target", ".", "back_deps", ".", "add", "(", "target", ")", "return", "name_to_target", ",", "matching_targets", ",", "roots", "&", "build_file_targets" ]
https://github.com/domino-team/openwrt-cc/blob/8b181297c34d14d3ca521cc9f31430d561dbc688/package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/analyzer.py#L318-L401
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/ipaddress.py
python
_BaseV6._explode_shorthand_ip_string
(self)
return ':'.join(parts)
Expand a shortened IPv6 address. Args: ip_str: A string, the IPv6 address. Returns: A string, the expanded IPv6 address.
Expand a shortened IPv6 address.
[ "Expand", "a", "shortened", "IPv6", "address", "." ]
def _explode_shorthand_ip_string(self): """Expand a shortened IPv6 address. Args: ip_str: A string, the IPv6 address. Returns: A string, the expanded IPv6 address. """ if isinstance(self, IPv6Network): ip_str = _compat_str(self.network_address) elif isinstance(self, IPv6Interface): ip_str = _compat_str(self.ip) else: ip_str = _compat_str(self) ip_int = self._ip_int_from_string(ip_str) hex_str = '%032x' % ip_int parts = [hex_str[x:x + 4] for x in range(0, 32, 4)] if isinstance(self, (_BaseNetwork, IPv6Interface)): return '%s/%d' % (':'.join(parts), self._prefixlen) return ':'.join(parts)
[ "def", "_explode_shorthand_ip_string", "(", "self", ")", ":", "if", "isinstance", "(", "self", ",", "IPv6Network", ")", ":", "ip_str", "=", "_compat_str", "(", "self", ".", "network_address", ")", "elif", "isinstance", "(", "self", ",", "IPv6Interface", ")", ":", "ip_str", "=", "_compat_str", "(", "self", ".", "ip", ")", "else", ":", "ip_str", "=", "_compat_str", "(", "self", ")", "ip_int", "=", "self", ".", "_ip_int_from_string", "(", "ip_str", ")", "hex_str", "=", "'%032x'", "%", "ip_int", "parts", "=", "[", "hex_str", "[", "x", ":", "x", "+", "4", "]", "for", "x", "in", "range", "(", "0", ",", "32", ",", "4", ")", "]", "if", "isinstance", "(", "self", ",", "(", "_BaseNetwork", ",", "IPv6Interface", ")", ")", ":", "return", "'%s/%d'", "%", "(", "':'", ".", "join", "(", "parts", ")", ",", "self", ".", "_prefixlen", ")", "return", "':'", ".", "join", "(", "parts", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/ipaddress.py#L1955-L1977
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pkg_resources/_vendor/pyparsing.py
python
ParserElement.__sub__
(self, other)
return self + And._ErrorStop() + other
Implementation of - operator, returns C{L{And}} with error stop
Implementation of - operator, returns C{L{And}} with error stop
[ "Implementation", "of", "-", "operator", "returns", "C", "{", "L", "{", "And", "}}", "with", "error", "stop" ]
def __sub__(self, other): """ Implementation of - operator, returns C{L{And}} with error stop """ if isinstance( other, basestring ): other = ParserElement._literalStringClass( other ) if not isinstance( other, ParserElement ): warnings.warn("Cannot combine element of type %s with ParserElement" % type(other), SyntaxWarning, stacklevel=2) return None return self + And._ErrorStop() + other
[ "def", "__sub__", "(", "self", ",", "other", ")", ":", "if", "isinstance", "(", "other", ",", "basestring", ")", ":", "other", "=", "ParserElement", ".", "_literalStringClass", "(", "other", ")", "if", "not", "isinstance", "(", "other", ",", "ParserElement", ")", ":", "warnings", ".", "warn", "(", "\"Cannot combine element of type %s with ParserElement\"", "%", "type", "(", "other", ")", ",", "SyntaxWarning", ",", "stacklevel", "=", "2", ")", "return", "None", "return", "self", "+", "And", ".", "_ErrorStop", "(", ")", "+", "other" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pkg_resources/_vendor/pyparsing.py#L1854-L1864
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/ops/rnn.py
python
_reverse_seq
(input_seq, lengths)
return results
Reverse a list of Tensors up to specified lengths. Args: input_seq: Sequence of seq_len tensors of dimension (batch_size, n_features) or nested tuples of tensors. lengths: A `Tensor` of dimension batch_size, containing lengths for each sequence in the batch. If "None" is specified, simply reverses the list. Returns: time-reversed sequence
Reverse a list of Tensors up to specified lengths.
[ "Reverse", "a", "list", "of", "Tensors", "up", "to", "specified", "lengths", "." ]
def _reverse_seq(input_seq, lengths): """Reverse a list of Tensors up to specified lengths. Args: input_seq: Sequence of seq_len tensors of dimension (batch_size, n_features) or nested tuples of tensors. lengths: A `Tensor` of dimension batch_size, containing lengths for each sequence in the batch. If "None" is specified, simply reverses the list. Returns: time-reversed sequence """ if lengths is None: return list(reversed(input_seq)) flat_input_seq = tuple(nest.flatten(input_) for input_ in input_seq) flat_results = [[] for _ in range(len(input_seq))] for sequence in zip(*flat_input_seq): input_shape = tensor_shape.unknown_shape(rank=sequence[0].get_shape().rank) for input_ in sequence: input_shape.assert_is_compatible_with(input_.get_shape()) input_.set_shape(input_shape) # Join into (time, batch_size, depth) s_joined = array_ops.stack(sequence) # Reverse along dimension 0 s_reversed = array_ops.reverse_sequence(s_joined, lengths, 0, 1) # Split again into list result = array_ops.unstack(s_reversed) for r, flat_result in zip(result, flat_results): r.set_shape(input_shape) flat_result.append(r) results = [ nest.pack_sequence_as(structure=input_, flat_sequence=flat_result) for input_, flat_result in zip(input_seq, flat_results) ] return results
[ "def", "_reverse_seq", "(", "input_seq", ",", "lengths", ")", ":", "if", "lengths", "is", "None", ":", "return", "list", "(", "reversed", "(", "input_seq", ")", ")", "flat_input_seq", "=", "tuple", "(", "nest", ".", "flatten", "(", "input_", ")", "for", "input_", "in", "input_seq", ")", "flat_results", "=", "[", "[", "]", "for", "_", "in", "range", "(", "len", "(", "input_seq", ")", ")", "]", "for", "sequence", "in", "zip", "(", "*", "flat_input_seq", ")", ":", "input_shape", "=", "tensor_shape", ".", "unknown_shape", "(", "rank", "=", "sequence", "[", "0", "]", ".", "get_shape", "(", ")", ".", "rank", ")", "for", "input_", "in", "sequence", ":", "input_shape", ".", "assert_is_compatible_with", "(", "input_", ".", "get_shape", "(", ")", ")", "input_", ".", "set_shape", "(", "input_shape", ")", "# Join into (time, batch_size, depth)", "s_joined", "=", "array_ops", ".", "stack", "(", "sequence", ")", "# Reverse along dimension 0", "s_reversed", "=", "array_ops", ".", "reverse_sequence", "(", "s_joined", ",", "lengths", ",", "0", ",", "1", ")", "# Split again into list", "result", "=", "array_ops", ".", "unstack", "(", "s_reversed", ")", "for", "r", ",", "flat_result", "in", "zip", "(", "result", ",", "flat_results", ")", ":", "r", ".", "set_shape", "(", "input_shape", ")", "flat_result", ".", "append", "(", "r", ")", "results", "=", "[", "nest", ".", "pack_sequence_as", "(", "structure", "=", "input_", ",", "flat_sequence", "=", "flat_result", ")", "for", "input_", ",", "flat_result", "in", "zip", "(", "input_seq", ",", "flat_results", ")", "]", "return", "results" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/rnn.py#L299-L338
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_windows.py
python
StatusBar.GetClassDefaultAttributes
(*args, **kwargs)
return _windows_.StatusBar_GetClassDefaultAttributes(*args, **kwargs)
GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes Get the default attributes for this class. This is useful if you want to use the same font or colour in your own control as in a standard control -- which is a much better idea than hard coding specific colours or fonts which might look completely out of place on the user's system, especially if it uses themes. The variant parameter is only relevant under Mac currently and is ignore under other platforms. Under Mac, it will change the size of the returned font. See `wx.Window.SetWindowVariant` for more about this.
GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes
[ "GetClassDefaultAttributes", "(", "int", "variant", "=", "WINDOW_VARIANT_NORMAL", ")", "-", ">", "VisualAttributes" ]
def GetClassDefaultAttributes(*args, **kwargs): """ GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes Get the default attributes for this class. This is useful if you want to use the same font or colour in your own control as in a standard control -- which is a much better idea than hard coding specific colours or fonts which might look completely out of place on the user's system, especially if it uses themes. The variant parameter is only relevant under Mac currently and is ignore under other platforms. Under Mac, it will change the size of the returned font. See `wx.Window.SetWindowVariant` for more about this. """ return _windows_.StatusBar_GetClassDefaultAttributes(*args, **kwargs)
[ "def", "GetClassDefaultAttributes", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_windows_", ".", "StatusBar_GetClassDefaultAttributes", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_windows.py#L1303-L1318
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py3/pandas/core/arrays/datetimelike.py
python
DatetimeLikeArrayMixin._sub_nat
(self)
return result.view("timedelta64[ns]")
Subtract pd.NaT from self
Subtract pd.NaT from self
[ "Subtract", "pd", ".", "NaT", "from", "self" ]
def _sub_nat(self): """ Subtract pd.NaT from self """ # GH#19124 Timedelta - datetime is not in general well-defined. # We make an exception for pd.NaT, which in this case quacks # like a timedelta. # For datetime64 dtypes by convention we treat NaT as a datetime, so # this subtraction returns a timedelta64 dtype. # For period dtype, timedelta64 is a close-enough return dtype. result = np.empty(self.shape, dtype=np.int64) result.fill(iNaT) return result.view("timedelta64[ns]")
[ "def", "_sub_nat", "(", "self", ")", ":", "# GH#19124 Timedelta - datetime is not in general well-defined.", "# We make an exception for pd.NaT, which in this case quacks", "# like a timedelta.", "# For datetime64 dtypes by convention we treat NaT as a datetime, so", "# this subtraction returns a timedelta64 dtype.", "# For period dtype, timedelta64 is a close-enough return dtype.", "result", "=", "np", ".", "empty", "(", "self", ".", "shape", ",", "dtype", "=", "np", ".", "int64", ")", "result", ".", "fill", "(", "iNaT", ")", "return", "result", ".", "view", "(", "\"timedelta64[ns]\"", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/arrays/datetimelike.py#L1149-L1161
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/python/framework/common_shapes.py
python
depthwise_conv2d_native_shape
(op)
return [tensor_shape.TensorShape([batch_size, out_rows, out_cols, depth_out])]
Shape function for a DepthwiseConv2D op. This op has two inputs: * input, a 4D tensor with shape = [batch_size, rows, cols, depth_in] * filter, a 4D tensor with shape = [filter_rows, filter_cols, depth_in, depthwise_multiplier] The output is a 4D tensor with shape = [batch_size, out_rows, out_cols, depth_in*depthwise_multiplier], where out_rows and out_cols depend on the value of the op's "padding" and "strides" attrs. Args: op: A DepthwiseConv2dNative Operation. Returns: A list containing the Shape of the DepthwiseConv2DNative output. Raises: ValueError: If the shapes of the input or filter are incompatible.
Shape function for a DepthwiseConv2D op.
[ "Shape", "function", "for", "a", "DepthwiseConv2D", "op", "." ]
def depthwise_conv2d_native_shape(op): """Shape function for a DepthwiseConv2D op. This op has two inputs: * input, a 4D tensor with shape = [batch_size, rows, cols, depth_in] * filter, a 4D tensor with shape = [filter_rows, filter_cols, depth_in, depthwise_multiplier] The output is a 4D tensor with shape = [batch_size, out_rows, out_cols, depth_in*depthwise_multiplier], where out_rows and out_cols depend on the value of the op's "padding" and "strides" attrs. Args: op: A DepthwiseConv2dNative Operation. Returns: A list containing the Shape of the DepthwiseConv2DNative output. Raises: ValueError: If the shapes of the input or filter are incompatible. """ input_shape = op.inputs[0].get_shape().with_rank(4) filter_shape = op.inputs[1].get_shape().with_rank(4) batch_size = input_shape[0] in_rows = input_shape[1] in_cols = input_shape[2] filter_rows = filter_shape[0] filter_cols = filter_shape[1] depth_out = filter_shape[3] * filter_shape[2] # Check that the input depths are compatible. input_shape[3].assert_is_compatible_with(filter_shape[2]) stride_b, stride_r, stride_c, stride_d = op.get_attr("strides") if stride_b != 1 or stride_d != 1: raise ValueError("Current implementation does not yet support " "strides in the batch and depth dimensions.") if stride_r != stride_c: # TODO(shlens): Add support for this. raise ValueError("Current implementation only supports equal length " "strides in the row and column dimensions.") # TODO(mrry,shlens): Raise an error if the stride would cause # information in the input to be ignored. This will require a change # in the kernel implementation. stride = stride_r padding = op.get_attr("padding") out_rows, out_cols = get2d_conv_output_size(in_rows, in_cols, filter_rows, filter_cols, stride, stride, padding) return [tensor_shape.TensorShape([batch_size, out_rows, out_cols, depth_out])]
[ "def", "depthwise_conv2d_native_shape", "(", "op", ")", ":", "input_shape", "=", "op", ".", "inputs", "[", "0", "]", ".", "get_shape", "(", ")", ".", "with_rank", "(", "4", ")", "filter_shape", "=", "op", ".", "inputs", "[", "1", "]", ".", "get_shape", "(", ")", ".", "with_rank", "(", "4", ")", "batch_size", "=", "input_shape", "[", "0", "]", "in_rows", "=", "input_shape", "[", "1", "]", "in_cols", "=", "input_shape", "[", "2", "]", "filter_rows", "=", "filter_shape", "[", "0", "]", "filter_cols", "=", "filter_shape", "[", "1", "]", "depth_out", "=", "filter_shape", "[", "3", "]", "*", "filter_shape", "[", "2", "]", "# Check that the input depths are compatible.", "input_shape", "[", "3", "]", ".", "assert_is_compatible_with", "(", "filter_shape", "[", "2", "]", ")", "stride_b", ",", "stride_r", ",", "stride_c", ",", "stride_d", "=", "op", ".", "get_attr", "(", "\"strides\"", ")", "if", "stride_b", "!=", "1", "or", "stride_d", "!=", "1", ":", "raise", "ValueError", "(", "\"Current implementation does not yet support \"", "\"strides in the batch and depth dimensions.\"", ")", "if", "stride_r", "!=", "stride_c", ":", "# TODO(shlens): Add support for this.", "raise", "ValueError", "(", "\"Current implementation only supports equal length \"", "\"strides in the row and column dimensions.\"", ")", "# TODO(mrry,shlens): Raise an error if the stride would cause", "# information in the input to be ignored. This will require a change", "# in the kernel implementation.", "stride", "=", "stride_r", "padding", "=", "op", ".", "get_attr", "(", "\"padding\"", ")", "out_rows", ",", "out_cols", "=", "get2d_conv_output_size", "(", "in_rows", ",", "in_cols", ",", "filter_rows", ",", "filter_cols", ",", "stride", ",", "stride", ",", "padding", ")", "return", "[", "tensor_shape", ".", "TensorShape", "(", "[", "batch_size", ",", "out_rows", ",", "out_cols", ",", "depth_out", "]", ")", "]" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/framework/common_shapes.py#L225-L278
baidu/bigflow
449245016c0df7d1252e85581e588bfc60cefad3
bigflow_python/python/bigflow/base.py
python
Transformer.begin_process
(self, *side_inputs)
return []
此方法在开始处理数据之前被调用,以通知用户要开始处理数据了。 用户必须返回一个可迭代的对象,其中值将会被放入结果的PCollection中。
此方法在开始处理数据之前被调用,以通知用户要开始处理数据了。
[ "此方法在开始处理数据之前被调用,以通知用户要开始处理数据了。" ]
def begin_process(self, *side_inputs): """ 此方法在开始处理数据之前被调用,以通知用户要开始处理数据了。 用户必须返回一个可迭代的对象,其中值将会被放入结果的PCollection中。 """ return []
[ "def", "begin_process", "(", "self", ",", "*", "side_inputs", ")", ":", "return", "[", "]" ]
https://github.com/baidu/bigflow/blob/449245016c0df7d1252e85581e588bfc60cefad3/bigflow_python/python/bigflow/base.py#L130-L136
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/telemetry/telemetry/internal/platform/network_controller_backend.py
python
NetworkControllerBackend.StopReplay
(self)
Stop web page replay. Stops both the replay server and the forwarder if currently active.
Stop web page replay.
[ "Stop", "web", "page", "replay", "." ]
def StopReplay(self): """Stop web page replay. Stops both the replay server and the forwarder if currently active. """ if self._forwarder: self._forwarder.Close() self._forwarder = None self._StopReplayServer()
[ "def", "StopReplay", "(", "self", ")", ":", "if", "self", ".", "_forwarder", ":", "self", ".", "_forwarder", ".", "Close", "(", ")", "self", ".", "_forwarder", "=", "None", "self", ".", "_StopReplayServer", "(", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/telemetry/internal/platform/network_controller_backend.py#L194-L202
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_internal/cli/cmdoptions.py
python
_handle_python_version
(option, opt_str, value, parser)
Handle a provided --python-version value.
Handle a provided --python-version value.
[ "Handle", "a", "provided", "--", "python", "-", "version", "value", "." ]
def _handle_python_version(option, opt_str, value, parser): # type: (Option, str, str, OptionParser) -> None """ Handle a provided --python-version value. """ version_info, error_msg = _convert_python_version(value) if error_msg is not None: msg = ( 'invalid --python-version value: {!r}: {}'.format( value, error_msg, ) ) raise_option_error(parser, option=option, msg=msg) parser.values.python_version = version_info
[ "def", "_handle_python_version", "(", "option", ",", "opt_str", ",", "value", ",", "parser", ")", ":", "# type: (Option, str, str, OptionParser) -> None", "version_info", ",", "error_msg", "=", "_convert_python_version", "(", "value", ")", "if", "error_msg", "is", "not", "None", ":", "msg", "=", "(", "'invalid --python-version value: {!r}: {}'", ".", "format", "(", "value", ",", "error_msg", ",", ")", ")", "raise_option_error", "(", "parser", ",", "option", "=", "option", ",", "msg", "=", "msg", ")", "parser", ".", "values", ".", "python_version", "=", "version_info" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_internal/cli/cmdoptions.py#L543-L557
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/text_format.py
python
Parse
(text, message, allow_unknown_extension=False, allow_field_number=False, descriptor_pool=None)
return ParseLines(text.split('\n'), message, allow_unknown_extension, allow_field_number, descriptor_pool=descriptor_pool)
Parses a text representation of a protocol message into a message. Args: text: Message text representation. message: A protocol buffer message to merge into. allow_unknown_extension: if True, skip over missing extensions and keep parsing allow_field_number: if True, both field number and field name are allowed. descriptor_pool: A DescriptorPool used to resolve Any types. Returns: The same message passed as argument. Raises: ParseError: On text parsing problems.
Parses a text representation of a protocol message into a message.
[ "Parses", "a", "text", "representation", "of", "a", "protocol", "message", "into", "a", "message", "." ]
def Parse(text, message, allow_unknown_extension=False, allow_field_number=False, descriptor_pool=None): """Parses a text representation of a protocol message into a message. Args: text: Message text representation. message: A protocol buffer message to merge into. allow_unknown_extension: if True, skip over missing extensions and keep parsing allow_field_number: if True, both field number and field name are allowed. descriptor_pool: A DescriptorPool used to resolve Any types. Returns: The same message passed as argument. Raises: ParseError: On text parsing problems. """ if not isinstance(text, str): text = text.decode('utf-8') return ParseLines(text.split('\n'), message, allow_unknown_extension, allow_field_number, descriptor_pool=descriptor_pool)
[ "def", "Parse", "(", "text", ",", "message", ",", "allow_unknown_extension", "=", "False", ",", "allow_field_number", "=", "False", ",", "descriptor_pool", "=", "None", ")", ":", "if", "not", "isinstance", "(", "text", ",", "str", ")", ":", "text", "=", "text", ".", "decode", "(", "'utf-8'", ")", "return", "ParseLines", "(", "text", ".", "split", "(", "'\\n'", ")", ",", "message", ",", "allow_unknown_extension", ",", "allow_field_number", ",", "descriptor_pool", "=", "descriptor_pool", ")" ]
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/text_format.py#L422-L449
bumptop/BumpTop
466d23597a07ae738f4265262fa01087fc6e257c
trunk/win/Source/bin/jinja2/debug.py
python
ProcessedTraceback.standard_exc_info
(self)
return self.exc_type, self.exc_value, self.frames[0].tb
Standard python exc_info for re-raising
Standard python exc_info for re-raising
[ "Standard", "python", "exc_info", "for", "re", "-", "raising" ]
def standard_exc_info(self): """Standard python exc_info for re-raising""" return self.exc_type, self.exc_value, self.frames[0].tb
[ "def", "standard_exc_info", "(", "self", ")", ":", "return", "self", ".", "exc_type", ",", "self", ".", "exc_value", ",", "self", ".", "frames", "[", "0", "]", ".", "tb" ]
https://github.com/bumptop/BumpTop/blob/466d23597a07ae738f4265262fa01087fc6e257c/trunk/win/Source/bin/jinja2/debug.py#L96-L98
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/plat-mac/lib-scriptpackages/Finder/Standard_Suite.py
python
Standard_Suite_Events.make
(self, _no_object=None, _attributes={}, **_arguments)
make: Make a new element Keyword argument new: the class of the new element Keyword argument at: the location at which to insert the element Keyword argument to: when creating an alias file, the original item to create an alias to or when creating a file viewer window, the target of the window Keyword argument with_properties: the initial values for the properties of the element Keyword argument _attributes: AppleEvent attribute dictionary Returns: to the new object(s)
make: Make a new element Keyword argument new: the class of the new element Keyword argument at: the location at which to insert the element Keyword argument to: when creating an alias file, the original item to create an alias to or when creating a file viewer window, the target of the window Keyword argument with_properties: the initial values for the properties of the element Keyword argument _attributes: AppleEvent attribute dictionary Returns: to the new object(s)
[ "make", ":", "Make", "a", "new", "element", "Keyword", "argument", "new", ":", "the", "class", "of", "the", "new", "element", "Keyword", "argument", "at", ":", "the", "location", "at", "which", "to", "insert", "the", "element", "Keyword", "argument", "to", ":", "when", "creating", "an", "alias", "file", "the", "original", "item", "to", "create", "an", "alias", "to", "or", "when", "creating", "a", "file", "viewer", "window", "the", "target", "of", "the", "window", "Keyword", "argument", "with_properties", ":", "the", "initial", "values", "for", "the", "properties", "of", "the", "element", "Keyword", "argument", "_attributes", ":", "AppleEvent", "attribute", "dictionary", "Returns", ":", "to", "the", "new", "object", "(", "s", ")" ]
def make(self, _no_object=None, _attributes={}, **_arguments): """make: Make a new element Keyword argument new: the class of the new element Keyword argument at: the location at which to insert the element Keyword argument to: when creating an alias file, the original item to create an alias to or when creating a file viewer window, the target of the window Keyword argument with_properties: the initial values for the properties of the element Keyword argument _attributes: AppleEvent attribute dictionary Returns: to the new object(s) """ _code = 'core' _subcode = 'crel' aetools.keysubst(_arguments, self._argmap_make) if _no_object is not None: raise TypeError, 'No direct arg expected' _reply, _arguments, _attributes = self.send(_code, _subcode, _arguments, _attributes) if _arguments.get('errn', 0): raise aetools.Error, aetools.decodeerror(_arguments) # XXXX Optionally decode result if _arguments.has_key('----'): return _arguments['----']
[ "def", "make", "(", "self", ",", "_no_object", "=", "None", ",", "_attributes", "=", "{", "}", ",", "*", "*", "_arguments", ")", ":", "_code", "=", "'core'", "_subcode", "=", "'crel'", "aetools", ".", "keysubst", "(", "_arguments", ",", "self", ".", "_argmap_make", ")", "if", "_no_object", "is", "not", "None", ":", "raise", "TypeError", ",", "'No direct arg expected'", "_reply", ",", "_arguments", ",", "_attributes", "=", "self", ".", "send", "(", "_code", ",", "_subcode", ",", "_arguments", ",", "_attributes", ")", "if", "_arguments", ".", "get", "(", "'errn'", ",", "0", ")", ":", "raise", "aetools", ".", "Error", ",", "aetools", ".", "decodeerror", "(", "_arguments", ")", "# XXXX Optionally decode result", "if", "_arguments", ".", "has_key", "(", "'----'", ")", ":", "return", "_arguments", "[", "'----'", "]" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/plat-mac/lib-scriptpackages/Finder/Standard_Suite.py#L169-L191
linyouhappy/kongkongxiyou
7a69b2913eb29f4be77f9a62fb90cdd72c4160f1
cocosjs/frameworks/cocos2d-x/plugin/tools/android-build.py
python
select_toolchain_version
()
Because ndk-r8e uses gcc4.6 as default. gcc4.6 doesn't support c++11. So we should select gcc4.7 when using ndk-r8e. But gcc4.7 is removed in ndk-r9, so we should determine whether gcc4.7 exist. Conclution: ndk-r8e -> use gcc4.7 ndk-r9 -> use gcc4.8
Because ndk-r8e uses gcc4.6 as default. gcc4.6 doesn't support c++11. So we should select gcc4.7 when using ndk-r8e. But gcc4.7 is removed in ndk-r9, so we should determine whether gcc4.7 exist. Conclution: ndk-r8e -> use gcc4.7 ndk-r9 -> use gcc4.8
[ "Because", "ndk", "-", "r8e", "uses", "gcc4", ".", "6", "as", "default", ".", "gcc4", ".", "6", "doesn", "t", "support", "c", "++", "11", ".", "So", "we", "should", "select", "gcc4", ".", "7", "when", "using", "ndk", "-", "r8e", ".", "But", "gcc4", ".", "7", "is", "removed", "in", "ndk", "-", "r9", "so", "we", "should", "determine", "whether", "gcc4", ".", "7", "exist", ".", "Conclution", ":", "ndk", "-", "r8e", "-", ">", "use", "gcc4", ".", "7", "ndk", "-", "r9", "-", ">", "use", "gcc4", ".", "8" ]
def select_toolchain_version(): '''Because ndk-r8e uses gcc4.6 as default. gcc4.6 doesn't support c++11. So we should select gcc4.7 when using ndk-r8e. But gcc4.7 is removed in ndk-r9, so we should determine whether gcc4.7 exist. Conclution: ndk-r8e -> use gcc4.7 ndk-r9 -> use gcc4.8 ''' ndk_root = check_environment_variables() if os.path.isdir(os.path.join(ndk_root,"toolchains/arm-linux-androideabi-4.8")): os.environ['NDK_TOOLCHAIN_VERSION'] = '4.8' print "The Selected NDK toolchain version was 4.8 !" elif os.path.isdir(os.path.join(ndk_root,"toolchains/arm-linux-androideabi-4.7")): os.environ['NDK_TOOLCHAIN_VERSION'] = '4.7' print "The Selected NDK toolchain version was 4.7 !" else: print "Couldn't find the gcc toolchain." exit(1)
[ "def", "select_toolchain_version", "(", ")", ":", "ndk_root", "=", "check_environment_variables", "(", ")", "if", "os", ".", "path", ".", "isdir", "(", "os", ".", "path", ".", "join", "(", "ndk_root", ",", "\"toolchains/arm-linux-androideabi-4.8\"", ")", ")", ":", "os", ".", "environ", "[", "'NDK_TOOLCHAIN_VERSION'", "]", "=", "'4.8'", "print", "\"The Selected NDK toolchain version was 4.8 !\"", "elif", "os", ".", "path", ".", "isdir", "(", "os", ".", "path", ".", "join", "(", "ndk_root", ",", "\"toolchains/arm-linux-androideabi-4.7\"", ")", ")", ":", "os", ".", "environ", "[", "'NDK_TOOLCHAIN_VERSION'", "]", "=", "'4.7'", "print", "\"The Selected NDK toolchain version was 4.7 !\"", "else", ":", "print", "\"Couldn't find the gcc toolchain.\"", "exit", "(", "1", ")" ]
https://github.com/linyouhappy/kongkongxiyou/blob/7a69b2913eb29f4be77f9a62fb90cdd72c4160f1/cocosjs/frameworks/cocos2d-x/plugin/tools/android-build.py#L25-L42
grpc/grpc
27bc6fe7797e43298dc931b96dc57322d0852a9f
src/python/grpcio/grpc/_channel.py
python
_MultiThreadedRendezvous.trailing_metadata
(self)
See grpc.Call.trailing_metadata
See grpc.Call.trailing_metadata
[ "See", "grpc", ".", "Call", ".", "trailing_metadata" ]
def trailing_metadata(self): """See grpc.Call.trailing_metadata""" with self._state.condition: def _done(): return self._state.trailing_metadata is not None _common.wait(self._state.condition.wait, _done) return self._state.trailing_metadata
[ "def", "trailing_metadata", "(", "self", ")", ":", "with", "self", ".", "_state", ".", "condition", ":", "def", "_done", "(", ")", ":", "return", "self", ".", "_state", ".", "trailing_metadata", "is", "not", "None", "_common", ".", "wait", "(", "self", ".", "_state", ".", "condition", ".", "wait", ",", "_done", ")", "return", "self", ".", "_state", ".", "trailing_metadata" ]
https://github.com/grpc/grpc/blob/27bc6fe7797e43298dc931b96dc57322d0852a9f/src/python/grpcio/grpc/_channel.py#L673-L681
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/contrib/keras/python/keras/backend.py
python
repeat_elements
(x, rep, axis)
return concatenate(x_rep, axis)
Repeats the elements of a tensor along an axis, like `np.repeat`. If `x` has shape `(s1, s2, s3)` and `axis` is `1`, the output will have shape `(s1, s2 * rep, s3)`. Arguments: x: Tensor or variable. rep: Python integer, number of times to repeat. axis: Axis along which to repeat. Raises: ValueError: In case `x.shape[axis]` is undefined. Returns: A tensor.
Repeats the elements of a tensor along an axis, like `np.repeat`.
[ "Repeats", "the", "elements", "of", "a", "tensor", "along", "an", "axis", "like", "np", ".", "repeat", "." ]
def repeat_elements(x, rep, axis): """Repeats the elements of a tensor along an axis, like `np.repeat`. If `x` has shape `(s1, s2, s3)` and `axis` is `1`, the output will have shape `(s1, s2 * rep, s3)`. Arguments: x: Tensor or variable. rep: Python integer, number of times to repeat. axis: Axis along which to repeat. Raises: ValueError: In case `x.shape[axis]` is undefined. Returns: A tensor. """ x_shape = x.get_shape().as_list() if x_shape[axis] is None: raise ValueError('Axis ' + str(axis) + ' of input tensor ' 'should have a defined dimension, but is None. ' 'Full tensor shape: ' + str(tuple(x_shape)) + '. ' 'Typically you need to pass a fully-defined ' '`input_shape` argument to your first layer.') # slices along the repeat axis splits = array_ops.split(value=x, num_or_size_splits=x_shape[axis], axis=axis) # repeat each slice the given number of reps x_rep = [s for s in splits for _ in range(rep)] return concatenate(x_rep, axis)
[ "def", "repeat_elements", "(", "x", ",", "rep", ",", "axis", ")", ":", "x_shape", "=", "x", ".", "get_shape", "(", ")", ".", "as_list", "(", ")", "if", "x_shape", "[", "axis", "]", "is", "None", ":", "raise", "ValueError", "(", "'Axis '", "+", "str", "(", "axis", ")", "+", "' of input tensor '", "'should have a defined dimension, but is None. '", "'Full tensor shape: '", "+", "str", "(", "tuple", "(", "x_shape", ")", ")", "+", "'. '", "'Typically you need to pass a fully-defined '", "'`input_shape` argument to your first layer.'", ")", "# slices along the repeat axis", "splits", "=", "array_ops", ".", "split", "(", "value", "=", "x", ",", "num_or_size_splits", "=", "x_shape", "[", "axis", "]", ",", "axis", "=", "axis", ")", "# repeat each slice the given number of reps", "x_rep", "=", "[", "s", "for", "s", "in", "splits", "for", "_", "in", "range", "(", "rep", ")", "]", "return", "concatenate", "(", "x_rep", ",", "axis", ")" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/keras/python/keras/backend.py#L1984-L2012
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/lite/tutorials/dataset.py
python
download
(directory, filename)
return filepath
Download (and unzip) a file from the MNIST dataset if not already done.
Download (and unzip) a file from the MNIST dataset if not already done.
[ "Download", "(", "and", "unzip", ")", "a", "file", "from", "the", "MNIST", "dataset", "if", "not", "already", "done", "." ]
def download(directory, filename): """Download (and unzip) a file from the MNIST dataset if not already done.""" filepath = os.path.join(directory, filename) if tf.gfile.Exists(filepath): return filepath if not tf.gfile.Exists(directory): tf.gfile.MakeDirs(directory) # CVDF mirror of http://yann.lecun.com/exdb/mnist/ url = 'https://storage.googleapis.com/cvdf-datasets/mnist/' + filename + '.gz' _, zipped_filepath = tempfile.mkstemp(suffix='.gz') print('Downloading %s to %s' % (url, zipped_filepath)) urllib.request.urlretrieve(url, zipped_filepath) with gzip.open(zipped_filepath, 'rb') as f_in, \ tf.gfile.Open(filepath, 'wb') as f_out: shutil.copyfileobj(f_in, f_out) os.remove(zipped_filepath) return filepath
[ "def", "download", "(", "directory", ",", "filename", ")", ":", "filepath", "=", "os", ".", "path", ".", "join", "(", "directory", ",", "filename", ")", "if", "tf", ".", "gfile", ".", "Exists", "(", "filepath", ")", ":", "return", "filepath", "if", "not", "tf", ".", "gfile", ".", "Exists", "(", "directory", ")", ":", "tf", ".", "gfile", ".", "MakeDirs", "(", "directory", ")", "# CVDF mirror of http://yann.lecun.com/exdb/mnist/", "url", "=", "'https://storage.googleapis.com/cvdf-datasets/mnist/'", "+", "filename", "+", "'.gz'", "_", ",", "zipped_filepath", "=", "tempfile", ".", "mkstemp", "(", "suffix", "=", "'.gz'", ")", "print", "(", "'Downloading %s to %s'", "%", "(", "url", ",", "zipped_filepath", ")", ")", "urllib", ".", "request", ".", "urlretrieve", "(", "url", ",", "zipped_filepath", ")", "with", "gzip", ".", "open", "(", "zipped_filepath", ",", "'rb'", ")", "as", "f_in", ",", "tf", ".", "gfile", ".", "Open", "(", "filepath", ",", "'wb'", ")", "as", "f_out", ":", "shutil", ".", "copyfileobj", "(", "f_in", ",", "f_out", ")", "os", ".", "remove", "(", "zipped_filepath", ")", "return", "filepath" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/lite/tutorials/dataset.py#L67-L83
Polidea/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py
python
SBTarget.BreakpointCreateByAddress
(self, *args)
return _lldb.SBTarget_BreakpointCreateByAddress(self, *args)
BreakpointCreateByAddress(self, addr_t address) -> SBBreakpoint
BreakpointCreateByAddress(self, addr_t address) -> SBBreakpoint
[ "BreakpointCreateByAddress", "(", "self", "addr_t", "address", ")", "-", ">", "SBBreakpoint" ]
def BreakpointCreateByAddress(self, *args): """BreakpointCreateByAddress(self, addr_t address) -> SBBreakpoint""" return _lldb.SBTarget_BreakpointCreateByAddress(self, *args)
[ "def", "BreakpointCreateByAddress", "(", "self", ",", "*", "args", ")", ":", "return", "_lldb", ".", "SBTarget_BreakpointCreateByAddress", "(", "self", ",", "*", "args", ")" ]
https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L9125-L9127
smilehao/xlua-framework
a03801538be2b0e92d39332d445b22caca1ef61f
ConfigData/trunk/tools/protobuf-2.5.0/protobuf-2.5.0/python/mox.py
python
And.__init__
(self, *args)
Initialize. Args: *args: One or more Comparator
Initialize.
[ "Initialize", "." ]
def __init__(self, *args): """Initialize. Args: *args: One or more Comparator """ self._comparators = args
[ "def", "__init__", "(", "self", ",", "*", "args", ")", ":", "self", ".", "_comparators", "=", "args" ]
https://github.com/smilehao/xlua-framework/blob/a03801538be2b0e92d39332d445b22caca1ef61f/ConfigData/trunk/tools/protobuf-2.5.0/protobuf-2.5.0/python/mox.py#L1050-L1057
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/setuptools/_vendor/pyparsing.py
python
ParserElement.validate
( self, validateTrace=[] )
Check defined expressions for valid structure, check for infinite recursive definitions.
Check defined expressions for valid structure, check for infinite recursive definitions.
[ "Check", "defined", "expressions", "for", "valid", "structure", "check", "for", "infinite", "recursive", "definitions", "." ]
def validate( self, validateTrace=[] ): """ Check defined expressions for valid structure, check for infinite recursive definitions. """ self.checkRecursion( [] )
[ "def", "validate", "(", "self", ",", "validateTrace", "=", "[", "]", ")", ":", "self", ".", "checkRecursion", "(", "[", "]", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/setuptools/_vendor/pyparsing.py#L2167-L2171
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/timeit.py
python
Timer.__init__
(self, stmt="pass", setup="pass", timer=default_timer)
Constructor. See class doc string.
Constructor. See class doc string.
[ "Constructor", ".", "See", "class", "doc", "string", "." ]
def __init__(self, stmt="pass", setup="pass", timer=default_timer): """Constructor. See class doc string.""" self.timer = timer ns = {} if isinstance(stmt, basestring): stmt = reindent(stmt, 8) if isinstance(setup, basestring): setup = reindent(setup, 4) src = template % {'stmt': stmt, 'setup': setup} elif hasattr(setup, '__call__'): src = template % {'stmt': stmt, 'setup': '_setup()'} ns['_setup'] = setup else: raise ValueError("setup is neither a string nor callable") self.src = src # Save for traceback display code = compile(src, dummy_src_name, "exec") exec code in globals(), ns self.inner = ns["inner"] elif hasattr(stmt, '__call__'): self.src = None if isinstance(setup, basestring): _setup = setup def setup(): exec _setup in globals(), ns elif not hasattr(setup, '__call__'): raise ValueError("setup is neither a string nor callable") self.inner = _template_func(setup, stmt) else: raise ValueError("stmt is neither a string nor callable")
[ "def", "__init__", "(", "self", ",", "stmt", "=", "\"pass\"", ",", "setup", "=", "\"pass\"", ",", "timer", "=", "default_timer", ")", ":", "self", ".", "timer", "=", "timer", "ns", "=", "{", "}", "if", "isinstance", "(", "stmt", ",", "basestring", ")", ":", "stmt", "=", "reindent", "(", "stmt", ",", "8", ")", "if", "isinstance", "(", "setup", ",", "basestring", ")", ":", "setup", "=", "reindent", "(", "setup", ",", "4", ")", "src", "=", "template", "%", "{", "'stmt'", ":", "stmt", ",", "'setup'", ":", "setup", "}", "elif", "hasattr", "(", "setup", ",", "'__call__'", ")", ":", "src", "=", "template", "%", "{", "'stmt'", ":", "stmt", ",", "'setup'", ":", "'_setup()'", "}", "ns", "[", "'_setup'", "]", "=", "setup", "else", ":", "raise", "ValueError", "(", "\"setup is neither a string nor callable\"", ")", "self", ".", "src", "=", "src", "# Save for traceback display", "code", "=", "compile", "(", "src", ",", "dummy_src_name", ",", "\"exec\"", ")", "exec", "code", "in", "globals", "(", ")", ",", "ns", "self", ".", "inner", "=", "ns", "[", "\"inner\"", "]", "elif", "hasattr", "(", "stmt", ",", "'__call__'", ")", ":", "self", ".", "src", "=", "None", "if", "isinstance", "(", "setup", ",", "basestring", ")", ":", "_setup", "=", "setup", "def", "setup", "(", ")", ":", "exec", "_setup", "in", "globals", "(", ")", ",", "ns", "elif", "not", "hasattr", "(", "setup", ",", "'__call__'", ")", ":", "raise", "ValueError", "(", "\"setup is neither a string nor callable\"", ")", "self", ".", "inner", "=", "_template_func", "(", "setup", ",", "stmt", ")", "else", ":", "raise", "ValueError", "(", "\"stmt is neither a string nor callable\"", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/timeit.py#L121-L149
google/mediapipe
e6c19885c6d3c6f410c730952aeed2852790d306
mediapipe/python/solutions/selfie_segmentation.py
python
SelfieSegmentation.process
(self, image: np.ndarray)
return super().process(input_data={'image': image})
Processes an RGB image and returns a segmentation mask. Args: image: An RGB image represented as a numpy ndarray. Raises: RuntimeError: If the underlying graph throws any error. ValueError: If the input image is not three channel RGB. Returns: A NamedTuple object with a "segmentation_mask" field that contains a float type 2d np array representing the mask.
Processes an RGB image and returns a segmentation mask.
[ "Processes", "an", "RGB", "image", "and", "returns", "a", "segmentation", "mask", "." ]
def process(self, image: np.ndarray) -> NamedTuple: """Processes an RGB image and returns a segmentation mask. Args: image: An RGB image represented as a numpy ndarray. Raises: RuntimeError: If the underlying graph throws any error. ValueError: If the input image is not three channel RGB. Returns: A NamedTuple object with a "segmentation_mask" field that contains a float type 2d np array representing the mask. """ return super().process(input_data={'image': image})
[ "def", "process", "(", "self", ",", "image", ":", "np", ".", "ndarray", ")", "->", "NamedTuple", ":", "return", "super", "(", ")", ".", "process", "(", "input_data", "=", "{", "'image'", ":", "image", "}", ")" ]
https://github.com/google/mediapipe/blob/e6c19885c6d3c6f410c730952aeed2852790d306/mediapipe/python/solutions/selfie_segmentation.py#L61-L76
root-project/root
fcd3583bb14852bf2e8cd2415717cbaac0e75896
bindings/pyroot/pythonizations/python/ROOT/_pythonization/_rdataframe.py
python
AsNumpyResult.__init__
(self, result_ptrs, columns)
Constructs an AsNumpyResult object. Parameters: result_ptrs (dict): results of the AsNumpy action. The key is the column name, the value is the result pointer for that column. columns (list): list of the names of the columns returned by AsNumpy.
Constructs an AsNumpyResult object.
[ "Constructs", "an", "AsNumpyResult", "object", "." ]
def __init__(self, result_ptrs, columns): """Constructs an AsNumpyResult object. Parameters: result_ptrs (dict): results of the AsNumpy action. The key is the column name, the value is the result pointer for that column. columns (list): list of the names of the columns returned by AsNumpy. """ self._result_ptrs = result_ptrs self._columns = columns self._py_arrays = None
[ "def", "__init__", "(", "self", ",", "result_ptrs", ",", "columns", ")", ":", "self", ".", "_result_ptrs", "=", "result_ptrs", "self", ".", "_columns", "=", "columns", "self", ".", "_py_arrays", "=", "None" ]
https://github.com/root-project/root/blob/fcd3583bb14852bf2e8cd2415717cbaac0e75896/bindings/pyroot/pythonizations/python/ROOT/_pythonization/_rdataframe.py#L268-L280
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/llvmlite/ir/builder.py
python
IRBuilder.and_
(self, lhs, rhs, name='')
Bitwise integer AND: name = lhs & rhs
Bitwise integer AND: name = lhs & rhs
[ "Bitwise", "integer", "AND", ":", "name", "=", "lhs", "&", "rhs" ]
def and_(self, lhs, rhs, name=''): """ Bitwise integer AND: name = lhs & rhs """
[ "def", "and_", "(", "self", ",", "lhs", ",", "rhs", ",", "name", "=", "''", ")", ":" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/llvmlite/ir/builder.py#L451-L455
devsisters/libquic
8954789a056d8e7d5fcb6452fd1572ca57eb5c4e
src/third_party/protobuf/python/google/protobuf/internal/well_known_types.py
python
Duration.ToJsonString
(self)
return result + '.%09ds' % nanos
Converts Duration to string format. Returns: A string converted from self. The string format will contains 3, 6, or 9 fractional digits depending on the precision required to represent the exact Duration value. For example: "1s", "1.010s", "1.000000100s", "-3.100s"
Converts Duration to string format.
[ "Converts", "Duration", "to", "string", "format", "." ]
def ToJsonString(self): """Converts Duration to string format. Returns: A string converted from self. The string format will contains 3, 6, or 9 fractional digits depending on the precision required to represent the exact Duration value. For example: "1s", "1.010s", "1.000000100s", "-3.100s" """ if self.seconds < 0 or self.nanos < 0: result = '-' seconds = - self.seconds + int((0 - self.nanos) // 1e9) nanos = (0 - self.nanos) % 1e9 else: result = '' seconds = self.seconds + int(self.nanos // 1e9) nanos = self.nanos % 1e9 result += '%d' % seconds if (nanos % 1e9) == 0: # If there are 0 fractional digits, the fractional # point '.' should be omitted when serializing. return result + 's' if (nanos % 1e6) == 0: # Serialize 3 fractional digits. return result + '.%03ds' % (nanos / 1e6) if (nanos % 1e3) == 0: # Serialize 6 fractional digits. return result + '.%06ds' % (nanos / 1e3) # Serialize 9 fractional digits. return result + '.%09ds' % nanos
[ "def", "ToJsonString", "(", "self", ")", ":", "if", "self", ".", "seconds", "<", "0", "or", "self", ".", "nanos", "<", "0", ":", "result", "=", "'-'", "seconds", "=", "-", "self", ".", "seconds", "+", "int", "(", "(", "0", "-", "self", ".", "nanos", ")", "//", "1e9", ")", "nanos", "=", "(", "0", "-", "self", ".", "nanos", ")", "%", "1e9", "else", ":", "result", "=", "''", "seconds", "=", "self", ".", "seconds", "+", "int", "(", "self", ".", "nanos", "//", "1e9", ")", "nanos", "=", "self", ".", "nanos", "%", "1e9", "result", "+=", "'%d'", "%", "seconds", "if", "(", "nanos", "%", "1e9", ")", "==", "0", ":", "# If there are 0 fractional digits, the fractional", "# point '.' should be omitted when serializing.", "return", "result", "+", "'s'", "if", "(", "nanos", "%", "1e6", ")", "==", "0", ":", "# Serialize 3 fractional digits.", "return", "result", "+", "'.%03ds'", "%", "(", "nanos", "/", "1e6", ")", "if", "(", "nanos", "%", "1e3", ")", "==", "0", ":", "# Serialize 6 fractional digits.", "return", "result", "+", "'.%06ds'", "%", "(", "nanos", "/", "1e3", ")", "# Serialize 9 fractional digits.", "return", "result", "+", "'.%09ds'", "%", "nanos" ]
https://github.com/devsisters/libquic/blob/8954789a056d8e7d5fcb6452fd1572ca57eb5c4e/src/third_party/protobuf/python/google/protobuf/internal/well_known_types.py#L241-L270
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/distutils/command/install.py
python
install.has_scripts
(self)
return self.distribution.has_scripts()
Returns true if the current distribution has any scripts to. install.
Returns true if the current distribution has any scripts to. install.
[ "Returns", "true", "if", "the", "current", "distribution", "has", "any", "scripts", "to", ".", "install", "." ]
def has_scripts(self): """Returns true if the current distribution has any scripts to. install.""" return self.distribution.has_scripts()
[ "def", "has_scripts", "(", "self", ")", ":", "return", "self", ".", "distribution", ".", "has_scripts", "(", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/distutils/command/install.py#L639-L642
kushview/Element
1cc16380caa2ab79461246ba758b9de1f46db2a5
waflib/extras/sphinx.py
python
configure
(cnf)
Check if sphinx-build program is available and loads gnu_dirs tool.
Check if sphinx-build program is available and loads gnu_dirs tool.
[ "Check", "if", "sphinx", "-", "build", "program", "is", "available", "and", "loads", "gnu_dirs", "tool", "." ]
def configure(cnf): """Check if sphinx-build program is available and loads gnu_dirs tool.""" cnf.find_program('sphinx-build', var='SPHINX_BUILD', mandatory=False) cnf.load('gnu_dirs')
[ "def", "configure", "(", "cnf", ")", ":", "cnf", ".", "find_program", "(", "'sphinx-build'", ",", "var", "=", "'SPHINX_BUILD'", ",", "mandatory", "=", "False", ")", "cnf", ".", "load", "(", "'gnu_dirs'", ")" ]
https://github.com/kushview/Element/blob/1cc16380caa2ab79461246ba758b9de1f46db2a5/waflib/extras/sphinx.py#L27-L30
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_gdi.py
python
DC.DrawRoundedRectangle
(*args, **kwargs)
return _gdi_.DC_DrawRoundedRectangle(*args, **kwargs)
DrawRoundedRectangle(self, int x, int y, int width, int height, double radius) Draws a rectangle with the given top left corner, and with the given size. The corners are quarter-circles using the given radius. The current pen is used for the outline and the current brush for filling the shape. If radius is positive, the value is assumed to be the radius of the rounded corner. If radius is negative, the absolute value is assumed to be the proportion of the smallest dimension of the rectangle. This means that the corner can be a sensible size relative to the size of the rectangle, and also avoids the strange effects X produces when the corners are too big for the rectangle.
DrawRoundedRectangle(self, int x, int y, int width, int height, double radius)
[ "DrawRoundedRectangle", "(", "self", "int", "x", "int", "y", "int", "width", "int", "height", "double", "radius", ")" ]
def DrawRoundedRectangle(*args, **kwargs): """ DrawRoundedRectangle(self, int x, int y, int width, int height, double radius) Draws a rectangle with the given top left corner, and with the given size. The corners are quarter-circles using the given radius. The current pen is used for the outline and the current brush for filling the shape. If radius is positive, the value is assumed to be the radius of the rounded corner. If radius is negative, the absolute value is assumed to be the proportion of the smallest dimension of the rectangle. This means that the corner can be a sensible size relative to the size of the rectangle, and also avoids the strange effects X produces when the corners are too big for the rectangle. """ return _gdi_.DC_DrawRoundedRectangle(*args, **kwargs)
[ "def", "DrawRoundedRectangle", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gdi_", ".", "DC_DrawRoundedRectangle", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_gdi.py#L3665-L3681
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/ros_comm/roslaunch/src/roslaunch/config.py
python
ROSLaunchConfig.add_machine
(self, m, verbose=True)
Declare a machine and associated parameters so that it can be used for running nodes. @param m: machine instance @type m: L{Machine} @return: True if new machine added, False if machine already specified. @rtype: bool @raises RLException: if cannot add machine as specified
Declare a machine and associated parameters so that it can be used for running nodes.
[ "Declare", "a", "machine", "and", "associated", "parameters", "so", "that", "it", "can", "be", "used", "for", "running", "nodes", "." ]
def add_machine(self, m, verbose=True): """ Declare a machine and associated parameters so that it can be used for running nodes. @param m: machine instance @type m: L{Machine} @return: True if new machine added, False if machine already specified. @rtype: bool @raises RLException: if cannot add machine as specified """ name = m.name # Fuerte: all machines must have an env loader. We can guess # it from the distro name for easier migration. if not m.env_loader: m.env_loader = calculate_env_loader() if m.address == 'localhost': #simplify address comparison address = rosgraph.network.get_local_address() self.logger.info("addMachine[%s]: remapping localhost address to %s"%(name, address)) if name in self.machines: if m != self.machines[name]: raise RLException("Machine [%s] already added and does not match duplicate entry"%name) return False else: self.machines[name] = m if verbose: print("Added machine [%s]" % name) return True
[ "def", "add_machine", "(", "self", ",", "m", ",", "verbose", "=", "True", ")", ":", "name", "=", "m", ".", "name", "# Fuerte: all machines must have an env loader. We can guess", "# it from the distro name for easier migration.", "if", "not", "m", ".", "env_loader", ":", "m", ".", "env_loader", "=", "calculate_env_loader", "(", ")", "if", "m", ".", "address", "==", "'localhost'", ":", "#simplify address comparison", "address", "=", "rosgraph", ".", "network", ".", "get_local_address", "(", ")", "self", ".", "logger", ".", "info", "(", "\"addMachine[%s]: remapping localhost address to %s\"", "%", "(", "name", ",", "address", ")", ")", "if", "name", "in", "self", ".", "machines", ":", "if", "m", "!=", "self", ".", "machines", "[", "name", "]", ":", "raise", "RLException", "(", "\"Machine [%s] already added and does not match duplicate entry\"", "%", "name", ")", "return", "False", "else", ":", "self", ".", "machines", "[", "name", "]", "=", "m", "if", "verbose", ":", "print", "(", "\"Added machine [%s]\"", "%", "name", ")", "return", "True" ]
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/ros_comm/roslaunch/src/roslaunch/config.py#L321-L347
Ewenwan/MVision
97b394dfa48cb21c82cd003b1a952745e413a17f
CNN/ShuffleNet/layers.py
python
conv2d
(name, x, w=None, num_filters=16, kernel_size=(3, 3), padding='SAME', stride=(1, 1), initializer=tf.contrib.layers.xavier_initializer(), l2_strength=0.0, bias=0.0, activation=None, batchnorm_enabled=False, max_pool_enabled=False, dropout_keep_prob=-1, is_training=True)
return conv_o
This block is responsible for a convolution 2D layer followed by optional (non-linearity, dropout, max-pooling). Note that: "is_training" should be passed by a correct value based on being in either training or testing. :param name: (string) The name scope provided by the upper tf.name_scope('name') as scope. :param x: (tf.tensor) The input to the layer (N, H, W, C). :param num_filters: (integer) No. of filters (This is the output depth) :param kernel_size: (integer tuple) The size of the convolving kernel. :param padding: (string) The amount of padding required. :param stride: (integer tuple) The stride required. :param initializer: (tf.contrib initializer) The initialization scheme, He et al. normal or Xavier normal are recommended. :param l2_strength:(weight decay) (float) L2 regularization parameter. :param bias: (float) Amount of bias. :param activation: (tf.graph operator) The activation function applied after the convolution operation. If None, linear is applied. :param batchnorm_enabled: (boolean) for enabling batch normalization. :param max_pool_enabled: (boolean) for enabling max-pooling 2x2 to decrease width and height by a factor of 2. :param dropout_keep_prob: (float) for the probability of keeping neurons. If equals -1, it means no dropout :param is_training: (boolean) to diff. between training and testing (important for batch normalization and dropout) :return: The output tensor of the layer (N, H', W', C').
This block is responsible for a convolution 2D layer followed by optional (non-linearity, dropout, max-pooling). Note that: "is_training" should be passed by a correct value based on being in either training or testing. :param name: (string) The name scope provided by the upper tf.name_scope('name') as scope. :param x: (tf.tensor) The input to the layer (N, H, W, C). :param num_filters: (integer) No. of filters (This is the output depth) :param kernel_size: (integer tuple) The size of the convolving kernel. :param padding: (string) The amount of padding required. :param stride: (integer tuple) The stride required. :param initializer: (tf.contrib initializer) The initialization scheme, He et al. normal or Xavier normal are recommended. :param l2_strength:(weight decay) (float) L2 regularization parameter. :param bias: (float) Amount of bias. :param activation: (tf.graph operator) The activation function applied after the convolution operation. If None, linear is applied. :param batchnorm_enabled: (boolean) for enabling batch normalization. :param max_pool_enabled: (boolean) for enabling max-pooling 2x2 to decrease width and height by a factor of 2. :param dropout_keep_prob: (float) for the probability of keeping neurons. If equals -1, it means no dropout :param is_training: (boolean) to diff. between training and testing (important for batch normalization and dropout) :return: The output tensor of the layer (N, H', W', C').
[ "This", "block", "is", "responsible", "for", "a", "convolution", "2D", "layer", "followed", "by", "optional", "(", "non", "-", "linearity", "dropout", "max", "-", "pooling", ")", ".", "Note", "that", ":", "is_training", "should", "be", "passed", "by", "a", "correct", "value", "based", "on", "being", "in", "either", "training", "or", "testing", ".", ":", "param", "name", ":", "(", "string", ")", "The", "name", "scope", "provided", "by", "the", "upper", "tf", ".", "name_scope", "(", "name", ")", "as", "scope", ".", ":", "param", "x", ":", "(", "tf", ".", "tensor", ")", "The", "input", "to", "the", "layer", "(", "N", "H", "W", "C", ")", ".", ":", "param", "num_filters", ":", "(", "integer", ")", "No", ".", "of", "filters", "(", "This", "is", "the", "output", "depth", ")", ":", "param", "kernel_size", ":", "(", "integer", "tuple", ")", "The", "size", "of", "the", "convolving", "kernel", ".", ":", "param", "padding", ":", "(", "string", ")", "The", "amount", "of", "padding", "required", ".", ":", "param", "stride", ":", "(", "integer", "tuple", ")", "The", "stride", "required", ".", ":", "param", "initializer", ":", "(", "tf", ".", "contrib", "initializer", ")", "The", "initialization", "scheme", "He", "et", "al", ".", "normal", "or", "Xavier", "normal", "are", "recommended", ".", ":", "param", "l2_strength", ":", "(", "weight", "decay", ")", "(", "float", ")", "L2", "regularization", "parameter", ".", ":", "param", "bias", ":", "(", "float", ")", "Amount", "of", "bias", ".", ":", "param", "activation", ":", "(", "tf", ".", "graph", "operator", ")", "The", "activation", "function", "applied", "after", "the", "convolution", "operation", ".", "If", "None", "linear", "is", "applied", ".", ":", "param", "batchnorm_enabled", ":", "(", "boolean", ")", "for", "enabling", "batch", "normalization", ".", ":", "param", "max_pool_enabled", ":", "(", "boolean", ")", "for", "enabling", "max", "-", "pooling", "2x2", "to", "decrease", "width", "and", "height", "by", "a", "factor", "of", "2", ".", ":", "param", "dropout_keep_prob", ":", "(", "float", ")", "for", "the", "probability", "of", "keeping", "neurons", ".", "If", "equals", "-", "1", "it", "means", "no", "dropout", ":", "param", "is_training", ":", "(", "boolean", ")", "to", "diff", ".", "between", "training", "and", "testing", "(", "important", "for", "batch", "normalization", "and", "dropout", ")", ":", "return", ":", "The", "output", "tensor", "of", "the", "layer", "(", "N", "H", "W", "C", ")", "." ]
def conv2d(name, x, w=None, num_filters=16, kernel_size=(3, 3), padding='SAME', stride=(1, 1), initializer=tf.contrib.layers.xavier_initializer(), l2_strength=0.0, bias=0.0, activation=None, batchnorm_enabled=False, max_pool_enabled=False, dropout_keep_prob=-1, is_training=True): """ This block is responsible for a convolution 2D layer followed by optional (non-linearity, dropout, max-pooling). Note that: "is_training" should be passed by a correct value based on being in either training or testing. :param name: (string) The name scope provided by the upper tf.name_scope('name') as scope. :param x: (tf.tensor) The input to the layer (N, H, W, C). :param num_filters: (integer) No. of filters (This is the output depth) :param kernel_size: (integer tuple) The size of the convolving kernel. :param padding: (string) The amount of padding required. :param stride: (integer tuple) The stride required. :param initializer: (tf.contrib initializer) The initialization scheme, He et al. normal or Xavier normal are recommended. :param l2_strength:(weight decay) (float) L2 regularization parameter. :param bias: (float) Amount of bias. :param activation: (tf.graph operator) The activation function applied after the convolution operation. If None, linear is applied. :param batchnorm_enabled: (boolean) for enabling batch normalization. :param max_pool_enabled: (boolean) for enabling max-pooling 2x2 to decrease width and height by a factor of 2. :param dropout_keep_prob: (float) for the probability of keeping neurons. If equals -1, it means no dropout :param is_training: (boolean) to diff. between training and testing (important for batch normalization and dropout) :return: The output tensor of the layer (N, H', W', C'). """ with tf.variable_scope(name) as scope: # 2d卷积 conv_o_b = __conv2d_p('conv', x=x, w=w, num_filters=num_filters, kernel_size=kernel_size, stride=stride, padding=padding, initializer=initializer, l2_strength=l2_strength, bias=bias) # BN + 激活 if batchnorm_enabled: conv_o_bn = tf.layers.batch_normalization(conv_o_b, training=is_training, epsilon=1e-5) if not activation: conv_a = conv_o_bn else: conv_a = activation(conv_o_bn) else: if not activation: conv_a = conv_o_b else: conv_a = activation(conv_o_b) # droupout 随机失活 def dropout_with_keep(): return tf.nn.dropout(conv_a, dropout_keep_prob) # 全部 激活 def dropout_no_keep(): return tf.nn.dropout(conv_a, 1.0) if dropout_keep_prob != -1: conv_o_dr = tf.cond(is_training, dropout_with_keep, dropout_no_keep) else: conv_o_dr = conv_a conv_o = conv_o_dr # 最大值池化 if max_pool_enabled: conv_o = max_pool_2d(conv_o_dr) return conv_o
[ "def", "conv2d", "(", "name", ",", "x", ",", "w", "=", "None", ",", "num_filters", "=", "16", ",", "kernel_size", "=", "(", "3", ",", "3", ")", ",", "padding", "=", "'SAME'", ",", "stride", "=", "(", "1", ",", "1", ")", ",", "initializer", "=", "tf", ".", "contrib", ".", "layers", ".", "xavier_initializer", "(", ")", ",", "l2_strength", "=", "0.0", ",", "bias", "=", "0.0", ",", "activation", "=", "None", ",", "batchnorm_enabled", "=", "False", ",", "max_pool_enabled", "=", "False", ",", "dropout_keep_prob", "=", "-", "1", ",", "is_training", "=", "True", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", ")", "as", "scope", ":", "# 2d卷积", "conv_o_b", "=", "__conv2d_p", "(", "'conv'", ",", "x", "=", "x", ",", "w", "=", "w", ",", "num_filters", "=", "num_filters", ",", "kernel_size", "=", "kernel_size", ",", "stride", "=", "stride", ",", "padding", "=", "padding", ",", "initializer", "=", "initializer", ",", "l2_strength", "=", "l2_strength", ",", "bias", "=", "bias", ")", "# BN + 激活", "if", "batchnorm_enabled", ":", "conv_o_bn", "=", "tf", ".", "layers", ".", "batch_normalization", "(", "conv_o_b", ",", "training", "=", "is_training", ",", "epsilon", "=", "1e-5", ")", "if", "not", "activation", ":", "conv_a", "=", "conv_o_bn", "else", ":", "conv_a", "=", "activation", "(", "conv_o_bn", ")", "else", ":", "if", "not", "activation", ":", "conv_a", "=", "conv_o_b", "else", ":", "conv_a", "=", "activation", "(", "conv_o_b", ")", "# droupout 随机失活", "def", "dropout_with_keep", "(", ")", ":", "return", "tf", ".", "nn", ".", "dropout", "(", "conv_a", ",", "dropout_keep_prob", ")", "# 全部 激活", "def", "dropout_no_keep", "(", ")", ":", "return", "tf", ".", "nn", ".", "dropout", "(", "conv_a", ",", "1.0", ")", "if", "dropout_keep_prob", "!=", "-", "1", ":", "conv_o_dr", "=", "tf", ".", "cond", "(", "is_training", ",", "dropout_with_keep", ",", "dropout_no_keep", ")", "else", ":", "conv_o_dr", "=", "conv_a", "conv_o", "=", "conv_o_dr", "# 最大值池化", "if", "max_pool_enabled", ":", "conv_o", "=", "max_pool_2d", "(", "conv_o_dr", ")", "return", "conv_o" ]
https://github.com/Ewenwan/MVision/blob/97b394dfa48cb21c82cd003b1a952745e413a17f/CNN/ShuffleNet/layers.py#L60-L118
Polidea/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py
python
SBBlock.GetInlinedCallSiteLine
(self)
return _lldb.SBBlock_GetInlinedCallSiteLine(self)
GetInlinedCallSiteLine(self) -> uint32_t Get the call site line if this block represents an inlined function; otherwise, return 0.
GetInlinedCallSiteLine(self) -> uint32_t
[ "GetInlinedCallSiteLine", "(", "self", ")", "-", ">", "uint32_t" ]
def GetInlinedCallSiteLine(self): """ GetInlinedCallSiteLine(self) -> uint32_t Get the call site line if this block represents an inlined function; otherwise, return 0. """ return _lldb.SBBlock_GetInlinedCallSiteLine(self)
[ "def", "GetInlinedCallSiteLine", "(", "self", ")", ":", "return", "_lldb", ".", "SBBlock_GetInlinedCallSiteLine", "(", "self", ")" ]
https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L1203-L1210
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/xml/sax/handler.py
python
ContentHandler.startDocument
(self)
Receive notification of the beginning of a document. The SAX parser will invoke this method only once, before any other methods in this interface or in DTDHandler (except for setDocumentLocator).
Receive notification of the beginning of a document.
[ "Receive", "notification", "of", "the", "beginning", "of", "a", "document", "." ]
def startDocument(self): """Receive notification of the beginning of a document. The SAX parser will invoke this method only once, before any other methods in this interface or in DTDHandler (except for setDocumentLocator)."""
[ "def", "startDocument", "(", "self", ")", ":" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/xml/sax/handler.py#L80-L85
llvm/llvm-project
ffa6262cb4e2a335d26416fad39a581b4f98c5f4
bolt/utils/llvm-bolt-wrapper.py
python
parse_cmp_offset
(cmp_out)
return int(re.search(r'byte (\d+),', cmp_out).groups()[0])
Extracts byte number from cmp output: file1 file2 differ: byte X, line Y
Extracts byte number from cmp output: file1 file2 differ: byte X, line Y
[ "Extracts", "byte", "number", "from", "cmp", "output", ":", "file1", "file2", "differ", ":", "byte", "X", "line", "Y" ]
def parse_cmp_offset(cmp_out): ''' Extracts byte number from cmp output: file1 file2 differ: byte X, line Y ''' return int(re.search(r'byte (\d+),', cmp_out).groups()[0])
[ "def", "parse_cmp_offset", "(", "cmp_out", ")", ":", "return", "int", "(", "re", ".", "search", "(", "r'byte (\\d+),'", ",", "cmp_out", ")", ".", "groups", "(", ")", "[", "0", "]", ")" ]
https://github.com/llvm/llvm-project/blob/ffa6262cb4e2a335d26416fad39a581b4f98c5f4/bolt/utils/llvm-bolt-wrapper.py#L204-L209
hcdth011/ROS-Hydro-SLAM
629448eecd2c9a3511158115fa53ea9e4ae41359
rpg_svo/svo_analysis/src/svo_analysis/tum_benchmark_tools/evaluate_ate.py
python
plot_traj
(ax,stamps,traj,style,color,label)
Plot a trajectory using matplotlib. Input: ax -- the plot stamps -- time stamps (1xn) traj -- trajectory (3xn) style -- line style color -- line color label -- plot legend
Plot a trajectory using matplotlib. Input: ax -- the plot stamps -- time stamps (1xn) traj -- trajectory (3xn) style -- line style color -- line color label -- plot legend
[ "Plot", "a", "trajectory", "using", "matplotlib", ".", "Input", ":", "ax", "--", "the", "plot", "stamps", "--", "time", "stamps", "(", "1xn", ")", "traj", "--", "trajectory", "(", "3xn", ")", "style", "--", "line", "style", "color", "--", "line", "color", "label", "--", "plot", "legend" ]
def plot_traj(ax,stamps,traj,style,color,label): """ Plot a trajectory using matplotlib. Input: ax -- the plot stamps -- time stamps (1xn) traj -- trajectory (3xn) style -- line style color -- line color label -- plot legend """ stamps.sort() interval = numpy.median([s-t for s,t in zip(stamps[1:],stamps[:-1])]) x = [] y = [] last = stamps[0] for i in range(len(stamps)): if stamps[i]-last < 2*interval: x.append(traj[i][0]) y.append(traj[i][1]) elif len(x)>0: ax.plot(x,y,style,color=color,label=label) label="" x=[] y=[] last= stamps[i] if len(x)>0: ax.plot(x,y,style,color=color,label=label)
[ "def", "plot_traj", "(", "ax", ",", "stamps", ",", "traj", ",", "style", ",", "color", ",", "label", ")", ":", "stamps", ".", "sort", "(", ")", "interval", "=", "numpy", ".", "median", "(", "[", "s", "-", "t", "for", "s", ",", "t", "in", "zip", "(", "stamps", "[", "1", ":", "]", ",", "stamps", "[", ":", "-", "1", "]", ")", "]", ")", "x", "=", "[", "]", "y", "=", "[", "]", "last", "=", "stamps", "[", "0", "]", "for", "i", "in", "range", "(", "len", "(", "stamps", ")", ")", ":", "if", "stamps", "[", "i", "]", "-", "last", "<", "2", "*", "interval", ":", "x", ".", "append", "(", "traj", "[", "i", "]", "[", "0", "]", ")", "y", ".", "append", "(", "traj", "[", "i", "]", "[", "1", "]", ")", "elif", "len", "(", "x", ")", ">", "0", ":", "ax", ".", "plot", "(", "x", ",", "y", ",", "style", ",", "color", "=", "color", ",", "label", "=", "label", ")", "label", "=", "\"\"", "x", "=", "[", "]", "y", "=", "[", "]", "last", "=", "stamps", "[", "i", "]", "if", "len", "(", "x", ")", ">", "0", ":", "ax", ".", "plot", "(", "x", ",", "y", ",", "style", ",", "color", "=", "color", ",", "label", "=", "label", ")" ]
https://github.com/hcdth011/ROS-Hydro-SLAM/blob/629448eecd2c9a3511158115fa53ea9e4ae41359/rpg_svo/svo_analysis/src/svo_analysis/tum_benchmark_tools/evaluate_ate.py#L81-L110
mhammond/pywin32
44afd86ba8485194df93234639243252deeb40d5
win32/Lib/win32timezone.py
python
TimeZoneInfo.getWinInfo
(self, targetYear)
return self.dynamicInfo.get(targetYear, self.dynamicInfo[RangeMap.last_item])
Return the most relevant "info" for this time zone in the target year.
Return the most relevant "info" for this time zone in the target year.
[ "Return", "the", "most", "relevant", "info", "for", "this", "time", "zone", "in", "the", "target", "year", "." ]
def getWinInfo(self, targetYear): """ Return the most relevant "info" for this time zone in the target year. """ if not hasattr(self, "dynamicInfo") or not self.dynamicInfo: return self.staticInfo # Find the greatest year entry in self.dynamicInfo which is for # a year greater than or equal to our targetYear. If not found, # default to the earliest year. return self.dynamicInfo.get(targetYear, self.dynamicInfo[RangeMap.last_item])
[ "def", "getWinInfo", "(", "self", ",", "targetYear", ")", ":", "if", "not", "hasattr", "(", "self", ",", "\"dynamicInfo\"", ")", "or", "not", "self", ".", "dynamicInfo", ":", "return", "self", ".", "staticInfo", "# Find the greatest year entry in self.dynamicInfo which is for", "# a year greater than or equal to our targetYear. If not found,", "# default to the earliest year.", "return", "self", ".", "dynamicInfo", ".", "get", "(", "targetYear", ",", "self", ".", "dynamicInfo", "[", "RangeMap", ".", "last_item", "]", ")" ]
https://github.com/mhammond/pywin32/blob/44afd86ba8485194df93234639243252deeb40d5/win32/Lib/win32timezone.py#L603-L613
kamyu104/LeetCode-Solutions
77605708a927ea3b85aee5a479db733938c7c211
Python/maximum-number-of-events-that-can-be-attended-ii.py
python
Solution.maxValue
(self, events, k)
return dp[-1][-1]
:type events: List[List[int]] :type k: int :rtype: int
:type events: List[List[int]] :type k: int :rtype: int
[ ":", "type", "events", ":", "List", "[", "List", "[", "int", "]]", ":", "type", "k", ":", "int", ":", "rtype", ":", "int" ]
def maxValue(self, events, k): """ :type events: List[List[int]] :type k: int :rtype: int """ events.sort(key=lambda x: x[1]) sorted_ends = [x[1] for x in events] dp = [[0]*(k+1) for _ in xrange(len(events)+1)] for i in xrange(1, len(events)+1): prev_i_m_1 = bisect.bisect_left(sorted_ends, events[i-1][0])-1 for j in xrange(1, k+1): dp[i][j] = max(dp[i-1][j], dp[prev_i_m_1+1][j-1]+events[i-1][2]) return dp[-1][-1]
[ "def", "maxValue", "(", "self", ",", "events", ",", "k", ")", ":", "events", ".", "sort", "(", "key", "=", "lambda", "x", ":", "x", "[", "1", "]", ")", "sorted_ends", "=", "[", "x", "[", "1", "]", "for", "x", "in", "events", "]", "dp", "=", "[", "[", "0", "]", "*", "(", "k", "+", "1", ")", "for", "_", "in", "xrange", "(", "len", "(", "events", ")", "+", "1", ")", "]", "for", "i", "in", "xrange", "(", "1", ",", "len", "(", "events", ")", "+", "1", ")", ":", "prev_i_m_1", "=", "bisect", ".", "bisect_left", "(", "sorted_ends", ",", "events", "[", "i", "-", "1", "]", "[", "0", "]", ")", "-", "1", "for", "j", "in", "xrange", "(", "1", ",", "k", "+", "1", ")", ":", "dp", "[", "i", "]", "[", "j", "]", "=", "max", "(", "dp", "[", "i", "-", "1", "]", "[", "j", "]", ",", "dp", "[", "prev_i_m_1", "+", "1", "]", "[", "j", "-", "1", "]", "+", "events", "[", "i", "-", "1", "]", "[", "2", "]", ")", "return", "dp", "[", "-", "1", "]", "[", "-", "1", "]" ]
https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/maximum-number-of-events-that-can-be-attended-ii.py#L8-L21
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/psutil/_common.py
python
_WrapNumbers.run
(self, input_dict, name)
return new_dict
Cache dict and sum numbers which overflow and wrap. Return an updated copy of `input_dict`
Cache dict and sum numbers which overflow and wrap. Return an updated copy of `input_dict`
[ "Cache", "dict", "and", "sum", "numbers", "which", "overflow", "and", "wrap", ".", "Return", "an", "updated", "copy", "of", "input_dict" ]
def run(self, input_dict, name): """Cache dict and sum numbers which overflow and wrap. Return an updated copy of `input_dict` """ if name not in self.cache: # This was the first call. self._add_dict(input_dict, name) return input_dict self._remove_dead_reminders(input_dict, name) old_dict = self.cache[name] new_dict = {} for key in input_dict.keys(): input_tuple = input_dict[key] try: old_tuple = old_dict[key] except KeyError: # The input dict has a new key (e.g. a new disk or NIC) # which didn't exist in the previous call. new_dict[key] = input_tuple continue bits = [] for i in range(len(input_tuple)): input_value = input_tuple[i] old_value = old_tuple[i] remkey = (key, i) if input_value < old_value: # it wrapped! self.reminders[name][remkey] += old_value self.reminder_keys[name][key].add(remkey) bits.append(input_value + self.reminders[name][remkey]) new_dict[key] = tuple(bits) self.cache[name] = input_dict return new_dict
[ "def", "run", "(", "self", ",", "input_dict", ",", "name", ")", ":", "if", "name", "not", "in", "self", ".", "cache", ":", "# This was the first call.", "self", ".", "_add_dict", "(", "input_dict", ",", "name", ")", "return", "input_dict", "self", ".", "_remove_dead_reminders", "(", "input_dict", ",", "name", ")", "old_dict", "=", "self", ".", "cache", "[", "name", "]", "new_dict", "=", "{", "}", "for", "key", "in", "input_dict", ".", "keys", "(", ")", ":", "input_tuple", "=", "input_dict", "[", "key", "]", "try", ":", "old_tuple", "=", "old_dict", "[", "key", "]", "except", "KeyError", ":", "# The input dict has a new key (e.g. a new disk or NIC)", "# which didn't exist in the previous call.", "new_dict", "[", "key", "]", "=", "input_tuple", "continue", "bits", "=", "[", "]", "for", "i", "in", "range", "(", "len", "(", "input_tuple", ")", ")", ":", "input_value", "=", "input_tuple", "[", "i", "]", "old_value", "=", "old_tuple", "[", "i", "]", "remkey", "=", "(", "key", ",", "i", ")", "if", "input_value", "<", "old_value", ":", "# it wrapped!", "self", ".", "reminders", "[", "name", "]", "[", "remkey", "]", "+=", "old_value", "self", ".", "reminder_keys", "[", "name", "]", "[", "key", "]", ".", "add", "(", "remkey", ")", "bits", ".", "append", "(", "input_value", "+", "self", ".", "reminders", "[", "name", "]", "[", "remkey", "]", ")", "new_dict", "[", "key", "]", "=", "tuple", "(", "bits", ")", "self", ".", "cache", "[", "name", "]", "=", "input_dict", "return", "new_dict" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/psutil/_common.py#L641-L678
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/mailbox.py
python
_singlefileMailbox._post_message_hook
(self, f)
return
Called after writing each message to file f.
Called after writing each message to file f.
[ "Called", "after", "writing", "each", "message", "to", "file", "f", "." ]
def _post_message_hook(self, f): """Called after writing each message to file f.""" return
[ "def", "_post_message_hook", "(", "self", ",", "f", ")", ":", "return" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/mailbox.py#L721-L723
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py2/pandas/core/generic.py
python
NDFrame.describe
(self, percentiles=None, include=None, exclude=None)
return d
Generate descriptive statistics that summarize the central tendency, dispersion and shape of a dataset's distribution, excluding ``NaN`` values. Analyzes both numeric and object series, as well as ``DataFrame`` column sets of mixed data types. The output will vary depending on what is provided. Refer to the notes below for more detail. Parameters ---------- percentiles : list-like of numbers, optional The percentiles to include in the output. All should fall between 0 and 1. The default is ``[.25, .5, .75]``, which returns the 25th, 50th, and 75th percentiles. include : 'all', list-like of dtypes or None (default), optional A white list of data types to include in the result. Ignored for ``Series``. Here are the options: - 'all' : All columns of the input will be included in the output. - A list-like of dtypes : Limits the results to the provided data types. To limit the result to numeric types submit ``numpy.number``. To limit it instead to object columns submit the ``numpy.object`` data type. Strings can also be used in the style of ``select_dtypes`` (e.g. ``df.describe(include=['O'])``). To select pandas categorical columns, use ``'category'`` - None (default) : The result will include all numeric columns. exclude : list-like of dtypes or None (default), optional, A black list of data types to omit from the result. Ignored for ``Series``. Here are the options: - A list-like of dtypes : Excludes the provided data types from the result. To exclude numeric types submit ``numpy.number``. To exclude object columns submit the data type ``numpy.object``. Strings can also be used in the style of ``select_dtypes`` (e.g. ``df.describe(include=['O'])``). To exclude pandas categorical columns, use ``'category'`` - None (default) : The result will exclude nothing. Returns ------- Series or DataFrame Summary statistics of the Series or Dataframe provided. See Also -------- DataFrame.count: Count number of non-NA/null observations. DataFrame.max: Maximum of the values in the object. DataFrame.min: Minimum of the values in the object. DataFrame.mean: Mean of the values. DataFrame.std: Standard deviation of the obersvations. DataFrame.select_dtypes: Subset of a DataFrame including/excluding columns based on their dtype. Notes ----- For numeric data, the result's index will include ``count``, ``mean``, ``std``, ``min``, ``max`` as well as lower, ``50`` and upper percentiles. By default the lower percentile is ``25`` and the upper percentile is ``75``. The ``50`` percentile is the same as the median. For object data (e.g. strings or timestamps), the result's index will include ``count``, ``unique``, ``top``, and ``freq``. The ``top`` is the most common value. The ``freq`` is the most common value's frequency. Timestamps also include the ``first`` and ``last`` items. If multiple object values have the highest count, then the ``count`` and ``top`` results will be arbitrarily chosen from among those with the highest count. For mixed data types provided via a ``DataFrame``, the default is to return only an analysis of numeric columns. If the dataframe consists only of object and categorical data without any numeric columns, the default is to return an analysis of both the object and categorical columns. If ``include='all'`` is provided as an option, the result will include a union of attributes of each type. The `include` and `exclude` parameters can be used to limit which columns in a ``DataFrame`` are analyzed for the output. The parameters are ignored when analyzing a ``Series``. Examples -------- Describing a numeric ``Series``. >>> s = pd.Series([1, 2, 3]) >>> s.describe() count 3.0 mean 2.0 std 1.0 min 1.0 25% 1.5 50% 2.0 75% 2.5 max 3.0 dtype: float64 Describing a categorical ``Series``. >>> s = pd.Series(['a', 'a', 'b', 'c']) >>> s.describe() count 4 unique 3 top a freq 2 dtype: object Describing a timestamp ``Series``. >>> s = pd.Series([ ... np.datetime64("2000-01-01"), ... np.datetime64("2010-01-01"), ... np.datetime64("2010-01-01") ... ]) >>> s.describe() count 3 unique 2 top 2010-01-01 00:00:00 freq 2 first 2000-01-01 00:00:00 last 2010-01-01 00:00:00 dtype: object Describing a ``DataFrame``. By default only numeric fields are returned. >>> df = pd.DataFrame({'categorical': pd.Categorical(['d','e','f']), ... 'numeric': [1, 2, 3], ... 'object': ['a', 'b', 'c'] ... }) >>> df.describe() numeric count 3.0 mean 2.0 std 1.0 min 1.0 25% 1.5 50% 2.0 75% 2.5 max 3.0 Describing all columns of a ``DataFrame`` regardless of data type. >>> df.describe(include='all') categorical numeric object count 3 3.0 3 unique 3 NaN 3 top f NaN c freq 1 NaN 1 mean NaN 2.0 NaN std NaN 1.0 NaN min NaN 1.0 NaN 25% NaN 1.5 NaN 50% NaN 2.0 NaN 75% NaN 2.5 NaN max NaN 3.0 NaN Describing a column from a ``DataFrame`` by accessing it as an attribute. >>> df.numeric.describe() count 3.0 mean 2.0 std 1.0 min 1.0 25% 1.5 50% 2.0 75% 2.5 max 3.0 Name: numeric, dtype: float64 Including only numeric columns in a ``DataFrame`` description. >>> df.describe(include=[np.number]) numeric count 3.0 mean 2.0 std 1.0 min 1.0 25% 1.5 50% 2.0 75% 2.5 max 3.0 Including only string columns in a ``DataFrame`` description. >>> df.describe(include=[np.object]) object count 3 unique 3 top c freq 1 Including only categorical columns from a ``DataFrame`` description. >>> df.describe(include=['category']) categorical count 3 unique 3 top f freq 1 Excluding numeric columns from a ``DataFrame`` description. >>> df.describe(exclude=[np.number]) categorical object count 3 3 unique 3 3 top f c freq 1 1 Excluding object columns from a ``DataFrame`` description. >>> df.describe(exclude=[np.object]) categorical numeric count 3 3.0 unique 3 NaN top f NaN freq 1 NaN mean NaN 2.0 std NaN 1.0 min NaN 1.0 25% NaN 1.5 50% NaN 2.0 75% NaN 2.5 max NaN 3.0
Generate descriptive statistics that summarize the central tendency, dispersion and shape of a dataset's distribution, excluding ``NaN`` values.
[ "Generate", "descriptive", "statistics", "that", "summarize", "the", "central", "tendency", "dispersion", "and", "shape", "of", "a", "dataset", "s", "distribution", "excluding", "NaN", "values", "." ]
def describe(self, percentiles=None, include=None, exclude=None): """ Generate descriptive statistics that summarize the central tendency, dispersion and shape of a dataset's distribution, excluding ``NaN`` values. Analyzes both numeric and object series, as well as ``DataFrame`` column sets of mixed data types. The output will vary depending on what is provided. Refer to the notes below for more detail. Parameters ---------- percentiles : list-like of numbers, optional The percentiles to include in the output. All should fall between 0 and 1. The default is ``[.25, .5, .75]``, which returns the 25th, 50th, and 75th percentiles. include : 'all', list-like of dtypes or None (default), optional A white list of data types to include in the result. Ignored for ``Series``. Here are the options: - 'all' : All columns of the input will be included in the output. - A list-like of dtypes : Limits the results to the provided data types. To limit the result to numeric types submit ``numpy.number``. To limit it instead to object columns submit the ``numpy.object`` data type. Strings can also be used in the style of ``select_dtypes`` (e.g. ``df.describe(include=['O'])``). To select pandas categorical columns, use ``'category'`` - None (default) : The result will include all numeric columns. exclude : list-like of dtypes or None (default), optional, A black list of data types to omit from the result. Ignored for ``Series``. Here are the options: - A list-like of dtypes : Excludes the provided data types from the result. To exclude numeric types submit ``numpy.number``. To exclude object columns submit the data type ``numpy.object``. Strings can also be used in the style of ``select_dtypes`` (e.g. ``df.describe(include=['O'])``). To exclude pandas categorical columns, use ``'category'`` - None (default) : The result will exclude nothing. Returns ------- Series or DataFrame Summary statistics of the Series or Dataframe provided. See Also -------- DataFrame.count: Count number of non-NA/null observations. DataFrame.max: Maximum of the values in the object. DataFrame.min: Minimum of the values in the object. DataFrame.mean: Mean of the values. DataFrame.std: Standard deviation of the obersvations. DataFrame.select_dtypes: Subset of a DataFrame including/excluding columns based on their dtype. Notes ----- For numeric data, the result's index will include ``count``, ``mean``, ``std``, ``min``, ``max`` as well as lower, ``50`` and upper percentiles. By default the lower percentile is ``25`` and the upper percentile is ``75``. The ``50`` percentile is the same as the median. For object data (e.g. strings or timestamps), the result's index will include ``count``, ``unique``, ``top``, and ``freq``. The ``top`` is the most common value. The ``freq`` is the most common value's frequency. Timestamps also include the ``first`` and ``last`` items. If multiple object values have the highest count, then the ``count`` and ``top`` results will be arbitrarily chosen from among those with the highest count. For mixed data types provided via a ``DataFrame``, the default is to return only an analysis of numeric columns. If the dataframe consists only of object and categorical data without any numeric columns, the default is to return an analysis of both the object and categorical columns. If ``include='all'`` is provided as an option, the result will include a union of attributes of each type. The `include` and `exclude` parameters can be used to limit which columns in a ``DataFrame`` are analyzed for the output. The parameters are ignored when analyzing a ``Series``. Examples -------- Describing a numeric ``Series``. >>> s = pd.Series([1, 2, 3]) >>> s.describe() count 3.0 mean 2.0 std 1.0 min 1.0 25% 1.5 50% 2.0 75% 2.5 max 3.0 dtype: float64 Describing a categorical ``Series``. >>> s = pd.Series(['a', 'a', 'b', 'c']) >>> s.describe() count 4 unique 3 top a freq 2 dtype: object Describing a timestamp ``Series``. >>> s = pd.Series([ ... np.datetime64("2000-01-01"), ... np.datetime64("2010-01-01"), ... np.datetime64("2010-01-01") ... ]) >>> s.describe() count 3 unique 2 top 2010-01-01 00:00:00 freq 2 first 2000-01-01 00:00:00 last 2010-01-01 00:00:00 dtype: object Describing a ``DataFrame``. By default only numeric fields are returned. >>> df = pd.DataFrame({'categorical': pd.Categorical(['d','e','f']), ... 'numeric': [1, 2, 3], ... 'object': ['a', 'b', 'c'] ... }) >>> df.describe() numeric count 3.0 mean 2.0 std 1.0 min 1.0 25% 1.5 50% 2.0 75% 2.5 max 3.0 Describing all columns of a ``DataFrame`` regardless of data type. >>> df.describe(include='all') categorical numeric object count 3 3.0 3 unique 3 NaN 3 top f NaN c freq 1 NaN 1 mean NaN 2.0 NaN std NaN 1.0 NaN min NaN 1.0 NaN 25% NaN 1.5 NaN 50% NaN 2.0 NaN 75% NaN 2.5 NaN max NaN 3.0 NaN Describing a column from a ``DataFrame`` by accessing it as an attribute. >>> df.numeric.describe() count 3.0 mean 2.0 std 1.0 min 1.0 25% 1.5 50% 2.0 75% 2.5 max 3.0 Name: numeric, dtype: float64 Including only numeric columns in a ``DataFrame`` description. >>> df.describe(include=[np.number]) numeric count 3.0 mean 2.0 std 1.0 min 1.0 25% 1.5 50% 2.0 75% 2.5 max 3.0 Including only string columns in a ``DataFrame`` description. >>> df.describe(include=[np.object]) object count 3 unique 3 top c freq 1 Including only categorical columns from a ``DataFrame`` description. >>> df.describe(include=['category']) categorical count 3 unique 3 top f freq 1 Excluding numeric columns from a ``DataFrame`` description. >>> df.describe(exclude=[np.number]) categorical object count 3 3 unique 3 3 top f c freq 1 1 Excluding object columns from a ``DataFrame`` description. >>> df.describe(exclude=[np.object]) categorical numeric count 3 3.0 unique 3 NaN top f NaN freq 1 NaN mean NaN 2.0 std NaN 1.0 min NaN 1.0 25% NaN 1.5 50% NaN 2.0 75% NaN 2.5 max NaN 3.0 """ if self.ndim >= 3: msg = "describe is not implemented on Panel objects." raise NotImplementedError(msg) elif self.ndim == 2 and self.columns.size == 0: raise ValueError("Cannot describe a DataFrame without columns") if percentiles is not None: # explicit conversion of `percentiles` to list percentiles = list(percentiles) # get them all to be in [0, 1] self._check_percentile(percentiles) # median should always be included if 0.5 not in percentiles: percentiles.append(0.5) percentiles = np.asarray(percentiles) else: percentiles = np.array([0.25, 0.5, 0.75]) # sort and check for duplicates unique_pcts = np.unique(percentiles) if len(unique_pcts) < len(percentiles): raise ValueError("percentiles cannot contain duplicates") percentiles = unique_pcts formatted_percentiles = format_percentiles(percentiles) def describe_numeric_1d(series): stat_index = (['count', 'mean', 'std', 'min'] + formatted_percentiles + ['max']) d = ([series.count(), series.mean(), series.std(), series.min()] + series.quantile(percentiles).tolist() + [series.max()]) return pd.Series(d, index=stat_index, name=series.name) def describe_categorical_1d(data): names = ['count', 'unique'] objcounts = data.value_counts() count_unique = len(objcounts[objcounts != 0]) result = [data.count(), count_unique] if result[1] > 0: top, freq = objcounts.index[0], objcounts.iloc[0] if is_datetime64_any_dtype(data): tz = data.dt.tz asint = data.dropna().values.view('i8') top = Timestamp(top) if top.tzinfo is not None and tz is not None: # Don't tz_localize(None) if key is already tz-aware top = top.tz_convert(tz) else: top = top.tz_localize(tz) names += ['top', 'freq', 'first', 'last'] result += [top, freq, Timestamp(asint.min(), tz=tz), Timestamp(asint.max(), tz=tz)] else: names += ['top', 'freq'] result += [top, freq] return pd.Series(result, index=names, name=data.name) def describe_1d(data): if is_bool_dtype(data): return describe_categorical_1d(data) elif is_numeric_dtype(data): return describe_numeric_1d(data) elif is_timedelta64_dtype(data): return describe_numeric_1d(data) else: return describe_categorical_1d(data) if self.ndim == 1: return describe_1d(self) elif (include is None) and (exclude is None): # when some numerics are found, keep only numerics data = self.select_dtypes(include=[np.number]) if len(data.columns) == 0: data = self elif include == 'all': if exclude is not None: msg = "exclude must be None when include is 'all'" raise ValueError(msg) data = self else: data = self.select_dtypes(include=include, exclude=exclude) ldesc = [describe_1d(s) for _, s in data.iteritems()] # set a convenient order for rows names = [] ldesc_indexes = sorted((x.index for x in ldesc), key=len) for idxnames in ldesc_indexes: for name in idxnames: if name not in names: names.append(name) d = pd.concat(ldesc, join_axes=pd.Index([names]), axis=1) d.columns = data.columns.copy() return d
[ "def", "describe", "(", "self", ",", "percentiles", "=", "None", ",", "include", "=", "None", ",", "exclude", "=", "None", ")", ":", "if", "self", ".", "ndim", ">=", "3", ":", "msg", "=", "\"describe is not implemented on Panel objects.\"", "raise", "NotImplementedError", "(", "msg", ")", "elif", "self", ".", "ndim", "==", "2", "and", "self", ".", "columns", ".", "size", "==", "0", ":", "raise", "ValueError", "(", "\"Cannot describe a DataFrame without columns\"", ")", "if", "percentiles", "is", "not", "None", ":", "# explicit conversion of `percentiles` to list", "percentiles", "=", "list", "(", "percentiles", ")", "# get them all to be in [0, 1]", "self", ".", "_check_percentile", "(", "percentiles", ")", "# median should always be included", "if", "0.5", "not", "in", "percentiles", ":", "percentiles", ".", "append", "(", "0.5", ")", "percentiles", "=", "np", ".", "asarray", "(", "percentiles", ")", "else", ":", "percentiles", "=", "np", ".", "array", "(", "[", "0.25", ",", "0.5", ",", "0.75", "]", ")", "# sort and check for duplicates", "unique_pcts", "=", "np", ".", "unique", "(", "percentiles", ")", "if", "len", "(", "unique_pcts", ")", "<", "len", "(", "percentiles", ")", ":", "raise", "ValueError", "(", "\"percentiles cannot contain duplicates\"", ")", "percentiles", "=", "unique_pcts", "formatted_percentiles", "=", "format_percentiles", "(", "percentiles", ")", "def", "describe_numeric_1d", "(", "series", ")", ":", "stat_index", "=", "(", "[", "'count'", ",", "'mean'", ",", "'std'", ",", "'min'", "]", "+", "formatted_percentiles", "+", "[", "'max'", "]", ")", "d", "=", "(", "[", "series", ".", "count", "(", ")", ",", "series", ".", "mean", "(", ")", ",", "series", ".", "std", "(", ")", ",", "series", ".", "min", "(", ")", "]", "+", "series", ".", "quantile", "(", "percentiles", ")", ".", "tolist", "(", ")", "+", "[", "series", ".", "max", "(", ")", "]", ")", "return", "pd", ".", "Series", "(", "d", ",", "index", "=", "stat_index", ",", "name", "=", "series", ".", "name", ")", "def", "describe_categorical_1d", "(", "data", ")", ":", "names", "=", "[", "'count'", ",", "'unique'", "]", "objcounts", "=", "data", ".", "value_counts", "(", ")", "count_unique", "=", "len", "(", "objcounts", "[", "objcounts", "!=", "0", "]", ")", "result", "=", "[", "data", ".", "count", "(", ")", ",", "count_unique", "]", "if", "result", "[", "1", "]", ">", "0", ":", "top", ",", "freq", "=", "objcounts", ".", "index", "[", "0", "]", ",", "objcounts", ".", "iloc", "[", "0", "]", "if", "is_datetime64_any_dtype", "(", "data", ")", ":", "tz", "=", "data", ".", "dt", ".", "tz", "asint", "=", "data", ".", "dropna", "(", ")", ".", "values", ".", "view", "(", "'i8'", ")", "top", "=", "Timestamp", "(", "top", ")", "if", "top", ".", "tzinfo", "is", "not", "None", "and", "tz", "is", "not", "None", ":", "# Don't tz_localize(None) if key is already tz-aware", "top", "=", "top", ".", "tz_convert", "(", "tz", ")", "else", ":", "top", "=", "top", ".", "tz_localize", "(", "tz", ")", "names", "+=", "[", "'top'", ",", "'freq'", ",", "'first'", ",", "'last'", "]", "result", "+=", "[", "top", ",", "freq", ",", "Timestamp", "(", "asint", ".", "min", "(", ")", ",", "tz", "=", "tz", ")", ",", "Timestamp", "(", "asint", ".", "max", "(", ")", ",", "tz", "=", "tz", ")", "]", "else", ":", "names", "+=", "[", "'top'", ",", "'freq'", "]", "result", "+=", "[", "top", ",", "freq", "]", "return", "pd", ".", "Series", "(", "result", ",", "index", "=", "names", ",", "name", "=", "data", ".", "name", ")", "def", "describe_1d", "(", "data", ")", ":", "if", "is_bool_dtype", "(", "data", ")", ":", "return", "describe_categorical_1d", "(", "data", ")", "elif", "is_numeric_dtype", "(", "data", ")", ":", "return", "describe_numeric_1d", "(", "data", ")", "elif", "is_timedelta64_dtype", "(", "data", ")", ":", "return", "describe_numeric_1d", "(", "data", ")", "else", ":", "return", "describe_categorical_1d", "(", "data", ")", "if", "self", ".", "ndim", "==", "1", ":", "return", "describe_1d", "(", "self", ")", "elif", "(", "include", "is", "None", ")", "and", "(", "exclude", "is", "None", ")", ":", "# when some numerics are found, keep only numerics", "data", "=", "self", ".", "select_dtypes", "(", "include", "=", "[", "np", ".", "number", "]", ")", "if", "len", "(", "data", ".", "columns", ")", "==", "0", ":", "data", "=", "self", "elif", "include", "==", "'all'", ":", "if", "exclude", "is", "not", "None", ":", "msg", "=", "\"exclude must be None when include is 'all'\"", "raise", "ValueError", "(", "msg", ")", "data", "=", "self", "else", ":", "data", "=", "self", ".", "select_dtypes", "(", "include", "=", "include", ",", "exclude", "=", "exclude", ")", "ldesc", "=", "[", "describe_1d", "(", "s", ")", "for", "_", ",", "s", "in", "data", ".", "iteritems", "(", ")", "]", "# set a convenient order for rows", "names", "=", "[", "]", "ldesc_indexes", "=", "sorted", "(", "(", "x", ".", "index", "for", "x", "in", "ldesc", ")", ",", "key", "=", "len", ")", "for", "idxnames", "in", "ldesc_indexes", ":", "for", "name", "in", "idxnames", ":", "if", "name", "not", "in", "names", ":", "names", ".", "append", "(", "name", ")", "d", "=", "pd", ".", "concat", "(", "ldesc", ",", "join_axes", "=", "pd", ".", "Index", "(", "[", "names", "]", ")", ",", "axis", "=", "1", ")", "d", ".", "columns", "=", "data", ".", "columns", ".", "copy", "(", ")", "return", "d" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/core/generic.py#L9484-L9815
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/cgi.py
python
parse_qsl
(qs, keep_blank_values=0, strict_parsing=0)
return urlparse.parse_qsl(qs, keep_blank_values, strict_parsing)
Parse a query given as a string argument.
Parse a query given as a string argument.
[ "Parse", "a", "query", "given", "as", "a", "string", "argument", "." ]
def parse_qsl(qs, keep_blank_values=0, strict_parsing=0): """Parse a query given as a string argument.""" warn("cgi.parse_qsl is deprecated, use urlparse.parse_qsl instead", PendingDeprecationWarning, 2) return urlparse.parse_qsl(qs, keep_blank_values, strict_parsing)
[ "def", "parse_qsl", "(", "qs", ",", "keep_blank_values", "=", "0", ",", "strict_parsing", "=", "0", ")", ":", "warn", "(", "\"cgi.parse_qsl is deprecated, use urlparse.parse_qsl instead\"", ",", "PendingDeprecationWarning", ",", "2", ")", "return", "urlparse", ".", "parse_qsl", "(", "qs", ",", "keep_blank_values", ",", "strict_parsing", ")" ]
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/cgi.py#L188-L192
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/ops/variables.py
python
initialize_variables
(var_list, name="init")
return variables_initializer(var_list, name=name)
See `tf.variables_initializer`.
See `tf.variables_initializer`.
[ "See", "tf", ".", "variables_initializer", "." ]
def initialize_variables(var_list, name="init"): """See `tf.variables_initializer`.""" return variables_initializer(var_list, name=name)
[ "def", "initialize_variables", "(", "var_list", ",", "name", "=", "\"init\"", ")", ":", "return", "variables_initializer", "(", "var_list", ",", "name", "=", "name", ")" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/ops/variables.py#L1391-L1393
ucb-bar/esp-llvm
8aec2ae754fd66d4e73b9b777a9f20c4583a0f03
utils/lit/lit/ShUtil.py
python
ShLexer.maybe_eat
(self, c)
return False
maybe_eat(c) - Consume the character c if it is the next character, returning True if a character was consumed.
maybe_eat(c) - Consume the character c if it is the next character, returning True if a character was consumed.
[ "maybe_eat", "(", "c", ")", "-", "Consume", "the", "character", "c", "if", "it", "is", "the", "next", "character", "returning", "True", "if", "a", "character", "was", "consumed", "." ]
def maybe_eat(self, c): """ maybe_eat(c) - Consume the character c if it is the next character, returning True if a character was consumed. """ if self.data[self.pos] == c: self.pos += 1 return True return False
[ "def", "maybe_eat", "(", "self", ",", "c", ")", ":", "if", "self", ".", "data", "[", "self", ".", "pos", "]", "==", "c", ":", "self", ".", "pos", "+=", "1", "return", "True", "return", "False" ]
https://github.com/ucb-bar/esp-llvm/blob/8aec2ae754fd66d4e73b9b777a9f20c4583a0f03/utils/lit/lit/ShUtil.py#L22-L29
hpi-xnor/BMXNet-v2
af2b1859eafc5c721b1397cef02f946aaf2ce20d
example/neural-style/nstyle.py
python
get_tv_grad_executor
(img, ctx, tv_weight)
return out.bind(ctx, args={"img": img, "kernel": kernel})
create TV gradient executor with input binded on img
create TV gradient executor with input binded on img
[ "create", "TV", "gradient", "executor", "with", "input", "binded", "on", "img" ]
def get_tv_grad_executor(img, ctx, tv_weight): """create TV gradient executor with input binded on img """ if tv_weight <= 0.0: return None nchannel = img.shape[1] simg = mx.sym.Variable("img") skernel = mx.sym.Variable("kernel") channels = mx.sym.SliceChannel(simg, num_outputs=nchannel) out = mx.sym.Concat(*[ mx.sym.Convolution(data=channels[i], weight=skernel, num_filter=1, kernel=(3, 3), pad=(1,1), no_bias=True, stride=(1,1)) for i in range(nchannel)]) kernel = mx.nd.array(np.array([[0, -1, 0], [-1, 4, -1], [0, -1, 0]]) .reshape((1, 1, 3, 3)), ctx) / 8.0 out = out * tv_weight return out.bind(ctx, args={"img": img, "kernel": kernel})
[ "def", "get_tv_grad_executor", "(", "img", ",", "ctx", ",", "tv_weight", ")", ":", "if", "tv_weight", "<=", "0.0", ":", "return", "None", "nchannel", "=", "img", ".", "shape", "[", "1", "]", "simg", "=", "mx", ".", "sym", ".", "Variable", "(", "\"img\"", ")", "skernel", "=", "mx", ".", "sym", ".", "Variable", "(", "\"kernel\"", ")", "channels", "=", "mx", ".", "sym", ".", "SliceChannel", "(", "simg", ",", "num_outputs", "=", "nchannel", ")", "out", "=", "mx", ".", "sym", ".", "Concat", "(", "*", "[", "mx", ".", "sym", ".", "Convolution", "(", "data", "=", "channels", "[", "i", "]", ",", "weight", "=", "skernel", ",", "num_filter", "=", "1", ",", "kernel", "=", "(", "3", ",", "3", ")", ",", "pad", "=", "(", "1", ",", "1", ")", ",", "no_bias", "=", "True", ",", "stride", "=", "(", "1", ",", "1", ")", ")", "for", "i", "in", "range", "(", "nchannel", ")", "]", ")", "kernel", "=", "mx", ".", "nd", ".", "array", "(", "np", ".", "array", "(", "[", "[", "0", ",", "-", "1", ",", "0", "]", ",", "[", "-", "1", ",", "4", ",", "-", "1", "]", ",", "[", "0", ",", "-", "1", ",", "0", "]", "]", ")", ".", "reshape", "(", "(", "1", ",", "1", ",", "3", ",", "3", ")", ")", ",", "ctx", ")", "/", "8.0", "out", "=", "out", "*", "tv_weight", "return", "out", ".", "bind", "(", "ctx", ",", "args", "=", "{", "\"img\"", ":", "img", ",", "\"kernel\"", ":", "kernel", "}", ")" ]
https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/example/neural-style/nstyle.py#L143-L165
Constellation/iv
64c3a9c7c517063f29d90d449180ea8f6f4d946f
tools/cpplint.py
python
CloseExpression
(clean_lines, linenum, pos)
return (line, clean_lines.NumLines(), -1)
If input points to ( or { or [ or <, finds the position that closes it. If lines[linenum][pos] points to a '(' or '{' or '[' or '<', finds the linenum/pos that correspond to the closing of the expression. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. pos: A position on the line. Returns: A tuple (line, linenum, pos) pointer *past* the closing brace, or (line, len(lines), -1) if we never find a close. Note we ignore strings and comments when matching; and the line we return is the 'cleansed' line at linenum.
If input points to ( or { or [ or <, finds the position that closes it.
[ "If", "input", "points", "to", "(", "or", "{", "or", "[", "or", "<", "finds", "the", "position", "that", "closes", "it", "." ]
def CloseExpression(clean_lines, linenum, pos): """If input points to ( or { or [ or <, finds the position that closes it. If lines[linenum][pos] points to a '(' or '{' or '[' or '<', finds the linenum/pos that correspond to the closing of the expression. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. pos: A position on the line. Returns: A tuple (line, linenum, pos) pointer *past* the closing brace, or (line, len(lines), -1) if we never find a close. Note we ignore strings and comments when matching; and the line we return is the 'cleansed' line at linenum. """ line = clean_lines.elided[linenum] startchar = line[pos] if startchar not in '({[<': return (line, clean_lines.NumLines(), -1) if startchar == '(': endchar = ')' if startchar == '[': endchar = ']' if startchar == '{': endchar = '}' if startchar == '<': endchar = '>' # Check first line (end_pos, num_open) = FindEndOfExpressionInLine( line, pos, 0, startchar, endchar) if end_pos > -1: return (line, linenum, end_pos) # Continue scanning forward while linenum < clean_lines.NumLines() - 1: linenum += 1 line = clean_lines.elided[linenum] (end_pos, num_open) = FindEndOfExpressionInLine( line, 0, num_open, startchar, endchar) if end_pos > -1: return (line, linenum, end_pos) # Did not find endchar before end of file, give up return (line, clean_lines.NumLines(), -1)
[ "def", "CloseExpression", "(", "clean_lines", ",", "linenum", ",", "pos", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "startchar", "=", "line", "[", "pos", "]", "if", "startchar", "not", "in", "'({[<'", ":", "return", "(", "line", ",", "clean_lines", ".", "NumLines", "(", ")", ",", "-", "1", ")", "if", "startchar", "==", "'('", ":", "endchar", "=", "')'", "if", "startchar", "==", "'['", ":", "endchar", "=", "']'", "if", "startchar", "==", "'{'", ":", "endchar", "=", "'}'", "if", "startchar", "==", "'<'", ":", "endchar", "=", "'>'", "# Check first line", "(", "end_pos", ",", "num_open", ")", "=", "FindEndOfExpressionInLine", "(", "line", ",", "pos", ",", "0", ",", "startchar", ",", "endchar", ")", "if", "end_pos", ">", "-", "1", ":", "return", "(", "line", ",", "linenum", ",", "end_pos", ")", "# Continue scanning forward", "while", "linenum", "<", "clean_lines", ".", "NumLines", "(", ")", "-", "1", ":", "linenum", "+=", "1", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "(", "end_pos", ",", "num_open", ")", "=", "FindEndOfExpressionInLine", "(", "line", ",", "0", ",", "num_open", ",", "startchar", ",", "endchar", ")", "if", "end_pos", ">", "-", "1", ":", "return", "(", "line", ",", "linenum", ",", "end_pos", ")", "# Did not find endchar before end of file, give up", "return", "(", "line", ",", "clean_lines", ".", "NumLines", "(", ")", ",", "-", "1", ")" ]
https://github.com/Constellation/iv/blob/64c3a9c7c517063f29d90d449180ea8f6f4d946f/tools/cpplint.py#L1242-L1285
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/pythonwin/pywin/framework/scriptutils.py
python
GetActiveView
()
Gets the edit control (eg, EditView) with the focus, or None
Gets the edit control (eg, EditView) with the focus, or None
[ "Gets", "the", "edit", "control", "(", "eg", "EditView", ")", "with", "the", "focus", "or", "None" ]
def GetActiveView(): """Gets the edit control (eg, EditView) with the focus, or None """ try: childFrame, bIsMaximised = win32ui.GetMainFrame().MDIGetActive() return childFrame.GetActiveView() except win32ui.error: return None
[ "def", "GetActiveView", "(", ")", ":", "try", ":", "childFrame", ",", "bIsMaximised", "=", "win32ui", ".", "GetMainFrame", "(", ")", ".", "MDIGetActive", "(", ")", "return", "childFrame", ".", "GetActiveView", "(", ")", "except", "win32ui", ".", "error", ":", "return", "None" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/pythonwin/pywin/framework/scriptutils.py#L116-L123
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/contrib/crf/python/ops/crf.py
python
crf_log_likelihood
(inputs, tag_indices, sequence_lengths, transition_params=None)
return log_likelihood, transition_params
Computes the log-likelihood of tag sequences in a CRF. Args: inputs: A [batch_size, max_seq_len, num_tags] tensor of unary potentials to use as input to the CRF layer. tag_indices: A [batch_size, max_seq_len] matrix of tag indices for which we compute the log-likelihood. sequence_lengths: A [batch_size] vector of true sequence lengths. transition_params: A [num_tags, num_tags] transition matrix, if available. Returns: log_likelihood: A scalar containing the log-likelihood of the given sequence of tag indices. transition_params: A [num_tags, num_tags] transition matrix. This is either provided by the caller or created in this function.
Computes the log-likelihood of tag sequences in a CRF.
[ "Computes", "the", "log", "-", "likelihood", "of", "tag", "sequences", "in", "a", "CRF", "." ]
def crf_log_likelihood(inputs, tag_indices, sequence_lengths, transition_params=None): """Computes the log-likelihood of tag sequences in a CRF. Args: inputs: A [batch_size, max_seq_len, num_tags] tensor of unary potentials to use as input to the CRF layer. tag_indices: A [batch_size, max_seq_len] matrix of tag indices for which we compute the log-likelihood. sequence_lengths: A [batch_size] vector of true sequence lengths. transition_params: A [num_tags, num_tags] transition matrix, if available. Returns: log_likelihood: A scalar containing the log-likelihood of the given sequence of tag indices. transition_params: A [num_tags, num_tags] transition matrix. This is either provided by the caller or created in this function. """ # Get shape information. num_tags = inputs.get_shape()[2].value # Get the transition matrix if not provided. if transition_params is None: transition_params = vs.get_variable("transitions", [num_tags, num_tags]) sequence_scores = crf_sequence_score(inputs, tag_indices, sequence_lengths, transition_params) log_norm = crf_log_norm(inputs, sequence_lengths, transition_params) # Normalize the scores to get the log-likelihood. log_likelihood = sequence_scores - log_norm return log_likelihood, transition_params
[ "def", "crf_log_likelihood", "(", "inputs", ",", "tag_indices", ",", "sequence_lengths", ",", "transition_params", "=", "None", ")", ":", "# Get shape information.", "num_tags", "=", "inputs", ".", "get_shape", "(", ")", "[", "2", "]", ".", "value", "# Get the transition matrix if not provided.", "if", "transition_params", "is", "None", ":", "transition_params", "=", "vs", ".", "get_variable", "(", "\"transitions\"", ",", "[", "num_tags", ",", "num_tags", "]", ")", "sequence_scores", "=", "crf_sequence_score", "(", "inputs", ",", "tag_indices", ",", "sequence_lengths", ",", "transition_params", ")", "log_norm", "=", "crf_log_norm", "(", "inputs", ",", "sequence_lengths", ",", "transition_params", ")", "# Normalize the scores to get the log-likelihood.", "log_likelihood", "=", "sequence_scores", "-", "log_norm", "return", "log_likelihood", ",", "transition_params" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/crf/python/ops/crf.py#L128-L160
kamyu104/LeetCode-Solutions
77605708a927ea3b85aee5a479db733938c7c211
Python/paint-house.py
python
Solution.minCost
(self, costs)
return min(min_cost[(n - 1) % 2])
:type costs: List[List[int]] :rtype: int
:type costs: List[List[int]] :rtype: int
[ ":", "type", "costs", ":", "List", "[", "List", "[", "int", "]]", ":", "rtype", ":", "int" ]
def minCost(self, costs): """ :type costs: List[List[int]] :rtype: int """ if not costs: return 0 min_cost = [costs[0], [0, 0, 0]] n = len(costs) for i in xrange(1, n): min_cost[i % 2][0] = costs[i][0] + \ min(min_cost[(i - 1) % 2][1], min_cost[(i - 1) % 2][2]) min_cost[i % 2][1] = costs[i][1] + \ min(min_cost[(i - 1) % 2][0], min_cost[(i - 1) % 2][2]) min_cost[i % 2][2] = costs[i][2] + \ min(min_cost[(i - 1) % 2][0], min_cost[(i - 1) % 2][1]) return min(min_cost[(n - 1) % 2])
[ "def", "minCost", "(", "self", ",", "costs", ")", ":", "if", "not", "costs", ":", "return", "0", "min_cost", "=", "[", "costs", "[", "0", "]", ",", "[", "0", ",", "0", ",", "0", "]", "]", "n", "=", "len", "(", "costs", ")", "for", "i", "in", "xrange", "(", "1", ",", "n", ")", ":", "min_cost", "[", "i", "%", "2", "]", "[", "0", "]", "=", "costs", "[", "i", "]", "[", "0", "]", "+", "min", "(", "min_cost", "[", "(", "i", "-", "1", ")", "%", "2", "]", "[", "1", "]", ",", "min_cost", "[", "(", "i", "-", "1", ")", "%", "2", "]", "[", "2", "]", ")", "min_cost", "[", "i", "%", "2", "]", "[", "1", "]", "=", "costs", "[", "i", "]", "[", "1", "]", "+", "min", "(", "min_cost", "[", "(", "i", "-", "1", ")", "%", "2", "]", "[", "0", "]", ",", "min_cost", "[", "(", "i", "-", "1", ")", "%", "2", "]", "[", "2", "]", ")", "min_cost", "[", "i", "%", "2", "]", "[", "2", "]", "=", "costs", "[", "i", "]", "[", "2", "]", "+", "min", "(", "min_cost", "[", "(", "i", "-", "1", ")", "%", "2", "]", "[", "0", "]", ",", "min_cost", "[", "(", "i", "-", "1", ")", "%", "2", "]", "[", "1", "]", ")", "return", "min", "(", "min_cost", "[", "(", "n", "-", "1", ")", "%", "2", "]", ")" ]
https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/paint-house.py#L5-L24
bristolcrypto/SPDZ-2
721abfae849625a02ea49aabc534f9cf41ca643f
Compiler/comparison.py
python
Trunc
(d, a, k, m, kappa, signed)
d = a >> m k: bit length of a m: compile-time integer signed: True/False, describes a
d = a >> m
[ "d", "=", "a", ">>", "m" ]
def Trunc(d, a, k, m, kappa, signed): """ d = a >> m k: bit length of a m: compile-time integer signed: True/False, describes a """ a_prime = program.curr_block.new_reg('s') t = program.curr_block.new_reg('s') c = [program.curr_block.new_reg('c') for i in range(3)] c2m = program.curr_block.new_reg('c') if m == 0: movs(d, a) return elif m == 1: Mod2(a_prime, a, k, kappa, signed) else: Mod2m(a_prime, a, k, m, kappa, signed) subs(t, a, a_prime) ldi(c[1], 1) ld2i(c2m, m) divc(c[2], c[1], c2m) mulm(d, t, c[2])
[ "def", "Trunc", "(", "d", ",", "a", ",", "k", ",", "m", ",", "kappa", ",", "signed", ")", ":", "a_prime", "=", "program", ".", "curr_block", ".", "new_reg", "(", "'s'", ")", "t", "=", "program", ".", "curr_block", ".", "new_reg", "(", "'s'", ")", "c", "=", "[", "program", ".", "curr_block", ".", "new_reg", "(", "'c'", ")", "for", "i", "in", "range", "(", "3", ")", "]", "c2m", "=", "program", ".", "curr_block", ".", "new_reg", "(", "'c'", ")", "if", "m", "==", "0", ":", "movs", "(", "d", ",", "a", ")", "return", "elif", "m", "==", "1", ":", "Mod2", "(", "a_prime", ",", "a", ",", "k", ",", "kappa", ",", "signed", ")", "else", ":", "Mod2m", "(", "a_prime", ",", "a", ",", "k", ",", "m", ",", "kappa", ",", "signed", ")", "subs", "(", "t", ",", "a", ",", "a_prime", ")", "ldi", "(", "c", "[", "1", "]", ",", "1", ")", "ld2i", "(", "c2m", ",", "m", ")", "divc", "(", "c", "[", "2", "]", ",", "c", "[", "1", "]", ",", "c2m", ")", "mulm", "(", "d", ",", "t", ",", "c", "[", "2", "]", ")" ]
https://github.com/bristolcrypto/SPDZ-2/blob/721abfae849625a02ea49aabc534f9cf41ca643f/Compiler/comparison.py#L86-L109
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/labeled_tensor/python/ops/core.py
python
Axis.index
(self, value)
return self._index[value]
Returns the integer position of the given tick label.
Returns the integer position of the given tick label.
[ "Returns", "the", "integer", "position", "of", "the", "given", "tick", "label", "." ]
def index(self, value): """Returns the integer position of the given tick label.""" if self._index is None: raise ValueError('Axis does not have tick labels') return self._index[value]
[ "def", "index", "(", "self", ",", "value", ")", ":", "if", "self", ".", "_index", "is", "None", ":", "raise", "ValueError", "(", "'Axis does not have tick labels'", ")", "return", "self", ".", "_index", "[", "value", "]" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/labeled_tensor/python/ops/core.py#L168-L172
google/ion
ef47f3b824050499ce5c6f774b366f6c4dbce0af
ion/build.py
python
_SmartDeleteDirectory
(path)
Delete a directory, or a symlink to a directory. Deleting a symlink to a directory requires extra effort than usual. Args: path: The directory to delete, or a symlink to a directory to delete. In the latter case, the target of the symlink AND the symlink will be deleted.
Delete a directory, or a symlink to a directory.
[ "Delete", "a", "directory", "or", "a", "symlink", "to", "a", "directory", "." ]
def _SmartDeleteDirectory(path): """Delete a directory, or a symlink to a directory. Deleting a symlink to a directory requires extra effort than usual. Args: path: The directory to delete, or a symlink to a directory to delete. In the latter case, the target of the symlink AND the symlink will be deleted. """ if os.path.isdir(path) and not os.path.islink(path): shutil.rmtree(path) elif os.path.islink(path): target = os.readlink(path) shutil.rmtree(target) os.unlink(path)
[ "def", "_SmartDeleteDirectory", "(", "path", ")", ":", "if", "os", ".", "path", ".", "isdir", "(", "path", ")", "and", "not", "os", ".", "path", ".", "islink", "(", "path", ")", ":", "shutil", ".", "rmtree", "(", "path", ")", "elif", "os", ".", "path", ".", "islink", "(", "path", ")", ":", "target", "=", "os", ".", "readlink", "(", "path", ")", "shutil", ".", "rmtree", "(", "target", ")", "os", ".", "unlink", "(", "path", ")" ]
https://github.com/google/ion/blob/ef47f3b824050499ce5c6f774b366f6c4dbce0af/ion/build.py#L254-L271
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/contrib/learn/python/learn/monitors.py
python
ValidationMonitor.best_value
(self)
return self._best_value
Returns the best early stopping metric value found so far.
Returns the best early stopping metric value found so far.
[ "Returns", "the", "best", "early", "stopping", "metric", "value", "found", "so", "far", "." ]
def best_value(self): """Returns the best early stopping metric value found so far.""" return self._best_value
[ "def", "best_value", "(", "self", ")", ":", "return", "self", ".", "_best_value" ]
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/contrib/learn/python/learn/monitors.py#L669-L671
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/computation/expr.py
python
_node_not_implemented
(node_name, cls)
return f
Return a function that raises a NotImplementedError with a passed node name.
Return a function that raises a NotImplementedError with a passed node name.
[ "Return", "a", "function", "that", "raises", "a", "NotImplementedError", "with", "a", "passed", "node", "name", "." ]
def _node_not_implemented(node_name, cls): """Return a function that raises a NotImplementedError with a passed node name. """ def f(self, *args, **kwargs): raise NotImplementedError(f"{repr(node_name)} nodes are not implemented") return f
[ "def", "_node_not_implemented", "(", "node_name", ",", "cls", ")", ":", "def", "f", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "raise", "NotImplementedError", "(", "f\"{repr(node_name)} nodes are not implemented\"", ")", "return", "f" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/computation/expr.py#L230-L238
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/ops/_op_impl/tbe/apply_centered_rms_prop_ds.py
python
_apply_centered_rms_prop_ds_tbe
()
return
ApplyCenteredRMSPropD TBE register
ApplyCenteredRMSPropD TBE register
[ "ApplyCenteredRMSPropD", "TBE", "register" ]
def _apply_centered_rms_prop_ds_tbe(): """ApplyCenteredRMSPropD TBE register""" return
[ "def", "_apply_centered_rms_prop_ds_tbe", "(", ")", ":", "return" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/_op_impl/tbe/apply_centered_rms_prop_ds.py#L76-L78
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/compileall.py
python
compile_dir
(dir, maxlevels=None, ddir=None, force=False, rx=None, quiet=0, legacy=False, optimize=-1, workers=1, invalidation_mode=None, *, stripdir=None, prependdir=None, limit_sl_dest=None, hardlink_dupes=False)
return success
Byte-compile all modules in the given directory tree. Arguments (only dir is required): dir: the directory to byte-compile maxlevels: maximum recursion level (default `sys.getrecursionlimit()`) ddir: the directory that will be prepended to the path to the file as it is compiled into each byte-code file. force: if True, force compilation, even if timestamps are up-to-date quiet: full output with False or 0, errors only with 1, no output with 2 legacy: if True, produce legacy pyc paths instead of PEP 3147 paths optimize: int or list of optimization levels or -1 for level of the interpreter. Multiple levels leads to multiple compiled files each with one optimization level. workers: maximum number of parallel workers invalidation_mode: how the up-to-dateness of the pyc will be checked stripdir: part of path to left-strip from source file path prependdir: path to prepend to beginning of original file path, applied after stripdir limit_sl_dest: ignore symlinks if they are pointing outside of the defined path hardlink_dupes: hardlink duplicated pyc files
Byte-compile all modules in the given directory tree.
[ "Byte", "-", "compile", "all", "modules", "in", "the", "given", "directory", "tree", "." ]
def compile_dir(dir, maxlevels=None, ddir=None, force=False, rx=None, quiet=0, legacy=False, optimize=-1, workers=1, invalidation_mode=None, *, stripdir=None, prependdir=None, limit_sl_dest=None, hardlink_dupes=False): """Byte-compile all modules in the given directory tree. Arguments (only dir is required): dir: the directory to byte-compile maxlevels: maximum recursion level (default `sys.getrecursionlimit()`) ddir: the directory that will be prepended to the path to the file as it is compiled into each byte-code file. force: if True, force compilation, even if timestamps are up-to-date quiet: full output with False or 0, errors only with 1, no output with 2 legacy: if True, produce legacy pyc paths instead of PEP 3147 paths optimize: int or list of optimization levels or -1 for level of the interpreter. Multiple levels leads to multiple compiled files each with one optimization level. workers: maximum number of parallel workers invalidation_mode: how the up-to-dateness of the pyc will be checked stripdir: part of path to left-strip from source file path prependdir: path to prepend to beginning of original file path, applied after stripdir limit_sl_dest: ignore symlinks if they are pointing outside of the defined path hardlink_dupes: hardlink duplicated pyc files """ ProcessPoolExecutor = None if ddir is not None and (stripdir is not None or prependdir is not None): raise ValueError(("Destination dir (ddir) cannot be used " "in combination with stripdir or prependdir")) if ddir is not None: stripdir = dir prependdir = ddir ddir = None if workers < 0: raise ValueError('workers must be greater or equal to 0') if workers != 1: try: # Only import when needed, as low resource platforms may # fail to import it from concurrent.futures import ProcessPoolExecutor except ImportError: workers = 1 if maxlevels is None: maxlevels = sys.getrecursionlimit() files = _walk_dir(dir, quiet=quiet, maxlevels=maxlevels) success = True if workers != 1 and ProcessPoolExecutor is not None: # If workers == 0, let ProcessPoolExecutor choose workers = workers or None with ProcessPoolExecutor(max_workers=workers) as executor: results = executor.map(partial(compile_file, ddir=ddir, force=force, rx=rx, quiet=quiet, legacy=legacy, optimize=optimize, invalidation_mode=invalidation_mode, stripdir=stripdir, prependdir=prependdir, limit_sl_dest=limit_sl_dest, hardlink_dupes=hardlink_dupes), files) success = min(results, default=True) else: for file in files: if not compile_file(file, ddir, force, rx, quiet, legacy, optimize, invalidation_mode, stripdir=stripdir, prependdir=prependdir, limit_sl_dest=limit_sl_dest, hardlink_dupes=hardlink_dupes): success = False return success
[ "def", "compile_dir", "(", "dir", ",", "maxlevels", "=", "None", ",", "ddir", "=", "None", ",", "force", "=", "False", ",", "rx", "=", "None", ",", "quiet", "=", "0", ",", "legacy", "=", "False", ",", "optimize", "=", "-", "1", ",", "workers", "=", "1", ",", "invalidation_mode", "=", "None", ",", "*", ",", "stripdir", "=", "None", ",", "prependdir", "=", "None", ",", "limit_sl_dest", "=", "None", ",", "hardlink_dupes", "=", "False", ")", ":", "ProcessPoolExecutor", "=", "None", "if", "ddir", "is", "not", "None", "and", "(", "stripdir", "is", "not", "None", "or", "prependdir", "is", "not", "None", ")", ":", "raise", "ValueError", "(", "(", "\"Destination dir (ddir) cannot be used \"", "\"in combination with stripdir or prependdir\"", ")", ")", "if", "ddir", "is", "not", "None", ":", "stripdir", "=", "dir", "prependdir", "=", "ddir", "ddir", "=", "None", "if", "workers", "<", "0", ":", "raise", "ValueError", "(", "'workers must be greater or equal to 0'", ")", "if", "workers", "!=", "1", ":", "try", ":", "# Only import when needed, as low resource platforms may", "# fail to import it", "from", "concurrent", ".", "futures", "import", "ProcessPoolExecutor", "except", "ImportError", ":", "workers", "=", "1", "if", "maxlevels", "is", "None", ":", "maxlevels", "=", "sys", ".", "getrecursionlimit", "(", ")", "files", "=", "_walk_dir", "(", "dir", ",", "quiet", "=", "quiet", ",", "maxlevels", "=", "maxlevels", ")", "success", "=", "True", "if", "workers", "!=", "1", "and", "ProcessPoolExecutor", "is", "not", "None", ":", "# If workers == 0, let ProcessPoolExecutor choose", "workers", "=", "workers", "or", "None", "with", "ProcessPoolExecutor", "(", "max_workers", "=", "workers", ")", "as", "executor", ":", "results", "=", "executor", ".", "map", "(", "partial", "(", "compile_file", ",", "ddir", "=", "ddir", ",", "force", "=", "force", ",", "rx", "=", "rx", ",", "quiet", "=", "quiet", ",", "legacy", "=", "legacy", ",", "optimize", "=", "optimize", ",", "invalidation_mode", "=", "invalidation_mode", ",", "stripdir", "=", "stripdir", ",", "prependdir", "=", "prependdir", ",", "limit_sl_dest", "=", "limit_sl_dest", ",", "hardlink_dupes", "=", "hardlink_dupes", ")", ",", "files", ")", "success", "=", "min", "(", "results", ",", "default", "=", "True", ")", "else", ":", "for", "file", "in", "files", ":", "if", "not", "compile_file", "(", "file", ",", "ddir", ",", "force", ",", "rx", ",", "quiet", ",", "legacy", ",", "optimize", ",", "invalidation_mode", ",", "stripdir", "=", "stripdir", ",", "prependdir", "=", "prependdir", ",", "limit_sl_dest", "=", "limit_sl_dest", ",", "hardlink_dupes", "=", "hardlink_dupes", ")", ":", "success", "=", "False", "return", "success" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/compileall.py#L48-L121
commaai/openpilot
4416c21b1e738ab7d04147c5ae52b5135e0cdb40
tools/lib/kbhit.py
python
KBHit.kbhit
()
return select([sys.stdin], [], [], 0)[0] != []
Returns True if keyboard character was hit, False otherwise.
Returns True if keyboard character was hit, False otherwise.
[ "Returns", "True", "if", "keyboard", "character", "was", "hit", "False", "otherwise", "." ]
def kbhit(): ''' Returns True if keyboard character was hit, False otherwise. ''' return select([sys.stdin], [], [], 0)[0] != []
[ "def", "kbhit", "(", ")", ":", "return", "select", "(", "[", "sys", ".", "stdin", "]", ",", "[", "]", ",", "[", "]", ",", "0", ")", "[", "0", "]", "!=", "[", "]" ]
https://github.com/commaai/openpilot/blob/4416c21b1e738ab7d04147c5ae52b5135e0cdb40/tools/lib/kbhit.py#L60-L63
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/flatmenu.py
python
FlatMenuBar.ResetToolbarItems
(self)
Used internally.
Used internally.
[ "Used", "internally", "." ]
def ResetToolbarItems(self): """ Used internally. """ for but in self._tbButtons: but._state = ControlNormal
[ "def", "ResetToolbarItems", "(", "self", ")", ":", "for", "but", "in", "self", ".", "_tbButtons", ":", "but", ".", "_state", "=", "ControlNormal" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/flatmenu.py#L3100-L3104
LiquidPlayer/LiquidCore
9405979363f2353ac9a71ad8ab59685dd7f919c9
deps/node-10.15.3/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/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.iteritems(): (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", ".", "iteritems", "(", ")", ":", "(", "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/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xcodeproj_file.py#L474-L485
google/earthenterprise
0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9
earth_enterprise/src/support/parse_khhttpd_access_log.py
python
KML.closeFolder
(self)
return kml
Closes folder element.
Closes folder element.
[ "Closes", "folder", "element", "." ]
def closeFolder(self): '''Closes folder element.''' kml = '</Folder>\n' return kml
[ "def", "closeFolder", "(", "self", ")", ":", "kml", "=", "'</Folder>\\n'", "return", "kml" ]
https://github.com/google/earthenterprise/blob/0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9/earth_enterprise/src/support/parse_khhttpd_access_log.py#L193-L196
carla-simulator/carla
8854804f4d7748e14d937ec763a2912823a7e5f5
PythonAPI/examples/rss/rss_visualization.py
python
RssBoundingBoxVisualizer._create_bb_points
(vehicle)
return cords
Returns 3D bounding box for a vehicle.
Returns 3D bounding box for a vehicle.
[ "Returns", "3D", "bounding", "box", "for", "a", "vehicle", "." ]
def _create_bb_points(vehicle): """ Returns 3D bounding box for a vehicle. """ cords = np.zeros((8, 4)) extent = vehicle.bounding_box.extent cords[0, :] = np.array([extent.x, extent.y, -extent.z, 1]) cords[1, :] = np.array([-extent.x, extent.y, -extent.z, 1]) cords[2, :] = np.array([-extent.x, -extent.y, -extent.z, 1]) cords[3, :] = np.array([extent.x, -extent.y, -extent.z, 1]) cords[4, :] = np.array([extent.x, extent.y, extent.z, 1]) cords[5, :] = np.array([-extent.x, extent.y, extent.z, 1]) cords[6, :] = np.array([-extent.x, -extent.y, extent.z, 1]) cords[7, :] = np.array([extent.x, -extent.y, extent.z, 1]) return cords
[ "def", "_create_bb_points", "(", "vehicle", ")", ":", "cords", "=", "np", ".", "zeros", "(", "(", "8", ",", "4", ")", ")", "extent", "=", "vehicle", ".", "bounding_box", ".", "extent", "cords", "[", "0", ",", ":", "]", "=", "np", ".", "array", "(", "[", "extent", ".", "x", ",", "extent", ".", "y", ",", "-", "extent", ".", "z", ",", "1", "]", ")", "cords", "[", "1", ",", ":", "]", "=", "np", ".", "array", "(", "[", "-", "extent", ".", "x", ",", "extent", ".", "y", ",", "-", "extent", ".", "z", ",", "1", "]", ")", "cords", "[", "2", ",", ":", "]", "=", "np", ".", "array", "(", "[", "-", "extent", ".", "x", ",", "-", "extent", ".", "y", ",", "-", "extent", ".", "z", ",", "1", "]", ")", "cords", "[", "3", ",", ":", "]", "=", "np", ".", "array", "(", "[", "extent", ".", "x", ",", "-", "extent", ".", "y", ",", "-", "extent", ".", "z", ",", "1", "]", ")", "cords", "[", "4", ",", ":", "]", "=", "np", ".", "array", "(", "[", "extent", ".", "x", ",", "extent", ".", "y", ",", "extent", ".", "z", ",", "1", "]", ")", "cords", "[", "5", ",", ":", "]", "=", "np", ".", "array", "(", "[", "-", "extent", ".", "x", ",", "extent", ".", "y", ",", "extent", ".", "z", ",", "1", "]", ")", "cords", "[", "6", ",", ":", "]", "=", "np", ".", "array", "(", "[", "-", "extent", ".", "x", ",", "-", "extent", ".", "y", ",", "extent", ".", "z", ",", "1", "]", ")", "cords", "[", "7", ",", ":", "]", "=", "np", ".", "array", "(", "[", "extent", ".", "x", ",", "-", "extent", ".", "y", ",", "extent", ".", "z", ",", "1", "]", ")", "return", "cords" ]
https://github.com/carla-simulator/carla/blob/8854804f4d7748e14d937ec763a2912823a7e5f5/PythonAPI/examples/rss/rss_visualization.py#L533-L548
SoarGroup/Soar
a1c5e249499137a27da60533c72969eef3b8ab6b
scons/scons-local-4.1.0/SCons/SConf.py
python
CheckProg
(context, prog_name)
return res
Simple check if a program exists in the path. Returns the path for the application, or None if not found.
Simple check if a program exists in the path. Returns the path for the application, or None if not found.
[ "Simple", "check", "if", "a", "program", "exists", "in", "the", "path", ".", "Returns", "the", "path", "for", "the", "application", "or", "None", "if", "not", "found", "." ]
def CheckProg(context, prog_name): """Simple check if a program exists in the path. Returns the path for the application, or None if not found. """ res = SCons.Conftest.CheckProg(context, prog_name) context.did_show_result = 1 return res
[ "def", "CheckProg", "(", "context", ",", "prog_name", ")", ":", "res", "=", "SCons", ".", "Conftest", ".", "CheckProg", "(", "context", ",", "prog_name", ")", "context", ".", "did_show_result", "=", "1", "return", "res" ]
https://github.com/SoarGroup/Soar/blob/a1c5e249499137a27da60533c72969eef3b8ab6b/scons/scons-local-4.1.0/SCons/SConf.py#L1104-L1110
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py3/pandas/core/base.py
python
IndexOpsMixin._memory_usage
(self, deep: bool = False)
return v
Memory usage of the values. Parameters ---------- deep : bool, default False Introspect the data deeply, interrogate `object` dtypes for system-level memory consumption. Returns ------- bytes used See Also -------- numpy.ndarray.nbytes : Total bytes consumed by the elements of the array. Notes ----- Memory usage does not include memory consumed by elements that are not components of the array if deep=False or if used on PyPy
Memory usage of the values.
[ "Memory", "usage", "of", "the", "values", "." ]
def _memory_usage(self, deep: bool = False) -> int: """ Memory usage of the values. Parameters ---------- deep : bool, default False Introspect the data deeply, interrogate `object` dtypes for system-level memory consumption. Returns ------- bytes used See Also -------- numpy.ndarray.nbytes : Total bytes consumed by the elements of the array. Notes ----- Memory usage does not include memory consumed by elements that are not components of the array if deep=False or if used on PyPy """ if hasattr(self.array, "memory_usage"): # error: "ExtensionArray" has no attribute "memory_usage" return self.array.memory_usage(deep=deep) # type: ignore[attr-defined] v = self.array.nbytes if deep and is_object_dtype(self) and not PYPY: values = cast(np.ndarray, self._values) v += lib.memory_usage_of_objects(values) return v
[ "def", "_memory_usage", "(", "self", ",", "deep", ":", "bool", "=", "False", ")", "->", "int", ":", "if", "hasattr", "(", "self", ".", "array", ",", "\"memory_usage\"", ")", ":", "# error: \"ExtensionArray\" has no attribute \"memory_usage\"", "return", "self", ".", "array", ".", "memory_usage", "(", "deep", "=", "deep", ")", "# type: ignore[attr-defined]", "v", "=", "self", ".", "array", ".", "nbytes", "if", "deep", "and", "is_object_dtype", "(", "self", ")", "and", "not", "PYPY", ":", "values", "=", "cast", "(", "np", ".", "ndarray", ",", "self", ".", "_values", ")", "v", "+=", "lib", ".", "memory_usage_of_objects", "(", "values", ")", "return", "v" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/base.py#L1069-L1101
panda3d/panda3d
833ad89ebad58395d0af0b7ec08538e5e4308265
direct/src/gui/OnscreenText.py
python
OnscreenText.__init__
(self, text = '', style = Plain, pos = (0, 0), roll = 0, scale = None, fg = None, bg = None, shadow = None, shadowOffset = (0.04, 0.04), frame = None, align = None, wordwrap = None, drawOrder = None, decal = 0, font = None, parent = None, sort = 0, mayChange = True, direction = None)
Make a text node from string, put it into the 2d sg and set it up with all the indicated parameters. Parameters: text: the actual text to display. This may be omitted and specified later via setText() if you don't have it available, but it is better to specify it up front. style: one of the pre-canned style parameters defined at the head of this file. This sets up the default values for many of the remaining parameters if they are unspecified; however, a parameter may still be specified to explicitly set it, overriding the pre-canned style. pos: the x, y position of the text on the screen. scale: the size of the text. This may either be a single float (and it will usually be a small number like 0.07) or it may be a 2-tuple of floats, specifying a different x, y scale. fg: the (r, g, b, a) foreground color of the text. This is normally a 4-tuple of floats or ints. bg: the (r, g, b, a) background color of the text. If the fourth value, a, is nonzero, a card is created to place behind the text and set to the given color. shadow: the (r, g, b, a) color of the shadow behind the text. If the fourth value, a, is nonzero, a little drop shadow is created and placed behind the text. frame: the (r, g, b, a) color of the frame drawn around the text. If the fourth value, a, is nonzero, a frame is created around the text. align: one of TextNode.ALeft, TextNode.ARight, or TextNode.ACenter. wordwrap: either the width to wordwrap the text at, or None to specify no automatic word wrapping. drawOrder: the drawing order of this text with respect to all other things in the 'fixed' bin within render2d. The text will actually use drawOrder through drawOrder + 2. decal: if this is True, the text is decalled onto its background card. Useful when the text will be parented into the 3-D scene graph. font: the font to use for the text. parent: the NodePath to parent the text to initially. mayChange: pass true if the text or its properties may need to be changed at runtime, false if it is static once created (which leads to better memory optimization). direction: this can be set to 'ltr' or 'rtl' to override the direction of the text.
Make a text node from string, put it into the 2d sg and set it up with all the indicated parameters.
[ "Make", "a", "text", "node", "from", "string", "put", "it", "into", "the", "2d", "sg", "and", "set", "it", "up", "with", "all", "the", "indicated", "parameters", "." ]
def __init__(self, text = '', style = Plain, pos = (0, 0), roll = 0, scale = None, fg = None, bg = None, shadow = None, shadowOffset = (0.04, 0.04), frame = None, align = None, wordwrap = None, drawOrder = None, decal = 0, font = None, parent = None, sort = 0, mayChange = True, direction = None): """ Make a text node from string, put it into the 2d sg and set it up with all the indicated parameters. Parameters: text: the actual text to display. This may be omitted and specified later via setText() if you don't have it available, but it is better to specify it up front. style: one of the pre-canned style parameters defined at the head of this file. This sets up the default values for many of the remaining parameters if they are unspecified; however, a parameter may still be specified to explicitly set it, overriding the pre-canned style. pos: the x, y position of the text on the screen. scale: the size of the text. This may either be a single float (and it will usually be a small number like 0.07) or it may be a 2-tuple of floats, specifying a different x, y scale. fg: the (r, g, b, a) foreground color of the text. This is normally a 4-tuple of floats or ints. bg: the (r, g, b, a) background color of the text. If the fourth value, a, is nonzero, a card is created to place behind the text and set to the given color. shadow: the (r, g, b, a) color of the shadow behind the text. If the fourth value, a, is nonzero, a little drop shadow is created and placed behind the text. frame: the (r, g, b, a) color of the frame drawn around the text. If the fourth value, a, is nonzero, a frame is created around the text. align: one of TextNode.ALeft, TextNode.ARight, or TextNode.ACenter. wordwrap: either the width to wordwrap the text at, or None to specify no automatic word wrapping. drawOrder: the drawing order of this text with respect to all other things in the 'fixed' bin within render2d. The text will actually use drawOrder through drawOrder + 2. decal: if this is True, the text is decalled onto its background card. Useful when the text will be parented into the 3-D scene graph. font: the font to use for the text. parent: the NodePath to parent the text to initially. mayChange: pass true if the text or its properties may need to be changed at runtime, false if it is static once created (which leads to better memory optimization). direction: this can be set to 'ltr' or 'rtl' to override the direction of the text. """ if parent is None: from direct.showbase import ShowBaseGlobal parent = ShowBaseGlobal.aspect2d # make a text node textNode = TextNode('') self.textNode = textNode # We ARE a node path. Initially, we're an empty node path. NodePath.__init__(self) # Choose the default parameters according to the selected # style. if style == Plain: scale = scale or 0.07 fg = fg or (0, 0, 0, 1) bg = bg or (0, 0, 0, 0) shadow = shadow or (0, 0, 0, 0) frame = frame or (0, 0, 0, 0) if align is None: align = TextNode.ACenter elif style == ScreenTitle: scale = scale or 0.15 fg = fg or (1, 0.2, 0.2, 1) bg = bg or (0, 0, 0, 0) shadow = shadow or (0, 0, 0, 1) frame = frame or (0, 0, 0, 0) if align is None: align = TextNode.ACenter elif style == ScreenPrompt: scale = scale or 0.1 fg = fg or (1, 1, 0, 1) bg = bg or (0, 0, 0, 0) shadow = shadow or (0, 0, 0, 1) frame = frame or (0, 0, 0, 0) if align is None: align = TextNode.ACenter elif style == NameConfirm: scale = scale or 0.1 fg = fg or (0, 1, 0, 1) bg = bg or (0, 0, 0, 0) shadow = shadow or (0, 0, 0, 0) frame = frame or (0, 0, 0, 0) if align is None: align = TextNode.ACenter elif style == BlackOnWhite: scale = scale or 0.1 fg = fg or (0, 0, 0, 1) bg = bg or (1, 1, 1, 1) shadow = shadow or (0, 0, 0, 0) frame = frame or (0, 0, 0, 0) if align is None: align = TextNode.ACenter else: raise ValueError if not isinstance(scale, tuple): # If the scale is already a tuple, it's a 2-d (x, y) scale. # Otherwise, it's a uniform scale--make it a tuple. scale = (scale, scale) # Save some of the parameters for posterity. self.__scale = scale self.__pos = pos self.__roll = roll self.__wordwrap = wordwrap if decal: textNode.setCardDecal(1) if font is None: font = DGG.getDefaultFont() textNode.setFont(font) textNode.setTextColor(fg[0], fg[1], fg[2], fg[3]) textNode.setAlign(align) if wordwrap: textNode.setWordwrap(wordwrap) if bg[3] != 0: # If we have a background color, create a card. textNode.setCardColor(bg[0], bg[1], bg[2], bg[3]) textNode.setCardAsMargin(0.1, 0.1, 0.1, 0.1) if shadow[3] != 0: # If we have a shadow color, create a shadow. # Can't use the *shadow interface because it might be a VBase4. #textNode.setShadowColor(*shadow) textNode.setShadowColor(shadow[0], shadow[1], shadow[2], shadow[3]) textNode.setShadow(*shadowOffset) if frame[3] != 0: # If we have a frame color, create a frame. textNode.setFrameColor(frame[0], frame[1], frame[2], frame[3]) textNode.setFrameAsMargin(0.1, 0.1, 0.1, 0.1) if direction is not None: if isinstance(direction, str): direction = direction.lower() if direction == 'rtl': direction = TextProperties.D_rtl elif direction == 'ltr': direction = TextProperties.D_ltr else: raise ValueError('invalid direction') textNode.setDirection(direction) # Create a transform for the text for our scale and position. # We'd rather do it here, on the text itself, rather than on # our NodePath, so we have one fewer transforms in the scene # graph. self.updateTransformMat() if drawOrder is not None: textNode.setBin('fixed') textNode.setDrawOrder(drawOrder) self.setText(text) if not text: # If we don't have any text, assume we'll be changing it later. self.mayChange = 1 else: self.mayChange = mayChange # Ok, now update the node. if not self.mayChange: # If we aren't going to change the text later, we can # throw away the TextNode. self.textNode = textNode.generate() self.isClean = 0 # Set ourselves up as the NodePath that points to this node. self.assign(parent.attachNewNode(self.textNode, sort))
[ "def", "__init__", "(", "self", ",", "text", "=", "''", ",", "style", "=", "Plain", ",", "pos", "=", "(", "0", ",", "0", ")", ",", "roll", "=", "0", ",", "scale", "=", "None", ",", "fg", "=", "None", ",", "bg", "=", "None", ",", "shadow", "=", "None", ",", "shadowOffset", "=", "(", "0.04", ",", "0.04", ")", ",", "frame", "=", "None", ",", "align", "=", "None", ",", "wordwrap", "=", "None", ",", "drawOrder", "=", "None", ",", "decal", "=", "0", ",", "font", "=", "None", ",", "parent", "=", "None", ",", "sort", "=", "0", ",", "mayChange", "=", "True", ",", "direction", "=", "None", ")", ":", "if", "parent", "is", "None", ":", "from", "direct", ".", "showbase", "import", "ShowBaseGlobal", "parent", "=", "ShowBaseGlobal", ".", "aspect2d", "# make a text node", "textNode", "=", "TextNode", "(", "''", ")", "self", ".", "textNode", "=", "textNode", "# We ARE a node path. Initially, we're an empty node path.", "NodePath", ".", "__init__", "(", "self", ")", "# Choose the default parameters according to the selected", "# style.", "if", "style", "==", "Plain", ":", "scale", "=", "scale", "or", "0.07", "fg", "=", "fg", "or", "(", "0", ",", "0", ",", "0", ",", "1", ")", "bg", "=", "bg", "or", "(", "0", ",", "0", ",", "0", ",", "0", ")", "shadow", "=", "shadow", "or", "(", "0", ",", "0", ",", "0", ",", "0", ")", "frame", "=", "frame", "or", "(", "0", ",", "0", ",", "0", ",", "0", ")", "if", "align", "is", "None", ":", "align", "=", "TextNode", ".", "ACenter", "elif", "style", "==", "ScreenTitle", ":", "scale", "=", "scale", "or", "0.15", "fg", "=", "fg", "or", "(", "1", ",", "0.2", ",", "0.2", ",", "1", ")", "bg", "=", "bg", "or", "(", "0", ",", "0", ",", "0", ",", "0", ")", "shadow", "=", "shadow", "or", "(", "0", ",", "0", ",", "0", ",", "1", ")", "frame", "=", "frame", "or", "(", "0", ",", "0", ",", "0", ",", "0", ")", "if", "align", "is", "None", ":", "align", "=", "TextNode", ".", "ACenter", "elif", "style", "==", "ScreenPrompt", ":", "scale", "=", "scale", "or", "0.1", "fg", "=", "fg", "or", "(", "1", ",", "1", ",", "0", ",", "1", ")", "bg", "=", "bg", "or", "(", "0", ",", "0", ",", "0", ",", "0", ")", "shadow", "=", "shadow", "or", "(", "0", ",", "0", ",", "0", ",", "1", ")", "frame", "=", "frame", "or", "(", "0", ",", "0", ",", "0", ",", "0", ")", "if", "align", "is", "None", ":", "align", "=", "TextNode", ".", "ACenter", "elif", "style", "==", "NameConfirm", ":", "scale", "=", "scale", "or", "0.1", "fg", "=", "fg", "or", "(", "0", ",", "1", ",", "0", ",", "1", ")", "bg", "=", "bg", "or", "(", "0", ",", "0", ",", "0", ",", "0", ")", "shadow", "=", "shadow", "or", "(", "0", ",", "0", ",", "0", ",", "0", ")", "frame", "=", "frame", "or", "(", "0", ",", "0", ",", "0", ",", "0", ")", "if", "align", "is", "None", ":", "align", "=", "TextNode", ".", "ACenter", "elif", "style", "==", "BlackOnWhite", ":", "scale", "=", "scale", "or", "0.1", "fg", "=", "fg", "or", "(", "0", ",", "0", ",", "0", ",", "1", ")", "bg", "=", "bg", "or", "(", "1", ",", "1", ",", "1", ",", "1", ")", "shadow", "=", "shadow", "or", "(", "0", ",", "0", ",", "0", ",", "0", ")", "frame", "=", "frame", "or", "(", "0", ",", "0", ",", "0", ",", "0", ")", "if", "align", "is", "None", ":", "align", "=", "TextNode", ".", "ACenter", "else", ":", "raise", "ValueError", "if", "not", "isinstance", "(", "scale", ",", "tuple", ")", ":", "# If the scale is already a tuple, it's a 2-d (x, y) scale.", "# Otherwise, it's a uniform scale--make it a tuple.", "scale", "=", "(", "scale", ",", "scale", ")", "# Save some of the parameters for posterity.", "self", ".", "__scale", "=", "scale", "self", ".", "__pos", "=", "pos", "self", ".", "__roll", "=", "roll", "self", ".", "__wordwrap", "=", "wordwrap", "if", "decal", ":", "textNode", ".", "setCardDecal", "(", "1", ")", "if", "font", "is", "None", ":", "font", "=", "DGG", ".", "getDefaultFont", "(", ")", "textNode", ".", "setFont", "(", "font", ")", "textNode", ".", "setTextColor", "(", "fg", "[", "0", "]", ",", "fg", "[", "1", "]", ",", "fg", "[", "2", "]", ",", "fg", "[", "3", "]", ")", "textNode", ".", "setAlign", "(", "align", ")", "if", "wordwrap", ":", "textNode", ".", "setWordwrap", "(", "wordwrap", ")", "if", "bg", "[", "3", "]", "!=", "0", ":", "# If we have a background color, create a card.", "textNode", ".", "setCardColor", "(", "bg", "[", "0", "]", ",", "bg", "[", "1", "]", ",", "bg", "[", "2", "]", ",", "bg", "[", "3", "]", ")", "textNode", ".", "setCardAsMargin", "(", "0.1", ",", "0.1", ",", "0.1", ",", "0.1", ")", "if", "shadow", "[", "3", "]", "!=", "0", ":", "# If we have a shadow color, create a shadow.", "# Can't use the *shadow interface because it might be a VBase4.", "#textNode.setShadowColor(*shadow)", "textNode", ".", "setShadowColor", "(", "shadow", "[", "0", "]", ",", "shadow", "[", "1", "]", ",", "shadow", "[", "2", "]", ",", "shadow", "[", "3", "]", ")", "textNode", ".", "setShadow", "(", "*", "shadowOffset", ")", "if", "frame", "[", "3", "]", "!=", "0", ":", "# If we have a frame color, create a frame.", "textNode", ".", "setFrameColor", "(", "frame", "[", "0", "]", ",", "frame", "[", "1", "]", ",", "frame", "[", "2", "]", ",", "frame", "[", "3", "]", ")", "textNode", ".", "setFrameAsMargin", "(", "0.1", ",", "0.1", ",", "0.1", ",", "0.1", ")", "if", "direction", "is", "not", "None", ":", "if", "isinstance", "(", "direction", ",", "str", ")", ":", "direction", "=", "direction", ".", "lower", "(", ")", "if", "direction", "==", "'rtl'", ":", "direction", "=", "TextProperties", ".", "D_rtl", "elif", "direction", "==", "'ltr'", ":", "direction", "=", "TextProperties", ".", "D_ltr", "else", ":", "raise", "ValueError", "(", "'invalid direction'", ")", "textNode", ".", "setDirection", "(", "direction", ")", "# Create a transform for the text for our scale and position.", "# We'd rather do it here, on the text itself, rather than on", "# our NodePath, so we have one fewer transforms in the scene", "# graph.", "self", ".", "updateTransformMat", "(", ")", "if", "drawOrder", "is", "not", "None", ":", "textNode", ".", "setBin", "(", "'fixed'", ")", "textNode", ".", "setDrawOrder", "(", "drawOrder", ")", "self", ".", "setText", "(", "text", ")", "if", "not", "text", ":", "# If we don't have any text, assume we'll be changing it later.", "self", ".", "mayChange", "=", "1", "else", ":", "self", ".", "mayChange", "=", "mayChange", "# Ok, now update the node.", "if", "not", "self", ".", "mayChange", ":", "# If we aren't going to change the text later, we can", "# throw away the TextNode.", "self", ".", "textNode", "=", "textNode", ".", "generate", "(", ")", "self", ".", "isClean", "=", "0", "# Set ourselves up as the NodePath that points to this node.", "self", ".", "assign", "(", "parent", ".", "attachNewNode", "(", "self", ".", "textNode", ",", "sort", ")", ")" ]
https://github.com/panda3d/panda3d/blob/833ad89ebad58395d0af0b7ec08538e5e4308265/direct/src/gui/OnscreenText.py#L25-L241
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/eager/function.py
python
_ForwardBackwardCall.record
(self, flat_outputs)
Given outputs from the execution of `forward`, records the operation.
Given outputs from the execution of `forward`, records the operation.
[ "Given", "outputs", "from", "the", "execution", "of", "forward", "records", "the", "operation", "." ]
def record(self, flat_outputs): """Given outputs from the execution of `forward`, records the operation.""" if (self._tape_watching and not isinstance(flat_outputs, ops.Operation) and flat_outputs is not None): # We only record function calls which have outputs, and then only when a # tape is watching. self._functions.record( flat_outputs, self._inference_args, self._input_tangents)
[ "def", "record", "(", "self", ",", "flat_outputs", ")", ":", "if", "(", "self", ".", "_tape_watching", "and", "not", "isinstance", "(", "flat_outputs", ",", "ops", ".", "Operation", ")", "and", "flat_outputs", "is", "not", "None", ")", ":", "# We only record function calls which have outputs, and then only when a", "# tape is watching.", "self", ".", "_functions", ".", "record", "(", "flat_outputs", ",", "self", ".", "_inference_args", ",", "self", ".", "_input_tangents", ")" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/eager/function.py#L1402-L1410
metashell/metashell
f4177e4854ea00c8dbc722cadab26ef413d798ea
3rd/templight/clang/bindings/python/clang/cindex.py
python
TokenGroup.get_tokens
(tu, extent)
Helper method to return all tokens in an extent. This functionality is needed multiple places in this module. We define it here because it seems like a logical place.
Helper method to return all tokens in an extent.
[ "Helper", "method", "to", "return", "all", "tokens", "in", "an", "extent", "." ]
def get_tokens(tu, extent): """Helper method to return all tokens in an extent. This functionality is needed multiple places in this module. We define it here because it seems like a logical place. """ tokens_memory = POINTER(Token)() tokens_count = c_uint() conf.lib.clang_tokenize(tu, extent, byref(tokens_memory), byref(tokens_count)) count = int(tokens_count.value) # If we get no tokens, no memory was allocated. Be sure not to return # anything and potentially call a destructor on nothing. if count < 1: return tokens_array = cast(tokens_memory, POINTER(Token * count)).contents token_group = TokenGroup(tu, tokens_memory, tokens_count) for i in range(0, count): token = Token() token.int_data = tokens_array[i].int_data token.ptr_data = tokens_array[i].ptr_data token._tu = tu token._group = token_group yield token
[ "def", "get_tokens", "(", "tu", ",", "extent", ")", ":", "tokens_memory", "=", "POINTER", "(", "Token", ")", "(", ")", "tokens_count", "=", "c_uint", "(", ")", "conf", ".", "lib", ".", "clang_tokenize", "(", "tu", ",", "extent", ",", "byref", "(", "tokens_memory", ")", ",", "byref", "(", "tokens_count", ")", ")", "count", "=", "int", "(", "tokens_count", ".", "value", ")", "# If we get no tokens, no memory was allocated. Be sure not to return", "# anything and potentially call a destructor on nothing.", "if", "count", "<", "1", ":", "return", "tokens_array", "=", "cast", "(", "tokens_memory", ",", "POINTER", "(", "Token", "*", "count", ")", ")", ".", "contents", "token_group", "=", "TokenGroup", "(", "tu", ",", "tokens_memory", ",", "tokens_count", ")", "for", "i", "in", "range", "(", "0", ",", "count", ")", ":", "token", "=", "Token", "(", ")", "token", ".", "int_data", "=", "tokens_array", "[", "i", "]", ".", "int_data", "token", ".", "ptr_data", "=", "tokens_array", "[", "i", "]", ".", "ptr_data", "token", ".", "_tu", "=", "tu", "token", ".", "_group", "=", "token_group", "yield", "token" ]
https://github.com/metashell/metashell/blob/f4177e4854ea00c8dbc722cadab26ef413d798ea/3rd/templight/clang/bindings/python/clang/cindex.py#L541-L571
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/statistics.py
python
fmean
(data)
Convert data to floats and compute the arithmetic mean. This runs faster than the mean() function and it always returns a float. If the input dataset is empty, it raises a StatisticsError. >>> fmean([3.5, 4.0, 5.25]) 4.25
Convert data to floats and compute the arithmetic mean.
[ "Convert", "data", "to", "floats", "and", "compute", "the", "arithmetic", "mean", "." ]
def fmean(data): """Convert data to floats and compute the arithmetic mean. This runs faster than the mean() function and it always returns a float. If the input dataset is empty, it raises a StatisticsError. >>> fmean([3.5, 4.0, 5.25]) 4.25 """ try: n = len(data) except TypeError: # Handle iterators that do not define __len__(). n = 0 def count(iterable): nonlocal n for n, x in enumerate(iterable, start=1): yield x total = fsum(count(data)) else: total = fsum(data) try: return total / n except ZeroDivisionError: raise StatisticsError('fmean requires at least one data point') from None
[ "def", "fmean", "(", "data", ")", ":", "try", ":", "n", "=", "len", "(", "data", ")", "except", "TypeError", ":", "# Handle iterators that do not define __len__().", "n", "=", "0", "def", "count", "(", "iterable", ")", ":", "nonlocal", "n", "for", "n", ",", "x", "in", "enumerate", "(", "iterable", ",", "start", "=", "1", ")", ":", "yield", "x", "total", "=", "fsum", "(", "count", "(", "data", ")", ")", "else", ":", "total", "=", "fsum", "(", "data", ")", "try", ":", "return", "total", "/", "n", "except", "ZeroDivisionError", ":", "raise", "StatisticsError", "(", "'fmean requires at least one data point'", ")", "from", "None" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/statistics.py#L321-L345
cloudendpoints/esp
2c4f1df4b9cc82e0682ce4713d470b61b8f970de
start_esp/fetch_service_config.py
python
fetch_service_name
(metadata)
return name
Fetch service name from metadata URL.
Fetch service name from metadata URL.
[ "Fetch", "service", "name", "from", "metadata", "URL", "." ]
def fetch_service_name(metadata): """Fetch service name from metadata URL.""" name = fetch_metadata( metadata, _INSTANCE_ATTRIBUTES + _METADATA_SERVICE_NAME, True) logging.info("Service name: " + name) return name
[ "def", "fetch_service_name", "(", "metadata", ")", ":", "name", "=", "fetch_metadata", "(", "metadata", ",", "_INSTANCE_ATTRIBUTES", "+", "_METADATA_SERVICE_NAME", ",", "True", ")", "logging", ".", "info", "(", "\"Service name: \"", "+", "name", ")", "return", "name" ]
https://github.com/cloudendpoints/esp/blob/2c4f1df4b9cc82e0682ce4713d470b61b8f970de/start_esp/fetch_service_config.py#L94-L99
synfig/synfig
a5ec91db5b751dc12e4400ccfb5c063fd6d2d928
synfig-studio/plugins/lottie-exporter/export_without_variable_width.py
python
init_logs
()
Initializes the logger, sets the level of the logging(DEBUG | INFO : depending on what is specified)
Initializes the logger, sets the level of the logging(DEBUG | INFO : depending on what is specified)
[ "Initializes", "the", "logger", "sets", "the", "level", "of", "the", "logging", "(", "DEBUG", "|", "INFO", ":", "depending", "on", "what", "is", "specified", ")" ]
def init_logs(): """ Initializes the logger, sets the level of the logging(DEBUG | INFO : depending on what is specified) """ logging.basicConfig(stream=sys.stdout, format='%(name)s - %(levelname)s - %(message)s') logging.getLogger().setLevel(logging.DEBUG)
[ "def", "init_logs", "(", ")", ":", "logging", ".", "basicConfig", "(", "stream", "=", "sys", ".", "stdout", ",", "format", "=", "'%(name)s - %(levelname)s - %(message)s'", ")", "logging", ".", "getLogger", "(", ")", ".", "setLevel", "(", "logging", ".", "DEBUG", ")" ]
https://github.com/synfig/synfig/blob/a5ec91db5b751dc12e4400ccfb5c063fd6d2d928/synfig-studio/plugins/lottie-exporter/export_without_variable_width.py#L124-L130
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py3/sklearn/cluster/_optics.py
python
compute_optics_graph
(X, min_samples, max_eps, metric, p, metric_params, algorithm, leaf_size, n_jobs)
return ordering, core_distances_, reachability_, predecessor_
Computes the OPTICS reachability graph. Read more in the :ref:`User Guide <optics>`. Parameters ---------- X : array, shape (n_samples, n_features), or (n_samples, n_samples) \ if metric=’precomputed’. A feature array, or array of distances between samples if metric='precomputed' min_samples : int > 1 or float between 0 and 1 The number of samples in a neighborhood for a point to be considered as a core point. Expressed as an absolute number or a fraction of the number of samples (rounded to be at least 2). max_eps : float, optional (default=np.inf) The maximum distance between two samples for one to be considered as in the neighborhood of the other. Default value of ``np.inf`` will identify clusters across all scales; reducing ``max_eps`` will result in shorter run times. metric : string or callable, optional (default='minkowski') Metric to use for distance computation. Any metric from scikit-learn or scipy.spatial.distance can be used. If metric is a callable function, it is called on each pair of instances (rows) and the resulting value recorded. The callable should take two arrays as input and return one value indicating the distance between them. This works for Scipy's metrics, but is less efficient than passing the metric name as a string. If metric is "precomputed", X is assumed to be a distance matrix and must be square. Valid values for metric are: - from scikit-learn: ['cityblock', 'cosine', 'euclidean', 'l1', 'l2', 'manhattan'] - from scipy.spatial.distance: ['braycurtis', 'canberra', 'chebyshev', 'correlation', 'dice', 'hamming', 'jaccard', 'kulsinski', 'mahalanobis', 'minkowski', 'rogerstanimoto', 'russellrao', 'seuclidean', 'sokalmichener', 'sokalsneath', 'sqeuclidean', 'yule'] See the documentation for scipy.spatial.distance for details on these metrics. p : integer, optional (default=2) Parameter for the Minkowski metric from :class:`sklearn.metrics.pairwise_distances`. When p = 1, this is equivalent to using manhattan_distance (l1), and euclidean_distance (l2) for p = 2. For arbitrary p, minkowski_distance (l_p) is used. metric_params : dict, optional (default=None) Additional keyword arguments for the metric function. algorithm : {'auto', 'ball_tree', 'kd_tree', 'brute'}, optional Algorithm used to compute the nearest neighbors: - 'ball_tree' will use :class:`BallTree` - 'kd_tree' will use :class:`KDTree` - 'brute' will use a brute-force search. - 'auto' will attempt to decide the most appropriate algorithm based on the values passed to :meth:`fit` method. (default) Note: fitting on sparse input will override the setting of this parameter, using brute force. leaf_size : int, optional (default=30) Leaf size passed to :class:`BallTree` or :class:`KDTree`. This can affect the speed of the construction and query, as well as the memory required to store the tree. The optimal value depends on the nature of the problem. n_jobs : int or None, optional (default=None) The number of parallel jobs to run for neighbors search. ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. ``-1`` means using all processors. See :term:`Glossary <n_jobs>` for more details. Returns ------- ordering_ : array, shape (n_samples,) The cluster ordered list of sample indices. core_distances_ : array, shape (n_samples,) Distance at which each sample becomes a core point, indexed by object order. Points which will never be core have a distance of inf. Use ``clust.core_distances_[clust.ordering_]`` to access in cluster order. reachability_ : array, shape (n_samples,) Reachability distances per sample, indexed by object order. Use ``clust.reachability_[clust.ordering_]`` to access in cluster order. predecessor_ : array, shape (n_samples,) Point that a sample was reached from, indexed by object order. Seed points have a predecessor of -1. References ---------- .. [1] Ankerst, Mihael, Markus M. Breunig, Hans-Peter Kriegel, and Jörg Sander. "OPTICS: ordering points to identify the clustering structure." ACM SIGMOD Record 28, no. 2 (1999): 49-60.
Computes the OPTICS reachability graph.
[ "Computes", "the", "OPTICS", "reachability", "graph", "." ]
def compute_optics_graph(X, min_samples, max_eps, metric, p, metric_params, algorithm, leaf_size, n_jobs): """Computes the OPTICS reachability graph. Read more in the :ref:`User Guide <optics>`. Parameters ---------- X : array, shape (n_samples, n_features), or (n_samples, n_samples) \ if metric=’precomputed’. A feature array, or array of distances between samples if metric='precomputed' min_samples : int > 1 or float between 0 and 1 The number of samples in a neighborhood for a point to be considered as a core point. Expressed as an absolute number or a fraction of the number of samples (rounded to be at least 2). max_eps : float, optional (default=np.inf) The maximum distance between two samples for one to be considered as in the neighborhood of the other. Default value of ``np.inf`` will identify clusters across all scales; reducing ``max_eps`` will result in shorter run times. metric : string or callable, optional (default='minkowski') Metric to use for distance computation. Any metric from scikit-learn or scipy.spatial.distance can be used. If metric is a callable function, it is called on each pair of instances (rows) and the resulting value recorded. The callable should take two arrays as input and return one value indicating the distance between them. This works for Scipy's metrics, but is less efficient than passing the metric name as a string. If metric is "precomputed", X is assumed to be a distance matrix and must be square. Valid values for metric are: - from scikit-learn: ['cityblock', 'cosine', 'euclidean', 'l1', 'l2', 'manhattan'] - from scipy.spatial.distance: ['braycurtis', 'canberra', 'chebyshev', 'correlation', 'dice', 'hamming', 'jaccard', 'kulsinski', 'mahalanobis', 'minkowski', 'rogerstanimoto', 'russellrao', 'seuclidean', 'sokalmichener', 'sokalsneath', 'sqeuclidean', 'yule'] See the documentation for scipy.spatial.distance for details on these metrics. p : integer, optional (default=2) Parameter for the Minkowski metric from :class:`sklearn.metrics.pairwise_distances`. When p = 1, this is equivalent to using manhattan_distance (l1), and euclidean_distance (l2) for p = 2. For arbitrary p, minkowski_distance (l_p) is used. metric_params : dict, optional (default=None) Additional keyword arguments for the metric function. algorithm : {'auto', 'ball_tree', 'kd_tree', 'brute'}, optional Algorithm used to compute the nearest neighbors: - 'ball_tree' will use :class:`BallTree` - 'kd_tree' will use :class:`KDTree` - 'brute' will use a brute-force search. - 'auto' will attempt to decide the most appropriate algorithm based on the values passed to :meth:`fit` method. (default) Note: fitting on sparse input will override the setting of this parameter, using brute force. leaf_size : int, optional (default=30) Leaf size passed to :class:`BallTree` or :class:`KDTree`. This can affect the speed of the construction and query, as well as the memory required to store the tree. The optimal value depends on the nature of the problem. n_jobs : int or None, optional (default=None) The number of parallel jobs to run for neighbors search. ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. ``-1`` means using all processors. See :term:`Glossary <n_jobs>` for more details. Returns ------- ordering_ : array, shape (n_samples,) The cluster ordered list of sample indices. core_distances_ : array, shape (n_samples,) Distance at which each sample becomes a core point, indexed by object order. Points which will never be core have a distance of inf. Use ``clust.core_distances_[clust.ordering_]`` to access in cluster order. reachability_ : array, shape (n_samples,) Reachability distances per sample, indexed by object order. Use ``clust.reachability_[clust.ordering_]`` to access in cluster order. predecessor_ : array, shape (n_samples,) Point that a sample was reached from, indexed by object order. Seed points have a predecessor of -1. References ---------- .. [1] Ankerst, Mihael, Markus M. Breunig, Hans-Peter Kriegel, and Jörg Sander. "OPTICS: ordering points to identify the clustering structure." ACM SIGMOD Record 28, no. 2 (1999): 49-60. """ n_samples = X.shape[0] _validate_size(min_samples, n_samples, 'min_samples') if min_samples <= 1: min_samples = max(2, int(min_samples * n_samples)) # Start all points as 'unprocessed' ## reachability_ = np.empty(n_samples) reachability_.fill(np.inf) predecessor_ = np.empty(n_samples, dtype=int) predecessor_.fill(-1) nbrs = NearestNeighbors(n_neighbors=min_samples, algorithm=algorithm, leaf_size=leaf_size, metric=metric, metric_params=metric_params, p=p, n_jobs=n_jobs) nbrs.fit(X) # Here we first do a kNN query for each point, this differs from # the original OPTICS that only used epsilon range queries. # TODO: handle working_memory somehow? core_distances_ = _compute_core_distances_(X=X, neighbors=nbrs, min_samples=min_samples, working_memory=None) # OPTICS puts an upper limit on these, use inf for undefined. core_distances_[core_distances_ > max_eps] = np.inf # Main OPTICS loop. Not parallelizable. The order that entries are # written to the 'ordering_' list is important! # Note that this implementation is O(n^2) theoretically, but # supposedly with very low constant factors. processed = np.zeros(X.shape[0], dtype=bool) ordering = np.zeros(X.shape[0], dtype=int) for ordering_idx in range(X.shape[0]): # Choose next based on smallest reachability distance # (And prefer smaller ids on ties, possibly np.inf!) index = np.where(processed == 0)[0] point = index[np.argmin(reachability_[index])] processed[point] = True ordering[ordering_idx] = point if core_distances_[point] != np.inf: _set_reach_dist(core_distances_=core_distances_, reachability_=reachability_, predecessor_=predecessor_, point_index=point, processed=processed, X=X, nbrs=nbrs, metric=metric, metric_params=metric_params, p=p, max_eps=max_eps) if np.all(np.isinf(reachability_)): warnings.warn("All reachability values are inf. Set a larger" " max_eps or all data will be considered outliers.", UserWarning) return ordering, core_distances_, reachability_, predecessor_
[ "def", "compute_optics_graph", "(", "X", ",", "min_samples", ",", "max_eps", ",", "metric", ",", "p", ",", "metric_params", ",", "algorithm", ",", "leaf_size", ",", "n_jobs", ")", ":", "n_samples", "=", "X", ".", "shape", "[", "0", "]", "_validate_size", "(", "min_samples", ",", "n_samples", ",", "'min_samples'", ")", "if", "min_samples", "<=", "1", ":", "min_samples", "=", "max", "(", "2", ",", "int", "(", "min_samples", "*", "n_samples", ")", ")", "# Start all points as 'unprocessed' ##", "reachability_", "=", "np", ".", "empty", "(", "n_samples", ")", "reachability_", ".", "fill", "(", "np", ".", "inf", ")", "predecessor_", "=", "np", ".", "empty", "(", "n_samples", ",", "dtype", "=", "int", ")", "predecessor_", ".", "fill", "(", "-", "1", ")", "nbrs", "=", "NearestNeighbors", "(", "n_neighbors", "=", "min_samples", ",", "algorithm", "=", "algorithm", ",", "leaf_size", "=", "leaf_size", ",", "metric", "=", "metric", ",", "metric_params", "=", "metric_params", ",", "p", "=", "p", ",", "n_jobs", "=", "n_jobs", ")", "nbrs", ".", "fit", "(", "X", ")", "# Here we first do a kNN query for each point, this differs from", "# the original OPTICS that only used epsilon range queries.", "# TODO: handle working_memory somehow?", "core_distances_", "=", "_compute_core_distances_", "(", "X", "=", "X", ",", "neighbors", "=", "nbrs", ",", "min_samples", "=", "min_samples", ",", "working_memory", "=", "None", ")", "# OPTICS puts an upper limit on these, use inf for undefined.", "core_distances_", "[", "core_distances_", ">", "max_eps", "]", "=", "np", ".", "inf", "# Main OPTICS loop. Not parallelizable. The order that entries are", "# written to the 'ordering_' list is important!", "# Note that this implementation is O(n^2) theoretically, but", "# supposedly with very low constant factors.", "processed", "=", "np", ".", "zeros", "(", "X", ".", "shape", "[", "0", "]", ",", "dtype", "=", "bool", ")", "ordering", "=", "np", ".", "zeros", "(", "X", ".", "shape", "[", "0", "]", ",", "dtype", "=", "int", ")", "for", "ordering_idx", "in", "range", "(", "X", ".", "shape", "[", "0", "]", ")", ":", "# Choose next based on smallest reachability distance", "# (And prefer smaller ids on ties, possibly np.inf!)", "index", "=", "np", ".", "where", "(", "processed", "==", "0", ")", "[", "0", "]", "point", "=", "index", "[", "np", ".", "argmin", "(", "reachability_", "[", "index", "]", ")", "]", "processed", "[", "point", "]", "=", "True", "ordering", "[", "ordering_idx", "]", "=", "point", "if", "core_distances_", "[", "point", "]", "!=", "np", ".", "inf", ":", "_set_reach_dist", "(", "core_distances_", "=", "core_distances_", ",", "reachability_", "=", "reachability_", ",", "predecessor_", "=", "predecessor_", ",", "point_index", "=", "point", ",", "processed", "=", "processed", ",", "X", "=", "X", ",", "nbrs", "=", "nbrs", ",", "metric", "=", "metric", ",", "metric_params", "=", "metric_params", ",", "p", "=", "p", ",", "max_eps", "=", "max_eps", ")", "if", "np", ".", "all", "(", "np", ".", "isinf", "(", "reachability_", ")", ")", ":", "warnings", ".", "warn", "(", "\"All reachability values are inf. Set a larger\"", "\" max_eps or all data will be considered outliers.\"", ",", "UserWarning", ")", "return", "ordering", ",", "core_distances_", ",", "reachability_", ",", "predecessor_" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/cluster/_optics.py#L342-L503
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
build/android/pylib/utils/emulator.py
python
LaunchTempEmulators
(emulator_count, abi, api_level, enable_kvm=False, kill_and_launch=True, sdcard_size=DEFAULT_SDCARD_SIZE, storage_size=DEFAULT_STORAGE_SIZE, wait_for_boot=True, headless=False)
return emulators
Create and launch temporary emulators and wait for them to boot. Args: emulator_count: number of emulators to launch. abi: the emulator target platform api_level: the api level (e.g., 19 for Android v4.4 - KitKat release) wait_for_boot: whether or not to wait for emulators to boot up headless: running emulator with no ui Returns: List of emulators.
Create and launch temporary emulators and wait for them to boot.
[ "Create", "and", "launch", "temporary", "emulators", "and", "wait", "for", "them", "to", "boot", "." ]
def LaunchTempEmulators(emulator_count, abi, api_level, enable_kvm=False, kill_and_launch=True, sdcard_size=DEFAULT_SDCARD_SIZE, storage_size=DEFAULT_STORAGE_SIZE, wait_for_boot=True, headless=False): """Create and launch temporary emulators and wait for them to boot. Args: emulator_count: number of emulators to launch. abi: the emulator target platform api_level: the api level (e.g., 19 for Android v4.4 - KitKat release) wait_for_boot: whether or not to wait for emulators to boot up headless: running emulator with no ui Returns: List of emulators. """ emulators = [] for n in xrange(emulator_count): t = time_profile.TimeProfile('Emulator launch %d' % n) # Creates a temporary AVD. avd_name = 'run_tests_avd_%d' % n logging.info('Emulator launch %d with avd_name=%s and api=%d', n, avd_name, api_level) emulator = Emulator(avd_name, abi, enable_kvm=enable_kvm, sdcard_size=sdcard_size, storage_size=storage_size, headless=headless) emulator.CreateAVD(api_level) emulator.Launch(kill_all_emulators=(n == 0 and kill_and_launch)) t.Stop() emulators.append(emulator) # Wait for all emulators to boot completed. if wait_for_boot: for emulator in emulators: emulator.ConfirmLaunch(True) logging.info('All emulators are fully booted') return emulators
[ "def", "LaunchTempEmulators", "(", "emulator_count", ",", "abi", ",", "api_level", ",", "enable_kvm", "=", "False", ",", "kill_and_launch", "=", "True", ",", "sdcard_size", "=", "DEFAULT_SDCARD_SIZE", ",", "storage_size", "=", "DEFAULT_STORAGE_SIZE", ",", "wait_for_boot", "=", "True", ",", "headless", "=", "False", ")", ":", "emulators", "=", "[", "]", "for", "n", "in", "xrange", "(", "emulator_count", ")", ":", "t", "=", "time_profile", ".", "TimeProfile", "(", "'Emulator launch %d'", "%", "n", ")", "# Creates a temporary AVD.", "avd_name", "=", "'run_tests_avd_%d'", "%", "n", "logging", ".", "info", "(", "'Emulator launch %d with avd_name=%s and api=%d'", ",", "n", ",", "avd_name", ",", "api_level", ")", "emulator", "=", "Emulator", "(", "avd_name", ",", "abi", ",", "enable_kvm", "=", "enable_kvm", ",", "sdcard_size", "=", "sdcard_size", ",", "storage_size", "=", "storage_size", ",", "headless", "=", "headless", ")", "emulator", ".", "CreateAVD", "(", "api_level", ")", "emulator", ".", "Launch", "(", "kill_all_emulators", "=", "(", "n", "==", "0", "and", "kill_and_launch", ")", ")", "t", ".", "Stop", "(", ")", "emulators", ".", "append", "(", "emulator", ")", "# Wait for all emulators to boot completed.", "if", "wait_for_boot", ":", "for", "emulator", "in", "emulators", ":", "emulator", ".", "ConfirmLaunch", "(", "True", ")", "logging", ".", "info", "(", "'All emulators are fully booted'", ")", "return", "emulators" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/build/android/pylib/utils/emulator.py#L189-L224
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
build/config/win/get_msvc_config_real.py
python
VisualStudioVersion.ToolPath
(self, tool)
return os.path.normpath(os.path.join(self.path, "VC/bin", tool))
Returns the path to a given compiler tool.
Returns the path to a given compiler tool.
[ "Returns", "the", "path", "to", "a", "given", "compiler", "tool", "." ]
def ToolPath(self, tool): """Returns the path to a given compiler tool. """ return os.path.normpath(os.path.join(self.path, "VC/bin", tool))
[ "def", "ToolPath", "(", "self", ",", "tool", ")", ":", "return", "os", ".", "path", ".", "normpath", "(", "os", ".", "path", ".", "join", "(", "self", ".", "path", ",", "\"VC/bin\"", ",", "tool", ")", ")" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/build/config/win/get_msvc_config_real.py#L63-L65
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py2/scipy/optimize/_constraints.py
python
new_constraint_to_old
(con, x0)
return old_constraints
Converts new-style constraint objects to old-style constraint dictionaries.
Converts new-style constraint objects to old-style constraint dictionaries.
[ "Converts", "new", "-", "style", "constraint", "objects", "to", "old", "-", "style", "constraint", "dictionaries", "." ]
def new_constraint_to_old(con, x0): """ Converts new-style constraint objects to old-style constraint dictionaries. """ if isinstance(con, NonlinearConstraint): if (con.finite_diff_jac_sparsity is not None or con.finite_diff_rel_step is not None or not isinstance(con.hess, BFGS) or # misses user specified BFGS con.keep_feasible): warn("Constraint options `finite_diff_jac_sparsity`, " "`finite_diff_rel_step`, `keep_feasible`, and `hess`" "are ignored by this method.", OptimizeWarning) fun = con.fun if callable(con.jac): jac = con.jac else: jac = None else: # LinearConstraint if con.keep_feasible: warn("Constraint option `keep_feasible` is ignored by this " "method.", OptimizeWarning) A = con.A if issparse(A): A = A.todense() fun = lambda x: np.dot(A, x) jac = lambda x: A # FIXME: when bugs in VectorFunction/LinearVectorFunction are worked out, # use pcon.fun.fun and pcon.fun.jac. Until then, get fun/jac above. pcon = PreparedConstraint(con, x0) lb, ub = pcon.bounds i_eq = lb == ub i_bound_below = np.logical_xor(lb != -np.inf, i_eq) i_bound_above = np.logical_xor(ub != np.inf, i_eq) i_unbounded = np.logical_and(lb == -np.inf, ub == np.inf) if np.any(i_unbounded): warn("At least one constraint is unbounded above and below. Such " "constraints are ignored.", OptimizeWarning) ceq = [] if np.any(i_eq): def f_eq(x): y = np.array(fun(x)).flatten() return y[i_eq] - lb[i_eq] ceq = [{"type": "eq", "fun": f_eq}] if jac is not None: def j_eq(x): dy = jac(x) if issparse(dy): dy = dy.todense() dy = np.atleast_2d(dy) return dy[i_eq, :] ceq[0]["jac"] = j_eq cineq = [] n_bound_below = np.sum(i_bound_below) n_bound_above = np.sum(i_bound_above) if n_bound_below + n_bound_above: def f_ineq(x): y = np.zeros(n_bound_below + n_bound_above) y_all = np.array(fun(x)).flatten() y[:n_bound_below] = y_all[i_bound_below] - lb[i_bound_below] y[n_bound_below:] = -(y_all[i_bound_above] - ub[i_bound_above]) return y cineq = [{"type": "ineq", "fun": f_ineq}] if jac is not None: def j_ineq(x): dy = np.zeros((n_bound_below + n_bound_above, len(x0))) dy_all = jac(x) if issparse(dy_all): dy_all = dy_all.todense() dy_all = np.atleast_2d(dy_all) dy[:n_bound_below, :] = dy_all[i_bound_below] dy[n_bound_below:, :] = -dy_all[i_bound_above] return dy cineq[0]["jac"] = j_ineq old_constraints = ceq + cineq if len(old_constraints) > 1: warn("Equality and inequality constraints are specified in the same " "element of the constraint list. For efficient use with this " "method, equality and inequality constraints should be specified " "in separate elements of the constraint list. ", OptimizeWarning) return old_constraints
[ "def", "new_constraint_to_old", "(", "con", ",", "x0", ")", ":", "if", "isinstance", "(", "con", ",", "NonlinearConstraint", ")", ":", "if", "(", "con", ".", "finite_diff_jac_sparsity", "is", "not", "None", "or", "con", ".", "finite_diff_rel_step", "is", "not", "None", "or", "not", "isinstance", "(", "con", ".", "hess", ",", "BFGS", ")", "or", "# misses user specified BFGS", "con", ".", "keep_feasible", ")", ":", "warn", "(", "\"Constraint options `finite_diff_jac_sparsity`, \"", "\"`finite_diff_rel_step`, `keep_feasible`, and `hess`\"", "\"are ignored by this method.\"", ",", "OptimizeWarning", ")", "fun", "=", "con", ".", "fun", "if", "callable", "(", "con", ".", "jac", ")", ":", "jac", "=", "con", ".", "jac", "else", ":", "jac", "=", "None", "else", ":", "# LinearConstraint", "if", "con", ".", "keep_feasible", ":", "warn", "(", "\"Constraint option `keep_feasible` is ignored by this \"", "\"method.\"", ",", "OptimizeWarning", ")", "A", "=", "con", ".", "A", "if", "issparse", "(", "A", ")", ":", "A", "=", "A", ".", "todense", "(", ")", "fun", "=", "lambda", "x", ":", "np", ".", "dot", "(", "A", ",", "x", ")", "jac", "=", "lambda", "x", ":", "A", "# FIXME: when bugs in VectorFunction/LinearVectorFunction are worked out,", "# use pcon.fun.fun and pcon.fun.jac. Until then, get fun/jac above.", "pcon", "=", "PreparedConstraint", "(", "con", ",", "x0", ")", "lb", ",", "ub", "=", "pcon", ".", "bounds", "i_eq", "=", "lb", "==", "ub", "i_bound_below", "=", "np", ".", "logical_xor", "(", "lb", "!=", "-", "np", ".", "inf", ",", "i_eq", ")", "i_bound_above", "=", "np", ".", "logical_xor", "(", "ub", "!=", "np", ".", "inf", ",", "i_eq", ")", "i_unbounded", "=", "np", ".", "logical_and", "(", "lb", "==", "-", "np", ".", "inf", ",", "ub", "==", "np", ".", "inf", ")", "if", "np", ".", "any", "(", "i_unbounded", ")", ":", "warn", "(", "\"At least one constraint is unbounded above and below. Such \"", "\"constraints are ignored.\"", ",", "OptimizeWarning", ")", "ceq", "=", "[", "]", "if", "np", ".", "any", "(", "i_eq", ")", ":", "def", "f_eq", "(", "x", ")", ":", "y", "=", "np", ".", "array", "(", "fun", "(", "x", ")", ")", ".", "flatten", "(", ")", "return", "y", "[", "i_eq", "]", "-", "lb", "[", "i_eq", "]", "ceq", "=", "[", "{", "\"type\"", ":", "\"eq\"", ",", "\"fun\"", ":", "f_eq", "}", "]", "if", "jac", "is", "not", "None", ":", "def", "j_eq", "(", "x", ")", ":", "dy", "=", "jac", "(", "x", ")", "if", "issparse", "(", "dy", ")", ":", "dy", "=", "dy", ".", "todense", "(", ")", "dy", "=", "np", ".", "atleast_2d", "(", "dy", ")", "return", "dy", "[", "i_eq", ",", ":", "]", "ceq", "[", "0", "]", "[", "\"jac\"", "]", "=", "j_eq", "cineq", "=", "[", "]", "n_bound_below", "=", "np", ".", "sum", "(", "i_bound_below", ")", "n_bound_above", "=", "np", ".", "sum", "(", "i_bound_above", ")", "if", "n_bound_below", "+", "n_bound_above", ":", "def", "f_ineq", "(", "x", ")", ":", "y", "=", "np", ".", "zeros", "(", "n_bound_below", "+", "n_bound_above", ")", "y_all", "=", "np", ".", "array", "(", "fun", "(", "x", ")", ")", ".", "flatten", "(", ")", "y", "[", ":", "n_bound_below", "]", "=", "y_all", "[", "i_bound_below", "]", "-", "lb", "[", "i_bound_below", "]", "y", "[", "n_bound_below", ":", "]", "=", "-", "(", "y_all", "[", "i_bound_above", "]", "-", "ub", "[", "i_bound_above", "]", ")", "return", "y", "cineq", "=", "[", "{", "\"type\"", ":", "\"ineq\"", ",", "\"fun\"", ":", "f_ineq", "}", "]", "if", "jac", "is", "not", "None", ":", "def", "j_ineq", "(", "x", ")", ":", "dy", "=", "np", ".", "zeros", "(", "(", "n_bound_below", "+", "n_bound_above", ",", "len", "(", "x0", ")", ")", ")", "dy_all", "=", "jac", "(", "x", ")", "if", "issparse", "(", "dy_all", ")", ":", "dy_all", "=", "dy_all", ".", "todense", "(", ")", "dy_all", "=", "np", ".", "atleast_2d", "(", "dy_all", ")", "dy", "[", ":", "n_bound_below", ",", ":", "]", "=", "dy_all", "[", "i_bound_below", "]", "dy", "[", "n_bound_below", ":", ",", ":", "]", "=", "-", "dy_all", "[", "i_bound_above", "]", "return", "dy", "cineq", "[", "0", "]", "[", "\"jac\"", "]", "=", "j_ineq", "old_constraints", "=", "ceq", "+", "cineq", "if", "len", "(", "old_constraints", ")", ">", "1", ":", "warn", "(", "\"Equality and inequality constraints are specified in the same \"", "\"element of the constraint list. For efficient use with this \"", "\"method, equality and inequality constraints should be specified \"", "\"in separate elements of the constraint list. \"", ",", "OptimizeWarning", ")", "return", "old_constraints" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/optimize/_constraints.py#L290-L381
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/train/callback/_landscape.py
python
_PCA._random_svd
(self, m, n_components, n_oversamples=10, random_state="warn")
return u[:, :n_components], s[:n_components], vt[:n_components, :]
Compute a truncated randomized SVD.
Compute a truncated randomized SVD.
[ "Compute", "a", "truncated", "randomized", "SVD", "." ]
def _random_svd(self, m, n_components, n_oversamples=10, random_state="warn"): """Compute a truncated randomized SVD.""" n_random = n_components + n_oversamples n_samples, n_features = m.shape # Adjust 7 or 4 was found a good compromise for randomized SVD. n_iter = 7 if n_components < 0.1 * min(m.shape) else 4 transpose = n_samples < n_features if transpose: m = m.T q = self._random_range_finder(m, size=n_random, n_iter=n_iter, random_state=random_state) # Project m to the low dimensional space using the basis vectors (q vector). b = self._safe_dot(q.T, m) # Compute the svd on this matrix (b matrix) uhat, s, vt = linalg.svd(b, full_matrices=False) del b u = np.dot(q, uhat) if not transpose: u, vt = self._svd_turn(u, vt) else: u, vt = self._svd_turn(u, vt, u_decision=False) if transpose: return vt[:n_components, :].T, s[:n_components], u[:, :n_components].T return u[:, :n_components], s[:n_components], vt[:n_components, :]
[ "def", "_random_svd", "(", "self", ",", "m", ",", "n_components", ",", "n_oversamples", "=", "10", ",", "random_state", "=", "\"warn\"", ")", ":", "n_random", "=", "n_components", "+", "n_oversamples", "n_samples", ",", "n_features", "=", "m", ".", "shape", "# Adjust 7 or 4 was found a good compromise for randomized SVD.", "n_iter", "=", "7", "if", "n_components", "<", "0.1", "*", "min", "(", "m", ".", "shape", ")", "else", "4", "transpose", "=", "n_samples", "<", "n_features", "if", "transpose", ":", "m", "=", "m", ".", "T", "q", "=", "self", ".", "_random_range_finder", "(", "m", ",", "size", "=", "n_random", ",", "n_iter", "=", "n_iter", ",", "random_state", "=", "random_state", ")", "# Project m to the low dimensional space using the basis vectors (q vector).", "b", "=", "self", ".", "_safe_dot", "(", "q", ".", "T", ",", "m", ")", "# Compute the svd on this matrix (b matrix)", "uhat", ",", "s", ",", "vt", "=", "linalg", ".", "svd", "(", "b", ",", "full_matrices", "=", "False", ")", "del", "b", "u", "=", "np", ".", "dot", "(", "q", ",", "uhat", ")", "if", "not", "transpose", ":", "u", ",", "vt", "=", "self", ".", "_svd_turn", "(", "u", ",", "vt", ")", "else", ":", "u", ",", "vt", "=", "self", ".", "_svd_turn", "(", "u", ",", "vt", ",", "u_decision", "=", "False", ")", "if", "transpose", ":", "return", "vt", "[", ":", "n_components", ",", ":", "]", ".", "T", ",", "s", "[", ":", "n_components", "]", ",", "u", "[", ":", ",", ":", "n_components", "]", ".", "T", "return", "u", "[", ":", ",", ":", "n_components", "]", ",", "s", "[", ":", "n_components", "]", ",", "vt", "[", ":", "n_components", ",", ":", "]" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/train/callback/_landscape.py#L938-L965
papyrussolution/OpenPapyrus
bbfb5ec2ea2109b8e2f125edd838e12eaf7b8b91
Src/OSF/protobuf-3.19.1/python/google/protobuf/internal/decoder.py
python
_SkipGroup
(buffer, pos, end)
Skip sub-group. Returns the new position.
Skip sub-group. Returns the new position.
[ "Skip", "sub", "-", "group", ".", "Returns", "the", "new", "position", "." ]
def _SkipGroup(buffer, pos, end): """Skip sub-group. Returns the new position.""" while 1: (tag_bytes, pos) = ReadTag(buffer, pos) new_pos = SkipField(buffer, pos, end, tag_bytes) if new_pos == -1: return pos pos = new_pos
[ "def", "_SkipGroup", "(", "buffer", ",", "pos", ",", "end", ")", ":", "while", "1", ":", "(", "tag_bytes", ",", "pos", ")", "=", "ReadTag", "(", "buffer", ",", "pos", ")", "new_pos", "=", "SkipField", "(", "buffer", ",", "pos", ",", "end", ",", "tag_bytes", ")", "if", "new_pos", "==", "-", "1", ":", "return", "pos", "pos", "=", "new_pos" ]
https://github.com/papyrussolution/OpenPapyrus/blob/bbfb5ec2ea2109b8e2f125edd838e12eaf7b8b91/Src/OSF/protobuf-3.19.1/python/google/protobuf/internal/decoder.py#L919-L927
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/floatspin.py
python
FloatSpin.IsFinite
(self, value)
return finite, snap_value
Tries to determine if a value is finite or infinite/NaN. :param `value`: the value to test.
Tries to determine if a value is finite or infinite/NaN.
[ "Tries", "to", "determine", "if", "a", "value", "is", "finite", "or", "infinite", "/", "NaN", "." ]
def IsFinite(self, value): """ Tries to determine if a value is finite or infinite/NaN. :param `value`: the value to test. """ try: snap_value = (value - self._defaultvalue)/self._increment finite = True except: finite = False snap_value = None return finite, snap_value
[ "def", "IsFinite", "(", "self", ",", "value", ")", ":", "try", ":", "snap_value", "=", "(", "value", "-", "self", ".", "_defaultvalue", ")", "/", "self", ".", "_increment", "finite", "=", "True", "except", ":", "finite", "=", "False", "snap_value", "=", "None", "return", "finite", ",", "snap_value" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/floatspin.py#L1184-L1198
qt/qt
0a2f2382541424726168804be2c90b91381608c6
src/3rdparty/webkit/Source/ThirdParty/gyp/pylib/gyp/MSVSSettings.py
python
_Renamed
(tool, msvs_name, msbuild_name, type)
Defines a setting for which the name has changed. Args: tool: a dictionary that gives the names of the tool for MSVS and MSBuild. msvs_name: the name of the MSVS setting. msbuild_name: the name of the MSBuild setting. type: the type of this setting.
Defines a setting for which the name has changed.
[ "Defines", "a", "setting", "for", "which", "the", "name", "has", "changed", "." ]
def _Renamed(tool, msvs_name, msbuild_name, type): """ Defines a setting for which the name has changed. Args: tool: a dictionary that gives the names of the tool for MSVS and MSBuild. msvs_name: the name of the MSVS setting. msbuild_name: the name of the MSBuild setting. type: the type of this setting. """ def _Translate(value, msbuild_settings): msbuild_tool_settings = _GetMsBuildToolSettings(msbuild_settings, tool) msbuild_tool_settings[msbuild_name] = type.ConvertToMSBuild(value) msvs_tool_name = tool['msvs'] msbuild_tool_name = tool['msbuild'] _msvs_validators[msvs_tool_name][msvs_name] = type.ValidateMSVS _msbuild_validators[msbuild_tool_name][msbuild_name] = type.ValidateMSBuild _msvs_to_msbuild_converters[msvs_tool_name][msvs_name] = _Translate
[ "def", "_Renamed", "(", "tool", ",", "msvs_name", ",", "msbuild_name", ",", "type", ")", ":", "def", "_Translate", "(", "value", ",", "msbuild_settings", ")", ":", "msbuild_tool_settings", "=", "_GetMsBuildToolSettings", "(", "msbuild_settings", ",", "tool", ")", "msbuild_tool_settings", "[", "msbuild_name", "]", "=", "type", ".", "ConvertToMSBuild", "(", "value", ")", "msvs_tool_name", "=", "tool", "[", "'msvs'", "]", "msbuild_tool_name", "=", "tool", "[", "'msbuild'", "]", "_msvs_validators", "[", "msvs_tool_name", "]", "[", "msvs_name", "]", "=", "type", ".", "ValidateMSVS", "_msbuild_validators", "[", "msbuild_tool_name", "]", "[", "msbuild_name", "]", "=", "type", ".", "ValidateMSBuild", "_msvs_to_msbuild_converters", "[", "msvs_tool_name", "]", "[", "msvs_name", "]", "=", "_Translate" ]
https://github.com/qt/qt/blob/0a2f2382541424726168804be2c90b91381608c6/src/3rdparty/webkit/Source/ThirdParty/gyp/pylib/gyp/MSVSSettings.py#L202-L218
tum-vision/fusenet
a1451be2971b348a01b0f525c2a3a7a0e215a591
python/caffe/net_spec.py
python
assign_proto
(proto, name, val)
Assign a Python object to a protobuf message, based on the Python type (in recursive fashion). Lists become repeated fields/messages, dicts become messages, and other types are assigned directly. For convenience, repeated fields whose values are not lists are converted to single-element lists; e.g., `my_repeated_int_field=3` is converted to `my_repeated_int_field=[3]`.
Assign a Python object to a protobuf message, based on the Python type (in recursive fashion). Lists become repeated fields/messages, dicts become messages, and other types are assigned directly. For convenience, repeated fields whose values are not lists are converted to single-element lists; e.g., `my_repeated_int_field=3` is converted to `my_repeated_int_field=[3]`.
[ "Assign", "a", "Python", "object", "to", "a", "protobuf", "message", "based", "on", "the", "Python", "type", "(", "in", "recursive", "fashion", ")", ".", "Lists", "become", "repeated", "fields", "/", "messages", "dicts", "become", "messages", "and", "other", "types", "are", "assigned", "directly", ".", "For", "convenience", "repeated", "fields", "whose", "values", "are", "not", "lists", "are", "converted", "to", "single", "-", "element", "lists", ";", "e", ".", "g", ".", "my_repeated_int_field", "=", "3", "is", "converted", "to", "my_repeated_int_field", "=", "[", "3", "]", "." ]
def assign_proto(proto, name, val): """Assign a Python object to a protobuf message, based on the Python type (in recursive fashion). Lists become repeated fields/messages, dicts become messages, and other types are assigned directly. For convenience, repeated fields whose values are not lists are converted to single-element lists; e.g., `my_repeated_int_field=3` is converted to `my_repeated_int_field=[3]`.""" is_repeated_field = hasattr(getattr(proto, name), 'extend') if is_repeated_field and not isinstance(val, list): val = [val] if isinstance(val, list): if isinstance(val[0], dict): for item in val: proto_item = getattr(proto, name).add() for k, v in six.iteritems(item): assign_proto(proto_item, k, v) else: getattr(proto, name).extend(val) elif isinstance(val, dict): for k, v in six.iteritems(val): assign_proto(getattr(proto, name), k, v) else: setattr(proto, name, val)
[ "def", "assign_proto", "(", "proto", ",", "name", ",", "val", ")", ":", "is_repeated_field", "=", "hasattr", "(", "getattr", "(", "proto", ",", "name", ")", ",", "'extend'", ")", "if", "is_repeated_field", "and", "not", "isinstance", "(", "val", ",", "list", ")", ":", "val", "=", "[", "val", "]", "if", "isinstance", "(", "val", ",", "list", ")", ":", "if", "isinstance", "(", "val", "[", "0", "]", ",", "dict", ")", ":", "for", "item", "in", "val", ":", "proto_item", "=", "getattr", "(", "proto", ",", "name", ")", ".", "add", "(", ")", "for", "k", ",", "v", "in", "six", ".", "iteritems", "(", "item", ")", ":", "assign_proto", "(", "proto_item", ",", "k", ",", "v", ")", "else", ":", "getattr", "(", "proto", ",", "name", ")", ".", "extend", "(", "val", ")", "elif", "isinstance", "(", "val", ",", "dict", ")", ":", "for", "k", ",", "v", "in", "six", ".", "iteritems", "(", "val", ")", ":", "assign_proto", "(", "getattr", "(", "proto", ",", "name", ")", ",", "k", ",", "v", ")", "else", ":", "setattr", "(", "proto", ",", "name", ",", "val", ")" ]
https://github.com/tum-vision/fusenet/blob/a1451be2971b348a01b0f525c2a3a7a0e215a591/python/caffe/net_spec.py#L56-L79
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/sysconfig.py
python
_init_non_posix
(vars)
Initialize the module as appropriate for NT
Initialize the module as appropriate for NT
[ "Initialize", "the", "module", "as", "appropriate", "for", "NT" ]
def _init_non_posix(vars): """Initialize the module as appropriate for NT""" # set basic install directories vars['LIBDEST'] = get_path('stdlib') vars['BINLIBDEST'] = get_path('platstdlib') vars['INCLUDEPY'] = get_path('include') vars['SO'] = '.pyd' vars['EXE'] = '.exe' vars['VERSION'] = _PY_VERSION_SHORT_NO_DOT vars['BINDIR'] = os.path.dirname(_safe_realpath(sys.executable))
[ "def", "_init_non_posix", "(", "vars", ")", ":", "# set basic install directories", "vars", "[", "'LIBDEST'", "]", "=", "get_path", "(", "'stdlib'", ")", "vars", "[", "'BINLIBDEST'", "]", "=", "get_path", "(", "'platstdlib'", ")", "vars", "[", "'INCLUDEPY'", "]", "=", "get_path", "(", "'include'", ")", "vars", "[", "'SO'", "]", "=", "'.pyd'", "vars", "[", "'EXE'", "]", "=", "'.exe'", "vars", "[", "'VERSION'", "]", "=", "_PY_VERSION_SHORT_NO_DOT", "vars", "[", "'BINDIR'", "]", "=", "os", ".", "path", ".", "dirname", "(", "_safe_realpath", "(", "sys", ".", "executable", ")", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/sysconfig.py#L360-L369
miyosuda/TensorFlowAndroidMNIST
7b5a4603d2780a8a2834575706e9001977524007
jni-build/jni/include/tensorflow/contrib/graph_editor/subgraph.py
python
SubGraphView._remap_outputs_to_consumers
(self)
Remap the outputs in place to match the number of consumers.
Remap the outputs in place to match the number of consumers.
[ "Remap", "the", "outputs", "in", "place", "to", "match", "the", "number", "of", "consumers", "." ]
def _remap_outputs_to_consumers(self): """Remap the outputs in place to match the number of consumers.""" self._remap_outputs_make_unique() output_ts = list(self._output_ts) self._output_ts = [] for t in output_ts: self._output_ts += [t]*len(t.consumers())
[ "def", "_remap_outputs_to_consumers", "(", "self", ")", ":", "self", ".", "_remap_outputs_make_unique", "(", ")", "output_ts", "=", "list", "(", "self", ".", "_output_ts", ")", "self", ".", "_output_ts", "=", "[", "]", "for", "t", "in", "output_ts", ":", "self", ".", "_output_ts", "+=", "[", "t", "]", "*", "len", "(", "t", ".", "consumers", "(", ")", ")" ]
https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/contrib/graph_editor/subgraph.py#L285-L291
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/python2_version/klampt/robotsim.py
python
IKSolver.lastSolveIters
(self)
return _robotsim.IKSolver_lastSolveIters(self)
lastSolveIters(IKSolver self) -> int Returns the number of Newton-Raphson iterations used in the last solve() call.
lastSolveIters(IKSolver self) -> int
[ "lastSolveIters", "(", "IKSolver", "self", ")", "-", ">", "int" ]
def lastSolveIters(self): """ lastSolveIters(IKSolver self) -> int Returns the number of Newton-Raphson iterations used in the last solve() call. """ return _robotsim.IKSolver_lastSolveIters(self)
[ "def", "lastSolveIters", "(", "self", ")", ":", "return", "_robotsim", ".", "IKSolver_lastSolveIters", "(", "self", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/robotsim.py#L6806-L6815
naver/sling
5671cd445a2caae0b4dd0332299e4cfede05062c
webkit/Tools/Scripts/webkitpy/port/base.py
python
Port.test_exists
(self, test_name)
return self.test_isfile(test_name) or self.test_isdir(test_name)
Return True if the test name refers to an existing test or baseline.
Return True if the test name refers to an existing test or baseline.
[ "Return", "True", "if", "the", "test", "name", "refers", "to", "an", "existing", "test", "or", "baseline", "." ]
def test_exists(self, test_name): """Return True if the test name refers to an existing test or baseline.""" # Used by test_expectations.py to determine if an entry refers to a # valid test and by printing.py to determine if baselines exist. return self.test_isfile(test_name) or self.test_isdir(test_name)
[ "def", "test_exists", "(", "self", ",", "test_name", ")", ":", "# Used by test_expectations.py to determine if an entry refers to a", "# valid test and by printing.py to determine if baselines exist.", "return", "self", ".", "test_isfile", "(", "test_name", ")", "or", "self", ".", "test_isdir", "(", "test_name", ")" ]
https://github.com/naver/sling/blob/5671cd445a2caae0b4dd0332299e4cfede05062c/webkit/Tools/Scripts/webkitpy/port/base.py#L638-L642
gnuradio/gnuradio
09c3c4fa4bfb1a02caac74cb5334dfe065391e3b
grc/core/FlowGraph.py
python
_update_old_message_port_keys
(source_key, sink_key, source_block, sink_block)
return source_key, sink_key
Backward compatibility for message port keys Message ports use their names as key (like in the 'connect' method). Flowgraph files from former versions still have numeric keys stored for message connections. These have to be replaced by the name of the respective port. The correct message port is deduced from the integer value of the key (assuming the order has not changed). The connection ends are updated only if both ends translate into a message port.
Backward compatibility for message port keys
[ "Backward", "compatibility", "for", "message", "port", "keys" ]
def _update_old_message_port_keys(source_key, sink_key, source_block, sink_block): """ Backward compatibility for message port keys Message ports use their names as key (like in the 'connect' method). Flowgraph files from former versions still have numeric keys stored for message connections. These have to be replaced by the name of the respective port. The correct message port is deduced from the integer value of the key (assuming the order has not changed). The connection ends are updated only if both ends translate into a message port. """ try: # get ports using the "old way" (assuming linear indexed keys) source_port = source_block.sources[int(source_key)] sink_port = sink_block.sinks[int(sink_key)] if source_port.dtype == "message" and sink_port.dtype == "message": source_key, sink_key = source_port.key, sink_port.key except (ValueError, IndexError): pass return source_key, sink_key
[ "def", "_update_old_message_port_keys", "(", "source_key", ",", "sink_key", ",", "source_block", ",", "sink_block", ")", ":", "try", ":", "# get ports using the \"old way\" (assuming linear indexed keys)", "source_port", "=", "source_block", ".", "sources", "[", "int", "(", "source_key", ")", "]", "sink_port", "=", "sink_block", ".", "sinks", "[", "int", "(", "sink_key", ")", "]", "if", "source_port", ".", "dtype", "==", "\"message\"", "and", "sink_port", ".", "dtype", "==", "\"message\"", ":", "source_key", ",", "sink_key", "=", "source_port", ".", "key", ",", "sink_port", ".", "key", "except", "(", "ValueError", ",", "IndexError", ")", ":", "pass", "return", "source_key", ",", "sink_key" ]
https://github.com/gnuradio/gnuradio/blob/09c3c4fa4bfb1a02caac74cb5334dfe065391e3b/grc/core/FlowGraph.py#L504-L525
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/third_party/lib_aarch64/python2.7/dist-packages/catkin_pkg/packages.py
python
find_packages_allowing_duplicates
(basepath, exclude_paths=None, exclude_subspaces=False, warnings=None)
return packages
Crawls the filesystem to find package manifest files and parses them. :param basepath: The path to search in, ``str`` :param exclude_paths: A list of paths which should not be searched, ``list`` :param exclude_subspaces: The flag is subfolders containing a .catkin file should not be searched, ``bool`` :param warnings: Print warnings if None or return them in the given list :returns: A dict mapping relative paths to ``Package`` objects ``dict``
Crawls the filesystem to find package manifest files and parses them.
[ "Crawls", "the", "filesystem", "to", "find", "package", "manifest", "files", "and", "parses", "them", "." ]
def find_packages_allowing_duplicates(basepath, exclude_paths=None, exclude_subspaces=False, warnings=None): """ Crawls the filesystem to find package manifest files and parses them. :param basepath: The path to search in, ``str`` :param exclude_paths: A list of paths which should not be searched, ``list`` :param exclude_subspaces: The flag is subfolders containing a .catkin file should not be searched, ``bool`` :param warnings: Print warnings if None or return them in the given list :returns: A dict mapping relative paths to ``Package`` objects ``dict`` """ packages = {} package_paths = find_package_paths(basepath, exclude_paths=exclude_paths, exclude_subspaces=exclude_subspaces) for path in package_paths: packages[path] = parse_package(os.path.join(basepath, path), warnings=warnings) return packages
[ "def", "find_packages_allowing_duplicates", "(", "basepath", ",", "exclude_paths", "=", "None", ",", "exclude_subspaces", "=", "False", ",", "warnings", "=", "None", ")", ":", "packages", "=", "{", "}", "package_paths", "=", "find_package_paths", "(", "basepath", ",", "exclude_paths", "=", "exclude_paths", ",", "exclude_subspaces", "=", "exclude_subspaces", ")", "for", "path", "in", "package_paths", ":", "packages", "[", "path", "]", "=", "parse_package", "(", "os", ".", "path", ".", "join", "(", "basepath", ",", "path", ")", ",", "warnings", "=", "warnings", ")", "return", "packages" ]
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_aarch64/python2.7/dist-packages/catkin_pkg/packages.py#L96-L111
BitMEX/api-connectors
37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812
official-ws/python/bitmex_websocket.py
python
BitMEXWebsocket.__get_auth
(self)
Return auth headers. Will use API Keys if present in settings.
Return auth headers. Will use API Keys if present in settings.
[ "Return", "auth", "headers", ".", "Will", "use", "API", "Keys", "if", "present", "in", "settings", "." ]
def __get_auth(self): '''Return auth headers. Will use API Keys if present in settings.''' if self.api_key: self.logger.info("Authenticating with API Key.") # To auth to the WS using an API key, we generate a signature of a nonce and # the WS API endpoint. expires = generate_nonce() return [ "api-expires: " + str(expires), "api-signature: " + generate_signature(self.api_secret, 'GET', '/realtime', expires, ''), "api-key:" + self.api_key ] else: self.logger.info("Not authenticating.") return []
[ "def", "__get_auth", "(", "self", ")", ":", "if", "self", ".", "api_key", ":", "self", ".", "logger", ".", "info", "(", "\"Authenticating with API Key.\"", ")", "# To auth to the WS using an API key, we generate a signature of a nonce and", "# the WS API endpoint.", "expires", "=", "generate_nonce", "(", ")", "return", "[", "\"api-expires: \"", "+", "str", "(", "expires", ")", ",", "\"api-signature: \"", "+", "generate_signature", "(", "self", ".", "api_secret", ",", "'GET'", ",", "'/realtime'", ",", "expires", ",", "''", ")", ",", "\"api-key:\"", "+", "self", ".", "api_key", "]", "else", ":", "self", ".", "logger", ".", "info", "(", "\"Not authenticating.\"", ")", "return", "[", "]" ]
https://github.com/BitMEX/api-connectors/blob/37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812/official-ws/python/bitmex_websocket.py#L137-L151