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
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/lib/io/file_io.py
python
get_matching_files
(filename)
return get_matching_files_v2(filename)
Returns a list of files that match the given pattern(s). Args: filename: string or iterable of strings. The glob pattern(s). Returns: A list of strings containing filenames that match the given pattern(s). Raises: * errors.OpError: If there are filesystem / directory listing errors. * errors.NotFoundError: If pattern to be matched is an invalid directory.
Returns a list of files that match the given pattern(s).
[ "Returns", "a", "list", "of", "files", "that", "match", "the", "given", "pattern", "(", "s", ")", "." ]
def get_matching_files(filename): """Returns a list of files that match the given pattern(s). Args: filename: string or iterable of strings. The glob pattern(s). Returns: A list of strings containing filenames that match the given pattern(s). Raises: * errors.OpError: If there are filesystem / directory listing errors. * errors.NotFoundError: If pattern to be matched is an invalid directory. """ return get_matching_files_v2(filename)
[ "def", "get_matching_files", "(", "filename", ")", ":", "return", "get_matching_files_v2", "(", "filename", ")" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/lib/io/file_io.py#L367-L380
psnonis/FinBERT
c0c555d833a14e2316a3701e59c0b5156f804b4e
bert-gpu/tensorrt-inference-server/src/clients/python/grpc_image_client.py
python
parse_model
(status, model_name, batch_size, verbose=False)
return (input.name, output.name, c, h, w, input.format, model_dtype_to_np(input.data_type))
Check the configuration of a model to make sure it meets the requirements for an image classification network (as expected by this client)
Check the configuration of a model to make sure it meets the requirements for an image classification network (as expected by this client)
[ "Check", "the", "configuration", "of", "a", "model", "to", "make", "sure", "it", "meets", "the", "requirements", "for", "an", "image", "classification", "network", "(", "as", "expected", "by", "this", "client", ")" ]
def parse_model(status, model_name, batch_size, verbose=False): """ Check the configuration of a model to make sure it meets the requirements for an image classification network (as expected by this client) """ server_status = status.server_status if model_name not in server_status.model_status.keys(): raise Exception("unable to get status for '" + model_name + "'") status = server_status.model_status[model_name] config = status.config if len(config.input) != 1: raise Exception("expecting 1 input, got {}".format(len(config.input))) if len(config.output) != 1: raise Exception("expecting 1 output, got {}".format(len(config.output))) input = config.input[0] output = config.output[0] if output.data_type != model_config.TYPE_FP32: raise Exception("expecting output datatype to be TYPE_FP32, model '" + model_name + "' output type is " + model_config.DataType.Name(output.data_type)) # Output is expected to be a vector. But allow any number of # dimensions as long as all but 1 is size 1 (e.g. { 10 }, { 1, 10 # }, { 10, 1, 1 } are all ok). non_one_cnt = 0 for dim in output.dims: if dim > 1: non_one_cnt += 1 if non_one_cnt > 1: raise Exception("expecting model output to be a vector") # Model specifying maximum batch size of 0 indicates that batching # is not supported and so the input tensors do not expect an "N" # dimension (and 'batch_size' should be 1 so that only a single # image instance is inferred at a time). max_batch_size = config.max_batch_size if max_batch_size == 0: if batch_size != 1: raise Exception("batching not supported for model '" + model_name + "'") else: # max_batch_size > 0 if batch_size > max_batch_size: raise Exception( "expecting batch size <= {} for model '{}'".format(max_batch_size, model_name)) # Model input must have 3 dims, either CHW or HWC if len(input.dims) != 3: raise Exception( "expecting input to have 3 dimensions, model '{}' input has {}".format( model_name, len(input.dims))) if ((input.format != model_config.ModelInput.FORMAT_NCHW) and (input.format != model_config.ModelInput.FORMAT_NHWC)): raise Exception("unexpected input format " + model_config.ModelInput.Format.Name(input.format) + ", expecting " + model_config.ModelInput.Format.Name(model_config.ModelInput.FORMAT_NCHW) + " or " + model_config.ModelInput.Format.Name(model_config.ModelInput.FORMAT_NHWC)) if input.format == model_config.ModelInput.FORMAT_NHWC: h = input.dims[0] w = input.dims[1] c = input.dims[2] else: c = input.dims[0] h = input.dims[1] w = input.dims[2] return (input.name, output.name, c, h, w, input.format, model_dtype_to_np(input.data_type))
[ "def", "parse_model", "(", "status", ",", "model_name", ",", "batch_size", ",", "verbose", "=", "False", ")", ":", "server_status", "=", "status", ".", "server_status", "if", "model_name", "not", "in", "server_status", ".", "model_status", ".", "keys", "(", ")", ":", "raise", "Exception", "(", "\"unable to get status for '\"", "+", "model_name", "+", "\"'\"", ")", "status", "=", "server_status", ".", "model_status", "[", "model_name", "]", "config", "=", "status", ".", "config", "if", "len", "(", "config", ".", "input", ")", "!=", "1", ":", "raise", "Exception", "(", "\"expecting 1 input, got {}\"", ".", "format", "(", "len", "(", "config", ".", "input", ")", ")", ")", "if", "len", "(", "config", ".", "output", ")", "!=", "1", ":", "raise", "Exception", "(", "\"expecting 1 output, got {}\"", ".", "format", "(", "len", "(", "config", ".", "output", ")", ")", ")", "input", "=", "config", ".", "input", "[", "0", "]", "output", "=", "config", ".", "output", "[", "0", "]", "if", "output", ".", "data_type", "!=", "model_config", ".", "TYPE_FP32", ":", "raise", "Exception", "(", "\"expecting output datatype to be TYPE_FP32, model '\"", "+", "model_name", "+", "\"' output type is \"", "+", "model_config", ".", "DataType", ".", "Name", "(", "output", ".", "data_type", ")", ")", "# Output is expected to be a vector. But allow any number of", "# dimensions as long as all but 1 is size 1 (e.g. { 10 }, { 1, 10", "# }, { 10, 1, 1 } are all ok).", "non_one_cnt", "=", "0", "for", "dim", "in", "output", ".", "dims", ":", "if", "dim", ">", "1", ":", "non_one_cnt", "+=", "1", "if", "non_one_cnt", ">", "1", ":", "raise", "Exception", "(", "\"expecting model output to be a vector\"", ")", "# Model specifying maximum batch size of 0 indicates that batching", "# is not supported and so the input tensors do not expect an \"N\"", "# dimension (and 'batch_size' should be 1 so that only a single", "# image instance is inferred at a time).", "max_batch_size", "=", "config", ".", "max_batch_size", "if", "max_batch_size", "==", "0", ":", "if", "batch_size", "!=", "1", ":", "raise", "Exception", "(", "\"batching not supported for model '\"", "+", "model_name", "+", "\"'\"", ")", "else", ":", "# max_batch_size > 0", "if", "batch_size", ">", "max_batch_size", ":", "raise", "Exception", "(", "\"expecting batch size <= {} for model '{}'\"", ".", "format", "(", "max_batch_size", ",", "model_name", ")", ")", "# Model input must have 3 dims, either CHW or HWC", "if", "len", "(", "input", ".", "dims", ")", "!=", "3", ":", "raise", "Exception", "(", "\"expecting input to have 3 dimensions, model '{}' input has {}\"", ".", "format", "(", "model_name", ",", "len", "(", "input", ".", "dims", ")", ")", ")", "if", "(", "(", "input", ".", "format", "!=", "model_config", ".", "ModelInput", ".", "FORMAT_NCHW", ")", "and", "(", "input", ".", "format", "!=", "model_config", ".", "ModelInput", ".", "FORMAT_NHWC", ")", ")", ":", "raise", "Exception", "(", "\"unexpected input format \"", "+", "model_config", ".", "ModelInput", ".", "Format", ".", "Name", "(", "input", ".", "format", ")", "+", "\", expecting \"", "+", "model_config", ".", "ModelInput", ".", "Format", ".", "Name", "(", "model_config", ".", "ModelInput", ".", "FORMAT_NCHW", ")", "+", "\" or \"", "+", "model_config", ".", "ModelInput", ".", "Format", ".", "Name", "(", "model_config", ".", "ModelInput", ".", "FORMAT_NHWC", ")", ")", "if", "input", ".", "format", "==", "model_config", ".", "ModelInput", ".", "FORMAT_NHWC", ":", "h", "=", "input", ".", "dims", "[", "0", "]", "w", "=", "input", ".", "dims", "[", "1", "]", "c", "=", "input", ".", "dims", "[", "2", "]", "else", ":", "c", "=", "input", ".", "dims", "[", "0", "]", "h", "=", "input", ".", "dims", "[", "1", "]", "w", "=", "input", ".", "dims", "[", "2", "]", "return", "(", "input", ".", "name", ",", "output", ".", "name", ",", "c", ",", "h", ",", "w", ",", "input", ".", "format", ",", "model_dtype_to_np", "(", "input", ".", "data_type", ")", ")" ]
https://github.com/psnonis/FinBERT/blob/c0c555d833a14e2316a3701e59c0b5156f804b4e/bert-gpu/tensorrt-inference-server/src/clients/python/grpc_image_client.py#L69-L141
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/numpy/py2/numpy/ma/core.py
python
putmask
(a, mask, values)
return
Changes elements of an array based on conditional and input values. This is the masked array version of `numpy.putmask`, for details see `numpy.putmask`. See Also -------- numpy.putmask Notes ----- Using a masked array as `values` will **not** transform a `ndarray` into a `MaskedArray`.
Changes elements of an array based on conditional and input values.
[ "Changes", "elements", "of", "an", "array", "based", "on", "conditional", "and", "input", "values", "." ]
def putmask(a, mask, values): # , mode='raise'): """ Changes elements of an array based on conditional and input values. This is the masked array version of `numpy.putmask`, for details see `numpy.putmask`. See Also -------- numpy.putmask Notes ----- Using a masked array as `values` will **not** transform a `ndarray` into a `MaskedArray`. """ # We can't use 'frommethod', the order of arguments is different if not isinstance(a, MaskedArray): a = a.view(MaskedArray) (valdata, valmask) = (getdata(values), getmask(values)) if getmask(a) is nomask: if valmask is not nomask: a._sharedmask = True a._mask = make_mask_none(a.shape, a.dtype) np.copyto(a._mask, valmask, where=mask) elif a._hardmask: if valmask is not nomask: m = a._mask.copy() np.copyto(m, valmask, where=mask) a.mask |= m else: if valmask is nomask: valmask = getmaskarray(values) np.copyto(a._mask, valmask, where=mask) np.copyto(a._data, valdata, where=mask) return
[ "def", "putmask", "(", "a", ",", "mask", ",", "values", ")", ":", "# , mode='raise'):", "# We can't use 'frommethod', the order of arguments is different", "if", "not", "isinstance", "(", "a", ",", "MaskedArray", ")", ":", "a", "=", "a", ".", "view", "(", "MaskedArray", ")", "(", "valdata", ",", "valmask", ")", "=", "(", "getdata", "(", "values", ")", ",", "getmask", "(", "values", ")", ")", "if", "getmask", "(", "a", ")", "is", "nomask", ":", "if", "valmask", "is", "not", "nomask", ":", "a", ".", "_sharedmask", "=", "True", "a", ".", "_mask", "=", "make_mask_none", "(", "a", ".", "shape", ",", "a", ".", "dtype", ")", "np", ".", "copyto", "(", "a", ".", "_mask", ",", "valmask", ",", "where", "=", "mask", ")", "elif", "a", ".", "_hardmask", ":", "if", "valmask", "is", "not", "nomask", ":", "m", "=", "a", ".", "_mask", ".", "copy", "(", ")", "np", ".", "copyto", "(", "m", ",", "valmask", ",", "where", "=", "mask", ")", "a", ".", "mask", "|=", "m", "else", ":", "if", "valmask", "is", "nomask", ":", "valmask", "=", "getmaskarray", "(", "values", ")", "np", ".", "copyto", "(", "a", ".", "_mask", ",", "valmask", ",", "where", "=", "mask", ")", "np", ".", "copyto", "(", "a", ".", "_data", ",", "valdata", ",", "where", "=", "mask", ")", "return" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py2/numpy/ma/core.py#L6873-L6909
bareos/bareos
56a10bb368b0a81e977bb51304033fe49d59efb0
restapi/bareos_restapi/__init__.py
python
read_all_storages
( *, response: Response, current_user: User = Depends(get_current_user), verbose: Optional[bareosBool] = Query("yes", title="Verbose output"), )
return show_configuration_items( response=response, current_user=current_user, itemType="storages", verbose=verbose, )
Read all jobdef resources. Built on console command _show storages_. Needs at least Bareos Version >= 20.0.0
Read all jobdef resources. Built on console command _show storages_.
[ "Read", "all", "jobdef", "resources", ".", "Built", "on", "console", "command", "_show", "storages_", "." ]
def read_all_storages( *, response: Response, current_user: User = Depends(get_current_user), verbose: Optional[bareosBool] = Query("yes", title="Verbose output"), ): """ Read all jobdef resources. Built on console command _show storages_. Needs at least Bareos Version >= 20.0.0 """ return show_configuration_items( response=response, current_user=current_user, itemType="storages", verbose=verbose, )
[ "def", "read_all_storages", "(", "*", ",", "response", ":", "Response", ",", "current_user", ":", "User", "=", "Depends", "(", "get_current_user", ")", ",", "verbose", ":", "Optional", "[", "bareosBool", "]", "=", "Query", "(", "\"yes\"", ",", "title", "=", "\"Verbose output\"", ")", ",", ")", ":", "return", "show_configuration_items", "(", "response", "=", "response", ",", "current_user", "=", "current_user", ",", "itemType", "=", "\"storages\"", ",", "verbose", "=", "verbose", ",", ")" ]
https://github.com/bareos/bareos/blob/56a10bb368b0a81e977bb51304033fe49d59efb0/restapi/bareos_restapi/__init__.py#L1695-L1711
perilouswithadollarsign/cstrike15_src
f82112a2388b841d72cb62ca48ab1846dfcc11c8
thirdparty/protobuf-2.5.0/python/google/protobuf/descriptor_pool.py
python
DescriptorPool.__init__
(self, descriptor_db=None)
Initializes a Pool of proto buffs. The descriptor_db argument to the constructor is provided to allow specialized file descriptor proto lookup code to be triggered on demand. An example would be an implementation which will read and compile a file specified in a call to FindFileByName() and not require the call to Add() at all. Results from this database will be cached internally here as well. Args: descriptor_db: A secondary source of file descriptors.
Initializes a Pool of proto buffs.
[ "Initializes", "a", "Pool", "of", "proto", "buffs", "." ]
def __init__(self, descriptor_db=None): """Initializes a Pool of proto buffs. The descriptor_db argument to the constructor is provided to allow specialized file descriptor proto lookup code to be triggered on demand. An example would be an implementation which will read and compile a file specified in a call to FindFileByName() and not require the call to Add() at all. Results from this database will be cached internally here as well. Args: descriptor_db: A secondary source of file descriptors. """ self._internal_db = descriptor_database.DescriptorDatabase() self._descriptor_db = descriptor_db self._descriptors = {} self._enum_descriptors = {} self._file_descriptors = {}
[ "def", "__init__", "(", "self", ",", "descriptor_db", "=", "None", ")", ":", "self", ".", "_internal_db", "=", "descriptor_database", ".", "DescriptorDatabase", "(", ")", "self", ".", "_descriptor_db", "=", "descriptor_db", "self", ".", "_descriptors", "=", "{", "}", "self", ".", "_enum_descriptors", "=", "{", "}", "self", ".", "_file_descriptors", "=", "{", "}" ]
https://github.com/perilouswithadollarsign/cstrike15_src/blob/f82112a2388b841d72cb62ca48ab1846dfcc11c8/thirdparty/protobuf-2.5.0/python/google/protobuf/descriptor_pool.py#L64-L81
mingchen/protobuf-ios
0958df34558cd54cb7b6e6ca5c8855bf3d475046
compiler/python/mox.py
python
Mox.ResetAll
(self)
Call reset on all mock objects. This does not unset stubs.
Call reset on all mock objects. This does not unset stubs.
[ "Call", "reset", "on", "all", "mock", "objects", ".", "This", "does", "not", "unset", "stubs", "." ]
def ResetAll(self): """Call reset on all mock objects. This does not unset stubs.""" for mock_obj in self._mock_objects: mock_obj._Reset()
[ "def", "ResetAll", "(", "self", ")", ":", "for", "mock_obj", "in", "self", ".", "_mock_objects", ":", "mock_obj", ".", "_Reset", "(", ")" ]
https://github.com/mingchen/protobuf-ios/blob/0958df34558cd54cb7b6e6ca5c8855bf3d475046/compiler/python/mox.py#L202-L206
eventql/eventql
7ca0dbb2e683b525620ea30dc40540a22d5eb227
deps/3rdparty/spidermonkey/mozjs/python/requests/requests/packages/urllib3/util/retry.py
python
Retry.sleep
(self)
Sleep between retry attempts using an exponential backoff. By default, the backoff factor is 0 and this method will return immediately.
Sleep between retry attempts using an exponential backoff.
[ "Sleep", "between", "retry", "attempts", "using", "an", "exponential", "backoff", "." ]
def sleep(self): """ Sleep between retry attempts using an exponential backoff. By default, the backoff factor is 0 and this method will return immediately. """ backoff = self.get_backoff_time() if backoff <= 0: return time.sleep(backoff)
[ "def", "sleep", "(", "self", ")", ":", "backoff", "=", "self", ".", "get_backoff_time", "(", ")", "if", "backoff", "<=", "0", ":", "return", "time", ".", "sleep", "(", "backoff", ")" ]
https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/python/requests/requests/packages/urllib3/util/retry.py#L169-L178
okex/V3-Open-API-SDK
c5abb0db7e2287718e0055e17e57672ce0ec7fd9
okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_internal/vcs/git.py
python
Git.get_revision_sha
(self, dest, rev)
return (sha, False)
Return (sha_or_none, is_branch), where sha_or_none is a commit hash if the revision names a remote branch or tag, otherwise None. Args: dest: the repository directory. rev: the revision name.
Return (sha_or_none, is_branch), where sha_or_none is a commit hash if the revision names a remote branch or tag, otherwise None.
[ "Return", "(", "sha_or_none", "is_branch", ")", "where", "sha_or_none", "is", "a", "commit", "hash", "if", "the", "revision", "names", "a", "remote", "branch", "or", "tag", "otherwise", "None", "." ]
def get_revision_sha(self, dest, rev): """ Return (sha_or_none, is_branch), where sha_or_none is a commit hash if the revision names a remote branch or tag, otherwise None. Args: dest: the repository directory. rev: the revision name. """ # Pass rev to pre-filter the list. output = self.run_command(['show-ref', rev], cwd=dest, show_stdout=False, on_returncode='ignore') refs = {} for line in output.strip().splitlines(): try: sha, ref = line.split() except ValueError: # Include the offending line to simplify troubleshooting if # this error ever occurs. raise ValueError('unexpected show-ref line: {!r}'.format(line)) refs[ref] = sha branch_ref = 'refs/remotes/origin/{}'.format(rev) tag_ref = 'refs/tags/{}'.format(rev) sha = refs.get(branch_ref) if sha is not None: return (sha, True) sha = refs.get(tag_ref) return (sha, False)
[ "def", "get_revision_sha", "(", "self", ",", "dest", ",", "rev", ")", ":", "# Pass rev to pre-filter the list.", "output", "=", "self", ".", "run_command", "(", "[", "'show-ref'", ",", "rev", "]", ",", "cwd", "=", "dest", ",", "show_stdout", "=", "False", ",", "on_returncode", "=", "'ignore'", ")", "refs", "=", "{", "}", "for", "line", "in", "output", ".", "strip", "(", ")", ".", "splitlines", "(", ")", ":", "try", ":", "sha", ",", "ref", "=", "line", ".", "split", "(", ")", "except", "ValueError", ":", "# Include the offending line to simplify troubleshooting if", "# this error ever occurs.", "raise", "ValueError", "(", "'unexpected show-ref line: {!r}'", ".", "format", "(", "line", ")", ")", "refs", "[", "ref", "]", "=", "sha", "branch_ref", "=", "'refs/remotes/origin/{}'", ".", "format", "(", "rev", ")", "tag_ref", "=", "'refs/tags/{}'", ".", "format", "(", "rev", ")", "sha", "=", "refs", ".", "get", "(", "branch_ref", ")", "if", "sha", "is", "not", "None", ":", "return", "(", "sha", ",", "True", ")", "sha", "=", "refs", ".", "get", "(", "tag_ref", ")", "return", "(", "sha", ",", "False", ")" ]
https://github.com/okex/V3-Open-API-SDK/blob/c5abb0db7e2287718e0055e17e57672ce0ec7fd9/okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_internal/vcs/git.py#L114-L146
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/aui.py
python
AuiPaneInfo.MaxSize
(*args, **kwargs)
return _aui.AuiPaneInfo_MaxSize(*args, **kwargs)
MaxSize(self, Size size) -> AuiPaneInfo
MaxSize(self, Size size) -> AuiPaneInfo
[ "MaxSize", "(", "self", "Size", "size", ")", "-", ">", "AuiPaneInfo" ]
def MaxSize(*args, **kwargs): """MaxSize(self, Size size) -> AuiPaneInfo""" return _aui.AuiPaneInfo_MaxSize(*args, **kwargs)
[ "def", "MaxSize", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_aui", ".", "AuiPaneInfo_MaxSize", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/aui.py#L397-L399
microsoft/AirSim
8057725712c0cd46979135396381784075ffc0f3
PythonClient/airsim/client.py
python
VehicleClient.simRunConsoleCommand
(self, command)
return self.client.call('simRunConsoleCommand', command)
Allows the client to execute a command in Unreal's native console, via an API. Affords access to the countless built-in commands such as "stat unit", "stat fps", "open [map]", adjust any config settings, etc. etc. Allows the user to create bespoke APIs very easily, by adding a custom event to the level blueprint, and then calling the console command "ce MyEventName [args]". No recompilation of AirSim needed! Args: command ([string]): Desired Unreal Engine Console command to run Returns: [bool]: Success
Allows the client to execute a command in Unreal's native console, via an API. Affords access to the countless built-in commands such as "stat unit", "stat fps", "open [map]", adjust any config settings, etc. etc. Allows the user to create bespoke APIs very easily, by adding a custom event to the level blueprint, and then calling the console command "ce MyEventName [args]". No recompilation of AirSim needed!
[ "Allows", "the", "client", "to", "execute", "a", "command", "in", "Unreal", "s", "native", "console", "via", "an", "API", ".", "Affords", "access", "to", "the", "countless", "built", "-", "in", "commands", "such", "as", "stat", "unit", "stat", "fps", "open", "[", "map", "]", "adjust", "any", "config", "settings", "etc", ".", "etc", ".", "Allows", "the", "user", "to", "create", "bespoke", "APIs", "very", "easily", "by", "adding", "a", "custom", "event", "to", "the", "level", "blueprint", "and", "then", "calling", "the", "console", "command", "ce", "MyEventName", "[", "args", "]", ".", "No", "recompilation", "of", "AirSim", "needed!" ]
def simRunConsoleCommand(self, command): """ Allows the client to execute a command in Unreal's native console, via an API. Affords access to the countless built-in commands such as "stat unit", "stat fps", "open [map]", adjust any config settings, etc. etc. Allows the user to create bespoke APIs very easily, by adding a custom event to the level blueprint, and then calling the console command "ce MyEventName [args]". No recompilation of AirSim needed! Args: command ([string]): Desired Unreal Engine Console command to run Returns: [bool]: Success """ return self.client.call('simRunConsoleCommand', command)
[ "def", "simRunConsoleCommand", "(", "self", ",", "command", ")", ":", "return", "self", ".", "client", ".", "call", "(", "'simRunConsoleCommand'", ",", "command", ")" ]
https://github.com/microsoft/AirSim/blob/8057725712c0cd46979135396381784075ffc0f3/PythonClient/airsim/client.py#L410-L422
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/summary/summary_iterator.py
python
summary_iterator
(path)
return _SummaryIterator(path)
Returns a iterator for reading `Event` protocol buffers from an event file. You can use this function to read events written to an event file. It returns a Python iterator that yields `Event` protocol buffers. Example: Print the contents of an events file. ```python for e in tf.compat.v1.train.summary_iterator(path to events file): print(e) ``` Example: Print selected summary values. ```python # This example supposes that the events file contains summaries with a # summary value tag 'loss'. These could have been added by calling # `add_summary()`, passing the output of a scalar summary op created with # with: `tf.compat.v1.summary.scalar('loss', loss_tensor)`. for e in tf.compat.v1.train.summary_iterator(path to events file): for v in e.summary.value: if v.tag == 'loss': print(v.simple_value) ``` Example: Continuously check for new summary values. ```python summaries = tf.compat.v1.train.summary_iterator(path to events file) while True: for e in summaries: for v in e.summary.value: if v.tag == 'loss': print(v.simple_value) # Wait for a bit before checking the file for any new events time.sleep(wait time) ``` See the protocol buffer definitions of [Event](https://www.tensorflow.org/code/tensorflow/core/util/event.proto) and [Summary](https://www.tensorflow.org/code/tensorflow/core/framework/summary.proto) for more information about their attributes. Args: path: The path to an event file created by a `SummaryWriter`. Returns: A iterator that yields `Event` protocol buffers
Returns a iterator for reading `Event` protocol buffers from an event file.
[ "Returns", "a", "iterator", "for", "reading", "Event", "protocol", "buffers", "from", "an", "event", "file", "." ]
def summary_iterator(path): # pylint: disable=line-too-long """Returns a iterator for reading `Event` protocol buffers from an event file. You can use this function to read events written to an event file. It returns a Python iterator that yields `Event` protocol buffers. Example: Print the contents of an events file. ```python for e in tf.compat.v1.train.summary_iterator(path to events file): print(e) ``` Example: Print selected summary values. ```python # This example supposes that the events file contains summaries with a # summary value tag 'loss'. These could have been added by calling # `add_summary()`, passing the output of a scalar summary op created with # with: `tf.compat.v1.summary.scalar('loss', loss_tensor)`. for e in tf.compat.v1.train.summary_iterator(path to events file): for v in e.summary.value: if v.tag == 'loss': print(v.simple_value) ``` Example: Continuously check for new summary values. ```python summaries = tf.compat.v1.train.summary_iterator(path to events file) while True: for e in summaries: for v in e.summary.value: if v.tag == 'loss': print(v.simple_value) # Wait for a bit before checking the file for any new events time.sleep(wait time) ``` See the protocol buffer definitions of [Event](https://www.tensorflow.org/code/tensorflow/core/util/event.proto) and [Summary](https://www.tensorflow.org/code/tensorflow/core/framework/summary.proto) for more information about their attributes. Args: path: The path to an event file created by a `SummaryWriter`. Returns: A iterator that yields `Event` protocol buffers """ return _SummaryIterator(path)
[ "def", "summary_iterator", "(", "path", ")", ":", "# pylint: disable=line-too-long", "return", "_SummaryIterator", "(", "path", ")" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/summary/summary_iterator.py#L40-L91
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py3/pandas/core/indexes/interval.py
python
_is_valid_endpoint
(endpoint)
return any( [ is_number(endpoint), isinstance(endpoint, Timestamp), isinstance(endpoint, Timedelta), endpoint is None, ] )
Helper for interval_range to check if start/end are valid types.
Helper for interval_range to check if start/end are valid types.
[ "Helper", "for", "interval_range", "to", "check", "if", "start", "/", "end", "are", "valid", "types", "." ]
def _is_valid_endpoint(endpoint) -> bool: """ Helper for interval_range to check if start/end are valid types. """ return any( [ is_number(endpoint), isinstance(endpoint, Timestamp), isinstance(endpoint, Timedelta), endpoint is None, ] )
[ "def", "_is_valid_endpoint", "(", "endpoint", ")", "->", "bool", ":", "return", "any", "(", "[", "is_number", "(", "endpoint", ")", ",", "isinstance", "(", "endpoint", ",", "Timestamp", ")", ",", "isinstance", "(", "endpoint", ",", "Timedelta", ")", ",", "endpoint", "is", "None", ",", "]", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/indexes/interval.py#L896-L907
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/AWSPythonSDK/1.5.8/s3transfer/download.py
python
DownloadChunkIterator.__init__
(self, body, chunksize)
Iterator to chunk out a downloaded S3 stream :param body: A readable file-like object :param chunksize: The amount to read each time
Iterator to chunk out a downloaded S3 stream
[ "Iterator", "to", "chunk", "out", "a", "downloaded", "S3", "stream" ]
def __init__(self, body, chunksize): """Iterator to chunk out a downloaded S3 stream :param body: A readable file-like object :param chunksize: The amount to read each time """ self._body = body self._chunksize = chunksize self._num_reads = 0
[ "def", "__init__", "(", "self", ",", "body", ",", "chunksize", ")", ":", "self", ".", "_body", "=", "body", "self", ".", "_chunksize", "=", "chunksize", "self", ".", "_num_reads", "=", "0" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/s3transfer/download.py#L646-L654
psnonis/FinBERT
c0c555d833a14e2316a3701e59c0b5156f804b4e
bert/run_classifier.py
python
MrpcProcessor.get_labels
(self)
return ["0", "1"]
See base class.
See base class.
[ "See", "base", "class", "." ]
def get_labels(self): """See base class.""" return ["0", "1"]
[ "def", "get_labels", "(", "self", ")", ":", "return", "[", "\"0\"", ",", "\"1\"", "]" ]
https://github.com/psnonis/FinBERT/blob/c0c555d833a14e2316a3701e59c0b5156f804b4e/bert/run_classifier.py#L314-L316
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
gpu/command_buffer/build_gles2_cmd_buffer.py
python
TypeHandler.WriteGLES2TraceImplementation
(self, func, file)
Writes the GLES2 Trace Implemention.
Writes the GLES2 Trace Implemention.
[ "Writes", "the", "GLES2", "Trace", "Implemention", "." ]
def WriteGLES2TraceImplementation(self, func, file): """Writes the GLES2 Trace Implemention.""" file.Write("%s GLES2TraceImplementation::%s(%s) {\n" % (func.return_type, func.original_name, func.MakeTypedOriginalArgString(""))) result_string = "return " if func.return_type == "void": result_string = "" file.Write(' TRACE_EVENT_BINARY_EFFICIENT0("gpu", "GLES2Trace::%s");\n' % func.name) file.Write(" %sgl_->%s(%s);\n" % (result_string, func.name, func.MakeOriginalArgString(""))) file.Write("}\n") file.Write("\n")
[ "def", "WriteGLES2TraceImplementation", "(", "self", ",", "func", ",", "file", ")", ":", "file", ".", "Write", "(", "\"%s GLES2TraceImplementation::%s(%s) {\\n\"", "%", "(", "func", ".", "return_type", ",", "func", ".", "original_name", ",", "func", ".", "MakeTypedOriginalArgString", "(", "\"\"", ")", ")", ")", "result_string", "=", "\"return \"", "if", "func", ".", "return_type", "==", "\"void\"", ":", "result_string", "=", "\"\"", "file", ".", "Write", "(", "' TRACE_EVENT_BINARY_EFFICIENT0(\"gpu\", \"GLES2Trace::%s\");\\n'", "%", "func", ".", "name", ")", "file", ".", "Write", "(", "\" %sgl_->%s(%s);\\n\"", "%", "(", "result_string", ",", "func", ".", "name", ",", "func", ".", "MakeOriginalArgString", "(", "\"\"", ")", ")", ")", "file", ".", "Write", "(", "\"}\\n\"", ")", "file", ".", "Write", "(", "\"\\n\"", ")" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/gpu/command_buffer/build_gles2_cmd_buffer.py#L3064-L3077
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/pkg_resources/_vendor/pyparsing.py
python
ParserElement.setResultsName
( self, name, listAllMatches=False )
return newself
Define name for referencing matching tokens as a nested attribute of the returned parse results. NOTE: this returns a *copy* of the original C{ParserElement} object; this is so that the client can define a basic element, such as an integer, and reference it in multiple places with different names. You can also set results names using the abbreviated syntax, C{expr("name")} in place of C{expr.setResultsName("name")} - see L{I{__call__}<__call__>}. Example:: date_str = (integer.setResultsName("year") + '/' + integer.setResultsName("month") + '/' + integer.setResultsName("day")) # equivalent form: date_str = integer("year") + '/' + integer("month") + '/' + integer("day")
Define name for referencing matching tokens as a nested attribute of the returned parse results. NOTE: this returns a *copy* of the original C{ParserElement} object; this is so that the client can define a basic element, such as an integer, and reference it in multiple places with different names.
[ "Define", "name", "for", "referencing", "matching", "tokens", "as", "a", "nested", "attribute", "of", "the", "returned", "parse", "results", ".", "NOTE", ":", "this", "returns", "a", "*", "copy", "*", "of", "the", "original", "C", "{", "ParserElement", "}", "object", ";", "this", "is", "so", "that", "the", "client", "can", "define", "a", "basic", "element", "such", "as", "an", "integer", "and", "reference", "it", "in", "multiple", "places", "with", "different", "names", "." ]
def setResultsName( self, name, listAllMatches=False ): """ Define name for referencing matching tokens as a nested attribute of the returned parse results. NOTE: this returns a *copy* of the original C{ParserElement} object; this is so that the client can define a basic element, such as an integer, and reference it in multiple places with different names. You can also set results names using the abbreviated syntax, C{expr("name")} in place of C{expr.setResultsName("name")} - see L{I{__call__}<__call__>}. Example:: date_str = (integer.setResultsName("year") + '/' + integer.setResultsName("month") + '/' + integer.setResultsName("day")) # equivalent form: date_str = integer("year") + '/' + integer("month") + '/' + integer("day") """ newself = self.copy() if name.endswith("*"): name = name[:-1] listAllMatches=True newself.resultsName = name newself.modalResults = not listAllMatches return newself
[ "def", "setResultsName", "(", "self", ",", "name", ",", "listAllMatches", "=", "False", ")", ":", "newself", "=", "self", ".", "copy", "(", ")", "if", "name", ".", "endswith", "(", "\"*\"", ")", ":", "name", "=", "name", "[", ":", "-", "1", "]", "listAllMatches", "=", "True", "newself", ".", "resultsName", "=", "name", "newself", ".", "modalResults", "=", "not", "listAllMatches", "return", "newself" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/pkg_resources/_vendor/pyparsing.py#L1204-L1230
adobe/chromium
cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7
remoting/tools/hostdir.py
python
list_cmd
(args)
return 0
list command
list command
[ "list", "command" ]
def list_cmd(args): """list command""" if len(args) != 0: return usage() (username, token) = load_auth_token() client = HostDirectory(username, token) print '%36s %30s %s' % ("HOST ID", "HOST NAME", "JABBER ID") for host in client.get_hosts(): print '%36s %30s %s' % (host.host_id, host.host_name, host.jabber_id) return 0
[ "def", "list_cmd", "(", "args", ")", ":", "if", "len", "(", "args", ")", "!=", "0", ":", "return", "usage", "(", ")", "(", "username", ",", "token", ")", "=", "load_auth_token", "(", ")", "client", "=", "HostDirectory", "(", "username", ",", "token", ")", "print", "'%36s %30s %s'", "%", "(", "\"HOST ID\"", ",", "\"HOST NAME\"", ",", "\"JABBER ID\"", ")", "for", "host", "in", "client", ".", "get_hosts", "(", ")", ":", "print", "'%36s %30s %s'", "%", "(", "host", ".", "host_id", ",", "host", ".", "host_name", ",", "host", ".", "jabber_id", ")", "return", "0" ]
https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/remoting/tools/hostdir.py#L157-L166
materialx/MaterialX
77ff72f352470b5c76dddde765951a8e3bcf79fc
python/MaterialX/main.py
python
_setParameterValue
(self, name, value, typeString = '')
(Deprecated) Set the typed value of a parameter by its name.
(Deprecated) Set the typed value of a parameter by its name.
[ "(", "Deprecated", ")", "Set", "the", "typed", "value", "of", "a", "parameter", "by", "its", "name", "." ]
def _setParameterValue(self, name, value, typeString = ''): """(Deprecated) Set the typed value of a parameter by its name.""" warnings.warn("This function is deprecated; parameters have been replaced with uniform inputs in 1.38.", DeprecationWarning, stacklevel = 2)
[ "def", "_setParameterValue", "(", "self", ",", "name", ",", "value", ",", "typeString", "=", "''", ")", ":", "warnings", ".", "warn", "(", "\"This function is deprecated; parameters have been replaced with uniform inputs in 1.38.\"", ",", "DeprecationWarning", ",", "stacklevel", "=", "2", ")" ]
https://github.com/materialx/MaterialX/blob/77ff72f352470b5c76dddde765951a8e3bcf79fc/python/MaterialX/main.py#L119-L121
apache/incubator-mxnet
f03fb23f1d103fec9541b5ae59ee06b1734a51d9
python/mxnet/profiler.py
python
Domain.new_counter
(self, name, value=None)
return Counter(self, name, value)
Create new Counter object owned by this domain Parameters ---------- name : string Name of the counter
Create new Counter object owned by this domain
[ "Create", "new", "Counter", "object", "owned", "by", "this", "domain" ]
def new_counter(self, name, value=None): """Create new Counter object owned by this domain Parameters ---------- name : string Name of the counter """ return Counter(self, name, value)
[ "def", "new_counter", "(", "self", ",", "name", ",", "value", "=", "None", ")", ":", "return", "Counter", "(", "self", ",", "name", ",", "value", ")" ]
https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/profiler.py#L267-L275
dmlc/treelite
df56babb6a4a2d7c29d719c28ce53acfa7dbab3c
python/treelite/contrib/__init__.py
python
expand_windows_path
(dirpath)
return dirpath
Expand a short path to full path (only applicable for Windows) Parameters ---------- dirpath : :py:class:`str <python:str>` Path to expand Returns ------- fullpath : :py:class:`str <python:str>` Expanded path
Expand a short path to full path (only applicable for Windows)
[ "Expand", "a", "short", "path", "to", "full", "path", "(", "only", "applicable", "for", "Windows", ")" ]
def expand_windows_path(dirpath): """ Expand a short path to full path (only applicable for Windows) Parameters ---------- dirpath : :py:class:`str <python:str>` Path to expand Returns ------- fullpath : :py:class:`str <python:str>` Expanded path """ if sys.platform == 'win32': buffer_size = 500 buffer = ctypes.create_unicode_buffer(buffer_size) get_long_path_name = ctypes.windll.kernel32.GetLongPathNameW get_long_path_name.argtypes = [ctypes.c_wchar_p, ctypes.c_wchar_p, ctypes.c_uint] get_long_path_name(dirpath, buffer, buffer_size) return buffer.value return dirpath
[ "def", "expand_windows_path", "(", "dirpath", ")", ":", "if", "sys", ".", "platform", "==", "'win32'", ":", "buffer_size", "=", "500", "buffer", "=", "ctypes", ".", "create_unicode_buffer", "(", "buffer_size", ")", "get_long_path_name", "=", "ctypes", ".", "windll", ".", "kernel32", ".", "GetLongPathNameW", "get_long_path_name", ".", "argtypes", "=", "[", "ctypes", ".", "c_wchar_p", ",", "ctypes", ".", "c_wchar_p", ",", "ctypes", ".", "c_uint", "]", "get_long_path_name", "(", "dirpath", ",", "buffer", ",", "buffer_size", ")", "return", "buffer", ".", "value", "return", "dirpath" ]
https://github.com/dmlc/treelite/blob/df56babb6a4a2d7c29d719c28ce53acfa7dbab3c/python/treelite/contrib/__init__.py#L16-L37
rrwick/Unicycler
96ffea71e3a78d63ade19d6124946773e65cf129
unicycler/misc.py
python
get_right_arrow
()
This function returns either a Unicode right arrow or '->', depending on the system encoding.
This function returns either a Unicode right arrow or '->', depending on the system encoding.
[ "This", "function", "returns", "either", "a", "Unicode", "right", "arrow", "or", "-", ">", "depending", "on", "the", "system", "encoding", "." ]
def get_right_arrow(): """ This function returns either a Unicode right arrow or '->', depending on the system encoding. """ try: '\u2192'.encode(sys.stdout.encoding) except (AttributeError, UnicodeEncodeError): return '->' else: return '\u2192'
[ "def", "get_right_arrow", "(", ")", ":", "try", ":", "'\\u2192'", ".", "encode", "(", "sys", ".", "stdout", ".", "encoding", ")", "except", "(", "AttributeError", ",", "UnicodeEncodeError", ")", ":", "return", "'->'", "else", ":", "return", "'\\u2192'" ]
https://github.com/rrwick/Unicycler/blob/96ffea71e3a78d63ade19d6124946773e65cf129/unicycler/misc.py#L783-L792
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/distutils/filelist.py
python
FileList.debug_print
(self, msg)
Print 'msg' to stdout if the global DEBUG (taken from the DISTUTILS_DEBUG environment variable) flag is true.
Print 'msg' to stdout if the global DEBUG (taken from the DISTUTILS_DEBUG environment variable) flag is true.
[ "Print", "msg", "to", "stdout", "if", "the", "global", "DEBUG", "(", "taken", "from", "the", "DISTUTILS_DEBUG", "environment", "variable", ")", "flag", "is", "true", "." ]
def debug_print(self, msg): """Print 'msg' to stdout if the global DEBUG (taken from the DISTUTILS_DEBUG environment variable) flag is true. """ from distutils.debug import DEBUG if DEBUG: print(msg)
[ "def", "debug_print", "(", "self", ",", "msg", ")", ":", "from", "distutils", ".", "debug", "import", "DEBUG", "if", "DEBUG", ":", "print", "(", "msg", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/distutils/filelist.py#L41-L47
NVIDIA/MDL-SDK
aa9642b2546ad7b6236b5627385d882c2ed83c5d
src/mdl/jit/llvm/dist/utils/lit/lit/llvm/config.py
python
LLVMConfig.use_llvm_tool
(self, name, search_env=None, required=False, quiet=False)
return tool
Find the executable program 'name', optionally using the specified environment variable as an override before searching the configuration's PATH.
Find the executable program 'name', optionally using the specified environment variable as an override before searching the configuration's PATH.
[ "Find", "the", "executable", "program", "name", "optionally", "using", "the", "specified", "environment", "variable", "as", "an", "override", "before", "searching", "the", "configuration", "s", "PATH", "." ]
def use_llvm_tool(self, name, search_env=None, required=False, quiet=False): """Find the executable program 'name', optionally using the specified environment variable as an override before searching the configuration's PATH.""" # If the override is specified in the environment, use it without # validation. if search_env: tool = self.config.environment.get(search_env) if tool: return tool # Otherwise look in the path. tool = lit.util.which(name, self.config.environment['PATH']) if required and not tool: message = "couldn't find '{}' program".format(name) if search_env: message = message + \ ', try setting {} in your environment'.format(search_env) self.lit_config.fatal(message) if tool: tool = os.path.normpath(tool) if not self.lit_config.quiet and not quiet: self.lit_config.note('using {}: {}'.format(name, tool)) return tool
[ "def", "use_llvm_tool", "(", "self", ",", "name", ",", "search_env", "=", "None", ",", "required", "=", "False", ",", "quiet", "=", "False", ")", ":", "# If the override is specified in the environment, use it without", "# validation.", "if", "search_env", ":", "tool", "=", "self", ".", "config", ".", "environment", ".", "get", "(", "search_env", ")", "if", "tool", ":", "return", "tool", "# Otherwise look in the path.", "tool", "=", "lit", ".", "util", ".", "which", "(", "name", ",", "self", ".", "config", ".", "environment", "[", "'PATH'", "]", ")", "if", "required", "and", "not", "tool", ":", "message", "=", "\"couldn't find '{}' program\"", ".", "format", "(", "name", ")", "if", "search_env", ":", "message", "=", "message", "+", "', try setting {} in your environment'", ".", "format", "(", "search_env", ")", "self", ".", "lit_config", ".", "fatal", "(", "message", ")", "if", "tool", ":", "tool", "=", "os", ".", "path", ".", "normpath", "(", "tool", ")", "if", "not", "self", ".", "lit_config", ".", "quiet", "and", "not", "quiet", ":", "self", ".", "lit_config", ".", "note", "(", "'using {}: {}'", ".", "format", "(", "name", ",", "tool", ")", ")", "return", "tool" ]
https://github.com/NVIDIA/MDL-SDK/blob/aa9642b2546ad7b6236b5627385d882c2ed83c5d/src/mdl/jit/llvm/dist/utils/lit/lit/llvm/config.py#L307-L332
vicaya/hypertable
e7386f799c238c109ae47973417c2a2c7f750825
src/py/ThriftClient/gen-py/hyperthrift/gen/ClientService.py
python
Client.get_row_as_arrays
(self, name, row)
return self.recv_get_row_as_arrays()
Alternative interface using array as cell Parameters: - name - row
Alternative interface using array as cell Parameters: - name - row
[ "Alternative", "interface", "using", "array", "as", "cell", "Parameters", ":", "-", "name", "-", "row" ]
def get_row_as_arrays(self, name, row): """ Alternative interface using array as cell Parameters: - name - row """ self.send_get_row_as_arrays(name, row) return self.recv_get_row_as_arrays()
[ "def", "get_row_as_arrays", "(", "self", ",", "name", ",", "row", ")", ":", "self", ".", "send_get_row_as_arrays", "(", "name", ",", "row", ")", "return", "self", ".", "recv_get_row_as_arrays", "(", ")" ]
https://github.com/vicaya/hypertable/blob/e7386f799c238c109ae47973417c2a2c7f750825/src/py/ThriftClient/gen-py/hyperthrift/gen/ClientService.py#L622-L631
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/calendar.py
python
formatstring
(cols, colwidth=_colwidth, spacing=_spacing)
return spacing.join(c.center(colwidth) for c in cols)
Returns a string formatted from n strings, centered within n columns.
Returns a string formatted from n strings, centered within n columns.
[ "Returns", "a", "string", "formatted", "from", "n", "strings", "centered", "within", "n", "columns", "." ]
def formatstring(cols, colwidth=_colwidth, spacing=_spacing): """Returns a string formatted from n strings, centered within n columns.""" spacing *= ' ' return spacing.join(c.center(colwidth) for c in cols)
[ "def", "formatstring", "(", "cols", ",", "colwidth", "=", "_colwidth", ",", "spacing", "=", "_spacing", ")", ":", "spacing", "*=", "' '", "return", "spacing", ".", "join", "(", "c", ".", "center", "(", "colwidth", ")", "for", "c", "in", "cols", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/calendar.py#L645-L648
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/python/ops/variables.py
python
Variable._set_save_slice_info
(self, save_slice_info)
Sets the slice info for this `Variable`. Args: save_slice_info: A `Variable.SaveSliceInfo` object.
Sets the slice info for this `Variable`.
[ "Sets", "the", "slice", "info", "for", "this", "Variable", "." ]
def _set_save_slice_info(self, save_slice_info): """Sets the slice info for this `Variable`. Args: save_slice_info: A `Variable.SaveSliceInfo` object. """ self._save_slice_info = save_slice_info
[ "def", "_set_save_slice_info", "(", "self", ",", "save_slice_info", ")", ":", "self", ".", "_save_slice_info", "=", "save_slice_info" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/ops/variables.py#L965-L971
moflow/moflow
2dfb27c799c90c6caf1477508eca3eec616ef7d2
bap/libtracewrap/libtrace/protobuf/python/google/protobuf/service_reflection.py
python
_ServiceBuilder._GetResponseClass
(self, method_descriptor)
return method_descriptor.output_type._concrete_class
Returns the class of the response protocol message. Args: method_descriptor: Descriptor of the method for which to return the response protocol message class. Returns: A class that represents the output protocol message of the specified method.
Returns the class of the response protocol message.
[ "Returns", "the", "class", "of", "the", "response", "protocol", "message", "." ]
def _GetResponseClass(self, method_descriptor): """Returns the class of the response protocol message. Args: method_descriptor: Descriptor of the method for which to return the response protocol message class. Returns: A class that represents the output protocol message of the specified method. """ if method_descriptor.containing_service != self.descriptor: raise RuntimeError( 'GetResponseClass() given method descriptor for wrong service type.') return method_descriptor.output_type._concrete_class
[ "def", "_GetResponseClass", "(", "self", ",", "method_descriptor", ")", ":", "if", "method_descriptor", ".", "containing_service", "!=", "self", ".", "descriptor", ":", "raise", "RuntimeError", "(", "'GetResponseClass() given method descriptor for wrong service type.'", ")", "return", "method_descriptor", ".", "output_type", ".", "_concrete_class" ]
https://github.com/moflow/moflow/blob/2dfb27c799c90c6caf1477508eca3eec616ef7d2/bap/libtracewrap/libtrace/protobuf/python/google/protobuf/service_reflection.py#L189-L203
intel/llvm
e6d0547e9d99b5a56430c4749f6c7e328bf221ab
mlir/utils/spirv/gen_spirv_dialect.py
python
get_capability_mapping
(operand_kinds)
return capability_mapping
Returns the capability mapping from duplicated cases to canonicalized ones. Arguments: - operand_kinds: all operand kinds' grammar spec Returns: - A map mapping from duplicated capability symbols to the canonicalized symbol chosen for SPIRVBase.td.
Returns the capability mapping from duplicated cases to canonicalized ones.
[ "Returns", "the", "capability", "mapping", "from", "duplicated", "cases", "to", "canonicalized", "ones", "." ]
def get_capability_mapping(operand_kinds): """Returns the capability mapping from duplicated cases to canonicalized ones. Arguments: - operand_kinds: all operand kinds' grammar spec Returns: - A map mapping from duplicated capability symbols to the canonicalized symbol chosen for SPIRVBase.td. """ # Find the operand kind for capability cap_kind = {} for kind in operand_kinds: if kind['kind'] == 'Capability': cap_kind = kind kind_cases = [ (case['enumerant'], case['value']) for case in cap_kind['enumerants'] ] _, capability_mapping = uniquify_enum_cases(kind_cases) return capability_mapping
[ "def", "get_capability_mapping", "(", "operand_kinds", ")", ":", "# Find the operand kind for capability", "cap_kind", "=", "{", "}", "for", "kind", "in", "operand_kinds", ":", "if", "kind", "[", "'kind'", "]", "==", "'Capability'", ":", "cap_kind", "=", "kind", "kind_cases", "=", "[", "(", "case", "[", "'enumerant'", "]", ",", "case", "[", "'value'", "]", ")", "for", "case", "in", "cap_kind", "[", "'enumerants'", "]", "]", "_", ",", "capability_mapping", "=", "uniquify_enum_cases", "(", "kind_cases", ")", "return", "capability_mapping" ]
https://github.com/intel/llvm/blob/e6d0547e9d99b5a56430c4749f6c7e328bf221ab/mlir/utils/spirv/gen_spirv_dialect.py#L225-L246
google/or-tools
2cb85b4eead4c38e1c54b48044f92087cf165bce
ortools/sat/python/cp_model.py
python
CpModel.NewOptionalIntervalVar
(self, start, size, end, is_present, name)
return IntervalVar(self.__model, start_expr, size_expr, end_expr, is_present_index, name)
Creates an optional interval var from start, size, end, and is_present. An optional interval variable is a constraint, that is itself used in other constraints like NoOverlap. This constraint is protected by an is_present literal that indicates if it is active or not. Internally, it ensures that `is_present` implies `start + size == end`. Args: start: The start of the interval. It can be an integer value, or an integer variable. size: The size of the interval. It can be an integer value, or an integer variable. end: The end of the interval. It can be an integer value, or an integer variable. is_present: A literal that indicates if the interval is active or not. A inactive interval is simply ignored by all constraints. name: The name of the interval variable. Returns: An `IntervalVar` object.
Creates an optional interval var from start, size, end, and is_present.
[ "Creates", "an", "optional", "interval", "var", "from", "start", "size", "end", "and", "is_present", "." ]
def NewOptionalIntervalVar(self, start, size, end, is_present, name): """Creates an optional interval var from start, size, end, and is_present. An optional interval variable is a constraint, that is itself used in other constraints like NoOverlap. This constraint is protected by an is_present literal that indicates if it is active or not. Internally, it ensures that `is_present` implies `start + size == end`. Args: start: The start of the interval. It can be an integer value, or an integer variable. size: The size of the interval. It can be an integer value, or an integer variable. end: The end of the interval. It can be an integer value, or an integer variable. is_present: A literal that indicates if the interval is active or not. A inactive interval is simply ignored by all constraints. name: The name of the interval variable. Returns: An `IntervalVar` object. """ # Add the linear constraint. self.Add(start + size == end).OnlyEnforceIf(is_present) # Creates the IntervalConstraintProto object. is_present_index = self.GetOrMakeBooleanIndex(is_present) start_expr = self.ParseLinearExpression(start) size_expr = self.ParseLinearExpression(size) end_expr = self.ParseLinearExpression(end) if len(start_expr.vars) > 1: raise TypeError( 'cp_model.NewIntervalVar: start must be affine or constant.') if len(size_expr.vars) > 1: raise TypeError( 'cp_model.NewIntervalVar: size must be affine or constant.') if len(end_expr.vars) > 1: raise TypeError( 'cp_model.NewIntervalVar: end must be affine or constant.') return IntervalVar(self.__model, start_expr, size_expr, end_expr, is_present_index, name)
[ "def", "NewOptionalIntervalVar", "(", "self", ",", "start", ",", "size", ",", "end", ",", "is_present", ",", "name", ")", ":", "# Add the linear constraint.", "self", ".", "Add", "(", "start", "+", "size", "==", "end", ")", ".", "OnlyEnforceIf", "(", "is_present", ")", "# Creates the IntervalConstraintProto object.", "is_present_index", "=", "self", ".", "GetOrMakeBooleanIndex", "(", "is_present", ")", "start_expr", "=", "self", ".", "ParseLinearExpression", "(", "start", ")", "size_expr", "=", "self", ".", "ParseLinearExpression", "(", "size", ")", "end_expr", "=", "self", ".", "ParseLinearExpression", "(", "end", ")", "if", "len", "(", "start_expr", ".", "vars", ")", ">", "1", ":", "raise", "TypeError", "(", "'cp_model.NewIntervalVar: start must be affine or constant.'", ")", "if", "len", "(", "size_expr", ".", "vars", ")", ">", "1", ":", "raise", "TypeError", "(", "'cp_model.NewIntervalVar: size must be affine or constant.'", ")", "if", "len", "(", "end_expr", ".", "vars", ")", ">", "1", ":", "raise", "TypeError", "(", "'cp_model.NewIntervalVar: end must be affine or constant.'", ")", "return", "IntervalVar", "(", "self", ".", "__model", ",", "start_expr", ",", "size_expr", ",", "end_expr", ",", "is_present_index", ",", "name", ")" ]
https://github.com/google/or-tools/blob/2cb85b4eead4c38e1c54b48044f92087cf165bce/ortools/sat/python/cp_model.py#L1614-L1656
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/ops/composite/multitype_ops/_compile_utils.py
python
reduce_
(a, reduce_fn, cmp_fn=None, axis=None, keepdims=False, initial=None, where=True, dtype=None)
return reduce_fn(a, axes).astype(dtype)
Applies comparison based on cmp_fn and reduction based on reduce_fn. If cmp_fn is None, only reduction is performed.
Applies comparison based on cmp_fn and reduction based on reduce_fn. If cmp_fn is None, only reduction is performed.
[ "Applies", "comparison", "based", "on", "cmp_fn", "and", "reduction", "based", "on", "reduce_fn", ".", "If", "cmp_fn", "is", "None", "only", "reduction", "is", "performed", "." ]
def reduce_(a, reduce_fn, cmp_fn=None, axis=None, keepdims=False, initial=None, where=True, dtype=None): """ Applies comparison based on cmp_fn and reduction based on reduce_fn. If cmp_fn is None, only reduction is performed. """ shape = F.shape(a) ndim = F.rank(a) if dtype is None: dtype = F.dtype(a) axes = const_utils.check_axis_valid_const(axis, ndim) if initial is not None: if ((isinstance(initial, Tensor) and F.rank(initial) > 0) or not isinstance(initial, (int, float, bool, Tensor))): const_utils.raise_type_error('initial should be scalar') if F.shape_mul(shape) == 0: const_utils.raise_value_error('zero-size tensors are not supported.') if initial is not None: if isinstance(initial, Tensor): initial = F.tile(initial, shape).astype(dtype) else: initial = F.fill(dtype, shape, initial) a = cmp_fn(a, initial) if isinstance(where, Tensor): if initial is None: const_utils.raise_value_error('initial value must be provided for where masks') ndim_orig = F.rank(a) # broadcasts input tensors shape_out = const_utils.infer_out_shape(F.shape(where), F.shape(a), F.shape(initial)) broadcast_to = P.BroadcastTo(shape_out) where = where.astype(mstype.float32) where = broadcast_to(where) where = where.astype(mstype.bool_) a = broadcast_to(a) initial = broadcast_to(initial) a = F.select(where, a, initial) axes = const_utils.real_axes(ndim_orig, F.rank(a), axes) return reduce_fn(a, axes).astype(dtype)
[ "def", "reduce_", "(", "a", ",", "reduce_fn", ",", "cmp_fn", "=", "None", ",", "axis", "=", "None", ",", "keepdims", "=", "False", ",", "initial", "=", "None", ",", "where", "=", "True", ",", "dtype", "=", "None", ")", ":", "shape", "=", "F", ".", "shape", "(", "a", ")", "ndim", "=", "F", ".", "rank", "(", "a", ")", "if", "dtype", "is", "None", ":", "dtype", "=", "F", ".", "dtype", "(", "a", ")", "axes", "=", "const_utils", ".", "check_axis_valid_const", "(", "axis", ",", "ndim", ")", "if", "initial", "is", "not", "None", ":", "if", "(", "(", "isinstance", "(", "initial", ",", "Tensor", ")", "and", "F", ".", "rank", "(", "initial", ")", ">", "0", ")", "or", "not", "isinstance", "(", "initial", ",", "(", "int", ",", "float", ",", "bool", ",", "Tensor", ")", ")", ")", ":", "const_utils", ".", "raise_type_error", "(", "'initial should be scalar'", ")", "if", "F", ".", "shape_mul", "(", "shape", ")", "==", "0", ":", "const_utils", ".", "raise_value_error", "(", "'zero-size tensors are not supported.'", ")", "if", "initial", "is", "not", "None", ":", "if", "isinstance", "(", "initial", ",", "Tensor", ")", ":", "initial", "=", "F", ".", "tile", "(", "initial", ",", "shape", ")", ".", "astype", "(", "dtype", ")", "else", ":", "initial", "=", "F", ".", "fill", "(", "dtype", ",", "shape", ",", "initial", ")", "a", "=", "cmp_fn", "(", "a", ",", "initial", ")", "if", "isinstance", "(", "where", ",", "Tensor", ")", ":", "if", "initial", "is", "None", ":", "const_utils", ".", "raise_value_error", "(", "'initial value must be provided for where masks'", ")", "ndim_orig", "=", "F", ".", "rank", "(", "a", ")", "# broadcasts input tensors", "shape_out", "=", "const_utils", ".", "infer_out_shape", "(", "F", ".", "shape", "(", "where", ")", ",", "F", ".", "shape", "(", "a", ")", ",", "F", ".", "shape", "(", "initial", ")", ")", "broadcast_to", "=", "P", ".", "BroadcastTo", "(", "shape_out", ")", "where", "=", "where", ".", "astype", "(", "mstype", ".", "float32", ")", "where", "=", "broadcast_to", "(", "where", ")", "where", "=", "where", ".", "astype", "(", "mstype", ".", "bool_", ")", "a", "=", "broadcast_to", "(", "a", ")", "initial", "=", "broadcast_to", "(", "initial", ")", "a", "=", "F", ".", "select", "(", "where", ",", "a", ",", "initial", ")", "axes", "=", "const_utils", ".", "real_axes", "(", "ndim_orig", ",", "F", ".", "rank", "(", "a", ")", ",", "axes", ")", "return", "reduce_fn", "(", "a", ",", "axes", ")", ".", "astype", "(", "dtype", ")" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/composite/multitype_ops/_compile_utils.py#L1097-L1138
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_internal/vcs/subversion.py
python
Subversion.get_netloc_and_auth
(cls, netloc, scheme)
return split_auth_from_netloc(netloc)
This override allows the auth information to be passed to svn via the --username and --password options instead of via the URL.
[]
def get_netloc_and_auth(cls, netloc, scheme): """ This override allows the auth information to be passed to svn via the --username and --password options instead of via the URL. """ if scheme == 'ssh': # The --username and --password options can't be used for # svn+ssh URLs, so keep the auth information in the URL. return super().get_netloc_and_auth(netloc, scheme) return split_auth_from_netloc(netloc)
[ "def", "get_netloc_and_auth", "(", "cls", ",", "netloc", ",", "scheme", ")", ":", "if", "scheme", "==", "'ssh'", ":", "# The --username and --password options can't be used for", "# svn+ssh URLs, so keep the auth information in the URL.", "return", "super", "(", ")", ".", "get_netloc_and_auth", "(", "netloc", ",", "scheme", ")", "return", "split_auth_from_netloc", "(", "netloc", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_internal/vcs/subversion.py#L163-L183
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/BaseHTTPServer.py
python
BaseHTTPRequestHandler.send_response
(self, code, message=None)
Send the response header and log the response code. Also send two standard headers with the server software version and the current date.
Send the response header and log the response code.
[ "Send", "the", "response", "header", "and", "log", "the", "response", "code", "." ]
def send_response(self, code, message=None): """Send the response header and log the response code. Also send two standard headers with the server software version and the current date. """ self.log_request(code) if message is None: if code in self.responses: message = self.responses[code][0] else: message = '' if self.request_version != 'HTTP/0.9': self.wfile.write("%s %d %s\r\n" % (self.protocol_version, code, message)) # print (self.protocol_version, code, message) self.send_header('Server', self.version_string()) self.send_header('Date', self.date_time_string())
[ "def", "send_response", "(", "self", ",", "code", ",", "message", "=", "None", ")", ":", "self", ".", "log_request", "(", "code", ")", "if", "message", "is", "None", ":", "if", "code", "in", "self", ".", "responses", ":", "message", "=", "self", ".", "responses", "[", "code", "]", "[", "0", "]", "else", ":", "message", "=", "''", "if", "self", ".", "request_version", "!=", "'HTTP/0.9'", ":", "self", ".", "wfile", ".", "write", "(", "\"%s %d %s\\r\\n\"", "%", "(", "self", ".", "protocol_version", ",", "code", ",", "message", ")", ")", "# print (self.protocol_version, code, message)", "self", ".", "send_header", "(", "'Server'", ",", "self", ".", "version_string", "(", ")", ")", "self", ".", "send_header", "(", "'Date'", ",", "self", ".", "date_time_string", "(", ")", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/BaseHTTPServer.py#L389-L407
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/pydoc.py
python
TextDoc.formatvalue
(self, object)
return '=' + self.repr(object)
Format an argument default value as text.
Format an argument default value as text.
[ "Format", "an", "argument", "default", "value", "as", "text", "." ]
def formatvalue(self, object): """Format an argument default value as text.""" return '=' + self.repr(object)
[ "def", "formatvalue", "(", "self", ",", "object", ")", ":", "return", "'='", "+", "self", ".", "repr", "(", "object", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/pydoc.py#L1251-L1253
facebookresearch/SparseConvNet
fe38ab5845c1c0aaf46d943f52b15243011dbe93
sparseconvnet/sparseConvNetTensor.py
python
SparseConvNetTensor.get_spatial_locations
(self, spatial_size=None)
return t
Coordinates and batch index for the active spatial locations
Coordinates and batch index for the active spatial locations
[ "Coordinates", "and", "batch", "index", "for", "the", "active", "spatial", "locations" ]
def get_spatial_locations(self, spatial_size=None): "Coordinates and batch index for the active spatial locations" if spatial_size is None: spatial_size = self.spatial_size t = self.metadata.getSpatialLocations(spatial_size) return t
[ "def", "get_spatial_locations", "(", "self", ",", "spatial_size", "=", "None", ")", ":", "if", "spatial_size", "is", "None", ":", "spatial_size", "=", "self", ".", "spatial_size", "t", "=", "self", ".", "metadata", ".", "getSpatialLocations", "(", "spatial_size", ")", "return", "t" ]
https://github.com/facebookresearch/SparseConvNet/blob/fe38ab5845c1c0aaf46d943f52b15243011dbe93/sparseconvnet/sparseConvNetTensor.py#L18-L23
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
models/AI-Model-Zoo/caffe-xilinx/python/caffe/io.py
python
Transformer.set_mean
(self, in_, mean)
Set the mean to subtract for centering the data. Parameters ---------- in_ : which input to assign this mean. mean : mean ndarray (input dimensional or broadcastable)
Set the mean to subtract for centering the data.
[ "Set", "the", "mean", "to", "subtract", "for", "centering", "the", "data", "." ]
def set_mean(self, in_, mean): """ Set the mean to subtract for centering the data. Parameters ---------- in_ : which input to assign this mean. mean : mean ndarray (input dimensional or broadcastable) """ self.__check_input(in_) ms = mean.shape if mean.ndim == 1: # broadcast channels if ms[0] != self.inputs[in_][1]: raise ValueError('Mean channels incompatible with input.') mean = mean[:, np.newaxis, np.newaxis] else: # elementwise mean if len(ms) == 2: ms = (1,) + ms if len(ms) != 3: raise ValueError('Mean shape invalid') if ms != self.inputs[in_][1:]: raise ValueError('Mean shape incompatible with input shape.') self.mean[in_] = mean
[ "def", "set_mean", "(", "self", ",", "in_", ",", "mean", ")", ":", "self", ".", "__check_input", "(", "in_", ")", "ms", "=", "mean", ".", "shape", "if", "mean", ".", "ndim", "==", "1", ":", "# broadcast channels", "if", "ms", "[", "0", "]", "!=", "self", ".", "inputs", "[", "in_", "]", "[", "1", "]", ":", "raise", "ValueError", "(", "'Mean channels incompatible with input.'", ")", "mean", "=", "mean", "[", ":", ",", "np", ".", "newaxis", ",", "np", ".", "newaxis", "]", "else", ":", "# elementwise mean", "if", "len", "(", "ms", ")", "==", "2", ":", "ms", "=", "(", "1", ",", ")", "+", "ms", "if", "len", "(", "ms", ")", "!=", "3", ":", "raise", "ValueError", "(", "'Mean shape invalid'", ")", "if", "ms", "!=", "self", ".", "inputs", "[", "in_", "]", "[", "1", ":", "]", ":", "raise", "ValueError", "(", "'Mean shape incompatible with input shape.'", ")", "self", ".", "mean", "[", "in_", "]", "=", "mean" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/models/AI-Model-Zoo/caffe-xilinx/python/caffe/io.py#L236-L260
lmb-freiburg/ogn
974f72ef4bf840d6f6693d22d1843a79223e77ce
scripts/cpp_lint.py
python
CheckCaffeRandom
(filename, clean_lines, linenum, error)
Checks for calls to C random functions (rand, rand_r, random, ...). Caffe code should (almost) always use the caffe_rng_* functions rather than these, as the internal state of these C functions is independent of the native Caffe RNG system which should produce deterministic results for a fixed Caffe seed set using Caffe::set_random_seed(...). 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.
Checks for calls to C random functions (rand, rand_r, random, ...).
[ "Checks", "for", "calls", "to", "C", "random", "functions", "(", "rand", "rand_r", "random", "...", ")", "." ]
def CheckCaffeRandom(filename, clean_lines, linenum, error): """Checks for calls to C random functions (rand, rand_r, random, ...). Caffe code should (almost) always use the caffe_rng_* functions rather than these, as the internal state of these C functions is independent of the native Caffe RNG system which should produce deterministic results for a fixed Caffe seed set using Caffe::set_random_seed(...). 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] for function in c_random_function_list: ix = line.find(function) # Comparisons made explicit for clarity -- pylint: disable=g-explicit-bool-comparison if ix >= 0 and (ix == 0 or (not line[ix - 1].isalnum() and line[ix - 1] not in ('_', '.', '>'))): error(filename, linenum, 'caffe/random_fn', 2, 'Use caffe_rng_rand() (or other caffe_rng_* function) instead of ' + function + ') to ensure results are deterministic for a fixed Caffe seed.')
[ "def", "CheckCaffeRandom", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "for", "function", "in", "c_random_function_list", ":", "ix", "=", "line", ".", "find", "(", "function", ")", "# Comparisons made explicit for clarity -- pylint: disable=g-explicit-bool-comparison", "if", "ix", ">=", "0", "and", "(", "ix", "==", "0", "or", "(", "not", "line", "[", "ix", "-", "1", "]", ".", "isalnum", "(", ")", "and", "line", "[", "ix", "-", "1", "]", "not", "in", "(", "'_'", ",", "'.'", ",", "'>'", ")", ")", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'caffe/random_fn'", ",", "2", ",", "'Use caffe_rng_rand() (or other caffe_rng_* function) instead of '", "+", "function", "+", "') to ensure results are deterministic for a fixed Caffe seed.'", ")" ]
https://github.com/lmb-freiburg/ogn/blob/974f72ef4bf840d6f6693d22d1843a79223e77ce/scripts/cpp_lint.py#L1640-L1663
apache/incubator-mxnet
f03fb23f1d103fec9541b5ae59ee06b1734a51d9
python/mxnet/base.py
python
c_handle_array
(objs)
return arr
Create ctypes const void ** from a list of MXNet objects with handles. Parameters ---------- objs : list of NDArray/Symbol. MXNet objects. Returns ------- (ctypes.c_void_p * len(objs)) A void ** pointer that can be passed to C API.
Create ctypes const void ** from a list of MXNet objects with handles.
[ "Create", "ctypes", "const", "void", "**", "from", "a", "list", "of", "MXNet", "objects", "with", "handles", "." ]
def c_handle_array(objs): """Create ctypes const void ** from a list of MXNet objects with handles. Parameters ---------- objs : list of NDArray/Symbol. MXNet objects. Returns ------- (ctypes.c_void_p * len(objs)) A void ** pointer that can be passed to C API. """ arr = (ctypes.c_void_p * len(objs))() arr[:] = [o.handle for o in objs] return arr
[ "def", "c_handle_array", "(", "objs", ")", ":", "arr", "=", "(", "ctypes", ".", "c_void_p", "*", "len", "(", "objs", ")", ")", "(", ")", "arr", "[", ":", "]", "=", "[", "o", ".", "handle", "for", "o", "in", "objs", "]", "return", "arr" ]
https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/base.py#L447-L462
domino-team/openwrt-cc
8b181297c34d14d3ca521cc9f31430d561dbc688
package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/msvs_emulation.py
python
MsvsSettings.GetLdflags
(self, config, gyp_to_build_path, expand_special, manifest_base_name, output_name, is_executable, build_dir)
return ldflags, intermediate_manifest, manifest_files
Returns the flags that need to be added to link commands, and the manifest files.
Returns the flags that need to be added to link commands, and the manifest files.
[ "Returns", "the", "flags", "that", "need", "to", "be", "added", "to", "link", "commands", "and", "the", "manifest", "files", "." ]
def GetLdflags(self, config, gyp_to_build_path, expand_special, manifest_base_name, output_name, is_executable, build_dir): """Returns the flags that need to be added to link commands, and the manifest files.""" config = self._TargetConfig(config) ldflags = [] ld = self._GetWrapper(self, self.msvs_settings[config], 'VCLinkerTool', append=ldflags) self._GetDefFileAsLdflags(ldflags, gyp_to_build_path) ld('GenerateDebugInformation', map={'true': '/DEBUG'}) ld('TargetMachine', map={'1': 'X86', '17': 'X64', '3': 'ARM'}, prefix='/MACHINE:') ldflags.extend(self._GetAdditionalLibraryDirectories( 'VCLinkerTool', config, gyp_to_build_path)) ld('DelayLoadDLLs', prefix='/DELAYLOAD:') ld('TreatLinkerWarningAsErrors', prefix='/WX', map={'true': '', 'false': ':NO'}) out = self.GetOutputName(config, expand_special) if out: ldflags.append('/OUT:' + out) pdb = self.GetPDBName(config, expand_special, output_name + '.pdb') if pdb: ldflags.append('/PDB:' + pdb) pgd = self.GetPGDName(config, expand_special) if pgd: ldflags.append('/PGD:' + pgd) map_file = self.GetMapFileName(config, expand_special) ld('GenerateMapFile', map={'true': '/MAP:' + map_file if map_file else '/MAP'}) ld('MapExports', map={'true': '/MAPINFO:EXPORTS'}) ld('AdditionalOptions', prefix='') minimum_required_version = self._Setting( ('VCLinkerTool', 'MinimumRequiredVersion'), config, default='') if minimum_required_version: minimum_required_version = ',' + minimum_required_version ld('SubSystem', map={'1': 'CONSOLE%s' % minimum_required_version, '2': 'WINDOWS%s' % minimum_required_version}, prefix='/SUBSYSTEM:') stack_reserve_size = self._Setting( ('VCLinkerTool', 'StackReserveSize'), config, default='') if stack_reserve_size: stack_commit_size = self._Setting( ('VCLinkerTool', 'StackCommitSize'), config, default='') if stack_commit_size: stack_commit_size = ',' + stack_commit_size ldflags.append('/STACK:%s%s' % (stack_reserve_size, stack_commit_size)) ld('TerminalServerAware', map={'1': ':NO', '2': ''}, prefix='/TSAWARE') ld('LinkIncremental', map={'1': ':NO', '2': ''}, prefix='/INCREMENTAL') ld('BaseAddress', prefix='/BASE:') ld('FixedBaseAddress', map={'1': ':NO', '2': ''}, prefix='/FIXED') ld('RandomizedBaseAddress', map={'1': ':NO', '2': ''}, prefix='/DYNAMICBASE') ld('DataExecutionPrevention', map={'1': ':NO', '2': ''}, prefix='/NXCOMPAT') ld('OptimizeReferences', map={'1': 'NOREF', '2': 'REF'}, prefix='/OPT:') ld('ForceSymbolReferences', prefix='/INCLUDE:') ld('EnableCOMDATFolding', map={'1': 'NOICF', '2': 'ICF'}, prefix='/OPT:') ld('LinkTimeCodeGeneration', map={'1': '', '2': ':PGINSTRUMENT', '3': ':PGOPTIMIZE', '4': ':PGUPDATE'}, prefix='/LTCG') ld('IgnoreDefaultLibraryNames', prefix='/NODEFAULTLIB:') ld('ResourceOnlyDLL', map={'true': '/NOENTRY'}) ld('EntryPointSymbol', prefix='/ENTRY:') ld('Profile', map={'true': '/PROFILE'}) ld('LargeAddressAware', map={'1': ':NO', '2': ''}, prefix='/LARGEADDRESSAWARE') # TODO(scottmg): This should sort of be somewhere else (not really a flag). ld('AdditionalDependencies', prefix='') if self.GetArch(config) == 'x86': safeseh_default = 'true' else: safeseh_default = None ld('ImageHasSafeExceptionHandlers', map={'false': ':NO', 'true': ''}, prefix='/SAFESEH', default=safeseh_default) # If the base address is not specifically controlled, DYNAMICBASE should # be on by default. base_flags = filter(lambda x: 'DYNAMICBASE' in x or x == '/FIXED', ldflags) if not base_flags: ldflags.append('/DYNAMICBASE') # If the NXCOMPAT flag has not been specified, default to on. Despite the # documentation that says this only defaults to on when the subsystem is # Vista or greater (which applies to the linker), the IDE defaults it on # unless it's explicitly off. if not filter(lambda x: 'NXCOMPAT' in x, ldflags): ldflags.append('/NXCOMPAT') have_def_file = filter(lambda x: x.startswith('/DEF:'), ldflags) manifest_flags, intermediate_manifest, manifest_files = \ self._GetLdManifestFlags(config, manifest_base_name, gyp_to_build_path, is_executable and not have_def_file, build_dir) ldflags.extend(manifest_flags) return ldflags, intermediate_manifest, manifest_files
[ "def", "GetLdflags", "(", "self", ",", "config", ",", "gyp_to_build_path", ",", "expand_special", ",", "manifest_base_name", ",", "output_name", ",", "is_executable", ",", "build_dir", ")", ":", "config", "=", "self", ".", "_TargetConfig", "(", "config", ")", "ldflags", "=", "[", "]", "ld", "=", "self", ".", "_GetWrapper", "(", "self", ",", "self", ".", "msvs_settings", "[", "config", "]", ",", "'VCLinkerTool'", ",", "append", "=", "ldflags", ")", "self", ".", "_GetDefFileAsLdflags", "(", "ldflags", ",", "gyp_to_build_path", ")", "ld", "(", "'GenerateDebugInformation'", ",", "map", "=", "{", "'true'", ":", "'/DEBUG'", "}", ")", "ld", "(", "'TargetMachine'", ",", "map", "=", "{", "'1'", ":", "'X86'", ",", "'17'", ":", "'X64'", ",", "'3'", ":", "'ARM'", "}", ",", "prefix", "=", "'/MACHINE:'", ")", "ldflags", ".", "extend", "(", "self", ".", "_GetAdditionalLibraryDirectories", "(", "'VCLinkerTool'", ",", "config", ",", "gyp_to_build_path", ")", ")", "ld", "(", "'DelayLoadDLLs'", ",", "prefix", "=", "'/DELAYLOAD:'", ")", "ld", "(", "'TreatLinkerWarningAsErrors'", ",", "prefix", "=", "'/WX'", ",", "map", "=", "{", "'true'", ":", "''", ",", "'false'", ":", "':NO'", "}", ")", "out", "=", "self", ".", "GetOutputName", "(", "config", ",", "expand_special", ")", "if", "out", ":", "ldflags", ".", "append", "(", "'/OUT:'", "+", "out", ")", "pdb", "=", "self", ".", "GetPDBName", "(", "config", ",", "expand_special", ",", "output_name", "+", "'.pdb'", ")", "if", "pdb", ":", "ldflags", ".", "append", "(", "'/PDB:'", "+", "pdb", ")", "pgd", "=", "self", ".", "GetPGDName", "(", "config", ",", "expand_special", ")", "if", "pgd", ":", "ldflags", ".", "append", "(", "'/PGD:'", "+", "pgd", ")", "map_file", "=", "self", ".", "GetMapFileName", "(", "config", ",", "expand_special", ")", "ld", "(", "'GenerateMapFile'", ",", "map", "=", "{", "'true'", ":", "'/MAP:'", "+", "map_file", "if", "map_file", "else", "'/MAP'", "}", ")", "ld", "(", "'MapExports'", ",", "map", "=", "{", "'true'", ":", "'/MAPINFO:EXPORTS'", "}", ")", "ld", "(", "'AdditionalOptions'", ",", "prefix", "=", "''", ")", "minimum_required_version", "=", "self", ".", "_Setting", "(", "(", "'VCLinkerTool'", ",", "'MinimumRequiredVersion'", ")", ",", "config", ",", "default", "=", "''", ")", "if", "minimum_required_version", ":", "minimum_required_version", "=", "','", "+", "minimum_required_version", "ld", "(", "'SubSystem'", ",", "map", "=", "{", "'1'", ":", "'CONSOLE%s'", "%", "minimum_required_version", ",", "'2'", ":", "'WINDOWS%s'", "%", "minimum_required_version", "}", ",", "prefix", "=", "'/SUBSYSTEM:'", ")", "stack_reserve_size", "=", "self", ".", "_Setting", "(", "(", "'VCLinkerTool'", ",", "'StackReserveSize'", ")", ",", "config", ",", "default", "=", "''", ")", "if", "stack_reserve_size", ":", "stack_commit_size", "=", "self", ".", "_Setting", "(", "(", "'VCLinkerTool'", ",", "'StackCommitSize'", ")", ",", "config", ",", "default", "=", "''", ")", "if", "stack_commit_size", ":", "stack_commit_size", "=", "','", "+", "stack_commit_size", "ldflags", ".", "append", "(", "'/STACK:%s%s'", "%", "(", "stack_reserve_size", ",", "stack_commit_size", ")", ")", "ld", "(", "'TerminalServerAware'", ",", "map", "=", "{", "'1'", ":", "':NO'", ",", "'2'", ":", "''", "}", ",", "prefix", "=", "'/TSAWARE'", ")", "ld", "(", "'LinkIncremental'", ",", "map", "=", "{", "'1'", ":", "':NO'", ",", "'2'", ":", "''", "}", ",", "prefix", "=", "'/INCREMENTAL'", ")", "ld", "(", "'BaseAddress'", ",", "prefix", "=", "'/BASE:'", ")", "ld", "(", "'FixedBaseAddress'", ",", "map", "=", "{", "'1'", ":", "':NO'", ",", "'2'", ":", "''", "}", ",", "prefix", "=", "'/FIXED'", ")", "ld", "(", "'RandomizedBaseAddress'", ",", "map", "=", "{", "'1'", ":", "':NO'", ",", "'2'", ":", "''", "}", ",", "prefix", "=", "'/DYNAMICBASE'", ")", "ld", "(", "'DataExecutionPrevention'", ",", "map", "=", "{", "'1'", ":", "':NO'", ",", "'2'", ":", "''", "}", ",", "prefix", "=", "'/NXCOMPAT'", ")", "ld", "(", "'OptimizeReferences'", ",", "map", "=", "{", "'1'", ":", "'NOREF'", ",", "'2'", ":", "'REF'", "}", ",", "prefix", "=", "'/OPT:'", ")", "ld", "(", "'ForceSymbolReferences'", ",", "prefix", "=", "'/INCLUDE:'", ")", "ld", "(", "'EnableCOMDATFolding'", ",", "map", "=", "{", "'1'", ":", "'NOICF'", ",", "'2'", ":", "'ICF'", "}", ",", "prefix", "=", "'/OPT:'", ")", "ld", "(", "'LinkTimeCodeGeneration'", ",", "map", "=", "{", "'1'", ":", "''", ",", "'2'", ":", "':PGINSTRUMENT'", ",", "'3'", ":", "':PGOPTIMIZE'", ",", "'4'", ":", "':PGUPDATE'", "}", ",", "prefix", "=", "'/LTCG'", ")", "ld", "(", "'IgnoreDefaultLibraryNames'", ",", "prefix", "=", "'/NODEFAULTLIB:'", ")", "ld", "(", "'ResourceOnlyDLL'", ",", "map", "=", "{", "'true'", ":", "'/NOENTRY'", "}", ")", "ld", "(", "'EntryPointSymbol'", ",", "prefix", "=", "'/ENTRY:'", ")", "ld", "(", "'Profile'", ",", "map", "=", "{", "'true'", ":", "'/PROFILE'", "}", ")", "ld", "(", "'LargeAddressAware'", ",", "map", "=", "{", "'1'", ":", "':NO'", ",", "'2'", ":", "''", "}", ",", "prefix", "=", "'/LARGEADDRESSAWARE'", ")", "# TODO(scottmg): This should sort of be somewhere else (not really a flag).", "ld", "(", "'AdditionalDependencies'", ",", "prefix", "=", "''", ")", "if", "self", ".", "GetArch", "(", "config", ")", "==", "'x86'", ":", "safeseh_default", "=", "'true'", "else", ":", "safeseh_default", "=", "None", "ld", "(", "'ImageHasSafeExceptionHandlers'", ",", "map", "=", "{", "'false'", ":", "':NO'", ",", "'true'", ":", "''", "}", ",", "prefix", "=", "'/SAFESEH'", ",", "default", "=", "safeseh_default", ")", "# If the base address is not specifically controlled, DYNAMICBASE should", "# be on by default.", "base_flags", "=", "filter", "(", "lambda", "x", ":", "'DYNAMICBASE'", "in", "x", "or", "x", "==", "'/FIXED'", ",", "ldflags", ")", "if", "not", "base_flags", ":", "ldflags", ".", "append", "(", "'/DYNAMICBASE'", ")", "# If the NXCOMPAT flag has not been specified, default to on. Despite the", "# documentation that says this only defaults to on when the subsystem is", "# Vista or greater (which applies to the linker), the IDE defaults it on", "# unless it's explicitly off.", "if", "not", "filter", "(", "lambda", "x", ":", "'NXCOMPAT'", "in", "x", ",", "ldflags", ")", ":", "ldflags", ".", "append", "(", "'/NXCOMPAT'", ")", "have_def_file", "=", "filter", "(", "lambda", "x", ":", "x", ".", "startswith", "(", "'/DEF:'", ")", ",", "ldflags", ")", "manifest_flags", ",", "intermediate_manifest", ",", "manifest_files", "=", "self", ".", "_GetLdManifestFlags", "(", "config", ",", "manifest_base_name", ",", "gyp_to_build_path", ",", "is_executable", "and", "not", "have_def_file", ",", "build_dir", ")", "ldflags", ".", "extend", "(", "manifest_flags", ")", "return", "ldflags", ",", "intermediate_manifest", ",", "manifest_files" ]
https://github.com/domino-team/openwrt-cc/blob/8b181297c34d14d3ca521cc9f31430d561dbc688/package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/msvs_emulation.py#L556-L657
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_misc.py
python
Log.FlushActive
(*args, **kwargs)
return _misc_.Log_FlushActive(*args, **kwargs)
FlushActive()
FlushActive()
[ "FlushActive", "()" ]
def FlushActive(*args, **kwargs): """FlushActive()""" return _misc_.Log_FlushActive(*args, **kwargs)
[ "def", "FlushActive", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_misc_", ".", "Log_FlushActive", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_misc.py#L1510-L1512
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_layers2.py
python
convert_activation
( builder, layer, input_names, output_names, keras_layer, respect_train )
Convert an activation layer from keras to coreml. Parameters ---------- keras_layer: layer A keras layer object. builder: NeuralNetworkBuilder A neural network builder object. respect_train: boolean, Ignored.
Convert an activation layer from keras to coreml.
[ "Convert", "an", "activation", "layer", "from", "keras", "to", "coreml", "." ]
def convert_activation( builder, layer, input_names, output_names, keras_layer, respect_train ): """ Convert an activation layer from keras to coreml. Parameters ---------- keras_layer: layer A keras layer object. builder: NeuralNetworkBuilder A neural network builder object. respect_train: boolean, Ignored. """ # Get input and output names input_name, output_name = (input_names[0], output_names[0]) non_linearity = _get_activation_name_from_keras_layer(keras_layer) # Add a non-linearity layer if non_linearity == "SOFTMAX": builder.add_softmax(name=layer, input_name=input_name, output_name=output_name) return if non_linearity == "RELU6": # No direct support of RELU with max-activation value - use negate and # clip layers relu_output_name = output_name + "_relu" builder.add_activation(layer, "RELU", input_name, relu_output_name) # negate it neg_output_name = relu_output_name + "_neg" builder.add_activation( layer + "__neg__", "LINEAR", relu_output_name, neg_output_name, [-1.0, 0] ) # apply threshold clip_output_name = relu_output_name + "_clip" builder.add_unary( layer + "__clip__", neg_output_name, clip_output_name, "threshold", alpha=-6.0, ) # negate it back builder.add_activation( layer + "_neg2", "LINEAR", clip_output_name, output_name, [-1.0, 0] ) return if non_linearity == "SELU": elu_output_name = output_name + "_elu" builder.add_activation( layer + "__elu__", "ELU", input_name, elu_output_name, params=1.6732 ) builder.add_elementwise( layer, input_names=elu_output_name, output_name=output_name, mode="MULTIPLY", alpha=1.0507, ) return params = None if non_linearity == "UNIT_ELU": params = 1.0 non_linearity = "ELU" elif non_linearity == "LEAKYRELU": params = [keras_layer.alpha] elif non_linearity == "PRELU": shared_axes = list(keras_layer.shared_axes) if not (shared_axes == [1, 2, 3] or shared_axes == [1, 2]): _utils.raise_error_unsupported_scenario( "Shared axis not being [1,2,3] or [1,2]", "parametric_relu", layer ) params = _keras.backend.eval(keras_layer.weights[0]) elif non_linearity == "ELU": params = keras_layer.alpha elif non_linearity == "THRESHOLDEDRELU": params = keras_layer.theta else: pass # do nothing to parameters builder.add_activation( name=layer, non_linearity=non_linearity, input_name=input_name, output_name=output_name, params=params, )
[ "def", "convert_activation", "(", "builder", ",", "layer", ",", "input_names", ",", "output_names", ",", "keras_layer", ",", "respect_train", ")", ":", "# Get input and output names", "input_name", ",", "output_name", "=", "(", "input_names", "[", "0", "]", ",", "output_names", "[", "0", "]", ")", "non_linearity", "=", "_get_activation_name_from_keras_layer", "(", "keras_layer", ")", "# Add a non-linearity layer", "if", "non_linearity", "==", "\"SOFTMAX\"", ":", "builder", ".", "add_softmax", "(", "name", "=", "layer", ",", "input_name", "=", "input_name", ",", "output_name", "=", "output_name", ")", "return", "if", "non_linearity", "==", "\"RELU6\"", ":", "# No direct support of RELU with max-activation value - use negate and", "# clip layers", "relu_output_name", "=", "output_name", "+", "\"_relu\"", "builder", ".", "add_activation", "(", "layer", ",", "\"RELU\"", ",", "input_name", ",", "relu_output_name", ")", "# negate it", "neg_output_name", "=", "relu_output_name", "+", "\"_neg\"", "builder", ".", "add_activation", "(", "layer", "+", "\"__neg__\"", ",", "\"LINEAR\"", ",", "relu_output_name", ",", "neg_output_name", ",", "[", "-", "1.0", ",", "0", "]", ")", "# apply threshold", "clip_output_name", "=", "relu_output_name", "+", "\"_clip\"", "builder", ".", "add_unary", "(", "layer", "+", "\"__clip__\"", ",", "neg_output_name", ",", "clip_output_name", ",", "\"threshold\"", ",", "alpha", "=", "-", "6.0", ",", ")", "# negate it back", "builder", ".", "add_activation", "(", "layer", "+", "\"_neg2\"", ",", "\"LINEAR\"", ",", "clip_output_name", ",", "output_name", ",", "[", "-", "1.0", ",", "0", "]", ")", "return", "if", "non_linearity", "==", "\"SELU\"", ":", "elu_output_name", "=", "output_name", "+", "\"_elu\"", "builder", ".", "add_activation", "(", "layer", "+", "\"__elu__\"", ",", "\"ELU\"", ",", "input_name", ",", "elu_output_name", ",", "params", "=", "1.6732", ")", "builder", ".", "add_elementwise", "(", "layer", ",", "input_names", "=", "elu_output_name", ",", "output_name", "=", "output_name", ",", "mode", "=", "\"MULTIPLY\"", ",", "alpha", "=", "1.0507", ",", ")", "return", "params", "=", "None", "if", "non_linearity", "==", "\"UNIT_ELU\"", ":", "params", "=", "1.0", "non_linearity", "=", "\"ELU\"", "elif", "non_linearity", "==", "\"LEAKYRELU\"", ":", "params", "=", "[", "keras_layer", ".", "alpha", "]", "elif", "non_linearity", "==", "\"PRELU\"", ":", "shared_axes", "=", "list", "(", "keras_layer", ".", "shared_axes", ")", "if", "not", "(", "shared_axes", "==", "[", "1", ",", "2", ",", "3", "]", "or", "shared_axes", "==", "[", "1", ",", "2", "]", ")", ":", "_utils", ".", "raise_error_unsupported_scenario", "(", "\"Shared axis not being [1,2,3] or [1,2]\"", ",", "\"parametric_relu\"", ",", "layer", ")", "params", "=", "_keras", ".", "backend", ".", "eval", "(", "keras_layer", ".", "weights", "[", "0", "]", ")", "elif", "non_linearity", "==", "\"ELU\"", ":", "params", "=", "keras_layer", ".", "alpha", "elif", "non_linearity", "==", "\"THRESHOLDEDRELU\"", ":", "params", "=", "keras_layer", ".", "theta", "else", ":", "pass", "# do nothing to parameters", "builder", ".", "add_activation", "(", "name", "=", "layer", ",", "non_linearity", "=", "non_linearity", ",", "input_name", "=", "input_name", ",", "output_name", "=", "output_name", ",", "params", "=", "params", ",", ")" ]
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_layers2.py#L245-L334
thalium/icebox
99d147d5b9269222225443ce171b4fd46d8985d4
third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py
python
xmlNode.setSpacePreserve
(self, val)
Set (or reset) the space preserving behaviour of a node, i.e. the value of the xml:space attribute.
Set (or reset) the space preserving behaviour of a node, i.e. the value of the xml:space attribute.
[ "Set", "(", "or", "reset", ")", "the", "space", "preserving", "behaviour", "of", "a", "node", "i", ".", "e", ".", "the", "value", "of", "the", "xml", ":", "space", "attribute", "." ]
def setSpacePreserve(self, val): """Set (or reset) the space preserving behaviour of a node, i.e. the value of the xml:space attribute. """ libxml2mod.xmlNodeSetSpacePreserve(self._o, val)
[ "def", "setSpacePreserve", "(", "self", ",", "val", ")", ":", "libxml2mod", ".", "xmlNodeSetSpacePreserve", "(", "self", ".", "_o", ",", "val", ")" ]
https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py#L2804-L2807
gemrb/gemrb
730206eed8d1dd358ca5e69a62f9e099aa22ffc6
gemrb/GUIScripts/bg1/CharGenCommon.py
python
CharGen.displayOverview
(self)
Sets up the primary character generation window. show all comments of previous stages
Sets up the primary character generation window. show all comments of previous stages
[ "Sets", "up", "the", "primary", "character", "generation", "window", ".", "show", "all", "comments", "of", "previous", "stages" ]
def displayOverview(self): """ Sets up the primary character generation window. show all comments of previous stages """ if(self.window): CharGenWindow = self.window else: CharGenWindow = GemRB.LoadWindow (0, "GUICG") step = self.step #set portrait PortraitButton = CharGenWindow.GetControl (12) PortraitButton.SetFlags(IE_GUI_BUTTON_PICTURE|IE_GUI_BUTTON_NO_IMAGE,OP_SET) PortraitName = GemRB.GetToken ("LargePortrait") PortraitButton.SetPicture (PortraitName, "NOPORTLG") PortraitButton.SetState(IE_GUI_BUTTON_LOCKED) #set stage buttons i = 0 for stage in self.stages: if(len(stage) == 3): #short stage (name,control,text) = stage button = CharGenWindow.GetControl(control) button.SetText(text); if i == step: button.SetState(IE_GUI_BUTTON_ENABLED) button.MakeDefault() button.SetEvent (IE_GUI_BUTTON_ON_PRESS, lambda: self.next()) else: button.SetState(IE_GUI_BUTTON_DISABLED) i = i + 1 #set back button BackButton = CharGenWindow.GetControl (11) #BackButton.SetText (15416) if(self.step != 0): BackButton.SetState (IE_GUI_BUTTON_ENABLED) else: BackButton.SetState(IE_GUI_BUTTON_DISABLED) BackButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, lambda: self.back()) BackButton.MakeEscape() AcceptButton = CharGenWindow.GetControl (8) playmode = GemRB.GetVar ("PlayMode") if playmode>=0: AcceptButton.SetText (11962) else: AcceptButton.SetText (13956) #set scrollbar ScrollBar = CharGenWindow.GetControl (10) CharGenWindow.SetEventProxy(ScrollBar) #set import ImportButton = CharGenWindow.GetControl (13) ImportButton.SetText (13955) ImportButton.SetState (IE_GUI_BUTTON_ENABLED) ImportButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, lambda: self.imprt()) #set cancel and start over CancelButton = CharGenWindow.GetControl (15) if step == 0 or not self.showReset: CancelButton.SetText (13727) # Cancel else: CancelButton.SetText (8159) # Start over CancelButton.SetState (IE_GUI_BUTTON_ENABLED) CancelButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, lambda: self.cancel()) #set and fill overview TextAreaControl = CharGenWindow.GetControl (9) if(self.step == 0): TextAreaControl.SetText(self.startText) else: TextAreaControl.SetText("") for part in range(step): if(len(self.stages[part]) == 5): (name,setFn,commentFn,unsetFn,guard) = self.stages[part] if(commentFn != None): commentFn(TextAreaControl) #show CharGenWindow.Focus() self.window = CharGenWindow
[ "def", "displayOverview", "(", "self", ")", ":", "if", "(", "self", ".", "window", ")", ":", "CharGenWindow", "=", "self", ".", "window", "else", ":", "CharGenWindow", "=", "GemRB", ".", "LoadWindow", "(", "0", ",", "\"GUICG\"", ")", "step", "=", "self", ".", "step", "#set portrait\t", "PortraitButton", "=", "CharGenWindow", ".", "GetControl", "(", "12", ")", "PortraitButton", ".", "SetFlags", "(", "IE_GUI_BUTTON_PICTURE", "|", "IE_GUI_BUTTON_NO_IMAGE", ",", "OP_SET", ")", "PortraitName", "=", "GemRB", ".", "GetToken", "(", "\"LargePortrait\"", ")", "PortraitButton", ".", "SetPicture", "(", "PortraitName", ",", "\"NOPORTLG\"", ")", "PortraitButton", ".", "SetState", "(", "IE_GUI_BUTTON_LOCKED", ")", "#set stage buttons", "i", "=", "0", "for", "stage", "in", "self", ".", "stages", ":", "if", "(", "len", "(", "stage", ")", "==", "3", ")", ":", "#short stage", "(", "name", ",", "control", ",", "text", ")", "=", "stage", "button", "=", "CharGenWindow", ".", "GetControl", "(", "control", ")", "button", ".", "SetText", "(", "text", ")", "if", "i", "==", "step", ":", "button", ".", "SetState", "(", "IE_GUI_BUTTON_ENABLED", ")", "button", ".", "MakeDefault", "(", ")", "button", ".", "SetEvent", "(", "IE_GUI_BUTTON_ON_PRESS", ",", "lambda", ":", "self", ".", "next", "(", ")", ")", "else", ":", "button", ".", "SetState", "(", "IE_GUI_BUTTON_DISABLED", ")", "i", "=", "i", "+", "1", "#set back button\t", "BackButton", "=", "CharGenWindow", ".", "GetControl", "(", "11", ")", "#BackButton.SetText (15416)", "if", "(", "self", ".", "step", "!=", "0", ")", ":", "BackButton", ".", "SetState", "(", "IE_GUI_BUTTON_ENABLED", ")", "else", ":", "BackButton", ".", "SetState", "(", "IE_GUI_BUTTON_DISABLED", ")", "BackButton", ".", "SetEvent", "(", "IE_GUI_BUTTON_ON_PRESS", ",", "lambda", ":", "self", ".", "back", "(", ")", ")", "BackButton", ".", "MakeEscape", "(", ")", "AcceptButton", "=", "CharGenWindow", ".", "GetControl", "(", "8", ")", "playmode", "=", "GemRB", ".", "GetVar", "(", "\"PlayMode\"", ")", "if", "playmode", ">=", "0", ":", "AcceptButton", ".", "SetText", "(", "11962", ")", "else", ":", "AcceptButton", ".", "SetText", "(", "13956", ")", "#set scrollbar", "ScrollBar", "=", "CharGenWindow", ".", "GetControl", "(", "10", ")", "CharGenWindow", ".", "SetEventProxy", "(", "ScrollBar", ")", "#set import", "ImportButton", "=", "CharGenWindow", ".", "GetControl", "(", "13", ")", "ImportButton", ".", "SetText", "(", "13955", ")", "ImportButton", ".", "SetState", "(", "IE_GUI_BUTTON_ENABLED", ")", "ImportButton", ".", "SetEvent", "(", "IE_GUI_BUTTON_ON_PRESS", ",", "lambda", ":", "self", ".", "imprt", "(", ")", ")", "#set cancel and start over", "CancelButton", "=", "CharGenWindow", ".", "GetControl", "(", "15", ")", "if", "step", "==", "0", "or", "not", "self", ".", "showReset", ":", "CancelButton", ".", "SetText", "(", "13727", ")", "# Cancel", "else", ":", "CancelButton", ".", "SetText", "(", "8159", ")", "# Start over", "CancelButton", ".", "SetState", "(", "IE_GUI_BUTTON_ENABLED", ")", "CancelButton", ".", "SetEvent", "(", "IE_GUI_BUTTON_ON_PRESS", ",", "lambda", ":", "self", ".", "cancel", "(", ")", ")", "#set and fill overview", "TextAreaControl", "=", "CharGenWindow", ".", "GetControl", "(", "9", ")", "if", "(", "self", ".", "step", "==", "0", ")", ":", "TextAreaControl", ".", "SetText", "(", "self", ".", "startText", ")", "else", ":", "TextAreaControl", ".", "SetText", "(", "\"\"", ")", "for", "part", "in", "range", "(", "step", ")", ":", "if", "(", "len", "(", "self", ".", "stages", "[", "part", "]", ")", "==", "5", ")", ":", "(", "name", ",", "setFn", ",", "commentFn", ",", "unsetFn", ",", "guard", ")", "=", "self", ".", "stages", "[", "part", "]", "if", "(", "commentFn", "!=", "None", ")", ":", "commentFn", "(", "TextAreaControl", ")", "#show", "CharGenWindow", ".", "Focus", "(", ")", "self", ".", "window", "=", "CharGenWindow" ]
https://github.com/gemrb/gemrb/blob/730206eed8d1dd358ca5e69a62f9e099aa22ffc6/gemrb/GUIScripts/bg1/CharGenCommon.py#L52-L136
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/webapp2/webapp2_extras/config.py
python
Config.__getitem__
(self, module)
Returns the configuration for a module. If it is not already set, loads a ``default_config`` variable from the given module and updates the configuration with those default values Every module that allows some kind of configuration sets a ``default_config`` global variable that is loaded by this function, cached and used in case the requested configuration was not defined by the user. :param module: The module name. :returns: A configuration value.
Returns the configuration for a module. If it is not already set, loads a ``default_config`` variable from the given module and updates the configuration with those default values
[ "Returns", "the", "configuration", "for", "a", "module", ".", "If", "it", "is", "not", "already", "set", "loads", "a", "default_config", "variable", "from", "the", "given", "module", "and", "updates", "the", "configuration", "with", "those", "default", "values" ]
def __getitem__(self, module): """Returns the configuration for a module. If it is not already set, loads a ``default_config`` variable from the given module and updates the configuration with those default values Every module that allows some kind of configuration sets a ``default_config`` global variable that is loaded by this function, cached and used in case the requested configuration was not defined by the user. :param module: The module name. :returns: A configuration value. """ if module not in self.loaded: # Load default configuration and update config. values = webapp2.import_string(module + '.default_config', silent=True) if values: self.setdefault(module, values) self.loaded.append(module) try: return dict.__getitem__(self, module) except KeyError: raise KeyError('Module %r is not configured.' % module)
[ "def", "__getitem__", "(", "self", ",", "module", ")", ":", "if", "module", "not", "in", "self", ".", "loaded", ":", "# Load default configuration and update config.", "values", "=", "webapp2", ".", "import_string", "(", "module", "+", "'.default_config'", ",", "silent", "=", "True", ")", "if", "values", ":", "self", ".", "setdefault", "(", "module", ",", "values", ")", "self", ".", "loaded", ".", "append", "(", "module", ")", "try", ":", "return", "dict", ".", "__getitem__", "(", "self", ",", "module", ")", "except", "KeyError", ":", "raise", "KeyError", "(", "'Module %r is not configured.'", "%", "module", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/webapp2/webapp2_extras/config.py#L86-L113
mapnik/mapnik
f3da900c355e1d15059c4a91b00203dcc9d9f0ef
scons/scons-local-4.1.0/SCons/Node/FS.py
python
Dir.walk
(self, func, arg)
Walk this directory tree by calling the specified function for each directory in the tree. This behaves like the os.path.walk() function, but for in-memory Node.FS.Dir objects. The function takes the same arguments as the functions passed to os.path.walk(): func(arg, dirname, fnames) Except that "dirname" will actually be the directory *Node*, not the string. The '.' and '..' entries are excluded from fnames. The fnames list may be modified in-place to filter the subdirectories visited or otherwise impose a specific order. The "arg" argument is always passed to func() and may be used in any way (or ignored, passing None is common).
Walk this directory tree by calling the specified function for each directory in the tree.
[ "Walk", "this", "directory", "tree", "by", "calling", "the", "specified", "function", "for", "each", "directory", "in", "the", "tree", "." ]
def walk(self, func, arg): """ Walk this directory tree by calling the specified function for each directory in the tree. This behaves like the os.path.walk() function, but for in-memory Node.FS.Dir objects. The function takes the same arguments as the functions passed to os.path.walk(): func(arg, dirname, fnames) Except that "dirname" will actually be the directory *Node*, not the string. The '.' and '..' entries are excluded from fnames. The fnames list may be modified in-place to filter the subdirectories visited or otherwise impose a specific order. The "arg" argument is always passed to func() and may be used in any way (or ignored, passing None is common). """ entries = self.entries names = list(entries.keys()) names.remove('.') names.remove('..') func(arg, self, names) for dirname in [n for n in names if isinstance(entries[n], Dir)]: entries[dirname].walk(func, arg)
[ "def", "walk", "(", "self", ",", "func", ",", "arg", ")", ":", "entries", "=", "self", ".", "entries", "names", "=", "list", "(", "entries", ".", "keys", "(", ")", ")", "names", ".", "remove", "(", "'.'", ")", "names", ".", "remove", "(", "'..'", ")", "func", "(", "arg", ",", "self", ",", "names", ")", "for", "dirname", "in", "[", "n", "for", "n", "in", "names", "if", "isinstance", "(", "entries", "[", "n", "]", ",", "Dir", ")", "]", ":", "entries", "[", "dirname", "]", ".", "walk", "(", "func", ",", "arg", ")" ]
https://github.com/mapnik/mapnik/blob/f3da900c355e1d15059c4a91b00203dcc9d9f0ef/scons/scons-local-4.1.0/SCons/Node/FS.py#L2104-L2128
ros-planning/moveit
ee48dc5cedc981d0869352aa3db0b41469c2735c
moveit_commander/src/moveit_commander/move_group.py
python
MoveGroupCommander.get_current_state_bounded
(self)
return s
Get the current state of the robot bounded.
Get the current state of the robot bounded.
[ "Get", "the", "current", "state", "of", "the", "robot", "bounded", "." ]
def get_current_state_bounded(self): """ Get the current state of the robot bounded.""" s = RobotState() c_str = self._g.get_current_state_bounded() conversions.msg_from_string(s, c_str) return s
[ "def", "get_current_state_bounded", "(", "self", ")", ":", "s", "=", "RobotState", "(", ")", "c_str", "=", "self", ".", "_g", ".", "get_current_state_bounded", "(", ")", "conversions", ".", "msg_from_string", "(", "s", ",", "c_str", ")", "return", "s" ]
https://github.com/ros-planning/moveit/blob/ee48dc5cedc981d0869352aa3db0b41469c2735c/moveit_commander/src/moveit_commander/move_group.py#L182-L187
KratosMultiphysics/Kratos
0000833054ed0503424eb28205d6508d9ca6cbbc
applications/ContactStructuralMechanicsApplication/python_scripts/search_base_process.py
python
SearchBaseProcess.ExecuteBeforeSolutionLoop
(self)
This method is executed before starting the time loop Keyword arguments: self -- It signifies an instance of a class.
This method is executed before starting the time loop
[ "This", "method", "is", "executed", "before", "starting", "the", "time", "loop" ]
def ExecuteBeforeSolutionLoop(self): """ This method is executed before starting the time loop Keyword arguments: self -- It signifies an instance of a class. """ pass
[ "def", "ExecuteBeforeSolutionLoop", "(", "self", ")", ":", "pass" ]
https://github.com/KratosMultiphysics/Kratos/blob/0000833054ed0503424eb28205d6508d9ca6cbbc/applications/ContactStructuralMechanicsApplication/python_scripts/search_base_process.py#L203-L209
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/numpy/py2/numpy/ma/core.py
python
common_fill_value
(a, b)
return None
Return the common filling value of two masked arrays, if any. If ``a.fill_value == b.fill_value``, return the fill value, otherwise return None. Parameters ---------- a, b : MaskedArray The masked arrays for which to compare fill values. Returns ------- fill_value : scalar or None The common fill value, or None. Examples -------- >>> x = np.ma.array([0, 1.], fill_value=3) >>> y = np.ma.array([0, 1.], fill_value=3) >>> np.ma.common_fill_value(x, y) 3.0
Return the common filling value of two masked arrays, if any.
[ "Return", "the", "common", "filling", "value", "of", "two", "masked", "arrays", "if", "any", "." ]
def common_fill_value(a, b): """ Return the common filling value of two masked arrays, if any. If ``a.fill_value == b.fill_value``, return the fill value, otherwise return None. Parameters ---------- a, b : MaskedArray The masked arrays for which to compare fill values. Returns ------- fill_value : scalar or None The common fill value, or None. Examples -------- >>> x = np.ma.array([0, 1.], fill_value=3) >>> y = np.ma.array([0, 1.], fill_value=3) >>> np.ma.common_fill_value(x, y) 3.0 """ t1 = get_fill_value(a) t2 = get_fill_value(b) if t1 == t2: return t1 return None
[ "def", "common_fill_value", "(", "a", ",", "b", ")", ":", "t1", "=", "get_fill_value", "(", "a", ")", "t2", "=", "get_fill_value", "(", "b", ")", "if", "t1", "==", "t2", ":", "return", "t1", "return", "None" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py2/numpy/ma/core.py#L562-L591
limbo018/DREAMPlace
146c3b9fd003d1acd52c96d9fd02e3f0a05154e4
dreamplace/PlaceDB.py
python
PlaceDB.height
(self)
return self.yh-self.yl
@return height of layout
[]
def height(self): """ @return height of layout """ return self.yh-self.yl
[ "def", "height", "(", "self", ")", ":", "return", "self", ".", "yh", "-", "self", ".", "yl" ]
https://github.com/limbo018/DREAMPlace/blob/146c3b9fd003d1acd52c96d9fd02e3f0a05154e4/dreamplace/PlaceDB.py#L233-L237
alexozer/jankdrone
c4b403eb254b41b832ab2bdfade12ba59c99e5dc
handheld/lib/nanopb/generator/nanopb_generator.py
python
main_plugin
()
Main function when invoked as a protoc plugin.
Main function when invoked as a protoc plugin.
[ "Main", "function", "when", "invoked", "as", "a", "protoc", "plugin", "." ]
def main_plugin(): '''Main function when invoked as a protoc plugin.''' import io, sys if sys.platform == "win32": import os, msvcrt # Set stdin and stdout to binary mode msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY) msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY) data = io.open(sys.stdin.fileno(), "rb").read() request = plugin_pb2.CodeGeneratorRequest.FromString(data) try: # Versions of Python prior to 2.7.3 do not support unicode # input to shlex.split(). Try to convert to str if possible. params = str(request.parameter) except UnicodeEncodeError: params = request.parameter import shlex args = shlex.split(params) options, dummy = optparser.parse_args(args) Globals.verbose_options = options.verbose response = plugin_pb2.CodeGeneratorResponse() # Google's protoc does not currently indicate the full path of proto files. # Instead always add the main file path to the search dirs, that works for # the common case. import os.path options.options_path.append(os.path.dirname(request.file_to_generate[0])) # Process any include files first, in order to have them # available as dependencies other_files = {} for fdesc in request.proto_file: other_files[fdesc.name] = parse_file(fdesc.name, fdesc, options) for filename in request.file_to_generate: for fdesc in request.proto_file: if fdesc.name == filename: results = process_file(filename, fdesc, options, other_files) f = response.file.add() f.name = results['headername'] f.content = results['headerdata'] f = response.file.add() f.name = results['sourcename'] f.content = results['sourcedata'] io.open(sys.stdout.fileno(), "wb").write(response.SerializeToString())
[ "def", "main_plugin", "(", ")", ":", "import", "io", ",", "sys", "if", "sys", ".", "platform", "==", "\"win32\"", ":", "import", "os", ",", "msvcrt", "# Set stdin and stdout to binary mode", "msvcrt", ".", "setmode", "(", "sys", ".", "stdin", ".", "fileno", "(", ")", ",", "os", ".", "O_BINARY", ")", "msvcrt", ".", "setmode", "(", "sys", ".", "stdout", ".", "fileno", "(", ")", ",", "os", ".", "O_BINARY", ")", "data", "=", "io", ".", "open", "(", "sys", ".", "stdin", ".", "fileno", "(", ")", ",", "\"rb\"", ")", ".", "read", "(", ")", "request", "=", "plugin_pb2", ".", "CodeGeneratorRequest", ".", "FromString", "(", "data", ")", "try", ":", "# Versions of Python prior to 2.7.3 do not support unicode", "# input to shlex.split(). Try to convert to str if possible.", "params", "=", "str", "(", "request", ".", "parameter", ")", "except", "UnicodeEncodeError", ":", "params", "=", "request", ".", "parameter", "import", "shlex", "args", "=", "shlex", ".", "split", "(", "params", ")", "options", ",", "dummy", "=", "optparser", ".", "parse_args", "(", "args", ")", "Globals", ".", "verbose_options", "=", "options", ".", "verbose", "response", "=", "plugin_pb2", ".", "CodeGeneratorResponse", "(", ")", "# Google's protoc does not currently indicate the full path of proto files.", "# Instead always add the main file path to the search dirs, that works for", "# the common case.", "import", "os", ".", "path", "options", ".", "options_path", ".", "append", "(", "os", ".", "path", ".", "dirname", "(", "request", ".", "file_to_generate", "[", "0", "]", ")", ")", "# Process any include files first, in order to have them", "# available as dependencies", "other_files", "=", "{", "}", "for", "fdesc", "in", "request", ".", "proto_file", ":", "other_files", "[", "fdesc", ".", "name", "]", "=", "parse_file", "(", "fdesc", ".", "name", ",", "fdesc", ",", "options", ")", "for", "filename", "in", "request", ".", "file_to_generate", ":", "for", "fdesc", "in", "request", ".", "proto_file", ":", "if", "fdesc", ".", "name", "==", "filename", ":", "results", "=", "process_file", "(", "filename", ",", "fdesc", ",", "options", ",", "other_files", ")", "f", "=", "response", ".", "file", ".", "add", "(", ")", "f", ".", "name", "=", "results", "[", "'headername'", "]", "f", ".", "content", "=", "results", "[", "'headerdata'", "]", "f", "=", "response", ".", "file", ".", "add", "(", ")", "f", ".", "name", "=", "results", "[", "'sourcename'", "]", "f", ".", "content", "=", "results", "[", "'sourcedata'", "]", "io", ".", "open", "(", "sys", ".", "stdout", ".", "fileno", "(", ")", ",", "\"wb\"", ")", ".", "write", "(", "response", ".", "SerializeToString", "(", ")", ")" ]
https://github.com/alexozer/jankdrone/blob/c4b403eb254b41b832ab2bdfade12ba59c99e5dc/handheld/lib/nanopb/generator/nanopb_generator.py#L1549-L1603
diwu/Tiny-Wings-Remake-on-Android
a9fd714432a350b69615bf8dbb40448231a54524
twxes10/libs/cocos2dx/platform/third_party/marmalade/freetype/src/tools/docmaker/utils.py
python
make_file_list
( args = None )
return file_list
builds a list of input files from command-line arguments
builds a list of input files from command-line arguments
[ "builds", "a", "list", "of", "input", "files", "from", "command", "-", "line", "arguments" ]
def make_file_list( args = None ): """builds a list of input files from command-line arguments""" file_list = [] # sys.stderr.write( repr( sys.argv[1 :] ) + '\n' ) if not args: args = sys.argv[1 :] for pathname in args: if string.find( pathname, '*' ) >= 0: newpath = glob.glob( pathname ) newpath.sort() # sort files -- this is important because # of the order of files else: newpath = [pathname] file_list.extend( newpath ) if len( file_list ) == 0: file_list = None else: # now filter the file list to remove non-existing ones file_list = filter( file_exists, file_list ) return file_list
[ "def", "make_file_list", "(", "args", "=", "None", ")", ":", "file_list", "=", "[", "]", "# sys.stderr.write( repr( sys.argv[1 :] ) + '\\n' )", "if", "not", "args", ":", "args", "=", "sys", ".", "argv", "[", "1", ":", "]", "for", "pathname", "in", "args", ":", "if", "string", ".", "find", "(", "pathname", ",", "'*'", ")", ">=", "0", ":", "newpath", "=", "glob", ".", "glob", "(", "pathname", ")", "newpath", ".", "sort", "(", ")", "# sort files -- this is important because", "# of the order of files", "else", ":", "newpath", "=", "[", "pathname", "]", "file_list", ".", "extend", "(", "newpath", ")", "if", "len", "(", "file_list", ")", "==", "0", ":", "file_list", "=", "None", "else", ":", "# now filter the file list to remove non-existing ones", "file_list", "=", "filter", "(", "file_exists", ",", "file_list", ")", "return", "file_list" ]
https://github.com/diwu/Tiny-Wings-Remake-on-Android/blob/a9fd714432a350b69615bf8dbb40448231a54524/twxes10/libs/cocos2dx/platform/third_party/marmalade/freetype/src/tools/docmaker/utils.py#L106-L130
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/ops/primitive.py
python
Primitive.recompute
(self, mode=True)
return self
Set the primitive recomputed. If a primitive set recomputed feeds into some backward nodes for computing gradient, rather than storing the intermediate activation computed in forward pass, we will recompute it in backward pass. Note: - If the computation involves something like randomization or global variable, the equivalence is not guaranteed currently. - Not supported in pynative mode Args: mode (bool): Specifies whether the primitive is recomputed. Default: True. Examples: >>> import numpy as np >>> import mindspore as ms >>> from mindspore import Tensor, ops, nn >>> class NetRecompute(nn.Cell): ... def __init__(self): ... super(NetRecompute,self).__init__() ... self.relu = ops.ReLU().recompute() ... self.sqrt = ops.Sqrt() ... def construct(self, x): ... out = self.relu(x) ... return self.sqrt(out) ... >>> class GradNet(nn.Cell): ... def __init__(self, network): ... super(GradNet,self).__init__() ... self.network = network ... self.grad = ops.GradOperation() ... def construct(self, x): ... g_out = self.grad(self.network)(x) ... return g_out ... >>> x = Tensor(np.array([-1,1]).astype(np.float32)) >>> net = NetRecompute() >>> grad = GradNet(net) >>> a = grad(x) >>> print(a) [0. 0.5]
Set the primitive recomputed. If a primitive set recomputed feeds into some backward nodes for computing gradient, rather than storing the intermediate activation computed in forward pass, we will recompute it in backward pass.
[ "Set", "the", "primitive", "recomputed", ".", "If", "a", "primitive", "set", "recomputed", "feeds", "into", "some", "backward", "nodes", "for", "computing", "gradient", "rather", "than", "storing", "the", "intermediate", "activation", "computed", "in", "forward", "pass", "we", "will", "recompute", "it", "in", "backward", "pass", "." ]
def recompute(self, mode=True): """ Set the primitive recomputed. If a primitive set recomputed feeds into some backward nodes for computing gradient, rather than storing the intermediate activation computed in forward pass, we will recompute it in backward pass. Note: - If the computation involves something like randomization or global variable, the equivalence is not guaranteed currently. - Not supported in pynative mode Args: mode (bool): Specifies whether the primitive is recomputed. Default: True. Examples: >>> import numpy as np >>> import mindspore as ms >>> from mindspore import Tensor, ops, nn >>> class NetRecompute(nn.Cell): ... def __init__(self): ... super(NetRecompute,self).__init__() ... self.relu = ops.ReLU().recompute() ... self.sqrt = ops.Sqrt() ... def construct(self, x): ... out = self.relu(x) ... return self.sqrt(out) ... >>> class GradNet(nn.Cell): ... def __init__(self, network): ... super(GradNet,self).__init__() ... self.network = network ... self.grad = ops.GradOperation() ... def construct(self, x): ... g_out = self.grad(self.network)(x) ... return g_out ... >>> x = Tensor(np.array([-1,1]).astype(np.float32)) >>> net = NetRecompute() >>> grad = GradNet(net) >>> a = grad(x) >>> print(a) [0. 0.5] """ if context.get_context("mode") == context.PYNATIVE_MODE: raise TypeError("Recompute is not supported in pynative mode currently.") Validator.check_bool(mode) self.add_prim_attr("recompute", mode) return self
[ "def", "recompute", "(", "self", ",", "mode", "=", "True", ")", ":", "if", "context", ".", "get_context", "(", "\"mode\"", ")", "==", "context", ".", "PYNATIVE_MODE", ":", "raise", "TypeError", "(", "\"Recompute is not supported in pynative mode currently.\"", ")", "Validator", ".", "check_bool", "(", "mode", ")", "self", ".", "add_prim_attr", "(", "\"recompute\"", ",", "mode", ")", "return", "self" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/primitive.py#L324-L371
chromiumembedded/cef
80caf947f3fe2210e5344713c5281d8af9bdc295
tools/yapf/yapf/yapflib/format_token.py
python
FormatToken.node_split_penalty
(self)
return pytree_utils.GetNodeAnnotation( self.node, pytree_utils.Annotation.SPLIT_PENALTY, default=0)
Split penalty attached to the pytree node of this token.
Split penalty attached to the pytree node of this token.
[ "Split", "penalty", "attached", "to", "the", "pytree", "node", "of", "this", "token", "." ]
def node_split_penalty(self): """Split penalty attached to the pytree node of this token.""" return pytree_utils.GetNodeAnnotation( self.node, pytree_utils.Annotation.SPLIT_PENALTY, default=0)
[ "def", "node_split_penalty", "(", "self", ")", ":", "return", "pytree_utils", ".", "GetNodeAnnotation", "(", "self", ".", "node", ",", "pytree_utils", ".", "Annotation", ".", "SPLIT_PENALTY", ",", "default", "=", "0", ")" ]
https://github.com/chromiumembedded/cef/blob/80caf947f3fe2210e5344713c5281d8af9bdc295/tools/yapf/yapf/yapflib/format_token.py#L190-L193
google/syzygy
8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5
third_party/numpy/files/numpy/oldnumeric/ma.py
python
domain_check_interval.__init__
(self, y1, y2)
domain_check_interval(a,b)(x) = true where x < a or y > b
domain_check_interval(a,b)(x) = true where x < a or y > b
[ "domain_check_interval", "(", "a", "b", ")", "(", "x", ")", "=", "true", "where", "x", "<", "a", "or", "y", ">", "b" ]
def __init__(self, y1, y2): "domain_check_interval(a,b)(x) = true where x < a or y > b" self.y1 = y1 self.y2 = y2
[ "def", "__init__", "(", "self", ",", "y1", ",", "y2", ")", ":", "self", ".", "y1", "=", "y1", "self", ".", "y2", "=", "y2" ]
https://github.com/google/syzygy/blob/8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5/third_party/numpy/files/numpy/oldnumeric/ma.py#L258-L261
google/llvm-propeller
45c226984fe8377ebfb2ad7713c680d652ba678d
lldb/examples/python/file_extract.py
python
FileExtract.get_n_uint64
(self, n, fail_value=0)
Extract "n" uint64_t integers from the binary file at the current file position, returns a list of integers
Extract "n" uint64_t integers from the binary file at the current file position, returns a list of integers
[ "Extract", "n", "uint64_t", "integers", "from", "the", "binary", "file", "at", "the", "current", "file", "position", "returns", "a", "list", "of", "integers" ]
def get_n_uint64(self, n, fail_value=0): '''Extract "n" uint64_t integers from the binary file at the current file position, returns a list of integers''' s = self.read_size(8 * n) if s: return struct.unpack(self.byte_order + ("%u" % n) + 'Q', s) else: return (fail_value,) * n
[ "def", "get_n_uint64", "(", "self", ",", "n", ",", "fail_value", "=", "0", ")", ":", "s", "=", "self", ".", "read_size", "(", "8", "*", "n", ")", "if", "s", ":", "return", "struct", ".", "unpack", "(", "self", ".", "byte_order", "+", "(", "\"%u\"", "%", "n", ")", "+", "'Q'", ",", "s", ")", "else", ":", "return", "(", "fail_value", ",", ")", "*", "n" ]
https://github.com/google/llvm-propeller/blob/45c226984fe8377ebfb2ad7713c680d652ba678d/lldb/examples/python/file_extract.py#L220-L226
facebookincubator/BOLT
88c70afe9d388ad430cc150cc158641701397f70
llvm/utils/rsp_bisect.py
python
modify_rsp
(rsp_entries, other_rel_path, modify_after_num)
return ret
Create a modified rsp file for use in bisection. Returns a new list from rsp. For each file in rsp after the first modify_after_num files, prepend other_rel_path.
Create a modified rsp file for use in bisection.
[ "Create", "a", "modified", "rsp", "file", "for", "use", "in", "bisection", "." ]
def modify_rsp(rsp_entries, other_rel_path, modify_after_num): """Create a modified rsp file for use in bisection. Returns a new list from rsp. For each file in rsp after the first modify_after_num files, prepend other_rel_path. """ ret = [] for r in rsp_entries: if is_path(r): if modify_after_num == 0: r = os.path.join(other_rel_path, r) else: modify_after_num -= 1 ret.append(r) assert modify_after_num == 0 return ret
[ "def", "modify_rsp", "(", "rsp_entries", ",", "other_rel_path", ",", "modify_after_num", ")", ":", "ret", "=", "[", "]", "for", "r", "in", "rsp_entries", ":", "if", "is_path", "(", "r", ")", ":", "if", "modify_after_num", "==", "0", ":", "r", "=", "os", ".", "path", ".", "join", "(", "other_rel_path", ",", "r", ")", "else", ":", "modify_after_num", "-=", "1", "ret", ".", "append", "(", "r", ")", "assert", "modify_after_num", "==", "0", "return", "ret" ]
https://github.com/facebookincubator/BOLT/blob/88c70afe9d388ad430cc150cc158641701397f70/llvm/utils/rsp_bisect.py#L89-L105
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py3/sklearn/ensemble/_gb_losses.py
python
LossFunction.negative_gradient
(self, y, raw_predictions, **kargs)
Compute the negative gradient. Parameters ---------- y : 1d array, shape (n_samples,) The target labels. raw_predictions : 2d array, shape (n_samples, K) The raw predictions (i.e. values from the tree leaves) of the tree ensemble at iteration ``i - 1``.
Compute the negative gradient.
[ "Compute", "the", "negative", "gradient", "." ]
def negative_gradient(self, y, raw_predictions, **kargs): """Compute the negative gradient. Parameters ---------- y : 1d array, shape (n_samples,) The target labels. raw_predictions : 2d array, shape (n_samples, K) The raw predictions (i.e. values from the tree leaves) of the tree ensemble at iteration ``i - 1``. """
[ "def", "negative_gradient", "(", "self", ",", "y", ",", "raw_predictions", ",", "*", "*", "kargs", ")", ":" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/ensemble/_gb_losses.py#L60-L71
fabianschenk/RESLAM
2e71a578b6d1a1ad1fb018641218e1f41dd9e330
thirdparty/Sophus/py/sophus/se3.py
python
Se3.exp
(v)
return Se3(so3, V * upsilon)
exponential map
exponential map
[ "exponential", "map" ]
def exp(v): """ exponential map """ upsilon = v[0:3, :] omega = sophus.Vector3(v[3], v[4], v[5]) so3 = sophus.So3.exp(omega) Omega = sophus.So3.hat(omega) Omega_sq = Omega * Omega theta = sympy.sqrt(sophus.squared_norm(omega)) V = (sympy.Matrix.eye(3) + (1 - sympy.cos(theta)) / (theta**2) * Omega + (theta - sympy.sin(theta)) / (theta**3) * Omega_sq) return Se3(so3, V * upsilon)
[ "def", "exp", "(", "v", ")", ":", "upsilon", "=", "v", "[", "0", ":", "3", ",", ":", "]", "omega", "=", "sophus", ".", "Vector3", "(", "v", "[", "3", "]", ",", "v", "[", "4", "]", ",", "v", "[", "5", "]", ")", "so3", "=", "sophus", ".", "So3", ".", "exp", "(", "omega", ")", "Omega", "=", "sophus", ".", "So3", ".", "hat", "(", "omega", ")", "Omega_sq", "=", "Omega", "*", "Omega", "theta", "=", "sympy", ".", "sqrt", "(", "sophus", ".", "squared_norm", "(", "omega", ")", ")", "V", "=", "(", "sympy", ".", "Matrix", ".", "eye", "(", "3", ")", "+", "(", "1", "-", "sympy", ".", "cos", "(", "theta", ")", ")", "/", "(", "theta", "**", "2", ")", "*", "Omega", "+", "(", "theta", "-", "sympy", ".", "sin", "(", "theta", ")", ")", "/", "(", "theta", "**", "3", ")", "*", "Omega_sq", ")", "return", "Se3", "(", "so3", ",", "V", "*", "upsilon", ")" ]
https://github.com/fabianschenk/RESLAM/blob/2e71a578b6d1a1ad1fb018641218e1f41dd9e330/thirdparty/Sophus/py/sophus/se3.py#L22-L33
thalium/icebox
99d147d5b9269222225443ce171b4fd46d8985d4
third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py
python
uCSIsCatSc
(code)
return ret
Check whether the character is part of Sc UCS Category
Check whether the character is part of Sc UCS Category
[ "Check", "whether", "the", "character", "is", "part", "of", "Sc", "UCS", "Category" ]
def uCSIsCatSc(code): """Check whether the character is part of Sc UCS Category """ ret = libxml2mod.xmlUCSIsCatSc(code) return ret
[ "def", "uCSIsCatSc", "(", "code", ")", ":", "ret", "=", "libxml2mod", ".", "xmlUCSIsCatSc", "(", "code", ")", "return", "ret" ]
https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py#L2386-L2389
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/calendar.py
python
weekday
(year, month, day)
return datetime.date(year, month, day).weekday()
Return weekday (0-6 ~ Mon-Sun) for year, month (1-12), day (1-31).
Return weekday (0-6 ~ Mon-Sun) for year, month (1-12), day (1-31).
[ "Return", "weekday", "(", "0", "-", "6", "~", "Mon", "-", "Sun", ")", "for", "year", "month", "(", "1", "-", "12", ")", "day", "(", "1", "-", "31", ")", "." ]
def weekday(year, month, day): """Return weekday (0-6 ~ Mon-Sun) for year, month (1-12), day (1-31).""" if not datetime.MINYEAR <= year <= datetime.MAXYEAR: year = 2000 + year % 400 return datetime.date(year, month, day).weekday()
[ "def", "weekday", "(", "year", ",", "month", ",", "day", ")", ":", "if", "not", "datetime", ".", "MINYEAR", "<=", "year", "<=", "datetime", ".", "MAXYEAR", ":", "year", "=", "2000", "+", "year", "%", "400", "return", "datetime", ".", "date", "(", "year", ",", "month", ",", "day", ")", ".", "weekday", "(", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/calendar.py#L113-L117
google/earthenterprise
0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9
earth_enterprise/src/fusion/portableglobe/servers/portable_globe.py
python
Globe.ServeLocalTiles
(self, globe_path)
Sets which tile db file is being served.
Sets which tile db file is being served.
[ "Sets", "which", "tile", "db", "file", "is", "being", "served", "." ]
def ServeLocalTiles(self, globe_path): """Sets which tile db file is being served.""" self.SetGlobePath(globe_path) self.db_ = None try: print "sqlite connection to ", globe_path self.db_ = sqlite3.connect(globe_path) except Exception: print "Failed to connect to %s." % globe_path
[ "def", "ServeLocalTiles", "(", "self", ",", "globe_path", ")", ":", "self", ".", "SetGlobePath", "(", "globe_path", ")", "self", ".", "db_", "=", "None", "try", ":", "print", "\"sqlite connection to \"", ",", "globe_path", "self", ".", "db_", "=", "sqlite3", ".", "connect", "(", "globe_path", ")", "except", "Exception", ":", "print", "\"Failed to connect to %s.\"", "%", "globe_path" ]
https://github.com/google/earthenterprise/blob/0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9/earth_enterprise/src/fusion/portableglobe/servers/portable_globe.py#L388-L396
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
deps/src/libxml2-2.9.1/python/libxml2class.py
python
uCSIsSupplementaryPrivateUseAreaB
(code)
return ret
Check whether the character is part of SupplementaryPrivateUseArea-B UCS Block
Check whether the character is part of SupplementaryPrivateUseArea-B UCS Block
[ "Check", "whether", "the", "character", "is", "part", "of", "SupplementaryPrivateUseArea", "-", "B", "UCS", "Block" ]
def uCSIsSupplementaryPrivateUseAreaB(code): """Check whether the character is part of SupplementaryPrivateUseArea-B UCS Block """ ret = libxml2mod.xmlUCSIsSupplementaryPrivateUseAreaB(code) return ret
[ "def", "uCSIsSupplementaryPrivateUseAreaB", "(", "code", ")", ":", "ret", "=", "libxml2mod", ".", "xmlUCSIsSupplementaryPrivateUseAreaB", "(", "code", ")", "return", "ret" ]
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/deps/src/libxml2-2.9.1/python/libxml2class.py#L2108-L2112
naver/sling
5671cd445a2caae0b4dd0332299e4cfede05062c
webkit/Source/JavaScriptCore/disassembler/udis86/ud_opcode.py
python
UdInsnDef.lookupPrefix
(self, pfx)
return True if pfx in self.prefixes else None
Lookup prefix (if any, None otherwise), by name
Lookup prefix (if any, None otherwise), by name
[ "Lookup", "prefix", "(", "if", "any", "None", "otherwise", ")", "by", "name" ]
def lookupPrefix(self, pfx): """Lookup prefix (if any, None otherwise), by name""" return True if pfx in self.prefixes else None
[ "def", "lookupPrefix", "(", "self", ",", "pfx", ")", ":", "return", "True", "if", "pfx", "in", "self", ".", "prefixes", "else", "None" ]
https://github.com/naver/sling/blob/5671cd445a2caae0b4dd0332299e4cfede05062c/webkit/Source/JavaScriptCore/disassembler/udis86/ud_opcode.py#L51-L53
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/aui.py
python
AuiPaneInfo.HasMaximizeButton
(*args, **kwargs)
return _aui.AuiPaneInfo_HasMaximizeButton(*args, **kwargs)
HasMaximizeButton(self) -> bool
HasMaximizeButton(self) -> bool
[ "HasMaximizeButton", "(", "self", ")", "-", ">", "bool" ]
def HasMaximizeButton(*args, **kwargs): """HasMaximizeButton(self) -> bool""" return _aui.AuiPaneInfo_HasMaximizeButton(*args, **kwargs)
[ "def", "HasMaximizeButton", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_aui", ".", "AuiPaneInfo_HasMaximizeButton", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/aui.py#L317-L319
google/google-api-cpp-client
3df15df632bef43eb320645ac3329d872aabf5ad
prepare_dependencies.py
python
MongoosePackageInstaller.MaybeTweakAfterUnpackage
(self)
Creates a CMakeLists.txt file for building the package.
Creates a CMakeLists.txt file for building the package.
[ "Creates", "a", "CMakeLists", ".", "txt", "file", "for", "building", "the", "package", "." ]
def MaybeTweakAfterUnpackage(self): """Creates a CMakeLists.txt file for building the package.""" config = self._config cmakelists_path = os.path.join(self._package_path, 'CMakeLists.txt') if config.force and os.path.exists(cmakelists_path): os.unlink(cmakelists_path) if os.path.exists(cmakelists_path): return # Mongoose just builds a server, and does so nonstandard. # We want a library. There's only one file so pretty simple. print '>>> Creating CMakeLists.txt as %s' % cmakelists_path with open(cmakelists_path, 'w') as f: f.write('cmake_minimum_required (VERSION 2.6)\n') f.write('project (Mongoose)\n') f.write('add_library(mongoose STATIC mongoose.c)\n') f.write('add_definitions( -DNO_CGI -U__STDC_FORMAT_MACROS )\n')
[ "def", "MaybeTweakAfterUnpackage", "(", "self", ")", ":", "config", "=", "self", ".", "_config", "cmakelists_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "_package_path", ",", "'CMakeLists.txt'", ")", "if", "config", ".", "force", "and", "os", ".", "path", ".", "exists", "(", "cmakelists_path", ")", ":", "os", ".", "unlink", "(", "cmakelists_path", ")", "if", "os", ".", "path", ".", "exists", "(", "cmakelists_path", ")", ":", "return", "# Mongoose just builds a server, and does so nonstandard.", "# We want a library. There's only one file so pretty simple.", "print", "'>>> Creating CMakeLists.txt as %s'", "%", "cmakelists_path", "with", "open", "(", "cmakelists_path", ",", "'w'", ")", "as", "f", ":", "f", ".", "write", "(", "'cmake_minimum_required (VERSION 2.6)\\n'", ")", "f", ".", "write", "(", "'project (Mongoose)\\n'", ")", "f", ".", "write", "(", "'add_library(mongoose STATIC mongoose.c)\\n'", ")", "f", ".", "write", "(", "'add_definitions( -DNO_CGI -U__STDC_FORMAT_MACROS )\\n'", ")" ]
https://github.com/google/google-api-cpp-client/blob/3df15df632bef43eb320645ac3329d872aabf5ad/prepare_dependencies.py#L677-L693
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/logging/__init__.py
python
Logger.handle
(self, record)
Call the handlers for the specified record. This method is used for unpickled records received from a socket, as well as those created locally. Logger-level filtering is applied.
Call the handlers for the specified record.
[ "Call", "the", "handlers", "for", "the", "specified", "record", "." ]
def handle(self, record): """ Call the handlers for the specified record. This method is used for unpickled records received from a socket, as well as those created locally. Logger-level filtering is applied. """ if (not self.disabled) and self.filter(record): self.callHandlers(record)
[ "def", "handle", "(", "self", ",", "record", ")", ":", "if", "(", "not", "self", ".", "disabled", ")", "and", "self", ".", "filter", "(", "record", ")", ":", "self", ".", "callHandlers", "(", "record", ")" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/logging/__init__.py#L1270-L1278
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_core.py
python
TextEntryBase.CanRedo
(*args, **kwargs)
return _core_.TextEntryBase_CanRedo(*args, **kwargs)
CanRedo(self) -> bool Returns True if the text field is editable and the last undo can be redone.
CanRedo(self) -> bool
[ "CanRedo", "(", "self", ")", "-", ">", "bool" ]
def CanRedo(*args, **kwargs): """ CanRedo(self) -> bool Returns True if the text field is editable and the last undo can be redone. """ return _core_.TextEntryBase_CanRedo(*args, **kwargs)
[ "def", "CanRedo", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "TextEntryBase_CanRedo", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L13232-L13239
ptrkrysik/gr-gsm
2de47e28ce1fb9a518337bfc0add36c8e3cff5eb
python/qa_tch_h_decoder.py
python
qa_tch_h_decoder.test_amr7_40_and_4_75
(self)
TCH/H MultiRate AMR 7.40 and 4.75 Two 7.40 followed by two 4.75 frames
TCH/H MultiRate AMR 7.40 and 4.75 Two 7.40 followed by two 4.75 frames
[ "TCH", "/", "H", "MultiRate", "AMR", "7", ".", "40", "and", "4", ".", "75", "Two", "7", ".", "40", "followed", "by", "two", "4", ".", "75", "frames" ]
def test_amr7_40_and_4_75 (self): """ TCH/H MultiRate AMR 7.40 and 4.75 Two 7.40 followed by two 4.75 frames """ b = self.b self.assertListEqual(self.tchh_multirate( multirate= "28111a40", subchan = 0, frames = [259657, 259659, 259662, 259664, 259662, 259664, 259666, 259668, 259666, 259668, 259670, 259672, 259670, 259672, 259675, 259677, 259675, 259677, 259679, 259681], timeslots= [ 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6], bursts = [ b[0], b[1], b[2], b[3], b[0], b[1], b[2], b[3], b[2], b[3], b[4], b[5], b[2], b[3], b[4], b[5], b[4], b[5], b[6], b[7]]), [ [0x23,0x21,0x41,0x4d,0x52,0x0a], [0x20,0xe0,0x27,0x2a,0x00,0x21,0x30,0x38,0x75,0xf8,0x14,0x3c,0xec,0xde,0x0b,0x47,0x6f,0x9c,0xc6,0x70], [0x20,0xe0,0x27,0x2a,0x00,0x21,0x30,0x38,0x75,0xf8,0x14,0x3c,0xec,0xde,0x0b,0x47,0x6f,0x9c,0xc6,0x70], [0x00,0x67,0x19,0x24,0xd5,0x1b,0xd1,0x29,0x3f,0xa1,0x50,0x5f,0x3e], [0x00,0x67,0x19,0x24,0xd5,0x1b,0xd1,0x29,0x3f,0xa1,0x50,0x5f,0x3e], ])
[ "def", "test_amr7_40_and_4_75", "(", "self", ")", ":", "b", "=", "self", ".", "b", "self", ".", "assertListEqual", "(", "self", ".", "tchh_multirate", "(", "multirate", "=", "\"28111a40\"", ",", "subchan", "=", "0", ",", "frames", "=", "[", "259657", ",", "259659", ",", "259662", ",", "259664", ",", "259662", ",", "259664", ",", "259666", ",", "259668", ",", "259666", ",", "259668", ",", "259670", ",", "259672", ",", "259670", ",", "259672", ",", "259675", ",", "259677", ",", "259675", ",", "259677", ",", "259679", ",", "259681", "]", ",", "timeslots", "=", "[", "6", ",", "6", ",", "6", ",", "6", ",", "6", ",", "6", ",", "6", ",", "6", ",", "6", ",", "6", ",", "6", ",", "6", ",", "6", ",", "6", ",", "6", ",", "6", ",", "6", ",", "6", ",", "6", ",", "6", "]", ",", "bursts", "=", "[", "b", "[", "0", "]", ",", "b", "[", "1", "]", ",", "b", "[", "2", "]", ",", "b", "[", "3", "]", ",", "b", "[", "0", "]", ",", "b", "[", "1", "]", ",", "b", "[", "2", "]", ",", "b", "[", "3", "]", ",", "b", "[", "2", "]", ",", "b", "[", "3", "]", ",", "b", "[", "4", "]", ",", "b", "[", "5", "]", ",", "b", "[", "2", "]", ",", "b", "[", "3", "]", ",", "b", "[", "4", "]", ",", "b", "[", "5", "]", ",", "b", "[", "4", "]", ",", "b", "[", "5", "]", ",", "b", "[", "6", "]", ",", "b", "[", "7", "]", "]", ")", ",", "[", "[", "0x23", ",", "0x21", ",", "0x41", ",", "0x4d", ",", "0x52", ",", "0x0a", "]", ",", "[", "0x20", ",", "0xe0", ",", "0x27", ",", "0x2a", ",", "0x00", ",", "0x21", ",", "0x30", ",", "0x38", ",", "0x75", ",", "0xf8", ",", "0x14", ",", "0x3c", ",", "0xec", ",", "0xde", ",", "0x0b", ",", "0x47", ",", "0x6f", ",", "0x9c", ",", "0xc6", ",", "0x70", "]", ",", "[", "0x20", ",", "0xe0", ",", "0x27", ",", "0x2a", ",", "0x00", ",", "0x21", ",", "0x30", ",", "0x38", ",", "0x75", ",", "0xf8", ",", "0x14", ",", "0x3c", ",", "0xec", ",", "0xde", ",", "0x0b", ",", "0x47", ",", "0x6f", ",", "0x9c", ",", "0xc6", ",", "0x70", "]", ",", "[", "0x00", ",", "0x67", ",", "0x19", ",", "0x24", ",", "0xd5", ",", "0x1b", ",", "0xd1", ",", "0x29", ",", "0x3f", ",", "0xa1", ",", "0x50", ",", "0x5f", ",", "0x3e", "]", ",", "[", "0x00", ",", "0x67", ",", "0x19", ",", "0x24", ",", "0xd5", ",", "0x1b", ",", "0xd1", ",", "0x29", ",", "0x3f", ",", "0xa1", ",", "0x50", ",", "0x5f", ",", "0x3e", "]", ",", "]", ")" ]
https://github.com/ptrkrysik/gr-gsm/blob/2de47e28ce1fb9a518337bfc0add36c8e3cff5eb/python/qa_tch_h_decoder.py#L117-L147
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/scipy/optimize/_differentialevolution.py
python
DifferentialEvolutionSolver._unscale_parameters
(self, parameters)
return (parameters - self.__scale_arg1) / self.__scale_arg2 + 0.5
scale from parameters to a number between 0 and 1.
scale from parameters to a number between 0 and 1.
[ "scale", "from", "parameters", "to", "a", "number", "between", "0", "and", "1", "." ]
def _unscale_parameters(self, parameters): """ scale from parameters to a number between 0 and 1. """ return (parameters - self.__scale_arg1) / self.__scale_arg2 + 0.5
[ "def", "_unscale_parameters", "(", "self", ",", "parameters", ")", ":", "return", "(", "parameters", "-", "self", ".", "__scale_arg1", ")", "/", "self", ".", "__scale_arg2", "+", "0.5" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/optimize/_differentialevolution.py#L676-L680
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/distlib/database.py
python
InstalledDistribution._get_records
(self)
return results
Get the list of installed files for the distribution :return: A list of tuples of path, hash and size. Note that hash and size might be ``None`` for some entries. The path is exactly as stored in the file (which is as in PEP 376).
[]
def _get_records(self): """ Get the list of installed files for the distribution :return: A list of tuples of path, hash and size. Note that hash and size might be ``None`` for some entries. The path is exactly as stored in the file (which is as in PEP 376). """ results = [] r = self.get_distinfo_resource('RECORD') with contextlib.closing(r.as_stream()) as stream: with CSVReader(stream=stream) as record_reader: # Base location is parent dir of .dist-info dir #base_location = os.path.dirname(self.path) #base_location = os.path.abspath(base_location) for row in record_reader: missing = [None for i in range(len(row), 3)] path, checksum, size = row + missing #if not os.path.isabs(path): # path = path.replace('/', os.sep) # path = os.path.join(base_location, path) results.append((path, checksum, size)) return results
[ "def", "_get_records", "(", "self", ")", ":", "results", "=", "[", "]", "r", "=", "self", ".", "get_distinfo_resource", "(", "'RECORD'", ")", "with", "contextlib", ".", "closing", "(", "r", ".", "as_stream", "(", ")", ")", "as", "stream", ":", "with", "CSVReader", "(", "stream", "=", "stream", ")", "as", "record_reader", ":", "# Base location is parent dir of .dist-info dir", "#base_location = os.path.dirname(self.path)", "#base_location = os.path.abspath(base_location)", "for", "row", "in", "record_reader", ":", "missing", "=", "[", "None", "for", "i", "in", "range", "(", "len", "(", "row", ")", ",", "3", ")", "]", "path", ",", "checksum", ",", "size", "=", "row", "+", "missing", "#if not os.path.isabs(path):", "# path = path.replace('/', os.sep)", "# path = os.path.join(base_location, path)", "results", ".", "append", "(", "(", "path", ",", "checksum", ",", "size", ")", ")", "return", "results" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/distlib/database.py#L1159-L1201
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
caffe2/python/dataset.py
python
_DatasetWriter.write
(self, writer_net, fields)
Add operations to `net` that append the blobs in `fields` to the end of the dataset. An additional operator will also be added that checks the consistency of the data in `fields` against the dataset schema. Args: writer_net: The net that will contain the Append operators. fields: A list of BlobReference to be appeneded to this dataset.
Add operations to `net` that append the blobs in `fields` to the end of the dataset. An additional operator will also be added that checks the consistency of the data in `fields` against the dataset schema.
[ "Add", "operations", "to", "net", "that", "append", "the", "blobs", "in", "fields", "to", "the", "end", "of", "the", "dataset", ".", "An", "additional", "operator", "will", "also", "be", "added", "that", "checks", "the", "consistency", "of", "the", "data", "in", "fields", "against", "the", "dataset", "schema", "." ]
def write(self, writer_net, fields): """ Add operations to `net` that append the blobs in `fields` to the end of the dataset. An additional operator will also be added that checks the consistency of the data in `fields` against the dataset schema. Args: writer_net: The net that will contain the Append operators. fields: A list of BlobReference to be appeneded to this dataset. """ assert self.mutex is not None, 'setup not called.' field_blobs = self._content.field_blobs() assert len(fields) == len(field_blobs), ( 'Expected %s fields, got %s.' % (len(field_blobs), len(fields))) writer_net.CheckDatasetConsistency( fields, [], fields=self._content.field_names()) writer_net.AtomicAppend( [self.mutex] + field_blobs + list(fields), field_blobs)
[ "def", "write", "(", "self", ",", "writer_net", ",", "fields", ")", ":", "assert", "self", ".", "mutex", "is", "not", "None", ",", "'setup not called.'", "field_blobs", "=", "self", ".", "_content", ".", "field_blobs", "(", ")", "assert", "len", "(", "fields", ")", "==", "len", "(", "field_blobs", ")", ",", "(", "'Expected %s fields, got %s.'", "%", "(", "len", "(", "field_blobs", ")", ",", "len", "(", "fields", ")", ")", ")", "writer_net", ".", "CheckDatasetConsistency", "(", "fields", ",", "[", "]", ",", "fields", "=", "self", ".", "_content", ".", "field_names", "(", ")", ")", "writer_net", ".", "AtomicAppend", "(", "[", "self", ".", "mutex", "]", "+", "field_blobs", "+", "list", "(", "fields", ")", ",", "field_blobs", ")" ]
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/caffe2/python/dataset.py#L134-L152
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/OpenSSL/crypto.py
python
X509Req.to_cryptography
(self)
return _CertificateSigningRequest(backend, self._req)
Export as a ``cryptography`` certificate signing request. :rtype: ``cryptography.x509.CertificateSigningRequest`` .. versionadded:: 17.1.0
Export as a ``cryptography`` certificate signing request.
[ "Export", "as", "a", "cryptography", "certificate", "signing", "request", "." ]
def to_cryptography(self): """ Export as a ``cryptography`` certificate signing request. :rtype: ``cryptography.x509.CertificateSigningRequest`` .. versionadded:: 17.1.0 """ from cryptography.hazmat.backends.openssl.x509 import ( _CertificateSigningRequest ) backend = _get_backend() return _CertificateSigningRequest(backend, self._req)
[ "def", "to_cryptography", "(", "self", ")", ":", "from", "cryptography", ".", "hazmat", ".", "backends", ".", "openssl", ".", "x509", "import", "(", "_CertificateSigningRequest", ")", "backend", "=", "_get_backend", "(", ")", "return", "_CertificateSigningRequest", "(", "backend", ",", "self", ".", "_req", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/OpenSSL/crypto.py#L863-L875
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/platform.py
python
_linux_distribution
(distname, version, id, supported_dists, full_distribution_name)
return distname, version, id
Tries to determine the name of the Linux OS distribution name. The function first looks for a distribution release file in /etc and then reverts to _dist_try_harder() in case no suitable files are found. supported_dists may be given to define the set of Linux distributions to look for. It defaults to a list of currently supported Linux distributions identified by their release file name. If full_distribution_name is true (default), the full distribution read from the OS is returned. Otherwise the short name taken from supported_dists is used. Returns a tuple (distname, version, id) which default to the args given as parameters.
Tries to determine the name of the Linux OS distribution name.
[ "Tries", "to", "determine", "the", "name", "of", "the", "Linux", "OS", "distribution", "name", "." ]
def _linux_distribution(distname, version, id, supported_dists, full_distribution_name): """ Tries to determine the name of the Linux OS distribution name. The function first looks for a distribution release file in /etc and then reverts to _dist_try_harder() in case no suitable files are found. supported_dists may be given to define the set of Linux distributions to look for. It defaults to a list of currently supported Linux distributions identified by their release file name. If full_distribution_name is true (default), the full distribution read from the OS is returned. Otherwise the short name taken from supported_dists is used. Returns a tuple (distname, version, id) which default to the args given as parameters. """ try: etc = os.listdir(_UNIXCONFDIR) except OSError: # Probably not a Unix system return distname, version, id etc.sort() for file in etc: m = _release_filename.match(file) if m is not None: _distname, dummy = m.groups() if _distname in supported_dists: distname = _distname break else: return _dist_try_harder(distname, version, id) # Read the first line with open(os.path.join(_UNIXCONFDIR, file), 'r', encoding='utf-8', errors='surrogateescape') as f: firstline = f.readline() _distname, _version, _id = _parse_release_file(firstline) if _distname and full_distribution_name: distname = _distname if _version: version = _version if _id: id = _id return distname, version, id
[ "def", "_linux_distribution", "(", "distname", ",", "version", ",", "id", ",", "supported_dists", ",", "full_distribution_name", ")", ":", "try", ":", "etc", "=", "os", ".", "listdir", "(", "_UNIXCONFDIR", ")", "except", "OSError", ":", "# Probably not a Unix system", "return", "distname", ",", "version", ",", "id", "etc", ".", "sort", "(", ")", "for", "file", "in", "etc", ":", "m", "=", "_release_filename", ".", "match", "(", "file", ")", "if", "m", "is", "not", "None", ":", "_distname", ",", "dummy", "=", "m", ".", "groups", "(", ")", "if", "_distname", "in", "supported_dists", ":", "distname", "=", "_distname", "break", "else", ":", "return", "_dist_try_harder", "(", "distname", ",", "version", ",", "id", ")", "# Read the first line", "with", "open", "(", "os", ".", "path", ".", "join", "(", "_UNIXCONFDIR", ",", "file", ")", ",", "'r'", ",", "encoding", "=", "'utf-8'", ",", "errors", "=", "'surrogateescape'", ")", "as", "f", ":", "firstline", "=", "f", ".", "readline", "(", ")", "_distname", ",", "_version", ",", "_id", "=", "_parse_release_file", "(", "firstline", ")", "if", "_distname", "and", "full_distribution_name", ":", "distname", "=", "_distname", "if", "_version", ":", "version", "=", "_version", "if", "_id", ":", "id", "=", "_id", "return", "distname", ",", "version", ",", "id" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/platform.py#L341-L391
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/gradientbutton.py
python
GradientButton.GetPressedBottomColour
(self)
return self._pressedBottomColour
Returns the pressed bottom start colour for the gradient shading.
Returns the pressed bottom start colour for the gradient shading.
[ "Returns", "the", "pressed", "bottom", "start", "colour", "for", "the", "gradient", "shading", "." ]
def GetPressedBottomColour(self): """ Returns the pressed bottom start colour for the gradient shading. """ return self._pressedBottomColour
[ "def", "GetPressedBottomColour", "(", "self", ")", ":", "return", "self", ".", "_pressedBottomColour" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/gradientbutton.py#L646-L649
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py3/pandas/core/dtypes/common.py
python
_is_dtype
(arr_or_dtype, condition)
return condition(dtype)
Return a boolean if the condition is satisfied for the arr_or_dtype. Parameters ---------- arr_or_dtype : array-like, str, np.dtype, or ExtensionArrayType The array-like or dtype object whose dtype we want to extract. condition : callable[Union[np.dtype, ExtensionDtype]] Returns ------- bool
Return a boolean if the condition is satisfied for the arr_or_dtype.
[ "Return", "a", "boolean", "if", "the", "condition", "is", "satisfied", "for", "the", "arr_or_dtype", "." ]
def _is_dtype(arr_or_dtype, condition) -> bool: """ Return a boolean if the condition is satisfied for the arr_or_dtype. Parameters ---------- arr_or_dtype : array-like, str, np.dtype, or ExtensionArrayType The array-like or dtype object whose dtype we want to extract. condition : callable[Union[np.dtype, ExtensionDtype]] Returns ------- bool """ if arr_or_dtype is None: return False try: dtype = get_dtype(arr_or_dtype) except (TypeError, ValueError): return False return condition(dtype)
[ "def", "_is_dtype", "(", "arr_or_dtype", ",", "condition", ")", "->", "bool", ":", "if", "arr_or_dtype", "is", "None", ":", "return", "False", "try", ":", "dtype", "=", "get_dtype", "(", "arr_or_dtype", ")", "except", "(", "TypeError", ",", "ValueError", ")", ":", "return", "False", "return", "condition", "(", "dtype", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/dtypes/common.py#L1519-L1540
JumpingYang001/webrtc
c03d6e965e1f54aeadd670e491eabe5fdb8db968
rtc_tools/py_event_log_analyzer/pb_parse.py
python
ParseProtobuf
(file_path)
return [ DataPoint(event.rtp_packet.header, event.rtp_packet.packet_length, event.timestamp_us, event.rtp_packet.incoming) for event in event_stream.stream if event.HasField("rtp_packet") ]
Parses RTC event log from protobuf file. Args: file_path: path to protobuf file of RTC event stream Returns: all RTP packet events from the event stream as a list of DataPoints
Parses RTC event log from protobuf file.
[ "Parses", "RTC", "event", "log", "from", "protobuf", "file", "." ]
def ParseProtobuf(file_path): """Parses RTC event log from protobuf file. Args: file_path: path to protobuf file of RTC event stream Returns: all RTP packet events from the event stream as a list of DataPoints """ event_stream = rtc_pb.EventStream() with open(file_path, "rb") as f: event_stream.ParseFromString(f.read()) return [ DataPoint(event.rtp_packet.header, event.rtp_packet.packet_length, event.timestamp_us, event.rtp_packet.incoming) for event in event_stream.stream if event.HasField("rtp_packet") ]
[ "def", "ParseProtobuf", "(", "file_path", ")", ":", "event_stream", "=", "rtc_pb", ".", "EventStream", "(", ")", "with", "open", "(", "file_path", ",", "\"rb\"", ")", "as", "f", ":", "event_stream", ".", "ParseFromString", "(", "f", ".", "read", "(", ")", ")", "return", "[", "DataPoint", "(", "event", ".", "rtp_packet", ".", "header", ",", "event", ".", "rtp_packet", ".", "packet_length", ",", "event", ".", "timestamp_us", ",", "event", ".", "rtp_packet", ".", "incoming", ")", "for", "event", "in", "event_stream", ".", "stream", "if", "event", ".", "HasField", "(", "\"rtp_packet\"", ")", "]" ]
https://github.com/JumpingYang001/webrtc/blob/c03d6e965e1f54aeadd670e491eabe5fdb8db968/rtc_tools/py_event_log_analyzer/pb_parse.py#L34-L51
neopenx/Dragon
0e639a7319035ddc81918bd3df059230436ee0a1
Dragon/python/dragon/vm/caffe/net.py
python
Net.backward
(self, **kwargs)
Backward pass. [**PyCaffe Style**] Parameters ---------- diffs : dict or None The diffs to feed before. Returns =------ None References ---------- The implementation of `Net_backward(pycaffe.py, L137)`_.
Backward pass. [**PyCaffe Style**]
[ "Backward", "pass", ".", "[", "**", "PyCaffe", "Style", "**", "]" ]
def backward(self, **kwargs): """Backward pass. [**PyCaffe Style**] Parameters ---------- diffs : dict or None The diffs to feed before. Returns =------ None References ---------- The implementation of `Net_backward(pycaffe.py, L137)`_. """ if kwargs: for name, blob in kwargs.items(): ws.FeedTensor(self._blobs[name]['diff'].data, blob) self.function()(return_outputs=False, stage='backward')
[ "def", "backward", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "kwargs", ":", "for", "name", ",", "blob", "in", "kwargs", ".", "items", "(", ")", ":", "ws", ".", "FeedTensor", "(", "self", ".", "_blobs", "[", "name", "]", "[", "'diff'", "]", ".", "data", ",", "blob", ")", "self", ".", "function", "(", ")", "(", "return_outputs", "=", "False", ",", "stage", "=", "'backward'", ")" ]
https://github.com/neopenx/Dragon/blob/0e639a7319035ddc81918bd3df059230436ee0a1/Dragon/python/dragon/vm/caffe/net.py#L381-L402
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/idlelib/query.py
python
HelpSource.__init__
(self, parent, title, *, menuitem='', filepath='', used_names={}, _htest=False, _utest=False)
Get menu entry and url/local file for Additional Help. User enters a name for the Help resource and a web url or file name. The user can browse for the file.
Get menu entry and url/local file for Additional Help.
[ "Get", "menu", "entry", "and", "url", "/", "local", "file", "for", "Additional", "Help", "." ]
def __init__(self, parent, title, *, menuitem='', filepath='', used_names={}, _htest=False, _utest=False): """Get menu entry and url/local file for Additional Help. User enters a name for the Help resource and a web url or file name. The user can browse for the file. """ self.filepath = filepath message = 'Name for item on Help menu:' super().__init__( parent, title, message, text0=menuitem, used_names=used_names, _htest=_htest, _utest=_utest)
[ "def", "__init__", "(", "self", ",", "parent", ",", "title", ",", "*", ",", "menuitem", "=", "''", ",", "filepath", "=", "''", ",", "used_names", "=", "{", "}", ",", "_htest", "=", "False", ",", "_utest", "=", "False", ")", ":", "self", ".", "filepath", "=", "filepath", "message", "=", "'Name for item on Help menu:'", "super", "(", ")", ".", "__init__", "(", "parent", ",", "title", ",", "message", ",", "text0", "=", "menuitem", ",", "used_names", "=", "used_names", ",", "_htest", "=", "_htest", ",", "_utest", "=", "_utest", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/idlelib/query.py#L246-L257
naver/sling
5671cd445a2caae0b4dd0332299e4cfede05062c
webkit/Source/JavaScriptCore/disassembler/udis86/ud_itab.py
python
UdItabGenerator.genOpcodeTable
(self, table, isGlobal=False)
Emit Opcode Table in C.
Emit Opcode Table in C.
[ "Emit", "Opcode", "Table", "in", "C", "." ]
def genOpcodeTable(self, table, isGlobal=False): """Emit Opcode Table in C. """ self.ItabC.write( "\n" ); if not isGlobal: self.ItabC.write('static ') self.ItabC.write( "const uint16_t %s[] = {\n" % self.getTableName(table)) for i in range(table.size()): if i > 0 and i % 4 == 0: self.ItabC.write( "\n" ) if i % 4 == 0: self.ItabC.write( " /* %2x */" % i) e = table.entryAt(i) if e is None: self.ItabC.write("%12s," % "INVALID") elif isinstance(e, UdOpcodeTable): self.ItabC.write("%12s," % ("GROUP(%d)" % self.getTableIndex(e))) elif isinstance(e, UdInsnDef): self.ItabC.write("%12s," % self.getInsnIndex(e)) self.ItabC.write( "\n" ) self.ItabC.write( "};\n" )
[ "def", "genOpcodeTable", "(", "self", ",", "table", ",", "isGlobal", "=", "False", ")", ":", "self", ".", "ItabC", ".", "write", "(", "\"\\n\"", ")", "if", "not", "isGlobal", ":", "self", ".", "ItabC", ".", "write", "(", "'static '", ")", "self", ".", "ItabC", ".", "write", "(", "\"const uint16_t %s[] = {\\n\"", "%", "self", ".", "getTableName", "(", "table", ")", ")", "for", "i", "in", "range", "(", "table", ".", "size", "(", ")", ")", ":", "if", "i", ">", "0", "and", "i", "%", "4", "==", "0", ":", "self", ".", "ItabC", ".", "write", "(", "\"\\n\"", ")", "if", "i", "%", "4", "==", "0", ":", "self", ".", "ItabC", ".", "write", "(", "\" /* %2x */\"", "%", "i", ")", "e", "=", "table", ".", "entryAt", "(", "i", ")", "if", "e", "is", "None", ":", "self", ".", "ItabC", ".", "write", "(", "\"%12s,\"", "%", "\"INVALID\"", ")", "elif", "isinstance", "(", "e", ",", "UdOpcodeTable", ")", ":", "self", ".", "ItabC", ".", "write", "(", "\"%12s,\"", "%", "(", "\"GROUP(%d)\"", "%", "self", ".", "getTableIndex", "(", "e", ")", ")", ")", "elif", "isinstance", "(", "e", ",", "UdInsnDef", ")", ":", "self", ".", "ItabC", ".", "write", "(", "\"%12s,\"", "%", "self", ".", "getInsnIndex", "(", "e", ")", ")", "self", ".", "ItabC", ".", "write", "(", "\"\\n\"", ")", "self", ".", "ItabC", ".", "write", "(", "\"};\\n\"", ")" ]
https://github.com/naver/sling/blob/5671cd445a2caae0b4dd0332299e4cfede05062c/webkit/Source/JavaScriptCore/disassembler/udis86/ud_itab.py#L221-L241
protocolbuffers/protobuf
b5ab0b7a18b7336c60130f4ddb2d97c51792f896
python/google/protobuf/service_reflection.py
python
GeneratedServiceType.__init__
(cls, name, bases, dictionary)
Creates a message service class. Args: name: Name of the class (ignored, but required by the metaclass protocol). bases: Base classes of the class being constructed. dictionary: The class dictionary of the class being constructed. dictionary[_DESCRIPTOR_KEY] must contain a ServiceDescriptor object describing this protocol service type.
Creates a message service class.
[ "Creates", "a", "message", "service", "class", "." ]
def __init__(cls, name, bases, dictionary): """Creates a message service class. Args: name: Name of the class (ignored, but required by the metaclass protocol). bases: Base classes of the class being constructed. dictionary: The class dictionary of the class being constructed. dictionary[_DESCRIPTOR_KEY] must contain a ServiceDescriptor object describing this protocol service type. """ # Don't do anything if this class doesn't have a descriptor. This happens # when a service class is subclassed. if GeneratedServiceType._DESCRIPTOR_KEY not in dictionary: return descriptor = dictionary[GeneratedServiceType._DESCRIPTOR_KEY] service_builder = _ServiceBuilder(descriptor) service_builder.BuildService(cls) cls.DESCRIPTOR = descriptor
[ "def", "__init__", "(", "cls", ",", "name", ",", "bases", ",", "dictionary", ")", ":", "# Don't do anything if this class doesn't have a descriptor. This happens", "# when a service class is subclassed.", "if", "GeneratedServiceType", ".", "_DESCRIPTOR_KEY", "not", "in", "dictionary", ":", "return", "descriptor", "=", "dictionary", "[", "GeneratedServiceType", ".", "_DESCRIPTOR_KEY", "]", "service_builder", "=", "_ServiceBuilder", "(", "descriptor", ")", "service_builder", ".", "BuildService", "(", "cls", ")", "cls", ".", "DESCRIPTOR", "=", "descriptor" ]
https://github.com/protocolbuffers/protobuf/blob/b5ab0b7a18b7336c60130f4ddb2d97c51792f896/python/google/protobuf/service_reflection.py#L64-L83
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py3/sklearn/mixture/_base.py
python
BaseMixture.predict_proba
(self, X)
return np.exp(log_resp)
Predict posterior probability of each component given the data. Parameters ---------- X : array-like, shape (n_samples, n_features) List of n_features-dimensional data points. Each row corresponds to a single data point. Returns ------- resp : array, shape (n_samples, n_components) Returns the probability each Gaussian (state) in the model given each sample.
Predict posterior probability of each component given the data.
[ "Predict", "posterior", "probability", "of", "each", "component", "given", "the", "data", "." ]
def predict_proba(self, X): """Predict posterior probability of each component given the data. Parameters ---------- X : array-like, shape (n_samples, n_features) List of n_features-dimensional data points. Each row corresponds to a single data point. Returns ------- resp : array, shape (n_samples, n_components) Returns the probability each Gaussian (state) in the model given each sample. """ check_is_fitted(self) X = _check_X(X, None, self.means_.shape[1]) _, log_resp = self._estimate_log_prob_resp(X) return np.exp(log_resp)
[ "def", "predict_proba", "(", "self", ",", "X", ")", ":", "check_is_fitted", "(", "self", ")", "X", "=", "_check_X", "(", "X", ",", "None", ",", "self", ".", "means_", ".", "shape", "[", "1", "]", ")", "_", ",", "log_resp", "=", "self", ".", "_estimate_log_prob_resp", "(", "X", ")", "return", "np", ".", "exp", "(", "log_resp", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/mixture/_base.py#L374-L392
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/threading.py
python
Barrier.__init__
(self, parties, action=None, timeout=None)
Create a barrier, initialised to 'parties' threads. 'action' is a callable which, when supplied, will be called by one of the threads after they have all entered the barrier and just prior to releasing them all. If a 'timeout' is provided, it is used as the default for all subsequent 'wait()' calls.
Create a barrier, initialised to 'parties' threads.
[ "Create", "a", "barrier", "initialised", "to", "parties", "threads", "." ]
def __init__(self, parties, action=None, timeout=None): """Create a barrier, initialised to 'parties' threads. 'action' is a callable which, when supplied, will be called by one of the threads after they have all entered the barrier and just prior to releasing them all. If a 'timeout' is provided, it is used as the default for all subsequent 'wait()' calls. """ self._cond = Condition(Lock()) self._action = action self._timeout = timeout self._parties = parties self._state = 0 #0 filling, 1, draining, -1 resetting, -2 broken self._count = 0
[ "def", "__init__", "(", "self", ",", "parties", ",", "action", "=", "None", ",", "timeout", "=", "None", ")", ":", "self", ".", "_cond", "=", "Condition", "(", "Lock", "(", ")", ")", "self", ".", "_action", "=", "action", "self", ".", "_timeout", "=", "timeout", "self", ".", "_parties", "=", "parties", "self", ".", "_state", "=", "0", "#0 filling, 1, draining, -1 resetting, -2 broken", "self", ".", "_count", "=", "0" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/threading.py#L576-L590
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/eager/context.py
python
Context._internal_operation_seed
(self)
return self._rng.randint(0, _MAXINT32)
Returns a fake operation seed. In eager mode, user shouldn't set or depend on operation seed. Here, we generate a random seed based on global seed to make operation's randomness different and depend on the global seed. Returns: A fake operation seed based on global seed.
Returns a fake operation seed.
[ "Returns", "a", "fake", "operation", "seed", "." ]
def _internal_operation_seed(self): """Returns a fake operation seed. In eager mode, user shouldn't set or depend on operation seed. Here, we generate a random seed based on global seed to make operation's randomness different and depend on the global seed. Returns: A fake operation seed based on global seed. """ return self._rng.randint(0, _MAXINT32)
[ "def", "_internal_operation_seed", "(", "self", ")", ":", "return", "self", ".", "_rng", ".", "randint", "(", "0", ",", "_MAXINT32", ")" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/eager/context.py#L524-L534
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/extern/aui/auibook.py
python
AuiTabContainer.SetNormalFont
(self, font)
Sets the normal font for drawing tab labels. :param Font `font`: the new font to use to draw tab labels in their normal, un-selected state.
Sets the normal font for drawing tab labels.
[ "Sets", "the", "normal", "font", "for", "drawing", "tab", "labels", "." ]
def SetNormalFont(self, font): """ Sets the normal font for drawing tab labels. :param Font `font`: the new font to use to draw tab labels in their normal, un-selected state. """ self._art.SetNormalFont(font)
[ "def", "SetNormalFont", "(", "self", ",", "font", ")", ":", "self", ".", "_art", ".", "SetNormalFont", "(", "font", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/extern/aui/auibook.py#L951-L958
microsoft/onnxruntime
f92e47e95b13a240e37caf7b36577983544f98fc
onnxruntime/python/onnxruntime_inference_collection.py
python
SparseTensor.as_csrc_view
(self)
return self._tensor.get_csrc_data()
The method will return CSR(C) representation of the sparse tensor which will enable querying CRS(C) indices. If the instance dit not contain CSR(C) format, it would throw. You can query indices as: :: inner_ndices = sparse_tensor.as_csrc_view().inner() outer_ndices = sparse_tensor.as_csrc_view().outer() returning numpy arrays backed by the native memory.
The method will return CSR(C) representation of the sparse tensor which will enable querying CRS(C) indices. If the instance dit not contain CSR(C) format, it would throw. You can query indices as:
[ "The", "method", "will", "return", "CSR", "(", "C", ")", "representation", "of", "the", "sparse", "tensor", "which", "will", "enable", "querying", "CRS", "(", "C", ")", "indices", ".", "If", "the", "instance", "dit", "not", "contain", "CSR", "(", "C", ")", "format", "it", "would", "throw", ".", "You", "can", "query", "indices", "as", ":" ]
def as_csrc_view(self): ''' The method will return CSR(C) representation of the sparse tensor which will enable querying CRS(C) indices. If the instance dit not contain CSR(C) format, it would throw. You can query indices as: :: inner_ndices = sparse_tensor.as_csrc_view().inner() outer_ndices = sparse_tensor.as_csrc_view().outer() returning numpy arrays backed by the native memory. ''' return self._tensor.get_csrc_data()
[ "def", "as_csrc_view", "(", "self", ")", ":", "return", "self", ".", "_tensor", ".", "get_csrc_data", "(", ")" ]
https://github.com/microsoft/onnxruntime/blob/f92e47e95b13a240e37caf7b36577983544f98fc/onnxruntime/python/onnxruntime_inference_collection.py#L766-L779
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/py_vulcanize/third_party/rjsmin/_setup/py2/data.py
python
Data.flatten
(self, installer)
return tmap.items()
Flatten the file list to (target, file) tuples
Flatten the file list to (target, file) tuples
[ "Flatten", "the", "file", "list", "to", "(", "target", "file", ")", "tuples" ]
def flatten(self, installer): """ Flatten the file list to (target, file) tuples """ # pylint: disable = W0613 if self._prefix: _, prefix = splitpath(self._prefix) telems = prefix else: telems = [] tmap = {} for fname in self._files: (_, name), target = splitpath(fname), telems if self._preserve: if self._strip: name = name[max(0, min(self._strip, len(name) - 1)):] if len(name) > 1: target = telems + name[:-1] tmap.setdefault(_posixpath.join(*target), []).append(fname) return tmap.items()
[ "def", "flatten", "(", "self", ",", "installer", ")", ":", "# pylint: disable = W0613", "if", "self", ".", "_prefix", ":", "_", ",", "prefix", "=", "splitpath", "(", "self", ".", "_prefix", ")", "telems", "=", "prefix", "else", ":", "telems", "=", "[", "]", "tmap", "=", "{", "}", "for", "fname", "in", "self", ".", "_files", ":", "(", "_", ",", "name", ")", ",", "target", "=", "splitpath", "(", "fname", ")", ",", "telems", "if", "self", ".", "_preserve", ":", "if", "self", ".", "_strip", ":", "name", "=", "name", "[", "max", "(", "0", ",", "min", "(", "self", ".", "_strip", ",", "len", "(", "name", ")", "-", "1", ")", ")", ":", "]", "if", "len", "(", "name", ")", ">", "1", ":", "target", "=", "telems", "+", "name", "[", ":", "-", "1", "]", "tmap", ".", "setdefault", "(", "_posixpath", ".", "join", "(", "*", "target", ")", ",", "[", "]", ")", ".", "append", "(", "fname", ")", "return", "tmap", ".", "items", "(", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/py_vulcanize/third_party/rjsmin/_setup/py2/data.py#L106-L124
lilypond/lilypond
2a14759372979f5b796ee802b0ee3bc15d28b06b
python/convertrules.py
python
rule
(version, message)
return dec
version: a LilyPond version tuple like (2, 11, 50) message: the message that describes the conversion. This decorator adds its function together with the version and the message to the global conversions list. (It doesn't need to return the function as it isn't used directly anyway.) A conversion rule using this decorator looks like this: @rule ((1, 2, 3), "convert foo to bar") def conv(s): s = s.replace('foo', 'bar') return s
version: a LilyPond version tuple like (2, 11, 50) message: the message that describes the conversion.
[ "version", ":", "a", "LilyPond", "version", "tuple", "like", "(", "2", "11", "50", ")", "message", ":", "the", "message", "that", "describes", "the", "conversion", "." ]
def rule(version, message): """ version: a LilyPond version tuple like (2, 11, 50) message: the message that describes the conversion. This decorator adds its function together with the version and the message to the global conversions list. (It doesn't need to return the function as it isn't used directly anyway.) A conversion rule using this decorator looks like this: @rule ((1, 2, 3), "convert foo to bar") def conv(s): s = s.replace('foo', 'bar') return s """ def dec(f): conversions.append((version, f, message)) return dec
[ "def", "rule", "(", "version", ",", "message", ")", ":", "def", "dec", "(", "f", ")", ":", "conversions", ".", "append", "(", "(", "version", ",", "f", ",", "message", ")", ")", "return", "dec" ]
https://github.com/lilypond/lilypond/blob/2a14759372979f5b796ee802b0ee3bc15d28b06b/python/convertrules.py#L50-L69
infinit/elle
a8154593c42743f45b9df09daf62b44630c24a02
drake/src/drake/__init__.py
python
DepFile.__init__
(self, builder, name)
Construct a dependency file for builder with given name.
Construct a dependency file for builder with given name.
[ "Construct", "a", "dependency", "file", "for", "builder", "with", "given", "name", "." ]
def __init__(self, builder, name): """Construct a dependency file for builder with given name.""" self.__builder = builder self.name = name self.__files = [] self.__invalid = False self.__hashes = None self.__dirty = False
[ "def", "__init__", "(", "self", ",", "builder", ",", "name", ")", ":", "self", ".", "__builder", "=", "builder", "self", ".", "name", "=", "name", "self", ".", "__files", "=", "[", "]", "self", ".", "__invalid", "=", "False", "self", ".", "__hashes", "=", "None", "self", ".", "__dirty", "=", "False" ]
https://github.com/infinit/elle/blob/a8154593c42743f45b9df09daf62b44630c24a02/drake/src/drake/__init__.py#L1161-L1168
OkCupid/okws
1c337392c676ccb4e9a4c92d11d5d2fada6427d2
contrib/pub3-upgrade.py
python
Pub1Parser.p_bindkey
(self, p)
bindkey : null | string | bind_var | integer
bindkey : null | string | bind_var | integer
[ "bindkey", ":", "null", "|", "string", "|", "bind_var", "|", "integer" ]
def p_bindkey (self, p): '''bindkey : null | string | bind_var | integer''' p[0] = p[1]
[ "def", "p_bindkey", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "p", "[", "1", "]" ]
https://github.com/OkCupid/okws/blob/1c337392c676ccb4e9a4c92d11d5d2fada6427d2/contrib/pub3-upgrade.py#L1016-L1021
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/ftplib.py
python
FTP.retrlines
(self, cmd, callback = None)
return self.voidresp()
Retrieve data in line mode. A new port is created for you. Args: cmd: A RETR, LIST, or NLST command. callback: An optional single parameter callable that is called for each line with the trailing CRLF stripped. [default: print_line()] Returns: The response code.
Retrieve data in line mode. A new port is created for you.
[ "Retrieve", "data", "in", "line", "mode", ".", "A", "new", "port", "is", "created", "for", "you", "." ]
def retrlines(self, cmd, callback = None): """Retrieve data in line mode. A new port is created for you. Args: cmd: A RETR, LIST, or NLST command. callback: An optional single parameter callable that is called for each line with the trailing CRLF stripped. [default: print_line()] Returns: The response code. """ if callback is None: callback = print_line resp = self.sendcmd('TYPE A') with self.transfercmd(cmd) as conn, \ conn.makefile('r', encoding=self.encoding) as fp: while 1: line = fp.readline(self.maxline + 1) if len(line) > self.maxline: raise Error("got more than %d bytes" % self.maxline) if self.debugging > 2: print('*retr*', repr(line)) if not line: break if line[-2:] == CRLF: line = line[:-2] elif line[-1:] == '\n': line = line[:-1] callback(line) # shutdown ssl layer if _SSLSocket is not None and isinstance(conn, _SSLSocket): conn.unwrap() return self.voidresp()
[ "def", "retrlines", "(", "self", ",", "cmd", ",", "callback", "=", "None", ")", ":", "if", "callback", "is", "None", ":", "callback", "=", "print_line", "resp", "=", "self", ".", "sendcmd", "(", "'TYPE A'", ")", "with", "self", ".", "transfercmd", "(", "cmd", ")", "as", "conn", ",", "conn", ".", "makefile", "(", "'r'", ",", "encoding", "=", "self", ".", "encoding", ")", "as", "fp", ":", "while", "1", ":", "line", "=", "fp", ".", "readline", "(", "self", ".", "maxline", "+", "1", ")", "if", "len", "(", "line", ")", ">", "self", ".", "maxline", ":", "raise", "Error", "(", "\"got more than %d bytes\"", "%", "self", ".", "maxline", ")", "if", "self", ".", "debugging", ">", "2", ":", "print", "(", "'*retr*'", ",", "repr", "(", "line", ")", ")", "if", "not", "line", ":", "break", "if", "line", "[", "-", "2", ":", "]", "==", "CRLF", ":", "line", "=", "line", "[", ":", "-", "2", "]", "elif", "line", "[", "-", "1", ":", "]", "==", "'\\n'", ":", "line", "=", "line", "[", ":", "-", "1", "]", "callback", "(", "line", ")", "# shutdown ssl layer", "if", "_SSLSocket", "is", "not", "None", "and", "isinstance", "(", "conn", ",", "_SSLSocket", ")", ":", "conn", ".", "unwrap", "(", ")", "return", "self", ".", "voidresp", "(", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/ftplib.py#L453-L486
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/richtext.py
python
TextAttrDimensionConverter.ConvertTenthsMMToPixels
(*args, **kwargs)
return _richtext.TextAttrDimensionConverter_ConvertTenthsMMToPixels(*args, **kwargs)
ConvertTenthsMMToPixels(self, int units) -> int
ConvertTenthsMMToPixels(self, int units) -> int
[ "ConvertTenthsMMToPixels", "(", "self", "int", "units", ")", "-", ">", "int" ]
def ConvertTenthsMMToPixels(*args, **kwargs): """ConvertTenthsMMToPixels(self, int units) -> int""" return _richtext.TextAttrDimensionConverter_ConvertTenthsMMToPixels(*args, **kwargs)
[ "def", "ConvertTenthsMMToPixels", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_richtext", ".", "TextAttrDimensionConverter_ConvertTenthsMMToPixels", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/richtext.py#L278-L280
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
src/external/boost/boost_1_68_0/tools/build/src/util/regex.py
python
replace
(s, pattern, replacement)
return re.sub(pattern, _replacement, s)
Replaces occurrences of a match string in a given string and returns the new string. The match string can be a regex expression. Args: s (str): the string to modify pattern (str): the search expression replacement (str): the string to replace each match with
Replaces occurrences of a match string in a given string and returns the new string. The match string can be a regex expression.
[ "Replaces", "occurrences", "of", "a", "match", "string", "in", "a", "given", "string", "and", "returns", "the", "new", "string", ".", "The", "match", "string", "can", "be", "a", "regex", "expression", "." ]
def replace(s, pattern, replacement): """Replaces occurrences of a match string in a given string and returns the new string. The match string can be a regex expression. Args: s (str): the string to modify pattern (str): the search expression replacement (str): the string to replace each match with """ # the replacement string may contain invalid backreferences (like \1 or \g) # which will cause python's regex to blow up. Since this should emulate # the jam version exactly and the jam version didn't support # backreferences, this version shouldn't either. re.sub # allows replacement to be a callable; this is being used # to simply return the replacement string and avoid the hassle # of worrying about backreferences within the string. def _replacement(matchobj): return replacement return re.sub(pattern, _replacement, s)
[ "def", "replace", "(", "s", ",", "pattern", ",", "replacement", ")", ":", "# the replacement string may contain invalid backreferences (like \\1 or \\g)", "# which will cause python's regex to blow up. Since this should emulate", "# the jam version exactly and the jam version didn't support", "# backreferences, this version shouldn't either. re.sub", "# allows replacement to be a callable; this is being used", "# to simply return the replacement string and avoid the hassle", "# of worrying about backreferences within the string.", "def", "_replacement", "(", "matchobj", ")", ":", "return", "replacement", "return", "re", ".", "sub", "(", "pattern", ",", "_replacement", ",", "s", ")" ]
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/external/boost/boost_1_68_0/tools/build/src/util/regex.py#L31-L50
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/tensorflow/contrib/distributions/python/ops/binomial.py
python
Binomial.dtype
(self)
return self._p.dtype
dtype of samples from this distribution.
dtype of samples from this distribution.
[ "dtype", "of", "samples", "from", "this", "distribution", "." ]
def dtype(self): """dtype of samples from this distribution.""" return self._p.dtype
[ "def", "dtype", "(", "self", ")", ":", "return", "self", ".", "_p", ".", "dtype" ]
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/contrib/distributions/python/ops/binomial.py#L158-L160
deepmind/open_spiel
4ca53bea32bb2875c7385d215424048ae92f78c8
open_spiel/python/mfg/games/linear_quadratic.py
python
MFGLinearQuadraticGame.new_initial_state
(self)
return MFGLinearQuadraticState(self)
Returns a state corresponding to the start of a game.
Returns a state corresponding to the start of a game.
[ "Returns", "a", "state", "corresponding", "to", "the", "start", "of", "a", "game", "." ]
def new_initial_state(self): """Returns a state corresponding to the start of a game.""" return MFGLinearQuadraticState(self)
[ "def", "new_initial_state", "(", "self", ")", ":", "return", "MFGLinearQuadraticState", "(", "self", ")" ]
https://github.com/deepmind/open_spiel/blob/4ca53bea32bb2875c7385d215424048ae92f78c8/open_spiel/python/mfg/games/linear_quadratic.py#L111-L113
jiangxiluning/FOTS.PyTorch
b1851c170b4f1ad18406766352cb5171648ce603
FOTS/utils/eval_tools/icdar2015/rrc_evaluation_funcs_1_1.py
python
validate_tl_line
(line,LTRB=True,withTranscription=True,withConfidence=True,imWidth=0,imHeight=0)
Validate the format of the line. If the line is not valid an exception will be raised. If maxWidth and maxHeight are specified, all points must be inside the imgage bounds. Posible values are: LTRB=True: xmin,ymin,xmax,ymax[,confidence][,transcription] LTRB=False: x1,y1,x2,y2,x3,y3,x4,y4[,confidence][,transcription]
Validate the format of the line. If the line is not valid an exception will be raised. If maxWidth and maxHeight are specified, all points must be inside the imgage bounds. Posible values are: LTRB=True: xmin,ymin,xmax,ymax[,confidence][,transcription] LTRB=False: x1,y1,x2,y2,x3,y3,x4,y4[,confidence][,transcription]
[ "Validate", "the", "format", "of", "the", "line", ".", "If", "the", "line", "is", "not", "valid", "an", "exception", "will", "be", "raised", ".", "If", "maxWidth", "and", "maxHeight", "are", "specified", "all", "points", "must", "be", "inside", "the", "imgage", "bounds", ".", "Posible", "values", "are", ":", "LTRB", "=", "True", ":", "xmin", "ymin", "xmax", "ymax", "[", "confidence", "]", "[", "transcription", "]", "LTRB", "=", "False", ":", "x1", "y1", "x2", "y2", "x3", "y3", "x4", "y4", "[", "confidence", "]", "[", "transcription", "]" ]
def validate_tl_line(line,LTRB=True,withTranscription=True,withConfidence=True,imWidth=0,imHeight=0): """ Validate the format of the line. If the line is not valid an exception will be raised. If maxWidth and maxHeight are specified, all points must be inside the imgage bounds. Posible values are: LTRB=True: xmin,ymin,xmax,ymax[,confidence][,transcription] LTRB=False: x1,y1,x2,y2,x3,y3,x4,y4[,confidence][,transcription] """ get_tl_line_values(line,LTRB,withTranscription,withConfidence,imWidth,imHeight)
[ "def", "validate_tl_line", "(", "line", ",", "LTRB", "=", "True", ",", "withTranscription", "=", "True", ",", "withConfidence", "=", "True", ",", "imWidth", "=", "0", ",", "imHeight", "=", "0", ")", ":", "get_tl_line_values", "(", "line", ",", "LTRB", ",", "withTranscription", ",", "withConfidence", ",", "imWidth", ",", "imHeight", ")" ]
https://github.com/jiangxiluning/FOTS.PyTorch/blob/b1851c170b4f1ad18406766352cb5171648ce603/FOTS/utils/eval_tools/icdar2015/rrc_evaluation_funcs_1_1.py#L111-L119
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/klampt/vis/glprogram.py
python
GLProgram.mousefunc
(self,button,state,x,y)
return False
Called when the mouse is clicked. May be overridden.
Called when the mouse is clicked. May be overridden.
[ "Called", "when", "the", "mouse", "is", "clicked", ".", "May", "be", "overridden", "." ]
def mousefunc(self,button,state,x,y): """Called when the mouse is clicked. May be overridden.""" return False
[ "def", "mousefunc", "(", "self", ",", "button", ",", "state", ",", "x", ",", "y", ")", ":", "return", "False" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/vis/glprogram.py#L129-L131
moderngl/moderngl
32fe79927e02b0fa893b3603d677bdae39771e14
moderngl/texture_3d.py
python
Texture3D.write
(self, data, viewport=None, *, alignment=1)
Update the content of the texture from byte data or a moderngl :py:class:`~moderngl.Buffer`:: # Write data from a moderngl Buffer data = ctx.buffer(reserve=8) texture = ctx.texture3d((2, 2, 2), 1) texture.write(data) # Write data from bytes data = b'\xff\xff\xff\xff\xff\xff\xff\xff' texture = ctx.texture3d((2, 2), 1) texture.write(data) Args: data (bytes): The pixel data. viewport (tuple): The viewport. Keyword Args: alignment (int): The byte alignment of the pixels.
Update the content of the texture from byte data or a moderngl :py:class:`~moderngl.Buffer`::
[ "Update", "the", "content", "of", "the", "texture", "from", "byte", "data", "or", "a", "moderngl", ":", "py", ":", "class", ":", "~moderngl", ".", "Buffer", "::" ]
def write(self, data, viewport=None, *, alignment=1) -> None: ''' Update the content of the texture from byte data or a moderngl :py:class:`~moderngl.Buffer`:: # Write data from a moderngl Buffer data = ctx.buffer(reserve=8) texture = ctx.texture3d((2, 2, 2), 1) texture.write(data) # Write data from bytes data = b'\xff\xff\xff\xff\xff\xff\xff\xff' texture = ctx.texture3d((2, 2), 1) texture.write(data) Args: data (bytes): The pixel data. viewport (tuple): The viewport. Keyword Args: alignment (int): The byte alignment of the pixels. ''' if type(data) is Buffer: data = data.mglo self.mglo.write(data, viewport, alignment)
[ "def", "write", "(", "self", ",", "data", ",", "viewport", "=", "None", ",", "*", ",", "alignment", "=", "1", ")", "->", "None", ":", "if", "type", "(", "data", ")", "is", "Buffer", ":", "data", "=", "data", ".", "mglo", "self", ".", "mglo", ".", "write", "(", "data", ",", "viewport", ",", "alignment", ")" ]
https://github.com/moderngl/moderngl/blob/32fe79927e02b0fa893b3603d677bdae39771e14/moderngl/texture_3d.py#L258-L284
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
caffe2/python/modeling/gradient_clipping.py
python
GradientClipping.__init__
(self, grad_clip_method, clip_norm_type='l2_norm', clip_threshold=0.1, use_parameter_norm=False, compute_norm_ratio=False, clip_max=1, clip_min=-1, blobs_to_include=None, blobs_to_exclude=None)
Clips gradient to avoid gradient magnitude explosion or vanishing gradient. Args: grad_clip_method: ways to clip the gradients clip_norm_type: type of norm used in the necessary computation clip_threshold: threshold used to determine whether to clip use_parameter_norm: a boolean to indicate whether to incorporate the norm of the parameter compute_norm_ratio: a boolean to compute the ratio between gradient norm and parameter norm explicitly for debugging purpose clip_max: when clipping by_value, any value that is greater than clip_max will be clipped to clip_max clip_min: when clipping by_value, any value that is smaller than clip_min will be clipped to clip_min blobs_to_include: names of blobs whose gradient is to be clipped. If it is set to none, all param 's gradient in grad_map will be clipped. blobs_to_exclude: names of blobs whose gradient is not to be clipped.
Clips gradient to avoid gradient magnitude explosion or vanishing gradient.
[ "Clips", "gradient", "to", "avoid", "gradient", "magnitude", "explosion", "or", "vanishing", "gradient", "." ]
def __init__(self, grad_clip_method, clip_norm_type='l2_norm', clip_threshold=0.1, use_parameter_norm=False, compute_norm_ratio=False, clip_max=1, clip_min=-1, blobs_to_include=None, blobs_to_exclude=None): """ Clips gradient to avoid gradient magnitude explosion or vanishing gradient. Args: grad_clip_method: ways to clip the gradients clip_norm_type: type of norm used in the necessary computation clip_threshold: threshold used to determine whether to clip use_parameter_norm: a boolean to indicate whether to incorporate the norm of the parameter compute_norm_ratio: a boolean to compute the ratio between gradient norm and parameter norm explicitly for debugging purpose clip_max: when clipping by_value, any value that is greater than clip_max will be clipped to clip_max clip_min: when clipping by_value, any value that is smaller than clip_min will be clipped to clip_min blobs_to_include: names of blobs whose gradient is to be clipped. If it is set to none, all param 's gradient in grad_map will be clipped. blobs_to_exclude: names of blobs whose gradient is not to be clipped. """ assert grad_clip_method in self.GRAD_CLIP_METHODS, ( "This method of clipping, {}, has not been implemented.".format( clip_norm_type)) if clip_norm_type is not None: assert clip_norm_type in self.CLIP_GRADIENT_NORM_TYPES, ( "This method of clipping, {}, has not been implemented.".format( clip_norm_type)) self.grad_clip_method = grad_clip_method self.clip_norm_type = clip_norm_type self.clip_threshold = float(clip_threshold) self.use_parameter_norm = use_parameter_norm self.compute_norm_ratio = compute_norm_ratio self.clip_max = float(clip_max) self.clip_min = float(clip_min) self.blobs_to_include = blobs_to_include self.blobs_to_exclude = blobs_to_exclude
[ "def", "__init__", "(", "self", ",", "grad_clip_method", ",", "clip_norm_type", "=", "'l2_norm'", ",", "clip_threshold", "=", "0.1", ",", "use_parameter_norm", "=", "False", ",", "compute_norm_ratio", "=", "False", ",", "clip_max", "=", "1", ",", "clip_min", "=", "-", "1", ",", "blobs_to_include", "=", "None", ",", "blobs_to_exclude", "=", "None", ")", ":", "assert", "grad_clip_method", "in", "self", ".", "GRAD_CLIP_METHODS", ",", "(", "\"This method of clipping, {}, has not been implemented.\"", ".", "format", "(", "clip_norm_type", ")", ")", "if", "clip_norm_type", "is", "not", "None", ":", "assert", "clip_norm_type", "in", "self", ".", "CLIP_GRADIENT_NORM_TYPES", ",", "(", "\"This method of clipping, {}, has not been implemented.\"", ".", "format", "(", "clip_norm_type", ")", ")", "self", ".", "grad_clip_method", "=", "grad_clip_method", "self", ".", "clip_norm_type", "=", "clip_norm_type", "self", ".", "clip_threshold", "=", "float", "(", "clip_threshold", ")", "self", ".", "use_parameter_norm", "=", "use_parameter_norm", "self", ".", "compute_norm_ratio", "=", "compute_norm_ratio", "self", ".", "clip_max", "=", "float", "(", "clip_max", ")", "self", ".", "clip_min", "=", "float", "(", "clip_min", ")", "self", ".", "blobs_to_include", "=", "blobs_to_include", "self", ".", "blobs_to_exclude", "=", "blobs_to_exclude" ]
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/caffe2/python/modeling/gradient_clipping.py#L27-L67
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/urllib3/packages/ssl_match_hostname/_implementation.py
python
match_hostname
(cert, hostname)
Verify that *cert* (in decoded format as returned by SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 and RFC 6125 rules are followed, but IP addresses are not accepted for *hostname*. CertificateError is raised on failure. On success, the function returns nothing.
Verify that *cert* (in decoded format as returned by SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 and RFC 6125 rules are followed, but IP addresses are not accepted for *hostname*.
[ "Verify", "that", "*", "cert", "*", "(", "in", "decoded", "format", "as", "returned", "by", "SSLSocket", ".", "getpeercert", "()", ")", "matches", "the", "*", "hostname", "*", ".", "RFC", "2818", "and", "RFC", "6125", "rules", "are", "followed", "but", "IP", "addresses", "are", "not", "accepted", "for", "*", "hostname", "*", "." ]
def match_hostname(cert, hostname): """Verify that *cert* (in decoded format as returned by SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 and RFC 6125 rules are followed, but IP addresses are not accepted for *hostname*. CertificateError is raised on failure. On success, the function returns nothing. """ if not cert: raise ValueError( "empty or no certificate, match_hostname needs a " "SSL socket or SSL context with either " "CERT_OPTIONAL or CERT_REQUIRED" ) try: # Divergence from upstream: ipaddress can't handle byte str host_ip = ipaddress.ip_address(_to_unicode(hostname)) except ValueError: # Not an IP address (common case) host_ip = None except UnicodeError: # Divergence from upstream: Have to deal with ipaddress not taking # byte strings. addresses should be all ascii, so we consider it not # an ipaddress in this case host_ip = None except AttributeError: # Divergence from upstream: Make ipaddress library optional if ipaddress is None: host_ip = None else: raise dnsnames = [] san = cert.get("subjectAltName", ()) for key, value in san: if key == "DNS": if host_ip is None and _dnsname_match(value, hostname): return dnsnames.append(value) elif key == "IP Address": if host_ip is not None and _ipaddress_match(value, host_ip): return dnsnames.append(value) if not dnsnames: # The subject is only checked when there is no dNSName entry # in subjectAltName for sub in cert.get("subject", ()): for key, value in sub: # XXX according to RFC 2818, the most specific Common Name # must be used. if key == "commonName": if _dnsname_match(value, hostname): return dnsnames.append(value) if len(dnsnames) > 1: raise CertificateError( "hostname %r " "doesn't match either of %s" % (hostname, ", ".join(map(repr, dnsnames))) ) elif len(dnsnames) == 1: raise CertificateError("hostname %r doesn't match %r" % (hostname, dnsnames[0])) else: raise CertificateError( "no appropriate commonName or subjectAltName fields were found" )
[ "def", "match_hostname", "(", "cert", ",", "hostname", ")", ":", "if", "not", "cert", ":", "raise", "ValueError", "(", "\"empty or no certificate, match_hostname needs a \"", "\"SSL socket or SSL context with either \"", "\"CERT_OPTIONAL or CERT_REQUIRED\"", ")", "try", ":", "# Divergence from upstream: ipaddress can't handle byte str", "host_ip", "=", "ipaddress", ".", "ip_address", "(", "_to_unicode", "(", "hostname", ")", ")", "except", "ValueError", ":", "# Not an IP address (common case)", "host_ip", "=", "None", "except", "UnicodeError", ":", "# Divergence from upstream: Have to deal with ipaddress not taking", "# byte strings. addresses should be all ascii, so we consider it not", "# an ipaddress in this case", "host_ip", "=", "None", "except", "AttributeError", ":", "# Divergence from upstream: Make ipaddress library optional", "if", "ipaddress", "is", "None", ":", "host_ip", "=", "None", "else", ":", "raise", "dnsnames", "=", "[", "]", "san", "=", "cert", ".", "get", "(", "\"subjectAltName\"", ",", "(", ")", ")", "for", "key", ",", "value", "in", "san", ":", "if", "key", "==", "\"DNS\"", ":", "if", "host_ip", "is", "None", "and", "_dnsname_match", "(", "value", ",", "hostname", ")", ":", "return", "dnsnames", ".", "append", "(", "value", ")", "elif", "key", "==", "\"IP Address\"", ":", "if", "host_ip", "is", "not", "None", "and", "_ipaddress_match", "(", "value", ",", "host_ip", ")", ":", "return", "dnsnames", ".", "append", "(", "value", ")", "if", "not", "dnsnames", ":", "# The subject is only checked when there is no dNSName entry", "# in subjectAltName", "for", "sub", "in", "cert", ".", "get", "(", "\"subject\"", ",", "(", ")", ")", ":", "for", "key", ",", "value", "in", "sub", ":", "# XXX according to RFC 2818, the most specific Common Name", "# must be used.", "if", "key", "==", "\"commonName\"", ":", "if", "_dnsname_match", "(", "value", ",", "hostname", ")", ":", "return", "dnsnames", ".", "append", "(", "value", ")", "if", "len", "(", "dnsnames", ")", ">", "1", ":", "raise", "CertificateError", "(", "\"hostname %r \"", "\"doesn't match either of %s\"", "%", "(", "hostname", ",", "\", \"", ".", "join", "(", "map", "(", "repr", ",", "dnsnames", ")", ")", ")", ")", "elif", "len", "(", "dnsnames", ")", "==", "1", ":", "raise", "CertificateError", "(", "\"hostname %r doesn't match %r\"", "%", "(", "hostname", ",", "dnsnames", "[", "0", "]", ")", ")", "else", ":", "raise", "CertificateError", "(", "\"no appropriate commonName or subjectAltName fields were found\"", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/urllib3/packages/ssl_match_hostname/_implementation.py#L97-L160
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/ros_comm/roslaunch/src/roslaunch/substitution_args.py
python
_find_resource
(resolved, a, args, _context, source_path_to_packages=None)
return before + paths[0] + after
process $(find-resource PKG PATH) Resolves the relative PATH from the share folder of the PKG either from install space, devel space or from the source folder. :returns: updated resolved argument, ``str`` :raises: :exc:SubstitutionException: if PKG and PATH invalidly specified or relative PATH is not found for PKG
process $(find-resource PKG PATH) Resolves the relative PATH from the share folder of the PKG either from install space, devel space or from the source folder. :returns: updated resolved argument, ``str`` :raises: :exc:SubstitutionException: if PKG and PATH invalidly specified or relative PATH is not found for PKG
[ "process", "$", "(", "find", "-", "resource", "PKG", "PATH", ")", "Resolves", "the", "relative", "PATH", "from", "the", "share", "folder", "of", "the", "PKG", "either", "from", "install", "space", "devel", "space", "or", "from", "the", "source", "folder", ".", ":", "returns", ":", "updated", "resolved", "argument", "str", ":", "raises", ":", ":", "exc", ":", "SubstitutionException", ":", "if", "PKG", "and", "PATH", "invalidly", "specified", "or", "relative", "PATH", "is", "not", "found", "for", "PKG" ]
def _find_resource(resolved, a, args, _context, source_path_to_packages=None): """ process $(find-resource PKG PATH) Resolves the relative PATH from the share folder of the PKG either from install space, devel space or from the source folder. :returns: updated resolved argument, ``str`` :raises: :exc:SubstitutionException: if PKG and PATH invalidly specified or relative PATH is not found for PKG """ if len(args) != 2: raise SubstitutionException("$(find-resource pkg path) command only accepts two argument [%s]" % a) before, after = _split_command(resolved, a) path = _sanitize_path(args[1]) # we try to find the specific path in share via catkin # which will search in install/devel space and the source folder of the package from catkin.find_in_workspaces import find_in_workspaces paths = find_in_workspaces( ['share'], project=args[0], path=path, first_matching_workspace_only=True, first_match_only=True, source_path_to_packages=source_path_to_packages) if not paths: raise SubstitutionException("$(find-resource pkg path) could not find path [%s]" % a) return before + paths[0] + after
[ "def", "_find_resource", "(", "resolved", ",", "a", ",", "args", ",", "_context", ",", "source_path_to_packages", "=", "None", ")", ":", "if", "len", "(", "args", ")", "!=", "2", ":", "raise", "SubstitutionException", "(", "\"$(find-resource pkg path) command only accepts two argument [%s]\"", "%", "a", ")", "before", ",", "after", "=", "_split_command", "(", "resolved", ",", "a", ")", "path", "=", "_sanitize_path", "(", "args", "[", "1", "]", ")", "# we try to find the specific path in share via catkin", "# which will search in install/devel space and the source folder of the package", "from", "catkin", ".", "find_in_workspaces", "import", "find_in_workspaces", "paths", "=", "find_in_workspaces", "(", "[", "'share'", "]", ",", "project", "=", "args", "[", "0", "]", ",", "path", "=", "path", ",", "first_matching_workspace_only", "=", "True", ",", "first_match_only", "=", "True", ",", "source_path_to_packages", "=", "source_path_to_packages", ")", "if", "not", "paths", ":", "raise", "SubstitutionException", "(", "\"$(find-resource pkg path) could not find path [%s]\"", "%", "a", ")", "return", "before", "+", "paths", "[", "0", "]", "+", "after" ]
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/ros_comm/roslaunch/src/roslaunch/substitution_args.py#L194-L213
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/python2_version/klampt/io/resource.py
python
thumbnail
(value,size,type='auto',world=None,frame=None)
return plugin.image
Retrieves an image of the given item, resized to the given size. Args: value: a resource type. size (pair of ints): the (width,height) of the thumbnail, in pixels. type (str, optional): the type of value world (WorldModel, optional): if given, the resource will be drawn with this world in the background. If the resource needs an associated object (e.g., Config, Configs, Trajectory), the object will be drawn with that given object. frame (se3 element, optional): not supported yet. Will eventually let you draw Points or RigidTransforms relative to some reference frame. Returns: (Image or bytes): A PIL Image if PIL is available, or just a raw RGBA memory buffer otherwise.
Retrieves an image of the given item, resized to the given size.
[ "Retrieves", "an", "image", "of", "the", "given", "item", "resized", "to", "the", "given", "size", "." ]
def thumbnail(value,size,type='auto',world=None,frame=None): """Retrieves an image of the given item, resized to the given size. Args: value: a resource type. size (pair of ints): the (width,height) of the thumbnail, in pixels. type (str, optional): the type of value world (WorldModel, optional): if given, the resource will be drawn with this world in the background. If the resource needs an associated object (e.g., Config, Configs, Trajectory), the object will be drawn with that given object. frame (se3 element, optional): not supported yet. Will eventually let you draw Points or RigidTransforms relative to some reference frame. Returns: (Image or bytes): A PIL Image if PIL is available, or just a raw RGBA memory buffer otherwise. """ global _thumbnail_window world = _get_world(world) if isinstance(value,WorldModel): world = value value = None if type == 'auto' and value is not None: typelist = types.objectToTypes(value) if isinstance(typelist,(list,tuple)): type = typelist[0] else: type = typelist if type == None: raise ValueError("Un-recognized type") if type=='Config' and world is None and len(value)==3: type = 'Vector3' if type in ['Config','Configs','Trajectory','IKGoal']: if world is None: raise ValueError("Need a world to draw a thumbnail of type "+type) if frame != None: if type not in ['RigidTransform','Vector3','Matrix3']: raise ValueError("Can't accept frame argument for objects of type "+type) old_window = vis.getWindow() if _thumbnail_window is None: _thumbnail_window = vis.createWindow("") vis.setWindow(_thumbnail_window) assert not vis.shown() vp = vis.getViewport() vp.w,vp.h = size if vp.w < 256 or vp.h < 256: vp.w = vp.w *256 / min(vp.w,vp.h) vp.h = vp.h *256 / min(vp.w,vp.h) vis.setViewport(vp) vp = vis.getViewport() plugin = _ThumbnailPlugin(world) if world: plugin.add("world",world) if value is not None: if type == 'Config': world.robot(0).setConfig(value) else: plugin.add("item",value) plugin.autoFitCamera() vis.setPlugin(plugin) vis.show() plugin.rendered = 0 while not plugin.done: time.sleep(0.1) vis.setPlugin(None) vis.show(False) vis.setWindow(old_window) if (vp.w,vp.h) != size and plugin.image.__class__.__name__=='Image': try: from PIL import Image plugin.image.thumbnail(size,Image.ANTIALIAS) except ImportError: try: import Image plugin.image.thumbnail(size,Image.ANTIALIAS) except ImportError: # if this happens then # plugin.image is just a raw RGBA memory buffer pass return plugin.image
[ "def", "thumbnail", "(", "value", ",", "size", ",", "type", "=", "'auto'", ",", "world", "=", "None", ",", "frame", "=", "None", ")", ":", "global", "_thumbnail_window", "world", "=", "_get_world", "(", "world", ")", "if", "isinstance", "(", "value", ",", "WorldModel", ")", ":", "world", "=", "value", "value", "=", "None", "if", "type", "==", "'auto'", "and", "value", "is", "not", "None", ":", "typelist", "=", "types", ".", "objectToTypes", "(", "value", ")", "if", "isinstance", "(", "typelist", ",", "(", "list", ",", "tuple", ")", ")", ":", "type", "=", "typelist", "[", "0", "]", "else", ":", "type", "=", "typelist", "if", "type", "==", "None", ":", "raise", "ValueError", "(", "\"Un-recognized type\"", ")", "if", "type", "==", "'Config'", "and", "world", "is", "None", "and", "len", "(", "value", ")", "==", "3", ":", "type", "=", "'Vector3'", "if", "type", "in", "[", "'Config'", ",", "'Configs'", ",", "'Trajectory'", ",", "'IKGoal'", "]", ":", "if", "world", "is", "None", ":", "raise", "ValueError", "(", "\"Need a world to draw a thumbnail of type \"", "+", "type", ")", "if", "frame", "!=", "None", ":", "if", "type", "not", "in", "[", "'RigidTransform'", ",", "'Vector3'", ",", "'Matrix3'", "]", ":", "raise", "ValueError", "(", "\"Can't accept frame argument for objects of type \"", "+", "type", ")", "old_window", "=", "vis", ".", "getWindow", "(", ")", "if", "_thumbnail_window", "is", "None", ":", "_thumbnail_window", "=", "vis", ".", "createWindow", "(", "\"\"", ")", "vis", ".", "setWindow", "(", "_thumbnail_window", ")", "assert", "not", "vis", ".", "shown", "(", ")", "vp", "=", "vis", ".", "getViewport", "(", ")", "vp", ".", "w", ",", "vp", ".", "h", "=", "size", "if", "vp", ".", "w", "<", "256", "or", "vp", ".", "h", "<", "256", ":", "vp", ".", "w", "=", "vp", ".", "w", "*", "256", "/", "min", "(", "vp", ".", "w", ",", "vp", ".", "h", ")", "vp", ".", "h", "=", "vp", ".", "h", "*", "256", "/", "min", "(", "vp", ".", "w", ",", "vp", ".", "h", ")", "vis", ".", "setViewport", "(", "vp", ")", "vp", "=", "vis", ".", "getViewport", "(", ")", "plugin", "=", "_ThumbnailPlugin", "(", "world", ")", "if", "world", ":", "plugin", ".", "add", "(", "\"world\"", ",", "world", ")", "if", "value", "is", "not", "None", ":", "if", "type", "==", "'Config'", ":", "world", ".", "robot", "(", "0", ")", ".", "setConfig", "(", "value", ")", "else", ":", "plugin", ".", "add", "(", "\"item\"", ",", "value", ")", "plugin", ".", "autoFitCamera", "(", ")", "vis", ".", "setPlugin", "(", "plugin", ")", "vis", ".", "show", "(", ")", "plugin", ".", "rendered", "=", "0", "while", "not", "plugin", ".", "done", ":", "time", ".", "sleep", "(", "0.1", ")", "vis", ".", "setPlugin", "(", "None", ")", "vis", ".", "show", "(", "False", ")", "vis", ".", "setWindow", "(", "old_window", ")", "if", "(", "vp", ".", "w", ",", "vp", ".", "h", ")", "!=", "size", "and", "plugin", ".", "image", ".", "__class__", ".", "__name__", "==", "'Image'", ":", "try", ":", "from", "PIL", "import", "Image", "plugin", ".", "image", ".", "thumbnail", "(", "size", ",", "Image", ".", "ANTIALIAS", ")", "except", "ImportError", ":", "try", ":", "import", "Image", "plugin", ".", "image", ".", "thumbnail", "(", "size", ",", "Image", ".", "ANTIALIAS", ")", "except", "ImportError", ":", "# if this happens then", "# plugin.image is just a raw RGBA memory buffer", "pass", "return", "plugin", ".", "image" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/io/resource.py#L415-L497