nwo
stringlengths
5
86
sha
stringlengths
40
40
path
stringlengths
4
189
language
stringclasses
1 value
identifier
stringlengths
1
94
parameters
stringlengths
2
4.03k
argument_list
stringclasses
1 value
return_statement
stringlengths
0
11.5k
docstring
stringlengths
1
33.2k
docstring_summary
stringlengths
0
5.15k
docstring_tokens
list
function
stringlengths
34
151k
function_tokens
list
url
stringlengths
90
278
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/wsgiref/handlers.py
python
BaseHandler.result_is_file
(self)
return wrapper is not None and isinstance(self.result,wrapper)
True if 'self.result' is an instance of 'self.wsgi_file_wrapper
True if 'self.result' is an instance of 'self.wsgi_file_wrapper
[ "True", "if", "self", ".", "result", "is", "an", "instance", "of", "self", ".", "wsgi_file_wrapper" ]
def result_is_file(self): """True if 'self.result' is an instance of 'self.wsgi_file_wrapper'""" wrapper = self.wsgi_file_wrapper return wrapper is not None and isinstance(self.result,wrapper)
[ "def", "result_is_file", "(", "self", ")", ":", "wrapper", "=", "self", ".", "wsgi_file_wrapper", "return", "wrapper", "is", "not", "None", "and", "isinstance", "(", "self", ".", "result", ",", "wrapper", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/wsgiref/handlers.py#L274-L277
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
current/deps/v8/tools/stats-viewer.py
python
StatsViewer.MountSharedData
(self)
Mount the binary counters file as a memory-mapped file. If something goes wrong print an informative message and exit the program.
Mount the binary counters file as a memory-mapped file. If something goes wrong print an informative message and exit the program.
[ "Mount", "the", "binary", "counters", "file", "as", "a", "memory", "-", "mapped", "file", ".", "If", "something", "goes", "wrong", "print", "an", "informative", "message", "and", "exit", "the", "program", "." ]
def MountSharedData(self): """Mount the binary counters file as a memory-mapped file. If something goes wrong print an informative message and exit the program.""" if not os.path.exists(self.data_name): maps_name = "/proc/%s/maps" % self.data_name if not os.path.exists(maps_name): print("\"%s\" is neither a counter file nor a PID." % self.data_name) sys.exit(1) maps_file = open(maps_name, "r") try: self.data_name = None for m in re.finditer(r"/dev/shm/\S*", maps_file.read()): if os.path.exists(m.group(0)): self.data_name = m.group(0) break if self.data_name is None: print("Can't find counter file in maps for PID %s." % self.data_name) sys.exit(1) finally: maps_file.close() data_file = open(self.data_name, "r") size = os.fstat(data_file.fileno()).st_size fileno = data_file.fileno() self.shared_mmap = mmap.mmap(fileno, size, access=mmap.ACCESS_READ) data_access = SharedDataAccess(self.shared_mmap) if data_access.IntAt(0) == COUNTERS_FILE_MAGIC_NUMBER: return CounterCollection(data_access) elif data_access.IntAt(0) == CHROME_COUNTERS_FILE_MAGIC_NUMBER: return ChromeCounterCollection(data_access) print("File %s is not stats data." % self.data_name) sys.exit(1)
[ "def", "MountSharedData", "(", "self", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "self", ".", "data_name", ")", ":", "maps_name", "=", "\"/proc/%s/maps\"", "%", "self", ".", "data_name", "if", "not", "os", ".", "path", ".", "exists"...
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/current/deps/v8/tools/stats-viewer.py#L99-L130
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/numpy/py3/numpy/lib/recfunctions.py
python
_get_fieldspec
(dtype)
Produce a list of name/dtype pairs corresponding to the dtype fields Similar to dtype.descr, but the second item of each tuple is a dtype, not a string. As a result, this handles subarray dtypes Can be passed to the dtype constructor to reconstruct the dtype, noting that this (deliberately) discards field offsets. Examples -------- >>> dt = np.dtype([(('a', 'A'), np.int64), ('b', np.double, 3)]) >>> dt.descr [(('a', 'A'), '<i8'), ('b', '<f8', (3,))] >>> _get_fieldspec(dt) [(('a', 'A'), dtype('int64')), ('b', dtype(('<f8', (3,))))]
Produce a list of name/dtype pairs corresponding to the dtype fields
[ "Produce", "a", "list", "of", "name", "/", "dtype", "pairs", "corresponding", "to", "the", "dtype", "fields" ]
def _get_fieldspec(dtype): """ Produce a list of name/dtype pairs corresponding to the dtype fields Similar to dtype.descr, but the second item of each tuple is a dtype, not a string. As a result, this handles subarray dtypes Can be passed to the dtype constructor to reconstruct the dtype, noting that this (deliberately) discards field offsets. Examples -------- >>> dt = np.dtype([(('a', 'A'), np.int64), ('b', np.double, 3)]) >>> dt.descr [(('a', 'A'), '<i8'), ('b', '<f8', (3,))] >>> _get_fieldspec(dt) [(('a', 'A'), dtype('int64')), ('b', dtype(('<f8', (3,))))] """ if dtype.names is None: # .descr returns a nameless field, so we should too return [('', dtype)] else: fields = ((name, dtype.fields[name]) for name in dtype.names) # keep any titles, if present return [ (name if len(f) == 2 else (f[2], name), f[0]) for name, f in fields ]
[ "def", "_get_fieldspec", "(", "dtype", ")", ":", "if", "dtype", ".", "names", "is", "None", ":", "# .descr returns a nameless field, so we should too", "return", "[", "(", "''", ",", "dtype", ")", "]", "else", ":", "fields", "=", "(", "(", "name", ",", "dt...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py3/numpy/lib/recfunctions.py#L75-L103
okex/V3-Open-API-SDK
c5abb0db7e2287718e0055e17e57672ce0ec7fd9
okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/pkg_resources/__init__.py
python
Environment.scan
(self, search_path=None)
Scan `search_path` for distributions usable in this environment Any distributions found are added to the environment. `search_path` should be a sequence of ``sys.path`` items. If not supplied, ``sys.path`` is used. Only distributions conforming to the platform/python version defined at initialization are added.
Scan `search_path` for distributions usable in this environment
[ "Scan", "search_path", "for", "distributions", "usable", "in", "this", "environment" ]
def scan(self, search_path=None): """Scan `search_path` for distributions usable in this environment Any distributions found are added to the environment. `search_path` should be a sequence of ``sys.path`` items. If not supplied, ``sys.path`` is used. Only distributions conforming to the platform/python version defined at initialization are added. """ if search_path is None: search_path = sys.path for item in search_path: for dist in find_distributions(item): self.add(dist)
[ "def", "scan", "(", "self", ",", "search_path", "=", "None", ")", ":", "if", "search_path", "is", "None", ":", "search_path", "=", "sys", ".", "path", "for", "item", "in", "search_path", ":", "for", "dist", "in", "find_distributions", "(", "item", ")", ...
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/_vendor/pkg_resources/__init__.py#L1002-L1015
Constellation/iv
64c3a9c7c517063f29d90d449180ea8f6f4d946f
tools/cpplint.py
python
_CppLintState.SetVerboseLevel
(self, level)
return last_verbose_level
Sets the module's verbosity, and returns the previous setting.
Sets the module's verbosity, and returns the previous setting.
[ "Sets", "the", "module", "s", "verbosity", "and", "returns", "the", "previous", "setting", "." ]
def SetVerboseLevel(self, level): """Sets the module's verbosity, and returns the previous setting.""" last_verbose_level = self.verbose_level self.verbose_level = level return last_verbose_level
[ "def", "SetVerboseLevel", "(", "self", ",", "level", ")", ":", "last_verbose_level", "=", "self", ".", "verbose_level", "self", ".", "verbose_level", "=", "level", "return", "last_verbose_level" ]
https://github.com/Constellation/iv/blob/64c3a9c7c517063f29d90d449180ea8f6f4d946f/tools/cpplint.py#L695-L699
google/nucleus
68d3947fafba1337f294c0668a6e1c7f3f1273e3
nucleus/util/utils.py
python
reservoir_sample
(iterable, k, random=None)
return sample
Samples k elements with uniform probability from an iterable. Selects a subset of k elements from n input elements with uniform probability without needing to hold all n elements in memory at the same time. This implementation has max space complexity O(min(k, n)), i.e., we allocate up to min(k, n) elements to store the samples. This means that we only use ~n elements when n is smaller than k, which can be important when k is large. If n elements are added to this sampler, and n <= k, all n elements will be retained. If n > k, each added element will be retained with a uniform probability of k / n. The order of the k retained samples from our n elements is undefined. In particular that means that the elements in the returned list can occur in a different order than they appeared in the iterable. More details about reservoir sampling (and the specific algorithm used here called Algorithm R) can be found on wikipedia: https://en.wikipedia.org/wiki/Reservoir_sampling#Algorithm_R Args: iterable: Python iterable. The iterable to sample from. k: int. The number of elements to sample. random: A random number generator or None. Returns: A list containing the k sampled elements. Raises: ValueError: If k is negative.
Samples k elements with uniform probability from an iterable.
[ "Samples", "k", "elements", "with", "uniform", "probability", "from", "an", "iterable", "." ]
def reservoir_sample(iterable, k, random=None): """Samples k elements with uniform probability from an iterable. Selects a subset of k elements from n input elements with uniform probability without needing to hold all n elements in memory at the same time. This implementation has max space complexity O(min(k, n)), i.e., we allocate up to min(k, n) elements to store the samples. This means that we only use ~n elements when n is smaller than k, which can be important when k is large. If n elements are added to this sampler, and n <= k, all n elements will be retained. If n > k, each added element will be retained with a uniform probability of k / n. The order of the k retained samples from our n elements is undefined. In particular that means that the elements in the returned list can occur in a different order than they appeared in the iterable. More details about reservoir sampling (and the specific algorithm used here called Algorithm R) can be found on wikipedia: https://en.wikipedia.org/wiki/Reservoir_sampling#Algorithm_R Args: iterable: Python iterable. The iterable to sample from. k: int. The number of elements to sample. random: A random number generator or None. Returns: A list containing the k sampled elements. Raises: ValueError: If k is negative. """ if k < 0: raise ValueError('k must be nonnegative, but got {}'.format(k)) if random is None: random = np.random sample = [] for i, item in enumerate(iterable): if len(sample) < k: sample.append(item) else: j = random.randint(0, i + 1) if j < k: sample[j] = item return sample
[ "def", "reservoir_sample", "(", "iterable", ",", "k", ",", "random", "=", "None", ")", ":", "if", "k", "<", "0", ":", "raise", "ValueError", "(", "'k must be nonnegative, but got {}'", ".", "format", "(", "k", ")", ")", "if", "random", "is", "None", ":",...
https://github.com/google/nucleus/blob/68d3947fafba1337f294c0668a6e1c7f3f1273e3/nucleus/util/utils.py#L65-L109
BitMEX/api-connectors
37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812
auto-generated/python/swagger_client/models/position.py
python
Position.symbol
(self, symbol)
Sets the symbol of this Position. :param symbol: The symbol of this Position. # noqa: E501 :type: str
Sets the symbol of this Position.
[ "Sets", "the", "symbol", "of", "this", "Position", "." ]
def symbol(self, symbol): """Sets the symbol of this Position. :param symbol: The symbol of this Position. # noqa: E501 :type: str """ if symbol is None: raise ValueError("Invalid value for `symbol`, must not be `None`") # noqa: E501 self._symbol = symbol
[ "def", "symbol", "(", "self", ",", "symbol", ")", ":", "if", "symbol", "is", "None", ":", "raise", "ValueError", "(", "\"Invalid value for `symbol`, must not be `None`\"", ")", "# noqa: E501", "self", ".", "_symbol", "=", "symbol" ]
https://github.com/BitMEX/api-connectors/blob/37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812/auto-generated/python/swagger_client/models/position.py#L531-L541
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/fitting_widgets/tf_asymmetry_fitting/tf_asymmetry_fitting_view.py
python
TFAsymmetryFittingView.__init__
(self, parent: QWidget = None)
Initializes the TFAsymmetryFittingView, and adds the TFAsymmetryFittingOptionsView widget.
Initializes the TFAsymmetryFittingView, and adds the TFAsymmetryFittingOptionsView widget.
[ "Initializes", "the", "TFAsymmetryFittingView", "and", "adds", "the", "TFAsymmetryFittingOptionsView", "widget", "." ]
def __init__(self, parent: QWidget = None): """Initializes the TFAsymmetryFittingView, and adds the TFAsymmetryFittingOptionsView widget.""" super(TFAsymmetryFittingView, self).__init__(parent) self.tf_asymmetry_mode_switcher = TFAsymmetryModeSwitcherView(self) self.tf_asymmetry_mode_switcher_layout.addWidget(self.tf_asymmetry_mode_switcher) self.tf_asymmetry_fitting_options = TFAsymmetryFittingOptionsView(self) self.tf_asymmetry_fitting_options_layout.addWidget(self.tf_asymmetry_fitting_options) self.tf_asymmetry_mode = False
[ "def", "__init__", "(", "self", ",", "parent", ":", "QWidget", "=", "None", ")", ":", "super", "(", "TFAsymmetryFittingView", ",", "self", ")", ".", "__init__", "(", "parent", ")", "self", ".", "tf_asymmetry_mode_switcher", "=", "TFAsymmetryModeSwitcherView", ...
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/fitting_widgets/tf_asymmetry_fitting/tf_asymmetry_fitting_view.py#L22-L32
asLody/whale
6a661b27cc4cf83b7b5a3b02451597ee1ac7f264
whale/cpplint.py
python
_OutputFormat
()
return _cpplint_state.output_format
Gets the module's output format.
Gets the module's output format.
[ "Gets", "the", "module", "s", "output", "format", "." ]
def _OutputFormat(): """Gets the module's output format.""" return _cpplint_state.output_format
[ "def", "_OutputFormat", "(", ")", ":", "return", "_cpplint_state", ".", "output_format" ]
https://github.com/asLody/whale/blob/6a661b27cc4cf83b7b5a3b02451597ee1ac7f264/whale/cpplint.py#L963-L965
cms-sw/cmssw
fd9de012d503d3405420bcbeec0ec879baa57cf2
FWCore/ParameterSet/python/Types.py
python
makeCppPSet
(module,cppPSetMaker)
return cppPSetMaker
Extracts all PSets from the module and makes C++ equivalent
Extracts all PSets from the module and makes C++ equivalent
[ "Extracts", "all", "PSets", "from", "the", "module", "and", "makes", "C", "++", "equivalent" ]
def makeCppPSet(module,cppPSetMaker): """Extracts all PSets from the module and makes C++ equivalent """ # if this isn't a dictionary, treat it as an object which holds PSets if not isinstance(module,dict): module = dict( ( (x,getattr(module,x)) for x in dir(module)) ) for x,p in module.items(): if isinstance(p,PSet): p.insertInto(cppPSetMaker,x) return cppPSetMaker
[ "def", "makeCppPSet", "(", "module", ",", "cppPSetMaker", ")", ":", "# if this isn't a dictionary, treat it as an object which holds PSets", "if", "not", "isinstance", "(", "module", ",", "dict", ")", ":", "module", "=", "dict", "(", "(", "(", "x", ",", "getattr",...
https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/FWCore/ParameterSet/python/Types.py#L1236-L1246
oracle/graaljs
36a56e8e993d45fc40939a3a4d9c0c24990720f1
graal-nodejs/tools/cpplint.py
python
_FunctionState.Count
(self)
Count line in current function body.
Count line in current function body.
[ "Count", "line", "in", "current", "function", "body", "." ]
def Count(self): """Count line in current function body.""" if self.in_a_function: self.lines_in_function += 1
[ "def", "Count", "(", "self", ")", ":", "if", "self", ".", "in_a_function", ":", "self", ".", "lines_in_function", "+=", "1" ]
https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/tools/cpplint.py#L1520-L1523
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/devil/devil/android/battery_utils.py
python
BatteryUtils.SetCharging
(self, enabled, timeout=None, retries=None)
Enables or disables charging on the device. Args: enabled: A boolean indicating whether charging should be enabled or disabled. timeout: timeout in seconds retries: number of retries
Enables or disables charging on the device.
[ "Enables", "or", "disables", "charging", "on", "the", "device", "." ]
def SetCharging(self, enabled, timeout=None, retries=None): """Enables or disables charging on the device. Args: enabled: A boolean indicating whether charging should be enabled or disabled. timeout: timeout in seconds retries: number of retries """ if self.GetCharging() == enabled: logging.warning('Device charging already in expected state: %s', enabled) return self._DiscoverDeviceProfile() if enabled: if self._cache['profile']['enable_command']: self._HardwareSetCharging(enabled) else: logging.info('Unable to enable charging via hardware. ' 'Falling back to software enabling.') self.EnableBatteryUpdates() else: if self._cache['profile']['enable_command']: self._ClearPowerData() self._HardwareSetCharging(enabled) else: logging.info('Unable to disable charging via hardware. ' 'Falling back to software disabling.') self.DisableBatteryUpdates()
[ "def", "SetCharging", "(", "self", ",", "enabled", ",", "timeout", "=", "None", ",", "retries", "=", "None", ")", ":", "if", "self", ".", "GetCharging", "(", ")", "==", "enabled", ":", "logging", ".", "warning", "(", "'Device charging already in expected sta...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/devil/devil/android/battery_utils.py#L518-L546
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/python2_version/klampt/robotsim.py
python
RobotModelLink.getParentTransform
(self)
return _robotsim.RobotModelLink_getParentTransform(self)
getParentTransform(RobotModelLink self) Gets transformation (R,t) to the parent link. Returns: (se3 object): a pair (R,t), with R a 9-list and t a 3-list of floats, giving the local transform from this link to its parent, in the reference (zero) configuration.
getParentTransform(RobotModelLink self)
[ "getParentTransform", "(", "RobotModelLink", "self", ")" ]
def getParentTransform(self): """ getParentTransform(RobotModelLink self) Gets transformation (R,t) to the parent link. Returns: (se3 object): a pair (R,t), with R a 9-list and t a 3-list of floats, giving the local transform from this link to its parent, in the reference (zero) configuration. """ return _robotsim.RobotModelLink_getParentTransform(self)
[ "def", "getParentTransform", "(", "self", ")", ":", "return", "_robotsim", ".", "RobotModelLink_getParentTransform", "(", "self", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/robotsim.py#L3821-L3836
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/decimal.py
python
Decimal.number_class
(self, context=None)
Returns an indication of the class of self. The class is one of the following strings: sNaN NaN -Infinity -Normal -Subnormal -Zero +Zero +Subnormal +Normal +Infinity
Returns an indication of the class of self.
[ "Returns", "an", "indication", "of", "the", "class", "of", "self", "." ]
def number_class(self, context=None): """Returns an indication of the class of self. The class is one of the following strings: sNaN NaN -Infinity -Normal -Subnormal -Zero +Zero +Subnormal +Normal +Infinity """ if self.is_snan(): return "sNaN" if self.is_qnan(): return "NaN" inf = self._isinfinity() if inf == 1: return "+Infinity" if inf == -1: return "-Infinity" if self.is_zero(): if self._sign: return "-Zero" else: return "+Zero" if context is None: context = getcontext() if self.is_subnormal(context=context): if self._sign: return "-Subnormal" else: return "+Subnormal" # just a normal, regular, boring number, :) if self._sign: return "-Normal" else: return "+Normal"
[ "def", "number_class", "(", "self", ",", "context", "=", "None", ")", ":", "if", "self", ".", "is_snan", "(", ")", ":", "return", "\"sNaN\"", "if", "self", ".", "is_qnan", "(", ")", ":", "return", "\"NaN\"", "inf", "=", "self", ".", "_isinfinity", "(...
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/decimal.py#L3330-L3370
NicknineTheEagle/TF2-Base
20459c5a7fbc995b6bf54fa85c2f62a101e9fb64
src/thirdparty/protobuf-2.3.0/python/google/protobuf/internal/decoder.py
python
_EndGroup
(buffer, pos, end)
return -1
Skipping an END_GROUP tag returns -1 to tell the parent loop to break.
Skipping an END_GROUP tag returns -1 to tell the parent loop to break.
[ "Skipping", "an", "END_GROUP", "tag", "returns", "-", "1", "to", "tell", "the", "parent", "loop", "to", "break", "." ]
def _EndGroup(buffer, pos, end): """Skipping an END_GROUP tag returns -1 to tell the parent loop to break.""" return -1
[ "def", "_EndGroup", "(", "buffer", ",", "pos", ",", "end", ")", ":", "return", "-", "1" ]
https://github.com/NicknineTheEagle/TF2-Base/blob/20459c5a7fbc995b6bf54fa85c2f62a101e9fb64/src/thirdparty/protobuf-2.3.0/python/google/protobuf/internal/decoder.py#L590-L593
bundy-dns/bundy
3d41934996b82b0cd2fe22dd74d2abc1daba835d
src/bin/bundyctl/bindcmd.py
python
BindCmdInterpreter._try_login
(self, username, password)
Attempts to log into cmdctl by sending a POST with the given username and password. On success of the POST (not the login, but the network operation), it returns a tuple (response, data). We check for some failures such as SSL errors and socket errors which could happen due to the environment in which BUNDY runs. On failure, it raises a FailToLogin exception and prints some information on the failure. This call is essentially 'private', but made 'protected' for easier testing.
Attempts to log into cmdctl by sending a POST with the given username and password. On success of the POST (not the login, but the network operation), it returns a tuple (response, data). We check for some failures such as SSL errors and socket errors which could happen due to the environment in which BUNDY runs. On failure, it raises a FailToLogin exception and prints some information on the failure. This call is essentially 'private', but made 'protected' for easier testing.
[ "Attempts", "to", "log", "into", "cmdctl", "by", "sending", "a", "POST", "with", "the", "given", "username", "and", "password", ".", "On", "success", "of", "the", "POST", "(", "not", "the", "login", "but", "the", "network", "operation", ")", "it", "retur...
def _try_login(self, username, password): ''' Attempts to log into cmdctl by sending a POST with the given username and password. On success of the POST (not the login, but the network operation), it returns a tuple (response, data). We check for some failures such as SSL errors and socket errors which could happen due to the environment in which BUNDY runs. On failure, it raises a FailToLogin exception and prints some information on the failure. This call is essentially 'private', but made 'protected' for easier testing. ''' param = {'username': username, 'password' : password} try: response = self.send_POST('/login', param) data = response.read().decode() # return here (will raise error after try block) return (response, data) except (ssl.SSLError, socket.error) as err: self._print('Error while sending login information:', err) pass raise FailToLogin()
[ "def", "_try_login", "(", "self", ",", "username", ",", "password", ")", ":", "param", "=", "{", "'username'", ":", "username", ",", "'password'", ":", "password", "}", "try", ":", "response", "=", "self", ".", "send_POST", "(", "'/login'", ",", "param",...
https://github.com/bundy-dns/bundy/blob/3d41934996b82b0cd2fe22dd74d2abc1daba835d/src/bin/bundyctl/bindcmd.py#L218-L238
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/ribbon/page.py
python
RibbonPage.DoGetBestSize
(self)
return best
Gets the size which best suits the window: for a control, it would be the minimal size which doesn't truncate the control, for a panel - the same size as it would have after a call to `Fit()`. :return: An instance of :class:`Size`. :note: Overridden from :class:`PyControl`.
Gets the size which best suits the window: for a control, it would be the minimal size which doesn't truncate the control, for a panel - the same size as it would have after a call to `Fit()`.
[ "Gets", "the", "size", "which", "best", "suits", "the", "window", ":", "for", "a", "control", "it", "would", "be", "the", "minimal", "size", "which", "doesn", "t", "truncate", "the", "control", "for", "a", "panel", "-", "the", "same", "size", "as", "it...
def DoGetBestSize(self): """ Gets the size which best suits the window: for a control, it would be the minimal size which doesn't truncate the control, for a panel - the same size as it would have after a call to `Fit()`. :return: An instance of :class:`Size`. :note: Overridden from :class:`PyControl`. """ best = wx.Size(0, 0) count = 0 if self.GetMajorAxis() == wx.HORIZONTAL: best.y = -1 for child in self.GetChildren(): child_best = child.GetBestSize() if child_best.x != -1: best.IncBy(child_best.x, 0) best.y = max(best.y, child_best.y) count += 1 if count > 1: best.IncBy((count - 1) * self._art.GetMetric(RIBBON_ART_PANEL_X_SEPARATION_SIZE), 0) else: best.x = -1 for child in self.GetChildren(): child_best = child.GetBestSize() best.x = max(best.x, child_best.x) if child_best.y != -1: best.IncBy(0, child_best.y) count += 1 if count > 1: best.IncBy(0, (count - 1) * self._art.GetMetric(RIBBON_ART_PANEL_Y_SEPARATION_SIZE)) if best.x != -1: best.x += self._art.GetMetric(RIBBON_ART_PAGE_BORDER_LEFT_SIZE) + self._art.GetMetric(RIBBON_ART_PAGE_BORDER_RIGHT_SIZE) if best.y != -1: best.y += self._art.GetMetric(RIBBON_ART_PAGE_BORDER_TOP_SIZE) + self._art.GetMetric(RIBBON_ART_PAGE_BORDER_BOTTOM_SIZE) return best
[ "def", "DoGetBestSize", "(", "self", ")", ":", "best", "=", "wx", ".", "Size", "(", "0", ",", "0", ")", "count", "=", "0", "if", "self", ".", "GetMajorAxis", "(", ")", "==", "wx", ".", "HORIZONTAL", ":", "best", ".", "y", "=", "-", "1", "for", ...
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/ribbon/page.py#L875-L924
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/ftplib.py
python
FTP.cwd
(self, dirname)
return self.voidcmd(cmd)
Change to a directory.
Change to a directory.
[ "Change", "to", "a", "directory", "." ]
def cwd(self, dirname): '''Change to a directory.''' if dirname == '..': try: return self.voidcmd('CDUP') except error_perm as msg: if msg.args[0][:3] != '500': raise elif dirname == '': dirname = '.' # does nothing, but could return error cmd = 'CWD ' + dirname return self.voidcmd(cmd)
[ "def", "cwd", "(", "self", ",", "dirname", ")", ":", "if", "dirname", "==", "'..'", ":", "try", ":", "return", "self", ".", "voidcmd", "(", "'CDUP'", ")", "except", "error_perm", "as", "msg", ":", "if", "msg", ".", "args", "[", "0", "]", "[", ":"...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/ftplib.py#L620-L631
openvinotoolkit/openvino
dedcbeafa8b84cccdc55ca64b8da516682b381c7
tools/mo/openvino/tools/mo/graph/graph.py
python
Node.copy_node
(self, new_attrs: dict = None, dst_graph=None)
return Node(dst_graph, new_id)
Copies node with all attributes (optionally updated) within the same graph or to different graph.
Copies node with all attributes (optionally updated) within the same graph or to different graph.
[ "Copies", "node", "with", "all", "attributes", "(", "optionally", "updated", ")", "within", "the", "same", "graph", "or", "to", "different", "graph", "." ]
def copy_node(self, new_attrs: dict = None, dst_graph=None): ''' Copies node with all attributes (optionally updated) within the same graph or to different graph.''' if new_attrs is None: new_attrs = {} if dst_graph is None: dst_graph = self.graph attrs = deepcopy(self.attrs()) new_id = dst_graph.unique_id(attrs['name']) if 'name' in attrs else dst_graph.unique_id() attrs['name'] = new_id attrs.update(new_attrs) dst_graph.add_node(new_id, **attrs) return Node(dst_graph, new_id)
[ "def", "copy_node", "(", "self", ",", "new_attrs", ":", "dict", "=", "None", ",", "dst_graph", "=", "None", ")", ":", "if", "new_attrs", "is", "None", ":", "new_attrs", "=", "{", "}", "if", "dst_graph", "is", "None", ":", "dst_graph", "=", "self", "....
https://github.com/openvinotoolkit/openvino/blob/dedcbeafa8b84cccdc55ca64b8da516682b381c7/tools/mo/openvino/tools/mo/graph/graph.py#L307-L319
perilouswithadollarsign/cstrike15_src
f82112a2388b841d72cb62ca48ab1846dfcc11c8
thirdparty/protobuf-2.5.0/python/google/protobuf/internal/enum_type_wrapper.py
python
EnumTypeWrapper.values
(self)
return [value_descriptor.number for value_descriptor in self._enum_type.values]
Return a list of the integer values in the enum. These are returned in the order they were defined in the .proto file.
Return a list of the integer values in the enum.
[ "Return", "a", "list", "of", "the", "integer", "values", "in", "the", "enum", "." ]
def values(self): """Return a list of the integer values in the enum. These are returned in the order they were defined in the .proto file. """ return [value_descriptor.number for value_descriptor in self._enum_type.values]
[ "def", "values", "(", "self", ")", ":", "return", "[", "value_descriptor", ".", "number", "for", "value_descriptor", "in", "self", ".", "_enum_type", ".", "values", "]" ]
https://github.com/perilouswithadollarsign/cstrike15_src/blob/f82112a2388b841d72cb62ca48ab1846dfcc11c8/thirdparty/protobuf-2.5.0/python/google/protobuf/internal/enum_type_wrapper.py#L74-L81
weolar/miniblink49
1c4678db0594a4abde23d3ebbcc7cd13c3170777
tools/idl_parser/idl_parser.py
python
Boolean
(val)
return False
Convert to strict boolean type.
Convert to strict boolean type.
[ "Convert", "to", "strict", "boolean", "type", "." ]
def Boolean(val): """Convert to strict boolean type.""" if val: return True return False
[ "def", "Boolean", "(", "val", ")", ":", "if", "val", ":", "return", "True", "return", "False" ]
https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/tools/idl_parser/idl_parser.py#L73-L77
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/python/util/tf_should_use.py
python
must_use_result_or_fatal
(fn)
return tf_decorator.make_decorator( fn, wrapped, 'must_use_result_or_fatal', ((fn.__doc__ or '') + ('\n\n ' '**NOTE** The output of this function must be used. If it is not, ' 'a fatal error will be raised. To mark the output as used, ' 'call its .mark_used() method.')))
Function wrapper that ensures the function's output is used. If the output is not used, a `tf.logging.fatal` error is raised. An output is marked as used if any of its attributes are read, modified, or updated. Examples when the output is a `Tensor` include: - Using it in any capacity (e.g. `y = t + 0`, `sess.run(t)`) - Accessing a property (e.g. getting `t.name` or `t.op`). Note, certain behaviors cannot be tracked - for these the object may not be marked as used. Examples include: - `t != 0`. In this case, comparison is done on types / ids. - `isinstance(t, tf.Tensor)`. Similar to above. Args: fn: The function to wrap. Returns: The wrapped function.
Function wrapper that ensures the function's output is used.
[ "Function", "wrapper", "that", "ensures", "the", "function", "s", "output", "is", "used", "." ]
def must_use_result_or_fatal(fn): """Function wrapper that ensures the function's output is used. If the output is not used, a `tf.logging.fatal` error is raised. An output is marked as used if any of its attributes are read, modified, or updated. Examples when the output is a `Tensor` include: - Using it in any capacity (e.g. `y = t + 0`, `sess.run(t)`) - Accessing a property (e.g. getting `t.name` or `t.op`). Note, certain behaviors cannot be tracked - for these the object may not be marked as used. Examples include: - `t != 0`. In this case, comparison is done on types / ids. - `isinstance(t, tf.Tensor)`. Similar to above. Args: fn: The function to wrap. Returns: The wrapped function. """ def wrapped(*args, **kwargs): return _add_should_use_warning(fn(*args, **kwargs), fatal_error=True) return tf_decorator.make_decorator( fn, wrapped, 'must_use_result_or_fatal', ((fn.__doc__ or '') + ('\n\n ' '**NOTE** The output of this function must be used. If it is not, ' 'a fatal error will be raised. To mark the output as used, ' 'call its .mark_used() method.')))
[ "def", "must_use_result_or_fatal", "(", "fn", ")", ":", "def", "wrapped", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_add_should_use_warning", "(", "fn", "(", "*", "args", ",", "*", "*", "kwargs", ")", ",", "fatal_error", "=", "Tru...
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/util/tf_should_use.py#L185-L216
wujian16/Cornell-MOE
df299d1be882d2af9796d7a68b3f9505cac7a53e
moe/optimal_learning/python/cpp_wrappers/gaussian_process.py
python
GaussianProcess.compute_grad_cholesky_variance_of_points
(self, points_to_sample, num_derivatives=-1)
return cpp_utils.uncppify(grad_chol_decomp, (num_derivatives, num_to_sample*(1 + self._num_derivatives), num_to_sample*(1 + self._num_derivatives), self.dim))
r"""Compute the gradient of the cholesky factorization of the variance (matrix) of this GP at each point of ``Xs`` (``points_to_sample``) wrt ``Xs``. ``points_to_sample`` may not contain duplicate points. Violating this results in singular covariance matrices. This function accounts for the effect on the gradient resulting from cholesky-factoring the variance matrix. See Smith 1995 for algorithm details. Note that ``grad_chol`` is nominally sized: ``grad_chol[num_to_sample][num_to_sample][num_to_sample][dim]``. Let this be indexed ``grad_chol[k][j][i][d]``, which is read the derivative of ``var[j][i]`` with respect to ``x_{k,d}`` (x = ``points_to_sample``) .. Note:: Comments are copied from :mod:`moe.optimal_learning.python.interfaces.gaussian_process_interface.GaussianProcessInterface.compute_grad_cholesky_variance_of_points` :param points_to_sample: num_to_sample points (in dim dimensions) being sampled from the GP :type points_to_sample: array of float64 with shape (num_to_sample, dim) :param num_derivatives: return derivatives wrt points_to_sample[0:num_derivatives]; large or negative values are clamped :type num_derivatives: int :return: grad_chol: gradient of the cholesky factorization of the variance matrix of this GP. ``grad_chol[k][j][i][d]`` is actually the gradients of ``var_{j,i}`` with respect to ``x_{k,d}``, the d-th dimension of the k-th entry of ``points_to_sample`` :rtype: array of float64 with shape (num_derivatives, num_to_sample, num_to_sample, dim)
r"""Compute the gradient of the cholesky factorization of the variance (matrix) of this GP at each point of ``Xs`` (``points_to_sample``) wrt ``Xs``.
[ "r", "Compute", "the", "gradient", "of", "the", "cholesky", "factorization", "of", "the", "variance", "(", "matrix", ")", "of", "this", "GP", "at", "each", "point", "of", "Xs", "(", "points_to_sample", ")", "wrt", "Xs", "." ]
def compute_grad_cholesky_variance_of_points(self, points_to_sample, num_derivatives=-1): r"""Compute the gradient of the cholesky factorization of the variance (matrix) of this GP at each point of ``Xs`` (``points_to_sample``) wrt ``Xs``. ``points_to_sample`` may not contain duplicate points. Violating this results in singular covariance matrices. This function accounts for the effect on the gradient resulting from cholesky-factoring the variance matrix. See Smith 1995 for algorithm details. Note that ``grad_chol`` is nominally sized: ``grad_chol[num_to_sample][num_to_sample][num_to_sample][dim]``. Let this be indexed ``grad_chol[k][j][i][d]``, which is read the derivative of ``var[j][i]`` with respect to ``x_{k,d}`` (x = ``points_to_sample``) .. Note:: Comments are copied from :mod:`moe.optimal_learning.python.interfaces.gaussian_process_interface.GaussianProcessInterface.compute_grad_cholesky_variance_of_points` :param points_to_sample: num_to_sample points (in dim dimensions) being sampled from the GP :type points_to_sample: array of float64 with shape (num_to_sample, dim) :param num_derivatives: return derivatives wrt points_to_sample[0:num_derivatives]; large or negative values are clamped :type num_derivatives: int :return: grad_chol: gradient of the cholesky factorization of the variance matrix of this GP. ``grad_chol[k][j][i][d]`` is actually the gradients of ``var_{j,i}`` with respect to ``x_{k,d}``, the d-th dimension of the k-th entry of ``points_to_sample`` :rtype: array of float64 with shape (num_derivatives, num_to_sample, num_to_sample, dim) """ num_derivatives = self._clamp_num_derivatives(points_to_sample.shape[0], num_derivatives) num_to_sample = points_to_sample.shape[0] grad_chol_decomp = self._gaussian_process.compute_grad_cholesky_variance_of_points( cpp_utils.cppify(points_to_sample), num_to_sample, num_derivatives, ) return cpp_utils.uncppify(grad_chol_decomp, (num_derivatives, num_to_sample*(1 + self._num_derivatives), num_to_sample*(1 + self._num_derivatives), self.dim))
[ "def", "compute_grad_cholesky_variance_of_points", "(", "self", ",", "points_to_sample", ",", "num_derivatives", "=", "-", "1", ")", ":", "num_derivatives", "=", "self", ".", "_clamp_num_derivatives", "(", "points_to_sample", ".", "shape", "[", "0", "]", ",", "num...
https://github.com/wujian16/Cornell-MOE/blob/df299d1be882d2af9796d7a68b3f9505cac7a53e/moe/optimal_learning/python/cpp_wrappers/gaussian_process.py#L282-L316
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_gdi.py
python
Pen.SetColour
(*args, **kwargs)
return _gdi_.Pen_SetColour(*args, **kwargs)
SetColour(self, Colour colour)
SetColour(self, Colour colour)
[ "SetColour", "(", "self", "Colour", "colour", ")" ]
def SetColour(*args, **kwargs): """SetColour(self, Colour colour)""" return _gdi_.Pen_SetColour(*args, **kwargs)
[ "def", "SetColour", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gdi_", ".", "Pen_SetColour", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_gdi.py#L429-L431
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_windows.py
python
MessageDialog.SetOKLabel
(*args, **kwargs)
return _windows_.MessageDialog_SetOKLabel(*args, **kwargs)
SetOKLabel(self, String ok) -> bool
SetOKLabel(self, String ok) -> bool
[ "SetOKLabel", "(", "self", "String", "ok", ")", "-", ">", "bool" ]
def SetOKLabel(*args, **kwargs): """SetOKLabel(self, String ok) -> bool""" return _windows_.MessageDialog_SetOKLabel(*args, **kwargs)
[ "def", "SetOKLabel", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_windows_", ".", "MessageDialog_SetOKLabel", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_windows.py#L3642-L3644
Tencent/mars
54969ba56b402a622db123e780a4f760b38c5c36
mars/lint/cpplint.py
python
IsBlankLine
(line)
return not line or line.isspace()
Returns true if the given line is blank. We consider a line to be blank if the line is empty or consists of only white spaces. Args: line: A line of a string. Returns: True, if the given line is blank.
Returns true if the given line is blank.
[ "Returns", "true", "if", "the", "given", "line", "is", "blank", "." ]
def IsBlankLine(line): """Returns true if the given line is blank. We consider a line to be blank if the line is empty or consists of only white spaces. Args: line: A line of a string. Returns: True, if the given line is blank. """ return not line or line.isspace()
[ "def", "IsBlankLine", "(", "line", ")", ":", "return", "not", "line", "or", "line", ".", "isspace", "(", ")" ]
https://github.com/Tencent/mars/blob/54969ba56b402a622db123e780a4f760b38c5c36/mars/lint/cpplint.py#L2818-L2830
macchina-io/macchina.io
ef24ba0e18379c3dd48fb84e6dbf991101cb8db0
platform/JS/V8/v8/third_party/markupsafe/_native.py
python
soft_unicode
(s)
return s
Make a string unicode if it isn't already. That way a markup string is not converted back to unicode.
Make a string unicode if it isn't already. That way a markup string is not converted back to unicode.
[ "Make", "a", "string", "unicode", "if", "it", "isn", "t", "already", ".", "That", "way", "a", "markup", "string", "is", "not", "converted", "back", "to", "unicode", "." ]
def soft_unicode(s): """Make a string unicode if it isn't already. That way a markup string is not converted back to unicode. """ if not isinstance(s, text_type): s = text_type(s) return s
[ "def", "soft_unicode", "(", "s", ")", ":", "if", "not", "isinstance", "(", "s", ",", "text_type", ")", ":", "s", "=", "text_type", "(", "s", ")", "return", "s" ]
https://github.com/macchina-io/macchina.io/blob/ef24ba0e18379c3dd48fb84e6dbf991101cb8db0/platform/JS/V8/v8/third_party/markupsafe/_native.py#L40-L46
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
src/external/coremltools_wrap/coremltools/coremltools/models/neural_network/builder.py
python
NeuralNetworkBuilder.add_resize_bilinear
( self, name, input_name, output_name, target_height=1, target_width=1, mode="ALIGN_ENDPOINTS_MODE", )
return spec_layer
Add a resize bilinear layer to the model. A layer that resize the input to a given spatial size using bilinear interpolation. Refer to the **ResizeBilinearLayerParams** message in specification (NeuralNetwork.proto) for more details. Parameters ---------- name: str The name of this layer. input_name: str The input blob name of this layer. output_name: str The output blob name of this layer. target_height: int Output height dimension. target_width: int Output width dimension. mode: str Following values are supported: 'STRICT_ALIGN_ENDPOINTS_MODE', 'ALIGN_ENDPOINTS_MODE', 'UPSAMPLE_MODE', 'ROI_ALIGN_MODE'. This parameter determines the sampling grid used for bilinear interpolation. See Also -------- add_upsample
Add a resize bilinear layer to the model. A layer that resize the input to a given spatial size using bilinear interpolation. Refer to the **ResizeBilinearLayerParams** message in specification (NeuralNetwork.proto) for more details.
[ "Add", "a", "resize", "bilinear", "layer", "to", "the", "model", ".", "A", "layer", "that", "resize", "the", "input", "to", "a", "given", "spatial", "size", "using", "bilinear", "interpolation", ".", "Refer", "to", "the", "**", "ResizeBilinearLayerParams", "...
def add_resize_bilinear( self, name, input_name, output_name, target_height=1, target_width=1, mode="ALIGN_ENDPOINTS_MODE", ): """ Add a resize bilinear layer to the model. A layer that resize the input to a given spatial size using bilinear interpolation. Refer to the **ResizeBilinearLayerParams** message in specification (NeuralNetwork.proto) for more details. Parameters ---------- name: str The name of this layer. input_name: str The input blob name of this layer. output_name: str The output blob name of this layer. target_height: int Output height dimension. target_width: int Output width dimension. mode: str Following values are supported: 'STRICT_ALIGN_ENDPOINTS_MODE', 'ALIGN_ENDPOINTS_MODE', 'UPSAMPLE_MODE', 'ROI_ALIGN_MODE'. This parameter determines the sampling grid used for bilinear interpolation. See Also -------- add_upsample """ spec_layer = self._add_generic_layer(name, [input_name], [output_name]) spec_layer_params = spec_layer.resizeBilinear spec_layer_params.targetSize.append(target_height) spec_layer_params.targetSize.append(target_width) mode = mode.upper() if isinstance(mode, _string_types) else mode if mode == "ALIGN_ENDPOINTS_MODE": spec_layer_params.mode.samplingMethod = _NeuralNetwork_pb2.SamplingMode.Method.Value( "ALIGN_ENDPOINTS_MODE" ) elif mode == "STRICT_ALIGN_ENDPOINTS_MODE": spec_layer_params.mode.samplingMethod = _NeuralNetwork_pb2.SamplingMode.Method.Value( "STRICT_ALIGN_ENDPOINTS_MODE" ) elif mode == "UPSAMPLE_MODE": spec_layer_params.mode.samplingMethod = _NeuralNetwork_pb2.SamplingMode.Method.Value( "UPSAMPLE_MODE" ) elif mode == "ROI_ALIGN_MODE": spec_layer_params.mode.samplingMethod = _NeuralNetwork_pb2.SamplingMode.Method.Value( "ROI_ALIGN_MODE" ) else: raise ValueError("Unsupported resize bilinear mode %s" % mode) return spec_layer
[ "def", "add_resize_bilinear", "(", "self", ",", "name", ",", "input_name", ",", "output_name", ",", "target_height", "=", "1", ",", "target_width", "=", "1", ",", "mode", "=", "\"ALIGN_ENDPOINTS_MODE\"", ",", ")", ":", "spec_layer", "=", "self", ".", "_add_g...
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/external/coremltools_wrap/coremltools/coremltools/models/neural_network/builder.py#L4152-L4209
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/extern/aui/auibook.py
python
AuiNotebook.AssignImageList
(self, imageList)
Sets the image list for the :class:`AuiNotebook` control. :param `imageList`: an instance of :class:`ImageList`.
Sets the image list for the :class:`AuiNotebook` control.
[ "Sets", "the", "image", "list", "for", "the", ":", "class", ":", "AuiNotebook", "control", "." ]
def AssignImageList(self, imageList): """ Sets the image list for the :class:`AuiNotebook` control. :param `imageList`: an instance of :class:`ImageList`. """ self.SetImageList(imageList)
[ "def", "AssignImageList", "(", "self", ",", "imageList", ")", ":", "self", ".", "SetImageList", "(", "imageList", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/extern/aui/auibook.py#L3709-L3716
openvinotoolkit/openvino
dedcbeafa8b84cccdc55ca64b8da516682b381c7
tools/mo/openvino/tools/mo/front/kaldi/loader/utils.py
python
get_uint64
(s: bytes)
return struct.unpack('q', s)[0]
Get unsigned int64 value from bytes :param s: bytes array contains unsigned int64 value :return: unsigned int64 value from bytes array
Get unsigned int64 value from bytes :param s: bytes array contains unsigned int64 value :return: unsigned int64 value from bytes array
[ "Get", "unsigned", "int64", "value", "from", "bytes", ":", "param", "s", ":", "bytes", "array", "contains", "unsigned", "int64", "value", ":", "return", ":", "unsigned", "int64", "value", "from", "bytes", "array" ]
def get_uint64(s: bytes) -> int: """ Get unsigned int64 value from bytes :param s: bytes array contains unsigned int64 value :return: unsigned int64 value from bytes array """ return struct.unpack('q', s)[0]
[ "def", "get_uint64", "(", "s", ":", "bytes", ")", "->", "int", ":", "return", "struct", ".", "unpack", "(", "'q'", ",", "s", ")", "[", "0", "]" ]
https://github.com/openvinotoolkit/openvino/blob/dedcbeafa8b84cccdc55ca64b8da516682b381c7/tools/mo/openvino/tools/mo/front/kaldi/loader/utils.py#L92-L98
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/urllib3/connectionpool.py
python
HTTPSConnectionPool._prepare_proxy
(self, conn)
Establish tunnel connection early, because otherwise httplib would improperly set Host: header to proxy's IP:port.
Establish tunnel connection early, because otherwise httplib would improperly set Host: header to proxy's IP:port.
[ "Establish", "tunnel", "connection", "early", "because", "otherwise", "httplib", "would", "improperly", "set", "Host", ":", "header", "to", "proxy", "s", "IP", ":", "port", "." ]
def _prepare_proxy(self, conn): """ Establish tunnel connection early, because otherwise httplib would improperly set Host: header to proxy's IP:port. """ # Python 2.7+ try: set_tunnel = conn.set_tunnel except AttributeError: # Platform-specific: Python 2.6 set_tunnel = conn._set_tunnel if sys.version_info <= (2, 6, 4) and not self.proxy_headers: # Python 2.6.4 and older set_tunnel(self._proxy_host, self.port) else: set_tunnel(self._proxy_host, self.port, self.proxy_headers) conn.connect()
[ "def", "_prepare_proxy", "(", "self", ",", "conn", ")", ":", "# Python 2.7+", "try", ":", "set_tunnel", "=", "conn", ".", "set_tunnel", "except", "AttributeError", ":", "# Platform-specific: Python 2.6", "set_tunnel", "=", "conn", ".", "_set_tunnel", "if", "sys", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/urllib3/connectionpool.py#L800-L816
mongodb/mongo
d8ff665343ad29cf286ee2cf4a1960d29371937b
buildscripts/idl/idl/syntax.py
python
FieldTypeVariant.__init__
(self, file_name, line, column)
Construct a FieldTypeVariant.
Construct a FieldTypeVariant.
[ "Construct", "a", "FieldTypeVariant", "." ]
def __init__(self, file_name, line, column): # type: (str, int, int) -> None """Construct a FieldTypeVariant.""" self.variant = [] # type: List[FieldType] super(FieldTypeVariant, self).__init__(file_name, line, column)
[ "def", "__init__", "(", "self", ",", "file_name", ",", "line", ",", "column", ")", ":", "# type: (str, int, int) -> None", "self", ".", "variant", "=", "[", "]", "# type: List[FieldType]", "super", "(", "FieldTypeVariant", ",", "self", ")", ".", "__init__", "(...
https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/idl/idl/syntax.py#L763-L768
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/targets/arrayobj.py
python
fix_integer_index
(context, builder, idxty, idx, size)
return ind
Fix the integer index' type and value for the given dimension size.
Fix the integer index' type and value for the given dimension size.
[ "Fix", "the", "integer", "index", "type", "and", "value", "for", "the", "given", "dimension", "size", "." ]
def fix_integer_index(context, builder, idxty, idx, size): """ Fix the integer index' type and value for the given dimension size. """ if idxty.signed: ind = context.cast(builder, idx, idxty, types.intp) ind = slicing.fix_index(builder, ind, size) else: ind = context.cast(builder, idx, idxty, types.uintp) return ind
[ "def", "fix_integer_index", "(", "context", ",", "builder", ",", "idxty", ",", "idx", ",", "size", ")", ":", "if", "idxty", ".", "signed", ":", "ind", "=", "context", ".", "cast", "(", "builder", ",", "idx", ",", "idxty", ",", "types", ".", "intp", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/targets/arrayobj.py#L140-L149
kushview/Element
1cc16380caa2ab79461246ba758b9de1f46db2a5
waflib/Tools/compiler_cxx.py
python
configure
(conf)
Detects a suitable C++ compiler :raises: :py:class:`waflib.Errors.ConfigurationError` when no suitable compiler is found
Detects a suitable C++ compiler
[ "Detects", "a", "suitable", "C", "++", "compiler" ]
def configure(conf): """ Detects a suitable C++ compiler :raises: :py:class:`waflib.Errors.ConfigurationError` when no suitable compiler is found """ try: test_for_compiler = conf.options.check_cxx_compiler or default_compilers() except AttributeError: conf.fatal("Add options(opt): opt.load('compiler_cxx')") for compiler in re.split('[ ,]+', test_for_compiler): conf.env.stash() conf.start_msg('Checking for %r (C++ compiler)' % compiler) try: conf.load(compiler) except conf.errors.ConfigurationError as e: conf.env.revert() conf.end_msg(False) debug('compiler_cxx: %r', e) else: if conf.env.CXX: conf.end_msg(conf.env.get_flat('CXX')) conf.env.COMPILER_CXX = compiler conf.env.commit() break conf.env.revert() conf.end_msg(False) else: conf.fatal('could not configure a C++ compiler!')
[ "def", "configure", "(", "conf", ")", ":", "try", ":", "test_for_compiler", "=", "conf", ".", "options", ".", "check_cxx_compiler", "or", "default_compilers", "(", ")", "except", "AttributeError", ":", "conf", ".", "fatal", "(", "\"Add options(opt): opt.load('comp...
https://github.com/kushview/Element/blob/1cc16380caa2ab79461246ba758b9de1f46db2a5/waflib/Tools/compiler_cxx.py#L65-L94
google/or-tools
2cb85b4eead4c38e1c54b48044f92087cf165bce
ortools/sat/python/cp_model_helper.py
python
assert_is_int32
(x)
return int(x)
Asserts that x is integer and x is in [min_int_32, max_int_32].
Asserts that x is integer and x is in [min_int_32, max_int_32].
[ "Asserts", "that", "x", "is", "integer", "and", "x", "is", "in", "[", "min_int_32", "max_int_32", "]", "." ]
def assert_is_int32(x): """Asserts that x is integer and x is in [min_int_32, max_int_32].""" if not is_integral(x): raise TypeError('Not an integer: %s' % x) if x < INT32_MIN or x > INT32_MAX: raise OverflowError('Does not fit in an int32_t: %s' % x) return int(x)
[ "def", "assert_is_int32", "(", "x", ")", ":", "if", "not", "is_integral", "(", "x", ")", ":", "raise", "TypeError", "(", "'Not an integer: %s'", "%", "x", ")", "if", "x", "<", "INT32_MIN", "or", "x", ">", "INT32_MAX", ":", "raise", "OverflowError", "(", ...
https://github.com/google/or-tools/blob/2cb85b4eead4c38e1c54b48044f92087cf165bce/ortools/sat/python/cp_model_helper.py#L62-L68
msftguy/ssh-rd
a5f3a79daeac5844edebf01916c9613563f1c390
_3rd/boost_1_48_0/tools/build/v2/util/utility.py
python
split_action_id
(id)
return (toolset, name)
Splits an id in the toolset and specific rule parts. E.g. 'gcc.compile.c++' returns ('gcc', 'compile.c++')
Splits an id in the toolset and specific rule parts. E.g. 'gcc.compile.c++' returns ('gcc', 'compile.c++')
[ "Splits", "an", "id", "in", "the", "toolset", "and", "specific", "rule", "parts", ".", "E", ".", "g", ".", "gcc", ".", "compile", ".", "c", "++", "returns", "(", "gcc", "compile", ".", "c", "++", ")" ]
def split_action_id (id): """ Splits an id in the toolset and specific rule parts. E.g. 'gcc.compile.c++' returns ('gcc', 'compile.c++') """ split = id.split ('.', 1) toolset = split [0] name = '' if len (split) > 1: name = split [1] return (toolset, name)
[ "def", "split_action_id", "(", "id", ")", ":", "split", "=", "id", ".", "split", "(", "'.'", ",", "1", ")", "toolset", "=", "split", "[", "0", "]", "name", "=", "''", "if", "len", "(", "split", ")", ">", "1", ":", "name", "=", "split", "[", "...
https://github.com/msftguy/ssh-rd/blob/a5f3a79daeac5844edebf01916c9613563f1c390/_3rd/boost_1_48_0/tools/build/v2/util/utility.py#L121-L130
ComputationalRadiationPhysics/picongpu
59e9b53605f9a5c1bf271eeb055bc74370a99052
lib/python/picongpu/plugins/plot_mpl/base_visualizer.py
python
Visualizer.clear_cbar
(self)
Clear colorbars if present. Should be implemented in derived classes that use colorbars.
Clear colorbars if present. Should be implemented in derived classes that use colorbars.
[ "Clear", "colorbars", "if", "present", ".", "Should", "be", "implemented", "in", "derived", "classes", "that", "use", "colorbars", "." ]
def clear_cbar(self): """ Clear colorbars if present. Should be implemented in derived classes that use colorbars. """ pass
[ "def", "clear_cbar", "(", "self", ")", ":", "pass" ]
https://github.com/ComputationalRadiationPhysics/picongpu/blob/59e9b53605f9a5c1bf271eeb055bc74370a99052/lib/python/picongpu/plugins/plot_mpl/base_visualizer.py#L254-L259
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/ops/structured/structured_tensor.py
python
StructuredTensor.with_updates
( self, updates: Dict[FieldName, Union[FieldValue, FieldFn, None]], validate: bool = False )
return self._with_updates_impl((), updates_items, validate)
Creates a new `StructuredTensor` with the updated fields. If this `StructuredTensor` is a scalar, and `k` is the `FieldName` being updated and `v` the new value, then: ``` result[k] = v # If (k, v) is in updates and v is a FieldValue result[k] = f(self[k]) # If (k, f) is in updates and f is a FieldFn result[k] = self[k] # If k is in self.field_names but not in updates ``` If this `StructuredTensor` has rank `N` and shape `[D1...DN]`, then each FieldValue `v` in `updates` must have shape `[D1...DN, ...]`, that is, prefixed with the same shape as the `StructuredTensor`. Then the resulting `StructuredTensor` will have: ``` result[i1...iN][k] = v[i1...iN] # (k, v) in updates result[i1...iN][k] = f(self.field_value(k))[i1...iN] # (k, f) in updates result[i1...iN][k] = self[i1...iN][k] # k not in updates ``` Note that `result.shape` is always equal to `self.shape` (but the shapes of nested StructuredTensors may be changed if they are updated with new values). Args: updates: A dictionary mapping `FieldName` to either a `FieldValue` to be used to update, or a `FieldFn` that will transform the value for the given `FieldName`. `FieldName` can be a string for a direct field, or a sequence of strings to refer to a nested sub-field. `FieldFn` is a function that takes a `FieldValue` as input and should return a `FieldValue`. All other fields are copied over to the new `StructuredTensor`. New `FieldName` can be given (to add new fields), but only to existing `StructuredTensor`, it won't automatically create new nested structures -- but one can create a whole `StructureTensor` sub-structure and set that into an existing structure. If the new value is set to `None`, it is removed. validate: If true, then add runtime validation ops that check that the field values all have compatible shapes in the outer `shape.rank` dimensions. Returns: A `StructuredTensor`. Raises: `ValueError`: If the any of the `FieldName` keys points to non-existent sub-structures, if parent and child nodes are updated, if shapes change, if a delete update is given for a non-existant field, or if a `FieldFn` transforming function is given for a `FieldName` that doesn't yet exist. Examples: >>> shoes_us = StructuredTensor.from_pyval([ ... {"age": 12, "nicknames": ["Josaphine"], ... "shoes": {"sizes": [8.0, 7.5, 7.5]}}, ... {"age": 82, "nicknames": ["Bob", "Bobby"], ... "shoes": {"sizes": [11.0, 11.5, 12.0]}}, ... {"age": 42, "nicknames": ["Elmo"], ... "shoes": {"sizes": [9.0, 9.5, 10.0]}}]) >>> def us_to_europe(t): ... return tf.round(t * 2.54 + 17.0) # Rough approximation. >>> shoe_sizes_key = ("shoes", "sizes") >>> shoes_eu = shoes_us.with_updates({shoe_sizes_key: us_to_europe}) >>> shoes_eu.field_value(shoe_sizes_key) <tf.RaggedTensor [[37.0, 36.0, 36.0], [45.0, 46.0, 47.0], [40.0, 41.0, 42.0]]>
Creates a new `StructuredTensor` with the updated fields.
[ "Creates", "a", "new", "StructuredTensor", "with", "the", "updated", "fields", "." ]
def with_updates( self, updates: Dict[FieldName, Union[FieldValue, FieldFn, None]], validate: bool = False ) -> 'StructuredTensor': """Creates a new `StructuredTensor` with the updated fields. If this `StructuredTensor` is a scalar, and `k` is the `FieldName` being updated and `v` the new value, then: ``` result[k] = v # If (k, v) is in updates and v is a FieldValue result[k] = f(self[k]) # If (k, f) is in updates and f is a FieldFn result[k] = self[k] # If k is in self.field_names but not in updates ``` If this `StructuredTensor` has rank `N` and shape `[D1...DN]`, then each FieldValue `v` in `updates` must have shape `[D1...DN, ...]`, that is, prefixed with the same shape as the `StructuredTensor`. Then the resulting `StructuredTensor` will have: ``` result[i1...iN][k] = v[i1...iN] # (k, v) in updates result[i1...iN][k] = f(self.field_value(k))[i1...iN] # (k, f) in updates result[i1...iN][k] = self[i1...iN][k] # k not in updates ``` Note that `result.shape` is always equal to `self.shape` (but the shapes of nested StructuredTensors may be changed if they are updated with new values). Args: updates: A dictionary mapping `FieldName` to either a `FieldValue` to be used to update, or a `FieldFn` that will transform the value for the given `FieldName`. `FieldName` can be a string for a direct field, or a sequence of strings to refer to a nested sub-field. `FieldFn` is a function that takes a `FieldValue` as input and should return a `FieldValue`. All other fields are copied over to the new `StructuredTensor`. New `FieldName` can be given (to add new fields), but only to existing `StructuredTensor`, it won't automatically create new nested structures -- but one can create a whole `StructureTensor` sub-structure and set that into an existing structure. If the new value is set to `None`, it is removed. validate: If true, then add runtime validation ops that check that the field values all have compatible shapes in the outer `shape.rank` dimensions. Returns: A `StructuredTensor`. Raises: `ValueError`: If the any of the `FieldName` keys points to non-existent sub-structures, if parent and child nodes are updated, if shapes change, if a delete update is given for a non-existant field, or if a `FieldFn` transforming function is given for a `FieldName` that doesn't yet exist. Examples: >>> shoes_us = StructuredTensor.from_pyval([ ... {"age": 12, "nicknames": ["Josaphine"], ... "shoes": {"sizes": [8.0, 7.5, 7.5]}}, ... {"age": 82, "nicknames": ["Bob", "Bobby"], ... "shoes": {"sizes": [11.0, 11.5, 12.0]}}, ... {"age": 42, "nicknames": ["Elmo"], ... "shoes": {"sizes": [9.0, 9.5, 10.0]}}]) >>> def us_to_europe(t): ... return tf.round(t * 2.54 + 17.0) # Rough approximation. >>> shoe_sizes_key = ("shoes", "sizes") >>> shoes_eu = shoes_us.with_updates({shoe_sizes_key: us_to_europe}) >>> shoes_eu.field_value(shoe_sizes_key) <tf.RaggedTensor [[37.0, 36.0, 36.0], [45.0, 46.0, 47.0], [40.0, 41.0, 42.0]]> """ updates_items = [(_normalize_field_name_to_tuple(name), value) for name, value in updates.items()] # Sort by keys and check for updates of both parent and child nodes. updates_items = sorted(updates_items) for i in range(1, len(updates_items)): # Parent of a node would precede node in the sorted order. name = updates_items[i][0] # item[0] is the name, item[1] is the value. prev_name = updates_items[i - 1][0] if name[:len(prev_name)] == prev_name: raise ValueError( '`StructuredTensor.with_updates` does not allow both parent and ' 'child nodes to be updated: parent={}, child={}. If needed you can ' 'update child nodes in the parent update value.'.format( prev_name, name)) return self._with_updates_impl((), updates_items, validate)
[ "def", "with_updates", "(", "self", ",", "updates", ":", "Dict", "[", "FieldName", ",", "Union", "[", "FieldValue", ",", "FieldFn", ",", "None", "]", "]", ",", "validate", ":", "bool", "=", "False", ")", "->", "'StructuredTensor'", ":", "updates_items", ...
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/structured/structured_tensor.py#L313-L402
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/telnetlib.py
python
Telnet.rawq_getchar
(self)
return c
Get next char from raw queue. Block if no data is immediately available. Raise EOFError when connection is closed.
Get next char from raw queue.
[ "Get", "next", "char", "from", "raw", "queue", "." ]
def rawq_getchar(self): """Get next char from raw queue. Block if no data is immediately available. Raise EOFError when connection is closed. """ if not self.rawq: self.fill_rawq() if self.eof: raise EOFError c = self.rawq[self.irawq] self.irawq = self.irawq + 1 if self.irawq >= len(self.rawq): self.rawq = '' self.irawq = 0 return c
[ "def", "rawq_getchar", "(", "self", ")", ":", "if", "not", "self", ".", "rawq", ":", "self", ".", "fill_rawq", "(", ")", "if", "self", ".", "eof", ":", "raise", "EOFError", "c", "=", "self", ".", "rawq", "[", "self", ".", "irawq", "]", "self", "....
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/telnetlib.py#L543-L559
SFTtech/openage
d6a08c53c48dc1e157807471df92197f6ca9e04d
openage/convert/value_object/read/media/datfile/terrain.py
python
TerrainPassGraphic.get_data_format_members
(cls, game_version)
return data_format
Return the members in this struct.
Return the members in this struct.
[ "Return", "the", "members", "in", "this", "struct", "." ]
def get_data_format_members(cls, game_version): """ Return the members in this struct. """ data_format = [ # when this restriction in unit a was selected, can the unit be placed on this terrain id? 0=no, -1=yes (READ_GEN, "slp_id_exit_tile", StorageType.ID_MEMBER, "int32_t"), (READ_GEN, "slp_id_enter_tile", StorageType.ID_MEMBER, "int32_t"), (READ_GEN, "slp_id_walk_tile", StorageType.ID_MEMBER, "int32_t"), ] if game_version[0].game_id == "SWGB": data_format.append((READ_GEN, "walk_sprite_rate", StorageType.FLOAT_MEMBER, "float")) else: data_format.append((READ_GEN, "replication_amount", StorageType.INT_MEMBER, "int32_t")) return data_format
[ "def", "get_data_format_members", "(", "cls", ",", "game_version", ")", ":", "data_format", "=", "[", "# when this restriction in unit a was selected, can the unit be placed on this terrain id? 0=no, -1=yes", "(", "READ_GEN", ",", "\"slp_id_exit_tile\"", ",", "StorageType", ".", ...
https://github.com/SFTtech/openage/blob/d6a08c53c48dc1e157807471df92197f6ca9e04d/openage/convert/value_object/read/media/datfile/terrain.py#L30-L46
deepmind/open_spiel
4ca53bea32bb2875c7385d215424048ae92f78c8
open_spiel/python/mfg/algorithms/policy_value.py
python
PolicyValue.__init__
(self, game, distribution: distribution_std.Distribution, policy: policy_std.Policy, state_value: Optional[value.ValueFunction] = None, root_state=None)
Initializes the value calculation. Args: game: The game to analyze. distribution: A `distribution.Distribution` object. policy: A `policy.Policy` object. state_value: A state value function. Defaults to Tabular. root_state: The state of the game at which to start. If `None`, the game root state is used.
Initializes the value calculation.
[ "Initializes", "the", "value", "calculation", "." ]
def __init__(self, game, distribution: distribution_std.Distribution, policy: policy_std.Policy, state_value: Optional[value.ValueFunction] = None, root_state=None): """Initializes the value calculation. Args: game: The game to analyze. distribution: A `distribution.Distribution` object. policy: A `policy.Policy` object. state_value: A state value function. Defaults to Tabular. root_state: The state of the game at which to start. If `None`, the game root state is used. """ super(PolicyValue, self).__init__(game) if root_state is None: self._root_states = game.new_initial_states() else: self._root_states = [root_state] self._distribution = distribution self._policy = policy self._state_value = (state_value if state_value is not None else value.TabularValueFunction(game)) self.evaluate()
[ "def", "__init__", "(", "self", ",", "game", ",", "distribution", ":", "distribution_std", ".", "Distribution", ",", "policy", ":", "policy_std", ".", "Policy", ",", "state_value", ":", "Optional", "[", "value", ".", "ValueFunction", "]", "=", "None", ",", ...
https://github.com/deepmind/open_spiel/blob/4ca53bea32bb2875c7385d215424048ae92f78c8/open_spiel/python/mfg/algorithms/policy_value.py#L26-L53
apache/incubator-mxnet
f03fb23f1d103fec9541b5ae59ee06b1734a51d9
python/mxnet/numpy/multiarray.py
python
fmin
(x1, x2, out=None, **kwargs)
return _mx_nd_np.fmin(x1, x2, out=out)
Returns element-wise minimum of the input arrays with broadcasting. (Ignores NaNs) Parameters ---------- x1, x2 : scalar or mxnet.numpy.ndarray The arrays holding the elements to be compared. They must have the same shape, or shapes that can be broadcast to a single shape. Returns ------- out : mxnet.numpy.ndarray or scalar The fmin of x1 and x2, element-wise. This is a scalar if both x1 and x2 are scalars. Examples -------- >>> np.fmin(np.array([2, 3, 4]), np.array([1, 5, 2])) array([1., 3., 2.]) >>> np.fmin(np.eye(2), np.array([0.5, 2])) # broadcasting array([[0.5, 0. ], [0. , 1. ]])
Returns element-wise minimum of the input arrays with broadcasting. (Ignores NaNs)
[ "Returns", "element", "-", "wise", "minimum", "of", "the", "input", "arrays", "with", "broadcasting", ".", "(", "Ignores", "NaNs", ")" ]
def fmin(x1, x2, out=None, **kwargs): """ Returns element-wise minimum of the input arrays with broadcasting. (Ignores NaNs) Parameters ---------- x1, x2 : scalar or mxnet.numpy.ndarray The arrays holding the elements to be compared. They must have the same shape, or shapes that can be broadcast to a single shape. Returns ------- out : mxnet.numpy.ndarray or scalar The fmin of x1 and x2, element-wise. This is a scalar if both x1 and x2 are scalars. Examples -------- >>> np.fmin(np.array([2, 3, 4]), np.array([1, 5, 2])) array([1., 3., 2.]) >>> np.fmin(np.eye(2), np.array([0.5, 2])) # broadcasting array([[0.5, 0. ], [0. , 1. ]]) """ return _mx_nd_np.fmin(x1, x2, out=out)
[ "def", "fmin", "(", "x1", ",", "x2", ",", "out", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "_mx_nd_np", ".", "fmin", "(", "x1", ",", "x2", ",", "out", "=", "out", ")" ]
https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/numpy/multiarray.py#L7796-L7820
eventql/eventql
7ca0dbb2e683b525620ea30dc40540a22d5eb227
deps/3rdparty/spidermonkey/mozjs/media/webrtc/trunk/tools/gyp/pylib/gyp/input.py
python
ProcessListFiltersInDict
(name, the_dict)
Process regular expression and exclusion-based filters on lists. An exclusion list is in a dict key named with a trailing "!", like "sources!". Every item in such a list is removed from the associated main list, which in this example, would be "sources". Removed items are placed into a "sources_excluded" list in the dict. Regular expression (regex) filters are contained in dict keys named with a trailing "/", such as "sources/" to operate on the "sources" list. Regex filters in a dict take the form: 'sources/': [ ['exclude', '_(linux|mac|win)\\.cc$'], ['include', '_mac\\.cc$'] ], The first filter says to exclude all files ending in _linux.cc, _mac.cc, and _win.cc. The second filter then includes all files ending in _mac.cc that are now or were once in the "sources" list. Items matching an "exclude" filter are subject to the same processing as would occur if they were listed by name in an exclusion list (ending in "!"). Items matching an "include" filter are brought back into the main list if previously excluded by an exclusion list or exclusion regex filter. Subsequent matching "exclude" patterns can still cause items to be excluded after matching an "include".
Process regular expression and exclusion-based filters on lists.
[ "Process", "regular", "expression", "and", "exclusion", "-", "based", "filters", "on", "lists", "." ]
def ProcessListFiltersInDict(name, the_dict): """Process regular expression and exclusion-based filters on lists. An exclusion list is in a dict key named with a trailing "!", like "sources!". Every item in such a list is removed from the associated main list, which in this example, would be "sources". Removed items are placed into a "sources_excluded" list in the dict. Regular expression (regex) filters are contained in dict keys named with a trailing "/", such as "sources/" to operate on the "sources" list. Regex filters in a dict take the form: 'sources/': [ ['exclude', '_(linux|mac|win)\\.cc$'], ['include', '_mac\\.cc$'] ], The first filter says to exclude all files ending in _linux.cc, _mac.cc, and _win.cc. The second filter then includes all files ending in _mac.cc that are now or were once in the "sources" list. Items matching an "exclude" filter are subject to the same processing as would occur if they were listed by name in an exclusion list (ending in "!"). Items matching an "include" filter are brought back into the main list if previously excluded by an exclusion list or exclusion regex filter. Subsequent matching "exclude" patterns can still cause items to be excluded after matching an "include". """ # Look through the dictionary for any lists whose keys end in "!" or "/". # These are lists that will be treated as exclude lists and regular # expression-based exclude/include lists. Collect the lists that are # needed first, looking for the lists that they operate on, and assemble # then into |lists|. This is done in a separate loop up front, because # the _included and _excluded keys need to be added to the_dict, and that # can't be done while iterating through it. lists = [] del_lists = [] for key, value in the_dict.iteritems(): operation = key[-1] if operation != '!' and operation != '/': continue if not isinstance(value, list): raise ValueError, name + ' key ' + key + ' must be list, not ' + \ value.__class__.__name__ list_key = key[:-1] if list_key not in the_dict: # This happens when there's a list like "sources!" but no corresponding # "sources" list. Since there's nothing for it to operate on, queue up # the "sources!" list for deletion now. del_lists.append(key) continue if not isinstance(the_dict[list_key], list): raise ValueError, name + ' key ' + list_key + \ ' must be list, not ' + \ value.__class__.__name__ + ' when applying ' + \ {'!': 'exclusion', '/': 'regex'}[operation] if not list_key in lists: lists.append(list_key) # Delete the lists that are known to be unneeded at this point. for del_list in del_lists: del the_dict[del_list] for list_key in lists: the_list = the_dict[list_key] # Initialize the list_actions list, which is parallel to the_list. Each # item in list_actions identifies whether the corresponding item in # the_list should be excluded, unconditionally preserved (included), or # whether no exclusion or inclusion has been applied. Items for which # no exclusion or inclusion has been applied (yet) have value -1, items # excluded have value 0, and items included have value 1. Includes and # excludes override previous actions. All items in list_actions are # initialized to -1 because no excludes or includes have been processed # yet. list_actions = list((-1,) * len(the_list)) exclude_key = list_key + '!' if exclude_key in the_dict: for exclude_item in the_dict[exclude_key]: for index in xrange(0, len(the_list)): if exclude_item == the_list[index]: # This item matches the exclude_item, so set its action to 0 # (exclude). list_actions[index] = 0 # The "whatever!" list is no longer needed, dump it. del the_dict[exclude_key] regex_key = list_key + '/' if regex_key in the_dict: for regex_item in the_dict[regex_key]: [action, pattern] = regex_item pattern_re = re.compile(pattern) if action == 'exclude': # This item matches an exclude regex, so set its value to 0 (exclude). action_value = 0 elif action == 'include': # This item matches an include regex, so set its value to 1 (include). action_value = 1 else: # This is an action that doesn't make any sense. raise ValueError, 'Unrecognized action ' + action + ' in ' + name + \ ' key ' + regex_key for index in xrange(0, len(the_list)): list_item = the_list[index] if list_actions[index] == action_value: # Even if the regex matches, nothing will change so continue (regex # searches are expensive). continue if pattern_re.search(list_item): # Regular expression match. list_actions[index] = action_value # The "whatever/" list is no longer needed, dump it. del the_dict[regex_key] # Add excluded items to the excluded list. # # Note that exclude_key ("sources!") is different from excluded_key # ("sources_excluded"). The exclude_key list is input and it was already # processed and deleted; the excluded_key list is output and it's about # to be created. excluded_key = list_key + '_excluded' if excluded_key in the_dict: raise GypError(name + ' key ' + excluded_key + ' must not be present prior ' ' to applying exclusion/regex filters for ' + list_key) excluded_list = [] # Go backwards through the list_actions list so that as items are deleted, # the indices of items that haven't been seen yet don't shift. That means # that things need to be prepended to excluded_list to maintain them in the # same order that they existed in the_list. for index in xrange(len(list_actions) - 1, -1, -1): if list_actions[index] == 0: # Dump anything with action 0 (exclude). Keep anything with action 1 # (include) or -1 (no include or exclude seen for the item). excluded_list.insert(0, the_list[index]) del the_list[index] # If anything was excluded, put the excluded list into the_dict at # excluded_key. if len(excluded_list) > 0: the_dict[excluded_key] = excluded_list # Now recurse into subdicts and lists that may contain dicts. for key, value in the_dict.iteritems(): if isinstance(value, dict): ProcessListFiltersInDict(key, value) elif isinstance(value, list): ProcessListFiltersInList(key, value)
[ "def", "ProcessListFiltersInDict", "(", "name", ",", "the_dict", ")", ":", "# Look through the dictionary for any lists whose keys end in \"!\" or \"/\".", "# These are lists that will be treated as exclude lists and regular", "# expression-based exclude/include lists. Collect the lists that ar...
https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/media/webrtc/trunk/tools/gyp/pylib/gyp/input.py#L2132-L2286
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_pool.py
python
_NormalizeFullyQualifiedName
(name)
return name.lstrip('.')
Remove leading period from fully-qualified type name. Due to b/13860351 in descriptor_database.py, types in the root namespace are generated with a leading period. This function removes that prefix. Args: name: A str, the fully-qualified symbol name. Returns: A str, the normalized fully-qualified symbol name.
Remove leading period from fully-qualified type name.
[ "Remove", "leading", "period", "from", "fully", "-", "qualified", "type", "name", "." ]
def _NormalizeFullyQualifiedName(name): """Remove leading period from fully-qualified type name. Due to b/13860351 in descriptor_database.py, types in the root namespace are generated with a leading period. This function removes that prefix. Args: name: A str, the fully-qualified symbol name. Returns: A str, the normalized fully-qualified symbol name. """ return name.lstrip('.')
[ "def", "_NormalizeFullyQualifiedName", "(", "name", ")", ":", "return", "name", ".", "lstrip", "(", "'.'", ")" ]
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_pool.py#L70-L82
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/indexes/base.py
python
ensure_index_from_sequences
(sequences, names=None)
Construct an index from sequences of data. A single sequence returns an Index. Many sequences returns a MultiIndex. Parameters ---------- sequences : sequence of sequences names : sequence of str Returns ------- index : Index or MultiIndex Examples -------- >>> ensure_index_from_sequences([[1, 2, 3]], names=['name']) Int64Index([1, 2, 3], dtype='int64', name='name') >>> ensure_index_from_sequences([['a', 'a'], ['a', 'b']], names=['L1', 'L2']) MultiIndex([('a', 'a'), ('a', 'b')], names=['L1', 'L2']) See Also -------- ensure_index
Construct an index from sequences of data.
[ "Construct", "an", "index", "from", "sequences", "of", "data", "." ]
def ensure_index_from_sequences(sequences, names=None): """ Construct an index from sequences of data. A single sequence returns an Index. Many sequences returns a MultiIndex. Parameters ---------- sequences : sequence of sequences names : sequence of str Returns ------- index : Index or MultiIndex Examples -------- >>> ensure_index_from_sequences([[1, 2, 3]], names=['name']) Int64Index([1, 2, 3], dtype='int64', name='name') >>> ensure_index_from_sequences([['a', 'a'], ['a', 'b']], names=['L1', 'L2']) MultiIndex([('a', 'a'), ('a', 'b')], names=['L1', 'L2']) See Also -------- ensure_index """ from pandas.core.indexes.multi import MultiIndex if len(sequences) == 1: if names is not None: names = names[0] return Index(sequences[0], name=names) else: return MultiIndex.from_arrays(sequences, names=names)
[ "def", "ensure_index_from_sequences", "(", "sequences", ",", "names", "=", "None", ")", ":", "from", "pandas", ".", "core", ".", "indexes", ".", "multi", "import", "MultiIndex", "if", "len", "(", "sequences", ")", "==", "1", ":", "if", "names", "is", "no...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/indexes/base.py#L5252-L5290
SFTtech/openage
d6a08c53c48dc1e157807471df92197f6ca9e04d
openage/util/filelike/fifo.py
python
FIFO.tell
(self)
return self.pos
Warning: Returns the position for reading. Due to the FIFO nature, the position for writing is further-advanced.
Warning: Returns the position for reading.
[ "Warning", ":", "Returns", "the", "position", "for", "reading", "." ]
def tell(self): """ Warning: Returns the position for reading. Due to the FIFO nature, the position for writing is further-advanced. """ return self.pos
[ "def", "tell", "(", "self", ")", ":", "return", "self", ".", "pos" ]
https://github.com/SFTtech/openage/blob/d6a08c53c48dc1e157807471df92197f6ca9e04d/openage/util/filelike/fifo.py#L37-L43
miyosuda/TensorFlowAndroidMNIST
7b5a4603d2780a8a2834575706e9001977524007
jni-build/jni/include/tensorflow/contrib/learn/python/learn/estimators/dnn_linear_combined.py
python
_DNNLinearCombinedBaseEstimator._get_predict_ops
(self, features)
return self._target_column.logits_to_predictions(logits, proba=True)
See base class.
See base class.
[ "See", "base", "class", "." ]
def _get_predict_ops(self, features): """See base class.""" features = self._get_feature_dict(features) logits = self._logits(features) return self._target_column.logits_to_predictions(logits, proba=True)
[ "def", "_get_predict_ops", "(", "self", ",", "features", ")", ":", "features", "=", "self", ".", "_get_feature_dict", "(", "features", ")", "logits", "=", "self", ".", "_logits", "(", "features", ")", "return", "self", ".", "_target_column", ".", "logits_to_...
https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/contrib/learn/python/learn/estimators/dnn_linear_combined.py#L186-L190
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/cmd.py
python
Cmd.emptyline
(self)
Called when an empty line is entered in response to the prompt. If this method is not overridden, it repeats the last nonempty command entered.
Called when an empty line is entered in response to the prompt.
[ "Called", "when", "an", "empty", "line", "is", "entered", "in", "response", "to", "the", "prompt", "." ]
def emptyline(self): """Called when an empty line is entered in response to the prompt. If this method is not overridden, it repeats the last nonempty command entered. """ if self.lastcmd: return self.onecmd(self.lastcmd)
[ "def", "emptyline", "(", "self", ")", ":", "if", "self", ".", "lastcmd", ":", "return", "self", ".", "onecmd", "(", "self", ".", "lastcmd", ")" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/cmd.py#L223-L231
nodejs/nan
8db8c8f544f2b6ce1b0859ef6ecdd0a3873a9e62
cpplint.py
python
_IsType
(clean_lines, nesting_state, expr)
return False
Check if expression looks like a type name, returns true if so. Args: clean_lines: A CleansedLines instance containing the file. nesting_state: A NestingState instance which maintains information about the current stack of nested blocks being parsed. expr: The expression to check. Returns: True, if token looks like a type.
Check if expression looks like a type name, returns true if so.
[ "Check", "if", "expression", "looks", "like", "a", "type", "name", "returns", "true", "if", "so", "." ]
def _IsType(clean_lines, nesting_state, expr): """Check if expression looks like a type name, returns true if so. Args: clean_lines: A CleansedLines instance containing the file. nesting_state: A NestingState instance which maintains information about the current stack of nested blocks being parsed. expr: The expression to check. Returns: True, if token looks like a type. """ # Keep only the last token in the expression last_word = Match(r'^.*(\b\S+)$', expr) if last_word: token = last_word.group(1) else: token = expr # Match native types and stdint types if _TYPES.match(token): return True # Try a bit harder to match templated types. Walk up the nesting # stack until we find something that resembles a typename # declaration for what we are looking for. typename_pattern = (r'\b(?:typename|class|struct)\s+' + re.escape(token) + r'\b') block_index = len(nesting_state.stack) - 1 while block_index >= 0: if isinstance(nesting_state.stack[block_index], _NamespaceInfo): return False # Found where the opening brace is. We want to scan from this # line up to the beginning of the function, minus a few lines. # template <typename Type1, // stop scanning here # ...> # class C # : public ... { // start scanning here last_line = nesting_state.stack[block_index].starting_linenum next_block_start = 0 if block_index > 0: next_block_start = nesting_state.stack[block_index - 1].starting_linenum first_line = last_line while first_line >= next_block_start: if clean_lines.elided[first_line].find('template') >= 0: break first_line -= 1 if first_line < next_block_start: # Didn't find any "template" keyword before reaching the next block, # there are probably no template things to check for this block block_index -= 1 continue # Look for typename in the specified range for i in xrange(first_line, last_line + 1, 1): if Search(typename_pattern, clean_lines.elided[i]): return True block_index -= 1 return False
[ "def", "_IsType", "(", "clean_lines", ",", "nesting_state", ",", "expr", ")", ":", "# Keep only the last token in the expression", "last_word", "=", "Match", "(", "r'^.*(\\b\\S+)$'", ",", "expr", ")", "if", "last_word", ":", "token", "=", "last_word", ".", "group"...
https://github.com/nodejs/nan/blob/8db8c8f544f2b6ce1b0859ef6ecdd0a3873a9e62/cpplint.py#L3725-L3785
fabianschenk/RESLAM
2e71a578b6d1a1ad1fb018641218e1f41dd9e330
thirdparty/Sophus/py/sophus/dual_quaternion.py
python
DualQuaternion.__mul__
(self, right)
return DualQuaternion(self.real_q * right.real_q, self.real_q * right.inf_q + self.inf_q * right.real_q)
dual quaternion multiplication
dual quaternion multiplication
[ "dual", "quaternion", "multiplication" ]
def __mul__(self, right): """ dual quaternion multiplication """ return DualQuaternion(self.real_q * right.real_q, self.real_q * right.inf_q + self.inf_q * right.real_q)
[ "def", "__mul__", "(", "self", ",", "right", ")", ":", "return", "DualQuaternion", "(", "self", ".", "real_q", "*", "right", ".", "real_q", ",", "self", ".", "real_q", "*", "right", ".", "inf_q", "+", "self", ".", "inf_q", "*", "right", ".", "real_q"...
https://github.com/fabianschenk/RESLAM/blob/2e71a578b6d1a1ad1fb018641218e1f41dd9e330/thirdparty/Sophus/py/sophus/dual_quaternion.py#L16-L20
kismetwireless/kismet
a7c0dc270c960fb1f58bd9cec4601c201885fd4e
capture_proxy_adsb/KismetCaptureProxyAdsb/kismetexternal/__init__.py
python
ExternalInterface.add_handler
(self, command, handler)
Register a command handler; this handler will be called when a command is received. :param command: Command (string, case sensitive) :param handler: Handler function which will be called with (sequence number, payload) :return: None
Register a command handler; this handler will be called when a command is received.
[ "Register", "a", "command", "handler", ";", "this", "handler", "will", "be", "called", "when", "a", "command", "is", "received", "." ]
def add_handler(self, command, handler): """ Register a command handler; this handler will be called when a command is received. :param command: Command (string, case sensitive) :param handler: Handler function which will be called with (sequence number, payload) :return: None """ self.handlers[command] = handler
[ "def", "add_handler", "(", "self", ",", "command", ",", "handler", ")", ":", "self", ".", "handlers", "[", "command", "]", "=", "handler" ]
https://github.com/kismetwireless/kismet/blob/a7c0dc270c960fb1f58bd9cec4601c201885fd4e/capture_proxy_adsb/KismetCaptureProxyAdsb/kismetexternal/__init__.py#L434-L443
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_gdi.py
python
DC.GetLayoutDirection
(*args, **kwargs)
return _gdi_.DC_GetLayoutDirection(*args, **kwargs)
GetLayoutDirection(self) -> int Get the layout direction (LTR or RTL)_ for this dc. On platforms where RTL layout is supported, the return value will either be ``wx.Layout_LeftToRight`` or ``wx.Layout_RightToLeft``. ``wx.Layout_Default`` is returned if layout direction is not supported.
GetLayoutDirection(self) -> int
[ "GetLayoutDirection", "(", "self", ")", "-", ">", "int" ]
def GetLayoutDirection(*args, **kwargs): """ GetLayoutDirection(self) -> int Get the layout direction (LTR or RTL)_ for this dc. On platforms where RTL layout is supported, the return value will either be ``wx.Layout_LeftToRight`` or ``wx.Layout_RightToLeft``. ``wx.Layout_Default`` is returned if layout direction is not supported. """ return _gdi_.DC_GetLayoutDirection(*args, **kwargs)
[ "def", "GetLayoutDirection", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gdi_", ".", "DC_GetLayoutDirection", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_gdi.py#L4620-L4630
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/lite/python/interpreter.py
python
Delegate.__init__
(self, library, options=None)
Loads delegate from the shared library. Args: library: Shared library name. options: Dictionary of options that are required to load the delegate. All keys and values in the dictionary should be serializable. Consult the documentation of the specific delegate for required and legal options. (default None) Raises: RuntimeError: This is raised if the Python implementation is not CPython.
Loads delegate from the shared library.
[ "Loads", "delegate", "from", "the", "shared", "library", "." ]
def __init__(self, library, options=None): """Loads delegate from the shared library. Args: library: Shared library name. options: Dictionary of options that are required to load the delegate. All keys and values in the dictionary should be serializable. Consult the documentation of the specific delegate for required and legal options. (default None) Raises: RuntimeError: This is raised if the Python implementation is not CPython. """ # TODO(b/136468453): Remove need for __del__ ordering needs of CPython # by using explicit closes(). See implementation of Interpreter __del__. if platform.python_implementation() != 'CPython': raise RuntimeError('Delegates are currently only supported into CPython' 'due to missing immediate reference counting.') self._library = ctypes.pydll.LoadLibrary(library) self._library.tflite_plugin_create_delegate.argtypes = [ ctypes.POINTER(ctypes.c_char_p), ctypes.POINTER(ctypes.c_char_p), ctypes.c_int, ctypes.CFUNCTYPE(None, ctypes.c_char_p) ] self._library.tflite_plugin_create_delegate.restype = ctypes.c_void_p # Convert the options from a dictionary to lists of char pointers. options = options or {} options_keys = (ctypes.c_char_p * len(options))() options_values = (ctypes.c_char_p * len(options))() for idx, (key, value) in enumerate(options.items()): options_keys[idx] = str(key).encode('utf-8') options_values[idx] = str(value).encode('utf-8') class ErrorMessageCapture(object): def __init__(self): self.message = '' def report(self, x): self.message += x capture = ErrorMessageCapture() error_capturer_cb = ctypes.CFUNCTYPE(None, ctypes.c_char_p)(capture.report) # Do not make a copy of _delegate_ptr. It is freed by Delegate's finalizer. self._delegate_ptr = self._library.tflite_plugin_create_delegate( options_keys, options_values, len(options), error_capturer_cb) if self._delegate_ptr is None: raise ValueError(capture.message)
[ "def", "__init__", "(", "self", ",", "library", ",", "options", "=", "None", ")", ":", "# TODO(b/136468453): Remove need for __del__ ordering needs of CPython", "# by using explicit closes(). See implementation of Interpreter __del__.", "if", "platform", ".", "python_implementation...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/lite/python/interpreter.py#L70-L119
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
python/paddle/fluid/nets.py
python
scaled_dot_product_attention
(queries, keys, values, num_heads=1, dropout_rate=0.)
return __combine_heads(ctx_multiheads)
r""" :api_attr: Static Graph This interface Multi-Head Attention using scaled dot product. Attention mechanism can be seen as mapping a query and a set of key-value pairs to an output. Multi-Head Attention performs attention using multi-head parallel, and the inputs of attention would be transformed by linear projection. The formula is as follows: .. math:: MultiHead(Q, K, V ) & = Concat(head_1, ..., head_h) where \ head_i & = Attention(QW_i^Q , KW_i^K , VW_i^V ) Attention(Q, K, V) & = softmax (\\frac{QK^\mathrm{T}}{\sqrt{d_k}}) V For more details, please refer to `Attention Is All You Need <https://arxiv.org/pdf/1706.03762.pdf>`_ . Note that the implementation is adapted to batch, and all matrix multiplication in :math:`Attention(Q, K, V)` is batched matrix multiplication. Refer to :ref:`api_fluid_layers_matmul` . Args: queries (Variable): A 3-D Tensor with shape :math:`[N, L_q, d_k \\times h]` , where :math:`N` stands for batch size, :math:`L_q` for the sequence length of query, :math:`d_k \\times h` for the feature size of query, :math:`h` for head number. The data type should be float32 or float64. keys (Variable): A 3-D Tensor with shape :math:`[N, L_k, d_k \\times h]` , where :math:`N` stands for batch size, :math:`L_k` for the sequence length of key, :math:`d_k \\times h` for the feature size of key, :math:`h` for head number. The data type should be the same as ``queries`` . values (Variable): A 3-D Tensor with shape :math:`[N, L_k, d_v \\times h]` , where :math:`N` stands for batch size, :math:`L_k` for the sequence length of key, :math:`d_v \\times h` for the feature size of value, :math:`h` for head number. The data type should be the same as ``queries`` . num_heads (int, optional): Indicate the number of head. If the number is 1, linear projection would not be performed on inputs. Default: 1. dropout_rate (float, optional): The rate to drop the attention weight. Default: 0.0, which means no dropout. Returns: Variable: A 3-D Tensor with shape :math:`[N, L_q, d_v \\times h]` , \ where :math:`N` stands for batch size, :math:`L_q` for the sequence \ length of query, :math:`d_v \\times h` for the feature size of value. \ It has the same data type with inputs, representing the output of \ Multi-Head Attention. Raises: TypeError: The dtype of inputs keys, values and queries should be the same. ValueError: Inputs queries, keys and values should all be 3-D tensors. ValueError: The hidden size of queries and keys should be the same. ValueError: The max sequence length in value batch and in key batch should be the same. ValueError: he hidden size of keys must be divisible by the number of attention heads. ValueError: he hidden size of values must be divisible by the number of attention heads. Examples: .. code-block:: python import paddle.fluid as fluid import paddle paddle.enable_static() queries = fluid.data(name="queries", shape=[3, 5, 9], dtype="float32") keys = fluid.data(name="keys", shape=[3, 6, 9], dtype="float32") values = fluid.data(name="values", shape=[3, 6, 10], dtype="float32") contexts = fluid.nets.scaled_dot_product_attention(queries, keys, values) contexts.shape # [3, 5, 10]
r""" :api_attr: Static Graph
[ "r", ":", "api_attr", ":", "Static", "Graph" ]
def scaled_dot_product_attention(queries, keys, values, num_heads=1, dropout_rate=0.): r""" :api_attr: Static Graph This interface Multi-Head Attention using scaled dot product. Attention mechanism can be seen as mapping a query and a set of key-value pairs to an output. Multi-Head Attention performs attention using multi-head parallel, and the inputs of attention would be transformed by linear projection. The formula is as follows: .. math:: MultiHead(Q, K, V ) & = Concat(head_1, ..., head_h) where \ head_i & = Attention(QW_i^Q , KW_i^K , VW_i^V ) Attention(Q, K, V) & = softmax (\\frac{QK^\mathrm{T}}{\sqrt{d_k}}) V For more details, please refer to `Attention Is All You Need <https://arxiv.org/pdf/1706.03762.pdf>`_ . Note that the implementation is adapted to batch, and all matrix multiplication in :math:`Attention(Q, K, V)` is batched matrix multiplication. Refer to :ref:`api_fluid_layers_matmul` . Args: queries (Variable): A 3-D Tensor with shape :math:`[N, L_q, d_k \\times h]` , where :math:`N` stands for batch size, :math:`L_q` for the sequence length of query, :math:`d_k \\times h` for the feature size of query, :math:`h` for head number. The data type should be float32 or float64. keys (Variable): A 3-D Tensor with shape :math:`[N, L_k, d_k \\times h]` , where :math:`N` stands for batch size, :math:`L_k` for the sequence length of key, :math:`d_k \\times h` for the feature size of key, :math:`h` for head number. The data type should be the same as ``queries`` . values (Variable): A 3-D Tensor with shape :math:`[N, L_k, d_v \\times h]` , where :math:`N` stands for batch size, :math:`L_k` for the sequence length of key, :math:`d_v \\times h` for the feature size of value, :math:`h` for head number. The data type should be the same as ``queries`` . num_heads (int, optional): Indicate the number of head. If the number is 1, linear projection would not be performed on inputs. Default: 1. dropout_rate (float, optional): The rate to drop the attention weight. Default: 0.0, which means no dropout. Returns: Variable: A 3-D Tensor with shape :math:`[N, L_q, d_v \\times h]` , \ where :math:`N` stands for batch size, :math:`L_q` for the sequence \ length of query, :math:`d_v \\times h` for the feature size of value. \ It has the same data type with inputs, representing the output of \ Multi-Head Attention. Raises: TypeError: The dtype of inputs keys, values and queries should be the same. ValueError: Inputs queries, keys and values should all be 3-D tensors. ValueError: The hidden size of queries and keys should be the same. ValueError: The max sequence length in value batch and in key batch should be the same. ValueError: he hidden size of keys must be divisible by the number of attention heads. ValueError: he hidden size of values must be divisible by the number of attention heads. Examples: .. code-block:: python import paddle.fluid as fluid import paddle paddle.enable_static() queries = fluid.data(name="queries", shape=[3, 5, 9], dtype="float32") keys = fluid.data(name="keys", shape=[3, 6, 9], dtype="float32") values = fluid.data(name="values", shape=[3, 6, 10], dtype="float32") contexts = fluid.nets.scaled_dot_product_attention(queries, keys, values) contexts.shape # [3, 5, 10] """ check_variable_and_dtype(queries, 'queries', ['float32', 'float64'], "scaled_dot_product_attention") check_variable_and_dtype(keys, 'keys', ['float32', 'float64'], "scaled_dot_product_attention") check_variable_and_dtype(values, 'values', ['float32', 'float64'], "scaled_dot_product_attention") if not (queries.dtype == keys.dtype == values.dtype): raise TypeError( "The dtype of keys, values and queries should be the same." "But received queries.dtype = %s, " " keys.dtype = %s, values.dtype) = %s." % (convert_dtype(queries.dtype), convert_dtype(keys.dtype), convert_dtype(values.dtype))) if not (len(queries.shape) == len(keys.shape) == len(values.shape) == 3): raise ValueError( "Inputs queries, keys and values should all be 3-D tensors." "But received len(queries.shape) = %d, " "len(keys.shape) = %d, len(values.shape) = %d." % (len(queries.shape), len(keys.shape), len(values.shape))) if queries.shape[-1] != keys.shape[-1]: raise ValueError( "The hidden size of queries and keys should be the same." "But received queries' hidden size = %d and keys' hidden size = %d." % (queries.shape[-1], keys.shape[-1])) if keys.shape[-2] != values.shape[-2]: raise ValueError( "The max sequence length in value batch and in key batch " "should be the same. But received max sequence length in value batch " "= %d, in key batch = %d." % (values.shape[-2], keys.shape[-2])) if keys.shape[-1] % num_heads != 0: raise ValueError("The hidden size of keys (%d) must be divisible " "by the number of attention heads (%d)." % (keys.shape[-1], num_heads)) if values.shape[-1] % num_heads != 0: raise ValueError("The hidden size of values (%d) must be divisible " "by the number of attention heads (%d)." % (values.shape[-1], num_heads)) def __compute_qkv(queries, keys, values, num_heads): """ Add linear projection to queries, keys, and values. Args: queries(Tensor): a 3-D input Tensor. keys(Tensor): a 3-D input Tensor. values(Tensor): a 3-D input Tensor. num_heads(int): The number of heads. Linearly project the inputs ONLY when num_heads > 1. Returns: Tensor: linearly projected output Tensors: queries', keys' and values'. They have the same shapes with queries, keys and values. """ if num_heads == 1: return queries, keys, values q = layers.fc(input=queries, size=queries.shape[-1], num_flatten_dims=2) k = layers.fc(input=keys, size=keys.shape[-1], num_flatten_dims=2) v = layers.fc(input=values, size=values.shape[-1], num_flatten_dims=2) return q, k, v def __split_heads(x, num_heads): """ Reshape the last dimension of input tensor x so that it becomes two dimensions. Args: x(Tensor): a 3-D input Tensor. num_heads(int): The number of heads. Returns: Tensor: a Tensor with shape [..., n, m/num_heads], where m is size of the last dimension of x. """ if num_heads == 1: return x hidden_size = x.shape[-1] # reshape the 3-D input: [batch_size, max_sequence_length, hidden_dim] # into a 4-D output: # [batch_size, max_sequence_length, num_heads, hidden_size_per_head]. reshaped = layers.reshape( x=x, shape=list(x.shape[:-1]) + [num_heads, hidden_size // num_heads]) # permute the dimensions into: # [batch_size, num_heads, max_sequence_len, hidden_size_per_head] return layers.transpose(x=reshaped, perm=[0, 2, 1, 3]) def __combine_heads(x): """ Reshape the last two dimensions of input tensor x so that it becomes one dimension. Args: x(Tensor): a 4-D input Tensor with shape [bs, num_heads, max_sequence_length, hidden_dim]. Returns: Tensor: a Tensor with shape [bs, max_sequence_length, num_heads * hidden_dim]. """ if len(x.shape) == 3: return x if len(x.shape) != 4: raise ValueError("Input(x) should be a 4-D Tensor.") trans_x = layers.transpose(x, perm=[0, 2, 1, 3]) return layers.reshape( x=trans_x, shape=list( map(int, [ trans_x.shape[0], trans_x.shape[1], trans_x.shape[2] * trans_x.shape[3] ]))) q, k, v = __compute_qkv(queries, keys, values, num_heads) q = __split_heads(q, num_heads) k = __split_heads(k, num_heads) v = __split_heads(v, num_heads) key_dim_per_head = keys.shape[-1] // num_heads scaled_q = layers.scale(x=q, scale=key_dim_per_head**-0.5) product = layers.matmul(x=scaled_q, y=k, transpose_y=True) weights = layers.reshape( x=layers.reshape( x=product, shape=[-1, product.shape[-1]], act="softmax"), shape=product.shape) if dropout_rate: weights = layers.dropout( weights, dropout_prob=dropout_rate, is_test=False) ctx_multiheads = layers.matmul(weights, v) return __combine_heads(ctx_multiheads)
[ "def", "scaled_dot_product_attention", "(", "queries", ",", "keys", ",", "values", ",", "num_heads", "=", "1", ",", "dropout_rate", "=", "0.", ")", ":", "check_variable_and_dtype", "(", "queries", ",", "'queries'", ",", "[", "'float32'", ",", "'float64'", "]",...
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/fluid/nets.py#L384-L598
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/setuptools/py2/setuptools/installer.py
python
strip_marker
(req)
return req
Return a new requirement without the environment marker to avoid calling pip with something like `babel; extra == "i18n"`, which would always be ignored.
Return a new requirement without the environment marker to avoid calling pip with something like `babel; extra == "i18n"`, which would always be ignored.
[ "Return", "a", "new", "requirement", "without", "the", "environment", "marker", "to", "avoid", "calling", "pip", "with", "something", "like", "babel", ";", "extra", "==", "i18n", "which", "would", "always", "be", "ignored", "." ]
def strip_marker(req): """ Return a new requirement without the environment marker to avoid calling pip with something like `babel; extra == "i18n"`, which would always be ignored. """ # create a copy to avoid mutating the input req = pkg_resources.Requirement.parse(str(req)) req.marker = None return req
[ "def", "strip_marker", "(", "req", ")", ":", "# create a copy to avoid mutating the input", "req", "=", "pkg_resources", ".", "Requirement", ".", "parse", "(", "str", "(", "req", ")", ")", "req", ".", "marker", "=", "None", "return", "req" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py2/setuptools/installer.py#L141-L150
facebookincubator/BOLT
88c70afe9d388ad430cc150cc158641701397f70
llvm/utils/pipeline.py
python
fromStr
(pipeStr)
return curr
Create pipeline object from string representation.
Create pipeline object from string representation.
[ "Create", "pipeline", "object", "from", "string", "representation", "." ]
def fromStr(pipeStr): """Create pipeline object from string representation.""" stack = [] curr = [] tok = '' kind = '' for c in pipeStr: if c == ',': if tok != '': curr.append([None, tok]) tok = '' elif c == '(': stack.append([kind, curr]) kind = tok curr = [] tok = '' elif c == ')': if tok != '': curr.append([None, tok]) tok = '' oldKind = kind oldCurr = curr [kind, curr] = stack.pop() curr.append([oldKind, oldCurr]) else: tok += c if tok != '': curr.append([None, tok]) return curr
[ "def", "fromStr", "(", "pipeStr", ")", ":", "stack", "=", "[", "]", "curr", "=", "[", "]", "tok", "=", "''", "kind", "=", "''", "for", "c", "in", "pipeStr", ":", "if", "c", "==", "','", ":", "if", "tok", "!=", "''", ":", "curr", ".", "append"...
https://github.com/facebookincubator/BOLT/blob/88c70afe9d388ad430cc150cc158641701397f70/llvm/utils/pipeline.py#L5-L33
cornell-zhang/heterocl
6d9e4b4acc2ee2707b2d25b27298c0335bccedfd
python/heterocl/tvm/contrib/tar.py
python
untar
(tar_file, directory)
Unpack all tar files into the directory Parameters ---------- tar_file : str The source tar file. directory : str The target directory
Unpack all tar files into the directory
[ "Unpack", "all", "tar", "files", "into", "the", "directory" ]
def untar(tar_file, directory): """Unpack all tar files into the directory Parameters ---------- tar_file : str The source tar file. directory : str The target directory """ cmd = ["tar"] cmd += ["-xf"] cmd += [tar_file] cmd += ["-C", directory] proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) (out, _) = proc.communicate() if proc.returncode != 0: msg = "Tar error:\n" msg += py_str(out) raise RuntimeError(msg)
[ "def", "untar", "(", "tar_file", ",", "directory", ")", ":", "cmd", "=", "[", "\"tar\"", "]", "cmd", "+=", "[", "\"-xf\"", "]", "cmd", "+=", "[", "tar_file", "]", "cmd", "+=", "[", "\"-C\"", ",", "directory", "]", "proc", "=", "subprocess", ".", "P...
https://github.com/cornell-zhang/heterocl/blob/6d9e4b4acc2ee2707b2d25b27298c0335bccedfd/python/heterocl/tvm/contrib/tar.py#L46-L69
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/ipython/py3/IPython/lib/guisupport.py
python
get_app_qt4
(*args, **kwargs)
return app
Create a new qt4 app or return an existing one.
Create a new qt4 app or return an existing one.
[ "Create", "a", "new", "qt4", "app", "or", "return", "an", "existing", "one", "." ]
def get_app_qt4(*args, **kwargs): """Create a new qt4 app or return an existing one.""" from IPython.external.qt_for_kernel import QtGui app = QtGui.QApplication.instance() if app is None: if not args: args = ([''],) app = QtGui.QApplication(*args, **kwargs) return app
[ "def", "get_app_qt4", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "from", "IPython", ".", "external", ".", "qt_for_kernel", "import", "QtGui", "app", "=", "QtGui", ".", "QApplication", ".", "instance", "(", ")", "if", "app", "is", "None", ":",...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py3/IPython/lib/guisupport.py#L112-L120
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_misc.py
python
Display_GetCount
(*args)
return _misc_.Display_GetCount(*args)
Display_GetCount() -> unsigned int Return the number of available displays.
Display_GetCount() -> unsigned int
[ "Display_GetCount", "()", "-", ">", "unsigned", "int" ]
def Display_GetCount(*args): """ Display_GetCount() -> unsigned int Return the number of available displays. """ return _misc_.Display_GetCount(*args)
[ "def", "Display_GetCount", "(", "*", "args", ")", ":", "return", "_misc_", ".", "Display_GetCount", "(", "*", "args", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_misc.py#L6226-L6232
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_controls.py
python
PreGenericDatePickerCtrl
(*args, **kwargs)
return val
PreGenericDatePickerCtrl() -> GenericDatePickerCtrl Precreate a GenericDatePickerCtrl for use in 2-phase creation.
PreGenericDatePickerCtrl() -> GenericDatePickerCtrl
[ "PreGenericDatePickerCtrl", "()", "-", ">", "GenericDatePickerCtrl" ]
def PreGenericDatePickerCtrl(*args, **kwargs): """ PreGenericDatePickerCtrl() -> GenericDatePickerCtrl Precreate a GenericDatePickerCtrl for use in 2-phase creation. """ val = _controls_.new_PreGenericDatePickerCtrl(*args, **kwargs) return val
[ "def", "PreGenericDatePickerCtrl", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "val", "=", "_controls_", ".", "new_PreGenericDatePickerCtrl", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "val" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_controls.py#L6571-L6578
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_misc.py
python
SystemOptions.__init__
(self, *args, **kwargs)
__init__(self) -> SystemOptions
__init__(self) -> SystemOptions
[ "__init__", "(", "self", ")", "-", ">", "SystemOptions" ]
def __init__(self, *args, **kwargs): """__init__(self) -> SystemOptions""" _misc_.SystemOptions_swiginit(self,_misc_.new_SystemOptions(*args, **kwargs))
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_misc_", ".", "SystemOptions_swiginit", "(", "self", ",", "_misc_", ".", "new_SystemOptions", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_misc.py#L218-L220
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/protobuf/py2/google/protobuf/symbol_database.py
python
SymbolDatabase.GetSymbol
(self, symbol)
return self._classes[self.pool.FindMessageTypeByName(symbol)]
Tries to find a symbol in the local database. Currently, this method only returns message.Message instances, however, if may be extended in future to support other symbol types. Args: symbol (str): a protocol buffer symbol. Returns: A Python class corresponding to the symbol. Raises: KeyError: if the symbol could not be found.
Tries to find a symbol in the local database.
[ "Tries", "to", "find", "a", "symbol", "in", "the", "local", "database", "." ]
def GetSymbol(self, symbol): """Tries to find a symbol in the local database. Currently, this method only returns message.Message instances, however, if may be extended in future to support other symbol types. Args: symbol (str): a protocol buffer symbol. Returns: A Python class corresponding to the symbol. Raises: KeyError: if the symbol could not be found. """ return self._classes[self.pool.FindMessageTypeByName(symbol)]
[ "def", "GetSymbol", "(", "self", ",", "symbol", ")", ":", "return", "self", ".", "_classes", "[", "self", ".", "pool", ".", "FindMessageTypeByName", "(", "symbol", ")", "]" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/protobuf/py2/google/protobuf/symbol_database.py#L132-L148
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/ipython/py3/IPython/core/inputsplitter.py
python
last_two_blanks
(src)
return (bool(last_two_blanks_re.match(new_src)) or bool(last_two_blanks_re2.match(new_src)) )
Determine if the input source ends in two blanks. A blank is either a newline or a line consisting of whitespace. Parameters ---------- src : string A single or multiline string.
Determine if the input source ends in two blanks.
[ "Determine", "if", "the", "input", "source", "ends", "in", "two", "blanks", "." ]
def last_two_blanks(src): """Determine if the input source ends in two blanks. A blank is either a newline or a line consisting of whitespace. Parameters ---------- src : string A single or multiline string. """ if not src: return False # The logic here is tricky: I couldn't get a regexp to work and pass all # the tests, so I took a different approach: split the source by lines, # grab the last two and prepend '###\n' as a stand-in for whatever was in # the body before the last two lines. Then, with that structure, it's # possible to analyze with two regexps. Not the most elegant solution, but # it works. If anyone tries to change this logic, make sure to validate # the whole test suite first! new_src = '\n'.join(['###\n'] + src.splitlines()[-2:]) return (bool(last_two_blanks_re.match(new_src)) or bool(last_two_blanks_re2.match(new_src)) )
[ "def", "last_two_blanks", "(", "src", ")", ":", "if", "not", "src", ":", "return", "False", "# The logic here is tricky: I couldn't get a regexp to work and pass all", "# the tests, so I took a different approach: split the source by lines,", "# grab the last two and prepend '###\\n' as ...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py3/IPython/core/inputsplitter.py#L223-L243
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/propgrid.py
python
PropertyGridPopulator.Add
(*args, **kwargs)
return _propgrid.PropertyGridPopulator_Add(*args, **kwargs)
Add(self, String propClass, String propLabel, String propName, String propValue, PGChoices pChoices=None) -> PGProperty
Add(self, String propClass, String propLabel, String propName, String propValue, PGChoices pChoices=None) -> PGProperty
[ "Add", "(", "self", "String", "propClass", "String", "propLabel", "String", "propName", "String", "propValue", "PGChoices", "pChoices", "=", "None", ")", "-", ">", "PGProperty" ]
def Add(*args, **kwargs): """ Add(self, String propClass, String propLabel, String propName, String propValue, PGChoices pChoices=None) -> PGProperty """ return _propgrid.PropertyGridPopulator_Add(*args, **kwargs)
[ "def", "Add", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_propgrid", ".", "PropertyGridPopulator_Add", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/propgrid.py#L2586-L2591
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/Pygments/py3/pygments/lexers/fortran.py
python
FortranFixedLexer._lex_fortran
(self, match, ctx=None)
Lex a line just as free form fortran without line break.
Lex a line just as free form fortran without line break.
[ "Lex", "a", "line", "just", "as", "free", "form", "fortran", "without", "line", "break", "." ]
def _lex_fortran(self, match, ctx=None): """Lex a line just as free form fortran without line break.""" lexer = FortranLexer() text = match.group(0) + "\n" for index, token, value in lexer.get_tokens_unprocessed(text): value = value.replace('\n', '') if value != '': yield index, token, value
[ "def", "_lex_fortran", "(", "self", ",", "match", ",", "ctx", "=", "None", ")", ":", "lexer", "=", "FortranLexer", "(", ")", "text", "=", "match", ".", "group", "(", "0", ")", "+", "\"\\n\"", "for", "index", ",", "token", ",", "value", "in", "lexer...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/Pygments/py3/pygments/lexers/fortran.py#L184-L191
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/polynomial/hermite_e.py
python
hermevander
(x, deg)
return np.rollaxis(v, 0, v.ndim)
Pseudo-Vandermonde matrix of given degree. Returns the pseudo-Vandermonde matrix of degree `deg` and sample points `x`. The pseudo-Vandermonde matrix is defined by .. math:: V[..., i] = He_i(x), where `0 <= i <= deg`. The leading indices of `V` index the elements of `x` and the last index is the degree of the HermiteE polynomial. If `c` is a 1-D array of coefficients of length `n + 1` and `V` is the array ``V = hermevander(x, n)``, then ``np.dot(V, c)`` and ``hermeval(x, c)`` are the same up to roundoff. This equivalence is useful both for least squares fitting and for the evaluation of a large number of HermiteE series of the same degree and sample points. Parameters ---------- x : array_like Array of points. The dtype is converted to float64 or complex128 depending on whether any of the elements are complex. If `x` is scalar it is converted to a 1-D array. deg : int Degree of the resulting matrix. Returns ------- vander : ndarray The pseudo-Vandermonde matrix. The shape of the returned matrix is ``x.shape + (deg + 1,)``, where The last index is the degree of the corresponding HermiteE polynomial. The dtype will be the same as the converted `x`. Examples -------- >>> from numpy.polynomial.hermite_e import hermevander >>> x = np.array([-1, 0, 1]) >>> hermevander(x, 3) array([[ 1., -1., 0., 2.], [ 1., 0., -1., -0.], [ 1., 1., 0., -2.]])
Pseudo-Vandermonde matrix of given degree.
[ "Pseudo", "-", "Vandermonde", "matrix", "of", "given", "degree", "." ]
def hermevander(x, deg) : """Pseudo-Vandermonde matrix of given degree. Returns the pseudo-Vandermonde matrix of degree `deg` and sample points `x`. The pseudo-Vandermonde matrix is defined by .. math:: V[..., i] = He_i(x), where `0 <= i <= deg`. The leading indices of `V` index the elements of `x` and the last index is the degree of the HermiteE polynomial. If `c` is a 1-D array of coefficients of length `n + 1` and `V` is the array ``V = hermevander(x, n)``, then ``np.dot(V, c)`` and ``hermeval(x, c)`` are the same up to roundoff. This equivalence is useful both for least squares fitting and for the evaluation of a large number of HermiteE series of the same degree and sample points. Parameters ---------- x : array_like Array of points. The dtype is converted to float64 or complex128 depending on whether any of the elements are complex. If `x` is scalar it is converted to a 1-D array. deg : int Degree of the resulting matrix. Returns ------- vander : ndarray The pseudo-Vandermonde matrix. The shape of the returned matrix is ``x.shape + (deg + 1,)``, where The last index is the degree of the corresponding HermiteE polynomial. The dtype will be the same as the converted `x`. Examples -------- >>> from numpy.polynomial.hermite_e import hermevander >>> x = np.array([-1, 0, 1]) >>> hermevander(x, 3) array([[ 1., -1., 0., 2.], [ 1., 0., -1., -0.], [ 1., 1., 0., -2.]]) """ ideg = int(deg) if ideg != deg: raise ValueError("deg must be integer") if ideg < 0: raise ValueError("deg must be non-negative") x = np.array(x, copy=0, ndmin=1) + 0.0 dims = (ideg + 1,) + x.shape dtyp = x.dtype v = np.empty(dims, dtype=dtyp) v[0] = x*0 + 1 if ideg > 0 : v[1] = x for i in range(2, ideg + 1) : v[i] = (v[i-1]*x - v[i-2]*(i - 1)) return np.rollaxis(v, 0, v.ndim)
[ "def", "hermevander", "(", "x", ",", "deg", ")", ":", "ideg", "=", "int", "(", "deg", ")", "if", "ideg", "!=", "deg", ":", "raise", "ValueError", "(", "\"deg must be integer\"", ")", "if", "ideg", "<", "0", ":", "raise", "ValueError", "(", "\"deg must ...
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/polynomial/hermite_e.py#L1173-L1232
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/profile.py
python
runctx
(statement, globals, locals, filename=None, sort=-1)
return _Utils(Profile).runctx(statement, globals, locals, filename, sort)
Run statement under profiler, supplying your own globals and locals, optionally saving results in filename. statement and filename have the same semantics as profile.run
Run statement under profiler, supplying your own globals and locals, optionally saving results in filename.
[ "Run", "statement", "under", "profiler", "supplying", "your", "own", "globals", "and", "locals", "optionally", "saving", "results", "in", "filename", "." ]
def runctx(statement, globals, locals, filename=None, sort=-1): """Run statement under profiler, supplying your own globals and locals, optionally saving results in filename. statement and filename have the same semantics as profile.run """ return _Utils(Profile).runctx(statement, globals, locals, filename, sort)
[ "def", "runctx", "(", "statement", ",", "globals", ",", "locals", ",", "filename", "=", "None", ",", "sort", "=", "-", "1", ")", ":", "return", "_Utils", "(", "Profile", ")", ".", "runctx", "(", "statement", ",", "globals", ",", "locals", ",", "filen...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/profile.py#L93-L99
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/ttk.py
python
_convert_stringval
(value)
return value
Converts a value to, hopefully, a more appropriate Python object.
Converts a value to, hopefully, a more appropriate Python object.
[ "Converts", "a", "value", "to", "hopefully", "a", "more", "appropriate", "Python", "object", "." ]
def _convert_stringval(value): """Converts a value to, hopefully, a more appropriate Python object.""" value = unicode(value) try: value = int(value) except (ValueError, TypeError): pass return value
[ "def", "_convert_stringval", "(", "value", ")", ":", "value", "=", "unicode", "(", "value", ")", "try", ":", "value", "=", "int", "(", "value", ")", "except", "(", "ValueError", ",", "TypeError", ")", ":", "pass", "return", "value" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/ttk.py#L320-L328
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py2/scipy/_lib/_tmpdirs.py
python
tempdir
()
Create and return a temporary directory. This has the same behavior as mkdtemp but can be used as a context manager. Upon exiting the context, the directory and everything contained in it are removed. Examples -------- >>> import os >>> with tempdir() as tmpdir: ... fname = os.path.join(tmpdir, 'example_file.txt') ... with open(fname, 'wt') as fobj: ... _ = fobj.write('a string\\n') >>> os.path.exists(tmpdir) False
Create and return a temporary directory. This has the same behavior as mkdtemp but can be used as a context manager.
[ "Create", "and", "return", "a", "temporary", "directory", ".", "This", "has", "the", "same", "behavior", "as", "mkdtemp", "but", "can", "be", "used", "as", "a", "context", "manager", "." ]
def tempdir(): """Create and return a temporary directory. This has the same behavior as mkdtemp but can be used as a context manager. Upon exiting the context, the directory and everything contained in it are removed. Examples -------- >>> import os >>> with tempdir() as tmpdir: ... fname = os.path.join(tmpdir, 'example_file.txt') ... with open(fname, 'wt') as fobj: ... _ = fobj.write('a string\\n') >>> os.path.exists(tmpdir) False """ d = mkdtemp() yield d rmtree(d)
[ "def", "tempdir", "(", ")", ":", "d", "=", "mkdtemp", "(", ")", "yield", "d", "rmtree", "(", "d", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/_lib/_tmpdirs.py#L11-L30
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
torch/storage.py
python
TypedStorage.int
(self)
return self._to(torch.int)
Casts this storage to int type
Casts this storage to int type
[ "Casts", "this", "storage", "to", "int", "type" ]
def int(self): """Casts this storage to int type""" return self._to(torch.int)
[ "def", "int", "(", "self", ")", ":", "return", "self", ".", "_to", "(", "torch", ".", "int", ")" ]
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/storage.py#L563-L565
tomahawk-player/tomahawk-resolvers
7f827bbe410ccfdb0446f7d6a91acc2199c9cc8d
archive/spotify/breakpad/third_party/protobuf/protobuf/python/ez_setup.py
python
update_md5
(filenames)
Update our built-in md5 registry
Update our built-in md5 registry
[ "Update", "our", "built", "-", "in", "md5", "registry" ]
def update_md5(filenames): """Update our built-in md5 registry""" import re for name in filenames: base = os.path.basename(name) f = open(name,'rb') md5_data[base] = md5(f.read()).hexdigest() f.close() data = [" %r: %r,\n" % it for it in md5_data.items()] data.sort() repl = "".join(data) import inspect srcfile = inspect.getsourcefile(sys.modules[__name__]) f = open(srcfile, 'rb'); src = f.read(); f.close() match = re.search("\nmd5_data = {\n([^}]+)}", src) if not match: print >>sys.stderr, "Internal error!" sys.exit(2) src = src[:match.start(1)] + repl + src[match.end(1):] f = open(srcfile,'w') f.write(src) f.close()
[ "def", "update_md5", "(", "filenames", ")", ":", "import", "re", "for", "name", "in", "filenames", ":", "base", "=", "os", ".", "path", ".", "basename", "(", "name", ")", "f", "=", "open", "(", "name", ",", "'rb'", ")", "md5_data", "[", "base", "]"...
https://github.com/tomahawk-player/tomahawk-resolvers/blob/7f827bbe410ccfdb0446f7d6a91acc2199c9cc8d/archive/spotify/breakpad/third_party/protobuf/protobuf/python/ez_setup.py#L249-L276
lzhang10/maxent
3560c94b737d4272ed86de529e50d823200e6d8e
python/maxent/cmaxent.py
python
MaxentModel.eval_all
(self, context)
return _cmaxent.MaxentModel_eval_all(self, context)
r""" eval_all(self, context) -> std::vector< pair< maxent::MaxentModel::outcome_type,double > > Evaluates a context, return the conditional distribution of given context as a list of (outcome, probability) pairs. This method calculates the conditional probability p(y|x) for each possible outcome tag y. Parameters: context A list of string names of the contextual predicates which are to be evaluated together. Feature values are assumed to be 1.0 if omitted.
r""" eval_all(self, context) -> std::vector< pair< maxent::MaxentModel::outcome_type,double > >
[ "r", "eval_all", "(", "self", "context", ")", "-", ">", "std", "::", "vector<", "pair<", "maxent", "::", "MaxentModel", "::", "outcome_type", "double", ">", ">" ]
def eval_all(self, context): r""" eval_all(self, context) -> std::vector< pair< maxent::MaxentModel::outcome_type,double > > Evaluates a context, return the conditional distribution of given context as a list of (outcome, probability) pairs. This method calculates the conditional probability p(y|x) for each possible outcome tag y. Parameters: context A list of string names of the contextual predicates which are to be evaluated together. Feature values are assumed to be 1.0 if omitted. """ return _cmaxent.MaxentModel_eval_all(self, context)
[ "def", "eval_all", "(", "self", ",", "context", ")", ":", "return", "_cmaxent", ".", "MaxentModel_eval_all", "(", "self", ",", "context", ")" ]
https://github.com/lzhang10/maxent/blob/3560c94b737d4272ed86de529e50d823200e6d8e/python/maxent/cmaxent.py#L219-L234
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/aui.py
python
AuiManager.RestorePane
(*args, **kwargs)
return _aui.AuiManager_RestorePane(*args, **kwargs)
RestorePane(self, AuiPaneInfo paneInfo)
RestorePane(self, AuiPaneInfo paneInfo)
[ "RestorePane", "(", "self", "AuiPaneInfo", "paneInfo", ")" ]
def RestorePane(*args, **kwargs): """RestorePane(self, AuiPaneInfo paneInfo)""" return _aui.AuiManager_RestorePane(*args, **kwargs)
[ "def", "RestorePane", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_aui", ".", "AuiManager_RestorePane", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/aui.py#L695-L697
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
torch/distributions/distribution.py
python
Distribution.support
(self)
Returns a :class:`~torch.distributions.constraints.Constraint` object representing this distribution's support.
Returns a :class:`~torch.distributions.constraints.Constraint` object representing this distribution's support.
[ "Returns", "a", ":", "class", ":", "~torch", ".", "distributions", ".", "constraints", ".", "Constraint", "object", "representing", "this", "distribution", "s", "support", "." ]
def support(self) -> Optional[Any]: """ Returns a :class:`~torch.distributions.constraints.Constraint` object representing this distribution's support. """ raise NotImplementedError
[ "def", "support", "(", "self", ")", "->", "Optional", "[", "Any", "]", ":", "raise", "NotImplementedError" ]
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/distributions/distribution.py#L110-L115
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_controls.py
python
TreeCtrl.CollapseAndReset
(*args, **kwargs)
return _controls_.TreeCtrl_CollapseAndReset(*args, **kwargs)
CollapseAndReset(self, TreeItemId item)
CollapseAndReset(self, TreeItemId item)
[ "CollapseAndReset", "(", "self", "TreeItemId", "item", ")" ]
def CollapseAndReset(*args, **kwargs): """CollapseAndReset(self, TreeItemId item)""" return _controls_.TreeCtrl_CollapseAndReset(*args, **kwargs)
[ "def", "CollapseAndReset", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "TreeCtrl_CollapseAndReset", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_controls.py#L5494-L5496
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Code/Tools/waf-1.7.13/waflib/Configure.py
python
ConfigurationContext.err_handler
(self, fun, error)
Error handler for the configuration tests, the default is to let the exception raise :param fun: configuration test :type fun: method :param error: exception :type error: exception
Error handler for the configuration tests, the default is to let the exception raise
[ "Error", "handler", "for", "the", "configuration", "tests", "the", "default", "is", "to", "let", "the", "exception", "raise" ]
def err_handler(self, fun, error): """ Error handler for the configuration tests, the default is to let the exception raise :param fun: configuration test :type fun: method :param error: exception :type error: exception """ pass
[ "def", "err_handler", "(", "self", ",", "fun", ",", "error", ")", ":", "pass" ]
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Code/Tools/waf-1.7.13/waflib/Configure.py#L379-L388
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
current/tools/inspector_protocol/jinja2/lexer.py
python
Lexer.tokenize
(self, source, name=None, filename=None, state=None)
return TokenStream(self.wrap(stream, name, filename), name, filename)
Calls tokeniter + tokenize and wraps it in a token stream.
Calls tokeniter + tokenize and wraps it in a token stream.
[ "Calls", "tokeniter", "+", "tokenize", "and", "wraps", "it", "in", "a", "token", "stream", "." ]
def tokenize(self, source, name=None, filename=None, state=None): """Calls tokeniter + tokenize and wraps it in a token stream. """ stream = self.tokeniter(source, name, filename, state) return TokenStream(self.wrap(stream, name, filename), name, filename)
[ "def", "tokenize", "(", "self", ",", "source", ",", "name", "=", "None", ",", "filename", "=", "None", ",", "state", "=", "None", ")", ":", "stream", "=", "self", ".", "tokeniter", "(", "source", ",", "name", ",", "filename", ",", "state", ")", "re...
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/current/tools/inspector_protocol/jinja2/lexer.py#L552-L556
psi4/psi4
be533f7f426b6ccc263904e55122899b16663395
psi4/driver/qcdb/libmintsmolecule.py
python
LibmintsMolecule.update_geometry
(self)
Updates the geometry, by (re)interpreting the string used to create the molecule, and the current values of the variables. The atoms list is cleared, and then rebuilt by this routine. This function must be called after first instantiation of Molecule. >>> H2 = qcdb.Molecule("H\\nH 1 0.74\\n") >>> print(H2.natom()) 0 >>> H2.update_geometry() >>> print(H2.natom()) 2
Updates the geometry, by (re)interpreting the string used to create the molecule, and the current values of the variables. The atoms list is cleared, and then rebuilt by this routine. This function must be called after first instantiation of Molecule.
[ "Updates", "the", "geometry", "by", "(", "re", ")", "interpreting", "the", "string", "used", "to", "create", "the", "molecule", "and", "the", "current", "values", "of", "the", "variables", ".", "The", "atoms", "list", "is", "cleared", "and", "then", "rebui...
def update_geometry(self): """Updates the geometry, by (re)interpreting the string used to create the molecule, and the current values of the variables. The atoms list is cleared, and then rebuilt by this routine. This function must be called after first instantiation of Molecule. >>> H2 = qcdb.Molecule("H\\nH 1 0.74\\n") >>> print(H2.natom()) 0 >>> H2.update_geometry() >>> print(H2.natom()) 2 """ if self.nallatom() == 0: print("Warning: There are no quantum mechanical atoms in this molecule.") # Idempotence condition if self.lock_frame: return #print("beginning update_geometry:") #self.print_full() if self.PYreinterpret_coordentries: self.reinterpret_coordentries() #print("after reinterpret_coordentries:") #self.print_full() if self.PYmove_to_com: self.move_to_com() #print("after com:") #self.print_full() self.wholegeom = self.geometry(np_out=True) # If the no_reorient command was given, don't reorient if not self.PYfix_orientation: # Now we need to rotate the geometry to its symmetry frame # to align the axes correctly for the point group # symmetry_frame looks for the highest point group so that we can align # the molecule according to its actual symmetry, rather than the symmetry # the the user might have provided. frame = self.symmetry_frame() self.rotate_full(frame) #print("after rotate:") #self.print_full() self.wholegeom = self.geometry(np_out=True) # Recompute point group of the molecule, so the symmetry info is updated to the new frame self.set_point_group(self.find_point_group()) self.set_full_point_group() self.wholegeom = self.geometry(np_out=True) # Disabling symmetrize for now if orientation is fixed, as it is not # correct. We may want to fix this in the future, but in some cases of # finite-differences the set geometry is not totally symmetric anyway. # Symmetrize the molecule to remove any noise self.symmetrize() #print("after symmetry:") #self.print_full() self.wholegeom = None self.lock_frame = True
[ "def", "update_geometry", "(", "self", ")", ":", "if", "self", ".", "nallatom", "(", ")", "==", "0", ":", "print", "(", "\"Warning: There are no quantum mechanical atoms in this molecule.\"", ")", "# Idempotence condition", "if", "self", ".", "lock_frame", ":", "ret...
https://github.com/psi4/psi4/blob/be533f7f426b6ccc263904e55122899b16663395/psi4/driver/qcdb/libmintsmolecule.py#L1521-L1582
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Editor/Python/windows/Lib/site-packages/setuptools/command/setopt.py
python
config_file
(kind="local")
Get the filename of the distutils, local, global, or per-user config `kind` must be one of "local", "global", or "user"
Get the filename of the distutils, local, global, or per-user config
[ "Get", "the", "filename", "of", "the", "distutils", "local", "global", "or", "per", "-", "user", "config" ]
def config_file(kind="local"): """Get the filename of the distutils, local, global, or per-user config `kind` must be one of "local", "global", or "user" """ if kind == 'local': return 'setup.cfg' if kind == 'global': return os.path.join( os.path.dirname(distutils.__file__), 'distutils.cfg' ) if kind == 'user': dot = os.name == 'posix' and '.' or '' return os.path.expanduser(convert_path("~/%spydistutils.cfg" % dot)) raise ValueError( "config_file() type must be 'local', 'global', or 'user'", kind )
[ "def", "config_file", "(", "kind", "=", "\"local\"", ")", ":", "if", "kind", "==", "'local'", ":", "return", "'setup.cfg'", "if", "kind", "==", "'global'", ":", "return", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "d...
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/setuptools/command/setopt.py#L14-L30
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/tornado/tornado-6/tornado/web.py
python
RequestHandler.get_argument
( # noqa: F811 self, name: str, default: Union[None, str, _ArgDefaultMarker] = _ARG_DEFAULT, strip: bool = True, )
return self._get_argument(name, default, self.request.arguments, strip)
Returns the value of the argument with the given name. If default is not provided, the argument is considered to be required, and we raise a `MissingArgumentError` if it is missing. If the argument appears in the request more than once, we return the last value. This method searches both the query and body arguments.
Returns the value of the argument with the given name.
[ "Returns", "the", "value", "of", "the", "argument", "with", "the", "given", "name", "." ]
def get_argument( # noqa: F811 self, name: str, default: Union[None, str, _ArgDefaultMarker] = _ARG_DEFAULT, strip: bool = True, ) -> Optional[str]: """Returns the value of the argument with the given name. If default is not provided, the argument is considered to be required, and we raise a `MissingArgumentError` if it is missing. If the argument appears in the request more than once, we return the last value. This method searches both the query and body arguments. """ return self._get_argument(name, default, self.request.arguments, strip)
[ "def", "get_argument", "(", "# noqa: F811", "self", ",", "name", ":", "str", ",", "default", ":", "Union", "[", "None", ",", "str", ",", "_ArgDefaultMarker", "]", "=", "_ARG_DEFAULT", ",", "strip", ":", "bool", "=", "True", ",", ")", "->", "Optional", ...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/tornado/tornado-6/tornado/web.py#L439-L455
libornovax/master_thesis_code
6eca474ed3cae673afde010caef338cf7349f839
scripts/compute_pr_curve.py
python
parse_arguments
()
return args
Parse input options of the script.
Parse input options of the script.
[ "Parse", "input", "options", "of", "the", "script", "." ]
def parse_arguments(): """ Parse input options of the script. """ parser = argparse.ArgumentParser(description='Plot the precision/recall curve.') parser.add_argument('path_gt', metavar='path_gt', type=str, help='Path to the BBTXT ground truth file') parser.add_argument('gt_mapping', metavar='gt_mapping', type=str, help='Label mapping of the ground truth BBTXT file. One of ' \ + str(LMM.available_mappings())) parser.add_argument('path_detections', metavar='path_detections', type=str, help='Path to the BBTXT file with detections that is to be evaluated') parser.add_argument('detections_mapping', metavar='detections_mapping', type=str, help='Label mapping of the detections BBTXT file. One of ' \ + str(LMM.available_mappings())) parser.add_argument('path_out', metavar='path_out', type=str, help='Path to the output file (without extension) - extensions will be ' \ 'added automatically because more files will be generated') parser.add_argument('--iou', type=float, default=0.5, help='Minimum intersection over union (IOU) for a detection to be counted' \ ' as a true positive') parser.add_argument('--title', type=str, default='', help='Title of the plot') args = parser.parse_args() if not check_path(args.path_detections) or not check_path(args.path_gt): parser.print_help() exit(1) if args.iou <= 0.0 or args.iou > 1.0: print('ERROR: Invalid number for IOU "%f"! Must be in (0,1].'%(args.iou)) exit(1) return args
[ "def", "parse_arguments", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'Plot the precision/recall curve.'", ")", "parser", ".", "add_argument", "(", "'path_gt'", ",", "metavar", "=", "'path_gt'", ",", "type", "=", "s...
https://github.com/libornovax/master_thesis_code/blob/6eca474ed3cae673afde010caef338cf7349f839/scripts/compute_pr_curve.py#L375-L409
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_windows.py
python
PreviewFrame.CreateControlBar
(*args, **kwargs)
return _windows_.PreviewFrame_CreateControlBar(*args, **kwargs)
CreateControlBar(self)
CreateControlBar(self)
[ "CreateControlBar", "(", "self", ")" ]
def CreateControlBar(*args, **kwargs): """CreateControlBar(self)""" return _windows_.PreviewFrame_CreateControlBar(*args, **kwargs)
[ "def", "CreateControlBar", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_windows_", ".", "PreviewFrame_CreateControlBar", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_windows.py#L5489-L5491
LiquidPlayer/LiquidCore
9405979363f2353ac9a71ad8ab59685dd7f919c9
deps/node-10.15.3/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/ninja.py
python
NinjaWriter.WriteActionsRulesCopies
(self, spec, extra_sources, prebuild, mac_bundle_depends)
return stamp
Write out the Actions, Rules, and Copies steps. Return a path representing the outputs of these steps.
Write out the Actions, Rules, and Copies steps. Return a path representing the outputs of these steps.
[ "Write", "out", "the", "Actions", "Rules", "and", "Copies", "steps", ".", "Return", "a", "path", "representing", "the", "outputs", "of", "these", "steps", "." ]
def WriteActionsRulesCopies(self, spec, extra_sources, prebuild, mac_bundle_depends): """Write out the Actions, Rules, and Copies steps. Return a path representing the outputs of these steps.""" outputs = [] if self.is_mac_bundle: mac_bundle_resources = spec.get('mac_bundle_resources', [])[:] else: mac_bundle_resources = [] extra_mac_bundle_resources = [] if 'actions' in spec: outputs += self.WriteActions(spec['actions'], extra_sources, prebuild, extra_mac_bundle_resources) if 'rules' in spec: outputs += self.WriteRules(spec['rules'], extra_sources, prebuild, mac_bundle_resources, extra_mac_bundle_resources) if 'copies' in spec: outputs += self.WriteCopies(spec['copies'], prebuild, mac_bundle_depends) if 'sources' in spec and self.flavor == 'win': outputs += self.WriteWinIdlFiles(spec, prebuild) stamp = self.WriteCollapsedDependencies('actions_rules_copies', outputs) if self.is_mac_bundle: xcassets = self.WriteMacBundleResources( extra_mac_bundle_resources + mac_bundle_resources, mac_bundle_depends) partial_info_plist = self.WriteMacXCassets(xcassets, mac_bundle_depends) self.WriteMacInfoPlist(partial_info_plist, mac_bundle_depends) return stamp
[ "def", "WriteActionsRulesCopies", "(", "self", ",", "spec", ",", "extra_sources", ",", "prebuild", ",", "mac_bundle_depends", ")", ":", "outputs", "=", "[", "]", "if", "self", ".", "is_mac_bundle", ":", "mac_bundle_resources", "=", "spec", ".", "get", "(", "...
https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/ninja.py#L538-L570
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/fileinput.py
python
lineno
()
return _state.lineno()
Return the cumulative line number of the line that has just been read. Before the first line has been read, returns 0. After the last line of the last file has been read, returns the line number of that line.
Return the cumulative line number of the line that has just been read. Before the first line has been read, returns 0. After the last line of the last file has been read, returns the line number of that line.
[ "Return", "the", "cumulative", "line", "number", "of", "the", "line", "that", "has", "just", "been", "read", ".", "Before", "the", "first", "line", "has", "been", "read", "returns", "0", ".", "After", "the", "last", "line", "of", "the", "last", "file", ...
def lineno(): """ Return the cumulative line number of the line that has just been read. Before the first line has been read, returns 0. After the last line of the last file has been read, returns the line number of that line. """ if not _state: raise RuntimeError("no active input()") return _state.lineno()
[ "def", "lineno", "(", ")", ":", "if", "not", "_state", ":", "raise", "RuntimeError", "(", "\"no active input()\"", ")", "return", "_state", ".", "lineno", "(", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/fileinput.py#L128-L136
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/polynomial/polyutils.py
python
getdomain
(x)
Return a domain suitable for given abscissae. Find a domain suitable for a polynomial or Chebyshev series defined at the values supplied. Parameters ---------- x : array_like 1-d array of abscissae whose domain will be determined. Returns ------- domain : ndarray 1-d array containing two values. If the inputs are complex, then the two returned points are the lower left and upper right corners of the smallest rectangle (aligned with the axes) in the complex plane containing the points `x`. If the inputs are real, then the two points are the ends of the smallest interval containing the points `x`. See Also -------- mapparms, mapdomain Examples -------- >>> from numpy.polynomial import polyutils as pu >>> points = np.arange(4)**2 - 5; points array([-5, -4, -1, 4]) >>> pu.getdomain(points) array([-5., 4.]) >>> c = np.exp(complex(0,1)*np.pi*np.arange(12)/6) # unit circle >>> pu.getdomain(c) array([-1.-1.j, 1.+1.j])
Return a domain suitable for given abscissae.
[ "Return", "a", "domain", "suitable", "for", "given", "abscissae", "." ]
def getdomain(x) : """ Return a domain suitable for given abscissae. Find a domain suitable for a polynomial or Chebyshev series defined at the values supplied. Parameters ---------- x : array_like 1-d array of abscissae whose domain will be determined. Returns ------- domain : ndarray 1-d array containing two values. If the inputs are complex, then the two returned points are the lower left and upper right corners of the smallest rectangle (aligned with the axes) in the complex plane containing the points `x`. If the inputs are real, then the two points are the ends of the smallest interval containing the points `x`. See Also -------- mapparms, mapdomain Examples -------- >>> from numpy.polynomial import polyutils as pu >>> points = np.arange(4)**2 - 5; points array([-5, -4, -1, 4]) >>> pu.getdomain(points) array([-5., 4.]) >>> c = np.exp(complex(0,1)*np.pi*np.arange(12)/6) # unit circle >>> pu.getdomain(c) array([-1.-1.j, 1.+1.j]) """ [x] = as_series([x], trim=False) if x.dtype.char in np.typecodes['Complex'] : rmin, rmax = x.real.min(), x.real.max() imin, imax = x.imag.min(), x.imag.max() return np.array((complex(rmin, imin), complex(rmax, imax))) else : return np.array((x.min(), x.max()))
[ "def", "getdomain", "(", "x", ")", ":", "[", "x", "]", "=", "as_series", "(", "[", "x", "]", ",", "trim", "=", "False", ")", "if", "x", ".", "dtype", ".", "char", "in", "np", ".", "typecodes", "[", "'Complex'", "]", ":", "rmin", ",", "rmax", ...
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/polynomial/polyutils.py#L226-L270
nsnam/ns-3-dev-git
efdb2e21f45c0a87a60b47c547b68fa140a7b686
waf-tools/versioning.py
python
check_git_repo_has_ns3_tags
(self)
return bool(tag)
Determine if the git repository is an ns-3 repository A repository is considered an ns-3 repository if it has at least one tag that matches the regex ns-3*
Determine if the git repository is an ns-3 repository
[ "Determine", "if", "the", "git", "repository", "is", "an", "ns", "-", "3", "repository" ]
def check_git_repo_has_ns3_tags(self): '''Determine if the git repository is an ns-3 repository A repository is considered an ns-3 repository if it has at least one tag that matches the regex ns-3* ''' tag = False cmd = [ 'git', 'describe', '--tags', '--abbrev=0', '--match', 'ns-3.[0-9]*' ] try: out = self.cmd_and_log(cmd, output=Context.STDOUT, quiet=Context.BOTH) tag = out.strip() except Exception: tag = False self.msg('Checking local git repository for ns3 tags', tag) return bool(tag)
[ "def", "check_git_repo_has_ns3_tags", "(", "self", ")", ":", "tag", "=", "False", "cmd", "=", "[", "'git'", ",", "'describe'", ",", "'--tags'", ",", "'--abbrev=0'", ",", "'--match'", ",", "'ns-3.[0-9]*'", "]", "try", ":", "out", "=", "self", ".", "cmd_and_...
https://github.com/nsnam/ns-3-dev-git/blob/efdb2e21f45c0a87a60b47c547b68fa140a7b686/waf-tools/versioning.py#L194-L222
Kitware/ParaView
f760af9124ff4634b23ebbeab95a4f56e0261955
ThirdParty/cinema/paraview/tpl/cinema_python/adaptors/paraview/cinemareader.py
python
FileStoreSpecA.get_objects
(self)
return objects
returns a list of viewable objects in the scene
returns a list of viewable objects in the scene
[ "returns", "a", "list", "of", "viewable", "objects", "in", "the", "scene" ]
def get_objects(self): """returns a list of viewable objects in the scene""" objects = ["Cinema"] return objects
[ "def", "get_objects", "(", "self", ")", ":", "objects", "=", "[", "\"Cinema\"", "]", "return", "objects" ]
https://github.com/Kitware/ParaView/blob/f760af9124ff4634b23ebbeab95a4f56e0261955/ThirdParty/cinema/paraview/tpl/cinema_python/adaptors/paraview/cinemareader.py#L129-L133
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
models/AI-Model-Zoo/caffe-xilinx/scripts/cpp_lint.py
python
CheckComment
(comment, filename, linenum, error)
Checks for common mistakes in TODO comments. Args: comment: The text of the comment from the line in question. filename: The name of the current file. linenum: The number of the line to check. error: The function to call with any errors found.
Checks for common mistakes in TODO comments.
[ "Checks", "for", "common", "mistakes", "in", "TODO", "comments", "." ]
def CheckComment(comment, filename, linenum, error): """Checks for common mistakes in TODO comments. Args: comment: The text of the comment from the line in question. filename: The name of the current file. linenum: The number of the line to check. error: The function to call with any errors found. """ match = _RE_PATTERN_TODO.match(comment) if match: # One whitespace is correct; zero whitespace is handled elsewhere. leading_whitespace = match.group(1) if len(leading_whitespace) > 1: error(filename, linenum, 'whitespace/todo', 2, 'Too many spaces before TODO') username = match.group(2) if not username: error(filename, linenum, 'readability/todo', 2, 'Missing username in TODO; it should look like ' '"// TODO(my_username): Stuff."') middle_whitespace = match.group(3) # Comparisons made explicit for correctness -- pylint: disable=g-explicit-bool-comparison if middle_whitespace != ' ' and middle_whitespace != '': error(filename, linenum, 'whitespace/todo', 2, 'TODO(my_username) should be followed by a space')
[ "def", "CheckComment", "(", "comment", ",", "filename", ",", "linenum", ",", "error", ")", ":", "match", "=", "_RE_PATTERN_TODO", ".", "match", "(", "comment", ")", "if", "match", ":", "# One whitespace is correct; zero whitespace is handled elsewhere.", "leading_whit...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/models/AI-Model-Zoo/caffe-xilinx/scripts/cpp_lint.py#L2457-L2484
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/attr/_make.py
python
attrib
( default=NOTHING, validator=None, repr=True, cmp=None, hash=None, init=True, metadata=None, type=None, converter=None, factory=None, kw_only=False, eq=None, order=None, )
return _CountingAttr( default=default, validator=validator, repr=repr, cmp=None, hash=hash, init=init, converter=converter, metadata=metadata, type=type, kw_only=kw_only, eq=eq, order=order, )
Create a new attribute on a class. .. warning:: Does *not* do anything unless the class is also decorated with `attr.s`! :param default: A value that is used if an ``attrs``-generated ``__init__`` is used and no value is passed while instantiating or the attribute is excluded using ``init=False``. If the value is an instance of `Factory`, its callable will be used to construct a new value (useful for mutable data types like lists or dicts). If a default is not set (or set manually to ``attr.NOTHING``), a value *must* be supplied when instantiating; otherwise a `TypeError` will be raised. The default can also be set using decorator notation as shown below. :type default: Any value :param callable factory: Syntactic sugar for ``default=attr.Factory(callable)``. :param validator: `callable` that is called by ``attrs``-generated ``__init__`` methods after the instance has been initialized. They receive the initialized instance, the `Attribute`, and the passed value. The return value is *not* inspected so the validator has to throw an exception itself. If a ``list`` is passed, its items are treated as validators and must all pass. Validators can be globally disabled and re-enabled using `get_run_validators`. The validator can also be set using decorator notation as shown below. :type validator: ``callable`` or a ``list`` of ``callable``\\ s. :param repr: Include this attribute in the generated ``__repr__`` method. If ``True``, include the attribute; if ``False``, omit it. By default, the built-in ``repr()`` function is used. To override how the attribute value is formatted, pass a ``callable`` that takes a single value and returns a string. Note that the resulting string is used as-is, i.e. it will be used directly *instead* of calling ``repr()`` (the default). :type repr: a ``bool`` or a ``callable`` to use a custom function. :param bool eq: If ``True`` (default), include this attribute in the generated ``__eq__`` and ``__ne__`` methods that check two instances for equality. :param bool order: If ``True`` (default), include this attributes in the generated ``__lt__``, ``__le__``, ``__gt__`` and ``__ge__`` methods. :param bool cmp: Setting to ``True`` is equivalent to setting ``eq=True, order=True``. Deprecated in favor of *eq* and *order*. :param hash: Include this attribute in the generated ``__hash__`` method. If ``None`` (default), mirror *eq*'s value. This is the correct behavior according the Python spec. Setting this value to anything else than ``None`` is *discouraged*. :type hash: ``bool`` or ``None`` :param bool init: Include this attribute in the generated ``__init__`` method. It is possible to set this to ``False`` and set a default value. In that case this attributed is unconditionally initialized with the specified default value or factory. :param callable converter: `callable` that is called by ``attrs``-generated ``__init__`` methods to converter attribute's value to the desired format. It is given the passed-in value, and the returned value will be used as the new value of the attribute. The value is converted before being passed to the validator, if any. :param metadata: An arbitrary mapping, to be used by third-party components. See `extending_metadata`. :param type: The type of the attribute. In Python 3.6 or greater, the preferred method to specify the type is using a variable annotation (see `PEP 526 <https://www.python.org/dev/peps/pep-0526/>`_). This argument is provided for backward compatibility. Regardless of the approach used, the type will be stored on ``Attribute.type``. Please note that ``attrs`` doesn't do anything with this metadata by itself. You can use it as part of your own code or for `static type checking <types>`. :param kw_only: Make this attribute keyword-only (Python 3+) in the generated ``__init__`` (if ``init`` is ``False``, this parameter is ignored). .. versionadded:: 15.2.0 *convert* .. versionadded:: 16.3.0 *metadata* .. versionchanged:: 17.1.0 *validator* can be a ``list`` now. .. versionchanged:: 17.1.0 *hash* is ``None`` and therefore mirrors *eq* by default. .. versionadded:: 17.3.0 *type* .. deprecated:: 17.4.0 *convert* .. versionadded:: 17.4.0 *converter* as a replacement for the deprecated *convert* to achieve consistency with other noun-based arguments. .. versionadded:: 18.1.0 ``factory=f`` is syntactic sugar for ``default=attr.Factory(f)``. .. versionadded:: 18.2.0 *kw_only* .. versionchanged:: 19.2.0 *convert* keyword argument removed .. versionchanged:: 19.2.0 *repr* also accepts a custom callable. .. deprecated:: 19.2.0 *cmp* Removal on or after 2021-06-01. .. versionadded:: 19.2.0 *eq* and *order*
Create a new attribute on a class.
[ "Create", "a", "new", "attribute", "on", "a", "class", "." ]
def attrib( default=NOTHING, validator=None, repr=True, cmp=None, hash=None, init=True, metadata=None, type=None, converter=None, factory=None, kw_only=False, eq=None, order=None, ): """ Create a new attribute on a class. .. warning:: Does *not* do anything unless the class is also decorated with `attr.s`! :param default: A value that is used if an ``attrs``-generated ``__init__`` is used and no value is passed while instantiating or the attribute is excluded using ``init=False``. If the value is an instance of `Factory`, its callable will be used to construct a new value (useful for mutable data types like lists or dicts). If a default is not set (or set manually to ``attr.NOTHING``), a value *must* be supplied when instantiating; otherwise a `TypeError` will be raised. The default can also be set using decorator notation as shown below. :type default: Any value :param callable factory: Syntactic sugar for ``default=attr.Factory(callable)``. :param validator: `callable` that is called by ``attrs``-generated ``__init__`` methods after the instance has been initialized. They receive the initialized instance, the `Attribute`, and the passed value. The return value is *not* inspected so the validator has to throw an exception itself. If a ``list`` is passed, its items are treated as validators and must all pass. Validators can be globally disabled and re-enabled using `get_run_validators`. The validator can also be set using decorator notation as shown below. :type validator: ``callable`` or a ``list`` of ``callable``\\ s. :param repr: Include this attribute in the generated ``__repr__`` method. If ``True``, include the attribute; if ``False``, omit it. By default, the built-in ``repr()`` function is used. To override how the attribute value is formatted, pass a ``callable`` that takes a single value and returns a string. Note that the resulting string is used as-is, i.e. it will be used directly *instead* of calling ``repr()`` (the default). :type repr: a ``bool`` or a ``callable`` to use a custom function. :param bool eq: If ``True`` (default), include this attribute in the generated ``__eq__`` and ``__ne__`` methods that check two instances for equality. :param bool order: If ``True`` (default), include this attributes in the generated ``__lt__``, ``__le__``, ``__gt__`` and ``__ge__`` methods. :param bool cmp: Setting to ``True`` is equivalent to setting ``eq=True, order=True``. Deprecated in favor of *eq* and *order*. :param hash: Include this attribute in the generated ``__hash__`` method. If ``None`` (default), mirror *eq*'s value. This is the correct behavior according the Python spec. Setting this value to anything else than ``None`` is *discouraged*. :type hash: ``bool`` or ``None`` :param bool init: Include this attribute in the generated ``__init__`` method. It is possible to set this to ``False`` and set a default value. In that case this attributed is unconditionally initialized with the specified default value or factory. :param callable converter: `callable` that is called by ``attrs``-generated ``__init__`` methods to converter attribute's value to the desired format. It is given the passed-in value, and the returned value will be used as the new value of the attribute. The value is converted before being passed to the validator, if any. :param metadata: An arbitrary mapping, to be used by third-party components. See `extending_metadata`. :param type: The type of the attribute. In Python 3.6 or greater, the preferred method to specify the type is using a variable annotation (see `PEP 526 <https://www.python.org/dev/peps/pep-0526/>`_). This argument is provided for backward compatibility. Regardless of the approach used, the type will be stored on ``Attribute.type``. Please note that ``attrs`` doesn't do anything with this metadata by itself. You can use it as part of your own code or for `static type checking <types>`. :param kw_only: Make this attribute keyword-only (Python 3+) in the generated ``__init__`` (if ``init`` is ``False``, this parameter is ignored). .. versionadded:: 15.2.0 *convert* .. versionadded:: 16.3.0 *metadata* .. versionchanged:: 17.1.0 *validator* can be a ``list`` now. .. versionchanged:: 17.1.0 *hash* is ``None`` and therefore mirrors *eq* by default. .. versionadded:: 17.3.0 *type* .. deprecated:: 17.4.0 *convert* .. versionadded:: 17.4.0 *converter* as a replacement for the deprecated *convert* to achieve consistency with other noun-based arguments. .. versionadded:: 18.1.0 ``factory=f`` is syntactic sugar for ``default=attr.Factory(f)``. .. versionadded:: 18.2.0 *kw_only* .. versionchanged:: 19.2.0 *convert* keyword argument removed .. versionchanged:: 19.2.0 *repr* also accepts a custom callable. .. deprecated:: 19.2.0 *cmp* Removal on or after 2021-06-01. .. versionadded:: 19.2.0 *eq* and *order* """ eq, order = _determine_eq_order(cmp, eq, order) if hash is not None and hash is not True and hash is not False: raise TypeError( "Invalid value for hash. Must be True, False, or None." ) if factory is not None: if default is not NOTHING: raise ValueError( "The `default` and `factory` arguments are mutually " "exclusive." ) if not callable(factory): raise ValueError("The `factory` argument must be a callable.") default = Factory(factory) if metadata is None: metadata = {} return _CountingAttr( default=default, validator=validator, repr=repr, cmp=None, hash=hash, init=init, converter=converter, metadata=metadata, type=type, kw_only=kw_only, eq=eq, order=order, )
[ "def", "attrib", "(", "default", "=", "NOTHING", ",", "validator", "=", "None", ",", "repr", "=", "True", ",", "cmp", "=", "None", ",", "hash", "=", "None", ",", "init", "=", "True", ",", "metadata", "=", "None", ",", "type", "=", "None", ",", "c...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/attr/_make.py#L73-L228
smartdevicelink/sdl_core
68f082169e0a40fccd9eb0db3c83911c28870f07
tools/infrastructure/api_compare.py
python
dict_to_json
(summary_result)
return json.dumps( summary_result, sort_keys=True, indent=4, separators=(',', ': '))
Function converts python dictionary to json format
Function converts python dictionary to json format
[ "Function", "converts", "python", "dictionary", "to", "json", "format" ]
def dict_to_json(summary_result): """Function converts python dictionary to json format""" return json.dumps( summary_result, sort_keys=True, indent=4, separators=(',', ': '))
[ "def", "dict_to_json", "(", "summary_result", ")", ":", "return", "json", ".", "dumps", "(", "summary_result", ",", "sort_keys", "=", "True", ",", "indent", "=", "4", ",", "separators", "=", "(", "','", ",", "': '", ")", ")" ]
https://github.com/smartdevicelink/sdl_core/blob/68f082169e0a40fccd9eb0db3c83911c28870f07/tools/infrastructure/api_compare.py#L76-L79
hughperkins/tf-coriander
970d3df6c11400ad68405f22b0c42a52374e94ca
tensorflow/contrib/factorization/python/ops/factorization_ops.py
python
WALSModel.update_col_factors
(self, sp_input=None, transpose_input=False)
return self._process_input_helper(False, sp_input=sp_input, transpose_input=transpose_input)
Updates the column factors. Args: sp_input: A SparseTensor representing a subset of columns of the full input. Please refer to comments for update_row_factors for restrictions. transpose_input: If true, the input will be logically transposed and the columns corresponding to the transposed input are updated. Returns: A tuple consisting of the following two elements: new_values: New values for the column factors. update_op: An op that assigns the newly computed values to the column factors.
Updates the column factors.
[ "Updates", "the", "column", "factors", "." ]
def update_col_factors(self, sp_input=None, transpose_input=False): """Updates the column factors. Args: sp_input: A SparseTensor representing a subset of columns of the full input. Please refer to comments for update_row_factors for restrictions. transpose_input: If true, the input will be logically transposed and the columns corresponding to the transposed input are updated. Returns: A tuple consisting of the following two elements: new_values: New values for the column factors. update_op: An op that assigns the newly computed values to the column factors. """ return self._process_input_helper(False, sp_input=sp_input, transpose_input=transpose_input)
[ "def", "update_col_factors", "(", "self", ",", "sp_input", "=", "None", ",", "transpose_input", "=", "False", ")", ":", "return", "self", ".", "_process_input_helper", "(", "False", ",", "sp_input", "=", "sp_input", ",", "transpose_input", "=", "transpose_input"...
https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/contrib/factorization/python/ops/factorization_ops.py#L622-L639
OAID/Caffe-HRT
aae71e498ab842c6f92bcc23fc668423615a4d65
python/caffe/net_spec.py
python
to_proto
(*tops)
return net
Generate a NetParameter that contains all layers needed to compute all arguments.
Generate a NetParameter that contains all layers needed to compute all arguments.
[ "Generate", "a", "NetParameter", "that", "contains", "all", "layers", "needed", "to", "compute", "all", "arguments", "." ]
def to_proto(*tops): """Generate a NetParameter that contains all layers needed to compute all arguments.""" layers = OrderedDict() autonames = Counter() for top in tops: top.fn._to_proto(layers, {}, autonames) net = caffe_pb2.NetParameter() net.layer.extend(layers.values()) return net
[ "def", "to_proto", "(", "*", "tops", ")", ":", "layers", "=", "OrderedDict", "(", ")", "autonames", "=", "Counter", "(", ")", "for", "top", "in", "tops", ":", "top", ".", "fn", ".", "_to_proto", "(", "layers", ",", "{", "}", ",", "autonames", ")", ...
https://github.com/OAID/Caffe-HRT/blob/aae71e498ab842c6f92bcc23fc668423615a4d65/python/caffe/net_spec.py#L43-L53
LiquidPlayer/LiquidCore
9405979363f2353ac9a71ad8ab59685dd7f919c9
deps/node-10.15.3/tools/gyp/pylib/gyp/generator/ninja.py
python
Define
(d, flavor)
return QuoteShellArgument(ninja_syntax.escape('-D' + d), flavor)
Takes a preprocessor define and returns a -D parameter that's ninja- and shell-escaped.
Takes a preprocessor define and returns a -D parameter that's ninja- and shell-escaped.
[ "Takes", "a", "preprocessor", "define", "and", "returns", "a", "-", "D", "parameter", "that", "s", "ninja", "-", "and", "shell", "-", "escaped", "." ]
def Define(d, flavor): """Takes a preprocessor define and returns a -D parameter that's ninja- and shell-escaped.""" if flavor == 'win': # cl.exe replaces literal # characters with = in preprocesor definitions for # some reason. Octal-encode to work around that. d = d.replace('#', '\\%03o' % ord('#')) return QuoteShellArgument(ninja_syntax.escape('-D' + d), flavor)
[ "def", "Define", "(", "d", ",", "flavor", ")", ":", "if", "flavor", "==", "'win'", ":", "# cl.exe replaces literal # characters with = in preprocesor definitions for", "# some reason. Octal-encode to work around that.", "d", "=", "d", ".", "replace", "(", "'#'", ",", "'...
https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/tools/gyp/pylib/gyp/generator/ninja.py#L85-L92
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/urllib/request.py
python
_parse_proxy
(proxy)
return scheme, user, password, hostport
Return (scheme, user, password, host/port) given a URL or an authority. If a URL is supplied, it must have an authority (host:port) component. According to RFC 3986, having an authority component means the URL must have two slashes after the scheme.
Return (scheme, user, password, host/port) given a URL or an authority.
[ "Return", "(", "scheme", "user", "password", "host", "/", "port", ")", "given", "a", "URL", "or", "an", "authority", "." ]
def _parse_proxy(proxy): """Return (scheme, user, password, host/port) given a URL or an authority. If a URL is supplied, it must have an authority (host:port) component. According to RFC 3986, having an authority component means the URL must have two slashes after the scheme. """ scheme, r_scheme = splittype(proxy) if not r_scheme.startswith("/"): # authority scheme = None authority = proxy else: # URL if not r_scheme.startswith("//"): raise ValueError("proxy URL with no authority: %r" % proxy) # We have an authority, so for RFC 3986-compliant URLs (by ss 3. # and 3.3.), path is empty or starts with '/' end = r_scheme.find("/", 2) if end == -1: end = None authority = r_scheme[2:end] userinfo, hostport = splituser(authority) if userinfo is not None: user, password = splitpasswd(userinfo) else: user = password = None return scheme, user, password, hostport
[ "def", "_parse_proxy", "(", "proxy", ")", ":", "scheme", ",", "r_scheme", "=", "splittype", "(", "proxy", ")", "if", "not", "r_scheme", ".", "startswith", "(", "\"/\"", ")", ":", "# authority", "scheme", "=", "None", "authority", "=", "proxy", "else", ":...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/urllib/request.py#L764-L791
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/ogl/_basic.py
python
Shape.AddText
(self, string)
Add a line of text to the shape's default text region.
Add a line of text to the shape's default text region.
[ "Add", "a", "line", "of", "text", "to", "the", "shape", "s", "default", "text", "region", "." ]
def AddText(self, string): """Add a line of text to the shape's default text region.""" if not self._regions: return region = self._regions[0] #region.ClearText() new_line = ShapeTextLine(0, 0, string) text = region.GetFormattedText() text.append(new_line) self._formatted = False
[ "def", "AddText", "(", "self", ",", "string", ")", ":", "if", "not", "self", ".", "_regions", ":", "return", "region", "=", "self", ".", "_regions", "[", "0", "]", "#region.ClearText()", "new_line", "=", "ShapeTextLine", "(", "0", ",", "0", ",", "strin...
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/ogl/_basic.py#L1190-L1201
hfinkel/llvm-project-cxxjit
91084ef018240bbb8e24235ff5cd8c355a9c1a1e
compiler-rt/lib/sanitizer_common/scripts/cpplint.py
python
UpdateIncludeState
(filename, include_state, io=codecs)
return True
Fill up the include_state with new includes found from the file. Args: filename: the name of the header to read. include_state: an _IncludeState instance in which the headers are inserted. io: The io factory to use to read the file. Provided for testability. Returns: True if a header was successfully added. False otherwise.
Fill up the include_state with new includes found from the file.
[ "Fill", "up", "the", "include_state", "with", "new", "includes", "found", "from", "the", "file", "." ]
def UpdateIncludeState(filename, include_state, io=codecs): """Fill up the include_state with new includes found from the file. Args: filename: the name of the header to read. include_state: an _IncludeState instance in which the headers are inserted. io: The io factory to use to read the file. Provided for testability. Returns: True if a header was successfully added. False otherwise. """ headerfile = None try: headerfile = io.open(filename, 'r', 'utf8', 'replace') except IOError: return False linenum = 0 for line in headerfile: linenum += 1 clean_line = CleanseComments(line) match = _RE_PATTERN_INCLUDE.search(clean_line) if match: include = match.group(2) # The value formatting is cute, but not really used right now. # What matters here is that the key is in include_state. include_state.setdefault(include, '%s:%d' % (filename, linenum)) return True
[ "def", "UpdateIncludeState", "(", "filename", ",", "include_state", ",", "io", "=", "codecs", ")", ":", "headerfile", "=", "None", "try", ":", "headerfile", "=", "io", ".", "open", "(", "filename", ",", "'r'", ",", "'utf8'", ",", "'replace'", ")", "excep...
https://github.com/hfinkel/llvm-project-cxxjit/blob/91084ef018240bbb8e24235ff5cd8c355a9c1a1e/compiler-rt/lib/sanitizer_common/scripts/cpplint.py#L3628-L3654
cyberbotics/webots
af7fa7d68dcf7b4550f1f2e132092b41e83698fc
projects/samples/robotbenchmark/square_path/controllers/square_path_advanced/square_path_advanced.py
python
setMotors
(speed, rotation)
Set the velocity value of both wheels. If rotation is false, both wheels will have the same velocity set, which will make the robot go straight. Otherwise, the left wheel will be set with the opposite value, making the robot turn without changing position.
Set the velocity value of both wheels.
[ "Set", "the", "velocity", "value", "of", "both", "wheels", "." ]
def setMotors(speed, rotation): """ Set the velocity value of both wheels. If rotation is false, both wheels will have the same velocity set, which will make the robot go straight. Otherwise, the left wheel will be set with the opposite value, making the robot turn without changing position. """ leftWheel.setVelocity(-speed if rotation else speed) rightWheel.setVelocity(speed)
[ "def", "setMotors", "(", "speed", ",", "rotation", ")", ":", "leftWheel", ".", "setVelocity", "(", "-", "speed", "if", "rotation", "else", "speed", ")", "rightWheel", ".", "setVelocity", "(", "speed", ")" ]
https://github.com/cyberbotics/webots/blob/af7fa7d68dcf7b4550f1f2e132092b41e83698fc/projects/samples/robotbenchmark/square_path/controllers/square_path_advanced/square_path_advanced.py#L43-L53
manutdzou/KITTI_SSD
5b620c2f291d36a0fe14489214f22a992f173f44
python/caffe/draw.py
python
get_edge_label
(layer)
return edge_label
Define edge label based on layer type.
Define edge label based on layer type.
[ "Define", "edge", "label", "based", "on", "layer", "type", "." ]
def get_edge_label(layer): """Define edge label based on layer type. """ if layer.type == 'Data': edge_label = 'Batch ' + str(layer.data_param.batch_size) elif layer.type == 'Convolution' or layer.type == 'Deconvolution': edge_label = str(layer.convolution_param.num_output) elif layer.type == 'InnerProduct': edge_label = str(layer.inner_product_param.num_output) else: edge_label = '""' return edge_label
[ "def", "get_edge_label", "(", "layer", ")", ":", "if", "layer", ".", "type", "==", "'Data'", ":", "edge_label", "=", "'Batch '", "+", "str", "(", "layer", ".", "data_param", ".", "batch_size", ")", "elif", "layer", ".", "type", "==", "'Convolution'", "or...
https://github.com/manutdzou/KITTI_SSD/blob/5b620c2f291d36a0fe14489214f22a992f173f44/python/caffe/draw.py#L46-L59
gnuradio/gnuradio
09c3c4fa4bfb1a02caac74cb5334dfe065391e3b
gr-fft/python/fft/logpwrfft.py
python
_logpwrfft_base.set_average
(self, average)
Set the averaging filter on/off. Args: average: true to set averaging on
Set the averaging filter on/off.
[ "Set", "the", "averaging", "filter", "on", "/", "off", "." ]
def set_average(self, average): """ Set the averaging filter on/off. Args: average: true to set averaging on """ self._average = average if self._average: self._avg.set_taps(self._avg_alpha) else: self._avg.set_taps(1.0)
[ "def", "set_average", "(", "self", ",", "average", ")", ":", "self", ".", "_average", "=", "average", "if", "self", ".", "_average", ":", "self", ".", "_avg", ".", "set_taps", "(", "self", ".", "_avg_alpha", ")", "else", ":", "self", ".", "_avg", "."...
https://github.com/gnuradio/gnuradio/blob/09c3c4fa4bfb1a02caac74cb5334dfe065391e3b/gr-fft/python/fft/logpwrfft.py#L103-L114
H-uru/Plasma
c2140ea046e82e9c199e257a7f2e7edb42602871
Scripts/Python/tldnPwrTwrPeriscope.py
python
tldnPwrTwrPeriscope.AvatarPage
(self, avObj, pageIn, lastOut)
reset scope accessibility if scope user quits or crashes
reset scope accessibility if scope user quits or crashes
[ "reset", "scope", "accessibility", "if", "scope", "user", "quits", "or", "crashes" ]
def AvatarPage(self, avObj, pageIn, lastOut): "reset scope accessibility if scope user quits or crashes" if pageIn: return avID = PtGetClientIDFromAvatarKey(avObj.getKey()) PtDebugPrint("tldnPwrTwrPeriscope.AvatarPage(): Client ID %d paging out" % (avID)) PtDebugPrint("tldnPwrTwrPeriscope.AvatarPage(): Periscope operator is client id %d" % (self.SDL["OperatorID"][0])) if avID == self.SDL["OperatorID"][0]: Activate.enable() self.SDL["OperatorID"] = (-1,) self.SDL["boolOperated"] = (0,) PtDebugPrint("tldnPwrTwrPeriscope.AvatarPage(): periscope operator paged out, reenabled periscope.") PtDebugPrint("tldnPwrTwrPeriscope.AvatarPage(): OperatorID=%d, boolOperated=%d" % (self.SDL["OperatorID"][0],self.SDL["boolOperated"][0])) else: return
[ "def", "AvatarPage", "(", "self", ",", "avObj", ",", "pageIn", ",", "lastOut", ")", ":", "if", "pageIn", ":", "return", "avID", "=", "PtGetClientIDFromAvatarKey", "(", "avObj", ".", "getKey", "(", ")", ")", "PtDebugPrint", "(", "\"tldnPwrTwrPeriscope.AvatarPag...
https://github.com/H-uru/Plasma/blob/c2140ea046e82e9c199e257a7f2e7edb42602871/Scripts/Python/tldnPwrTwrPeriscope.py#L221-L237