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
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/wsgiref/headers.py
python
Headers.add_header
(self, _name, _value, **_params)
Extended header setting. _name is the header field to add. keyword arguments can be used to set additional parameters for the header field, with underscores converted to dashes. Normally the parameter will be added as key="value" unless value is None, in which case only the key will be added. Example: h.add_header('content-disposition', 'attachment', filename='bud.gif') Note that unlike the corresponding 'email.message' method, this does *not* handle '(charset, language, value)' tuples: all values must be strings or None.
Extended header setting.
[ "Extended", "header", "setting", "." ]
def add_header(self, _name, _value, **_params): """Extended header setting. _name is the header field to add. keyword arguments can be used to set additional parameters for the header field, with underscores converted to dashes. Normally the parameter will be added as key="value" unless value is None, in which case only the key will be added. Example: h.add_header('content-disposition', 'attachment', filename='bud.gif') Note that unlike the corresponding 'email.message' method, this does *not* handle '(charset, language, value)' tuples: all values must be strings or None. """ parts = [] if _value is not None: parts.append(_value) for k, v in _params.items(): if v is None: parts.append(k.replace('_', '-')) else: parts.append(_formatparam(k.replace('_', '-'), v)) self._headers.append((_name, "; ".join(parts)))
[ "def", "add_header", "(", "self", ",", "_name", ",", "_value", ",", "*", "*", "_params", ")", ":", "parts", "=", "[", "]", "if", "_value", "is", "not", "None", ":", "parts", ".", "append", "(", "_value", ")", "for", "k", ",", "v", "in", "_params", ".", "items", "(", ")", ":", "if", "v", "is", "None", ":", "parts", ".", "append", "(", "k", ".", "replace", "(", "'_'", ",", "'-'", ")", ")", "else", ":", "parts", ".", "append", "(", "_formatparam", "(", "k", ".", "replace", "(", "'_'", ",", "'-'", ")", ",", "v", ")", ")", "self", ".", "_headers", ".", "append", "(", "(", "_name", ",", "\"; \"", ".", "join", "(", "parts", ")", ")", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/wsgiref/headers.py#L145-L169
klzgrad/naiveproxy
ed2c513637c77b18721fe428d7ed395b4d284c83
src/third_party/depot_tools/cpplint.py
python
_CppLintState.SetVerboseLevel
(self, level)
return last_verbose_level
Sets the module's verbosity, and returns the previous setting.
Sets the module's verbosity, and returns the previous setting.
[ "Sets", "the", "module", "s", "verbosity", "and", "returns", "the", "previous", "setting", "." ]
def SetVerboseLevel(self, level): """Sets the module's verbosity, and returns the previous setting.""" last_verbose_level = self.verbose_level self.verbose_level = level return last_verbose_level
[ "def", "SetVerboseLevel", "(", "self", ",", "level", ")", ":", "last_verbose_level", "=", "self", ".", "verbose_level", "self", ".", "verbose_level", "=", "level", "return", "last_verbose_level" ]
https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/third_party/depot_tools/cpplint.py#L849-L853
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/contrib/labeled_tensor/python/ops/ops.py
python
tile
(labeled_tensor, multiples, name=None)
Constructs a tensor by tiling a given tensor. Only axes without tick-labels can be tiled. (Otherwise, axis labels on tiled tensors would no longer be unique.) See lt.tile. Args: labeled_tensor: The input tensor. multiples: A mapping where the keys are axis names and the values are the integer number of times to tile along that axis. Only axes with a multiple different than 1 need be included. name: Optional op name. Returns: A tensor with the indicated axes tiled. Raises: ValueError: If the tiled axes are not axes in the input tensor, or if any axes in multiples have tick labels.
Constructs a tensor by tiling a given tensor.
[ "Constructs", "a", "tensor", "by", "tiling", "a", "given", "tensor", "." ]
def tile(labeled_tensor, multiples, name=None): """Constructs a tensor by tiling a given tensor. Only axes without tick-labels can be tiled. (Otherwise, axis labels on tiled tensors would no longer be unique.) See lt.tile. Args: labeled_tensor: The input tensor. multiples: A mapping where the keys are axis names and the values are the integer number of times to tile along that axis. Only axes with a multiple different than 1 need be included. name: Optional op name. Returns: A tensor with the indicated axes tiled. Raises: ValueError: If the tiled axes are not axes in the input tensor, or if any axes in multiples have tick labels. """ with ops.name_scope(name, 'lt_tile', [labeled_tensor]) as scope: labeled_tensor = core.convert_to_labeled_tensor(labeled_tensor) if not set(multiples.keys()) <= set(labeled_tensor.axes.keys()): raise ValueError('tile axes %r are not contained in the set of axis ' 'names %r on the input labeled tensor' % (multiples.keys(), labeled_tensor.axes)) labeled_axes = [ name for name in multiples if labeled_tensor.axes[name].labels is not None ] if labeled_axes: raise ValueError('cannot tile axes with tick labels: %r' % labeled_axes) multiples_list = [multiples.get(name, 1) for name in labeled_tensor.axes] tile_op = array_ops.tile(labeled_tensor.tensor, multiples_list, name=scope) new_axes = [ axis.name if axis.labels is None else axis for axis in labeled_tensor.axes.values() ] return core.LabeledTensor(tile_op, new_axes)
[ "def", "tile", "(", "labeled_tensor", ",", "multiples", ",", "name", "=", "None", ")", ":", "with", "ops", ".", "name_scope", "(", "name", ",", "'lt_tile'", ",", "[", "labeled_tensor", "]", ")", "as", "scope", ":", "labeled_tensor", "=", "core", ".", "convert_to_labeled_tensor", "(", "labeled_tensor", ")", "if", "not", "set", "(", "multiples", ".", "keys", "(", ")", ")", "<=", "set", "(", "labeled_tensor", ".", "axes", ".", "keys", "(", ")", ")", ":", "raise", "ValueError", "(", "'tile axes %r are not contained in the set of axis '", "'names %r on the input labeled tensor'", "%", "(", "multiples", ".", "keys", "(", ")", ",", "labeled_tensor", ".", "axes", ")", ")", "labeled_axes", "=", "[", "name", "for", "name", "in", "multiples", "if", "labeled_tensor", ".", "axes", "[", "name", "]", ".", "labels", "is", "not", "None", "]", "if", "labeled_axes", ":", "raise", "ValueError", "(", "'cannot tile axes with tick labels: %r'", "%", "labeled_axes", ")", "multiples_list", "=", "[", "multiples", ".", "get", "(", "name", ",", "1", ")", "for", "name", "in", "labeled_tensor", ".", "axes", "]", "tile_op", "=", "array_ops", ".", "tile", "(", "labeled_tensor", ".", "tensor", ",", "multiples_list", ",", "name", "=", "scope", ")", "new_axes", "=", "[", "axis", ".", "name", "if", "axis", ".", "labels", "is", "None", "else", "axis", "for", "axis", "in", "labeled_tensor", ".", "axes", ".", "values", "(", ")", "]", "return", "core", ".", "LabeledTensor", "(", "tile_op", ",", "new_axes", ")" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/labeled_tensor/python/ops/ops.py#L980-L1024
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/urllib3/util/url.py
python
Url.url
(self)
return url
Convert self into a url This function should more or less round-trip with :func:`.parse_url`. The returned url may not be exactly the same as the url inputted to :func:`.parse_url`, but it should be equivalent by the RFC (e.g., urls with a blank port will have : removed). Example: :: >>> U = parse_url('http://google.com/mail/') >>> U.url 'http://google.com/mail/' >>> Url('http', 'username:password', 'host.com', 80, ... '/path', 'query', 'fragment').url 'http://username:password@host.com:80/path?query#fragment'
Convert self into a url
[ "Convert", "self", "into", "a", "url" ]
def url(self): """ Convert self into a url This function should more or less round-trip with :func:`.parse_url`. The returned url may not be exactly the same as the url inputted to :func:`.parse_url`, but it should be equivalent by the RFC (e.g., urls with a blank port will have : removed). Example: :: >>> U = parse_url('http://google.com/mail/') >>> U.url 'http://google.com/mail/' >>> Url('http', 'username:password', 'host.com', 80, ... '/path', 'query', 'fragment').url 'http://username:password@host.com:80/path?query#fragment' """ scheme, auth, host, port, path, query, fragment = self url = u"" # We use "is not None" we want things to happen with empty strings (or 0 port) if scheme is not None: url += scheme + u"://" if auth is not None: url += auth + u"@" if host is not None: url += host if port is not None: url += u":" + str(port) if path is not None: url += path if query is not None: url += u"?" + query if fragment is not None: url += u"#" + fragment return url
[ "def", "url", "(", "self", ")", ":", "scheme", ",", "auth", ",", "host", ",", "port", ",", "path", ",", "query", ",", "fragment", "=", "self", "url", "=", "u\"\"", "# We use \"is not None\" we want things to happen with empty strings (or 0 port)", "if", "scheme", "is", "not", "None", ":", "url", "+=", "scheme", "+", "u\"://\"", "if", "auth", "is", "not", "None", ":", "url", "+=", "auth", "+", "u\"@\"", "if", "host", "is", "not", "None", ":", "url", "+=", "host", "if", "port", "is", "not", "None", ":", "url", "+=", "u\":\"", "+", "str", "(", "port", ")", "if", "path", "is", "not", "None", ":", "url", "+=", "path", "if", "query", "is", "not", "None", ":", "url", "+=", "u\"?\"", "+", "query", "if", "fragment", "is", "not", "None", ":", "url", "+=", "u\"#\"", "+", "fragment", "return", "url" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/urllib3/util/url.py#L132-L169
timi-liuliang/echo
40a5a24d430eee4118314459ab7e03afcb3b8719
thirdparty/protobuf/python/google/protobuf/descriptor.py
python
MakeDescriptor
(desc_proto, package='', build_file_if_cpp=True)
return Descriptor(desc_proto.name, desc_name, None, None, fields, nested_types.values(), enum_types.values(), [])
Make a protobuf Descriptor given a DescriptorProto protobuf. Handles nested descriptors. Note that this is limited to the scope of defining a message inside of another message. Composite fields can currently only be resolved if the message is defined in the same scope as the field. Args: desc_proto: The descriptor_pb2.DescriptorProto protobuf message. package: Optional package name for the new message Descriptor (string). build_file_if_cpp: Update the C++ descriptor pool if api matches. Set to False on recursion, so no duplicates are created. Returns: A Descriptor for protobuf messages.
Make a protobuf Descriptor given a DescriptorProto protobuf.
[ "Make", "a", "protobuf", "Descriptor", "given", "a", "DescriptorProto", "protobuf", "." ]
def MakeDescriptor(desc_proto, package='', build_file_if_cpp=True): """Make a protobuf Descriptor given a DescriptorProto protobuf. Handles nested descriptors. Note that this is limited to the scope of defining a message inside of another message. Composite fields can currently only be resolved if the message is defined in the same scope as the field. Args: desc_proto: The descriptor_pb2.DescriptorProto protobuf message. package: Optional package name for the new message Descriptor (string). build_file_if_cpp: Update the C++ descriptor pool if api matches. Set to False on recursion, so no duplicates are created. Returns: A Descriptor for protobuf messages. """ if api_implementation.Type() == 'cpp' and build_file_if_cpp: # The C++ implementation requires all descriptors to be backed by the same # definition in the C++ descriptor pool. To do this, we build a # FileDescriptorProto with the same definition as this descriptor and build # it into the pool. from google.protobuf import descriptor_pb2 file_descriptor_proto = descriptor_pb2.FileDescriptorProto() file_descriptor_proto.message_type.add().MergeFrom(desc_proto) # Generate a random name for this proto file to prevent conflicts with # any imported ones. We need to specify a file name so BuildFile accepts # our FileDescriptorProto, but it is not important what that file name # is actually set to. proto_name = str(uuid.uuid4()) if package: file_descriptor_proto.name = os.path.join(package.replace('.', '/'), proto_name + '.proto') file_descriptor_proto.package = package else: file_descriptor_proto.name = proto_name + '.proto' if api_implementation.Version() == 2: # pylint: disable=protected-access _message.Message._BuildFile(file_descriptor_proto.SerializeToString()) # pylint: enable=protected-access else: cpp_message.BuildFile(file_descriptor_proto.SerializeToString()) full_message_name = [desc_proto.name] if package: full_message_name.insert(0, package) # Create Descriptors for enum types enum_types = {} for enum_proto in desc_proto.enum_type: full_name = '.'.join(full_message_name + [enum_proto.name]) enum_desc = EnumDescriptor( enum_proto.name, full_name, None, [ EnumValueDescriptor(enum_val.name, ii, enum_val.number) for ii, enum_val in enumerate(enum_proto.value)]) enum_types[full_name] = enum_desc # Create Descriptors for nested types nested_types = {} for nested_proto in desc_proto.nested_type: full_name = '.'.join(full_message_name + [nested_proto.name]) # Nested types are just those defined inside of the message, not all types # used by fields in the message, so no loops are possible here. nested_desc = MakeDescriptor(nested_proto, package='.'.join(full_message_name), build_file_if_cpp=False) nested_types[full_name] = nested_desc fields = [] for field_proto in desc_proto.field: full_name = '.'.join(full_message_name + [field_proto.name]) enum_desc = None nested_desc = None if field_proto.HasField('type_name'): type_name = field_proto.type_name full_type_name = '.'.join(full_message_name + [type_name[type_name.rfind('.')+1:]]) if full_type_name in nested_types: nested_desc = nested_types[full_type_name] elif full_type_name in enum_types: enum_desc = enum_types[full_type_name] # Else type_name references a non-local type, which isn't implemented field = FieldDescriptor( field_proto.name, full_name, field_proto.number - 1, field_proto.number, field_proto.type, FieldDescriptor.ProtoTypeToCppProtoType(field_proto.type), field_proto.label, None, nested_desc, enum_desc, None, False, None, has_default_value=False) fields.append(field) desc_name = '.'.join(full_message_name) return Descriptor(desc_proto.name, desc_name, None, None, fields, nested_types.values(), enum_types.values(), [])
[ "def", "MakeDescriptor", "(", "desc_proto", ",", "package", "=", "''", ",", "build_file_if_cpp", "=", "True", ")", ":", "if", "api_implementation", ".", "Type", "(", ")", "==", "'cpp'", "and", "build_file_if_cpp", ":", "# The C++ implementation requires all descriptors to be backed by the same", "# definition in the C++ descriptor pool. To do this, we build a", "# FileDescriptorProto with the same definition as this descriptor and build", "# it into the pool.", "from", "google", ".", "protobuf", "import", "descriptor_pb2", "file_descriptor_proto", "=", "descriptor_pb2", ".", "FileDescriptorProto", "(", ")", "file_descriptor_proto", ".", "message_type", ".", "add", "(", ")", ".", "MergeFrom", "(", "desc_proto", ")", "# Generate a random name for this proto file to prevent conflicts with", "# any imported ones. We need to specify a file name so BuildFile accepts", "# our FileDescriptorProto, but it is not important what that file name", "# is actually set to.", "proto_name", "=", "str", "(", "uuid", ".", "uuid4", "(", ")", ")", "if", "package", ":", "file_descriptor_proto", ".", "name", "=", "os", ".", "path", ".", "join", "(", "package", ".", "replace", "(", "'.'", ",", "'/'", ")", ",", "proto_name", "+", "'.proto'", ")", "file_descriptor_proto", ".", "package", "=", "package", "else", ":", "file_descriptor_proto", ".", "name", "=", "proto_name", "+", "'.proto'", "if", "api_implementation", ".", "Version", "(", ")", "==", "2", ":", "# pylint: disable=protected-access", "_message", ".", "Message", ".", "_BuildFile", "(", "file_descriptor_proto", ".", "SerializeToString", "(", ")", ")", "# pylint: enable=protected-access", "else", ":", "cpp_message", ".", "BuildFile", "(", "file_descriptor_proto", ".", "SerializeToString", "(", ")", ")", "full_message_name", "=", "[", "desc_proto", ".", "name", "]", "if", "package", ":", "full_message_name", ".", "insert", "(", "0", ",", "package", ")", "# Create Descriptors for enum types", "enum_types", "=", "{", "}", "for", "enum_proto", "in", "desc_proto", ".", "enum_type", ":", "full_name", "=", "'.'", ".", "join", "(", "full_message_name", "+", "[", "enum_proto", ".", "name", "]", ")", "enum_desc", "=", "EnumDescriptor", "(", "enum_proto", ".", "name", ",", "full_name", ",", "None", ",", "[", "EnumValueDescriptor", "(", "enum_val", ".", "name", ",", "ii", ",", "enum_val", ".", "number", ")", "for", "ii", ",", "enum_val", "in", "enumerate", "(", "enum_proto", ".", "value", ")", "]", ")", "enum_types", "[", "full_name", "]", "=", "enum_desc", "# Create Descriptors for nested types", "nested_types", "=", "{", "}", "for", "nested_proto", "in", "desc_proto", ".", "nested_type", ":", "full_name", "=", "'.'", ".", "join", "(", "full_message_name", "+", "[", "nested_proto", ".", "name", "]", ")", "# Nested types are just those defined inside of the message, not all types", "# used by fields in the message, so no loops are possible here.", "nested_desc", "=", "MakeDescriptor", "(", "nested_proto", ",", "package", "=", "'.'", ".", "join", "(", "full_message_name", ")", ",", "build_file_if_cpp", "=", "False", ")", "nested_types", "[", "full_name", "]", "=", "nested_desc", "fields", "=", "[", "]", "for", "field_proto", "in", "desc_proto", ".", "field", ":", "full_name", "=", "'.'", ".", "join", "(", "full_message_name", "+", "[", "field_proto", ".", "name", "]", ")", "enum_desc", "=", "None", "nested_desc", "=", "None", "if", "field_proto", ".", "HasField", "(", "'type_name'", ")", ":", "type_name", "=", "field_proto", ".", "type_name", "full_type_name", "=", "'.'", ".", "join", "(", "full_message_name", "+", "[", "type_name", "[", "type_name", ".", "rfind", "(", "'.'", ")", "+", "1", ":", "]", "]", ")", "if", "full_type_name", "in", "nested_types", ":", "nested_desc", "=", "nested_types", "[", "full_type_name", "]", "elif", "full_type_name", "in", "enum_types", ":", "enum_desc", "=", "enum_types", "[", "full_type_name", "]", "# Else type_name references a non-local type, which isn't implemented", "field", "=", "FieldDescriptor", "(", "field_proto", ".", "name", ",", "full_name", ",", "field_proto", ".", "number", "-", "1", ",", "field_proto", ".", "number", ",", "field_proto", ".", "type", ",", "FieldDescriptor", ".", "ProtoTypeToCppProtoType", "(", "field_proto", ".", "type", ")", ",", "field_proto", ".", "label", ",", "None", ",", "nested_desc", ",", "enum_desc", ",", "None", ",", "False", ",", "None", ",", "has_default_value", "=", "False", ")", "fields", ".", "append", "(", "field", ")", "desc_name", "=", "'.'", ".", "join", "(", "full_message_name", ")", "return", "Descriptor", "(", "desc_proto", ".", "name", ",", "desc_name", ",", "None", ",", "None", ",", "fields", ",", "nested_types", ".", "values", "(", ")", ",", "enum_types", ".", "values", "(", ")", ",", "[", "]", ")" ]
https://github.com/timi-liuliang/echo/blob/40a5a24d430eee4118314459ab7e03afcb3b8719/thirdparty/protobuf/python/google/protobuf/descriptor.py#L757-L849
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/mapreduce/mapreduce/input_readers.py
python
BlobstoreZipLineInputReader.from_json
(cls, json, _reader=blobstore.BlobReader)
return cls(json[cls.BLOB_KEY_PARAM], json[cls.START_FILE_INDEX_PARAM], json[cls.END_FILE_INDEX_PARAM], json[cls.OFFSET_PARAM], _reader)
Creates an instance of the InputReader for the given input shard state. Args: json: The InputReader state as a dict-like object. _reader: For dependency injection. Returns: An instance of the InputReader configured using the values of json.
Creates an instance of the InputReader for the given input shard state.
[ "Creates", "an", "instance", "of", "the", "InputReader", "for", "the", "given", "input", "shard", "state", "." ]
def from_json(cls, json, _reader=blobstore.BlobReader): """Creates an instance of the InputReader for the given input shard state. Args: json: The InputReader state as a dict-like object. _reader: For dependency injection. Returns: An instance of the InputReader configured using the values of json. """ return cls(json[cls.BLOB_KEY_PARAM], json[cls.START_FILE_INDEX_PARAM], json[cls.END_FILE_INDEX_PARAM], json[cls.OFFSET_PARAM], _reader)
[ "def", "from_json", "(", "cls", ",", "json", ",", "_reader", "=", "blobstore", ".", "BlobReader", ")", ":", "return", "cls", "(", "json", "[", "cls", ".", "BLOB_KEY_PARAM", "]", ",", "json", "[", "cls", ".", "START_FILE_INDEX_PARAM", "]", ",", "json", "[", "cls", ".", "END_FILE_INDEX_PARAM", "]", ",", "json", "[", "cls", ".", "OFFSET_PARAM", "]", ",", "_reader", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/mapreduce/mapreduce/input_readers.py#L1807-L1821
mongodb/mongo
d8ff665343ad29cf286ee2cf4a1960d29371937b
buildscripts/resmokelib/powercycle/__init__.py
python
PowercyclePlugin._add_powercycle_commands
(parent_parser)
return run_parser
Add sub-subcommands for powercycle.
Add sub-subcommands for powercycle.
[ "Add", "sub", "-", "subcommands", "for", "powercycle", "." ]
def _add_powercycle_commands(parent_parser): """Add sub-subcommands for powercycle.""" sub_parsers = parent_parser.add_subparsers() setup_parser = sub_parsers.add_parser("setup-host", help="Step 1. Set up the host for powercycle") setup_parser.set_defaults(run_option=Powercycle.HOST_SETUP) run_parser = sub_parsers.add_parser( "run", help="Step 2. Run the Powercycle test of your choice;" "search for 'powercycle invocation' in evg task logs") run_parser.set_defaults(run_option=Powercycle.RUN) save_parser = sub_parsers.add_parser( "save-diagnostics", help="Copy Powercycle diagnostics to local machine; mainly used by Evergreen. For" "local invocation, consider instead ssh-ing into the Powercycle host directly") save_parser.set_defaults(run_option=Powercycle.SAVE_DIAG) save_parser = sub_parsers.add_parser( "remote-hang-analyzer", help="Run the hang analyzer on the remote machine; mainly used by Evergreen") save_parser.set_defaults(run_option=Powercycle.REMOTE_HANG_ANALYZER) # Only need to return run_parser for further processing; others don't need additional args. return run_parser
[ "def", "_add_powercycle_commands", "(", "parent_parser", ")", ":", "sub_parsers", "=", "parent_parser", ".", "add_subparsers", "(", ")", "setup_parser", "=", "sub_parsers", ".", "add_parser", "(", "\"setup-host\"", ",", "help", "=", "\"Step 1. Set up the host for powercycle\"", ")", "setup_parser", ".", "set_defaults", "(", "run_option", "=", "Powercycle", ".", "HOST_SETUP", ")", "run_parser", "=", "sub_parsers", ".", "add_parser", "(", "\"run\"", ",", "help", "=", "\"Step 2. Run the Powercycle test of your choice;\"", "\"search for 'powercycle invocation' in evg task logs\"", ")", "run_parser", ".", "set_defaults", "(", "run_option", "=", "Powercycle", ".", "RUN", ")", "save_parser", "=", "sub_parsers", ".", "add_parser", "(", "\"save-diagnostics\"", ",", "help", "=", "\"Copy Powercycle diagnostics to local machine; mainly used by Evergreen. For\"", "\"local invocation, consider instead ssh-ing into the Powercycle host directly\"", ")", "save_parser", ".", "set_defaults", "(", "run_option", "=", "Powercycle", ".", "SAVE_DIAG", ")", "save_parser", "=", "sub_parsers", ".", "add_parser", "(", "\"remote-hang-analyzer\"", ",", "help", "=", "\"Run the hang analyzer on the remote machine; mainly used by Evergreen\"", ")", "save_parser", ".", "set_defaults", "(", "run_option", "=", "Powercycle", ".", "REMOTE_HANG_ANALYZER", ")", "# Only need to return run_parser for further processing; others don't need additional args.", "return", "run_parser" ]
https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/resmokelib/powercycle/__init__.py#L79-L104
qt/qtbase
81b9ee66b8e40ed145185fe46b7c91929688cafd
util/locale_database/cldr.py
python
CldrReader.likelySubTags
(self)
Generator for likely subtag information. Yields pairs (have, give) of 4-tuples; if what you have matches the left member, giving the right member is probably sensible. Each 4-tuple's entries are the full names of a language, a script, a territory (usually a country) and a variant (currently ignored).
Generator for likely subtag information.
[ "Generator", "for", "likely", "subtag", "information", "." ]
def likelySubTags(self): """Generator for likely subtag information. Yields pairs (have, give) of 4-tuples; if what you have matches the left member, giving the right member is probably sensible. Each 4-tuple's entries are the full names of a language, a script, a territory (usually a country) and a variant (currently ignored).""" skips = [] for got, use in self.root.likelySubTags(): try: have = self.__parseTags(got) give = self.__parseTags(use) except Error as e: if ((use.startswith(got) or got.startswith('und_')) and e.message.startswith('Unknown ') and ' code ' in e.message): skips.append(use) else: self.grumble(f'Skipping likelySubtag "{got}" -> "{use}" ({e})\n') continue if all(code.startswith('Any') and code[3].isupper() for code in have[:-1]): continue give = (give[0], # Substitute according to http://www.unicode.org/reports/tr35/#Likely_Subtags have[1] if give[1] == 'AnyScript' else give[1], have[2] if give[2] == 'AnyTerritory' else give[2], give[3]) # AnyVariant similarly ? yield have, give if skips: # TODO: look at LDML's reserved locale tag names; they # show up a lot in this, and may be grounds for filtering # more out. pass
[ "def", "likelySubTags", "(", "self", ")", ":", "skips", "=", "[", "]", "for", "got", ",", "use", "in", "self", ".", "root", ".", "likelySubTags", "(", ")", ":", "try", ":", "have", "=", "self", ".", "__parseTags", "(", "got", ")", "give", "=", "self", ".", "__parseTags", "(", "use", ")", "except", "Error", "as", "e", ":", "if", "(", "(", "use", ".", "startswith", "(", "got", ")", "or", "got", ".", "startswith", "(", "'und_'", ")", ")", "and", "e", ".", "message", ".", "startswith", "(", "'Unknown '", ")", "and", "' code '", "in", "e", ".", "message", ")", ":", "skips", ".", "append", "(", "use", ")", "else", ":", "self", ".", "grumble", "(", "f'Skipping likelySubtag \"{got}\" -> \"{use}\" ({e})\\n'", ")", "continue", "if", "all", "(", "code", ".", "startswith", "(", "'Any'", ")", "and", "code", "[", "3", "]", ".", "isupper", "(", ")", "for", "code", "in", "have", "[", ":", "-", "1", "]", ")", ":", "continue", "give", "=", "(", "give", "[", "0", "]", ",", "# Substitute according to http://www.unicode.org/reports/tr35/#Likely_Subtags", "have", "[", "1", "]", "if", "give", "[", "1", "]", "==", "'AnyScript'", "else", "give", "[", "1", "]", ",", "have", "[", "2", "]", "if", "give", "[", "2", "]", "==", "'AnyTerritory'", "else", "give", "[", "2", "]", ",", "give", "[", "3", "]", ")", "# AnyVariant similarly ?", "yield", "have", ",", "give", "if", "skips", ":", "# TODO: look at LDML's reserved locale tag names; they", "# show up a lot in this, and may be grounds for filtering", "# more out.", "pass" ]
https://github.com/qt/qtbase/blob/81b9ee66b8e40ed145185fe46b7c91929688cafd/util/locale_database/cldr.py#L65-L100
trailofbits/llvm-sanitizer-tutorial
d29dfeec7f51fbf234fd0080f28f2b30cd0b6e99
llvm/projects/compiler-rt/lib/sanitizer_common/scripts/cpplint.py
python
ResetNolintSuppressions
()
Resets the set of NOLINT suppressions to empty.
Resets the set of NOLINT suppressions to empty.
[ "Resets", "the", "set", "of", "NOLINT", "suppressions", "to", "empty", "." ]
def ResetNolintSuppressions(): "Resets the set of NOLINT suppressions to empty." _error_suppressions.clear()
[ "def", "ResetNolintSuppressions", "(", ")", ":", "_error_suppressions", ".", "clear", "(", ")" ]
https://github.com/trailofbits/llvm-sanitizer-tutorial/blob/d29dfeec7f51fbf234fd0080f28f2b30cd0b6e99/llvm/projects/compiler-rt/lib/sanitizer_common/scripts/cpplint.py#L389-L391
cyberbotics/webots
af7fa7d68dcf7b4550f1f2e132092b41e83698fc
projects/default/controllers/sumo_supervisor/SumoDisplay.py
python
SumoDisplay.step
(self, step)
Update the Display image.
Update the Display image.
[ "Update", "the", "Display", "image", "." ]
def step(self, step): """Update the Display image.""" if not pilFound: return self.timeCounter += step if self.timeCounter >= self.refreshRate: imageFilename = self.directory + '/screeshot_' + str(self.screeshotID) + '.jpg' self.traci.gui.screenshot(self.view, imageFilename) if self.resize: im = Image.open(imageFilename) im = im.resize(size=(self.width, self.height)) im.save(imageFilename) im.close() image = self.displayDevice.imageLoad(imageFilename) self.displayDevice.imagePaste(image, 0, 0) else: image = self.displayDevice.imageLoad(imageFilename) im = Image.open(imageFilename) imageWidth, imageHeight = im.size im.close() widthOffset = imageWidth / 2 - self.width / 2 if widthOffset < 0: widthOffset = 0 heightOffset = imageHeight / 2 - self.height / 2 if heightOffset < 0: heightOffset = 0 self.displayDevice.imagePaste(image, -widthOffset, -heightOffset) self.screeshotID += 1 self.timeCounter = 0
[ "def", "step", "(", "self", ",", "step", ")", ":", "if", "not", "pilFound", ":", "return", "self", ".", "timeCounter", "+=", "step", "if", "self", ".", "timeCounter", ">=", "self", ".", "refreshRate", ":", "imageFilename", "=", "self", ".", "directory", "+", "'/screeshot_'", "+", "str", "(", "self", ".", "screeshotID", ")", "+", "'.jpg'", "self", ".", "traci", ".", "gui", ".", "screenshot", "(", "self", ".", "view", ",", "imageFilename", ")", "if", "self", ".", "resize", ":", "im", "=", "Image", ".", "open", "(", "imageFilename", ")", "im", "=", "im", ".", "resize", "(", "size", "=", "(", "self", ".", "width", ",", "self", ".", "height", ")", ")", "im", ".", "save", "(", "imageFilename", ")", "im", ".", "close", "(", ")", "image", "=", "self", ".", "displayDevice", ".", "imageLoad", "(", "imageFilename", ")", "self", ".", "displayDevice", ".", "imagePaste", "(", "image", ",", "0", ",", "0", ")", "else", ":", "image", "=", "self", ".", "displayDevice", ".", "imageLoad", "(", "imageFilename", ")", "im", "=", "Image", ".", "open", "(", "imageFilename", ")", "imageWidth", ",", "imageHeight", "=", "im", ".", "size", "im", ".", "close", "(", ")", "widthOffset", "=", "imageWidth", "/", "2", "-", "self", ".", "width", "/", "2", "if", "widthOffset", "<", "0", ":", "widthOffset", "=", "0", "heightOffset", "=", "imageHeight", "/", "2", "-", "self", ".", "height", "/", "2", "if", "heightOffset", "<", "0", ":", "heightOffset", "=", "0", "self", ".", "displayDevice", ".", "imagePaste", "(", "image", ",", "-", "widthOffset", ",", "-", "heightOffset", ")", "self", ".", "screeshotID", "+=", "1", "self", ".", "timeCounter", "=", "0" ]
https://github.com/cyberbotics/webots/blob/af7fa7d68dcf7b4550f1f2e132092b41e83698fc/projects/default/controllers/sumo_supervisor/SumoDisplay.py#L50-L78
nvdla/sw
79538ba1b52b040a4a4645f630e457fa01839e90
umd/external/protobuf-2.6/python/google/protobuf/text_format.py
python
PrintFieldValue
(field, value, out, indent=0, as_utf8=False, as_one_line=False, pointy_brackets=False, float_format=None)
Print a single field value (not including name). For repeated fields, the value should be a single element.
Print a single field value (not including name). For repeated fields, the value should be a single element.
[ "Print", "a", "single", "field", "value", "(", "not", "including", "name", ")", ".", "For", "repeated", "fields", "the", "value", "should", "be", "a", "single", "element", "." ]
def PrintFieldValue(field, value, out, indent=0, as_utf8=False, as_one_line=False, pointy_brackets=False, float_format=None): """Print a single field value (not including name). For repeated fields, the value should be a single element.""" if pointy_brackets: openb = '<' closeb = '>' else: openb = '{' closeb = '}' if field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE: if as_one_line: out.write(' %s ' % openb) PrintMessage(value, out, indent, as_utf8, as_one_line, pointy_brackets=pointy_brackets, float_format=float_format) out.write(closeb) else: out.write(' %s\n' % openb) PrintMessage(value, out, indent + 2, as_utf8, as_one_line, pointy_brackets=pointy_brackets, float_format=float_format) out.write(' ' * indent + closeb) elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_ENUM: enum_value = field.enum_type.values_by_number.get(value, None) if enum_value is not None: out.write(enum_value.name) else: out.write(str(value)) elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_STRING: out.write('\"') if isinstance(value, unicode): out_value = value.encode('utf-8') else: out_value = value if field.type == descriptor.FieldDescriptor.TYPE_BYTES: # We need to escape non-UTF8 chars in TYPE_BYTES field. out_as_utf8 = False else: out_as_utf8 = as_utf8 out.write(text_encoding.CEscape(out_value, out_as_utf8)) out.write('\"') elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_BOOL: if value: out.write('true') else: out.write('false') elif field.cpp_type in _FLOAT_TYPES and float_format is not None: out.write('{1:{0}}'.format(float_format, value)) else: out.write(str(value))
[ "def", "PrintFieldValue", "(", "field", ",", "value", ",", "out", ",", "indent", "=", "0", ",", "as_utf8", "=", "False", ",", "as_one_line", "=", "False", ",", "pointy_brackets", "=", "False", ",", "float_format", "=", "None", ")", ":", "if", "pointy_brackets", ":", "openb", "=", "'<'", "closeb", "=", "'>'", "else", ":", "openb", "=", "'{'", "closeb", "=", "'}'", "if", "field", ".", "cpp_type", "==", "descriptor", ".", "FieldDescriptor", ".", "CPPTYPE_MESSAGE", ":", "if", "as_one_line", ":", "out", ".", "write", "(", "' %s '", "%", "openb", ")", "PrintMessage", "(", "value", ",", "out", ",", "indent", ",", "as_utf8", ",", "as_one_line", ",", "pointy_brackets", "=", "pointy_brackets", ",", "float_format", "=", "float_format", ")", "out", ".", "write", "(", "closeb", ")", "else", ":", "out", ".", "write", "(", "' %s\\n'", "%", "openb", ")", "PrintMessage", "(", "value", ",", "out", ",", "indent", "+", "2", ",", "as_utf8", ",", "as_one_line", ",", "pointy_brackets", "=", "pointy_brackets", ",", "float_format", "=", "float_format", ")", "out", ".", "write", "(", "' '", "*", "indent", "+", "closeb", ")", "elif", "field", ".", "cpp_type", "==", "descriptor", ".", "FieldDescriptor", ".", "CPPTYPE_ENUM", ":", "enum_value", "=", "field", ".", "enum_type", ".", "values_by_number", ".", "get", "(", "value", ",", "None", ")", "if", "enum_value", "is", "not", "None", ":", "out", ".", "write", "(", "enum_value", ".", "name", ")", "else", ":", "out", ".", "write", "(", "str", "(", "value", ")", ")", "elif", "field", ".", "cpp_type", "==", "descriptor", ".", "FieldDescriptor", ".", "CPPTYPE_STRING", ":", "out", ".", "write", "(", "'\\\"'", ")", "if", "isinstance", "(", "value", ",", "unicode", ")", ":", "out_value", "=", "value", ".", "encode", "(", "'utf-8'", ")", "else", ":", "out_value", "=", "value", "if", "field", ".", "type", "==", "descriptor", ".", "FieldDescriptor", ".", "TYPE_BYTES", ":", "# We need to escape non-UTF8 chars in TYPE_BYTES field.", "out_as_utf8", "=", "False", "else", ":", "out_as_utf8", "=", "as_utf8", "out", ".", "write", "(", "text_encoding", ".", "CEscape", "(", "out_value", ",", "out_as_utf8", ")", ")", "out", ".", "write", "(", "'\\\"'", ")", "elif", "field", ".", "cpp_type", "==", "descriptor", ".", "FieldDescriptor", ".", "CPPTYPE_BOOL", ":", "if", "value", ":", "out", ".", "write", "(", "'true'", ")", "else", ":", "out", ".", "write", "(", "'false'", ")", "elif", "field", ".", "cpp_type", "in", "_FLOAT_TYPES", "and", "float_format", "is", "not", "None", ":", "out", ".", "write", "(", "'{1:{0}}'", ".", "format", "(", "float_format", ",", "value", ")", ")", "else", ":", "out", ".", "write", "(", "str", "(", "value", ")", ")" ]
https://github.com/nvdla/sw/blob/79538ba1b52b040a4a4645f630e457fa01839e90/umd/external/protobuf-2.6/python/google/protobuf/text_format.py#L158-L211
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/py/py/_path/svnwc.py
python
SvnWCCommandPath.dirpath
(self, *args)
return self.__class__(self.localpath.dirpath(*args), auth=self.auth)
return the directory Path of the current Path.
return the directory Path of the current Path.
[ "return", "the", "directory", "Path", "of", "the", "current", "Path", "." ]
def dirpath(self, *args): """ return the directory Path of the current Path. """ return self.__class__(self.localpath.dirpath(*args), auth=self.auth)
[ "def", "dirpath", "(", "self", ",", "*", "args", ")", ":", "return", "self", ".", "__class__", "(", "self", ".", "localpath", ".", "dirpath", "(", "*", "args", ")", ",", "auth", "=", "self", ".", "auth", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/py/py/_path/svnwc.py#L529-L531
ptrkrysik/gr-gsm
2de47e28ce1fb9a518337bfc0add36c8e3cff5eb
docs/doxygen/swig_doc.py
python
make_class_entry
(klass, description=None, ignored_methods=[], params=None)
return "\n\n".join(output)
Create a class docstring for a swig interface file.
Create a class docstring for a swig interface file.
[ "Create", "a", "class", "docstring", "for", "a", "swig", "interface", "file", "." ]
def make_class_entry(klass, description=None, ignored_methods=[], params=None): """ Create a class docstring for a swig interface file. """ if params is None: params = klass.params output = [] output.append(make_entry(klass, description=description, params=params)) for func in klass.in_category(DoxyFunction): if func.name() not in ignored_methods: name = klass.name() + '::' + func.name() output.append(make_func_entry(func, name=name)) return "\n\n".join(output)
[ "def", "make_class_entry", "(", "klass", ",", "description", "=", "None", ",", "ignored_methods", "=", "[", "]", ",", "params", "=", "None", ")", ":", "if", "params", "is", "None", ":", "params", "=", "klass", ".", "params", "output", "=", "[", "]", "output", ".", "append", "(", "make_entry", "(", "klass", ",", "description", "=", "description", ",", "params", "=", "params", ")", ")", "for", "func", "in", "klass", ".", "in_category", "(", "DoxyFunction", ")", ":", "if", "func", ".", "name", "(", ")", "not", "in", "ignored_methods", ":", "name", "=", "klass", ".", "name", "(", ")", "+", "'::'", "+", "func", ".", "name", "(", ")", "output", ".", "append", "(", "make_func_entry", "(", "func", ",", "name", "=", "name", ")", ")", "return", "\"\\n\\n\"", ".", "join", "(", "output", ")" ]
https://github.com/ptrkrysik/gr-gsm/blob/2de47e28ce1fb9a518337bfc0add36c8e3cff5eb/docs/doxygen/swig_doc.py#L168-L180
fossephate/JoyCon-Driver
857e4e76e26f05d72400ae5d9f2a22cae88f3548
joycon-driver/full/wxWidgets-3.0.3/build/bakefiles/wxwin.py
python
headersOnly
(files)
return utils.substitute2(files, callback)
Filters 'files' so that only headers are left. Used with <msvc-project-files> to add headers to VC++ projects but not files such as arrimpl.cpp.
Filters 'files' so that only headers are left. Used with <msvc-project-files> to add headers to VC++ projects but not files such as arrimpl.cpp.
[ "Filters", "files", "so", "that", "only", "headers", "are", "left", ".", "Used", "with", "<msvc", "-", "project", "-", "files", ">", "to", "add", "headers", "to", "VC", "++", "projects", "but", "not", "files", "such", "as", "arrimpl", ".", "cpp", "." ]
def headersOnly(files): """Filters 'files' so that only headers are left. Used with <msvc-project-files> to add headers to VC++ projects but not files such as arrimpl.cpp.""" def callback(cond, sources): prf = suf = '' if sources[0].isspace(): prf=' ' if sources[-1].isspace(): suf=' ' retval = [] for s in sources.split(): if s.endswith('.h'): retval.append(s) return '%s%s%s' % (prf, ' '.join(retval), suf) return utils.substitute2(files, callback)
[ "def", "headersOnly", "(", "files", ")", ":", "def", "callback", "(", "cond", ",", "sources", ")", ":", "prf", "=", "suf", "=", "''", "if", "sources", "[", "0", "]", ".", "isspace", "(", ")", ":", "prf", "=", "' '", "if", "sources", "[", "-", "1", "]", ".", "isspace", "(", ")", ":", "suf", "=", "' '", "retval", "=", "[", "]", "for", "s", "in", "sources", ".", "split", "(", ")", ":", "if", "s", ".", "endswith", "(", "'.h'", ")", ":", "retval", ".", "append", "(", "s", ")", "return", "'%s%s%s'", "%", "(", "prf", ",", "' '", ".", "join", "(", "retval", ")", ",", "suf", ")", "return", "utils", ".", "substitute2", "(", "files", ",", "callback", ")" ]
https://github.com/fossephate/JoyCon-Driver/blob/857e4e76e26f05d72400ae5d9f2a22cae88f3548/joycon-driver/full/wxWidgets-3.0.3/build/bakefiles/wxwin.py#L135-L149
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/pbr/packaging.py
python
_get_revno_and_last_tag
(git_dir)
return "", row_count
Return the commit data about the most recent tag. We use git-describe to find this out, but if there are no tags then we fall back to counting commits since the beginning of time.
Return the commit data about the most recent tag.
[ "Return", "the", "commit", "data", "about", "the", "most", "recent", "tag", "." ]
def _get_revno_and_last_tag(git_dir): """Return the commit data about the most recent tag. We use git-describe to find this out, but if there are no tags then we fall back to counting commits since the beginning of time. """ changelog = git._iter_log_oneline(git_dir=git_dir) row_count = 0 for row_count, (ignored, tag_set, ignored) in enumerate(changelog): version_tags = set() semver_to_tag = dict() for tag in list(tag_set): try: semver = version.SemanticVersion.from_pip_string(tag) semver_to_tag[semver] = tag version_tags.add(semver) except Exception: pass if version_tags: return semver_to_tag[max(version_tags)], row_count return "", row_count
[ "def", "_get_revno_and_last_tag", "(", "git_dir", ")", ":", "changelog", "=", "git", ".", "_iter_log_oneline", "(", "git_dir", "=", "git_dir", ")", "row_count", "=", "0", "for", "row_count", ",", "(", "ignored", ",", "tag_set", ",", "ignored", ")", "in", "enumerate", "(", "changelog", ")", ":", "version_tags", "=", "set", "(", ")", "semver_to_tag", "=", "dict", "(", ")", "for", "tag", "in", "list", "(", "tag_set", ")", ":", "try", ":", "semver", "=", "version", ".", "SemanticVersion", ".", "from_pip_string", "(", "tag", ")", "semver_to_tag", "[", "semver", "]", "=", "tag", "version_tags", ".", "add", "(", "semver", ")", "except", "Exception", ":", "pass", "if", "version_tags", ":", "return", "semver_to_tag", "[", "max", "(", "version_tags", ")", "]", ",", "row_count", "return", "\"\"", ",", "row_count" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/pbr/packaging.py#L653-L674
jackaudio/jack2
21b293dbc37d42446141a08922cdec0d2550c6a0
waflib/Build.py
python
BuildContext.set_env
(self, val)
Setter for the env property
Setter for the env property
[ "Setter", "for", "the", "env", "property" ]
def set_env(self, val): """Setter for the env property""" self.all_envs[self.variant] = val
[ "def", "set_env", "(", "self", ",", "val", ")", ":", "self", ".", "all_envs", "[", "self", ".", "variant", "]", "=", "val" ]
https://github.com/jackaudio/jack2/blob/21b293dbc37d42446141a08922cdec0d2550c6a0/waflib/Build.py#L391-L393
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_gdi.py
python
PseudoDC.DrawRoundedRectangle
(*args, **kwargs)
return _gdi_.PseudoDC_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_.PseudoDC_DrawRoundedRectangle(*args, **kwargs)
[ "def", "DrawRoundedRectangle", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gdi_", ".", "PseudoDC_DrawRoundedRectangle", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_gdi.py#L7919-L7935
senlinuc/caffe_ocr
81642f61ea8f888e360cca30e08e05b7bc6d4556
examples/pycaffe/layers/pascal_multilabel_datalayers.py
python
print_info
(name, params)
Ouput some info regarding the class
Ouput some info regarding the class
[ "Ouput", "some", "info", "regarding", "the", "class" ]
def print_info(name, params): """ Ouput some info regarding the class """ print "{} initialized for split: {}, with bs: {}, im_shape: {}.".format( name, params['split'], params['batch_size'], params['im_shape'])
[ "def", "print_info", "(", "name", ",", "params", ")", ":", "print", "\"{} initialized for split: {}, with bs: {}, im_shape: {}.\"", ".", "format", "(", "name", ",", "params", "[", "'split'", "]", ",", "params", "[", "'batch_size'", "]", ",", "params", "[", "'im_shape'", "]", ")" ]
https://github.com/senlinuc/caffe_ocr/blob/81642f61ea8f888e360cca30e08e05b7bc6d4556/examples/pycaffe/layers/pascal_multilabel_datalayers.py#L208-L216
miyosuda/TensorFlowAndroidMNIST
7b5a4603d2780a8a2834575706e9001977524007
jni-build/jni/include/tensorflow/contrib/layers/python/layers/feature_column.py
python
_WeightedSparseColumn.insert_transformed_feature
(self, columns_to_tensors)
Inserts a tuple with the id and weight tensors.
Inserts a tuple with the id and weight tensors.
[ "Inserts", "a", "tuple", "with", "the", "id", "and", "weight", "tensors", "." ]
def insert_transformed_feature(self, columns_to_tensors): """Inserts a tuple with the id and weight tensors.""" if self.sparse_id_column not in columns_to_tensors: self.sparse_id_column.insert_transformed_feature(columns_to_tensors) columns_to_tensors[self] = tuple([ columns_to_tensors[self.sparse_id_column], columns_to_tensors[self.weight_column_name]])
[ "def", "insert_transformed_feature", "(", "self", ",", "columns_to_tensors", ")", ":", "if", "self", ".", "sparse_id_column", "not", "in", "columns_to_tensors", ":", "self", ".", "sparse_id_column", ".", "insert_transformed_feature", "(", "columns_to_tensors", ")", "columns_to_tensors", "[", "self", "]", "=", "tuple", "(", "[", "columns_to_tensors", "[", "self", ".", "sparse_id_column", "]", ",", "columns_to_tensors", "[", "self", ".", "weight_column_name", "]", "]", ")" ]
https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/contrib/layers/python/layers/feature_column.py#L490-L496
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/numpy/py3/numpy/random/_pickle.py
python
__bit_generator_ctor
(bit_generator_name='MT19937')
return bit_generator()
Pickling helper function that returns a bit generator object Parameters ---------- bit_generator_name : str String containing the name of the BitGenerator Returns ------- bit_generator: BitGenerator BitGenerator instance
Pickling helper function that returns a bit generator object
[ "Pickling", "helper", "function", "that", "returns", "a", "bit", "generator", "object" ]
def __bit_generator_ctor(bit_generator_name='MT19937'): """ Pickling helper function that returns a bit generator object Parameters ---------- bit_generator_name : str String containing the name of the BitGenerator Returns ------- bit_generator: BitGenerator BitGenerator instance """ if bit_generator_name in BitGenerators: bit_generator = BitGenerators[bit_generator_name] else: raise ValueError(str(bit_generator_name) + ' is not a known ' 'BitGenerator module.') return bit_generator()
[ "def", "__bit_generator_ctor", "(", "bit_generator_name", "=", "'MT19937'", ")", ":", "if", "bit_generator_name", "in", "BitGenerators", ":", "bit_generator", "=", "BitGenerators", "[", "bit_generator_name", "]", "else", ":", "raise", "ValueError", "(", "str", "(", "bit_generator_name", ")", "+", "' is not a known '", "'BitGenerator module.'", ")", "return", "bit_generator", "(", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py3/numpy/random/_pickle.py#L40-L60
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/contrib/gan/python/train.py
python
get_joint_train_hooks
(train_steps=namedtuples.GANTrainSteps(1, 1))
return get_hooks
Returns a hooks function for sequential GAN training. When using these train hooks, IT IS RECOMMENDED TO USE `use_locking=True` ON ALL OPTIMIZERS TO AVOID RACE CONDITIONS. The order of steps taken is: 1) Combined generator and discriminator steps 2) Generator only steps, if any remain 3) Discriminator only steps, if any remain **NOTE**: Unlike `get_sequential_train_hooks`, this method performs updates for the generator and discriminator simultaneously whenever possible. This reduces the number of `tf.Session` calls, and can also change the training semantics. To illustrate the difference look at the following example: `train_steps=namedtuples.GANTrainSteps(3, 5)` will cause `get_sequential_train_hooks` to make 8 session calls: 1) 3 generator steps 2) 5 discriminator steps In contrast, `get_joint_train_steps` will make 5 session calls: 1) 3 generator + discriminator steps 2) 2 discriminator steps Args: train_steps: A `GANTrainSteps` tuple that determines how many generator and discriminator training steps to take. Returns: A function that takes a GANTrainOps tuple and returns a list of hooks.
Returns a hooks function for sequential GAN training.
[ "Returns", "a", "hooks", "function", "for", "sequential", "GAN", "training", "." ]
def get_joint_train_hooks(train_steps=namedtuples.GANTrainSteps(1, 1)): """Returns a hooks function for sequential GAN training. When using these train hooks, IT IS RECOMMENDED TO USE `use_locking=True` ON ALL OPTIMIZERS TO AVOID RACE CONDITIONS. The order of steps taken is: 1) Combined generator and discriminator steps 2) Generator only steps, if any remain 3) Discriminator only steps, if any remain **NOTE**: Unlike `get_sequential_train_hooks`, this method performs updates for the generator and discriminator simultaneously whenever possible. This reduces the number of `tf.Session` calls, and can also change the training semantics. To illustrate the difference look at the following example: `train_steps=namedtuples.GANTrainSteps(3, 5)` will cause `get_sequential_train_hooks` to make 8 session calls: 1) 3 generator steps 2) 5 discriminator steps In contrast, `get_joint_train_steps` will make 5 session calls: 1) 3 generator + discriminator steps 2) 2 discriminator steps Args: train_steps: A `GANTrainSteps` tuple that determines how many generator and discriminator training steps to take. Returns: A function that takes a GANTrainOps tuple and returns a list of hooks. """ g_steps = train_steps.generator_train_steps d_steps = train_steps.discriminator_train_steps # Get the number of each type of step that should be run. num_d_and_g_steps = min(g_steps, d_steps) num_g_steps = g_steps - num_d_and_g_steps num_d_steps = d_steps - num_d_and_g_steps def get_hooks(train_ops): g_op = train_ops.generator_train_op d_op = train_ops.discriminator_train_op joint_hook = RunTrainOpsHook([g_op, d_op], num_d_and_g_steps) g_hook = RunTrainOpsHook(g_op, num_g_steps) d_hook = RunTrainOpsHook(d_op, num_d_steps) return [joint_hook, g_hook, d_hook] return get_hooks
[ "def", "get_joint_train_hooks", "(", "train_steps", "=", "namedtuples", ".", "GANTrainSteps", "(", "1", ",", "1", ")", ")", ":", "g_steps", "=", "train_steps", ".", "generator_train_steps", "d_steps", "=", "train_steps", ".", "discriminator_train_steps", "# Get the number of each type of step that should be run.", "num_d_and_g_steps", "=", "min", "(", "g_steps", ",", "d_steps", ")", "num_g_steps", "=", "g_steps", "-", "num_d_and_g_steps", "num_d_steps", "=", "d_steps", "-", "num_d_and_g_steps", "def", "get_hooks", "(", "train_ops", ")", ":", "g_op", "=", "train_ops", ".", "generator_train_op", "d_op", "=", "train_ops", ".", "discriminator_train_op", "joint_hook", "=", "RunTrainOpsHook", "(", "[", "g_op", ",", "d_op", "]", ",", "num_d_and_g_steps", ")", "g_hook", "=", "RunTrainOpsHook", "(", "g_op", ",", "num_g_steps", ")", "d_hook", "=", "RunTrainOpsHook", "(", "d_op", ",", "num_d_steps", ")", "return", "[", "joint_hook", ",", "g_hook", ",", "d_hook", "]", "return", "get_hooks" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/gan/python/train.py#L606-L656
gimli-org/gimli
17aa2160de9b15ababd9ef99e89b1bc3277bbb23
pygimli/physics/ert/ertModelling.py
python
ERTModellingReference.pointSource
(self, cell, f, userData)
r""" Define function for the current source term. :math:`\delta(x-pos), \int f(x) \delta(x-pos)=f(pos)=N(pos)` Right hand side entries will be shape functions(pos)
r""" Define function for the current source term.
[ "r", "Define", "function", "for", "the", "current", "source", "term", "." ]
def pointSource(self, cell, f, userData): r""" Define function for the current source term. :math:`\delta(x-pos), \int f(x) \delta(x-pos)=f(pos)=N(pos)` Right hand side entries will be shape functions(pos) """ i = userData['i'] sourcePos = userData['sourcePos'][i] if cell.shape().isInside(sourcePos): f.setVal(cell.N(cell.shape().rst(sourcePos)), cell.ids())
[ "def", "pointSource", "(", "self", ",", "cell", ",", "f", ",", "userData", ")", ":", "i", "=", "userData", "[", "'i'", "]", "sourcePos", "=", "userData", "[", "'sourcePos'", "]", "[", "i", "]", "if", "cell", ".", "shape", "(", ")", ".", "isInside", "(", "sourcePos", ")", ":", "f", ".", "setVal", "(", "cell", ".", "N", "(", "cell", ".", "shape", "(", ")", ".", "rst", "(", "sourcePos", ")", ")", ",", "cell", ".", "ids", "(", ")", ")" ]
https://github.com/gimli-org/gimli/blob/17aa2160de9b15ababd9ef99e89b1bc3277bbb23/pygimli/physics/ert/ertModelling.py#L429-L440
gimli-org/gimli
17aa2160de9b15ababd9ef99e89b1bc3277bbb23
pygimli/physics/ert/ves.py
python
VESModelling.setDataSpace
(self, ab2=None, mn2=None, am=None, bm=None, an=None, bn=None, **kwargs)
Set data basis, i.e., arrays for all am, an, bm, bn distances. Parameters ----------
Set data basis, i.e., arrays for all am, an, bm, bn distances.
[ "Set", "data", "basis", "i", ".", "e", ".", "arrays", "for", "all", "am", "an", "bm", "bn", "distances", "." ]
def setDataSpace(self, ab2=None, mn2=None, am=None, bm=None, an=None, bn=None, **kwargs): """Set data basis, i.e., arrays for all am, an, bm, bn distances. Parameters ---------- """ # Sometimes you don't have AB2/MN2 but provide am etc. self.am = am self.an = an self.bm = bm self.bn = bn if ab2 is not None and mn2 is not None: # overrides am etc. if isinstance(mn2, float): mn2 = np.ones(len(ab2))*mn2 if len(ab2) != len(mn2): print("ab2", ab2) print("mn2", mn2) raise Exception("length of ab2 is unequal length of mn2") self.am = ab2 - mn2 self.an = ab2 + mn2 self.bm = ab2 + mn2 self.bn = ab2 - mn2 elif (am is not None and bm is not None and an is not None and bn is not None): self.am = am self.bm = bm self.an = an self.bn = bn if self.am is not None and self.bm is not None: self.ab2 = (self.am + self.bm) / 2 self.mn2 = abs(self.am - self.an) / 2 self.k = (2.0 * np.pi) / (1.0 / self.am - 1.0 / self.an - 1.0 / self.bm + 1.0 / self.bn)
[ "def", "setDataSpace", "(", "self", ",", "ab2", "=", "None", ",", "mn2", "=", "None", ",", "am", "=", "None", ",", "bm", "=", "None", ",", "an", "=", "None", ",", "bn", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# Sometimes you don't have AB2/MN2 but provide am etc.", "self", ".", "am", "=", "am", "self", ".", "an", "=", "an", "self", ".", "bm", "=", "bm", "self", ".", "bn", "=", "bn", "if", "ab2", "is", "not", "None", "and", "mn2", "is", "not", "None", ":", "# overrides am etc.", "if", "isinstance", "(", "mn2", ",", "float", ")", ":", "mn2", "=", "np", ".", "ones", "(", "len", "(", "ab2", ")", ")", "*", "mn2", "if", "len", "(", "ab2", ")", "!=", "len", "(", "mn2", ")", ":", "print", "(", "\"ab2\"", ",", "ab2", ")", "print", "(", "\"mn2\"", ",", "mn2", ")", "raise", "Exception", "(", "\"length of ab2 is unequal length of mn2\"", ")", "self", ".", "am", "=", "ab2", "-", "mn2", "self", ".", "an", "=", "ab2", "+", "mn2", "self", ".", "bm", "=", "ab2", "+", "mn2", "self", ".", "bn", "=", "ab2", "-", "mn2", "elif", "(", "am", "is", "not", "None", "and", "bm", "is", "not", "None", "and", "an", "is", "not", "None", "and", "bn", "is", "not", "None", ")", ":", "self", ".", "am", "=", "am", "self", ".", "bm", "=", "bm", "self", ".", "an", "=", "an", "self", ".", "bn", "=", "bn", "if", "self", ".", "am", "is", "not", "None", "and", "self", ".", "bm", "is", "not", "None", ":", "self", ".", "ab2", "=", "(", "self", ".", "am", "+", "self", ".", "bm", ")", "/", "2", "self", ".", "mn2", "=", "abs", "(", "self", ".", "am", "-", "self", ".", "an", ")", "/", "2", "self", ".", "k", "=", "(", "2.0", "*", "np", ".", "pi", ")", "/", "(", "1.0", "/", "self", ".", "am", "-", "1.0", "/", "self", ".", "an", "-", "1.0", "/", "self", ".", "bm", "+", "1.0", "/", "self", ".", "bn", ")" ]
https://github.com/gimli-org/gimli/blob/17aa2160de9b15ababd9ef99e89b1bc3277bbb23/pygimli/physics/ert/ves.py#L80-L119
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/setuptools/dist.py
python
Distribution.get_command_class
(self, command)
Pluggable version of get_command_class()
Pluggable version of get_command_class()
[ "Pluggable", "version", "of", "get_command_class", "()" ]
def get_command_class(self, command): """Pluggable version of get_command_class()""" if command in self.cmdclass: return self.cmdclass[command] eps = pkg_resources.iter_entry_points('distutils.commands', command) for ep in eps: ep.require(installer=self.fetch_build_egg) self.cmdclass[command] = cmdclass = ep.load() return cmdclass else: return _Distribution.get_command_class(self, command)
[ "def", "get_command_class", "(", "self", ",", "command", ")", ":", "if", "command", "in", "self", ".", "cmdclass", ":", "return", "self", ".", "cmdclass", "[", "command", "]", "eps", "=", "pkg_resources", ".", "iter_entry_points", "(", "'distutils.commands'", ",", "command", ")", "for", "ep", "in", "eps", ":", "ep", ".", "require", "(", "installer", "=", "self", ".", "fetch_build_egg", ")", "self", ".", "cmdclass", "[", "command", "]", "=", "cmdclass", "=", "ep", ".", "load", "(", ")", "return", "cmdclass", "else", ":", "return", "_Distribution", ".", "get_command_class", "(", "self", ",", "command", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/setuptools/dist.py#L756-L767
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/statistics.py
python
NormalDist.cdf
(self, x)
return 0.5 * (1.0 + erf((x - self._mu) / (self._sigma * sqrt(2.0))))
Cumulative distribution function. P(X <= x)
Cumulative distribution function. P(X <= x)
[ "Cumulative", "distribution", "function", ".", "P", "(", "X", "<", "=", "x", ")" ]
def cdf(self, x): "Cumulative distribution function. P(X <= x)" if not self._sigma: raise StatisticsError('cdf() not defined when sigma is zero') return 0.5 * (1.0 + erf((x - self._mu) / (self._sigma * sqrt(2.0))))
[ "def", "cdf", "(", "self", ",", "x", ")", ":", "if", "not", "self", ".", "_sigma", ":", "raise", "StatisticsError", "(", "'cdf() not defined when sigma is zero'", ")", "return", "0.5", "*", "(", "1.0", "+", "erf", "(", "(", "x", "-", "self", ".", "_mu", ")", "/", "(", "self", ".", "_sigma", "*", "sqrt", "(", "2.0", ")", ")", ")", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/statistics.py#L942-L946
bundy-dns/bundy
3d41934996b82b0cd2fe22dd74d2abc1daba835d
src/lib/python/bundy/ddns/session.py
python
UpdateSession.__do_update_delete_rrs_from_rrset
(self, rrset)
Deletes all resource records in the given rrset from the zone. Resource records that do not exist are ignored. If the rrset if of type SOA, it is ignored. Uses the __ns_deleter_helper if the rrset's name is the zone's apex, and the type is NS.
Deletes all resource records in the given rrset from the zone. Resource records that do not exist are ignored. If the rrset if of type SOA, it is ignored. Uses the __ns_deleter_helper if the rrset's name is the zone's apex, and the type is NS.
[ "Deletes", "all", "resource", "records", "in", "the", "given", "rrset", "from", "the", "zone", ".", "Resource", "records", "that", "do", "not", "exist", "are", "ignored", ".", "If", "the", "rrset", "if", "of", "type", "SOA", "it", "is", "ignored", ".", "Uses", "the", "__ns_deleter_helper", "if", "the", "rrset", "s", "name", "is", "the", "zone", "s", "apex", "and", "the", "type", "is", "NS", "." ]
def __do_update_delete_rrs_from_rrset(self, rrset): '''Deletes all resource records in the given rrset from the zone. Resource records that do not exist are ignored. If the rrset if of type SOA, it is ignored. Uses the __ns_deleter_helper if the rrset's name is the zone's apex, and the type is NS. ''' # Delete all rrs in the rrset, except if name=self.__zname and type=soa, or # type = ns and there is only one left (...) # The delete does not want class NONE, we would not have gotten here # if it wasn't, but now is a good time to change it to the zclass. to_delete = convert_rrset_class(rrset, self.__zclass) if rrset.get_name() == self.__zname: if rrset.get_type() == RRType.SOA: # ignore return elif rrset.get_type() == RRType.NS: # hmm. okay. annoying. There must be at least one left, # delegate to helper method self.__ns_deleter_helper(to_delete) return for rr in foreach_rr(to_delete): self.__diff.delete_data(rr)
[ "def", "__do_update_delete_rrs_from_rrset", "(", "self", ",", "rrset", ")", ":", "# Delete all rrs in the rrset, except if name=self.__zname and type=soa, or", "# type = ns and there is only one left (...)", "# The delete does not want class NONE, we would not have gotten here", "# if it wasn't, but now is a good time to change it to the zclass.", "to_delete", "=", "convert_rrset_class", "(", "rrset", ",", "self", ".", "__zclass", ")", "if", "rrset", ".", "get_name", "(", ")", "==", "self", ".", "__zname", ":", "if", "rrset", ".", "get_type", "(", ")", "==", "RRType", ".", "SOA", ":", "# ignore", "return", "elif", "rrset", ".", "get_type", "(", ")", "==", "RRType", ".", "NS", ":", "# hmm. okay. annoying. There must be at least one left,", "# delegate to helper method", "self", ".", "__ns_deleter_helper", "(", "to_delete", ")", "return", "for", "rr", "in", "foreach_rr", "(", "to_delete", ")", ":", "self", ".", "__diff", ".", "delete_data", "(", "rr", ")" ]
https://github.com/bundy-dns/bundy/blob/3d41934996b82b0cd2fe22dd74d2abc1daba835d/src/lib/python/bundy/ddns/session.py#L763-L787
alexgkendall/caffe-segnet
344c113bf1832886f1cbe9f33ffe28a3beeaf412
scripts/cpp_lint.py
python
CheckForNewlineAtEOF
(filename, lines, error)
Logs an error if there is no newline char at the end of the file. Args: filename: The name of the current file. lines: An array of strings, each representing a line of the file. error: The function to call with any errors found.
Logs an error if there is no newline char at the end of the file.
[ "Logs", "an", "error", "if", "there", "is", "no", "newline", "char", "at", "the", "end", "of", "the", "file", "." ]
def CheckForNewlineAtEOF(filename, lines, error): """Logs an error if there is no newline char at the end of the file. Args: filename: The name of the current file. lines: An array of strings, each representing a line of the file. error: The function to call with any errors found. """ # The array lines() was created by adding two newlines to the # original file (go figure), then splitting on \n. # To verify that the file ends in \n, we just have to make sure the # last-but-two element of lines() exists and is empty. if len(lines) < 3 or lines[-2]: error(filename, len(lines) - 2, 'whitespace/ending_newline', 5, 'Could not find a newline character at the end of the file.')
[ "def", "CheckForNewlineAtEOF", "(", "filename", ",", "lines", ",", "error", ")", ":", "# The array lines() was created by adding two newlines to the", "# original file (go figure), then splitting on \\n.", "# To verify that the file ends in \\n, we just have to make sure the", "# last-but-two element of lines() exists and is empty.", "if", "len", "(", "lines", ")", "<", "3", "or", "lines", "[", "-", "2", "]", ":", "error", "(", "filename", ",", "len", "(", "lines", ")", "-", "2", ",", "'whitespace/ending_newline'", ",", "5", ",", "'Could not find a newline character at the end of the file.'", ")" ]
https://github.com/alexgkendall/caffe-segnet/blob/344c113bf1832886f1cbe9f33ffe28a3beeaf412/scripts/cpp_lint.py#L1508-L1523
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/graphy/graphy/common.py
python
Axis.__init__
(self, axis_min=None, axis_max=None)
Construct a new Axis. Args: axis_min: smallest value on the axis axis_max: largest value on the axis
Construct a new Axis.
[ "Construct", "a", "new", "Axis", "." ]
def __init__(self, axis_min=None, axis_max=None): """Construct a new Axis. Args: axis_min: smallest value on the axis axis_max: largest value on the axis """ self.min = axis_min self.max = axis_max self.labels = [] self.label_positions = [] self.grid_spacing = 0 self.label_gridlines = False
[ "def", "__init__", "(", "self", ",", "axis_min", "=", "None", ",", "axis_max", "=", "None", ")", ":", "self", ".", "min", "=", "axis_min", "self", ".", "max", "=", "axis_max", "self", ".", "labels", "=", "[", "]", "self", ".", "label_positions", "=", "[", "]", "self", ".", "grid_spacing", "=", "0", "self", ".", "label_gridlines", "=", "False" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/graphy/graphy/common.py#L188-L200
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/third_party/lib_aarch64/python2.7/dist-packages/rosdep2/sources_list.py
python
parse_sources_file
(filepath)
Parse file on disk :returns: List of data sources, [:class:`DataSource`] :raises: :exc:`InvalidData` If any error occurs reading file, so an I/O error, non-existent file, or invalid format.
Parse file on disk
[ "Parse", "file", "on", "disk" ]
def parse_sources_file(filepath): """ Parse file on disk :returns: List of data sources, [:class:`DataSource`] :raises: :exc:`InvalidData` If any error occurs reading file, so an I/O error, non-existent file, or invalid format. """ try: with open(filepath, 'r') as f: return parse_sources_data(f.read(), origin=filepath) except IOError as e: raise InvalidData("I/O error reading sources file: %s"%(str(e)), origin=filepath)
[ "def", "parse_sources_file", "(", "filepath", ")", ":", "try", ":", "with", "open", "(", "filepath", ",", "'r'", ")", "as", "f", ":", "return", "parse_sources_data", "(", "f", ".", "read", "(", ")", ",", "origin", "=", "filepath", ")", "except", "IOError", "as", "e", ":", "raise", "InvalidData", "(", "\"I/O error reading sources file: %s\"", "%", "(", "str", "(", "e", ")", ")", ",", "origin", "=", "filepath", ")" ]
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_aarch64/python2.7/dist-packages/rosdep2/sources_list.py#L369-L381
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py3/scipy/signal/signaltools.py
python
_filtfilt_gust
(b, a, x, axis=-1, irlen=None)
return y_opt, x0, x1
Forward-backward IIR filter that uses Gustafsson's method. Apply the IIR filter defined by `(b,a)` to `x` twice, first forward then backward, using Gustafsson's initial conditions [1]_. Let ``y_fb`` be the result of filtering first forward and then backward, and let ``y_bf`` be the result of filtering first backward then forward. Gustafsson's method is to compute initial conditions for the forward pass and the backward pass such that ``y_fb == y_bf``. Parameters ---------- b : scalar or 1-D ndarray Numerator coefficients of the filter. a : scalar or 1-D ndarray Denominator coefficients of the filter. x : ndarray Data to be filtered. axis : int, optional Axis of `x` to be filtered. Default is -1. irlen : int or None, optional The length of the nonnegligible part of the impulse response. If `irlen` is None, or if the length of the signal is less than ``2 * irlen``, then no part of the impulse response is ignored. Returns ------- y : ndarray The filtered data. x0 : ndarray Initial condition for the forward filter. x1 : ndarray Initial condition for the backward filter. Notes ----- Typically the return values `x0` and `x1` are not needed by the caller. The intended use of these return values is in unit tests. References ---------- .. [1] F. Gustaffson. Determining the initial states in forward-backward filtering. Transactions on Signal Processing, 46(4):988-992, 1996.
Forward-backward IIR filter that uses Gustafsson's method.
[ "Forward", "-", "backward", "IIR", "filter", "that", "uses", "Gustafsson", "s", "method", "." ]
def _filtfilt_gust(b, a, x, axis=-1, irlen=None): """Forward-backward IIR filter that uses Gustafsson's method. Apply the IIR filter defined by `(b,a)` to `x` twice, first forward then backward, using Gustafsson's initial conditions [1]_. Let ``y_fb`` be the result of filtering first forward and then backward, and let ``y_bf`` be the result of filtering first backward then forward. Gustafsson's method is to compute initial conditions for the forward pass and the backward pass such that ``y_fb == y_bf``. Parameters ---------- b : scalar or 1-D ndarray Numerator coefficients of the filter. a : scalar or 1-D ndarray Denominator coefficients of the filter. x : ndarray Data to be filtered. axis : int, optional Axis of `x` to be filtered. Default is -1. irlen : int or None, optional The length of the nonnegligible part of the impulse response. If `irlen` is None, or if the length of the signal is less than ``2 * irlen``, then no part of the impulse response is ignored. Returns ------- y : ndarray The filtered data. x0 : ndarray Initial condition for the forward filter. x1 : ndarray Initial condition for the backward filter. Notes ----- Typically the return values `x0` and `x1` are not needed by the caller. The intended use of these return values is in unit tests. References ---------- .. [1] F. Gustaffson. Determining the initial states in forward-backward filtering. Transactions on Signal Processing, 46(4):988-992, 1996. """ # In the comments, "Gustafsson's paper" and [1] refer to the # paper referenced in the docstring. b = np.atleast_1d(b) a = np.atleast_1d(a) order = max(len(b), len(a)) - 1 if order == 0: # The filter is just scalar multiplication, with no state. scale = (b[0] / a[0])**2 y = scale * x return y, np.array([]), np.array([]) if axis != -1 or axis != x.ndim - 1: # Move the axis containing the data to the end. x = np.swapaxes(x, axis, x.ndim - 1) # n is the number of samples in the data to be filtered. n = x.shape[-1] if irlen is None or n <= 2*irlen: m = n else: m = irlen # Create Obs, the observability matrix (called O in the paper). # This matrix can be interpreted as the operator that propagates # an arbitrary initial state to the output, assuming the input is # zero. # In Gustafsson's paper, the forward and backward filters are not # necessarily the same, so he has both O_f and O_b. We use the same # filter in both directions, so we only need O. The same comment # applies to S below. Obs = np.zeros((m, order)) zi = np.zeros(order) zi[0] = 1 Obs[:, 0] = lfilter(b, a, np.zeros(m), zi=zi)[0] for k in range(1, order): Obs[k:, k] = Obs[:-k, 0] # Obsr is O^R (Gustafsson's notation for row-reversed O) Obsr = Obs[::-1] # Create S. S is the matrix that applies the filter to the reversed # propagated initial conditions. That is, # out = S.dot(zi) # is the same as # tmp, _ = lfilter(b, a, zeros(), zi=zi) # Propagate ICs. # out = lfilter(b, a, tmp[::-1]) # Reverse and filter. # Equations (5) & (6) of [1] S = lfilter(b, a, Obs[::-1], axis=0) # Sr is S^R (row-reversed S) Sr = S[::-1] # M is [(S^R - O), (O^R - S)] if m == n: M = np.hstack((Sr - Obs, Obsr - S)) else: # Matrix described in section IV of [1]. M = np.zeros((2*m, 2*order)) M[:m, :order] = Sr - Obs M[m:, order:] = Obsr - S # Naive forward-backward and backward-forward filters. # These have large transients because the filters use zero initial # conditions. y_f = lfilter(b, a, x) y_fb = lfilter(b, a, y_f[..., ::-1])[..., ::-1] y_b = lfilter(b, a, x[..., ::-1])[..., ::-1] y_bf = lfilter(b, a, y_b) delta_y_bf_fb = y_bf - y_fb if m == n: delta = delta_y_bf_fb else: start_m = delta_y_bf_fb[..., :m] end_m = delta_y_bf_fb[..., -m:] delta = np.concatenate((start_m, end_m), axis=-1) # ic_opt holds the "optimal" initial conditions. # The following code computes the result shown in the formula # of the paper between equations (6) and (7). if delta.ndim == 1: ic_opt = linalg.lstsq(M, delta)[0] else: # Reshape delta so it can be used as an array of multiple # right-hand-sides in linalg.lstsq. delta2d = delta.reshape(-1, delta.shape[-1]).T ic_opt0 = linalg.lstsq(M, delta2d)[0].T ic_opt = ic_opt0.reshape(delta.shape[:-1] + (M.shape[-1],)) # Now compute the filtered signal using equation (7) of [1]. # First, form [S^R, O^R] and call it W. if m == n: W = np.hstack((Sr, Obsr)) else: W = np.zeros((2*m, 2*order)) W[:m, :order] = Sr W[m:, order:] = Obsr # Equation (7) of [1] says # Y_fb^opt = Y_fb^0 + W * [x_0^opt; x_{N-1}^opt] # `wic` is (almost) the product on the right. # W has shape (m, 2*order), and ic_opt has shape (..., 2*order), # so we can't use W.dot(ic_opt). Instead, we dot ic_opt with W.T, # so wic has shape (..., m). wic = ic_opt.dot(W.T) # `wic` is "almost" the product of W and the optimal ICs in equation # (7)--if we're using a truncated impulse response (m < n), `wic` # contains only the adjustments required for the ends of the signal. # Here we form y_opt, taking this into account if necessary. y_opt = y_fb if m == n: y_opt += wic else: y_opt[..., :m] += wic[..., :m] y_opt[..., -m:] += wic[..., -m:] x0 = ic_opt[..., :order] x1 = ic_opt[..., -order:] if axis != -1 or axis != x.ndim - 1: # Restore the data axis to its original position. x0 = np.swapaxes(x0, axis, x.ndim - 1) x1 = np.swapaxes(x1, axis, x.ndim - 1) y_opt = np.swapaxes(y_opt, axis, x.ndim - 1) return y_opt, x0, x1
[ "def", "_filtfilt_gust", "(", "b", ",", "a", ",", "x", ",", "axis", "=", "-", "1", ",", "irlen", "=", "None", ")", ":", "# In the comments, \"Gustafsson's paper\" and [1] refer to the", "# paper referenced in the docstring.", "b", "=", "np", ".", "atleast_1d", "(", "b", ")", "a", "=", "np", ".", "atleast_1d", "(", "a", ")", "order", "=", "max", "(", "len", "(", "b", ")", ",", "len", "(", "a", ")", ")", "-", "1", "if", "order", "==", "0", ":", "# The filter is just scalar multiplication, with no state.", "scale", "=", "(", "b", "[", "0", "]", "/", "a", "[", "0", "]", ")", "**", "2", "y", "=", "scale", "*", "x", "return", "y", ",", "np", ".", "array", "(", "[", "]", ")", ",", "np", ".", "array", "(", "[", "]", ")", "if", "axis", "!=", "-", "1", "or", "axis", "!=", "x", ".", "ndim", "-", "1", ":", "# Move the axis containing the data to the end.", "x", "=", "np", ".", "swapaxes", "(", "x", ",", "axis", ",", "x", ".", "ndim", "-", "1", ")", "# n is the number of samples in the data to be filtered.", "n", "=", "x", ".", "shape", "[", "-", "1", "]", "if", "irlen", "is", "None", "or", "n", "<=", "2", "*", "irlen", ":", "m", "=", "n", "else", ":", "m", "=", "irlen", "# Create Obs, the observability matrix (called O in the paper).", "# This matrix can be interpreted as the operator that propagates", "# an arbitrary initial state to the output, assuming the input is", "# zero.", "# In Gustafsson's paper, the forward and backward filters are not", "# necessarily the same, so he has both O_f and O_b. We use the same", "# filter in both directions, so we only need O. The same comment", "# applies to S below.", "Obs", "=", "np", ".", "zeros", "(", "(", "m", ",", "order", ")", ")", "zi", "=", "np", ".", "zeros", "(", "order", ")", "zi", "[", "0", "]", "=", "1", "Obs", "[", ":", ",", "0", "]", "=", "lfilter", "(", "b", ",", "a", ",", "np", ".", "zeros", "(", "m", ")", ",", "zi", "=", "zi", ")", "[", "0", "]", "for", "k", "in", "range", "(", "1", ",", "order", ")", ":", "Obs", "[", "k", ":", ",", "k", "]", "=", "Obs", "[", ":", "-", "k", ",", "0", "]", "# Obsr is O^R (Gustafsson's notation for row-reversed O)", "Obsr", "=", "Obs", "[", ":", ":", "-", "1", "]", "# Create S. S is the matrix that applies the filter to the reversed", "# propagated initial conditions. That is,", "# out = S.dot(zi)", "# is the same as", "# tmp, _ = lfilter(b, a, zeros(), zi=zi) # Propagate ICs.", "# out = lfilter(b, a, tmp[::-1]) # Reverse and filter.", "# Equations (5) & (6) of [1]", "S", "=", "lfilter", "(", "b", ",", "a", ",", "Obs", "[", ":", ":", "-", "1", "]", ",", "axis", "=", "0", ")", "# Sr is S^R (row-reversed S)", "Sr", "=", "S", "[", ":", ":", "-", "1", "]", "# M is [(S^R - O), (O^R - S)]", "if", "m", "==", "n", ":", "M", "=", "np", ".", "hstack", "(", "(", "Sr", "-", "Obs", ",", "Obsr", "-", "S", ")", ")", "else", ":", "# Matrix described in section IV of [1].", "M", "=", "np", ".", "zeros", "(", "(", "2", "*", "m", ",", "2", "*", "order", ")", ")", "M", "[", ":", "m", ",", ":", "order", "]", "=", "Sr", "-", "Obs", "M", "[", "m", ":", ",", "order", ":", "]", "=", "Obsr", "-", "S", "# Naive forward-backward and backward-forward filters.", "# These have large transients because the filters use zero initial", "# conditions.", "y_f", "=", "lfilter", "(", "b", ",", "a", ",", "x", ")", "y_fb", "=", "lfilter", "(", "b", ",", "a", ",", "y_f", "[", "...", ",", ":", ":", "-", "1", "]", ")", "[", "...", ",", ":", ":", "-", "1", "]", "y_b", "=", "lfilter", "(", "b", ",", "a", ",", "x", "[", "...", ",", ":", ":", "-", "1", "]", ")", "[", "...", ",", ":", ":", "-", "1", "]", "y_bf", "=", "lfilter", "(", "b", ",", "a", ",", "y_b", ")", "delta_y_bf_fb", "=", "y_bf", "-", "y_fb", "if", "m", "==", "n", ":", "delta", "=", "delta_y_bf_fb", "else", ":", "start_m", "=", "delta_y_bf_fb", "[", "...", ",", ":", "m", "]", "end_m", "=", "delta_y_bf_fb", "[", "...", ",", "-", "m", ":", "]", "delta", "=", "np", ".", "concatenate", "(", "(", "start_m", ",", "end_m", ")", ",", "axis", "=", "-", "1", ")", "# ic_opt holds the \"optimal\" initial conditions.", "# The following code computes the result shown in the formula", "# of the paper between equations (6) and (7).", "if", "delta", ".", "ndim", "==", "1", ":", "ic_opt", "=", "linalg", ".", "lstsq", "(", "M", ",", "delta", ")", "[", "0", "]", "else", ":", "# Reshape delta so it can be used as an array of multiple", "# right-hand-sides in linalg.lstsq.", "delta2d", "=", "delta", ".", "reshape", "(", "-", "1", ",", "delta", ".", "shape", "[", "-", "1", "]", ")", ".", "T", "ic_opt0", "=", "linalg", ".", "lstsq", "(", "M", ",", "delta2d", ")", "[", "0", "]", ".", "T", "ic_opt", "=", "ic_opt0", ".", "reshape", "(", "delta", ".", "shape", "[", ":", "-", "1", "]", "+", "(", "M", ".", "shape", "[", "-", "1", "]", ",", ")", ")", "# Now compute the filtered signal using equation (7) of [1].", "# First, form [S^R, O^R] and call it W.", "if", "m", "==", "n", ":", "W", "=", "np", ".", "hstack", "(", "(", "Sr", ",", "Obsr", ")", ")", "else", ":", "W", "=", "np", ".", "zeros", "(", "(", "2", "*", "m", ",", "2", "*", "order", ")", ")", "W", "[", ":", "m", ",", ":", "order", "]", "=", "Sr", "W", "[", "m", ":", ",", "order", ":", "]", "=", "Obsr", "# Equation (7) of [1] says", "# Y_fb^opt = Y_fb^0 + W * [x_0^opt; x_{N-1}^opt]", "# `wic` is (almost) the product on the right.", "# W has shape (m, 2*order), and ic_opt has shape (..., 2*order),", "# so we can't use W.dot(ic_opt). Instead, we dot ic_opt with W.T,", "# so wic has shape (..., m).", "wic", "=", "ic_opt", ".", "dot", "(", "W", ".", "T", ")", "# `wic` is \"almost\" the product of W and the optimal ICs in equation", "# (7)--if we're using a truncated impulse response (m < n), `wic`", "# contains only the adjustments required for the ends of the signal.", "# Here we form y_opt, taking this into account if necessary.", "y_opt", "=", "y_fb", "if", "m", "==", "n", ":", "y_opt", "+=", "wic", "else", ":", "y_opt", "[", "...", ",", ":", "m", "]", "+=", "wic", "[", "...", ",", ":", "m", "]", "y_opt", "[", "...", ",", "-", "m", ":", "]", "+=", "wic", "[", "...", ",", "-", "m", ":", "]", "x0", "=", "ic_opt", "[", "...", ",", ":", "order", "]", "x1", "=", "ic_opt", "[", "...", ",", "-", "order", ":", "]", "if", "axis", "!=", "-", "1", "or", "axis", "!=", "x", ".", "ndim", "-", "1", ":", "# Restore the data axis to its original position.", "x0", "=", "np", ".", "swapaxes", "(", "x0", ",", "axis", ",", "x", ".", "ndim", "-", "1", ")", "x1", "=", "np", ".", "swapaxes", "(", "x1", ",", "axis", ",", "x", ".", "ndim", "-", "1", ")", "y_opt", "=", "np", ".", "swapaxes", "(", "y_opt", ",", "axis", ",", "x", ".", "ndim", "-", "1", ")", "return", "y_opt", ",", "x0", ",", "x1" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/signal/signaltools.py#L2792-L2968
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/grid.py
python
GridCellBoolEditor_UseStringValues
(*args, **kwargs)
return _grid.GridCellBoolEditor_UseStringValues(*args, **kwargs)
GridCellBoolEditor_UseStringValues(String valueTrue=OneString, String valueFalse=EmptyString)
GridCellBoolEditor_UseStringValues(String valueTrue=OneString, String valueFalse=EmptyString)
[ "GridCellBoolEditor_UseStringValues", "(", "String", "valueTrue", "=", "OneString", "String", "valueFalse", "=", "EmptyString", ")" ]
def GridCellBoolEditor_UseStringValues(*args, **kwargs): """GridCellBoolEditor_UseStringValues(String valueTrue=OneString, String valueFalse=EmptyString)""" return _grid.GridCellBoolEditor_UseStringValues(*args, **kwargs)
[ "def", "GridCellBoolEditor_UseStringValues", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_grid", ".", "GridCellBoolEditor_UseStringValues", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/grid.py#L473-L475
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/build/waf-1.7.13/lmbrwaflib/lumberyard_modules.py
python
configure_task_generator
(ctx, target, kw)
Helper function to apply default configurations and to set platform/configuration dependent settings * Fork of ConfigureTaskGenerator
Helper function to apply default configurations and to set platform/configuration dependent settings * Fork of ConfigureTaskGenerator
[ "Helper", "function", "to", "apply", "default", "configurations", "and", "to", "set", "platform", "/", "configuration", "dependent", "settings", "*", "Fork", "of", "ConfigureTaskGenerator" ]
def configure_task_generator(ctx, target, kw): """ Helper function to apply default configurations and to set platform/configuration dependent settings * Fork of ConfigureTaskGenerator """ # Ensure we have a name for lookup purposes kw.setdefault('name', target) # Lookup the PlatformConfiguration for the current platform/configuration (if this is a build command) target_platform = [] # Special case: Only non-android launchers can use required gems apply_required_gems = kw.get('use_required_gems', False) if kw.get('is_launcher', False): if apply_required_gems and not ctx.is_android_platform(target_platform): ctx.apply_required_gems_to_context(target, kw) else: if apply_required_gems: ctx.apply_required_gems_to_context(target, kw) # Apply all settings, based on current platform and configuration ApplyConfigOverwrite(ctx, kw) ApplyBuildOptionSettings(ctx, kw) # Load all file lists (including additional settings) file_list = kw['file_list'] for setting in kw.get('additional_settings',[]): for setting_kw in setting: if setting_kw in LEGACY_KEYWORDS: Logs.warn("[WARN] platform/configuration specific keyword '{}' found in 'additional_settings' keyword for " "target'{}' is not supported with any of the Lumberyard* modules. Use the project_settings " "keyword to specify platform/config specific values instead".format(setting_kw, target)) file_list += setting.get('file_list', []) file_list = kw['file_list'] LoadFileLists(ctx, kw, file_list) kw.setdefault('additional_settings', []) LoadAdditionalFileSettings(ctx, kw) apply_uselibs(ctx, target, kw) process_optional_copy_keywords(ctx, target, kw) # Clean out some duplicate kw values to reduce the size for the hash calculation kw['defines'] = clean_duplicates_in_list(kw['defines'], '{} : defines'.format(target)) # Optionally remove any c/cxx flag that may have been inherited by a shared settings file remove_cxxflags = kw.get('remove_cxxflags', None) if remove_cxxflags: cflag_keys = ('cflags', 'cxxflags') for remove_cxxflag in remove_cxxflags: for cflag_key in cflag_keys: kw.setdefault(cflag_key,[]).remove(remove_cxxflag) # Optionally remove any define that may have been inherited by a shared settings file remove_defines = kw.get('remove_defines', None) if remove_defines: for remove_define in remove_defines: kw.setdefault('defines').remove(remove_define)
[ "def", "configure_task_generator", "(", "ctx", ",", "target", ",", "kw", ")", ":", "# Ensure we have a name for lookup purposes", "kw", ".", "setdefault", "(", "'name'", ",", "target", ")", "# Lookup the PlatformConfiguration for the current platform/configuration (if this is a build command)", "target_platform", "=", "[", "]", "# Special case: Only non-android launchers can use required gems", "apply_required_gems", "=", "kw", ".", "get", "(", "'use_required_gems'", ",", "False", ")", "if", "kw", ".", "get", "(", "'is_launcher'", ",", "False", ")", ":", "if", "apply_required_gems", "and", "not", "ctx", ".", "is_android_platform", "(", "target_platform", ")", ":", "ctx", ".", "apply_required_gems_to_context", "(", "target", ",", "kw", ")", "else", ":", "if", "apply_required_gems", ":", "ctx", ".", "apply_required_gems_to_context", "(", "target", ",", "kw", ")", "# Apply all settings, based on current platform and configuration", "ApplyConfigOverwrite", "(", "ctx", ",", "kw", ")", "ApplyBuildOptionSettings", "(", "ctx", ",", "kw", ")", "# Load all file lists (including additional settings)", "file_list", "=", "kw", "[", "'file_list'", "]", "for", "setting", "in", "kw", ".", "get", "(", "'additional_settings'", ",", "[", "]", ")", ":", "for", "setting_kw", "in", "setting", ":", "if", "setting_kw", "in", "LEGACY_KEYWORDS", ":", "Logs", ".", "warn", "(", "\"[WARN] platform/configuration specific keyword '{}' found in 'additional_settings' keyword for \"", "\"target'{}' is not supported with any of the Lumberyard* modules. Use the project_settings \"", "\"keyword to specify platform/config specific values instead\"", ".", "format", "(", "setting_kw", ",", "target", ")", ")", "file_list", "+=", "setting", ".", "get", "(", "'file_list'", ",", "[", "]", ")", "file_list", "=", "kw", "[", "'file_list'", "]", "LoadFileLists", "(", "ctx", ",", "kw", ",", "file_list", ")", "kw", ".", "setdefault", "(", "'additional_settings'", ",", "[", "]", ")", "LoadAdditionalFileSettings", "(", "ctx", ",", "kw", ")", "apply_uselibs", "(", "ctx", ",", "target", ",", "kw", ")", "process_optional_copy_keywords", "(", "ctx", ",", "target", ",", "kw", ")", "# Clean out some duplicate kw values to reduce the size for the hash calculation", "kw", "[", "'defines'", "]", "=", "clean_duplicates_in_list", "(", "kw", "[", "'defines'", "]", ",", "'{} : defines'", ".", "format", "(", "target", ")", ")", "# Optionally remove any c/cxx flag that may have been inherited by a shared settings file", "remove_cxxflags", "=", "kw", ".", "get", "(", "'remove_cxxflags'", ",", "None", ")", "if", "remove_cxxflags", ":", "cflag_keys", "=", "(", "'cflags'", ",", "'cxxflags'", ")", "for", "remove_cxxflag", "in", "remove_cxxflags", ":", "for", "cflag_key", "in", "cflag_keys", ":", "kw", ".", "setdefault", "(", "cflag_key", ",", "[", "]", ")", ".", "remove", "(", "remove_cxxflag", ")", "# Optionally remove any define that may have been inherited by a shared settings file", "remove_defines", "=", "kw", ".", "get", "(", "'remove_defines'", ",", "None", ")", "if", "remove_defines", ":", "for", "remove_define", "in", "remove_defines", ":", "kw", ".", "setdefault", "(", "'defines'", ")", ".", "remove", "(", "remove_define", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/build/waf-1.7.13/lmbrwaflib/lumberyard_modules.py#L318-L382
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/debug/lib/grpc_debug_server.py
python
EventListenerBaseServicer._process_tensor_event_in_chunks
(self, event, tensor_chunks)
Possibly reassemble event chunks. Due to gRPC's message size limit, a large tensor can be encapsulated in multiple Event proto chunks to be sent through the debugger stream. This method keeps track of the chunks that have arrived, reassemble all chunks corresponding to a tensor when they have arrived and return the reassembled Event proto. Args: event: The single Event proto that has arrived. tensor_chunks: A dict used to keep track of the Event protos that have arrived but haven't been reassembled. Returns: If all Event protos corresponding to a tensor have arrived, returns the reassembled Event proto. Otherwise, return None.
Possibly reassemble event chunks.
[ "Possibly", "reassemble", "event", "chunks", "." ]
def _process_tensor_event_in_chunks(self, event, tensor_chunks): """Possibly reassemble event chunks. Due to gRPC's message size limit, a large tensor can be encapsulated in multiple Event proto chunks to be sent through the debugger stream. This method keeps track of the chunks that have arrived, reassemble all chunks corresponding to a tensor when they have arrived and return the reassembled Event proto. Args: event: The single Event proto that has arrived. tensor_chunks: A dict used to keep track of the Event protos that have arrived but haven't been reassembled. Returns: If all Event protos corresponding to a tensor have arrived, returns the reassembled Event proto. Otherwise, return None. """ value = event.summary.value[0] debugger_plugin_metadata = json.loads( compat.as_text(value.metadata.plugin_data.content)) device_name = debugger_plugin_metadata["device"] num_chunks = debugger_plugin_metadata["numChunks"] chunk_index = debugger_plugin_metadata["chunkIndex"] if num_chunks <= 1: return event debug_node_name = value.node_name timestamp = int(event.wall_time) tensor_key = "%s_%s_%d" % (device_name, debug_node_name, timestamp) if tensor_key not in tensor_chunks: tensor_chunks[tensor_key] = [None] * num_chunks chunks = tensor_chunks[tensor_key] if value.tensor.tensor_content: chunks[chunk_index] = value.tensor elif value.tensor.string_val: chunks[chunk_index] = event if None not in chunks: if value.tensor.tensor_content: event.summary.value[0].tensor.tensor_content = b"".join( chunk.tensor_content for chunk in chunks) del tensor_chunks[tensor_key] return event elif value.tensor.string_val: merged_event = chunks[0] for chunk in chunks[1:]: merged_event.summary.value[0].tensor.string_val.extend( list(chunk.summary.value[0].tensor.string_val)) return merged_event
[ "def", "_process_tensor_event_in_chunks", "(", "self", ",", "event", ",", "tensor_chunks", ")", ":", "value", "=", "event", ".", "summary", ".", "value", "[", "0", "]", "debugger_plugin_metadata", "=", "json", ".", "loads", "(", "compat", ".", "as_text", "(", "value", ".", "metadata", ".", "plugin_data", ".", "content", ")", ")", "device_name", "=", "debugger_plugin_metadata", "[", "\"device\"", "]", "num_chunks", "=", "debugger_plugin_metadata", "[", "\"numChunks\"", "]", "chunk_index", "=", "debugger_plugin_metadata", "[", "\"chunkIndex\"", "]", "if", "num_chunks", "<=", "1", ":", "return", "event", "debug_node_name", "=", "value", ".", "node_name", "timestamp", "=", "int", "(", "event", ".", "wall_time", ")", "tensor_key", "=", "\"%s_%s_%d\"", "%", "(", "device_name", ",", "debug_node_name", ",", "timestamp", ")", "if", "tensor_key", "not", "in", "tensor_chunks", ":", "tensor_chunks", "[", "tensor_key", "]", "=", "[", "None", "]", "*", "num_chunks", "chunks", "=", "tensor_chunks", "[", "tensor_key", "]", "if", "value", ".", "tensor", ".", "tensor_content", ":", "chunks", "[", "chunk_index", "]", "=", "value", ".", "tensor", "elif", "value", ".", "tensor", ".", "string_val", ":", "chunks", "[", "chunk_index", "]", "=", "event", "if", "None", "not", "in", "chunks", ":", "if", "value", ".", "tensor", ".", "tensor_content", ":", "event", ".", "summary", ".", "value", "[", "0", "]", ".", "tensor", ".", "tensor_content", "=", "b\"\"", ".", "join", "(", "chunk", ".", "tensor_content", "for", "chunk", "in", "chunks", ")", "del", "tensor_chunks", "[", "tensor_key", "]", "return", "event", "elif", "value", ".", "tensor", ".", "string_val", ":", "merged_event", "=", "chunks", "[", "0", "]", "for", "chunk", "in", "chunks", "[", "1", ":", "]", ":", "merged_event", ".", "summary", ".", "value", "[", "0", "]", ".", "tensor", ".", "string_val", ".", "extend", "(", "list", "(", "chunk", ".", "summary", ".", "value", "[", "0", "]", ".", "tensor", ".", "string_val", ")", ")", "return", "merged_event" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/debug/lib/grpc_debug_server.py#L225-L278
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pkg_resources/_vendor/pyparsing.py
python
ParserElement.addParseAction
( self, *fns, **kwargs )
return self
Add one or more parse actions to expression's list of parse actions. See L{I{setParseAction}<setParseAction>}. See examples in L{I{copy}<copy>}.
[]
def addParseAction( self, *fns, **kwargs ): """ Add one or more parse actions to expression's list of parse actions. See L{I{setParseAction}<setParseAction>}. See examples in L{I{copy}<copy>}. """ self.parseAction += list(map(_trim_arity, list(fns))) self.callDuringTry = self.callDuringTry or kwargs.get("callDuringTry", False) return self
[ "def", "addParseAction", "(", "self", ",", "*", "fns", ",", "*", "*", "kwargs", ")", ":", "self", ".", "parseAction", "+=", "list", "(", "map", "(", "_trim_arity", ",", "list", "(", "fns", ")", ")", ")", "self", ".", "callDuringTry", "=", "self", ".", "callDuringTry", "or", "kwargs", ".", "get", "(", "\"callDuringTry\"", ",", "False", ")", "return", "self" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pkg_resources/_vendor/pyparsing.py#L2575-L2591
google/syzygy
8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5
third_party/numpy/files/numpy/lib/financial.py
python
pmt
(rate, nper, pv, fv=0, when='end')
return -(fv + pv*temp) / fact
Compute the payment against loan principal plus interest. Given: * a present value, `pv` (e.g., an amount borrowed) * a future value, `fv` (e.g., 0) * an interest `rate` compounded once per period, of which there are * `nper` total * and (optional) specification of whether payment is made at the beginning (`when` = {'begin', 1}) or the end (`when` = {'end', 0}) of each period Return: the (fixed) periodic payment. Parameters ---------- rate : array_like Rate of interest (per period) nper : array_like Number of compounding periods pv : array_like Present value fv : array_like (optional) Future value (default = 0) when : {{'begin', 1}, {'end', 0}}, {string, int} When payments are due ('begin' (1) or 'end' (0)) Returns ------- out : ndarray Payment against loan plus interest. If all input is scalar, returns a scalar float. If any input is array_like, returns payment for each input element. If multiple inputs are array_like, they all must have the same shape. Notes ----- The payment is computed by solving the equation:: fv + pv*(1 + rate)**nper + pmt*(1 + rate*when)/rate*((1 + rate)**nper - 1) == 0 or, when ``rate == 0``:: fv + pv + pmt * nper == 0 for ``pmt``. Note that computing a monthly mortgage payment is only one use for this function. For example, pmt returns the periodic deposit one must make to achieve a specified future balance given an initial deposit, a fixed, periodically compounded interest rate, and the total number of periods. References ---------- .. [WRW] Wheeler, D. A., E. Rathke, and R. Weir (Eds.) (2009, May). Open Document Format for Office Applications (OpenDocument)v1.2, Part 2: Recalculated Formula (OpenFormula) Format - Annotated Version, Pre-Draft 12. Organization for the Advancement of Structured Information Standards (OASIS). Billerica, MA, USA. [ODT Document]. Available: http://www.oasis-open.org/committees/documents.php ?wg_abbrev=office-formulaOpenDocument-formula-20090508.odt Examples -------- What is the monthly payment needed to pay off a $200,000 loan in 15 years at an annual interest rate of 7.5%? >>> np.pmt(0.075/12, 12*15, 200000) -1854.0247200054619 In order to pay-off (i.e., have a future-value of 0) the $200,000 obtained today, a monthly payment of $1,854.02 would be required. Note that this example illustrates usage of `fv` having a default value of 0.
Compute the payment against loan principal plus interest.
[ "Compute", "the", "payment", "against", "loan", "principal", "plus", "interest", "." ]
def pmt(rate, nper, pv, fv=0, when='end'): """ Compute the payment against loan principal plus interest. Given: * a present value, `pv` (e.g., an amount borrowed) * a future value, `fv` (e.g., 0) * an interest `rate` compounded once per period, of which there are * `nper` total * and (optional) specification of whether payment is made at the beginning (`when` = {'begin', 1}) or the end (`when` = {'end', 0}) of each period Return: the (fixed) periodic payment. Parameters ---------- rate : array_like Rate of interest (per period) nper : array_like Number of compounding periods pv : array_like Present value fv : array_like (optional) Future value (default = 0) when : {{'begin', 1}, {'end', 0}}, {string, int} When payments are due ('begin' (1) or 'end' (0)) Returns ------- out : ndarray Payment against loan plus interest. If all input is scalar, returns a scalar float. If any input is array_like, returns payment for each input element. If multiple inputs are array_like, they all must have the same shape. Notes ----- The payment is computed by solving the equation:: fv + pv*(1 + rate)**nper + pmt*(1 + rate*when)/rate*((1 + rate)**nper - 1) == 0 or, when ``rate == 0``:: fv + pv + pmt * nper == 0 for ``pmt``. Note that computing a monthly mortgage payment is only one use for this function. For example, pmt returns the periodic deposit one must make to achieve a specified future balance given an initial deposit, a fixed, periodically compounded interest rate, and the total number of periods. References ---------- .. [WRW] Wheeler, D. A., E. Rathke, and R. Weir (Eds.) (2009, May). Open Document Format for Office Applications (OpenDocument)v1.2, Part 2: Recalculated Formula (OpenFormula) Format - Annotated Version, Pre-Draft 12. Organization for the Advancement of Structured Information Standards (OASIS). Billerica, MA, USA. [ODT Document]. Available: http://www.oasis-open.org/committees/documents.php ?wg_abbrev=office-formulaOpenDocument-formula-20090508.odt Examples -------- What is the monthly payment needed to pay off a $200,000 loan in 15 years at an annual interest rate of 7.5%? >>> np.pmt(0.075/12, 12*15, 200000) -1854.0247200054619 In order to pay-off (i.e., have a future-value of 0) the $200,000 obtained today, a monthly payment of $1,854.02 would be required. Note that this example illustrates usage of `fv` having a default value of 0. """ when = _convert_when(when) rate, nper, pv, fv, when = map(np.asarray, [rate, nper, pv, fv, when]) temp = (1+rate)**nper miter = np.broadcast(rate, nper, pv, fv, when) zer = np.zeros(miter.shape) fact = np.where(rate==zer, nper+zer, (1+rate*when)*(temp-1)/rate+zer) return -(fv + pv*temp) / fact
[ "def", "pmt", "(", "rate", ",", "nper", ",", "pv", ",", "fv", "=", "0", ",", "when", "=", "'end'", ")", ":", "when", "=", "_convert_when", "(", "when", ")", "rate", ",", "nper", ",", "pv", ",", "fv", ",", "when", "=", "map", "(", "np", ".", "asarray", ",", "[", "rate", ",", "nper", ",", "pv", ",", "fv", ",", "when", "]", ")", "temp", "=", "(", "1", "+", "rate", ")", "**", "nper", "miter", "=", "np", ".", "broadcast", "(", "rate", ",", "nper", ",", "pv", ",", "fv", ",", "when", ")", "zer", "=", "np", ".", "zeros", "(", "miter", ".", "shape", ")", "fact", "=", "np", ".", "where", "(", "rate", "==", "zer", ",", "nper", "+", "zer", ",", "(", "1", "+", "rate", "*", "when", ")", "*", "(", "temp", "-", "1", ")", "/", "rate", "+", "zer", ")", "return", "-", "(", "fv", "+", "pv", "*", "temp", ")", "/", "fact" ]
https://github.com/google/syzygy/blob/8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5/third_party/numpy/files/numpy/lib/financial.py#L116-L205
zju3dv/clean-pvnet
5870c509e3cc205e1bb28910a7b1a9a3c8add9a8
lib/utils/data_utils.py
python
draw_heatmap_np
(hm, point, box_size)
return hm
point: [x, y]
point: [x, y]
[ "point", ":", "[", "x", "y", "]" ]
def draw_heatmap_np(hm, point, box_size): """point: [x, y]""" # radius = gaussian_radius(box_size) radius = box_size[0] radius = max(0, int(radius)) ct_int = np.array(point, dtype=np.int32) draw_umich_gaussian(hm, ct_int, radius) return hm
[ "def", "draw_heatmap_np", "(", "hm", ",", "point", ",", "box_size", ")", ":", "# radius = gaussian_radius(box_size)", "radius", "=", "box_size", "[", "0", "]", "radius", "=", "max", "(", "0", ",", "int", "(", "radius", ")", ")", "ct_int", "=", "np", ".", "array", "(", "point", ",", "dtype", "=", "np", ".", "int32", ")", "draw_umich_gaussian", "(", "hm", ",", "ct_int", ",", "radius", ")", "return", "hm" ]
https://github.com/zju3dv/clean-pvnet/blob/5870c509e3cc205e1bb28910a7b1a9a3c8add9a8/lib/utils/data_utils.py#L86-L93
epiqc/ScaffCC
66a79944ee4cd116b27bc1a69137276885461db8
clang/tools/scan-build-py/libscanbuild/report.py
python
chop
(prefix, filename)
return filename if not len(prefix) else os.path.relpath(filename, prefix)
Create 'filename' from '/prefix/filename'
Create 'filename' from '/prefix/filename'
[ "Create", "filename", "from", "/", "prefix", "/", "filename" ]
def chop(prefix, filename): """ Create 'filename' from '/prefix/filename' """ return filename if not len(prefix) else os.path.relpath(filename, prefix)
[ "def", "chop", "(", "prefix", ",", "filename", ")", ":", "return", "filename", "if", "not", "len", "(", "prefix", ")", "else", "os", ".", "path", ".", "relpath", "(", "filename", ",", "prefix", ")" ]
https://github.com/epiqc/ScaffCC/blob/66a79944ee4cd116b27bc1a69137276885461db8/clang/tools/scan-build-py/libscanbuild/report.py#L442-L445
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/python2_version/klampt/model/collide.py
python
WorldCollider.isCollisionEnabled
(self,obj_or_pair)
Returns true if the object or pair of objects are considered for collision. Args: obj_or_pair: either a single body (RobotModelLink, RigidObjectModel, TerrainModel) in the world, or a pair of bodies. In the former case, True is returned if the body is checked with anything.
Returns true if the object or pair of objects are considered for collision.
[ "Returns", "true", "if", "the", "object", "or", "pair", "of", "objects", "are", "considered", "for", "collision", "." ]
def isCollisionEnabled(self,obj_or_pair): """Returns true if the object or pair of objects are considered for collision. Args: obj_or_pair: either a single body (RobotModelLink, RigidObjectModel, TerrainModel) in the world, or a pair of bodies. In the former case, True is returned if the body is checked with anything. """ if hasattr(obj_or_pair,'__iter__'): (a,b) = obj_or_pair ageom = self._getGeomIndex(a) bgeom = self._getGeomIndex(b) if ageom is None or bgeom is None: return False return ageom in self.mask[bgeom] or bgeom in self.mask[ageom] else: geom = self._getGeomIndex(obj_or_pair) if geom is None: return False return len(self.mask[geom]) > 0
[ "def", "isCollisionEnabled", "(", "self", ",", "obj_or_pair", ")", ":", "if", "hasattr", "(", "obj_or_pair", ",", "'__iter__'", ")", ":", "(", "a", ",", "b", ")", "=", "obj_or_pair", "ageom", "=", "self", ".", "_getGeomIndex", "(", "a", ")", "bgeom", "=", "self", ".", "_getGeomIndex", "(", "b", ")", "if", "ageom", "is", "None", "or", "bgeom", "is", "None", ":", "return", "False", "return", "ageom", "in", "self", ".", "mask", "[", "bgeom", "]", "or", "bgeom", "in", "self", ".", "mask", "[", "ageom", "]", "else", ":", "geom", "=", "self", ".", "_getGeomIndex", "(", "obj_or_pair", ")", "if", "geom", "is", "None", ":", "return", "False", "return", "len", "(", "self", ".", "mask", "[", "geom", "]", ")", ">", "0" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/model/collide.py#L359-L380
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/plugins/Launch/launch/handlers.py
python
_StyleError
(stc, start, txt, regex)
return found_err, more
Style Error message groups @param stc: OutputBuffer reference @param start: start of text just added to buffer @param txt: text that was just added @param regex: regular expression object for matching the errors @return: (bool errfound, bool more)
Style Error message groups @param stc: OutputBuffer reference @param start: start of text just added to buffer @param txt: text that was just added @param regex: regular expression object for matching the errors @return: (bool errfound, bool more)
[ "Style", "Error", "message", "groups", "@param", "stc", ":", "OutputBuffer", "reference", "@param", "start", ":", "start", "of", "text", "just", "added", "to", "buffer", "@param", "txt", ":", "text", "that", "was", "just", "added", "@param", "regex", ":", "regular", "expression", "object", "for", "matching", "the", "errors", "@return", ":", "(", "bool", "errfound", "bool", "more", ")" ]
def _StyleError(stc, start, txt, regex): """Style Error message groups @param stc: OutputBuffer reference @param start: start of text just added to buffer @param txt: text that was just added @param regex: regular expression object for matching the errors @return: (bool errfound, bool more) """ found_err = False more = False sty_e = start for group in regex.finditer(txt): sty_s = start + group.start() sty_e = start + group.end() stc.StartStyling(sty_s, 0xff) stc.SetStyling(sty_e - sty_s, eclib.OPB_STYLE_ERROR) found_err = True if sty_e != start + len(txt): more = True return found_err, more
[ "def", "_StyleError", "(", "stc", ",", "start", ",", "txt", ",", "regex", ")", ":", "found_err", "=", "False", "more", "=", "False", "sty_e", "=", "start", "for", "group", "in", "regex", ".", "finditer", "(", "txt", ")", ":", "sty_s", "=", "start", "+", "group", ".", "start", "(", ")", "sty_e", "=", "start", "+", "group", ".", "end", "(", ")", "stc", ".", "StartStyling", "(", "sty_s", ",", "0xff", ")", "stc", ".", "SetStyling", "(", "sty_e", "-", "sty_s", ",", "eclib", ".", "OPB_STYLE_ERROR", ")", "found_err", "=", "True", "if", "sty_e", "!=", "start", "+", "len", "(", "txt", ")", ":", "more", "=", "True", "return", "found_err", ",", "more" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/plugins/Launch/launch/handlers.py#L919-L941
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqt/mantidqt/widgets/plotconfigdialog/presenter.py
python
PlotConfigDialogPresenter.apply_properties
(self)
Attempts to apply properties. Returns a bool denoting whether there was an error drawing the canvas drawn
Attempts to apply properties. Returns a bool denoting whether there was an error drawing the canvas drawn
[ "Attempts", "to", "apply", "properties", ".", "Returns", "a", "bool", "denoting", "whether", "there", "was", "an", "error", "drawing", "the", "canvas", "drawn" ]
def apply_properties(self): """Attempts to apply properties. Returns a bool denoting whether there was an error drawing the canvas drawn""" for tab in reversed(self.tab_widget_presenters): if tab: tab.apply_properties() try: self.fig.canvas.draw() except Exception as exception: self.error_callback(str(exception)) return for tab in reversed(self.tab_widget_presenters): if tab == self.tab_widget_presenters[0]: # Do not call update view on the legend tab because the legend config # does not depend on the curves or axes - it only changes how the legend # is displayed (e.g. legend fonts, border color, etc.) continue if tab: tab.update_view() self.success_callback()
[ "def", "apply_properties", "(", "self", ")", ":", "for", "tab", "in", "reversed", "(", "self", ".", "tab_widget_presenters", ")", ":", "if", "tab", ":", "tab", ".", "apply_properties", "(", ")", "try", ":", "self", ".", "fig", ".", "canvas", ".", "draw", "(", ")", "except", "Exception", "as", "exception", ":", "self", ".", "error_callback", "(", "str", "(", "exception", ")", ")", "return", "for", "tab", "in", "reversed", "(", "self", ".", "tab_widget_presenters", ")", ":", "if", "tab", "==", "self", ".", "tab_widget_presenters", "[", "0", "]", ":", "# Do not call update view on the legend tab because the legend config", "# does not depend on the curves or axes - it only changes how the legend", "# is displayed (e.g. legend fonts, border color, etc.)", "continue", "if", "tab", ":", "tab", ".", "update_view", "(", ")", "self", ".", "success_callback", "(", ")" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqt/mantidqt/widgets/plotconfigdialog/presenter.py#L72-L93
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/corrections_tab_widget/background_corrections_view.py
python
BackgroundCorrectionsView._format_selection
(self)
Formats the selected cell to have the expected number of decimal places.
Formats the selected cell to have the expected number of decimal places.
[ "Formats", "the", "selected", "cell", "to", "have", "the", "expected", "number", "of", "decimal", "places", "." ]
def _format_selection(self) -> None: """Formats the selected cell to have the expected number of decimal places.""" if self._selected_row is not None and self._selected_column is not None and self._selected_column != USE_RAW_COLUMN_INDEX: value = float(self.correction_options_table.item(self._selected_row, self._selected_column).text()) self._set_selected_value(value)
[ "def", "_format_selection", "(", "self", ")", "->", "None", ":", "if", "self", ".", "_selected_row", "is", "not", "None", "and", "self", ".", "_selected_column", "is", "not", "None", "and", "self", ".", "_selected_column", "!=", "USE_RAW_COLUMN_INDEX", ":", "value", "=", "float", "(", "self", ".", "correction_options_table", ".", "item", "(", "self", ".", "_selected_row", ",", "self", ".", "_selected_column", ")", ".", "text", "(", ")", ")", "self", ".", "_set_selected_value", "(", "value", ")" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/corrections_tab_widget/background_corrections_view.py#L387-L391
turi-code/SFrame
796b9bdfb2fa1b881d82080754643c7e68629cd2
oss_src/unity/python/sframe/data_structures/sframe.py
python
SFrame.export_csv
(self, filename, delimiter=',', line_terminator='\n', header=True, quote_level=csv.QUOTE_NONNUMERIC, double_quote=True, escape_char='\\', quote_char='\"', na_rep='', file_header='', file_footer='', line_prefix='', _no_prefix_on_first_value=False, **kwargs)
Writes an SFrame to a CSV file. Parameters ---------- filename : string The location to save the CSV. delimiter : string, optional This describes the delimiter used for writing csv files. line_terminator: string, optional The newline character header : bool, optional If true, the column names are emitted as a header. quote_level: csv.QUOTE_ALL | csv.QUOTE_NONE | csv.QUOTE_NONNUMERIC, optional The quoting level. If csv.QUOTE_ALL, every field is quoted. if csv.quote_NONE, no field is quoted. If csv.QUOTE_NONNUMERIC, only non-numeric fileds are quoted. csv.QUOTE_MINIMAL is interpreted as csv.QUOTE_NONNUMERIC. double_quote : bool, optional If True, quotes are escaped as two consecutive quotes escape_char : string, optional Character which begins a C escape sequence quote_char: string, optional Character used to quote fields na_rep: string, optional The value used to denote a missing value. file_header: string, optional A string printed to the start of the file file_footer: string, optional A string printed to the end of the file line_prefix: string, optional A string printed at the start of each value line
Writes an SFrame to a CSV file.
[ "Writes", "an", "SFrame", "to", "a", "CSV", "file", "." ]
def export_csv(self, filename, delimiter=',', line_terminator='\n', header=True, quote_level=csv.QUOTE_NONNUMERIC, double_quote=True, escape_char='\\', quote_char='\"', na_rep='', file_header='', file_footer='', line_prefix='', _no_prefix_on_first_value=False, **kwargs): """ Writes an SFrame to a CSV file. Parameters ---------- filename : string The location to save the CSV. delimiter : string, optional This describes the delimiter used for writing csv files. line_terminator: string, optional The newline character header : bool, optional If true, the column names are emitted as a header. quote_level: csv.QUOTE_ALL | csv.QUOTE_NONE | csv.QUOTE_NONNUMERIC, optional The quoting level. If csv.QUOTE_ALL, every field is quoted. if csv.quote_NONE, no field is quoted. If csv.QUOTE_NONNUMERIC, only non-numeric fileds are quoted. csv.QUOTE_MINIMAL is interpreted as csv.QUOTE_NONNUMERIC. double_quote : bool, optional If True, quotes are escaped as two consecutive quotes escape_char : string, optional Character which begins a C escape sequence quote_char: string, optional Character used to quote fields na_rep: string, optional The value used to denote a missing value. file_header: string, optional A string printed to the start of the file file_footer: string, optional A string printed to the end of the file line_prefix: string, optional A string printed at the start of each value line """ # Pandas argument compatibility if "sep" in kwargs: delimiter = kwargs['sep'] del kwargs['sep'] if "quotechar" in kwargs: quote_char = kwargs['quotechar'] del kwargs['quotechar'] if "doublequote" in kwargs: double_quote = kwargs['doublequote'] del kwargs['doublequote'] if "lineterminator" in kwargs: line_terminator = kwargs['lineterminator'] del kwargs['lineterminator'] if len(kwargs) > 0: raise TypeError("Unexpected keyword arguments " + str(list(kwargs.keys()))) write_csv_options = {} write_csv_options['delimiter'] = delimiter write_csv_options['escape_char'] = escape_char write_csv_options['double_quote'] = double_quote write_csv_options['quote_char'] = quote_char if quote_level == csv.QUOTE_MINIMAL: write_csv_options['quote_level'] = 0 elif quote_level == csv.QUOTE_ALL: write_csv_options['quote_level'] = 1 elif quote_level == csv.QUOTE_NONNUMERIC: write_csv_options['quote_level'] = 2 elif quote_level == csv.QUOTE_NONE: write_csv_options['quote_level'] = 3 write_csv_options['header'] = header write_csv_options['line_terminator'] = line_terminator write_csv_options['na_value'] = na_rep write_csv_options['file_header'] = file_header write_csv_options['file_footer'] = file_footer write_csv_options['line_prefix'] = line_prefix # undocumented option. Disables line prefix on the first value line write_csv_options['_no_prefix_on_first_value'] = _no_prefix_on_first_value url = _make_internal_url(filename) self.__proxy__.save_as_csv(url, write_csv_options)
[ "def", "export_csv", "(", "self", ",", "filename", ",", "delimiter", "=", "','", ",", "line_terminator", "=", "'\\n'", ",", "header", "=", "True", ",", "quote_level", "=", "csv", ".", "QUOTE_NONNUMERIC", ",", "double_quote", "=", "True", ",", "escape_char", "=", "'\\\\'", ",", "quote_char", "=", "'\\\"'", ",", "na_rep", "=", "''", ",", "file_header", "=", "''", ",", "file_footer", "=", "''", ",", "line_prefix", "=", "''", ",", "_no_prefix_on_first_value", "=", "False", ",", "*", "*", "kwargs", ")", ":", "# Pandas argument compatibility", "if", "\"sep\"", "in", "kwargs", ":", "delimiter", "=", "kwargs", "[", "'sep'", "]", "del", "kwargs", "[", "'sep'", "]", "if", "\"quotechar\"", "in", "kwargs", ":", "quote_char", "=", "kwargs", "[", "'quotechar'", "]", "del", "kwargs", "[", "'quotechar'", "]", "if", "\"doublequote\"", "in", "kwargs", ":", "double_quote", "=", "kwargs", "[", "'doublequote'", "]", "del", "kwargs", "[", "'doublequote'", "]", "if", "\"lineterminator\"", "in", "kwargs", ":", "line_terminator", "=", "kwargs", "[", "'lineterminator'", "]", "del", "kwargs", "[", "'lineterminator'", "]", "if", "len", "(", "kwargs", ")", ">", "0", ":", "raise", "TypeError", "(", "\"Unexpected keyword arguments \"", "+", "str", "(", "list", "(", "kwargs", ".", "keys", "(", ")", ")", ")", ")", "write_csv_options", "=", "{", "}", "write_csv_options", "[", "'delimiter'", "]", "=", "delimiter", "write_csv_options", "[", "'escape_char'", "]", "=", "escape_char", "write_csv_options", "[", "'double_quote'", "]", "=", "double_quote", "write_csv_options", "[", "'quote_char'", "]", "=", "quote_char", "if", "quote_level", "==", "csv", ".", "QUOTE_MINIMAL", ":", "write_csv_options", "[", "'quote_level'", "]", "=", "0", "elif", "quote_level", "==", "csv", ".", "QUOTE_ALL", ":", "write_csv_options", "[", "'quote_level'", "]", "=", "1", "elif", "quote_level", "==", "csv", ".", "QUOTE_NONNUMERIC", ":", "write_csv_options", "[", "'quote_level'", "]", "=", "2", "elif", "quote_level", "==", "csv", ".", "QUOTE_NONE", ":", "write_csv_options", "[", "'quote_level'", "]", "=", "3", "write_csv_options", "[", "'header'", "]", "=", "header", "write_csv_options", "[", "'line_terminator'", "]", "=", "line_terminator", "write_csv_options", "[", "'na_value'", "]", "=", "na_rep", "write_csv_options", "[", "'file_header'", "]", "=", "file_header", "write_csv_options", "[", "'file_footer'", "]", "=", "file_footer", "write_csv_options", "[", "'line_prefix'", "]", "=", "line_prefix", "# undocumented option. Disables line prefix on the first value line", "write_csv_options", "[", "'_no_prefix_on_first_value'", "]", "=", "_no_prefix_on_first_value", "url", "=", "_make_internal_url", "(", "filename", ")", "self", ".", "__proxy__", ".", "save_as_csv", "(", "url", ",", "write_csv_options", ")" ]
https://github.com/turi-code/SFrame/blob/796b9bdfb2fa1b881d82080754643c7e68629cd2/oss_src/unity/python/sframe/data_structures/sframe.py#L3369-L3458
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/ops/array_ops.py
python
size_internal
(input, name=None, optimize=True, out_type=dtypes.int32)
Returns the size of a tensor. Args: input: A `Tensor` or `SparseTensor`. name: A name for the operation (optional). optimize: if true, encode the size as a constant when possible. out_type: (Optional) The specified non-quantized numeric output type of the operation. Defaults to `tf.int32`. Returns: A `Tensor` of type `out_type`. Defaults to `tf.int32`.
Returns the size of a tensor.
[ "Returns", "the", "size", "of", "a", "tensor", "." ]
def size_internal(input, name=None, optimize=True, out_type=dtypes.int32): # pylint: disable=redefined-builtin,protected-access """Returns the size of a tensor. Args: input: A `Tensor` or `SparseTensor`. name: A name for the operation (optional). optimize: if true, encode the size as a constant when possible. out_type: (Optional) The specified non-quantized numeric output type of the operation. Defaults to `tf.int32`. Returns: A `Tensor` of type `out_type`. Defaults to `tf.int32`. """ if (context.executing_eagerly() and not hasattr(input, "graph") and not isinstance( input, (sparse_tensor.SparseTensor, sparse_tensor.SparseTensorValue))): input = ops.convert_to_tensor(input) np_out_type = out_type.as_numpy_dtype num_elements = np.prod(input._shape_tuple(), dtype=np_out_type) # pylint: disable=protected-access return ops.convert_to_tensor(num_elements, dtype=out_type) with ops.name_scope(name, "Size", [input]) as name: if isinstance( input, (sparse_tensor.SparseTensor, sparse_tensor.SparseTensorValue)): return gen_math_ops.prod( gen_math_ops.cast(input.dense_shape, out_type), 0, name=name) else: input = ops.convert_to_tensor(input) input_shape = input.get_shape() if optimize: if input_shape.is_fully_defined(): return constant(input_shape.num_elements(), out_type, name=name) if input_shape.dims and any(dim == 0 for dim in input_shape.dims): return constant(0, out_type, name=name) return gen_array_ops.size(input, name=name, out_type=out_type)
[ "def", "size_internal", "(", "input", ",", "name", "=", "None", ",", "optimize", "=", "True", ",", "out_type", "=", "dtypes", ".", "int32", ")", ":", "# pylint: disable=redefined-builtin,protected-access", "if", "(", "context", ".", "executing_eagerly", "(", ")", "and", "not", "hasattr", "(", "input", ",", "\"graph\"", ")", "and", "not", "isinstance", "(", "input", ",", "(", "sparse_tensor", ".", "SparseTensor", ",", "sparse_tensor", ".", "SparseTensorValue", ")", ")", ")", ":", "input", "=", "ops", ".", "convert_to_tensor", "(", "input", ")", "np_out_type", "=", "out_type", ".", "as_numpy_dtype", "num_elements", "=", "np", ".", "prod", "(", "input", ".", "_shape_tuple", "(", ")", ",", "dtype", "=", "np_out_type", ")", "# pylint: disable=protected-access", "return", "ops", ".", "convert_to_tensor", "(", "num_elements", ",", "dtype", "=", "out_type", ")", "with", "ops", ".", "name_scope", "(", "name", ",", "\"Size\"", ",", "[", "input", "]", ")", "as", "name", ":", "if", "isinstance", "(", "input", ",", "(", "sparse_tensor", ".", "SparseTensor", ",", "sparse_tensor", ".", "SparseTensorValue", ")", ")", ":", "return", "gen_math_ops", ".", "prod", "(", "gen_math_ops", ".", "cast", "(", "input", ".", "dense_shape", ",", "out_type", ")", ",", "0", ",", "name", "=", "name", ")", "else", ":", "input", "=", "ops", ".", "convert_to_tensor", "(", "input", ")", "input_shape", "=", "input", ".", "get_shape", "(", ")", "if", "optimize", ":", "if", "input_shape", ".", "is_fully_defined", "(", ")", ":", "return", "constant", "(", "input_shape", ".", "num_elements", "(", ")", ",", "out_type", ",", "name", "=", "name", ")", "if", "input_shape", ".", "dims", "and", "any", "(", "dim", "==", "0", "for", "dim", "in", "input_shape", ".", "dims", ")", ":", "return", "constant", "(", "0", ",", "out_type", ",", "name", "=", "name", ")", "return", "gen_array_ops", ".", "size", "(", "input", ",", "name", "=", "name", ",", "out_type", "=", "out_type", ")" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/array_ops.py#L787-L822
ablab/spades
3a754192b88540524ce6fb69eef5ea9273a38465
assembler/ext/src/python_libs/joblib3/pool.py
python
has_shareable_memory
(a)
return _get_backing_memmap(a) is not None
Return True if a is backed by some mmap buffer directly or not
Return True if a is backed by some mmap buffer directly or not
[ "Return", "True", "if", "a", "is", "backed", "by", "some", "mmap", "buffer", "directly", "or", "not" ]
def has_shareable_memory(a): """Return True if a is backed by some mmap buffer directly or not""" return _get_backing_memmap(a) is not None
[ "def", "has_shareable_memory", "(", "a", ")", ":", "return", "_get_backing_memmap", "(", "a", ")", "is", "not", "None" ]
https://github.com/ablab/spades/blob/3a754192b88540524ce6fb69eef5ea9273a38465/assembler/ext/src/python_libs/joblib3/pool.py#L88-L90
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_core.py
python
IndividualLayoutConstraint.LeftOf
(*args, **kwargs)
return _core_.IndividualLayoutConstraint_LeftOf(*args, **kwargs)
LeftOf(self, Window sibling, int marg=0) Constrains this edge to be to the left of the given window, with an optional margin. Implicitly, this is relative to the left edge of the other window.
LeftOf(self, Window sibling, int marg=0)
[ "LeftOf", "(", "self", "Window", "sibling", "int", "marg", "=", "0", ")" ]
def LeftOf(*args, **kwargs): """ LeftOf(self, Window sibling, int marg=0) Constrains this edge to be to the left of the given window, with an optional margin. Implicitly, this is relative to the left edge of the other window. """ return _core_.IndividualLayoutConstraint_LeftOf(*args, **kwargs)
[ "def", "LeftOf", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "IndividualLayoutConstraint_LeftOf", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L16136-L16144
nasa/fprime
595cf3682d8365943d86c1a6fe7c78f0a116acf0
Autocoders/Python/src/fprime_ac/generators/DictBody.py
python
DictBody.getObj
(self)
return self.__obj
Return the object to the visitor.
Return the object to the visitor.
[ "Return", "the", "object", "to", "the", "visitor", "." ]
def getObj(self): """ Return the object to the visitor. """ return self.__obj
[ "def", "getObj", "(", "self", ")", ":", "return", "self", ".", "__obj" ]
https://github.com/nasa/fprime/blob/595cf3682d8365943d86c1a6fe7c78f0a116acf0/Autocoders/Python/src/fprime_ac/generators/DictBody.py#L101-L105
thalium/icebox
99d147d5b9269222225443ce171b4fd46d8985d4
third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py
python
uCSIsCJKRadicalsSupplement
(code)
return ret
Check whether the character is part of CJKRadicalsSupplement UCS Block
Check whether the character is part of CJKRadicalsSupplement UCS Block
[ "Check", "whether", "the", "character", "is", "part", "of", "CJKRadicalsSupplement", "UCS", "Block" ]
def uCSIsCJKRadicalsSupplement(code): """Check whether the character is part of CJKRadicalsSupplement UCS Block """ ret = libxml2mod.xmlUCSIsCJKRadicalsSupplement(code) return ret
[ "def", "uCSIsCJKRadicalsSupplement", "(", "code", ")", ":", "ret", "=", "libxml2mod", ".", "xmlUCSIsCJKRadicalsSupplement", "(", "code", ")", "return", "ret" ]
https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py#L1423-L1427
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
current/tools/inspector_protocol/jinja2/environment.py
python
_environment_sanity_check
(environment)
return environment
Perform a sanity check on the environment.
Perform a sanity check on the environment.
[ "Perform", "a", "sanity", "check", "on", "the", "environment", "." ]
def _environment_sanity_check(environment): """Perform a sanity check on the environment.""" assert issubclass(environment.undefined, Undefined), 'undefined must ' \ 'be a subclass of undefined because filters depend on it.' assert environment.block_start_string != \ environment.variable_start_string != \ environment.comment_start_string, 'block, variable and comment ' \ 'start strings must be different' assert environment.newline_sequence in ('\r', '\r\n', '\n'), \ 'newline_sequence set to unknown line ending string.' return environment
[ "def", "_environment_sanity_check", "(", "environment", ")", ":", "assert", "issubclass", "(", "environment", ".", "undefined", ",", "Undefined", ")", ",", "'undefined must '", "'be a subclass of undefined because filters depend on it.'", "assert", "environment", ".", "block_start_string", "!=", "environment", ".", "variable_start_string", "!=", "environment", ".", "comment_start_string", ",", "'block, variable and comment '", "'start strings must be different'", "assert", "environment", ".", "newline_sequence", "in", "(", "'\\r'", ",", "'\\r\\n'", ",", "'\\n'", ")", ",", "'newline_sequence set to unknown line ending string.'", "return", "environment" ]
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/current/tools/inspector_protocol/jinja2/environment.py#L100-L110
neopenx/Dragon
0e639a7319035ddc81918bd3df059230436ee0a1
Dragon/python/dragon/core/tensor.py
python
Tensor.copy
(self)
return new_tensor
Return a Tensor with same content. [**Theano Style**] Returns ------- Tensor The copy. See Also -------- `ops.Copy(*args, **kwargs)`_ - How to copy A to B.
Return a Tensor with same content. [**Theano Style**]
[ "Return", "a", "Tensor", "with", "same", "content", ".", "[", "**", "Theano", "Style", "**", "]" ]
def copy(self): """Return a Tensor with same content. [**Theano Style**] Returns ------- Tensor The copy. See Also -------- `ops.Copy(*args, **kwargs)`_ - How to copy A to B. """ new_tensor = Tensor(self.name + '_copy') arguments = {'inputs': self, 'existing_outputs': new_tensor} self.CreateOperator(nout=1, op_type='Copy', **arguments) if self.shape is not None: new_tensor.shape = self.shape[:] return new_tensor
[ "def", "copy", "(", "self", ")", ":", "new_tensor", "=", "Tensor", "(", "self", ".", "name", "+", "'_copy'", ")", "arguments", "=", "{", "'inputs'", ":", "self", ",", "'existing_outputs'", ":", "new_tensor", "}", "self", ".", "CreateOperator", "(", "nout", "=", "1", ",", "op_type", "=", "'Copy'", ",", "*", "*", "arguments", ")", "if", "self", ".", "shape", "is", "not", "None", ":", "new_tensor", ".", "shape", "=", "self", ".", "shape", "[", ":", "]", "return", "new_tensor" ]
https://github.com/neopenx/Dragon/blob/0e639a7319035ddc81918bd3df059230436ee0a1/Dragon/python/dragon/core/tensor.py#L729-L750
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
src/external/coremltools_wrap/coremltools/coremltools/models/neural_network/flexible_shape_utils.py
python
set_multiarray_ndshape_range
(spec, feature_name, lower_bounds, upper_bounds)
Annotate an input or output MLMultiArray feature in a Neural Network spec to accommodate a range of shapes. This is different from "update_multiarray_shape_range", which works with rank 5 SBCHW mapping. :param spec: MLModel The MLModel spec containing the feature :param feature_name: str The name of the feature for which to add shape range information. If the feature is not found in the input or output descriptions then an exception is thrown :param lower_bounds: List[int] list of integers specifying the lower bounds of each dimension. Length must be same as the rank (length of shape) of the feature_name. :param upper_bounds: List[int] list of integers specifying the upper bounds of each dimension. -1 corresponds to unbounded range. Length must be same as the rank (length of shape) of the feature_name. Examples -------- .. sourcecode:: python >>> import coremltools >>> from coremltools.models.neural_network import flexible_shape_utils >>> spec = coremltools.utils.load_spec('mymodel.mlmodel') >>> # say, the default shape of "my_multiarray_featurename" is (2,3) >>> flexible_shape_utils.set_multiarray_ndshape_range(spec, feature_name='my_multiarray_featurename', lower_bounds=[1,2], upper_bounds=[10,-1]) :return: None. The spec is updated
Annotate an input or output MLMultiArray feature in a Neural Network spec to accommodate a range of shapes. This is different from "update_multiarray_shape_range", which works with rank 5 SBCHW mapping.
[ "Annotate", "an", "input", "or", "output", "MLMultiArray", "feature", "in", "a", "Neural", "Network", "spec", "to", "accommodate", "a", "range", "of", "shapes", ".", "This", "is", "different", "from", "update_multiarray_shape_range", "which", "works", "with", "rank", "5", "SBCHW", "mapping", "." ]
def set_multiarray_ndshape_range(spec, feature_name, lower_bounds, upper_bounds): """ Annotate an input or output MLMultiArray feature in a Neural Network spec to accommodate a range of shapes. This is different from "update_multiarray_shape_range", which works with rank 5 SBCHW mapping. :param spec: MLModel The MLModel spec containing the feature :param feature_name: str The name of the feature for which to add shape range information. If the feature is not found in the input or output descriptions then an exception is thrown :param lower_bounds: List[int] list of integers specifying the lower bounds of each dimension. Length must be same as the rank (length of shape) of the feature_name. :param upper_bounds: List[int] list of integers specifying the upper bounds of each dimension. -1 corresponds to unbounded range. Length must be same as the rank (length of shape) of the feature_name. Examples -------- .. sourcecode:: python >>> import coremltools >>> from coremltools.models.neural_network import flexible_shape_utils >>> spec = coremltools.utils.load_spec('mymodel.mlmodel') >>> # say, the default shape of "my_multiarray_featurename" is (2,3) >>> flexible_shape_utils.set_multiarray_ndshape_range(spec, feature_name='my_multiarray_featurename', lower_bounds=[1,2], upper_bounds=[10,-1]) :return: None. The spec is updated """ if not isinstance(lower_bounds, list): raise Exception("lower_bounds must be a list") if not isinstance(upper_bounds, list): raise Exception("upper_bounds must be a list") feature = _get_feature(spec, feature_name) if feature.type.WhichOneof("Type") != "multiArrayType": raise Exception( "Trying to update shape range for " "a non-multiArray feature type" ) shape = feature.type.multiArrayType.shape if len(shape) != len(lower_bounds): raise Exception( "Length of lower_bounds is not equal to the number of dimensions in the default shape" ) if len(shape) != len(upper_bounds): raise Exception( "Length of upper_bounds is not equal to the number of dimensions in the default shape" ) feature.type.multiArrayType.ClearField("ShapeFlexibility") for i in range(len(lower_bounds)): if shape[i] < lower_bounds[i]: raise Exception( "Default shape in %d-th dimension, which is %d, is smaller" " than the lower bound of %d" % (i, int(shape[i]), lower_bounds[i]) ) if upper_bounds[i] != -1: if shape[i] > upper_bounds[i]: raise Exception( "Default shape in %d-th dimension, which is %d, is greater" " than the upper bound of %d" % (i, int(shape[i]), upper_bounds[i]) ) s = feature.type.multiArrayType.shapeRange.sizeRanges.add() s.lowerBound = lower_bounds[i] s.upperBound = upper_bounds[i] # Bump up specification version spec.specificationVersion = max( _MINIMUM_NDARRAY_SPEC_VERSION, spec.specificationVersion )
[ "def", "set_multiarray_ndshape_range", "(", "spec", ",", "feature_name", ",", "lower_bounds", ",", "upper_bounds", ")", ":", "if", "not", "isinstance", "(", "lower_bounds", ",", "list", ")", ":", "raise", "Exception", "(", "\"lower_bounds must be a list\"", ")", "if", "not", "isinstance", "(", "upper_bounds", ",", "list", ")", ":", "raise", "Exception", "(", "\"upper_bounds must be a list\"", ")", "feature", "=", "_get_feature", "(", "spec", ",", "feature_name", ")", "if", "feature", ".", "type", ".", "WhichOneof", "(", "\"Type\"", ")", "!=", "\"multiArrayType\"", ":", "raise", "Exception", "(", "\"Trying to update shape range for \"", "\"a non-multiArray feature type\"", ")", "shape", "=", "feature", ".", "type", ".", "multiArrayType", ".", "shape", "if", "len", "(", "shape", ")", "!=", "len", "(", "lower_bounds", ")", ":", "raise", "Exception", "(", "\"Length of lower_bounds is not equal to the number of dimensions in the default shape\"", ")", "if", "len", "(", "shape", ")", "!=", "len", "(", "upper_bounds", ")", ":", "raise", "Exception", "(", "\"Length of upper_bounds is not equal to the number of dimensions in the default shape\"", ")", "feature", ".", "type", ".", "multiArrayType", ".", "ClearField", "(", "\"ShapeFlexibility\"", ")", "for", "i", "in", "range", "(", "len", "(", "lower_bounds", ")", ")", ":", "if", "shape", "[", "i", "]", "<", "lower_bounds", "[", "i", "]", ":", "raise", "Exception", "(", "\"Default shape in %d-th dimension, which is %d, is smaller\"", "\" than the lower bound of %d\"", "%", "(", "i", ",", "int", "(", "shape", "[", "i", "]", ")", ",", "lower_bounds", "[", "i", "]", ")", ")", "if", "upper_bounds", "[", "i", "]", "!=", "-", "1", ":", "if", "shape", "[", "i", "]", ">", "upper_bounds", "[", "i", "]", ":", "raise", "Exception", "(", "\"Default shape in %d-th dimension, which is %d, is greater\"", "\" than the upper bound of %d\"", "%", "(", "i", ",", "int", "(", "shape", "[", "i", "]", ")", ",", "upper_bounds", "[", "i", "]", ")", ")", "s", "=", "feature", ".", "type", ".", "multiArrayType", ".", "shapeRange", ".", "sizeRanges", ".", "add", "(", ")", "s", ".", "lowerBound", "=", "lower_bounds", "[", "i", "]", "s", ".", "upperBound", "=", "upper_bounds", "[", "i", "]", "# Bump up specification version", "spec", ".", "specificationVersion", "=", "max", "(", "_MINIMUM_NDARRAY_SPEC_VERSION", ",", "spec", ".", "specificationVersion", ")" ]
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/external/coremltools_wrap/coremltools/coremltools/models/neural_network/flexible_shape_utils.py#L578-L661
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/re.py
python
split
(pattern, string, maxsplit=0, flags=0)
return _compile(pattern, flags).split(string, maxsplit)
Split the source string by the occurrences of the pattern, returning a list containing the resulting substrings.
Split the source string by the occurrences of the pattern, returning a list containing the resulting substrings.
[ "Split", "the", "source", "string", "by", "the", "occurrences", "of", "the", "pattern", "returning", "a", "list", "containing", "the", "resulting", "substrings", "." ]
def split(pattern, string, maxsplit=0, flags=0): """Split the source string by the occurrences of the pattern, returning a list containing the resulting substrings.""" return _compile(pattern, flags).split(string, maxsplit)
[ "def", "split", "(", "pattern", ",", "string", ",", "maxsplit", "=", "0", ",", "flags", "=", "0", ")", ":", "return", "_compile", "(", "pattern", ",", "flags", ")", ".", "split", "(", "string", ",", "maxsplit", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/re.py#L164-L167
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
tools/memory_inspector/memory_inspector/core/memory_map.py
python
MapEntry.GetRelativeOffset
(self, abs_addr)
return abs_addr - self.start + self.mapped_offset
Converts abs_addr to the corresponding offset in the mapped file.
Converts abs_addr to the corresponding offset in the mapped file.
[ "Converts", "abs_addr", "to", "the", "corresponding", "offset", "in", "the", "mapped", "file", "." ]
def GetRelativeOffset(self, abs_addr): """Converts abs_addr to the corresponding offset in the mapped file.""" assert(abs_addr >= self.start and abs_addr <= self.end) return abs_addr - self.start + self.mapped_offset
[ "def", "GetRelativeOffset", "(", "self", ",", "abs_addr", ")", ":", "assert", "(", "abs_addr", ">=", "self", ".", "start", "and", "abs_addr", "<=", "self", ".", "end", ")", "return", "abs_addr", "-", "self", ".", "start", "+", "self", ".", "mapped_offset" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/memory_inspector/memory_inspector/core/memory_map.py#L60-L63
CaoWGG/TensorRT-CenterNet
f949252e37b51e60f873808f46d3683f15735e79
onnx-tensorrt/third_party/onnx/third_party/benchmark/tools/gbench/util.py
python
run_benchmark
(exe_name, benchmark_flags)
return json_res
Run a benchmark specified by 'exe_name' with the specified 'benchmark_flags'. The benchmark is run directly as a subprocess to preserve real time console output. RETURNS: A JSON object representing the benchmark output
Run a benchmark specified by 'exe_name' with the specified 'benchmark_flags'. The benchmark is run directly as a subprocess to preserve real time console output. RETURNS: A JSON object representing the benchmark output
[ "Run", "a", "benchmark", "specified", "by", "exe_name", "with", "the", "specified", "benchmark_flags", ".", "The", "benchmark", "is", "run", "directly", "as", "a", "subprocess", "to", "preserve", "real", "time", "console", "output", ".", "RETURNS", ":", "A", "JSON", "object", "representing", "the", "benchmark", "output" ]
def run_benchmark(exe_name, benchmark_flags): """ Run a benchmark specified by 'exe_name' with the specified 'benchmark_flags'. The benchmark is run directly as a subprocess to preserve real time console output. RETURNS: A JSON object representing the benchmark output """ output_name = find_benchmark_flag('--benchmark_out=', benchmark_flags) is_temp_output = False if output_name is None: is_temp_output = True thandle, output_name = tempfile.mkstemp() os.close(thandle) benchmark_flags = list(benchmark_flags) + \ ['--benchmark_out=%s' % output_name] cmd = [exe_name] + benchmark_flags print("RUNNING: %s" % ' '.join(cmd)) exitCode = subprocess.call(cmd) if exitCode != 0: print('TEST FAILED...') sys.exit(exitCode) json_res = load_benchmark_results(output_name) if is_temp_output: os.unlink(output_name) return json_res
[ "def", "run_benchmark", "(", "exe_name", ",", "benchmark_flags", ")", ":", "output_name", "=", "find_benchmark_flag", "(", "'--benchmark_out='", ",", "benchmark_flags", ")", "is_temp_output", "=", "False", "if", "output_name", "is", "None", ":", "is_temp_output", "=", "True", "thandle", ",", "output_name", "=", "tempfile", ".", "mkstemp", "(", ")", "os", ".", "close", "(", "thandle", ")", "benchmark_flags", "=", "list", "(", "benchmark_flags", ")", "+", "[", "'--benchmark_out=%s'", "%", "output_name", "]", "cmd", "=", "[", "exe_name", "]", "+", "benchmark_flags", "print", "(", "\"RUNNING: %s\"", "%", "' '", ".", "join", "(", "cmd", ")", ")", "exitCode", "=", "subprocess", ".", "call", "(", "cmd", ")", "if", "exitCode", "!=", "0", ":", "print", "(", "'TEST FAILED...'", ")", "sys", ".", "exit", "(", "exitCode", ")", "json_res", "=", "load_benchmark_results", "(", "output_name", ")", "if", "is_temp_output", ":", "os", ".", "unlink", "(", "output_name", ")", "return", "json_res" ]
https://github.com/CaoWGG/TensorRT-CenterNet/blob/f949252e37b51e60f873808f46d3683f15735e79/onnx-tensorrt/third_party/onnx/third_party/benchmark/tools/gbench/util.py#L117-L143
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/ed_menu.py
python
EdMenu.InsertAlpha
(self, id_, label=u'', helpstr=u'', kind=wx.ITEM_NORMAL, after=0, use_bmp=True)
return mitem
Attempts to insert the new menuitem into the menu alphabetically. The optional parameter 'after' is used specify an item id to start the alphabetical lookup after. Otherwise the lookup begins from the first item in the menu. @param id_: New MenuItem ID @keyword label: Menu Label @keyword helpstr: Help String @keyword kind: MenuItem type @keyword after: id of item to start alpha lookup after @keyword use_bmp: try and set a bitmap if an appropriate one is available in the ArtProvider @return: menu item that was inserted
Attempts to insert the new menuitem into the menu alphabetically. The optional parameter 'after' is used specify an item id to start the alphabetical lookup after. Otherwise the lookup begins from the first item in the menu. @param id_: New MenuItem ID @keyword label: Menu Label @keyword helpstr: Help String @keyword kind: MenuItem type @keyword after: id of item to start alpha lookup after @keyword use_bmp: try and set a bitmap if an appropriate one is available in the ArtProvider @return: menu item that was inserted
[ "Attempts", "to", "insert", "the", "new", "menuitem", "into", "the", "menu", "alphabetically", ".", "The", "optional", "parameter", "after", "is", "used", "specify", "an", "item", "id", "to", "start", "the", "alphabetical", "lookup", "after", ".", "Otherwise", "the", "lookup", "begins", "from", "the", "first", "item", "in", "the", "menu", ".", "@param", "id_", ":", "New", "MenuItem", "ID", "@keyword", "label", ":", "Menu", "Label", "@keyword", "helpstr", ":", "Help", "String", "@keyword", "kind", ":", "MenuItem", "type", "@keyword", "after", ":", "id", "of", "item", "to", "start", "alpha", "lookup", "after", "@keyword", "use_bmp", ":", "try", "and", "set", "a", "bitmap", "if", "an", "appropriate", "one", "is", "available", "in", "the", "ArtProvider", "@return", ":", "menu", "item", "that", "was", "inserted" ]
def InsertAlpha(self, id_, label=u'', helpstr=u'', kind=wx.ITEM_NORMAL, after=0, use_bmp=True): """Attempts to insert the new menuitem into the menu alphabetically. The optional parameter 'after' is used specify an item id to start the alphabetical lookup after. Otherwise the lookup begins from the first item in the menu. @param id_: New MenuItem ID @keyword label: Menu Label @keyword helpstr: Help String @keyword kind: MenuItem type @keyword after: id of item to start alpha lookup after @keyword use_bmp: try and set a bitmap if an appropriate one is available in the ArtProvider @return: menu item that was inserted """ if after: start = False else: start = True last_ind = self.GetMenuItemCount() - 1 pos = last_ind for item in range(self.GetMenuItemCount()): mitem = self.FindItemByPosition(item) if mitem.IsSeparator(): continue mlabel = mitem.GetItemLabel() if after and mitem.GetId() == after: start = True continue if after and not start: continue if label < mlabel: pos = item break l_item = self.FindItemByPosition(last_ind) if pos == last_ind and (l_item.IsSeparator() or label > mlabel): mitem = self.Append(id_, label, helpstr, kind, use_bmp) else: mitem = self.Insert(pos, id_, label, helpstr, kind, use_bmp) return mitem
[ "def", "InsertAlpha", "(", "self", ",", "id_", ",", "label", "=", "u''", ",", "helpstr", "=", "u''", ",", "kind", "=", "wx", ".", "ITEM_NORMAL", ",", "after", "=", "0", ",", "use_bmp", "=", "True", ")", ":", "if", "after", ":", "start", "=", "False", "else", ":", "start", "=", "True", "last_ind", "=", "self", ".", "GetMenuItemCount", "(", ")", "-", "1", "pos", "=", "last_ind", "for", "item", "in", "range", "(", "self", ".", "GetMenuItemCount", "(", ")", ")", ":", "mitem", "=", "self", ".", "FindItemByPosition", "(", "item", ")", "if", "mitem", ".", "IsSeparator", "(", ")", ":", "continue", "mlabel", "=", "mitem", ".", "GetItemLabel", "(", ")", "if", "after", "and", "mitem", ".", "GetId", "(", ")", "==", "after", ":", "start", "=", "True", "continue", "if", "after", "and", "not", "start", ":", "continue", "if", "label", "<", "mlabel", ":", "pos", "=", "item", "break", "l_item", "=", "self", ".", "FindItemByPosition", "(", "last_ind", ")", "if", "pos", "==", "last_ind", "and", "(", "l_item", ".", "IsSeparator", "(", ")", "or", "label", ">", "mlabel", ")", ":", "mitem", "=", "self", ".", "Append", "(", "id_", ",", "label", ",", "helpstr", ",", "kind", ",", "use_bmp", ")", "else", ":", "mitem", "=", "self", ".", "Insert", "(", "pos", ",", "id_", ",", "label", ",", "helpstr", ",", "kind", ",", "use_bmp", ")", "return", "mitem" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/ed_menu.py#L162-L204
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/groupby/groupby.py
python
GroupBy.ohlc
(self)
return self._apply_to_column_groupbys(lambda x: x._cython_agg_general("ohlc"))
Compute sum of values, excluding missing values. For multiple groupings, the result index will be a MultiIndex Returns ------- DataFrame Open, high, low and close values within each group.
Compute sum of values, excluding missing values.
[ "Compute", "sum", "of", "values", "excluding", "missing", "values", "." ]
def ohlc(self) -> DataFrame: """ Compute sum of values, excluding missing values. For multiple groupings, the result index will be a MultiIndex Returns ------- DataFrame Open, high, low and close values within each group. """ return self._apply_to_column_groupbys(lambda x: x._cython_agg_general("ohlc"))
[ "def", "ohlc", "(", "self", ")", "->", "DataFrame", ":", "return", "self", ".", "_apply_to_column_groupbys", "(", "lambda", "x", ":", "x", ".", "_cython_agg_general", "(", "\"ohlc\"", ")", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/groupby/groupby.py#L1428-L1440
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/eager/function.py
python
defun_with_attributes
(func=None, input_signature=None, attributes=None, autograph=True, experimental_autograph_options=None, experimental_relax_shapes=False)
return decorated
Compiles a Python function into a callable TensorFlow graph. This function supports adding extra function attributes. See detailed documentation in defun(). Currently this is not exposed in public API since we don't expect user to directly use attributes, and attribute won't work by itself. This assumption might change in future. Args: func: function to be compiled. input_signature: same as defun()'s input_signature. attributes: A dictionary of arguments which will be added to function def as attributes. Currently only support primitive types as value, and only whitelisted attribute name is allowed. Unwhitelisted attribute name or unsupported value will result into ValueError. `func_name` is also one of the whitelisted argument which is a python string, and sets the name for this `ConcreteFunction` in the graph. autograph: same as defun()'s autograph. experimental_autograph_options: same as defun()'s experimental_autograph_options. experimental_relax_shapes: same as defun()'s experimental_relax_shapes Returns: Same as the return value of defun, with attributes added to the function in graph.
Compiles a Python function into a callable TensorFlow graph.
[ "Compiles", "a", "Python", "function", "into", "a", "callable", "TensorFlow", "graph", "." ]
def defun_with_attributes(func=None, input_signature=None, attributes=None, autograph=True, experimental_autograph_options=None, experimental_relax_shapes=False): """Compiles a Python function into a callable TensorFlow graph. This function supports adding extra function attributes. See detailed documentation in defun(). Currently this is not exposed in public API since we don't expect user to directly use attributes, and attribute won't work by itself. This assumption might change in future. Args: func: function to be compiled. input_signature: same as defun()'s input_signature. attributes: A dictionary of arguments which will be added to function def as attributes. Currently only support primitive types as value, and only whitelisted attribute name is allowed. Unwhitelisted attribute name or unsupported value will result into ValueError. `func_name` is also one of the whitelisted argument which is a python string, and sets the name for this `ConcreteFunction` in the graph. autograph: same as defun()'s autograph. experimental_autograph_options: same as defun()'s experimental_autograph_options. experimental_relax_shapes: same as defun()'s experimental_relax_shapes Returns: Same as the return value of defun, with attributes added to the function in graph. """ if input_signature is not None: validate_signature(input_signature) # TODO(apassos): deal with captured global state. Deal with control flow. def decorated(function): try: if attributes: name = attributes.pop("func_name", function.__name__) else: name = function.__name__ except AttributeError: name = "function" return tf_decorator.make_decorator( function, Function( function, name, input_signature=input_signature, attributes=attributes, autograph=autograph, autograph_options=experimental_autograph_options, experimental_relax_shapes=experimental_relax_shapes)) # This code path is for the `foo = tfe.defun(foo, ...)` use case if func is not None: return decorated(func) # This code path is for the # # @tfe.defun(...) # def foo(...): # ... # # use case, which is equivalent to `foo = tfe.defun(...)(foo)` return decorated
[ "def", "defun_with_attributes", "(", "func", "=", "None", ",", "input_signature", "=", "None", ",", "attributes", "=", "None", ",", "autograph", "=", "True", ",", "experimental_autograph_options", "=", "None", ",", "experimental_relax_shapes", "=", "False", ")", ":", "if", "input_signature", "is", "not", "None", ":", "validate_signature", "(", "input_signature", ")", "# TODO(apassos): deal with captured global state. Deal with control flow.", "def", "decorated", "(", "function", ")", ":", "try", ":", "if", "attributes", ":", "name", "=", "attributes", ".", "pop", "(", "\"func_name\"", ",", "function", ".", "__name__", ")", "else", ":", "name", "=", "function", ".", "__name__", "except", "AttributeError", ":", "name", "=", "\"function\"", "return", "tf_decorator", ".", "make_decorator", "(", "function", ",", "Function", "(", "function", ",", "name", ",", "input_signature", "=", "input_signature", ",", "attributes", "=", "attributes", ",", "autograph", "=", "autograph", ",", "autograph_options", "=", "experimental_autograph_options", ",", "experimental_relax_shapes", "=", "experimental_relax_shapes", ")", ")", "# This code path is for the `foo = tfe.defun(foo, ...)` use case", "if", "func", "is", "not", "None", ":", "return", "decorated", "(", "func", ")", "# This code path is for the", "#", "# @tfe.defun(...)", "# def foo(...):", "# ...", "#", "# use case, which is equivalent to `foo = tfe.defun(...)(foo)`", "return", "decorated" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/eager/function.py#L2529-L2594
microsoft/clang
86d4513d3e0daa4d5a29b0b1de7c854ca15f9fe5
tools/scan-view/share/ScanView.py
python
ScanViewRequestHandler.do_POST
(self)
Serve a POST request.
Serve a POST request.
[ "Serve", "a", "POST", "request", "." ]
def do_POST(self): """Serve a POST request.""" try: length = self.headers.getheader('content-length') or "0" try: length = int(length) except: length = 0 content = self.rfile.read(length) fields = parse_query(content) f = self.send_head(fields) if f: self.copyfile(f, self.wfile) f.close() except Exception,e: self.handle_exception(e)
[ "def", "do_POST", "(", "self", ")", ":", "try", ":", "length", "=", "self", ".", "headers", ".", "getheader", "(", "'content-length'", ")", "or", "\"0\"", "try", ":", "length", "=", "int", "(", "length", ")", "except", ":", "length", "=", "0", "content", "=", "self", ".", "rfile", ".", "read", "(", "length", ")", "fields", "=", "parse_query", "(", "content", ")", "f", "=", "self", ".", "send_head", "(", "fields", ")", "if", "f", ":", "self", ".", "copyfile", "(", "f", ",", "self", ".", "wfile", ")", "f", ".", "close", "(", ")", "except", "Exception", ",", "e", ":", "self", ".", "handle_exception", "(", "e", ")" ]
https://github.com/microsoft/clang/blob/86d4513d3e0daa4d5a29b0b1de7c854ca15f9fe5/tools/scan-view/share/ScanView.py#L219-L234
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/ros_comm/rosgraph/src/rosgraph/names.py
python
resolve_name
(name, namespace_, remappings=None)
Resolve a ROS name to its global, canonical form. Private ~names are resolved relative to the node name. @param name: name to resolve. @type name: str @param namespace_: node name to resolve relative to. @type namespace_: str @param remappings: Map of resolved remappings. Use None to indicate no remapping. @return: Resolved name. If name is empty/None, resolve_name returns parent namespace_. If namespace_ is empty/None, @rtype: str
Resolve a ROS name to its global, canonical form. Private ~names are resolved relative to the node name.
[ "Resolve", "a", "ROS", "name", "to", "its", "global", "canonical", "form", ".", "Private", "~names", "are", "resolved", "relative", "to", "the", "node", "name", "." ]
def resolve_name(name, namespace_, remappings=None): """ Resolve a ROS name to its global, canonical form. Private ~names are resolved relative to the node name. @param name: name to resolve. @type name: str @param namespace_: node name to resolve relative to. @type namespace_: str @param remappings: Map of resolved remappings. Use None to indicate no remapping. @return: Resolved name. If name is empty/None, resolve_name returns parent namespace_. If namespace_ is empty/None, @rtype: str """ if not name: #empty string resolves to parent of the namespace_ return namespace(namespace_) name = canonicalize_name(name) if name[0] == SEP: #global name resolved_name = name elif is_private(name): #~name # #3044: be careful not to accidentally make rest of name global resolved_name = canonicalize_name(namespace_ + SEP + name[1:]) else: #relative resolved_name = namespace(namespace_) + name #Mappings override general namespace-based resolution # - do this before canonicalization as remappings are meant to # match the name as specified in the code if remappings and resolved_name in remappings: return remappings[resolved_name] else: return resolved_name
[ "def", "resolve_name", "(", "name", ",", "namespace_", ",", "remappings", "=", "None", ")", ":", "if", "not", "name", ":", "#empty string resolves to parent of the namespace_", "return", "namespace", "(", "namespace_", ")", "name", "=", "canonicalize_name", "(", "name", ")", "if", "name", "[", "0", "]", "==", "SEP", ":", "#global name", "resolved_name", "=", "name", "elif", "is_private", "(", "name", ")", ":", "#~name", "# #3044: be careful not to accidentally make rest of name global", "resolved_name", "=", "canonicalize_name", "(", "namespace_", "+", "SEP", "+", "name", "[", "1", ":", "]", ")", "else", ":", "#relative", "resolved_name", "=", "namespace", "(", "namespace_", ")", "+", "name", "#Mappings override general namespace-based resolution", "# - do this before canonicalization as remappings are meant to", "# match the name as specified in the code", "if", "remappings", "and", "resolved_name", "in", "remappings", ":", "return", "remappings", "[", "resolved_name", "]", "else", ":", "return", "resolved_name" ]
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/ros_comm/rosgraph/src/rosgraph/names.py#L260-L292
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/AWSPythonSDK/1.5.8/docutils/utils/__init__.py
python
version_identifier
(version_info=None)
return version
Given a `version_info` tuple (default is docutils.__version_info__), build & return a version identifier string.
Given a `version_info` tuple (default is docutils.__version_info__), build & return a version identifier string.
[ "Given", "a", "version_info", "tuple", "(", "default", "is", "docutils", ".", "__version_info__", ")", "build", "&", "return", "a", "version", "identifier", "string", "." ]
def version_identifier(version_info=None): # to add in Docutils 0.15: # version_info is a namedtuple, an instance of Docutils.VersionInfo. """ Given a `version_info` tuple (default is docutils.__version_info__), build & return a version identifier string. """ if version_info is None: version_info = __version_info__ if version_info[2]: # version_info.micro micro = '.%s' % version_info[2] else: micro = '' releaselevel = release_level_abbreviations[ version_info[3]] # version_info.releaselevel if version_info[4]: # version_info.serial serial = version_info[4] else: serial = '' if version_info[5]: # version_info.release dev = '' else: dev = '.dev' version = '%s.%s%s%s%s%s' % ( version_info[0], # version_info.major version_info[1], # version_info.minor micro, releaselevel, serial, dev) return version
[ "def", "version_identifier", "(", "version_info", "=", "None", ")", ":", "# to add in Docutils 0.15:", "# version_info is a namedtuple, an instance of Docutils.VersionInfo.", "if", "version_info", "is", "None", ":", "version_info", "=", "__version_info__", "if", "version_info", "[", "2", "]", ":", "# version_info.micro", "micro", "=", "'.%s'", "%", "version_info", "[", "2", "]", "else", ":", "micro", "=", "''", "releaselevel", "=", "release_level_abbreviations", "[", "version_info", "[", "3", "]", "]", "# version_info.releaselevel", "if", "version_info", "[", "4", "]", ":", "# version_info.serial", "serial", "=", "version_info", "[", "4", "]", "else", ":", "serial", "=", "''", "if", "version_info", "[", "5", "]", ":", "# version_info.release", "dev", "=", "''", "else", ":", "dev", "=", "'.dev'", "version", "=", "'%s.%s%s%s%s%s'", "%", "(", "version_info", "[", "0", "]", ",", "# version_info.major", "version_info", "[", "1", "]", ",", "# version_info.minor", "micro", ",", "releaselevel", ",", "serial", ",", "dev", ")", "return", "version" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/docutils/utils/__init__.py#L777-L807
y123456yz/reading-and-annotate-mongodb-3.6
93280293672ca7586dc24af18132aa61e4ed7fcf
mongo/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Tool/GettextCommon.py
python
_detect_msginit
(env)
return None
Detects *msginit(1)* program.
Detects *msginit(1)* program.
[ "Detects", "*", "msginit", "(", "1", ")", "*", "program", "." ]
def _detect_msginit(env): """ Detects *msginit(1)* program. """ if env.has_key('MSGINIT'): return env['MSGINIT'] msginit = env.Detect('msginit'); if msginit: return msginit raise SCons.Errors.StopError(MsginitNotFound, "Could not detect msginit") return None
[ "def", "_detect_msginit", "(", "env", ")", ":", "if", "env", ".", "has_key", "(", "'MSGINIT'", ")", ":", "return", "env", "[", "'MSGINIT'", "]", "msginit", "=", "env", ".", "Detect", "(", "'msginit'", ")", "if", "msginit", ":", "return", "msginit", "raise", "SCons", ".", "Errors", ".", "StopError", "(", "MsginitNotFound", ",", "\"Could not detect msginit\"", ")", "return", "None" ]
https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Tool/GettextCommon.py#L364-L372
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/jedi/jedi/api/classes.py
python
BaseDefinition.line
(self)
return start_pos[0]
The line where the definition occurs (starting with 1).
The line where the definition occurs (starting with 1).
[ "The", "line", "where", "the", "definition", "occurs", "(", "starting", "with", "1", ")", "." ]
def line(self): """The line where the definition occurs (starting with 1).""" start_pos = self._name.start_pos if start_pos is None: return None return start_pos[0]
[ "def", "line", "(", "self", ")", ":", "start_pos", "=", "self", ".", "_name", ".", "start_pos", "if", "start_pos", "is", "None", ":", "return", "None", "return", "start_pos", "[", "0", "]" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/jedi/jedi/api/classes.py#L209-L214
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/numpy/py2/numpy/core/defchararray.py
python
array
(obj, itemsize=None, copy=True, unicode=None, order=None)
return val.view(chararray)
Create a `chararray`. .. note:: This class is provided for numarray backward-compatibility. New code (not concerned with numarray compatibility) should use arrays of type `string_` or `unicode_` and use the free functions in :mod:`numpy.char <numpy.core.defchararray>` for fast vectorized string operations instead. Versus a regular NumPy array of type `str` or `unicode`, this class adds the following functionality: 1) values automatically have whitespace removed from the end when indexed 2) comparison operators automatically remove whitespace from the end when comparing values 3) vectorized string operations are provided as methods (e.g. `str.endswith`) and infix operators (e.g. ``+, *, %``) Parameters ---------- obj : array of str or unicode-like itemsize : int, optional `itemsize` is the number of characters per scalar in the resulting array. If `itemsize` is None, and `obj` is an object array or a Python list, the `itemsize` will be automatically determined. If `itemsize` is provided and `obj` is of type str or unicode, then the `obj` string will be chunked into `itemsize` pieces. copy : bool, optional If true (default), then the object is copied. Otherwise, a copy will only be made if __array__ returns a copy, if obj is a nested sequence, or if a copy is needed to satisfy any of the other requirements (`itemsize`, unicode, `order`, etc.). unicode : bool, optional When true, the resulting `chararray` can contain Unicode characters, when false only 8-bit characters. If unicode is `None` and `obj` is one of the following: - a `chararray`, - an ndarray of type `str` or `unicode` - a Python str or unicode object, then the unicode setting of the output array will be automatically determined. order : {'C', 'F', 'A'}, optional Specify the order of the array. If order is 'C' (default), then the array will be in C-contiguous order (last-index varies the fastest). If order is 'F', then the returned array will be in Fortran-contiguous order (first-index varies the fastest). If order is 'A', then the returned array may be in any order (either C-, Fortran-contiguous, or even discontiguous).
Create a `chararray`.
[ "Create", "a", "chararray", "." ]
def array(obj, itemsize=None, copy=True, unicode=None, order=None): """ Create a `chararray`. .. note:: This class is provided for numarray backward-compatibility. New code (not concerned with numarray compatibility) should use arrays of type `string_` or `unicode_` and use the free functions in :mod:`numpy.char <numpy.core.defchararray>` for fast vectorized string operations instead. Versus a regular NumPy array of type `str` or `unicode`, this class adds the following functionality: 1) values automatically have whitespace removed from the end when indexed 2) comparison operators automatically remove whitespace from the end when comparing values 3) vectorized string operations are provided as methods (e.g. `str.endswith`) and infix operators (e.g. ``+, *, %``) Parameters ---------- obj : array of str or unicode-like itemsize : int, optional `itemsize` is the number of characters per scalar in the resulting array. If `itemsize` is None, and `obj` is an object array or a Python list, the `itemsize` will be automatically determined. If `itemsize` is provided and `obj` is of type str or unicode, then the `obj` string will be chunked into `itemsize` pieces. copy : bool, optional If true (default), then the object is copied. Otherwise, a copy will only be made if __array__ returns a copy, if obj is a nested sequence, or if a copy is needed to satisfy any of the other requirements (`itemsize`, unicode, `order`, etc.). unicode : bool, optional When true, the resulting `chararray` can contain Unicode characters, when false only 8-bit characters. If unicode is `None` and `obj` is one of the following: - a `chararray`, - an ndarray of type `str` or `unicode` - a Python str or unicode object, then the unicode setting of the output array will be automatically determined. order : {'C', 'F', 'A'}, optional Specify the order of the array. If order is 'C' (default), then the array will be in C-contiguous order (last-index varies the fastest). If order is 'F', then the returned array will be in Fortran-contiguous order (first-index varies the fastest). If order is 'A', then the returned array may be in any order (either C-, Fortran-contiguous, or even discontiguous). """ if isinstance(obj, (_bytes, _unicode)): if unicode is None: if isinstance(obj, _unicode): unicode = True else: unicode = False if itemsize is None: itemsize = _len(obj) shape = _len(obj) // itemsize if unicode: if sys.maxunicode == 0xffff: # On a narrow Python build, the buffer for Unicode # strings is UCS2, which doesn't match the buffer for # NumPy Unicode types, which is ALWAYS UCS4. # Therefore, we need to convert the buffer. On Python # 2.6 and later, we can use the utf_32 codec. Earlier # versions don't have that codec, so we convert to a # numerical array that matches the input buffer, and # then use NumPy to convert it to UCS4. All of this # should happen in native endianness. obj = obj.encode('utf_32') else: obj = _unicode(obj) else: # Let the default Unicode -> string encoding (if any) take # precedence. obj = _bytes(obj) return chararray(shape, itemsize=itemsize, unicode=unicode, buffer=obj, order=order) if isinstance(obj, (list, tuple)): obj = numpy.asarray(obj) if isinstance(obj, ndarray) and issubclass(obj.dtype.type, character): # If we just have a vanilla chararray, create a chararray # view around it. if not isinstance(obj, chararray): obj = obj.view(chararray) if itemsize is None: itemsize = obj.itemsize # itemsize is in 8-bit chars, so for Unicode, we need # to divide by the size of a single Unicode character, # which for NumPy is always 4 if issubclass(obj.dtype.type, unicode_): itemsize //= 4 if unicode is None: if issubclass(obj.dtype.type, unicode_): unicode = True else: unicode = False if unicode: dtype = unicode_ else: dtype = string_ if order is not None: obj = numpy.asarray(obj, order=order) if (copy or (itemsize != obj.itemsize) or (not unicode and isinstance(obj, unicode_)) or (unicode and isinstance(obj, string_))): obj = obj.astype((dtype, long(itemsize))) return obj if isinstance(obj, ndarray) and issubclass(obj.dtype.type, object): if itemsize is None: # Since no itemsize was specified, convert the input array to # a list so the ndarray constructor will automatically # determine the itemsize for us. obj = obj.tolist() # Fall through to the default case if unicode: dtype = unicode_ else: dtype = string_ if itemsize is None: val = narray(obj, dtype=dtype, order=order, subok=True) else: val = narray(obj, dtype=(dtype, itemsize), order=order, subok=True) return val.view(chararray)
[ "def", "array", "(", "obj", ",", "itemsize", "=", "None", ",", "copy", "=", "True", ",", "unicode", "=", "None", ",", "order", "=", "None", ")", ":", "if", "isinstance", "(", "obj", ",", "(", "_bytes", ",", "_unicode", ")", ")", ":", "if", "unicode", "is", "None", ":", "if", "isinstance", "(", "obj", ",", "_unicode", ")", ":", "unicode", "=", "True", "else", ":", "unicode", "=", "False", "if", "itemsize", "is", "None", ":", "itemsize", "=", "_len", "(", "obj", ")", "shape", "=", "_len", "(", "obj", ")", "//", "itemsize", "if", "unicode", ":", "if", "sys", ".", "maxunicode", "==", "0xffff", ":", "# On a narrow Python build, the buffer for Unicode", "# strings is UCS2, which doesn't match the buffer for", "# NumPy Unicode types, which is ALWAYS UCS4.", "# Therefore, we need to convert the buffer. On Python", "# 2.6 and later, we can use the utf_32 codec. Earlier", "# versions don't have that codec, so we convert to a", "# numerical array that matches the input buffer, and", "# then use NumPy to convert it to UCS4. All of this", "# should happen in native endianness.", "obj", "=", "obj", ".", "encode", "(", "'utf_32'", ")", "else", ":", "obj", "=", "_unicode", "(", "obj", ")", "else", ":", "# Let the default Unicode -> string encoding (if any) take", "# precedence.", "obj", "=", "_bytes", "(", "obj", ")", "return", "chararray", "(", "shape", ",", "itemsize", "=", "itemsize", ",", "unicode", "=", "unicode", ",", "buffer", "=", "obj", ",", "order", "=", "order", ")", "if", "isinstance", "(", "obj", ",", "(", "list", ",", "tuple", ")", ")", ":", "obj", "=", "numpy", ".", "asarray", "(", "obj", ")", "if", "isinstance", "(", "obj", ",", "ndarray", ")", "and", "issubclass", "(", "obj", ".", "dtype", ".", "type", ",", "character", ")", ":", "# If we just have a vanilla chararray, create a chararray", "# view around it.", "if", "not", "isinstance", "(", "obj", ",", "chararray", ")", ":", "obj", "=", "obj", ".", "view", "(", "chararray", ")", "if", "itemsize", "is", "None", ":", "itemsize", "=", "obj", ".", "itemsize", "# itemsize is in 8-bit chars, so for Unicode, we need", "# to divide by the size of a single Unicode character,", "# which for NumPy is always 4", "if", "issubclass", "(", "obj", ".", "dtype", ".", "type", ",", "unicode_", ")", ":", "itemsize", "//=", "4", "if", "unicode", "is", "None", ":", "if", "issubclass", "(", "obj", ".", "dtype", ".", "type", ",", "unicode_", ")", ":", "unicode", "=", "True", "else", ":", "unicode", "=", "False", "if", "unicode", ":", "dtype", "=", "unicode_", "else", ":", "dtype", "=", "string_", "if", "order", "is", "not", "None", ":", "obj", "=", "numpy", ".", "asarray", "(", "obj", ",", "order", "=", "order", ")", "if", "(", "copy", "or", "(", "itemsize", "!=", "obj", ".", "itemsize", ")", "or", "(", "not", "unicode", "and", "isinstance", "(", "obj", ",", "unicode_", ")", ")", "or", "(", "unicode", "and", "isinstance", "(", "obj", ",", "string_", ")", ")", ")", ":", "obj", "=", "obj", ".", "astype", "(", "(", "dtype", ",", "long", "(", "itemsize", ")", ")", ")", "return", "obj", "if", "isinstance", "(", "obj", ",", "ndarray", ")", "and", "issubclass", "(", "obj", ".", "dtype", ".", "type", ",", "object", ")", ":", "if", "itemsize", "is", "None", ":", "# Since no itemsize was specified, convert the input array to", "# a list so the ndarray constructor will automatically", "# determine the itemsize for us.", "obj", "=", "obj", ".", "tolist", "(", ")", "# Fall through to the default case", "if", "unicode", ":", "dtype", "=", "unicode_", "else", ":", "dtype", "=", "string_", "if", "itemsize", "is", "None", ":", "val", "=", "narray", "(", "obj", ",", "dtype", "=", "dtype", ",", "order", "=", "order", ",", "subok", "=", "True", ")", "else", ":", "val", "=", "narray", "(", "obj", ",", "dtype", "=", "(", "dtype", ",", "itemsize", ")", ",", "order", "=", "order", ",", "subok", "=", "True", ")", "return", "val", ".", "view", "(", "chararray", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py2/numpy/core/defchararray.py#L2634-L2783
llvm/llvm-project
ffa6262cb4e2a335d26416fad39a581b4f98c5f4
llvm/utils/git/pre-push.py
python
get_dev_null
()
return dev_null_fd
Lazily create a /dev/null fd for use in shell()
Lazily create a /dev/null fd for use in shell()
[ "Lazily", "create", "a", "/", "dev", "/", "null", "fd", "for", "use", "in", "shell", "()" ]
def get_dev_null(): """Lazily create a /dev/null fd for use in shell()""" global dev_null_fd if dev_null_fd is None: dev_null_fd = open(os.devnull, 'w') return dev_null_fd
[ "def", "get_dev_null", "(", ")", ":", "global", "dev_null_fd", "if", "dev_null_fd", "is", "None", ":", "dev_null_fd", "=", "open", "(", "os", ".", "devnull", ",", "'w'", ")", "return", "dev_null_fd" ]
https://github.com/llvm/llvm-project/blob/ffa6262cb4e2a335d26416fad39a581b4f98c5f4/llvm/utils/git/pre-push.py#L76-L81
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/dataview.py
python
DataViewCtrl.EnsureVisible
(*args, **kwargs)
return _dataview.DataViewCtrl_EnsureVisible(*args, **kwargs)
EnsureVisible(self, DataViewItem item, DataViewColumn column=None)
EnsureVisible(self, DataViewItem item, DataViewColumn column=None)
[ "EnsureVisible", "(", "self", "DataViewItem", "item", "DataViewColumn", "column", "=", "None", ")" ]
def EnsureVisible(*args, **kwargs): """EnsureVisible(self, DataViewItem item, DataViewColumn column=None)""" return _dataview.DataViewCtrl_EnsureVisible(*args, **kwargs)
[ "def", "EnsureVisible", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_dataview", ".", "DataViewCtrl_EnsureVisible", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/dataview.py#L1812-L1814
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/grid.py
python
Grid.SelectBlock
(*args, **kwargs)
return _grid.Grid_SelectBlock(*args, **kwargs)
SelectBlock(self, int topRow, int leftCol, int bottomRow, int rightCol, bool addToSelected=False)
SelectBlock(self, int topRow, int leftCol, int bottomRow, int rightCol, bool addToSelected=False)
[ "SelectBlock", "(", "self", "int", "topRow", "int", "leftCol", "int", "bottomRow", "int", "rightCol", "bool", "addToSelected", "=", "False", ")" ]
def SelectBlock(*args, **kwargs): """ SelectBlock(self, int topRow, int leftCol, int bottomRow, int rightCol, bool addToSelected=False) """ return _grid.Grid_SelectBlock(*args, **kwargs)
[ "def", "SelectBlock", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_grid", ".", "Grid_SelectBlock", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/grid.py#L2034-L2039
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/protobuf/py3/google/protobuf/internal/decoder.py
python
MapDecoder
(field_descriptor, new_default, is_message_map)
return DecodeMap
Returns a decoder for a map field.
Returns a decoder for a map field.
[ "Returns", "a", "decoder", "for", "a", "map", "field", "." ]
def MapDecoder(field_descriptor, new_default, is_message_map): """Returns a decoder for a map field.""" key = field_descriptor tag_bytes = encoder.TagBytes(field_descriptor.number, wire_format.WIRETYPE_LENGTH_DELIMITED) tag_len = len(tag_bytes) local_DecodeVarint = _DecodeVarint # Can't read _concrete_class yet; might not be initialized. message_type = field_descriptor.message_type def DecodeMap(buffer, pos, end, message, field_dict): submsg = message_type._concrete_class() value = field_dict.get(key) if value is None: value = field_dict.setdefault(key, new_default(message)) while 1: # Read length. (size, pos) = local_DecodeVarint(buffer, pos) new_pos = pos + size if new_pos > end: raise _DecodeError('Truncated message.') # Read sub-message. submsg.Clear() if submsg._InternalParse(buffer, pos, new_pos) != new_pos: # The only reason _InternalParse would return early is if it # encountered an end-group tag. raise _DecodeError('Unexpected end-group tag.') if is_message_map: value[submsg.key].CopyFrom(submsg.value) else: value[submsg.key] = submsg.value # Predict that the next tag is another copy of the same repeated field. pos = new_pos + tag_len if buffer[new_pos:pos] != tag_bytes or new_pos == end: # Prediction failed. Return. return new_pos return DecodeMap
[ "def", "MapDecoder", "(", "field_descriptor", ",", "new_default", ",", "is_message_map", ")", ":", "key", "=", "field_descriptor", "tag_bytes", "=", "encoder", ".", "TagBytes", "(", "field_descriptor", ".", "number", ",", "wire_format", ".", "WIRETYPE_LENGTH_DELIMITED", ")", "tag_len", "=", "len", "(", "tag_bytes", ")", "local_DecodeVarint", "=", "_DecodeVarint", "# Can't read _concrete_class yet; might not be initialized.", "message_type", "=", "field_descriptor", ".", "message_type", "def", "DecodeMap", "(", "buffer", ",", "pos", ",", "end", ",", "message", ",", "field_dict", ")", ":", "submsg", "=", "message_type", ".", "_concrete_class", "(", ")", "value", "=", "field_dict", ".", "get", "(", "key", ")", "if", "value", "is", "None", ":", "value", "=", "field_dict", ".", "setdefault", "(", "key", ",", "new_default", "(", "message", ")", ")", "while", "1", ":", "# Read length.", "(", "size", ",", "pos", ")", "=", "local_DecodeVarint", "(", "buffer", ",", "pos", ")", "new_pos", "=", "pos", "+", "size", "if", "new_pos", ">", "end", ":", "raise", "_DecodeError", "(", "'Truncated message.'", ")", "# Read sub-message.", "submsg", ".", "Clear", "(", ")", "if", "submsg", ".", "_InternalParse", "(", "buffer", ",", "pos", ",", "new_pos", ")", "!=", "new_pos", ":", "# The only reason _InternalParse would return early is if it", "# encountered an end-group tag.", "raise", "_DecodeError", "(", "'Unexpected end-group tag.'", ")", "if", "is_message_map", ":", "value", "[", "submsg", ".", "key", "]", ".", "CopyFrom", "(", "submsg", ".", "value", ")", "else", ":", "value", "[", "submsg", ".", "key", "]", "=", "submsg", ".", "value", "# Predict that the next tag is another copy of the same repeated field.", "pos", "=", "new_pos", "+", "tag_len", "if", "buffer", "[", "new_pos", ":", "pos", "]", "!=", "tag_bytes", "or", "new_pos", "==", "end", ":", "# Prediction failed. Return.", "return", "new_pos", "return", "DecodeMap" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/protobuf/py3/google/protobuf/internal/decoder.py#L864-L904
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/ma/extras.py
python
unique
(ar1, return_index=False, return_inverse=False)
return output
Finds the unique elements of an array. Masked values are considered the same element (masked). The output array is always a masked array. See `numpy.unique` for more details. See Also -------- numpy.unique : Equivalent function for ndarrays.
Finds the unique elements of an array.
[ "Finds", "the", "unique", "elements", "of", "an", "array", "." ]
def unique(ar1, return_index=False, return_inverse=False): """ Finds the unique elements of an array. Masked values are considered the same element (masked). The output array is always a masked array. See `numpy.unique` for more details. See Also -------- numpy.unique : Equivalent function for ndarrays. """ output = np.unique(ar1, return_index=return_index, return_inverse=return_inverse) if isinstance(output, tuple): output = list(output) output[0] = output[0].view(MaskedArray) output = tuple(output) else: output = output.view(MaskedArray) return output
[ "def", "unique", "(", "ar1", ",", "return_index", "=", "False", ",", "return_inverse", "=", "False", ")", ":", "output", "=", "np", ".", "unique", "(", "ar1", ",", "return_index", "=", "return_index", ",", "return_inverse", "=", "return_inverse", ")", "if", "isinstance", "(", "output", ",", "tuple", ")", ":", "output", "=", "list", "(", "output", ")", "output", "[", "0", "]", "=", "output", "[", "0", "]", ".", "view", "(", "MaskedArray", ")", "output", "=", "tuple", "(", "output", ")", "else", ":", "output", "=", "output", ".", "view", "(", "MaskedArray", ")", "return", "output" ]
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/ma/extras.py#L1042-L1063
raymondlu/super-animation-samples
04234269112ff0dc32447f27a761dbbb00b8ba17
samples/cocos2d-x-3.1/CocosLuaGame2/frameworks/cocos2d-x/tools/bindings-generator/backup/clang-llvm-3.3-pybinding/cindex.py
python
Cursor.get_children
(self)
return iter(children)
Return an iterator for accessing the children of this cursor.
Return an iterator for accessing the children of this cursor.
[ "Return", "an", "iterator", "for", "accessing", "the", "children", "of", "this", "cursor", "." ]
def get_children(self): """Return an iterator for accessing the children of this cursor.""" # FIXME: Expose iteration from CIndex, PR6125. def visitor(child, parent, children): # FIXME: Document this assertion in API. # FIXME: There should just be an isNull method. assert child != conf.lib.clang_getNullCursor() # Create reference to TU so it isn't GC'd before Cursor. child._tu = self._tu children.append(child) return 1 # continue children = [] conf.lib.clang_visitChildren(self, callbacks['cursor_visit'](visitor), children) return iter(children)
[ "def", "get_children", "(", "self", ")", ":", "# FIXME: Expose iteration from CIndex, PR6125.", "def", "visitor", "(", "child", ",", "parent", ",", "children", ")", ":", "# FIXME: Document this assertion in API.", "# FIXME: There should just be an isNull method.", "assert", "child", "!=", "conf", ".", "lib", ".", "clang_getNullCursor", "(", ")", "# Create reference to TU so it isn't GC'd before Cursor.", "child", ".", "_tu", "=", "self", ".", "_tu", "children", ".", "append", "(", "child", ")", "return", "1", "# continue", "children", "=", "[", "]", "conf", ".", "lib", ".", "clang_visitChildren", "(", "self", ",", "callbacks", "[", "'cursor_visit'", "]", "(", "visitor", ")", ",", "children", ")", "return", "iter", "(", "children", ")" ]
https://github.com/raymondlu/super-animation-samples/blob/04234269112ff0dc32447f27a761dbbb00b8ba17/samples/cocos2d-x-3.1/CocosLuaGame2/frameworks/cocos2d-x/tools/bindings-generator/backup/clang-llvm-3.3-pybinding/cindex.py#L1291-L1307
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/richtext.py
python
RichTextFileHandler.CanHandle
(*args, **kwargs)
return _richtext.RichTextFileHandler_CanHandle(*args, **kwargs)
CanHandle(self, String filename) -> bool
CanHandle(self, String filename) -> bool
[ "CanHandle", "(", "self", "String", "filename", ")", "-", ">", "bool" ]
def CanHandle(*args, **kwargs): """CanHandle(self, String filename) -> bool""" return _richtext.RichTextFileHandler_CanHandle(*args, **kwargs)
[ "def", "CanHandle", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_richtext", ".", "RichTextFileHandler_CanHandle", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/richtext.py#L2768-L2770
ValveSoftware/source-sdk-2013
0d8dceea4310fde5706b3ce1c70609d72a38efdf
mp/src/thirdparty/protobuf-2.3.0/python/ez_setup.py
python
use_setuptools
( version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir, download_delay=15 )
Automatically find/download setuptools and make it available on sys.path `version` should be a valid setuptools version number that is available as an egg for download under the `download_base` URL (which should end with a '/'). `to_dir` is the directory where setuptools will be downloaded, if it is not already available. If `download_delay` is specified, it should be the number of seconds that will be paused before initiating a download, should one be required. If an older version of setuptools is installed, this routine will print a message to ``sys.stderr`` and raise SystemExit in an attempt to abort the calling script.
Automatically find/download setuptools and make it available on sys.path
[ "Automatically", "find", "/", "download", "setuptools", "and", "make", "it", "available", "on", "sys", ".", "path" ]
def use_setuptools( version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir, download_delay=15 ): """Automatically find/download setuptools and make it available on sys.path `version` should be a valid setuptools version number that is available as an egg for download under the `download_base` URL (which should end with a '/'). `to_dir` is the directory where setuptools will be downloaded, if it is not already available. If `download_delay` is specified, it should be the number of seconds that will be paused before initiating a download, should one be required. If an older version of setuptools is installed, this routine will print a message to ``sys.stderr`` and raise SystemExit in an attempt to abort the calling script. """ was_imported = 'pkg_resources' in sys.modules or 'setuptools' in sys.modules def do_download(): egg = download_setuptools(version, download_base, to_dir, download_delay) sys.path.insert(0, egg) import setuptools; setuptools.bootstrap_install_from = egg try: import pkg_resources except ImportError: return do_download() try: pkg_resources.require("setuptools>="+version); return except pkg_resources.VersionConflict, e: if was_imported: print >>sys.stderr, ( "The required version of setuptools (>=%s) is not available, and\n" "can't be installed while this script is running. Please install\n" " a more recent version first, using 'easy_install -U setuptools'." "\n\n(Currently using %r)" ) % (version, e.args[0]) sys.exit(2) else: del pkg_resources, sys.modules['pkg_resources'] # reload ok return do_download() except pkg_resources.DistributionNotFound: return do_download()
[ "def", "use_setuptools", "(", "version", "=", "DEFAULT_VERSION", ",", "download_base", "=", "DEFAULT_URL", ",", "to_dir", "=", "os", ".", "curdir", ",", "download_delay", "=", "15", ")", ":", "was_imported", "=", "'pkg_resources'", "in", "sys", ".", "modules", "or", "'setuptools'", "in", "sys", ".", "modules", "def", "do_download", "(", ")", ":", "egg", "=", "download_setuptools", "(", "version", ",", "download_base", ",", "to_dir", ",", "download_delay", ")", "sys", ".", "path", ".", "insert", "(", "0", ",", "egg", ")", "import", "setuptools", "setuptools", ".", "bootstrap_install_from", "=", "egg", "try", ":", "import", "pkg_resources", "except", "ImportError", ":", "return", "do_download", "(", ")", "try", ":", "pkg_resources", ".", "require", "(", "\"setuptools>=\"", "+", "version", ")", "return", "except", "pkg_resources", ".", "VersionConflict", ",", "e", ":", "if", "was_imported", ":", "print", ">>", "sys", ".", "stderr", ",", "(", "\"The required version of setuptools (>=%s) is not available, and\\n\"", "\"can't be installed while this script is running. Please install\\n\"", "\" a more recent version first, using 'easy_install -U setuptools'.\"", "\"\\n\\n(Currently using %r)\"", ")", "%", "(", "version", ",", "e", ".", "args", "[", "0", "]", ")", "sys", ".", "exit", "(", "2", ")", "else", ":", "del", "pkg_resources", ",", "sys", ".", "modules", "[", "'pkg_resources'", "]", "# reload ok", "return", "do_download", "(", ")", "except", "pkg_resources", ".", "DistributionNotFound", ":", "return", "do_download", "(", ")" ]
https://github.com/ValveSoftware/source-sdk-2013/blob/0d8dceea4310fde5706b3ce1c70609d72a38efdf/mp/src/thirdparty/protobuf-2.3.0/python/ez_setup.py#L77-L116
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
android_webview/tools/webview_licenses.py
python
GenerateNoticeFile
()
return '\n'.join(content)
Generates the contents of an Android NOTICE file for the third-party code. This is used by the snapshot tool. Returns: The contents of the NOTICE file.
Generates the contents of an Android NOTICE file for the third-party code. This is used by the snapshot tool. Returns: The contents of the NOTICE file.
[ "Generates", "the", "contents", "of", "an", "Android", "NOTICE", "file", "for", "the", "third", "-", "party", "code", ".", "This", "is", "used", "by", "the", "snapshot", "tool", ".", "Returns", ":", "The", "contents", "of", "the", "NOTICE", "file", "." ]
def GenerateNoticeFile(): """Generates the contents of an Android NOTICE file for the third-party code. This is used by the snapshot tool. Returns: The contents of the NOTICE file. """ third_party_dirs = _FindThirdPartyDirs() # Don't forget Chromium's LICENSE file content = [_ReadFile('LICENSE')] # We provide attribution for all third-party directories. # TODO(steveblock): Limit this to only code used by the WebView binary. for directory in sorted(third_party_dirs): metadata = licenses.ParseDir(directory, REPOSITORY_ROOT, require_license_file=False) license_file = metadata['License File'] if license_file and license_file != licenses.NOT_SHIPPED: content.append(_ReadFile(license_file)) return '\n'.join(content)
[ "def", "GenerateNoticeFile", "(", ")", ":", "third_party_dirs", "=", "_FindThirdPartyDirs", "(", ")", "# Don't forget Chromium's LICENSE file", "content", "=", "[", "_ReadFile", "(", "'LICENSE'", ")", "]", "# We provide attribution for all third-party directories.", "# TODO(steveblock): Limit this to only code used by the WebView binary.", "for", "directory", "in", "sorted", "(", "third_party_dirs", ")", ":", "metadata", "=", "licenses", ".", "ParseDir", "(", "directory", ",", "REPOSITORY_ROOT", ",", "require_license_file", "=", "False", ")", "license_file", "=", "metadata", "[", "'License File'", "]", "if", "license_file", "and", "license_file", "!=", "licenses", ".", "NOT_SHIPPED", ":", "content", ".", "append", "(", "_ReadFile", "(", "license_file", ")", ")", "return", "'\\n'", ".", "join", "(", "content", ")" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/android_webview/tools/webview_licenses.py#L267-L288
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
third_party/closure_linter/closure_linter/checkerbase.py
python
CheckerBase.HandleError
(self, code, message, token, position=None, fix_data=None)
Prints out the given error message including a line number. Args: code: The error code. message: The error to print. token: The token where the error occurred, or None if it was a file-wide issue. position: The position of the error, defaults to None. fix_data: Metadata used for fixing the error.
Prints out the given error message including a line number.
[ "Prints", "out", "the", "given", "error", "message", "including", "a", "line", "number", "." ]
def HandleError(self, code, message, token, position=None, fix_data=None): """Prints out the given error message including a line number. Args: code: The error code. message: The error to print. token: The token where the error occurred, or None if it was a file-wide issue. position: The position of the error, defaults to None. fix_data: Metadata used for fixing the error. """ self._has_errors = True self._error_handler.HandleError( error.Error(code, message, token, position, fix_data))
[ "def", "HandleError", "(", "self", ",", "code", ",", "message", ",", "token", ",", "position", "=", "None", ",", "fix_data", "=", "None", ")", ":", "self", ".", "_has_errors", "=", "True", "self", ".", "_error_handler", ".", "HandleError", "(", "error", ".", "Error", "(", "code", ",", "message", ",", "token", ",", "position", ",", "fix_data", ")", ")" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/closure_linter/closure_linter/checkerbase.py#L127-L141
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqtinterfaces/mantidqtinterfaces/reduction_gui/widgets/sans/sans_catalog.py
python
SANSCatalogWidget.tableWidgetContext
(self, point)
Create a menu for the tableWidget and associated actions
Create a menu for the tableWidget and associated actions
[ "Create", "a", "menu", "for", "the", "tableWidget", "and", "associated", "actions" ]
def tableWidgetContext(self, point): '''Create a menu for the tableWidget and associated actions''' tw_menu = QMenu("Menu", self) tw_menu.addAction(self.copyAction) tw_menu.exec_(self.mapToGlobal(point))
[ "def", "tableWidgetContext", "(", "self", ",", "point", ")", ":", "tw_menu", "=", "QMenu", "(", "\"Menu\"", ",", "self", ")", "tw_menu", ".", "addAction", "(", "self", ".", "copyAction", ")", "tw_menu", ".", "exec_", "(", "self", ".", "mapToGlobal", "(", "point", ")", ")" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/reduction_gui/widgets/sans/sans_catalog.py#L72-L76
RobotLocomotion/drake
0e18a34604c45ed65bc9018a54f7610f91cdad5b
doc/styleguide/build.py
python
_add_title
(*, temp_dir, filename, title)
Adds a header to a Markdown file so that we can build it with Jekyll directly, without using the GitHub Pages infrastructure. The original file is replaced.
Adds a header to a Markdown file so that we can build it with Jekyll directly, without using the GitHub Pages infrastructure. The original file is replaced.
[ "Adds", "a", "header", "to", "a", "Markdown", "file", "so", "that", "we", "can", "build", "it", "with", "Jekyll", "directly", "without", "using", "the", "GitHub", "Pages", "infrastructure", ".", "The", "original", "file", "is", "replaced", "." ]
def _add_title(*, temp_dir, filename, title): """Adds a header to a Markdown file so that we can build it with Jekyll directly, without using the GitHub Pages infrastructure. The original file is replaced. """ temp_dir_filename = join(temp_dir, filename) with open(temp_dir_filename, "r", encoding="utf-8") as f: data = f.read() os.unlink(temp_dir_filename) with open(temp_dir_filename, "w", encoding="utf-8") as f: f.write(textwrap.dedent(f"""\ --- title: {title} --- """) + "\n") f.write(data)
[ "def", "_add_title", "(", "*", ",", "temp_dir", ",", "filename", ",", "title", ")", ":", "temp_dir_filename", "=", "join", "(", "temp_dir", ",", "filename", ")", "with", "open", "(", "temp_dir_filename", ",", "\"r\"", ",", "encoding", "=", "\"utf-8\"", ")", "as", "f", ":", "data", "=", "f", ".", "read", "(", ")", "os", ".", "unlink", "(", "temp_dir_filename", ")", "with", "open", "(", "temp_dir_filename", ",", "\"w\"", ",", "encoding", "=", "\"utf-8\"", ")", "as", "f", ":", "f", ".", "write", "(", "textwrap", ".", "dedent", "(", "f\"\"\"\\\n ---\n title: {title}\n ---\n \"\"\"", ")", "+", "\"\\n\"", ")", "f", ".", "write", "(", "data", ")" ]
https://github.com/RobotLocomotion/drake/blob/0e18a34604c45ed65bc9018a54f7610f91cdad5b/doc/styleguide/build.py#L13-L28
ceph/ceph
959663007321a369c83218414a29bd9dbc8bda3a
src/ceph-volume/ceph_volume/devices/simple/activate.py
python
Activate.validate_devices
(self, json_config)
``json_config`` is the loaded dictionary coming from the JSON file. It is usually mixed with other non-device items, but for sakes of comparison it doesn't really matter. This method is just making sure that the keys needed exist
``json_config`` is the loaded dictionary coming from the JSON file. It is usually mixed with other non-device items, but for sakes of comparison it doesn't really matter. This method is just making sure that the keys needed exist
[ "json_config", "is", "the", "loaded", "dictionary", "coming", "from", "the", "JSON", "file", ".", "It", "is", "usually", "mixed", "with", "other", "non", "-", "device", "items", "but", "for", "sakes", "of", "comparison", "it", "doesn", "t", "really", "matter", ".", "This", "method", "is", "just", "making", "sure", "that", "the", "keys", "needed", "exist" ]
def validate_devices(self, json_config): """ ``json_config`` is the loaded dictionary coming from the JSON file. It is usually mixed with other non-device items, but for sakes of comparison it doesn't really matter. This method is just making sure that the keys needed exist """ devices = json_config.keys() try: objectstore = json_config['type'] except KeyError: if {'data', 'journal'}.issubset(set(devices)): logger.warning( '"type" key not found, assuming "filestore" since journal key is present' ) objectstore = 'filestore' else: logger.warning( '"type" key not found, assuming "bluestore" since journal key is not present' ) objectstore = 'bluestore' # Go through all the device combinations that are absolutely required, # raise an error describing what was expected and what was found # otherwise. if objectstore == 'filestore': if {'data', 'journal'}.issubset(set(devices)): return True else: found = [i for i in devices if i in ['data', 'journal']] mlogger.error("Required devices (data, and journal) not present for filestore") mlogger.error('filestore devices found: %s', found) raise RuntimeError('Unable to activate filestore OSD due to missing devices') else: # This is a bit tricky, with newer bluestore we don't need data, older implementations # do (e.g. with ceph-disk). ceph-volume just uses a tmpfs that doesn't require data. if {'block', 'data'}.issubset(set(devices)): return True else: bluestore_devices = ['block.db', 'block.wal', 'block', 'data'] found = [i for i in devices if i in bluestore_devices] mlogger.error("Required devices (block and data) not present for bluestore") mlogger.error('bluestore devices found: %s', found) raise RuntimeError('Unable to activate bluestore OSD due to missing devices')
[ "def", "validate_devices", "(", "self", ",", "json_config", ")", ":", "devices", "=", "json_config", ".", "keys", "(", ")", "try", ":", "objectstore", "=", "json_config", "[", "'type'", "]", "except", "KeyError", ":", "if", "{", "'data'", ",", "'journal'", "}", ".", "issubset", "(", "set", "(", "devices", ")", ")", ":", "logger", ".", "warning", "(", "'\"type\" key not found, assuming \"filestore\" since journal key is present'", ")", "objectstore", "=", "'filestore'", "else", ":", "logger", ".", "warning", "(", "'\"type\" key not found, assuming \"bluestore\" since journal key is not present'", ")", "objectstore", "=", "'bluestore'", "# Go through all the device combinations that are absolutely required,", "# raise an error describing what was expected and what was found", "# otherwise.", "if", "objectstore", "==", "'filestore'", ":", "if", "{", "'data'", ",", "'journal'", "}", ".", "issubset", "(", "set", "(", "devices", ")", ")", ":", "return", "True", "else", ":", "found", "=", "[", "i", "for", "i", "in", "devices", "if", "i", "in", "[", "'data'", ",", "'journal'", "]", "]", "mlogger", ".", "error", "(", "\"Required devices (data, and journal) not present for filestore\"", ")", "mlogger", ".", "error", "(", "'filestore devices found: %s'", ",", "found", ")", "raise", "RuntimeError", "(", "'Unable to activate filestore OSD due to missing devices'", ")", "else", ":", "# This is a bit tricky, with newer bluestore we don't need data, older implementations", "# do (e.g. with ceph-disk). ceph-volume just uses a tmpfs that doesn't require data.", "if", "{", "'block'", ",", "'data'", "}", ".", "issubset", "(", "set", "(", "devices", ")", ")", ":", "return", "True", "else", ":", "bluestore_devices", "=", "[", "'block.db'", ",", "'block.wal'", ",", "'block'", ",", "'data'", "]", "found", "=", "[", "i", "for", "i", "in", "devices", "if", "i", "in", "bluestore_devices", "]", "mlogger", ".", "error", "(", "\"Required devices (block and data) not present for bluestore\"", ")", "mlogger", ".", "error", "(", "'bluestore devices found: %s'", ",", "found", ")", "raise", "RuntimeError", "(", "'Unable to activate bluestore OSD due to missing devices'", ")" ]
https://github.com/ceph/ceph/blob/959663007321a369c83218414a29bd9dbc8bda3a/src/ceph-volume/ceph_volume/devices/simple/activate.py#L29-L71
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/urllib3/util/timeout.py
python
Timeout.read_timeout
(self)
Get the value for the read timeout. This assumes some time has elapsed in the connection timeout and computes the read timeout appropriately. If self.total is set, the read timeout is dependent on the amount of time taken by the connect timeout. If the connection time has not been established, a :exc:`~urllib3.exceptions.TimeoutStateError` will be raised. :return: Value to use for the read timeout. :rtype: int, float, :attr:`Timeout.DEFAULT_TIMEOUT` or None :raises urllib3.exceptions.TimeoutStateError: If :meth:`start_connect` has not yet been called on this object.
Get the value for the read timeout.
[ "Get", "the", "value", "for", "the", "read", "timeout", "." ]
def read_timeout(self): """Get the value for the read timeout. This assumes some time has elapsed in the connection timeout and computes the read timeout appropriately. If self.total is set, the read timeout is dependent on the amount of time taken by the connect timeout. If the connection time has not been established, a :exc:`~urllib3.exceptions.TimeoutStateError` will be raised. :return: Value to use for the read timeout. :rtype: int, float, :attr:`Timeout.DEFAULT_TIMEOUT` or None :raises urllib3.exceptions.TimeoutStateError: If :meth:`start_connect` has not yet been called on this object. """ if ( self.total is not None and self.total is not self.DEFAULT_TIMEOUT and self._read is not None and self._read is not self.DEFAULT_TIMEOUT ): # In case the connect timeout has not yet been established. if self._start_connect is None: return self._read return max(0, min(self.total - self.get_connect_duration(), self._read)) elif self.total is not None and self.total is not self.DEFAULT_TIMEOUT: return max(0, self.total - self.get_connect_duration()) else: return self._read
[ "def", "read_timeout", "(", "self", ")", ":", "if", "(", "self", ".", "total", "is", "not", "None", "and", "self", ".", "total", "is", "not", "self", ".", "DEFAULT_TIMEOUT", "and", "self", ".", "_read", "is", "not", "None", "and", "self", ".", "_read", "is", "not", "self", ".", "DEFAULT_TIMEOUT", ")", ":", "# In case the connect timeout has not yet been established.", "if", "self", ".", "_start_connect", "is", "None", ":", "return", "self", ".", "_read", "return", "max", "(", "0", ",", "min", "(", "self", ".", "total", "-", "self", ".", "get_connect_duration", "(", ")", ",", "self", ".", "_read", ")", ")", "elif", "self", ".", "total", "is", "not", "None", "and", "self", ".", "total", "is", "not", "self", ".", "DEFAULT_TIMEOUT", ":", "return", "max", "(", "0", ",", "self", ".", "total", "-", "self", ".", "get_connect_duration", "(", ")", ")", "else", ":", "return", "self", ".", "_read" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/urllib3/util/timeout.py#L477-L535
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/klampt/src/robotsim.py
python
TransformPoser.__init__
(self)
r""" __init__(TransformPoser self) -> TransformPoser
r""" __init__(TransformPoser self) -> TransformPoser
[ "r", "__init__", "(", "TransformPoser", "self", ")", "-", ">", "TransformPoser" ]
def __init__(self): r""" __init__(TransformPoser self) -> TransformPoser """ _robotsim.TransformPoser_swiginit(self, _robotsim.new_TransformPoser())
[ "def", "__init__", "(", "self", ")", ":", "_robotsim", ".", "TransformPoser_swiginit", "(", "self", ",", "_robotsim", ".", "new_TransformPoser", "(", ")", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/src/robotsim.py#L3544-L3550
wenwei202/caffe
f54a74abaf6951d8485cbdcfa1d74a4c37839466
scripts/cpp_lint.py
python
CheckBraces
(filename, clean_lines, linenum, error)
Looks for misplaced braces (e.g. at the end of line). Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found.
Looks for misplaced braces (e.g. at the end of line).
[ "Looks", "for", "misplaced", "braces", "(", "e", ".", "g", ".", "at", "the", "end", "of", "line", ")", "." ]
def CheckBraces(filename, clean_lines, linenum, error): """Looks for misplaced braces (e.g. at the end of line). Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # get rid of comments and strings if Match(r'\s*{\s*$', line): # We allow an open brace to start a line in the case where someone is using # braces in a block to explicitly create a new scope, which is commonly used # to control the lifetime of stack-allocated variables. Braces are also # used for brace initializers inside function calls. We don't detect this # perfectly: we just don't complain if the last non-whitespace character on # the previous non-blank line is ',', ';', ':', '(', '{', or '}', or if the # previous line starts a preprocessor block. prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0] if (not Search(r'[,;:}{(]\s*$', prevline) and not Match(r'\s*#', prevline)): error(filename, linenum, 'whitespace/braces', 4, '{ should almost always be at the end of the previous line') # An else clause should be on the same line as the preceding closing brace. if Match(r'\s*else\s*', line): prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0] if Match(r'\s*}\s*$', prevline): error(filename, linenum, 'whitespace/newline', 4, 'An else should appear on the same line as the preceding }') # If braces come on one side of an else, they should be on both. # However, we have to worry about "else if" that spans multiple lines! if Search(r'}\s*else[^{]*$', line) or Match(r'[^}]*else\s*{', line): if Search(r'}\s*else if([^{]*)$', line): # could be multi-line if # find the ( after the if pos = line.find('else if') pos = line.find('(', pos) if pos > 0: (endline, _, endpos) = CloseExpression(clean_lines, linenum, pos) if endline[endpos:].find('{') == -1: # must be brace after if error(filename, linenum, 'readability/braces', 5, 'If an else has a brace on one side, it should have it on both') else: # common case: else not followed by a multi-line if error(filename, linenum, 'readability/braces', 5, 'If an else has a brace on one side, it should have it on both') # Likewise, an else should never have the else clause on the same line if Search(r'\belse [^\s{]', line) and not Search(r'\belse if\b', line): error(filename, linenum, 'whitespace/newline', 4, 'Else clause should never be on same line as else (use 2 lines)') # In the same way, a do/while should never be on one line if Match(r'\s*do [^\s{]', line): error(filename, linenum, 'whitespace/newline', 4, 'do/while clauses should not be on a single line') # Block bodies should not be followed by a semicolon. Due to C++11 # brace initialization, there are more places where semicolons are # required than not, so we use a whitelist approach to check these # rather than a blacklist. These are the places where "};" should # be replaced by just "}": # 1. Some flavor of block following closing parenthesis: # for (;;) {}; # while (...) {}; # switch (...) {}; # Function(...) {}; # if (...) {}; # if (...) else if (...) {}; # # 2. else block: # if (...) else {}; # # 3. const member function: # Function(...) const {}; # # 4. Block following some statement: # x = 42; # {}; # # 5. Block at the beginning of a function: # Function(...) { # {}; # } # # Note that naively checking for the preceding "{" will also match # braces inside multi-dimensional arrays, but this is fine since # that expression will not contain semicolons. # # 6. Block following another block: # while (true) {} # {}; # # 7. End of namespaces: # namespace {}; # # These semicolons seems far more common than other kinds of # redundant semicolons, possibly due to people converting classes # to namespaces. For now we do not warn for this case. # # Try matching case 1 first. match = Match(r'^(.*\)\s*)\{', line) if match: # Matched closing parenthesis (case 1). Check the token before the # matching opening parenthesis, and don't warn if it looks like a # macro. This avoids these false positives: # - macro that defines a base class # - multi-line macro that defines a base class # - macro that defines the whole class-head # # But we still issue warnings for macros that we know are safe to # warn, specifically: # - TEST, TEST_F, TEST_P, MATCHER, MATCHER_P # - TYPED_TEST # - INTERFACE_DEF # - EXCLUSIVE_LOCKS_REQUIRED, SHARED_LOCKS_REQUIRED, LOCKS_EXCLUDED: # # We implement a whitelist of safe macros instead of a blacklist of # unsafe macros, even though the latter appears less frequently in # google code and would have been easier to implement. This is because # the downside for getting the whitelist wrong means some extra # semicolons, while the downside for getting the blacklist wrong # would result in compile errors. # # In addition to macros, we also don't want to warn on compound # literals. closing_brace_pos = match.group(1).rfind(')') opening_parenthesis = ReverseCloseExpression( clean_lines, linenum, closing_brace_pos) if opening_parenthesis[2] > -1: line_prefix = opening_parenthesis[0][0:opening_parenthesis[2]] macro = Search(r'\b([A-Z_]+)\s*$', line_prefix) if ((macro and macro.group(1) not in ( 'TEST', 'TEST_F', 'MATCHER', 'MATCHER_P', 'TYPED_TEST', 'EXCLUSIVE_LOCKS_REQUIRED', 'SHARED_LOCKS_REQUIRED', 'LOCKS_EXCLUDED', 'INTERFACE_DEF')) or Search(r'\s+=\s*$', line_prefix)): match = None else: # Try matching cases 2-3. match = Match(r'^(.*(?:else|\)\s*const)\s*)\{', line) if not match: # Try matching cases 4-6. These are always matched on separate lines. # # Note that we can't simply concatenate the previous line to the # current line and do a single match, otherwise we may output # duplicate warnings for the blank line case: # if (cond) { # // blank line # } prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0] if prevline and Search(r'[;{}]\s*$', prevline): match = Match(r'^(\s*)\{', line) # Check matching closing brace if match: (endline, endlinenum, endpos) = CloseExpression( clean_lines, linenum, len(match.group(1))) if endpos > -1 and Match(r'^\s*;', endline[endpos:]): # Current {} pair is eligible for semicolon check, and we have found # the redundant semicolon, output warning here. # # Note: because we are scanning forward for opening braces, and # outputting warnings for the matching closing brace, if there are # nested blocks with trailing semicolons, we will get the error # messages in reversed order. error(filename, endlinenum, 'readability/braces', 4, "You don't need a ; after a }")
[ "def", "CheckBraces", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "# get rid of comments and strings", "if", "Match", "(", "r'\\s*{\\s*$'", ",", "line", ")", ":", "# We allow an open brace to start a line in the case where someone is using", "# braces in a block to explicitly create a new scope, which is commonly used", "# to control the lifetime of stack-allocated variables. Braces are also", "# used for brace initializers inside function calls. We don't detect this", "# perfectly: we just don't complain if the last non-whitespace character on", "# the previous non-blank line is ',', ';', ':', '(', '{', or '}', or if the", "# previous line starts a preprocessor block.", "prevline", "=", "GetPreviousNonBlankLine", "(", "clean_lines", ",", "linenum", ")", "[", "0", "]", "if", "(", "not", "Search", "(", "r'[,;:}{(]\\s*$'", ",", "prevline", ")", "and", "not", "Match", "(", "r'\\s*#'", ",", "prevline", ")", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/braces'", ",", "4", ",", "'{ should almost always be at the end of the previous line'", ")", "# An else clause should be on the same line as the preceding closing brace.", "if", "Match", "(", "r'\\s*else\\s*'", ",", "line", ")", ":", "prevline", "=", "GetPreviousNonBlankLine", "(", "clean_lines", ",", "linenum", ")", "[", "0", "]", "if", "Match", "(", "r'\\s*}\\s*$'", ",", "prevline", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/newline'", ",", "4", ",", "'An else should appear on the same line as the preceding }'", ")", "# If braces come on one side of an else, they should be on both.", "# However, we have to worry about \"else if\" that spans multiple lines!", "if", "Search", "(", "r'}\\s*else[^{]*$'", ",", "line", ")", "or", "Match", "(", "r'[^}]*else\\s*{'", ",", "line", ")", ":", "if", "Search", "(", "r'}\\s*else if([^{]*)$'", ",", "line", ")", ":", "# could be multi-line if", "# find the ( after the if", "pos", "=", "line", ".", "find", "(", "'else if'", ")", "pos", "=", "line", ".", "find", "(", "'('", ",", "pos", ")", "if", "pos", ">", "0", ":", "(", "endline", ",", "_", ",", "endpos", ")", "=", "CloseExpression", "(", "clean_lines", ",", "linenum", ",", "pos", ")", "if", "endline", "[", "endpos", ":", "]", ".", "find", "(", "'{'", ")", "==", "-", "1", ":", "# must be brace after if", "error", "(", "filename", ",", "linenum", ",", "'readability/braces'", ",", "5", ",", "'If an else has a brace on one side, it should have it on both'", ")", "else", ":", "# common case: else not followed by a multi-line if", "error", "(", "filename", ",", "linenum", ",", "'readability/braces'", ",", "5", ",", "'If an else has a brace on one side, it should have it on both'", ")", "# Likewise, an else should never have the else clause on the same line", "if", "Search", "(", "r'\\belse [^\\s{]'", ",", "line", ")", "and", "not", "Search", "(", "r'\\belse if\\b'", ",", "line", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/newline'", ",", "4", ",", "'Else clause should never be on same line as else (use 2 lines)'", ")", "# In the same way, a do/while should never be on one line", "if", "Match", "(", "r'\\s*do [^\\s{]'", ",", "line", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/newline'", ",", "4", ",", "'do/while clauses should not be on a single line'", ")", "# Block bodies should not be followed by a semicolon. Due to C++11", "# brace initialization, there are more places where semicolons are", "# required than not, so we use a whitelist approach to check these", "# rather than a blacklist. These are the places where \"};\" should", "# be replaced by just \"}\":", "# 1. Some flavor of block following closing parenthesis:", "# for (;;) {};", "# while (...) {};", "# switch (...) {};", "# Function(...) {};", "# if (...) {};", "# if (...) else if (...) {};", "#", "# 2. else block:", "# if (...) else {};", "#", "# 3. const member function:", "# Function(...) const {};", "#", "# 4. Block following some statement:", "# x = 42;", "# {};", "#", "# 5. Block at the beginning of a function:", "# Function(...) {", "# {};", "# }", "#", "# Note that naively checking for the preceding \"{\" will also match", "# braces inside multi-dimensional arrays, but this is fine since", "# that expression will not contain semicolons.", "#", "# 6. Block following another block:", "# while (true) {}", "# {};", "#", "# 7. End of namespaces:", "# namespace {};", "#", "# These semicolons seems far more common than other kinds of", "# redundant semicolons, possibly due to people converting classes", "# to namespaces. For now we do not warn for this case.", "#", "# Try matching case 1 first.", "match", "=", "Match", "(", "r'^(.*\\)\\s*)\\{'", ",", "line", ")", "if", "match", ":", "# Matched closing parenthesis (case 1). Check the token before the", "# matching opening parenthesis, and don't warn if it looks like a", "# macro. This avoids these false positives:", "# - macro that defines a base class", "# - multi-line macro that defines a base class", "# - macro that defines the whole class-head", "#", "# But we still issue warnings for macros that we know are safe to", "# warn, specifically:", "# - TEST, TEST_F, TEST_P, MATCHER, MATCHER_P", "# - TYPED_TEST", "# - INTERFACE_DEF", "# - EXCLUSIVE_LOCKS_REQUIRED, SHARED_LOCKS_REQUIRED, LOCKS_EXCLUDED:", "#", "# We implement a whitelist of safe macros instead of a blacklist of", "# unsafe macros, even though the latter appears less frequently in", "# google code and would have been easier to implement. This is because", "# the downside for getting the whitelist wrong means some extra", "# semicolons, while the downside for getting the blacklist wrong", "# would result in compile errors.", "#", "# In addition to macros, we also don't want to warn on compound", "# literals.", "closing_brace_pos", "=", "match", ".", "group", "(", "1", ")", ".", "rfind", "(", "')'", ")", "opening_parenthesis", "=", "ReverseCloseExpression", "(", "clean_lines", ",", "linenum", ",", "closing_brace_pos", ")", "if", "opening_parenthesis", "[", "2", "]", ">", "-", "1", ":", "line_prefix", "=", "opening_parenthesis", "[", "0", "]", "[", "0", ":", "opening_parenthesis", "[", "2", "]", "]", "macro", "=", "Search", "(", "r'\\b([A-Z_]+)\\s*$'", ",", "line_prefix", ")", "if", "(", "(", "macro", "and", "macro", ".", "group", "(", "1", ")", "not", "in", "(", "'TEST'", ",", "'TEST_F'", ",", "'MATCHER'", ",", "'MATCHER_P'", ",", "'TYPED_TEST'", ",", "'EXCLUSIVE_LOCKS_REQUIRED'", ",", "'SHARED_LOCKS_REQUIRED'", ",", "'LOCKS_EXCLUDED'", ",", "'INTERFACE_DEF'", ")", ")", "or", "Search", "(", "r'\\s+=\\s*$'", ",", "line_prefix", ")", ")", ":", "match", "=", "None", "else", ":", "# Try matching cases 2-3.", "match", "=", "Match", "(", "r'^(.*(?:else|\\)\\s*const)\\s*)\\{'", ",", "line", ")", "if", "not", "match", ":", "# Try matching cases 4-6. These are always matched on separate lines.", "#", "# Note that we can't simply concatenate the previous line to the", "# current line and do a single match, otherwise we may output", "# duplicate warnings for the blank line case:", "# if (cond) {", "# // blank line", "# }", "prevline", "=", "GetPreviousNonBlankLine", "(", "clean_lines", ",", "linenum", ")", "[", "0", "]", "if", "prevline", "and", "Search", "(", "r'[;{}]\\s*$'", ",", "prevline", ")", ":", "match", "=", "Match", "(", "r'^(\\s*)\\{'", ",", "line", ")", "# Check matching closing brace", "if", "match", ":", "(", "endline", ",", "endlinenum", ",", "endpos", ")", "=", "CloseExpression", "(", "clean_lines", ",", "linenum", ",", "len", "(", "match", ".", "group", "(", "1", ")", ")", ")", "if", "endpos", ">", "-", "1", "and", "Match", "(", "r'^\\s*;'", ",", "endline", "[", "endpos", ":", "]", ")", ":", "# Current {} pair is eligible for semicolon check, and we have found", "# the redundant semicolon, output warning here.", "#", "# Note: because we are scanning forward for opening braces, and", "# outputting warnings for the matching closing brace, if there are", "# nested blocks with trailing semicolons, we will get the error", "# messages in reversed order.", "error", "(", "filename", ",", "endlinenum", ",", "'readability/braces'", ",", "4", ",", "\"You don't need a ; after a }\"", ")" ]
https://github.com/wenwei202/caffe/blob/f54a74abaf6951d8485cbdcfa1d74a4c37839466/scripts/cpp_lint.py#L3069-L3240
Polidea/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py
python
SBWatchpoint.GetHardwareIndex
(self)
return _lldb.SBWatchpoint_GetHardwareIndex(self)
GetHardwareIndex(self) -> int32_t With -1 representing an invalid hardware index.
GetHardwareIndex(self) -> int32_t
[ "GetHardwareIndex", "(", "self", ")", "-", ">", "int32_t" ]
def GetHardwareIndex(self): """ GetHardwareIndex(self) -> int32_t With -1 representing an invalid hardware index. """ return _lldb.SBWatchpoint_GetHardwareIndex(self)
[ "def", "GetHardwareIndex", "(", "self", ")", ":", "return", "_lldb", ".", "SBWatchpoint_GetHardwareIndex", "(", "self", ")" ]
https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L12602-L12608
freesurfer/freesurfer
6dbe527d43ffa611acb2cd112e9469f9bfec8e36
python/freesurfer/utils/legacy.py
python
check_subjdirs
()
return os.environ['SUBJECTS_DIR']
Quit if SUBJECTS_DIR is not defined as an environment variable. This is not a function which returns a boolean. Execution is stopped if not found. If found, returns the SUBJECTS_DIR
Quit if SUBJECTS_DIR is not defined as an environment variable. This is not a function which returns a boolean. Execution is stopped if not found. If found, returns the SUBJECTS_DIR
[ "Quit", "if", "SUBJECTS_DIR", "is", "not", "defined", "as", "an", "environment", "variable", ".", "This", "is", "not", "a", "function", "which", "returns", "a", "boolean", ".", "Execution", "is", "stopped", "if", "not", "found", ".", "If", "found", "returns", "the", "SUBJECTS_DIR" ]
def check_subjdirs(): """ Quit if SUBJECTS_DIR is not defined as an environment variable. This is not a function which returns a boolean. Execution is stopped if not found. If found, returns the SUBJECTS_DIR """ if 'SUBJECTS_DIR' not in os.environ: print('ERROR: SUBJECTS_DIR environment variable not defined!') sys.exit(1) return os.environ['SUBJECTS_DIR']
[ "def", "check_subjdirs", "(", ")", ":", "if", "'SUBJECTS_DIR'", "not", "in", "os", ".", "environ", ":", "print", "(", "'ERROR: SUBJECTS_DIR environment variable not defined!'", ")", "sys", ".", "exit", "(", "1", ")", "return", "os", ".", "environ", "[", "'SUBJECTS_DIR'", "]" ]
https://github.com/freesurfer/freesurfer/blob/6dbe527d43ffa611acb2cd112e9469f9bfec8e36/python/freesurfer/utils/legacy.py#L40-L49
smilehao/xlua-framework
a03801538be2b0e92d39332d445b22caca1ef61f
ConfigData/trunk/tools/protobuf-2.5.0/protobuf-2.5.0/python/build/lib/google/protobuf/text_format.py
python
_Tokenizer._ConsumeSingleByteString
(self)
return result
Consume one token of a string literal. String literals (whether bytes or text) can come in multiple adjacent tokens which are automatically concatenated, like in C or Python. This method only consumes one token.
Consume one token of a string literal.
[ "Consume", "one", "token", "of", "a", "string", "literal", "." ]
def _ConsumeSingleByteString(self): """Consume one token of a string literal. String literals (whether bytes or text) can come in multiple adjacent tokens which are automatically concatenated, like in C or Python. This method only consumes one token. """ text = self.token if len(text) < 1 or text[0] not in ('\'', '"'): raise self._ParseError('Expected string.') if len(text) < 2 or text[-1] != text[0]: raise self._ParseError('String missing ending quote.') try: result = _CUnescape(text[1:-1]) except ValueError, e: raise self._ParseError(str(e)) self.NextToken() return result
[ "def", "_ConsumeSingleByteString", "(", "self", ")", ":", "text", "=", "self", ".", "token", "if", "len", "(", "text", ")", "<", "1", "or", "text", "[", "0", "]", "not", "in", "(", "'\\''", ",", "'\"'", ")", ":", "raise", "self", ".", "_ParseError", "(", "'Expected string.'", ")", "if", "len", "(", "text", ")", "<", "2", "or", "text", "[", "-", "1", "]", "!=", "text", "[", "0", "]", ":", "raise", "self", ".", "_ParseError", "(", "'String missing ending quote.'", ")", "try", ":", "result", "=", "_CUnescape", "(", "text", "[", "1", ":", "-", "1", "]", ")", "except", "ValueError", ",", "e", ":", "raise", "self", ".", "_ParseError", "(", "str", "(", "e", ")", ")", "self", ".", "NextToken", "(", ")", "return", "result" ]
https://github.com/smilehao/xlua-framework/blob/a03801538be2b0e92d39332d445b22caca1ef61f/ConfigData/trunk/tools/protobuf-2.5.0/protobuf-2.5.0/python/build/lib/google/protobuf/text_format.py#L520-L539
mongodb/mongo
d8ff665343ad29cf286ee2cf4a1960d29371937b
buildscripts/idl/idl/binder.py
python
_bind_command_type
(ctxt, parsed_spec, command)
return ast_field
Bind the type field in a command as the first field.
Bind the type field in a command as the first field.
[ "Bind", "the", "type", "field", "in", "a", "command", "as", "the", "first", "field", "." ]
def _bind_command_type(ctxt, parsed_spec, command): # type: (errors.ParserContext, syntax.IDLSpec, syntax.Command) -> ast.Field """Bind the type field in a command as the first field.""" # pylint: disable=too-many-branches,too-many-statements ast_field = ast.Field(command.file_name, command.line, command.column) ast_field.name = command.name ast_field.description = command.description ast_field.optional = False ast_field.supports_doc_sequence = False ast_field.serialize_op_msg_request_only = False ast_field.constructed = False ast_field.cpp_name = "CommandParameter" # Validate naming restrictions if ast_field.name.startswith("array<"): ctxt.add_array_not_valid_error(ast_field, "field", ast_field.name) # Resolve the command type as a field syntax_symbol = parsed_spec.symbols.resolve_field_type(ctxt, command, command.name, command.type) if syntax_symbol is None: return None if isinstance(syntax_symbol, syntax.Command): ctxt.add_bad_command_as_field_error(ast_field, command.type.debug_string()) return None assert not isinstance(syntax_symbol, syntax.Enum) base_type = (syntax_symbol.element_type if isinstance(syntax_symbol, syntax.ArrayType) else syntax_symbol) # Copy over only the needed information if this is a struct or a type. if isinstance(base_type, syntax.Struct): _bind_struct_field(ctxt, ast_field, syntax_symbol) elif isinstance(base_type, syntax.VariantType): # Arrays of variants aren't supported for now. assert isinstance(syntax_symbol, syntax.VariantType) _bind_variant_field(ctxt, ast_field, cast(syntax.VariantType, syntax_symbol)) else: assert isinstance(base_type, syntax.Type) idltype = cast(syntax.Type, base_type) ast_field.type = _bind_type(idltype) ast_field.type.is_array = isinstance(syntax_symbol, syntax.ArrayType) ast_field.default = idltype.default # Validate merged type _validate_type_properties(ctxt, ast_field.type, "command.type") # Validate merged type _validate_field_properties(ctxt, ast_field) return ast_field
[ "def", "_bind_command_type", "(", "ctxt", ",", "parsed_spec", ",", "command", ")", ":", "# type: (errors.ParserContext, syntax.IDLSpec, syntax.Command) -> ast.Field", "# pylint: disable=too-many-branches,too-many-statements", "ast_field", "=", "ast", ".", "Field", "(", "command", ".", "file_name", ",", "command", ".", "line", ",", "command", ".", "column", ")", "ast_field", ".", "name", "=", "command", ".", "name", "ast_field", ".", "description", "=", "command", ".", "description", "ast_field", ".", "optional", "=", "False", "ast_field", ".", "supports_doc_sequence", "=", "False", "ast_field", ".", "serialize_op_msg_request_only", "=", "False", "ast_field", ".", "constructed", "=", "False", "ast_field", ".", "cpp_name", "=", "\"CommandParameter\"", "# Validate naming restrictions", "if", "ast_field", ".", "name", ".", "startswith", "(", "\"array<\"", ")", ":", "ctxt", ".", "add_array_not_valid_error", "(", "ast_field", ",", "\"field\"", ",", "ast_field", ".", "name", ")", "# Resolve the command type as a field", "syntax_symbol", "=", "parsed_spec", ".", "symbols", ".", "resolve_field_type", "(", "ctxt", ",", "command", ",", "command", ".", "name", ",", "command", ".", "type", ")", "if", "syntax_symbol", "is", "None", ":", "return", "None", "if", "isinstance", "(", "syntax_symbol", ",", "syntax", ".", "Command", ")", ":", "ctxt", ".", "add_bad_command_as_field_error", "(", "ast_field", ",", "command", ".", "type", ".", "debug_string", "(", ")", ")", "return", "None", "assert", "not", "isinstance", "(", "syntax_symbol", ",", "syntax", ".", "Enum", ")", "base_type", "=", "(", "syntax_symbol", ".", "element_type", "if", "isinstance", "(", "syntax_symbol", ",", "syntax", ".", "ArrayType", ")", "else", "syntax_symbol", ")", "# Copy over only the needed information if this is a struct or a type.", "if", "isinstance", "(", "base_type", ",", "syntax", ".", "Struct", ")", ":", "_bind_struct_field", "(", "ctxt", ",", "ast_field", ",", "syntax_symbol", ")", "elif", "isinstance", "(", "base_type", ",", "syntax", ".", "VariantType", ")", ":", "# Arrays of variants aren't supported for now.", "assert", "isinstance", "(", "syntax_symbol", ",", "syntax", ".", "VariantType", ")", "_bind_variant_field", "(", "ctxt", ",", "ast_field", ",", "cast", "(", "syntax", ".", "VariantType", ",", "syntax_symbol", ")", ")", "else", ":", "assert", "isinstance", "(", "base_type", ",", "syntax", ".", "Type", ")", "idltype", "=", "cast", "(", "syntax", ".", "Type", ",", "base_type", ")", "ast_field", ".", "type", "=", "_bind_type", "(", "idltype", ")", "ast_field", ".", "type", ".", "is_array", "=", "isinstance", "(", "syntax_symbol", ",", "syntax", ".", "ArrayType", ")", "ast_field", ".", "default", "=", "idltype", ".", "default", "# Validate merged type", "_validate_type_properties", "(", "ctxt", ",", "ast_field", ".", "type", ",", "\"command.type\"", ")", "# Validate merged type", "_validate_field_properties", "(", "ctxt", ",", "ast_field", ")", "return", "ast_field" ]
https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/idl/idl/binder.py#L473-L527
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/imaplib.py
python
IMAP4.socket
(self)
return self.sock
Return socket instance used to connect to IMAP4 server. socket = <instance>.socket()
Return socket instance used to connect to IMAP4 server.
[ "Return", "socket", "instance", "used", "to", "connect", "to", "IMAP4", "server", "." ]
def socket(self): """Return socket instance used to connect to IMAP4 server. socket = <instance>.socket() """ return self.sock
[ "def", "socket", "(", "self", ")", ":", "return", "self", ".", "sock" ]
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/imaplib.py#L254-L259
polyworld/polyworld
eb7e6bbc82fe77ba79e3bc48c3da2ad8c8238c26
scripts/networkx_extensions.py
python
characteristic_path_length
(G, weighted=False)
Return the characteristic path length. Parameters ---------- G : NetworkX graph weighted : bool, optional, default=False If true use edge weights on path. If False, use 1 as the edge distance. Examples -------- >>> G=nx.path_graph(4) >>> print nx.average_shortest_path_length(G) 1.25
Return the characteristic path length.
[ "Return", "the", "characteristic", "path", "length", "." ]
def characteristic_path_length(G, weighted=False): """ Return the characteristic path length. Parameters ---------- G : NetworkX graph weighted : bool, optional, default=False If true use edge weights on path. If False, use 1 as the edge distance. Examples -------- >>> G=nx.path_graph(4) >>> print nx.average_shortest_path_length(G) 1.25 """ if weighted: path_length = nx.single_source_dijkstra_path_length else: path_length = nx.single_source_shortest_path_length num_connected_nodes = 0 avg = 0.0 for n in G: l = path_length(G,n).values() if len(l) > 1: # > 1 because NetworkX includes a zero-length self-connection in this list num_connected_nodes += 1 avg += float(sum(l)) / (len(l)-1) if num_connected_nodes > 0: return avg / num_connected_nodes else: return float('inf')
[ "def", "characteristic_path_length", "(", "G", ",", "weighted", "=", "False", ")", ":", "if", "weighted", ":", "path_length", "=", "nx", ".", "single_source_dijkstra_path_length", "else", ":", "path_length", "=", "nx", ".", "single_source_shortest_path_length", "num_connected_nodes", "=", "0", "avg", "=", "0.0", "for", "n", "in", "G", ":", "l", "=", "path_length", "(", "G", ",", "n", ")", ".", "values", "(", ")", "if", "len", "(", "l", ")", ">", "1", ":", "# > 1 because NetworkX includes a zero-length self-connection in this list", "num_connected_nodes", "+=", "1", "avg", "+=", "float", "(", "sum", "(", "l", ")", ")", "/", "(", "len", "(", "l", ")", "-", "1", ")", "if", "num_connected_nodes", ">", "0", ":", "return", "avg", "/", "num_connected_nodes", "else", ":", "return", "float", "(", "'inf'", ")" ]
https://github.com/polyworld/polyworld/blob/eb7e6bbc82fe77ba79e3bc48c3da2ad8c8238c26/scripts/networkx_extensions.py#L137-L172
qboticslabs/mastering_ros
d83e78f30acc45b0f18522c1d5fae3a7f52974b9
chapter_4_codes/seven_dof_arm_gazebo/scripts/pick_and_place.py
python
Pick_Place._create_place_goal
(self, group, target, places)
return goal
Create a MoveIt! PlaceGoal
Create a MoveIt! PlaceGoal
[ "Create", "a", "MoveIt!", "PlaceGoal" ]
def _create_place_goal(self, group, target, places): """ Create a MoveIt! PlaceGoal """ # Create goal: goal = PlaceGoal() goal.group_name = group goal.attached_object_name = target goal.place_locations.extend(places) # Configure goal planning options: goal.allowed_planning_time = 7.0 goal.planning_options.planning_scene_diff.is_diff = True goal.planning_options.planning_scene_diff.robot_state.is_diff = True goal.planning_options.plan_only = False goal.planning_options.replan = True goal.planning_options.replan_attempts = 20 return goal
[ "def", "_create_place_goal", "(", "self", ",", "group", ",", "target", ",", "places", ")", ":", "# Create goal:", "goal", "=", "PlaceGoal", "(", ")", "goal", ".", "group_name", "=", "group", "goal", ".", "attached_object_name", "=", "target", "goal", ".", "place_locations", ".", "extend", "(", "places", ")", "# Configure goal planning options:", "goal", ".", "allowed_planning_time", "=", "7.0", "goal", ".", "planning_options", ".", "planning_scene_diff", ".", "is_diff", "=", "True", "goal", ".", "planning_options", ".", "planning_scene_diff", ".", "robot_state", ".", "is_diff", "=", "True", "goal", ".", "planning_options", ".", "plan_only", "=", "False", "goal", ".", "planning_options", ".", "replan", "=", "True", "goal", ".", "planning_options", ".", "replan_attempts", "=", "20", "return", "goal" ]
https://github.com/qboticslabs/mastering_ros/blob/d83e78f30acc45b0f18522c1d5fae3a7f52974b9/chapter_4_codes/seven_dof_arm_gazebo/scripts/pick_and_place.py#L273-L295
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/_pydecimal.py
python
Context.quantize
(self, a, b)
return a.quantize(b, context=self)
Returns a value equal to 'a' (rounded), having the exponent of 'b'. The coefficient of the result is derived from that of the left-hand operand. It may be rounded using the current rounding setting (if the exponent is being increased), multiplied by a positive power of ten (if the exponent is being decreased), or is unchanged (if the exponent is already equal to that of the right-hand operand). Unlike other operations, if the length of the coefficient after the quantize operation would be greater than precision then an Invalid operation condition is raised. This guarantees that, unless there is an error condition, the exponent of the result of a quantize is always equal to that of the right-hand operand. Also unlike other operations, quantize will never raise Underflow, even if the result is subnormal and inexact. >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001')) Decimal('2.170') >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01')) Decimal('2.17') >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1')) Decimal('2.2') >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0')) Decimal('2') >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1')) Decimal('0E+1') >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity')) Decimal('-Infinity') >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity')) Decimal('NaN') >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1')) Decimal('-0') >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5')) Decimal('-0E+5') >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2')) Decimal('NaN') >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2')) Decimal('NaN') >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1')) Decimal('217.0') >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0')) Decimal('217') >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1')) Decimal('2.2E+2') >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2')) Decimal('2E+2') >>> ExtendedContext.quantize(1, 2) Decimal('1') >>> ExtendedContext.quantize(Decimal(1), 2) Decimal('1') >>> ExtendedContext.quantize(1, Decimal(2)) Decimal('1')
Returns a value equal to 'a' (rounded), having the exponent of 'b'.
[ "Returns", "a", "value", "equal", "to", "a", "(", "rounded", ")", "having", "the", "exponent", "of", "b", "." ]
def quantize(self, a, b): """Returns a value equal to 'a' (rounded), having the exponent of 'b'. The coefficient of the result is derived from that of the left-hand operand. It may be rounded using the current rounding setting (if the exponent is being increased), multiplied by a positive power of ten (if the exponent is being decreased), or is unchanged (if the exponent is already equal to that of the right-hand operand). Unlike other operations, if the length of the coefficient after the quantize operation would be greater than precision then an Invalid operation condition is raised. This guarantees that, unless there is an error condition, the exponent of the result of a quantize is always equal to that of the right-hand operand. Also unlike other operations, quantize will never raise Underflow, even if the result is subnormal and inexact. >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001')) Decimal('2.170') >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01')) Decimal('2.17') >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1')) Decimal('2.2') >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0')) Decimal('2') >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1')) Decimal('0E+1') >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity')) Decimal('-Infinity') >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity')) Decimal('NaN') >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1')) Decimal('-0') >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5')) Decimal('-0E+5') >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2')) Decimal('NaN') >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2')) Decimal('NaN') >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1')) Decimal('217.0') >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0')) Decimal('217') >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1')) Decimal('2.2E+2') >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2')) Decimal('2E+2') >>> ExtendedContext.quantize(1, 2) Decimal('1') >>> ExtendedContext.quantize(Decimal(1), 2) Decimal('1') >>> ExtendedContext.quantize(1, Decimal(2)) Decimal('1') """ a = _convert_other(a, raiseit=True) return a.quantize(b, context=self)
[ "def", "quantize", "(", "self", ",", "a", ",", "b", ")", ":", "a", "=", "_convert_other", "(", "a", ",", "raiseit", "=", "True", ")", "return", "a", ".", "quantize", "(", "b", ",", "context", "=", "self", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/_pydecimal.py#L5221-L5277
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/external/bazel_tools/third_party/py/gflags/__init__.py
python
_WriteSimpleXMLElement
(outfile, name, value, indent)
Writes a simple XML element. Args: outfile: File object we write the XML element to. name: A string, the name of XML element. value: A Python object, whose string representation will be used as the value of the XML element. indent: A string, prepended to each line of generated output.
Writes a simple XML element.
[ "Writes", "a", "simple", "XML", "element", "." ]
def _WriteSimpleXMLElement(outfile, name, value, indent): """Writes a simple XML element. Args: outfile: File object we write the XML element to. name: A string, the name of XML element. value: A Python object, whose string representation will be used as the value of the XML element. indent: A string, prepended to each line of generated output. """ value_str = _StrOrUnicode(value) if isinstance(value, bool): # Display boolean values as the C++ flag library does: no caps. value_str = value_str.lower() safe_value_str = _MakeXMLSafe(value_str) outfile.write('%s<%s>%s</%s>\n' % (indent, name, safe_value_str, name))
[ "def", "_WriteSimpleXMLElement", "(", "outfile", ",", "name", ",", "value", ",", "indent", ")", ":", "value_str", "=", "_StrOrUnicode", "(", "value", ")", "if", "isinstance", "(", "value", ",", "bool", ")", ":", "# Display boolean values as the C++ flag library does: no caps.", "value_str", "=", "value_str", ".", "lower", "(", ")", "safe_value_str", "=", "_MakeXMLSafe", "(", "value_str", ")", "outfile", ".", "write", "(", "'%s<%s>%s</%s>\\n'", "%", "(", "indent", ",", "name", ",", "safe_value_str", ",", "name", ")", ")" ]
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/external/bazel_tools/third_party/py/gflags/__init__.py#L1789-L1804
naver/sling
5671cd445a2caae0b4dd0332299e4cfede05062c
webkit/Tools/Scripts/webkitpy/thirdparty/mod_pywebsocket/common.py
python
format_extensions
(extension_list)
return ', '.join(formatted_extension_list)
Formats a list of ExtensionParameter objects.
Formats a list of ExtensionParameter objects.
[ "Formats", "a", "list", "of", "ExtensionParameter", "objects", "." ]
def format_extensions(extension_list): """Formats a list of ExtensionParameter objects.""" formatted_extension_list = [] for extension in extension_list: formatted_extension_list.append(format_extension(extension)) return ', '.join(formatted_extension_list)
[ "def", "format_extensions", "(", "extension_list", ")", ":", "formatted_extension_list", "=", "[", "]", "for", "extension", "in", "extension_list", ":", "formatted_extension_list", ".", "append", "(", "format_extension", "(", "extension", ")", ")", "return", "', '", ".", "join", "(", "formatted_extension_list", ")" ]
https://github.com/naver/sling/blob/5671cd445a2caae0b4dd0332299e4cfede05062c/webkit/Tools/Scripts/webkitpy/thirdparty/mod_pywebsocket/common.py#L298-L304
oracle/graaljs
36a56e8e993d45fc40939a3a4d9c0c24990720f1
graal-nodejs/tools/gyp/pylib/gyp/input.py
python
TurnIntIntoStrInDict
(the_dict)
Given dict the_dict, recursively converts all integers into strings.
Given dict the_dict, recursively converts all integers into strings.
[ "Given", "dict", "the_dict", "recursively", "converts", "all", "integers", "into", "strings", "." ]
def TurnIntIntoStrInDict(the_dict): """Given dict the_dict, recursively converts all integers into strings. """ # Use items instead of iteritems because there's no need to try to look at # reinserted keys and their associated values. for k, v in the_dict.items(): if type(v) is int: v = str(v) the_dict[k] = v elif type(v) is dict: TurnIntIntoStrInDict(v) elif type(v) is list: TurnIntIntoStrInList(v) if type(k) is int: del the_dict[k] the_dict[str(k)] = v
[ "def", "TurnIntIntoStrInDict", "(", "the_dict", ")", ":", "# Use items instead of iteritems because there's no need to try to look at", "# reinserted keys and their associated values.", "for", "k", ",", "v", "in", "the_dict", ".", "items", "(", ")", ":", "if", "type", "(", "v", ")", "is", "int", ":", "v", "=", "str", "(", "v", ")", "the_dict", "[", "k", "]", "=", "v", "elif", "type", "(", "v", ")", "is", "dict", ":", "TurnIntIntoStrInDict", "(", "v", ")", "elif", "type", "(", "v", ")", "is", "list", ":", "TurnIntIntoStrInList", "(", "v", ")", "if", "type", "(", "k", ")", "is", "int", ":", "del", "the_dict", "[", "k", "]", "the_dict", "[", "str", "(", "k", ")", "]", "=", "v" ]
https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/tools/gyp/pylib/gyp/input.py#L2862-L2878
google-ar/WebARonTango
e86965d2cbc652156b480e0fcf77c716745578cd
chromium/src/gpu/command_buffer/build_gles2_cmd_buffer.py
python
Argument.GetArgAccessor
(self)
return self.name
Returns the name of the accessor for the argument within the struct.
Returns the name of the accessor for the argument within the struct.
[ "Returns", "the", "name", "of", "the", "accessor", "for", "the", "argument", "within", "the", "struct", "." ]
def GetArgAccessor(self): """Returns the name of the accessor for the argument within the struct.""" return self.name
[ "def", "GetArgAccessor", "(", "self", ")", ":", "return", "self", ".", "name" ]
https://github.com/google-ar/WebARonTango/blob/e86965d2cbc652156b480e0fcf77c716745578cd/chromium/src/gpu/command_buffer/build_gles2_cmd_buffer.py#L8587-L8589
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py3/pandas/core/arrays/datetimes.py
python
DatetimeArray.tz_convert
(self, tz)
return self._simple_new(self._ndarray, dtype=dtype, freq=self.freq)
Convert tz-aware Datetime Array/Index from one time zone to another. Parameters ---------- tz : str, pytz.timezone, dateutil.tz.tzfile or None Time zone for time. Corresponding timestamps would be converted to this time zone of the Datetime Array/Index. A `tz` of None will convert to UTC and remove the timezone information. Returns ------- Array or Index Raises ------ TypeError If Datetime Array/Index is tz-naive. See Also -------- DatetimeIndex.tz : A timezone that has a variable offset from UTC. DatetimeIndex.tz_localize : Localize tz-naive DatetimeIndex to a given time zone, or remove timezone from a tz-aware DatetimeIndex. Examples -------- With the `tz` parameter, we can change the DatetimeIndex to other time zones: >>> dti = pd.date_range(start='2014-08-01 09:00', ... freq='H', periods=3, tz='Europe/Berlin') >>> dti DatetimeIndex(['2014-08-01 09:00:00+02:00', '2014-08-01 10:00:00+02:00', '2014-08-01 11:00:00+02:00'], dtype='datetime64[ns, Europe/Berlin]', freq='H') >>> dti.tz_convert('US/Central') DatetimeIndex(['2014-08-01 02:00:00-05:00', '2014-08-01 03:00:00-05:00', '2014-08-01 04:00:00-05:00'], dtype='datetime64[ns, US/Central]', freq='H') With the ``tz=None``, we can remove the timezone (after converting to UTC if necessary): >>> dti = pd.date_range(start='2014-08-01 09:00', freq='H', ... periods=3, tz='Europe/Berlin') >>> dti DatetimeIndex(['2014-08-01 09:00:00+02:00', '2014-08-01 10:00:00+02:00', '2014-08-01 11:00:00+02:00'], dtype='datetime64[ns, Europe/Berlin]', freq='H') >>> dti.tz_convert(None) DatetimeIndex(['2014-08-01 07:00:00', '2014-08-01 08:00:00', '2014-08-01 09:00:00'], dtype='datetime64[ns]', freq='H')
Convert tz-aware Datetime Array/Index from one time zone to another.
[ "Convert", "tz", "-", "aware", "Datetime", "Array", "/", "Index", "from", "one", "time", "zone", "to", "another", "." ]
def tz_convert(self, tz) -> DatetimeArray: """ Convert tz-aware Datetime Array/Index from one time zone to another. Parameters ---------- tz : str, pytz.timezone, dateutil.tz.tzfile or None Time zone for time. Corresponding timestamps would be converted to this time zone of the Datetime Array/Index. A `tz` of None will convert to UTC and remove the timezone information. Returns ------- Array or Index Raises ------ TypeError If Datetime Array/Index is tz-naive. See Also -------- DatetimeIndex.tz : A timezone that has a variable offset from UTC. DatetimeIndex.tz_localize : Localize tz-naive DatetimeIndex to a given time zone, or remove timezone from a tz-aware DatetimeIndex. Examples -------- With the `tz` parameter, we can change the DatetimeIndex to other time zones: >>> dti = pd.date_range(start='2014-08-01 09:00', ... freq='H', periods=3, tz='Europe/Berlin') >>> dti DatetimeIndex(['2014-08-01 09:00:00+02:00', '2014-08-01 10:00:00+02:00', '2014-08-01 11:00:00+02:00'], dtype='datetime64[ns, Europe/Berlin]', freq='H') >>> dti.tz_convert('US/Central') DatetimeIndex(['2014-08-01 02:00:00-05:00', '2014-08-01 03:00:00-05:00', '2014-08-01 04:00:00-05:00'], dtype='datetime64[ns, US/Central]', freq='H') With the ``tz=None``, we can remove the timezone (after converting to UTC if necessary): >>> dti = pd.date_range(start='2014-08-01 09:00', freq='H', ... periods=3, tz='Europe/Berlin') >>> dti DatetimeIndex(['2014-08-01 09:00:00+02:00', '2014-08-01 10:00:00+02:00', '2014-08-01 11:00:00+02:00'], dtype='datetime64[ns, Europe/Berlin]', freq='H') >>> dti.tz_convert(None) DatetimeIndex(['2014-08-01 07:00:00', '2014-08-01 08:00:00', '2014-08-01 09:00:00'], dtype='datetime64[ns]', freq='H') """ tz = timezones.maybe_get_tz(tz) if self.tz is None: # tz naive, use tz_localize raise TypeError( "Cannot convert tz-naive timestamps, use tz_localize to localize" ) # No conversion since timestamps are all UTC to begin with dtype = tz_to_dtype(tz) return self._simple_new(self._ndarray, dtype=dtype, freq=self.freq)
[ "def", "tz_convert", "(", "self", ",", "tz", ")", "->", "DatetimeArray", ":", "tz", "=", "timezones", ".", "maybe_get_tz", "(", "tz", ")", "if", "self", ".", "tz", "is", "None", ":", "# tz naive, use tz_localize", "raise", "TypeError", "(", "\"Cannot convert tz-naive timestamps, use tz_localize to localize\"", ")", "# No conversion since timestamps are all UTC to begin with", "dtype", "=", "tz_to_dtype", "(", "tz", ")", "return", "self", ".", "_simple_new", "(", "self", ".", "_ndarray", ",", "dtype", "=", "dtype", ",", "freq", "=", "self", ".", "freq", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/arrays/datetimes.py#L787-L861
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pytz/tzinfo.py
python
StaticTzInfo.localize
(self, dt, is_dst=False)
return dt.replace(tzinfo=self)
Convert naive time to local time
Convert naive time to local time
[ "Convert", "naive", "time", "to", "local", "time" ]
def localize(self, dt, is_dst=False): '''Convert naive time to local time''' if dt.tzinfo is not None: raise ValueError('Not naive datetime (tzinfo is already set)') return dt.replace(tzinfo=self)
[ "def", "localize", "(", "self", ",", "dt", ",", "is_dst", "=", "False", ")", ":", "if", "dt", ".", "tzinfo", "is", "not", "None", ":", "raise", "ValueError", "(", "'Not naive datetime (tzinfo is already set)'", ")", "return", "dt", ".", "replace", "(", "tzinfo", "=", "self", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pytz/tzinfo.py#L112-L116
ValveSoftware/source-sdk-2013
0d8dceea4310fde5706b3ce1c70609d72a38efdf
mp/src/thirdparty/protobuf-2.3.0/python/mox.py
python
MockMethod.MultipleTimes
(self, group_name="default")
return self._CheckAndCreateNewGroup(group_name, MultipleTimesGroup)
Move this method into group of calls which may be called multiple times. A group of repeating calls must be defined together, and must be executed in full before the next expected mehtod can be called. Args: group_name: the name of the unordered group. Returns: self
Move this method into group of calls which may be called multiple times.
[ "Move", "this", "method", "into", "group", "of", "calls", "which", "may", "be", "called", "multiple", "times", "." ]
def MultipleTimes(self, group_name="default"): """Move this method into group of calls which may be called multiple times. A group of repeating calls must be defined together, and must be executed in full before the next expected mehtod can be called. Args: group_name: the name of the unordered group. Returns: self """ return self._CheckAndCreateNewGroup(group_name, MultipleTimesGroup)
[ "def", "MultipleTimes", "(", "self", ",", "group_name", "=", "\"default\"", ")", ":", "return", "self", ".", "_CheckAndCreateNewGroup", "(", "group_name", ",", "MultipleTimesGroup", ")" ]
https://github.com/ValveSoftware/source-sdk-2013/blob/0d8dceea4310fde5706b3ce1c70609d72a38efdf/mp/src/thirdparty/protobuf-2.3.0/python/mox.py#L704-L716
MegEngine/MegEngine
ce9ad07a27ec909fb8db4dd67943d24ba98fb93a
imperative/python/megengine/functional/tensor.py
python
flatten
(inp: Tensor, start_axis: int = 0, end_axis: int = -1)
return inp.reshape(*target_shape)
r"""Reshapes the tensor by flattening the sub-tensor from dimension ``start_axis`` to dimension ``end_axis``. Args: inp: input tensor. start_axis: start dimension that the sub-tensor to be flattened. Default: 0 end_axis: end dimension that the sub-tensor to be flattened. Default: -1 Returns: output tensor. Examples: .. testcode:: import numpy as np from megengine import tensor import megengine.functional as F inp_shape = (2, 2, 3, 3) x = tensor( np.arange(36, dtype=np.int32).reshape(inp_shape), ) out = F.flatten(x, 2) print(x.numpy().shape) print(out.numpy().shape) Outputs: .. testoutput:: (2, 2, 3, 3) (2, 2, 9)
r"""Reshapes the tensor by flattening the sub-tensor from dimension ``start_axis`` to dimension ``end_axis``.
[ "r", "Reshapes", "the", "tensor", "by", "flattening", "the", "sub", "-", "tensor", "from", "dimension", "start_axis", "to", "dimension", "end_axis", "." ]
def flatten(inp: Tensor, start_axis: int = 0, end_axis: int = -1) -> Tensor: r"""Reshapes the tensor by flattening the sub-tensor from dimension ``start_axis`` to dimension ``end_axis``. Args: inp: input tensor. start_axis: start dimension that the sub-tensor to be flattened. Default: 0 end_axis: end dimension that the sub-tensor to be flattened. Default: -1 Returns: output tensor. Examples: .. testcode:: import numpy as np from megengine import tensor import megengine.functional as F inp_shape = (2, 2, 3, 3) x = tensor( np.arange(36, dtype=np.int32).reshape(inp_shape), ) out = F.flatten(x, 2) print(x.numpy().shape) print(out.numpy().shape) Outputs: .. testoutput:: (2, 2, 3, 3) (2, 2, 9) """ target_shape = tuple(inp.shape[i] for i in range(start_axis)) + (-1,) if end_axis != -1: target_shape += (*inp.shape[end_axis + 1 :],) return inp.reshape(*target_shape)
[ "def", "flatten", "(", "inp", ":", "Tensor", ",", "start_axis", ":", "int", "=", "0", ",", "end_axis", ":", "int", "=", "-", "1", ")", "->", "Tensor", ":", "target_shape", "=", "tuple", "(", "inp", ".", "shape", "[", "i", "]", "for", "i", "in", "range", "(", "start_axis", ")", ")", "+", "(", "-", "1", ",", ")", "if", "end_axis", "!=", "-", "1", ":", "target_shape", "+=", "(", "*", "inp", ".", "shape", "[", "end_axis", "+", "1", ":", "]", ",", ")", "return", "inp", ".", "reshape", "(", "*", "target_shape", ")" ]
https://github.com/MegEngine/MegEngine/blob/ce9ad07a27ec909fb8db4dd67943d24ba98fb93a/imperative/python/megengine/functional/tensor.py#L914-L951
Tencent/CMONGO
c40380caa14e05509f46993aa8b8da966b09b0b5
buildscripts/cpplint.py
python
IsRValueAllowed
(clean_lines, linenum)
return False
Check if RValue reference is allowed on a particular line. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. Returns: True if line is within the region where RValue references are allowed.
Check if RValue reference is allowed on a particular line.
[ "Check", "if", "RValue", "reference", "is", "allowed", "on", "a", "particular", "line", "." ]
def IsRValueAllowed(clean_lines, linenum): """Check if RValue reference is allowed on a particular line. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. Returns: True if line is within the region where RValue references are allowed. """ # Allow region marked by PUSH/POP macros for i in xrange(linenum, 0, -1): line = clean_lines.elided[i] if Match(r'GOOGLE_ALLOW_RVALUE_REFERENCES_(?:PUSH|POP)', line): if not line.endswith('PUSH'): return False for j in xrange(linenum, clean_lines.NumLines(), 1): line = clean_lines.elided[j] if Match(r'GOOGLE_ALLOW_RVALUE_REFERENCES_(?:PUSH|POP)', line): return line.endswith('POP') # Allow operator= line = clean_lines.elided[linenum] if Search(r'\boperator\s*=\s*\(', line): return IsDeletedOrDefault(clean_lines, linenum) # Allow constructors match = Match(r'\s*([\w<>]+)\s*::\s*([\w<>]+)\s*\(', line) if match and match.group(1) == match.group(2): return IsDeletedOrDefault(clean_lines, linenum) if Search(r'\b(?:explicit|inline)\s+[\w<>]+\s*\(', line): return IsDeletedOrDefault(clean_lines, linenum) if Match(r'\s*[\w<>]+\s*\(', line): previous_line = 'ReturnType' if linenum > 0: previous_line = clean_lines.elided[linenum - 1] if Match(r'^\s*$', previous_line) or Search(r'[{}:;]\s*$', previous_line): return IsDeletedOrDefault(clean_lines, linenum) return False
[ "def", "IsRValueAllowed", "(", "clean_lines", ",", "linenum", ")", ":", "# Allow region marked by PUSH/POP macros", "for", "i", "in", "xrange", "(", "linenum", ",", "0", ",", "-", "1", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "i", "]", "if", "Match", "(", "r'GOOGLE_ALLOW_RVALUE_REFERENCES_(?:PUSH|POP)'", ",", "line", ")", ":", "if", "not", "line", ".", "endswith", "(", "'PUSH'", ")", ":", "return", "False", "for", "j", "in", "xrange", "(", "linenum", ",", "clean_lines", ".", "NumLines", "(", ")", ",", "1", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "j", "]", "if", "Match", "(", "r'GOOGLE_ALLOW_RVALUE_REFERENCES_(?:PUSH|POP)'", ",", "line", ")", ":", "return", "line", ".", "endswith", "(", "'POP'", ")", "# Allow operator=", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "if", "Search", "(", "r'\\boperator\\s*=\\s*\\('", ",", "line", ")", ":", "return", "IsDeletedOrDefault", "(", "clean_lines", ",", "linenum", ")", "# Allow constructors", "match", "=", "Match", "(", "r'\\s*([\\w<>]+)\\s*::\\s*([\\w<>]+)\\s*\\('", ",", "line", ")", "if", "match", "and", "match", ".", "group", "(", "1", ")", "==", "match", ".", "group", "(", "2", ")", ":", "return", "IsDeletedOrDefault", "(", "clean_lines", ",", "linenum", ")", "if", "Search", "(", "r'\\b(?:explicit|inline)\\s+[\\w<>]+\\s*\\('", ",", "line", ")", ":", "return", "IsDeletedOrDefault", "(", "clean_lines", ",", "linenum", ")", "if", "Match", "(", "r'\\s*[\\w<>]+\\s*\\('", ",", "line", ")", ":", "previous_line", "=", "'ReturnType'", "if", "linenum", ">", "0", ":", "previous_line", "=", "clean_lines", ".", "elided", "[", "linenum", "-", "1", "]", "if", "Match", "(", "r'^\\s*$'", ",", "previous_line", ")", "or", "Search", "(", "r'[{}:;]\\s*$'", ",", "previous_line", ")", ":", "return", "IsDeletedOrDefault", "(", "clean_lines", ",", "linenum", ")", "return", "False" ]
https://github.com/Tencent/CMONGO/blob/c40380caa14e05509f46993aa8b8da966b09b0b5/buildscripts/cpplint.py#L3633-L3672
google/shaka-player-embedded
dabbeb5b47cc257b37b9a254661546352aaf0afe
shaka/tools/webidl/webidl/parser.py
python
IdlParser._check_options
(self, p, idx, feature)
Checks that the given feature is allowed, and adds an error otherwise.
Checks that the given feature is allowed, and adds an error otherwise.
[ "Checks", "that", "the", "given", "feature", "is", "allowed", "and", "adds", "an", "error", "otherwise", "." ]
def _check_options(self, p, idx, feature): """Checks that the given feature is allowed, and adds an error otherwise.""" if self.options.has_feature(feature): return self._add_error('Feature "%s" is not allowed by options' % feature, p.lineno(idx), p.lexpos(idx))
[ "def", "_check_options", "(", "self", ",", "p", ",", "idx", ",", "feature", ")", ":", "if", "self", ".", "options", ".", "has_feature", "(", "feature", ")", ":", "return", "self", ".", "_add_error", "(", "'Feature \"%s\" is not allowed by options'", "%", "feature", ",", "p", ".", "lineno", "(", "idx", ")", ",", "p", ".", "lexpos", "(", "idx", ")", ")" ]
https://github.com/google/shaka-player-embedded/blob/dabbeb5b47cc257b37b9a254661546352aaf0afe/shaka/tools/webidl/webidl/parser.py#L705-L710
daijifeng001/caffe-rfcn
543f8f6a4b7c88256ea1445ae951a12d1ad9cffd
tools/extra/extract_seconds.py
python
get_log_created_year
(input_file)
return log_created_year
Get year from log file system timestamp
Get year from log file system timestamp
[ "Get", "year", "from", "log", "file", "system", "timestamp" ]
def get_log_created_year(input_file): """Get year from log file system timestamp """ log_created_time = os.path.getctime(input_file) log_created_year = datetime.datetime.fromtimestamp(log_created_time).year return log_created_year
[ "def", "get_log_created_year", "(", "input_file", ")", ":", "log_created_time", "=", "os", ".", "path", ".", "getctime", "(", "input_file", ")", "log_created_year", "=", "datetime", ".", "datetime", ".", "fromtimestamp", "(", "log_created_time", ")", ".", "year", "return", "log_created_year" ]
https://github.com/daijifeng001/caffe-rfcn/blob/543f8f6a4b7c88256ea1445ae951a12d1ad9cffd/tools/extra/extract_seconds.py#L22-L28
thalium/icebox
99d147d5b9269222225443ce171b4fd46d8985d4
third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py
python
xmlEntity.handleEntity
(self, ctxt)
Default handling of defined entities, when should we define a new input stream ? When do we just handle that as a set of chars ? OBSOLETE: to be removed at some point.
Default handling of defined entities, when should we define a new input stream ? When do we just handle that as a set of chars ? OBSOLETE: to be removed at some point.
[ "Default", "handling", "of", "defined", "entities", "when", "should", "we", "define", "a", "new", "input", "stream", "?", "When", "do", "we", "just", "handle", "that", "as", "a", "set", "of", "chars", "?", "OBSOLETE", ":", "to", "be", "removed", "at", "some", "point", "." ]
def handleEntity(self, ctxt): """Default handling of defined entities, when should we define a new input stream ? When do we just handle that as a set of chars ? OBSOLETE: to be removed at some point. """ if ctxt is None: ctxt__o = None else: ctxt__o = ctxt._o libxml2mod.xmlHandleEntity(ctxt__o, self._o)
[ "def", "handleEntity", "(", "self", ",", "ctxt", ")", ":", "if", "ctxt", "is", "None", ":", "ctxt__o", "=", "None", "else", ":", "ctxt__o", "=", "ctxt", ".", "_o", "libxml2mod", ".", "xmlHandleEntity", "(", "ctxt__o", ",", "self", ".", "_o", ")" ]
https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py#L5799-L5805
Polidea/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py
python
SBLineEntry.__init__
(self, *args)
__init__(self) -> SBLineEntry __init__(self, SBLineEntry rhs) -> SBLineEntry
__init__(self) -> SBLineEntry __init__(self, SBLineEntry rhs) -> SBLineEntry
[ "__init__", "(", "self", ")", "-", ">", "SBLineEntry", "__init__", "(", "self", "SBLineEntry", "rhs", ")", "-", ">", "SBLineEntry" ]
def __init__(self, *args): """ __init__(self) -> SBLineEntry __init__(self, SBLineEntry rhs) -> SBLineEntry """ this = _lldb.new_SBLineEntry(*args) try: self.this.append(this) except: self.this = this
[ "def", "__init__", "(", "self", ",", "*", "args", ")", ":", "this", "=", "_lldb", ".", "new_SBLineEntry", "(", "*", "args", ")", "try", ":", "self", ".", "this", ".", "append", "(", "this", ")", "except", ":", "self", ".", "this", "=", "this" ]
https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L5612-L5619
oracle/graaljs
36a56e8e993d45fc40939a3a4d9c0c24990720f1
graal-nodejs/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/MSVSUserFile.py
python
Writer.AddConfig
(self, name)
Adds a configuration to the project. Args: name: Configuration name.
Adds a configuration to the project.
[ "Adds", "a", "configuration", "to", "the", "project", "." ]
def AddConfig(self, name): """Adds a configuration to the project. Args: name: Configuration name. """ self.configurations[name] = ["Configuration", {"Name": name}]
[ "def", "AddConfig", "(", "self", ",", "name", ")", ":", "self", ".", "configurations", "[", "name", "]", "=", "[", "\"Configuration\"", ",", "{", "\"Name\"", ":", "name", "}", "]" ]
https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/MSVSUserFile.py#L72-L78