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
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/asyncio/base_events.py
python
BaseEventLoop.start_tls
(self, transport, protocol, sslcontext, *, server_side=False, server_hostname=None, ssl_handshake_timeout=None)
return ssl_protocol._app_transport
Upgrade transport to TLS. Return a new transport that *protocol* should start using immediately.
Upgrade transport to TLS.
[ "Upgrade", "transport", "to", "TLS", "." ]
async def start_tls(self, transport, protocol, sslcontext, *, server_side=False, server_hostname=None, ssl_handshake_timeout=None): """Upgrade transport to TLS. Return a new transport that *protocol* should start using immediately. """ if ssl is None: raise RuntimeError('Python ssl module is not available') if not isinstance(sslcontext, ssl.SSLContext): raise TypeError( f'sslcontext is expected to be an instance of ssl.SSLContext, ' f'got {sslcontext!r}') if not getattr(transport, '_start_tls_compatible', False): raise TypeError( f'transport {transport!r} is not supported by start_tls()') waiter = self.create_future() ssl_protocol = sslproto.SSLProtocol( self, protocol, sslcontext, waiter, server_side, server_hostname, ssl_handshake_timeout=ssl_handshake_timeout, call_connection_made=False) # Pause early so that "ssl_protocol.data_received()" doesn't # have a chance to get called before "ssl_protocol.connection_made()". transport.pause_reading() transport.set_protocol(ssl_protocol) conmade_cb = self.call_soon(ssl_protocol.connection_made, transport) resume_cb = self.call_soon(transport.resume_reading) try: await waiter except BaseException: transport.close() conmade_cb.cancel() resume_cb.cancel() raise return ssl_protocol._app_transport
[ "async", "def", "start_tls", "(", "self", ",", "transport", ",", "protocol", ",", "sslcontext", ",", "*", ",", "server_side", "=", "False", ",", "server_hostname", "=", "None", ",", "ssl_handshake_timeout", "=", "None", ")", ":", "if", "ssl", "is", "None",...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/asyncio/base_events.py#L1194-L1238
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/pkg_resources.py
python
safe_version
(version)
return re.sub('[^A-Za-z0-9.]+', '-', version)
Convert an arbitrary string to a standard version string Spaces become dots, and all other non-alphanumeric characters become dashes, with runs of multiple dashes condensed to a single dash.
Convert an arbitrary string to a standard version string
[ "Convert", "an", "arbitrary", "string", "to", "a", "standard", "version", "string" ]
def safe_version(version): """Convert an arbitrary string to a standard version string Spaces become dots, and all other non-alphanumeric characters become dashes, with runs of multiple dashes condensed to a single dash. """ version = version.replace(' ','.') return re.sub('[^A-Za-z0-9.]+', '-', version)
[ "def", "safe_version", "(", "version", ")", ":", "version", "=", "version", ".", "replace", "(", "' '", ",", "'.'", ")", "return", "re", ".", "sub", "(", "'[^A-Za-z0-9.]+'", ",", "'-'", ",", "version", ")" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/pkg_resources.py#L1089-L1096
google/google-api-cpp-client
3df15df632bef43eb320645ac3329d872aabf5ad
prepare_dependencies.py
python
ConfigInfo.abs_install_dir
(self)
return self._abs_install_dir
The root directory for the external dependency installation dir.
The root directory for the external dependency installation dir.
[ "The", "root", "directory", "for", "the", "external", "dependency", "installation", "dir", "." ]
def abs_install_dir(self): """The root directory for the external dependency installation dir.""" return self._abs_install_dir
[ "def", "abs_install_dir", "(", "self", ")", ":", "return", "self", ".", "_abs_install_dir" ]
https://github.com/google/google-api-cpp-client/blob/3df15df632bef43eb320645ac3329d872aabf5ad/prepare_dependencies.py#L230-L232
fifengine/fifengine
4b62c42e85bec19893cef8e63e6855927cff2c47
engine/python/fife/extensions/serializers/simplexml.py
python
SimpleXMLSerializer._serializeList
(self, list)
return " ; ".join(list)
Serializes a list, so it can be stored in a text file
Serializes a list, so it can be stored in a text file
[ "Serializes", "a", "list", "so", "it", "can", "be", "stored", "in", "a", "text", "file" ]
def _serializeList(self, list): """ Serializes a list, so it can be stored in a text file """ return " ; ".join(list)
[ "def", "_serializeList", "(", "self", ",", "list", ")", ":", "return", "\" ; \"", ".", "join", "(", "list", ")" ]
https://github.com/fifengine/fifengine/blob/4b62c42e85bec19893cef8e63e6855927cff2c47/engine/python/fife/extensions/serializers/simplexml.py#L448-L450
ZintrulCre/LeetCode_Archiver
de23e16ead29336b5ee7aa1898a392a5d6463d27
LeetCode/python3/169.py
python
Solution.majorityElement
(self, nums)
return max(d.keys(), key=d.get)
:type nums: List[int] :rtype: int
:type nums: List[int] :rtype: int
[ ":", "type", "nums", ":", "List", "[", "int", "]", ":", "rtype", ":", "int" ]
def majorityElement(self, nums): """ :type nums: List[int] :rtype: int """ d = collections.Counter(nums) return max(d.keys(), key=d.get)
[ "def", "majorityElement", "(", "self", ",", "nums", ")", ":", "d", "=", "collections", ".", "Counter", "(", "nums", ")", "return", "max", "(", "d", ".", "keys", "(", ")", ",", "key", "=", "d", ".", "get", ")" ]
https://github.com/ZintrulCre/LeetCode_Archiver/blob/de23e16ead29336b5ee7aa1898a392a5d6463d27/LeetCode/python3/169.py#L5-L11
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/aui/tabart.py
python
VC8TabArt.__init__
(self)
Default class constructor.
Default class constructor.
[ "Default", "class", "constructor", "." ]
def __init__(self): """ Default class constructor. """ AuiDefaultTabArt.__init__(self)
[ "def", "__init__", "(", "self", ")", ":", "AuiDefaultTabArt", ".", "__init__", "(", "self", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/aui/tabart.py#L2173-L2176
ValveSoftware/source-sdk-2013
0d8dceea4310fde5706b3ce1c70609d72a38efdf
sp/src/thirdparty/protobuf-2.3.0/python/mox.py
python
MockMethod.__ne__
(self, rhs)
return not self == rhs
Test whether this MockMethod is not equivalent to another MockMethod. Args: # rhs: the right hand side of the test rhs: MockMethod
Test whether this MockMethod is not equivalent to another MockMethod.
[ "Test", "whether", "this", "MockMethod", "is", "not", "equivalent", "to", "another", "MockMethod", "." ]
def __ne__(self, rhs): """Test whether this MockMethod is not equivalent to another MockMethod. Args: # rhs: the right hand side of the test rhs: MockMethod """ return not self == rhs
[ "def", "__ne__", "(", "self", ",", "rhs", ")", ":", "return", "not", "self", "==", "rhs" ]
https://github.com/ValveSoftware/source-sdk-2013/blob/0d8dceea4310fde5706b3ce1c70609d72a38efdf/sp/src/thirdparty/protobuf-2.3.0/python/mox.py#L635-L643
bigtreetech/BIGTREETECH-SKR-mini-E3
221247c12502ff92d071c701ea63cf3aa9bb3b29
firmware/V1.0/Marlin-2.0.7.2-SKR-mini-E3-V1.0/Marlin/src/lcd/extui/lib/ftdi_eve_touch_ui/ftdi_eve_lib/extras/bitmap2cpp.py
python
pack_rle
(data)
return rle
Use run-length encoding to pack the bytes
Use run-length encoding to pack the bytes
[ "Use", "run", "-", "length", "encoding", "to", "pack", "the", "bytes" ]
def pack_rle(data): """Use run-length encoding to pack the bytes""" rle = [] value = data[0] count = 0 for i in data: if i != value or count == 255: rle.append(count) rle.append(value) value = i count = 1 else: count += 1 rle.append(count) rle.append(value) return rle
[ "def", "pack_rle", "(", "data", ")", ":", "rle", "=", "[", "]", "value", "=", "data", "[", "0", "]", "count", "=", "0", "for", "i", "in", "data", ":", "if", "i", "!=", "value", "or", "count", "==", "255", ":", "rle", ".", "append", "(", "coun...
https://github.com/bigtreetech/BIGTREETECH-SKR-mini-E3/blob/221247c12502ff92d071c701ea63cf3aa9bb3b29/firmware/V1.0/Marlin-2.0.7.2-SKR-mini-E3-V1.0/Marlin/src/lcd/extui/lib/ftdi_eve_touch_ui/ftdi_eve_lib/extras/bitmap2cpp.py#L23-L38
devpack/android-python27
d42dd67565e104cf7b0b50eb473f615db3e69901
python-build-with-qt/sip-4.11.2/siputils.py
python
ProgramMakefile.generate_target_install
(self, mfile)
Generate the install target. mfile is the file object.
Generate the install target.
[ "Generate", "the", "install", "target", "." ]
def generate_target_install(self, mfile): """Generate the install target. mfile is the file object. """ if self._install_dir is None: self._install_dir = self.config.default_bin_dir mfile.write("\ninstall: $(TARGET)\n") self.install_file(mfile, "$(TARGET)", self._install_dir)
[ "def", "generate_target_install", "(", "self", ",", "mfile", ")", ":", "if", "self", ".", "_install_dir", "is", "None", ":", "self", ".", "_install_dir", "=", "self", ".", "config", ".", "default_bin_dir", "mfile", ".", "write", "(", "\"\\ninstall: $(TARGET)\\...
https://github.com/devpack/android-python27/blob/d42dd67565e104cf7b0b50eb473f615db3e69901/python-build-with-qt/sip-4.11.2/siputils.py#L1862-L1871
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/klampt/robotsim.py
python
RobotModel.torquesFromAccel
(self, ddq: Vector)
return _robotsim.RobotModel_torquesFromAccel(self, ddq)
r""" Computes the inverse dynamics. Uses Recursive Newton Euler solver and takes O(n) time. Args: ddq (:obj:`list of floats`) .. note:: Does not include gravity term G(q). getGravityForces(g) will need to be added to the result. Returns: list of floats: the n-element torque vector that would produce the joint accelerations ddq in the absence of external forces.
r""" Computes the inverse dynamics. Uses Recursive Newton Euler solver and takes O(n) time.
[ "r", "Computes", "the", "inverse", "dynamics", ".", "Uses", "Recursive", "Newton", "Euler", "solver", "and", "takes", "O", "(", "n", ")", "time", "." ]
def torquesFromAccel(self, ddq: Vector) ->None: r""" Computes the inverse dynamics. Uses Recursive Newton Euler solver and takes O(n) time. Args: ddq (:obj:`list of floats`) .. note:: Does not include gravity term G(q). getGravityForces(g) will need to be added to the result. Returns: list of floats: the n-element torque vector that would produce the joint accelerations ddq in the absence of external forces. """ return _robotsim.RobotModel_torquesFromAccel(self, ddq)
[ "def", "torquesFromAccel", "(", "self", ",", "ddq", ":", "Vector", ")", "->", "None", ":", "return", "_robotsim", ".", "RobotModel_torquesFromAccel", "(", "self", ",", "ddq", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/robotsim.py#L5028-L5047
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
caffe2/python/visualize.py
python
ChannelFirst
(arr)
return arr.swapaxes(ndim - 1, ndim - 2).swapaxes(ndim - 2, ndim - 3)
Convert a HWC array to CHW.
Convert a HWC array to CHW.
[ "Convert", "a", "HWC", "array", "to", "CHW", "." ]
def ChannelFirst(arr): """Convert a HWC array to CHW.""" ndim = arr.ndim return arr.swapaxes(ndim - 1, ndim - 2).swapaxes(ndim - 2, ndim - 3)
[ "def", "ChannelFirst", "(", "arr", ")", ":", "ndim", "=", "arr", ".", "ndim", "return", "arr", ".", "swapaxes", "(", "ndim", "-", "1", ",", "ndim", "-", "2", ")", ".", "swapaxes", "(", "ndim", "-", "2", ",", "ndim", "-", "3", ")" ]
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/caffe2/python/visualize.py#L16-L19
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_controls.py
python
ListCtrl.FindItemAtPos
(*args, **kwargs)
return _controls_.ListCtrl_FindItemAtPos(*args, **kwargs)
FindItemAtPos(self, long start, Point pt, int direction) -> long
FindItemAtPos(self, long start, Point pt, int direction) -> long
[ "FindItemAtPos", "(", "self", "long", "start", "Point", "pt", "int", "direction", ")", "-", ">", "long" ]
def FindItemAtPos(*args, **kwargs): """FindItemAtPos(self, long start, Point pt, int direction) -> long""" return _controls_.ListCtrl_FindItemAtPos(*args, **kwargs)
[ "def", "FindItemAtPos", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "ListCtrl_FindItemAtPos", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_controls.py#L4677-L4679
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
build/android/pylib/android_commands.py
python
AndroidCommands.SearchLogcatRecord
(self, record, message, thread_id=None, proc_id=None, log_level=None, component=None)
return results
Searches the specified logcat output and returns results. This method searches through the logcat output specified by record for a certain message, narrowing results by matching them against any other specified criteria. It returns all matching lines as described below. Args: record: A string generated by Start/StopRecordingLogcat to search. message: An output string to search for. thread_id: The thread id that is the origin of the message. proc_id: The process that is the origin of the message. log_level: The log level of the message. component: The name of the component that would create the message. Returns: A list of dictionaries represeting matching entries, each containing keys thread_id, proc_id, log_level, component, and message.
Searches the specified logcat output and returns results.
[ "Searches", "the", "specified", "logcat", "output", "and", "returns", "results", "." ]
def SearchLogcatRecord(self, record, message, thread_id=None, proc_id=None, log_level=None, component=None): """Searches the specified logcat output and returns results. This method searches through the logcat output specified by record for a certain message, narrowing results by matching them against any other specified criteria. It returns all matching lines as described below. Args: record: A string generated by Start/StopRecordingLogcat to search. message: An output string to search for. thread_id: The thread id that is the origin of the message. proc_id: The process that is the origin of the message. log_level: The log level of the message. component: The name of the component that would create the message. Returns: A list of dictionaries represeting matching entries, each containing keys thread_id, proc_id, log_level, component, and message. """ if thread_id: thread_id = str(thread_id) if proc_id: proc_id = str(proc_id) results = [] reg = re.compile('(\d+)\s+(\d+)\s+([A-Z])\s+([A-Za-z]+)\s*:(.*)$', re.MULTILINE) log_list = reg.findall(record) for (tid, pid, log_lev, comp, msg) in log_list: if ((not thread_id or thread_id == tid) and (not proc_id or proc_id == pid) and (not log_level or log_level == log_lev) and (not component or component == comp) and msg.find(message) > -1): match = dict({'thread_id': tid, 'proc_id': pid, 'log_level': log_lev, 'component': comp, 'message': msg}) results.append(match) return results
[ "def", "SearchLogcatRecord", "(", "self", ",", "record", ",", "message", ",", "thread_id", "=", "None", ",", "proc_id", "=", "None", ",", "log_level", "=", "None", ",", "component", "=", "None", ")", ":", "if", "thread_id", ":", "thread_id", "=", "str", ...
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/build/android/pylib/android_commands.py#L1407-L1444
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/common/py_trace_event/py_trace_event/trace_time.py
python
InitializeNowFunction
(plat)
Sets a monotonic clock for the current platform. Args: plat: Platform that is being run on.
Sets a monotonic clock for the current platform.
[ "Sets", "a", "monotonic", "clock", "for", "the", "current", "platform", "." ]
def InitializeNowFunction(plat): """Sets a monotonic clock for the current platform. Args: plat: Platform that is being run on. """ if plat.startswith(_PLATFORMS['mac']): InitializeMacNowFunction(plat) elif (plat.startswith(_PLATFORMS['linux']) or plat.startswith(_PLATFORMS['freebsd']) or plat.startswith(_PLATFORMS['bsd']) or plat.startswith(_PLATFORMS['sunos'])): InitializeLinuxNowFunction(plat) elif (plat.startswith(_PLATFORMS['windows']) or plat.startswith(_PLATFORMS['cygwin'])): InitializeWinNowFunction(plat) else: raise RuntimeError('%s is not a supported platform.' % plat) global _NOW_FUNCTION global _CLOCK assert _NOW_FUNCTION, 'Now function not properly set during initialization.' assert _CLOCK, 'Clock not properly set during initialization.'
[ "def", "InitializeNowFunction", "(", "plat", ")", ":", "if", "plat", ".", "startswith", "(", "_PLATFORMS", "[", "'mac'", "]", ")", ":", "InitializeMacNowFunction", "(", "plat", ")", "elif", "(", "plat", ".", "startswith", "(", "_PLATFORMS", "[", "'linux'", ...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/common/py_trace_event/py_trace_event/trace_time.py#L196-L221
chromiumembedded/cef
80caf947f3fe2210e5344713c5281d8af9bdc295
tools/date_util.py
python
get_date
()
return datetime.datetime.now().strftime('%B %d, %Y')
Returns the current date.
Returns the current date.
[ "Returns", "the", "current", "date", "." ]
def get_date(): """ Returns the current date. """ return datetime.datetime.now().strftime('%B %d, %Y')
[ "def", "get_date", "(", ")", ":", "return", "datetime", ".", "datetime", ".", "now", "(", ")", ".", "strftime", "(", "'%B %d, %Y'", ")" ]
https://github.com/chromiumembedded/cef/blob/80caf947f3fe2210e5344713c5281d8af9bdc295/tools/date_util.py#L14-L16
facebook/bistro
db9eff7e92f5cedcc917a440d5c88064c7980e40
build/fbcode_builder/getdeps/dyndeps.py
python
WinDeps.compute_dependency_paths
(self, build_dir)
return sorted(dep_dirs)
Return a list of all directories that need to be added to $PATH to ensure that library dependencies can be found correctly. This is computed by scanning binaries to determine exactly the right list of dependencies. The compute_dependency_paths_fast() is a alternative function that runs faster but may return additional extraneous paths.
Return a list of all directories that need to be added to $PATH to ensure that library dependencies can be found correctly. This is computed by scanning binaries to determine exactly the right list of dependencies.
[ "Return", "a", "list", "of", "all", "directories", "that", "need", "to", "be", "added", "to", "$PATH", "to", "ensure", "that", "library", "dependencies", "can", "be", "found", "correctly", ".", "This", "is", "computed", "by", "scanning", "binaries", "to", ...
def compute_dependency_paths(self, build_dir): """Return a list of all directories that need to be added to $PATH to ensure that library dependencies can be found correctly. This is computed by scanning binaries to determine exactly the right list of dependencies. The compute_dependency_paths_fast() is a alternative function that runs faster but may return additional extraneous paths. """ dep_dirs = set() # Find paths by scanning the binaries. for dep in self.find_all_dependencies(build_dir): dep_dirs.add(os.path.dirname(dep)) dep_dirs.update(self.read_custom_dep_dirs(build_dir)) return sorted(dep_dirs)
[ "def", "compute_dependency_paths", "(", "self", ",", "build_dir", ")", ":", "dep_dirs", "=", "set", "(", ")", "# Find paths by scanning the binaries.", "for", "dep", "in", "self", ".", "find_all_dependencies", "(", "build_dir", ")", ":", "dep_dirs", ".", "add", ...
https://github.com/facebook/bistro/blob/db9eff7e92f5cedcc917a440d5c88064c7980e40/build/fbcode_builder/getdeps/dyndeps.py#L249-L263
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/keras/layers/kernelized.py
python
_get_random_features_initializer
(initializer, shape)
return random_features_initializer
Returns Initializer object for random features.
Returns Initializer object for random features.
[ "Returns", "Initializer", "object", "for", "random", "features", "." ]
def _get_random_features_initializer(initializer, shape): """Returns Initializer object for random features.""" def _get_cauchy_samples(loc, scale, shape): probs = np.random.uniform(low=0., high=1., size=shape) return loc + scale * np.tan(np.pi * (probs - 0.5)) random_features_initializer = initializer if isinstance(initializer, six.string_types): if initializer.lower() == 'gaussian': random_features_initializer = init_ops.random_normal_initializer( stddev=1.0) elif initializer.lower() == 'laplacian': random_features_initializer = init_ops.constant_initializer( _get_cauchy_samples(loc=0.0, scale=1.0, shape=shape)) else: raise ValueError( 'Unsupported kernel type: \'{}\'. Supported kernel types: {}.'.format( random_features_initializer, _SUPPORTED_RBF_KERNEL_TYPES)) return random_features_initializer
[ "def", "_get_random_features_initializer", "(", "initializer", ",", "shape", ")", ":", "def", "_get_cauchy_samples", "(", "loc", ",", "scale", ",", "shape", ")", ":", "probs", "=", "np", ".", "random", ".", "uniform", "(", "low", "=", "0.", ",", "high", ...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/keras/layers/kernelized.py#L231-L251
thalium/icebox
99d147d5b9269222225443ce171b4fd46d8985d4
third_party/retdec-3.2/scripts/type_extractor/type_extractor/params_info.py
python
Param.parse_param_size
(self)
Gets size of parameter in bit fields in structs.
Gets size of parameter in bit fields in structs.
[ "Gets", "size", "of", "parameter", "in", "bit", "fields", "in", "structs", "." ]
def parse_param_size(self): """Gets size of parameter in bit fields in structs.""" size = re.search(r'\d+$', self.type) if size: self.size = size.group(0) self.type = self.type[:self.type_text.rfind(':')].strip()
[ "def", "parse_param_size", "(", "self", ")", ":", "size", "=", "re", ".", "search", "(", "r'\\d+$'", ",", "self", ".", "type", ")", "if", "size", ":", "self", ".", "size", "=", "size", ".", "group", "(", "0", ")", "self", ".", "type", "=", "self"...
https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/retdec-3.2/scripts/type_extractor/type_extractor/params_info.py#L89-L94
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/ros_comm/roslaunch/src/roslaunch/pmon.py
python
ProcessMonitor.registrations_complete
(self)
Inform the process monitor that registrations are complete. After the registrations_complete flag is set, process monitor will exit if there are no processes left to monitor.
Inform the process monitor that registrations are complete. After the registrations_complete flag is set, process monitor will exit if there are no processes left to monitor.
[ "Inform", "the", "process", "monitor", "that", "registrations", "are", "complete", ".", "After", "the", "registrations_complete", "flag", "is", "set", "process", "monitor", "will", "exit", "if", "there", "are", "no", "processes", "left", "to", "monitor", "." ]
def registrations_complete(self): """ Inform the process monitor that registrations are complete. After the registrations_complete flag is set, process monitor will exit if there are no processes left to monitor. """ self._registrations_complete = True logger.info("registrations completed %s"%self)
[ "def", "registrations_complete", "(", "self", ")", ":", "self", ".", "_registrations_complete", "=", "True", "logger", ".", "info", "(", "\"registrations completed %s\"", "%", "self", ")" ]
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/ros_comm/roslaunch/src/roslaunch/pmon.py#L370-L377
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_windows.py
python
TopLevelWindow.MacGetUnifiedAppearance
(*args, **kwargs)
return _windows_.TopLevelWindow_MacGetUnifiedAppearance(*args, **kwargs)
MacGetUnifiedAppearance(self) -> bool
MacGetUnifiedAppearance(self) -> bool
[ "MacGetUnifiedAppearance", "(", "self", ")", "-", ">", "bool" ]
def MacGetUnifiedAppearance(*args, **kwargs): """MacGetUnifiedAppearance(self) -> bool""" return _windows_.TopLevelWindow_MacGetUnifiedAppearance(*args, **kwargs)
[ "def", "MacGetUnifiedAppearance", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_windows_", ".", "TopLevelWindow_MacGetUnifiedAppearance", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_windows.py#L485-L487
ablab/quast
5f6709528129a6ad266a6b24ef3f40b88f0fe04b
quast_libs/busco/GeneSetAnalysis.py
python
GeneSetAnalysis._check_tool_dependencies
(self)
check dependencies on tools :raises SystemExit: if a Tool is not available
check dependencies on tools :raises SystemExit: if a Tool is not available
[ "check", "dependencies", "on", "tools", ":", "raises", "SystemExit", ":", "if", "a", "Tool", "is", "not", "available" ]
def _check_tool_dependencies(self): """ check dependencies on tools :raises SystemExit: if a Tool is not available """ # check 'hmmersearch' command availability if not Tool.check_tool_available('hmmsearch', self._params): BuscoAnalysis._logger.error( '\"hmmsearch\" is not accessible, ' 'add or modify its path in the config file. Do not include the command ' 'in the path !') raise SystemExit # check version if self._get_hmmer_version(self._hmmer.cmd[0]) >= BuscoConfig.HMMER_VERSION: pass else: BuscoAnalysis._logger.error( 'HMMer version detected is not supported, please use HMMer ' ' v.%s +' % BuscoConfig.HMMER_VERSION) raise SystemExit
[ "def", "_check_tool_dependencies", "(", "self", ")", ":", "# check 'hmmersearch' command availability", "if", "not", "Tool", ".", "check_tool_available", "(", "'hmmsearch'", ",", "self", ".", "_params", ")", ":", "BuscoAnalysis", ".", "_logger", ".", "error", "(", ...
https://github.com/ablab/quast/blob/5f6709528129a6ad266a6b24ef3f40b88f0fe04b/quast_libs/busco/GeneSetAnalysis.py#L132-L153
hughperkins/tf-coriander
970d3df6c11400ad68405f22b0c42a52374e94ca
tensorflow/python/ops/math_ops.py
python
reduce_prod
(input_tensor, reduction_indices=None, keep_dims=False, name=None)
return gen_math_ops._prod(input_tensor, _ReductionDims(input_tensor, reduction_indices), keep_dims, name=name)
Computes the product of elements across dimensions of a tensor. Reduces `input_tensor` along the dimensions given in `reduction_indices`. Unless `keep_dims` is true, the rank of the tensor is reduced by 1 for each entry in `reduction_indices`. If `keep_dims` is true, the reduced dimensions are retained with length 1. If `reduction_indices` has no entries, all dimensions are reduced, and a tensor with a single element is returned. Args: input_tensor: The tensor to reduce. Should have numeric type. reduction_indices: The dimensions to reduce. If `None` (the default), reduces all dimensions. keep_dims: If true, retains reduced dimensions with length 1. name: A name for the operation (optional). Returns: The reduced tensor.
Computes the product of elements across dimensions of a tensor.
[ "Computes", "the", "product", "of", "elements", "across", "dimensions", "of", "a", "tensor", "." ]
def reduce_prod(input_tensor, reduction_indices=None, keep_dims=False, name=None): """Computes the product of elements across dimensions of a tensor. Reduces `input_tensor` along the dimensions given in `reduction_indices`. Unless `keep_dims` is true, the rank of the tensor is reduced by 1 for each entry in `reduction_indices`. If `keep_dims` is true, the reduced dimensions are retained with length 1. If `reduction_indices` has no entries, all dimensions are reduced, and a tensor with a single element is returned. Args: input_tensor: The tensor to reduce. Should have numeric type. reduction_indices: The dimensions to reduce. If `None` (the default), reduces all dimensions. keep_dims: If true, retains reduced dimensions with length 1. name: A name for the operation (optional). Returns: The reduced tensor. """ return gen_math_ops._prod(input_tensor, _ReductionDims(input_tensor, reduction_indices), keep_dims, name=name)
[ "def", "reduce_prod", "(", "input_tensor", ",", "reduction_indices", "=", "None", ",", "keep_dims", "=", "False", ",", "name", "=", "None", ")", ":", "return", "gen_math_ops", ".", "_prod", "(", "input_tensor", ",", "_ReductionDims", "(", "input_tensor", ",", ...
https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/ops/math_ops.py#L1121-L1145
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/decimal.py
python
Context.fma
(self, a, b, c)
return a.fma(b, c, context=self)
Returns a multiplied by b, plus c. The first two operands are multiplied together, using multiply, the third operand is then added to the result of that multiplication, using add, all with only one final rounding. >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7')) Decimal('22') >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7')) Decimal('-8') >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578')) Decimal('1.38435736E+12') >>> ExtendedContext.fma(1, 3, 4) Decimal('7') >>> ExtendedContext.fma(1, Decimal(3), 4) Decimal('7') >>> ExtendedContext.fma(1, 3, Decimal(4)) Decimal('7')
Returns a multiplied by b, plus c.
[ "Returns", "a", "multiplied", "by", "b", "plus", "c", "." ]
def fma(self, a, b, c): """Returns a multiplied by b, plus c. The first two operands are multiplied together, using multiply, the third operand is then added to the result of that multiplication, using add, all with only one final rounding. >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7')) Decimal('22') >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7')) Decimal('-8') >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578')) Decimal('1.38435736E+12') >>> ExtendedContext.fma(1, 3, 4) Decimal('7') >>> ExtendedContext.fma(1, Decimal(3), 4) Decimal('7') >>> ExtendedContext.fma(1, 3, Decimal(4)) Decimal('7') """ a = _convert_other(a, raiseit=True) return a.fma(b, c, context=self)
[ "def", "fma", "(", "self", ",", "a", ",", "b", ",", "c", ")", ":", "a", "=", "_convert_other", "(", "a", ",", "raiseit", "=", "True", ")", "return", "a", ".", "fma", "(", "b", ",", "c", ",", "context", "=", "self", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/decimal.py#L4289-L4310
freesurfer/freesurfer
6dbe527d43ffa611acb2cd112e9469f9bfec8e36
python/freesurfer/surface.py
python
Surface.copy
(self)
return copy.deepcopy(self)
Returns a deep copy of the surface.
Returns a deep copy of the surface.
[ "Returns", "a", "deep", "copy", "of", "the", "surface", "." ]
def copy(self): '''Returns a deep copy of the surface.''' return copy.deepcopy(self)
[ "def", "copy", "(", "self", ")", ":", "return", "copy", ".", "deepcopy", "(", "self", ")" ]
https://github.com/freesurfer/freesurfer/blob/6dbe527d43ffa611acb2cd112e9469f9bfec8e36/python/freesurfer/surface.py#L51-L53
espressomd/espresso
7e29f9052e710fe1ebf0f5d2a8076b32921fbc6a
src/python/espressomd/drude_helpers.py
python
DrudeHelpers.add_all_thole
(self, system, verbose=False)
Calls :meth:`add_thole_pair_damping()` for all necessary combinations to create the interactions. Parameters ---------- system : :class:`espressomd.system.System` verbose : :obj:`bool` Turns on verbosity.
Calls :meth:`add_thole_pair_damping()` for all necessary combinations to create the interactions.
[ "Calls", ":", "meth", ":", "add_thole_pair_damping", "()", "for", "all", "necessary", "combinations", "to", "create", "the", "interactions", "." ]
def add_all_thole(self, system, verbose=False): """ Calls :meth:`add_thole_pair_damping()` for all necessary combinations to create the interactions. Parameters ---------- system : :class:`espressomd.system.System` verbose : :obj:`bool` Turns on verbosity. """ # Drude <-> Drude for i in range(len(self.drude_type_list)): for j in range(i, len(self.drude_type_list)): self.add_thole_pair_damping( system, self.drude_type_list[i], self.drude_type_list[j], verbose) # core <-> core for i in range(len(self.core_type_list)): for j in range(i, len(self.core_type_list)): self.add_thole_pair_damping( system, self.core_type_list[i], self.core_type_list[j], verbose) # Drude <-> core for i in self.drude_type_list: for j in self.core_type_list: self.add_thole_pair_damping(system, i, j, verbose)
[ "def", "add_all_thole", "(", "self", ",", "system", ",", "verbose", "=", "False", ")", ":", "# Drude <-> Drude", "for", "i", "in", "range", "(", "len", "(", "self", ".", "drude_type_list", ")", ")", ":", "for", "j", "in", "range", "(", "i", ",", "len...
https://github.com/espressomd/espresso/blob/7e29f9052e710fe1ebf0f5d2a8076b32921fbc6a/src/python/espressomd/drude_helpers.py#L175-L202
xhzdeng/crpn
a5aef0f80dbe486103123f740c634fb01e6cc9a1
lib/pycocotools/coco.py
python
COCO.loadRes
(self, resFile)
return res
Load result file and return a result api object. :param resFile (str) : file name of result file :return: res (obj) : result api object
Load result file and return a result api object. :param resFile (str) : file name of result file :return: res (obj) : result api object
[ "Load", "result", "file", "and", "return", "a", "result", "api", "object", ".", ":", "param", "resFile", "(", "str", ")", ":", "file", "name", "of", "result", "file", ":", "return", ":", "res", "(", "obj", ")", ":", "result", "api", "object" ]
def loadRes(self, resFile): """ Load result file and return a result api object. :param resFile (str) : file name of result file :return: res (obj) : result api object """ res = COCO() res.dataset['images'] = [img for img in self.dataset['images']] # res.dataset['info'] = copy.deepcopy(self.dataset['info']) # res.dataset['licenses'] = copy.deepcopy(self.dataset['licenses']) print 'Loading and preparing results... ' tic = time.time() anns = json.load(open(resFile)) assert type(anns) == list, 'results in not an array of objects' annsImgIds = [ann['image_id'] for ann in anns] assert set(annsImgIds) == (set(annsImgIds) & set(self.getImgIds())), \ 'Results do not correspond to current coco set' if 'caption' in anns[0]: imgIds = set([img['id'] for img in res.dataset['images']]) & set([ann['image_id'] for ann in anns]) res.dataset['images'] = [img for img in res.dataset['images'] if img['id'] in imgIds] for id, ann in enumerate(anns): ann['id'] = id+1 elif 'bbox' in anns[0] and not anns[0]['bbox'] == []: res.dataset['categories'] = copy.deepcopy(self.dataset['categories']) for id, ann in enumerate(anns): bb = ann['bbox'] x1, x2, y1, y2 = [bb[0], bb[0]+bb[2], bb[1], bb[1]+bb[3]] if not 'segmentation' in ann: ann['segmentation'] = [[x1, y1, x1, y2, x2, y2, x2, y1]] ann['area'] = bb[2]*bb[3] ann['id'] = id+1 ann['iscrowd'] = 0 elif 'segmentation' in anns[0]: res.dataset['categories'] = copy.deepcopy(self.dataset['categories']) for id, ann in enumerate(anns): # now only support compressed RLE format as segmentation results ann['area'] = mask.area([ann['segmentation']])[0] if not 'bbox' in ann: ann['bbox'] = mask.toBbox([ann['segmentation']])[0] ann['id'] = id+1 ann['iscrowd'] = 0 print 'DONE (t=%0.2fs)'%(time.time()- tic) res.dataset['annotations'] = anns res.createIndex() return res
[ "def", "loadRes", "(", "self", ",", "resFile", ")", ":", "res", "=", "COCO", "(", ")", "res", ".", "dataset", "[", "'images'", "]", "=", "[", "img", "for", "img", "in", "self", ".", "dataset", "[", "'images'", "]", "]", "# res.dataset['info'] = copy.de...
https://github.com/xhzdeng/crpn/blob/a5aef0f80dbe486103123f740c634fb01e6cc9a1/lib/pycocotools/coco.py#L281-L327
apache/incubator-mxnet
f03fb23f1d103fec9541b5ae59ee06b1734a51d9
python/mxnet/numpy_extension/_op.py
python
one_hot
(data, depth=None, on_value=1.0, off_value=0.0, dtype="float32")
return _mx_nd_npx.one_hot(data=data, depth=depth, on_value=on_value, off_value=off_value, dtype=dtype)
r"""Returns a one-hot array. The locations represented by `indices` take value `on_value`, while all other locations take value `off_value`. `one_hot` operation with `indices` of shape ``(i0, i1)`` and `depth` of ``d`` would result in an output array of shape ``(i0, i1, d)`` with:: output[i,j,:] = off_value output[i,j,indices[i,j]] = on_value Parameters ---------- indices : NDArray array of locations where to set on_value depth : long, required Depth of the one hot dimension. on_value : double, optional, default=1 The value assigned to the locations represented by indices. off_value : double, optional, default=0 The value assigned to the locations not represented by indices. dtype : {'bfloat16', 'float16', 'float32', 'float64', 'int32', 'int64', 'int8', 'uint8'}, optional, default='float32' DType of the output Returns ------- out : NDArray or list of NDArrays The output of this function. Example ------- >>> data = np.array([1,0,2,0]) >>> npx.one_hot(data, 3) array([[0., 1., 0.], [1., 0., 0.], [0., 0., 1.], [1., 0., 0.]], dtype=float64) >>> npx.one_hot(data, 3, on_value=8, off_value=1, dtype='int32') array([[1, 8, 1], [8, 1, 1], [1, 1, 8], [8, 1, 1]], dtype=int32) >>> data = np.array([[1,0],[1,0],[2,0]]) >>> npx.one_hot(data, 3) array([[[0., 1., 0.], [1., 0., 0.]], [[0., 1., 0.], [1., 0., 0.]], [[0., 0., 1.], [1., 0., 0.]]], dtype=float64)
r"""Returns a one-hot array.
[ "r", "Returns", "a", "one", "-", "hot", "array", "." ]
def one_hot(data, depth=None, on_value=1.0, off_value=0.0, dtype="float32"): r"""Returns a one-hot array. The locations represented by `indices` take value `on_value`, while all other locations take value `off_value`. `one_hot` operation with `indices` of shape ``(i0, i1)`` and `depth` of ``d`` would result in an output array of shape ``(i0, i1, d)`` with:: output[i,j,:] = off_value output[i,j,indices[i,j]] = on_value Parameters ---------- indices : NDArray array of locations where to set on_value depth : long, required Depth of the one hot dimension. on_value : double, optional, default=1 The value assigned to the locations represented by indices. off_value : double, optional, default=0 The value assigned to the locations not represented by indices. dtype : {'bfloat16', 'float16', 'float32', 'float64', 'int32', 'int64', 'int8', 'uint8'}, optional, default='float32' DType of the output Returns ------- out : NDArray or list of NDArrays The output of this function. Example ------- >>> data = np.array([1,0,2,0]) >>> npx.one_hot(data, 3) array([[0., 1., 0.], [1., 0., 0.], [0., 0., 1.], [1., 0., 0.]], dtype=float64) >>> npx.one_hot(data, 3, on_value=8, off_value=1, dtype='int32') array([[1, 8, 1], [8, 1, 1], [1, 1, 8], [8, 1, 1]], dtype=int32) >>> data = np.array([[1,0],[1,0],[2,0]]) >>> npx.one_hot(data, 3) array([[[0., 1., 0.], [1., 0., 0.]], [[0., 1., 0.], [1., 0., 0.]], [[0., 0., 1.], [1., 0., 0.]]], dtype=float64) """ return _mx_nd_npx.one_hot(data=data, depth=depth, on_value=on_value, off_value=off_value, dtype=dtype)
[ "def", "one_hot", "(", "data", ",", "depth", "=", "None", ",", "on_value", "=", "1.0", ",", "off_value", "=", "0.0", ",", "dtype", "=", "\"float32\"", ")", ":", "return", "_mx_nd_npx", ".", "one_hot", "(", "data", "=", "data", ",", "depth", "=", "dep...
https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/numpy_extension/_op.py#L788-L842
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/genlisp/src/genlisp/generate.py
python
write_begin
(s, spec, is_service=False)
Writes the beginning of the file: a comment saying it's auto-generated and the in-package form
Writes the beginning of the file: a comment saying it's auto-generated and the in-package form
[ "Writes", "the", "beginning", "of", "the", "file", ":", "a", "comment", "saying", "it", "s", "auto", "-", "generated", "and", "the", "in", "-", "package", "form" ]
def write_begin(s, spec, is_service=False): "Writes the beginning of the file: a comment saying it's auto-generated and the in-package form" s.write('; Auto-generated. Do not edit!\n\n\n', newline=False) suffix = 'srv' if is_service else 'msg' s.write('(cl:in-package %s-%s)\n\n\n'%(spec.package, suffix), newline=False)
[ "def", "write_begin", "(", "s", ",", "spec", ",", "is_service", "=", "False", ")", ":", "s", ".", "write", "(", "'; Auto-generated. Do not edit!\\n\\n\\n'", ",", "newline", "=", "False", ")", "suffix", "=", "'srv'", "if", "is_service", "else", "'msg'", "s", ...
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/genlisp/src/genlisp/generate.py#L213-L218
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/speedmeter.py
python
SpeedMeter.GetMiddleTextColour
(self)
return self._middlecolour
Returns the colour for the text in the middle.
Returns the colour for the text in the middle.
[ "Returns", "the", "colour", "for", "the", "text", "in", "the", "middle", "." ]
def GetMiddleTextColour(self): """ Returns the colour for the text in the middle.""" return self._middlecolour
[ "def", "GetMiddleTextColour", "(", "self", ")", ":", "return", "self", ".", "_middlecolour" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/speedmeter.py#L1529-L1532
mapnik/mapnik
f3da900c355e1d15059c4a91b00203dcc9d9f0ef
scons/scons-local-4.1.0/SCons/Tool/masm.py
python
generate
(env)
Add Builders and construction variables for masm to an Environment.
Add Builders and construction variables for masm to an Environment.
[ "Add", "Builders", "and", "construction", "variables", "for", "masm", "to", "an", "Environment", "." ]
def generate(env): """Add Builders and construction variables for masm to an Environment.""" static_obj, shared_obj = SCons.Tool.createObjBuilders(env) for suffix in ASSuffixes: static_obj.add_action(suffix, SCons.Defaults.ASAction) shared_obj.add_action(suffix, SCons.Defaults.ASAction) static_obj.add_emitter(suffix, SCons.Defaults.StaticObjectEmitter) shared_obj.add_emitter(suffix, SCons.Defaults.SharedObjectEmitter) for suffix in ASPPSuffixes: static_obj.add_action(suffix, SCons.Defaults.ASPPAction) shared_obj.add_action(suffix, SCons.Defaults.ASPPAction) static_obj.add_emitter(suffix, SCons.Defaults.StaticObjectEmitter) shared_obj.add_emitter(suffix, SCons.Defaults.SharedObjectEmitter) env['AS'] = 'ml' env['ASFLAGS'] = SCons.Util.CLVar('/nologo') env['ASPPFLAGS'] = '$ASFLAGS' env['ASCOM'] = '$AS $ASFLAGS /c /Fo$TARGET $SOURCES' env['ASPPCOM'] = '$CC $ASPPFLAGS $CPPFLAGS $_CPPDEFFLAGS $_CPPINCFLAGS /c /Fo$TARGET $SOURCES' env['STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME'] = 1
[ "def", "generate", "(", "env", ")", ":", "static_obj", ",", "shared_obj", "=", "SCons", ".", "Tool", ".", "createObjBuilders", "(", "env", ")", "for", "suffix", "in", "ASSuffixes", ":", "static_obj", ".", "add_action", "(", "suffix", ",", "SCons", ".", "...
https://github.com/mapnik/mapnik/blob/f3da900c355e1d15059c4a91b00203dcc9d9f0ef/scons/scons-local-4.1.0/SCons/Tool/masm.py#L47-L68
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
torch/distributed/elastic/rendezvous/dynamic_rendezvous.py
python
_DistributedRendezvousOpExecutor.run
( self, state_handler: Callable[[_RendezvousContext, float], _Action], deadline: float, )
See base class.
See base class.
[ "See", "base", "class", "." ]
def run( self, state_handler: Callable[[_RendezvousContext, float], _Action], deadline: float, ) -> None: """See base class.""" action = None while action != _Action.FINISH: # Reads or writes the latest rendezvous state shared by all nodes in # the rendezvous. Note that our local changes might get overridden # by another node if that node synced its changes before us. has_set = self._state_holder.sync() if has_set is not None: if has_set: msg = ( f"The node '{self._node}' has successfully synced its local changes with " f"other nodes in the rendezvous '{self._settings.run_id}'." ) else: msg = ( f"The node '{self._node}' has a stale state and failed to sync its local " f"changes with other nodes in the rendezvous '{self._settings.run_id}'." ) self._record(message=msg) log.debug(msg) self._state = self._state_holder.state ctx = _RendezvousContext(self._node, self._state, self._settings) # Determine the next action to take based on the current state of # the rendezvous. action = state_handler(ctx, deadline) if action == _Action.FINISH: continue if action == _Action.ERROR_CLOSED: raise RendezvousClosedError() if action == _Action.ERROR_TIMEOUT: raise RendezvousTimeoutError() if action == _Action.SYNC: # Delay the execution by one second to avoid overloading the # backend if we are asked to poll for state changes. _delay(seconds=1) else: if action == _Action.KEEP_ALIVE: self._keep_alive() elif action == _Action.ADD_TO_PARTICIPANTS: self._add_to_participants() elif action == _Action.ADD_TO_WAIT_LIST: self._add_to_wait_list() elif action == _Action.REMOVE_FROM_PARTICIPANTS: self._remove_from_participants() elif action == _Action.REMOVE_FROM_WAIT_LIST: self._remove_from_wait_list() elif action == _Action.MARK_RENDEZVOUS_COMPLETE: self._mark_rendezvous_complete() elif action == _Action.MARK_RENDEZVOUS_CLOSED: self._mark_rendezvous_closed() # Attempt to sync our changes back to other nodes. self._state_holder.mark_dirty()
[ "def", "run", "(", "self", ",", "state_handler", ":", "Callable", "[", "[", "_RendezvousContext", ",", "float", "]", ",", "_Action", "]", ",", "deadline", ":", "float", ",", ")", "->", "None", ":", "action", "=", "None", "while", "action", "!=", "_Acti...
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/distributed/elastic/rendezvous/dynamic_rendezvous.py#L594-L660
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_core.py
python
Menu.Break
(*args, **kwargs)
return _core_.Menu_Break(*args, **kwargs)
Break(self)
Break(self)
[ "Break", "(", "self", ")" ]
def Break(*args, **kwargs): """Break(self)""" return _core_.Menu_Break(*args, **kwargs)
[ "def", "Break", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "Menu_Break", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L12041-L12043
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/boto/boto/dynamodb/types.py
python
item_object_hook
(dct)
return dct
A custom object hook for use when decoding JSON item bodys. This hook will transform Amazon DynamoDB JSON responses to something that maps directly to native Python types.
A custom object hook for use when decoding JSON item bodys. This hook will transform Amazon DynamoDB JSON responses to something that maps directly to native Python types.
[ "A", "custom", "object", "hook", "for", "use", "when", "decoding", "JSON", "item", "bodys", ".", "This", "hook", "will", "transform", "Amazon", "DynamoDB", "JSON", "responses", "to", "something", "that", "maps", "directly", "to", "native", "Python", "types", ...
def item_object_hook(dct): """ A custom object hook for use when decoding JSON item bodys. This hook will transform Amazon DynamoDB JSON responses to something that maps directly to native Python types. """ if len(dct.keys()) > 1: return dct if 'S' in dct: return dct['S'] if 'N' in dct: return convert_num(dct['N']) if 'SS' in dct: return set(dct['SS']) if 'NS' in dct: return set(map(convert_num, dct['NS'])) if 'B' in dct: return convert_binary(dct['B']) if 'BS' in dct: return set(map(convert_binary, dct['BS'])) return dct
[ "def", "item_object_hook", "(", "dct", ")", ":", "if", "len", "(", "dct", ".", "keys", "(", ")", ")", ">", "1", ":", "return", "dct", "if", "'S'", "in", "dct", ":", "return", "dct", "[", "'S'", "]", "if", "'N'", "in", "dct", ":", "return", "con...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/dynamodb/types.py#L208-L228
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/ops/operations/math_ops.py
python
_Reduce.do_infer
(self, input_x, axis, valid_dtype=mstype.number_type)
return {'shape': out_shape, 'min_shape': output_min_shape, 'max_shape': output_max_shape, 'dtype': input_x['dtype'], 'value': value}
return meta infos of input parameters
return meta infos of input parameters
[ "return", "meta", "infos", "of", "input", "parameters" ]
def do_infer(self, input_x, axis, valid_dtype=mstype.number_type): """ return meta infos of input parameters """ axis_v = axis['value'] input_shp = input_x['shape'] args = {'input_x': input_x['dtype']} validator.check_tensors_dtypes_same_and_valid(args, valid_dtype, self.name) if not isinstance(axis['dtype'], mstype.tensor_type) and axis_v is None: raise ValueError(f"For '{self.name}', the 'axis' cannot be None, but got {axis}.") if -1 in input_shp: if axis_v is None: max_v = max(input_shp) if 'max_shape' and 'min_shape' in input_x: input_max_shp = input_x['max_shape'] max_v = max(input_max_shp) axis_shape_list = axis['shape'] if len(axis_shape_list) != 1: raise ValueError(f"For '{self.name}', the shape of 'axis' must be 1-D, but " f"got {len(axis_shape_list)}.") axis_shape = axis_shape_list[0] if axis_shape == -1 and not self.keep_dims: out_shape = np.array([-2]).tolist() output_min_shape = input_x['min_shape'] output_max_shape = input_x['max_shape'] elif not self.keep_dims: out_shape = -1 * np.ones_like(input_shp[:-axis_shape]) out_shape = out_shape.tolist() output_min_shape = np.ones_like(out_shape).tolist() output_max_shape = max_v * np.ones_like(out_shape) output_max_shape = output_max_shape.tolist() else: out_shape = -1 * np.ones_like(input_shp) out_shape = out_shape.tolist() output_min_shape = np.ones_like(input_shp).tolist() output_max_shape = max_v * np.ones_like(input_shp) output_max_shape = output_max_shape.tolist() else: output_max_shape = _infer_shape_reduce(input_x['max_shape'], axis_v, self.keep_dims, self.name) output_min_shape = _infer_shape_reduce(input_x['min_shape'], axis_v, self.keep_dims, self.name) out_shape = _infer_shape_reduce(input_shp, axis_v, self.keep_dims, self.name) else: if axis_v is None: raise ValueError(f"For {self.name}, axis must be const, its value cannot be None.") out_shape = _infer_shape_reduce(input_shp, axis_v, self.keep_dims, self.name) output_max_shape = out_shape output_min_shape = out_shape value = None if input_x['value'] is not None: prim_map = { 'ReduceSum': np.sum, 'ReduceMax': np.max, 'ReduceMin': np.min, } np_reduce_func = prim_map.get(self.name, None) if np_reduce_func is not None: value = input_x['value'].asnumpy() if isinstance(axis_v, int): pass elif axis_v: axis_v = tuple(set(axis_v)) else: axis_v = tuple(range(len(input_x['shape']))) value = np_reduce_func(value, axis_v, keepdims=self.keep_dims) value = np.array(value) value = Tensor(value) return {'shape': out_shape, 'min_shape': output_min_shape, 'max_shape': output_max_shape, 'dtype': input_x['dtype'], 'value': value}
[ "def", "do_infer", "(", "self", ",", "input_x", ",", "axis", ",", "valid_dtype", "=", "mstype", ".", "number_type", ")", ":", "axis_v", "=", "axis", "[", "'value'", "]", "input_shp", "=", "input_x", "[", "'shape'", "]", "args", "=", "{", "'input_x'", "...
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/operations/math_ops.py#L511-L581
may0324/DeepCompression-caffe
0aff6c1287bda4cfc7f378ed8a16524e1afabd8c
python/caffe/detector.py
python
Detector.detect_windows
(self, images_windows)
return detections
Do windowed detection over given images and windows. Windows are extracted then warped to the input dimensions of the net. Parameters ---------- images_windows: (image filename, window list) iterable. context_crop: size of context border to crop in pixels. Returns ------- detections: list of {filename: image filename, window: crop coordinates, predictions: prediction vector} dicts.
Do windowed detection over given images and windows. Windows are extracted then warped to the input dimensions of the net.
[ "Do", "windowed", "detection", "over", "given", "images", "and", "windows", ".", "Windows", "are", "extracted", "then", "warped", "to", "the", "input", "dimensions", "of", "the", "net", "." ]
def detect_windows(self, images_windows): """ Do windowed detection over given images and windows. Windows are extracted then warped to the input dimensions of the net. Parameters ---------- images_windows: (image filename, window list) iterable. context_crop: size of context border to crop in pixels. Returns ------- detections: list of {filename: image filename, window: crop coordinates, predictions: prediction vector} dicts. """ # Extract windows. window_inputs = [] for image_fname, windows in images_windows: image = caffe.io.load_image(image_fname).astype(np.float32) for window in windows: window_inputs.append(self.crop(image, window)) # Run through the net (warping windows to input dimensions). in_ = self.inputs[0] caffe_in = np.zeros((len(window_inputs), window_inputs[0].shape[2]) + self.blobs[in_].data.shape[2:], dtype=np.float32) for ix, window_in in enumerate(window_inputs): caffe_in[ix] = self.transformer.preprocess(in_, window_in) out = self.forward_all(**{in_: caffe_in}) predictions = out[self.outputs[0]].squeeze(axis=(2, 3)) # Package predictions with images and windows. detections = [] ix = 0 for image_fname, windows in images_windows: for window in windows: detections.append({ 'window': window, 'prediction': predictions[ix], 'filename': image_fname }) ix += 1 return detections
[ "def", "detect_windows", "(", "self", ",", "images_windows", ")", ":", "# Extract windows.", "window_inputs", "=", "[", "]", "for", "image_fname", ",", "windows", "in", "images_windows", ":", "image", "=", "caffe", ".", "io", ".", "load_image", "(", "image_fna...
https://github.com/may0324/DeepCompression-caffe/blob/0aff6c1287bda4cfc7f378ed8a16524e1afabd8c/python/caffe/detector.py#L56-L99
RomanKubiak/ctrlr
f452347540725588736a425f38c67c3b514ef24d
JUCE/docs/doxygen/process_source_files.py
python
get_curly_brace_scope_end
(string, start_pos)
return -1
Given a string and a starting position of an opening brace, find the position of the closing brace.
Given a string and a starting position of an opening brace, find the position of the closing brace.
[ "Given", "a", "string", "and", "a", "starting", "position", "of", "an", "opening", "brace", "find", "the", "position", "of", "the", "closing", "brace", "." ]
def get_curly_brace_scope_end(string, start_pos): """Given a string and a starting position of an opening brace, find the position of the closing brace. """ start_pos += 1 string_end = len(string) bracket_counter = 1 while start_pos < string_end: if string[start_pos] == "{": bracket_counter += 1 elif string[start_pos] == "}": bracket_counter -= 1 if bracket_counter == 0: return start_pos start_pos += 1 return -1
[ "def", "get_curly_brace_scope_end", "(", "string", ",", "start_pos", ")", ":", "start_pos", "+=", "1", "string_end", "=", "len", "(", "string", ")", "bracket_counter", "=", "1", "while", "start_pos", "<", "string_end", ":", "if", "string", "[", "start_pos", ...
https://github.com/RomanKubiak/ctrlr/blob/f452347540725588736a425f38c67c3b514ef24d/JUCE/docs/doxygen/process_source_files.py#L9-L24
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/html.py
python
HtmlHelpWindow.GetData
(*args, **kwargs)
return _html.HtmlHelpWindow_GetData(*args, **kwargs)
GetData(self) -> HtmlHelpData
GetData(self) -> HtmlHelpData
[ "GetData", "(", "self", ")", "-", ">", "HtmlHelpData" ]
def GetData(*args, **kwargs): """GetData(self) -> HtmlHelpData""" return _html.HtmlHelpWindow_GetData(*args, **kwargs)
[ "def", "GetData", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_html", ".", "HtmlHelpWindow_GetData", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/html.py#L1590-L1592
mapnik/mapnik
f3da900c355e1d15059c4a91b00203dcc9d9f0ef
scons/scons-local-4.1.0/SCons/Tool/gfortran.py
python
generate
(env)
Add Builders and construction variables for gfortran to an Environment.
Add Builders and construction variables for gfortran to an Environment.
[ "Add", "Builders", "and", "construction", "variables", "for", "gfortran", "to", "an", "Environment", "." ]
def generate(env): """Add Builders and construction variables for gfortran to an Environment.""" fortran.generate(env) for dialect in ['F77', 'F90', 'FORTRAN', 'F95', 'F03', 'F08']: env['%s' % dialect] = 'gfortran' env['SH%s' % dialect] = '$%s' % dialect if env['PLATFORM'] in ['cygwin', 'win32']: env['SH%sFLAGS' % dialect] = SCons.Util.CLVar('$%sFLAGS' % dialect) else: env['SH%sFLAGS' % dialect] = SCons.Util.CLVar('$%sFLAGS -fPIC' % dialect) env['INC%sPREFIX' % dialect] = "-I" env['INC%sSUFFIX' % dialect] = "" env['FORTRANMODDIRPREFIX'] = "-J"
[ "def", "generate", "(", "env", ")", ":", "fortran", ".", "generate", "(", "env", ")", "for", "dialect", "in", "[", "'F77'", ",", "'F90'", ",", "'FORTRAN'", ",", "'F95'", ",", "'F03'", ",", "'F08'", "]", ":", "env", "[", "'%s'", "%", "dialect", "]",...
https://github.com/mapnik/mapnik/blob/f3da900c355e1d15059c4a91b00203dcc9d9f0ef/scons/scons-local-4.1.0/SCons/Tool/gfortran.py#L41-L57
isl-org/Open3D
79aec3ddde6a571ce2f28e4096477e52ec465244
python/open3d/visualization/_external_visualizer.py
python
ExternalVisualizer.draw
(self, geometry=None, *args, **kwargs)
This function has the same functionality as 'set'. This function is compatible with the standalone 'draw' function and can be used to redirect calls to the external visualizer. Note that only the geometry argument is supported, all other arguments will be ignored. Example: Here we use draw with the default external visualizer:: import open3d as o3d torus = o3d.geometry.TriangleMesh.create_torus() sphere = o3d.geometry.TriangleMesh.create_sphere() draw = o3d.visualization.EV.draw draw([ {'geometry': sphere, 'name': 'sphere'}, {'geometry': torus, 'name': 'torus', 'time': 1} ]) # now use the standard draw function as comparison draw = o3d.visualization.draw draw([ {'geometry': sphere, 'name': 'sphere'}, {'geometry': torus, 'name': 'torus', 'time': 1} ]) Args: geometry: The geometry to draw. This can be a geometry object, a list of geometries. To pass additional information along with the geometry we can use a dictionary. Supported keys for the dictionary are 'geometry', 'name', and 'time'.
This function has the same functionality as 'set'.
[ "This", "function", "has", "the", "same", "functionality", "as", "set", "." ]
def draw(self, geometry=None, *args, **kwargs): """This function has the same functionality as 'set'. This function is compatible with the standalone 'draw' function and can be used to redirect calls to the external visualizer. Note that only the geometry argument is supported, all other arguments will be ignored. Example: Here we use draw with the default external visualizer:: import open3d as o3d torus = o3d.geometry.TriangleMesh.create_torus() sphere = o3d.geometry.TriangleMesh.create_sphere() draw = o3d.visualization.EV.draw draw([ {'geometry': sphere, 'name': 'sphere'}, {'geometry': torus, 'name': 'torus', 'time': 1} ]) # now use the standard draw function as comparison draw = o3d.visualization.draw draw([ {'geometry': sphere, 'name': 'sphere'}, {'geometry': torus, 'name': 'torus', 'time': 1} ]) Args: geometry: The geometry to draw. This can be a geometry object, a list of geometries. To pass additional information along with the geometry we can use a dictionary. Supported keys for the dictionary are 'geometry', 'name', and 'time'. """ if args or kwargs: import warnings warnings.warn( "ExternalVisualizer.draw() does only support the 'geometry' argument", Warning) def add(g): if isinstance(g, dict): obj = g['geometry'] path = g.get('name', '') time = g.get('time', 0) self.set(obj=obj, path=path, time=time) else: self.set(g) if isinstance(geometry, (tuple, list)): for g in geometry: add(g) elif geometry is not None: add(geometry)
[ "def", "draw", "(", "self", ",", "geometry", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "args", "or", "kwargs", ":", "import", "warnings", "warnings", ".", "warn", "(", "\"ExternalVisualizer.draw() does only support the 'geometry' ...
https://github.com/isl-org/Open3D/blob/79aec3ddde6a571ce2f28e4096477e52ec465244/python/open3d/visualization/_external_visualizer.py#L158-L207
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
current/deps/v8/tools/grokdump.py
python
InspectionShell.do_k
(self, arguments)
Teach V8 heap layout information to the inspector. This increases the amount of annotations the inspector can produce while dumping data. The first page of each heap space is of particular interest because it contains known objects that do not move.
Teach V8 heap layout information to the inspector.
[ "Teach", "V8", "heap", "layout", "information", "to", "the", "inspector", "." ]
def do_k(self, arguments): """ Teach V8 heap layout information to the inspector. This increases the amount of annotations the inspector can produce while dumping data. The first page of each heap space is of particular interest because it contains known objects that do not move. """ self.padawan.PrintKnowledge()
[ "def", "do_k", "(", "self", ",", "arguments", ")", ":", "self", ".", "padawan", ".", "PrintKnowledge", "(", ")" ]
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/current/deps/v8/tools/grokdump.py#L3641-L3649
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/compiler.py
python
DefaultPassBuilder.define_objectmode_pipeline
(state, name='object')
return pm
Returns an object-mode pipeline based PassManager
Returns an object-mode pipeline based PassManager
[ "Returns", "an", "object", "-", "mode", "pipeline", "based", "PassManager" ]
def define_objectmode_pipeline(state, name='object'): """Returns an object-mode pipeline based PassManager """ pm = PassManager(name) if state.func_ir is None: pm.add_pass(TranslateByteCode, "analyzing bytecode") pm.add_pass(FixupArgs, "fix up args") pm.add_pass(IRProcessing, "processing IR") if utils.PYVERSION >= (3, 7): # The following passes are needed to adjust for looplifting pm.add_pass(CanonicalizeLoopEntry, "canonicalize loop entry") pm.add_pass(CanonicalizeLoopExit, "canonicalize loop exit") pm.add_pass(ObjectModeFrontEnd, "object mode frontend") pm.add_pass(InlineClosureLikes, "inline calls to locally defined closures") # convert any remaining closures into functions pm.add_pass(MakeFunctionToJitFunction, "convert make_function into JIT functions") pm.add_pass(AnnotateTypes, "annotate types") pm.add_pass(IRLegalization, "ensure IR is legal prior to lowering") pm.add_pass(ObjectModeBackEnd, "object mode backend") pm.finalize() return pm
[ "def", "define_objectmode_pipeline", "(", "state", ",", "name", "=", "'object'", ")", ":", "pm", "=", "PassManager", "(", "name", ")", "if", "state", ".", "func_ir", "is", "None", ":", "pm", ".", "add_pass", "(", "TranslateByteCode", ",", "\"analyzing byteco...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/compiler.py#L488-L512
abseil/abseil-cpp
73316fc3c565e5998983b0fb502d938ccddcded2
absl/abseil.podspec.gen.py
python
generate
(args)
Generates a podspec file from all BUILD files under absl directory.
Generates a podspec file from all BUILD files under absl directory.
[ "Generates", "a", "podspec", "file", "from", "all", "BUILD", "files", "under", "absl", "directory", "." ]
def generate(args): """Generates a podspec file from all BUILD files under absl directory.""" rules = filter(relevant_rule, collect_rules("absl")) with open(args.output, "wt") as f: write_podspec(f, rules, vars(args))
[ "def", "generate", "(", "args", ")", ":", "rules", "=", "filter", "(", "relevant_rule", ",", "collect_rules", "(", "\"absl\"", ")", ")", "with", "open", "(", "args", ".", "output", ",", "\"wt\"", ")", "as", "f", ":", "write_podspec", "(", "f", ",", "...
https://github.com/abseil/abseil-cpp/blob/73316fc3c565e5998983b0fb502d938ccddcded2/absl/abseil.podspec.gen.py#L200-L204
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
tools/idl_parser/idl_parser.py
python
IDLParser.p_TypeSuffixStartingWithArray
(self, p)
TypeSuffixStartingWithArray : '[' ']' TypeSuffix |
TypeSuffixStartingWithArray : '[' ']' TypeSuffix |
[ "TypeSuffixStartingWithArray", ":", "[", "]", "TypeSuffix", "|" ]
def p_TypeSuffixStartingWithArray(self, p): """TypeSuffixStartingWithArray : '[' ']' TypeSuffix | """ if len(p) > 1: p[0] = self.BuildProduction('Array', p, 0, p[3])
[ "def", "p_TypeSuffixStartingWithArray", "(", "self", ",", "p", ")", ":", "if", "len", "(", "p", ")", ">", "1", ":", "p", "[", "0", "]", "=", "self", ".", "BuildProduction", "(", "'Array'", ",", "p", ",", "0", ",", "p", "[", "3", "]", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/idl_parser/idl_parser.py#L1025-L1029
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_windows.py
python
TopLevelWindow.RequestUserAttention
(*args, **kwargs)
return _windows_.TopLevelWindow_RequestUserAttention(*args, **kwargs)
RequestUserAttention(self, int flags=USER_ATTENTION_INFO)
RequestUserAttention(self, int flags=USER_ATTENTION_INFO)
[ "RequestUserAttention", "(", "self", "int", "flags", "=", "USER_ATTENTION_INFO", ")" ]
def RequestUserAttention(*args, **kwargs): """RequestUserAttention(self, int flags=USER_ATTENTION_INFO)""" return _windows_.TopLevelWindow_RequestUserAttention(*args, **kwargs)
[ "def", "RequestUserAttention", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_windows_", ".", "TopLevelWindow_RequestUserAttention", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_windows.py#L469-L471
thalium/icebox
99d147d5b9269222225443ce171b4fd46d8985d4
third_party/virtualbox/src/VBox/VMM/VMMAll/IEMAllInstructionsPython.py
python
TestType.validate
(self, sValue)
return True
Returns True if value is okay, error message on failure.
Returns True if value is okay, error message on failure.
[ "Returns", "True", "if", "value", "is", "okay", "error", "message", "on", "failure", "." ]
def validate(self, sValue): """ Returns True if value is okay, error message on failure. """ try: self.get(sValue); except TestType.BadValue as oXcpt: return oXcpt.sMessage; return True;
[ "def", "validate", "(", "self", ",", "sValue", ")", ":", "try", ":", "self", ".", "get", "(", "sValue", ")", "except", "TestType", ".", "BadValue", "as", "oXcpt", ":", "return", "oXcpt", ".", "sMessage", "return", "True" ]
https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/VBox/VMM/VMMAll/IEMAllInstructionsPython.py#L833-L841
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py2/sklearn/externals/funcsigs.py
python
Parameter.replace
(self, name=_void, kind=_void, annotation=_void, default=_void, _partial_kwarg=_void)
return type(self)(name, kind, default=default, annotation=annotation, _partial_kwarg=_partial_kwarg)
Creates a customized copy of the Parameter.
Creates a customized copy of the Parameter.
[ "Creates", "a", "customized", "copy", "of", "the", "Parameter", "." ]
def replace(self, name=_void, kind=_void, annotation=_void, default=_void, _partial_kwarg=_void): '''Creates a customized copy of the Parameter.''' if name is _void: name = self._name if kind is _void: kind = self._kind if annotation is _void: annotation = self._annotation if default is _void: default = self._default if _partial_kwarg is _void: _partial_kwarg = self._partial_kwarg return type(self)(name, kind, default=default, annotation=annotation, _partial_kwarg=_partial_kwarg)
[ "def", "replace", "(", "self", ",", "name", "=", "_void", ",", "kind", "=", "_void", ",", "annotation", "=", "_void", ",", "default", "=", "_void", ",", "_partial_kwarg", "=", "_void", ")", ":", "if", "name", "is", "_void", ":", "name", "=", "self", ...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/externals/funcsigs.py#L282-L302
wenwei202/caffe
f54a74abaf6951d8485cbdcfa1d74a4c37839466
python/caffe/draw.py
python
get_layer_label
(layer, rankdir)
return node_label
Define node label based on layer type. Parameters ---------- layer : ? rankdir : {'LR', 'TB', 'BT'} Direction of graph layout. Returns ------- string : A label for the current layer
Define node label based on layer type.
[ "Define", "node", "label", "based", "on", "layer", "type", "." ]
def get_layer_label(layer, rankdir): """Define node label based on layer type. Parameters ---------- layer : ? rankdir : {'LR', 'TB', 'BT'} Direction of graph layout. Returns ------- string : A label for the current layer """ if rankdir in ('TB', 'BT'): # If graph orientation is vertical, horizontal space is free and # vertical space is not; separate words with spaces separator = ' ' else: # If graph orientation is horizontal, vertical space is free and # horizontal space is not; separate words with newlines separator = '\\n' if layer.type == 'Convolution' or layer.type == 'Deconvolution': # Outer double quotes needed or else colon characters don't parse # properly node_label = '"%s%s(%s)%skernel size: %d%sstride: %d%spad: %d"' %\ (layer.name, separator, layer.type, separator, layer.convolution_param.kernel_size[0] if len(layer.convolution_param.kernel_size._values) else 1, separator, layer.convolution_param.stride[0] if len(layer.convolution_param.stride._values) else 1, separator, layer.convolution_param.pad[0] if len(layer.convolution_param.pad._values) else 0) elif layer.type == 'Pooling': pooling_types_dict = get_pooling_types_dict() node_label = '"%s%s(%s %s)%skernel size: %d%sstride: %d%spad: %d"' %\ (layer.name, separator, pooling_types_dict[layer.pooling_param.pool], layer.type, separator, layer.pooling_param.kernel_size, separator, layer.pooling_param.stride, separator, layer.pooling_param.pad) else: node_label = '"%s%s(%s)"' % (layer.name, separator, layer.type) return node_label
[ "def", "get_layer_label", "(", "layer", ",", "rankdir", ")", ":", "if", "rankdir", "in", "(", "'TB'", ",", "'BT'", ")", ":", "# If graph orientation is vertical, horizontal space is free and", "# vertical space is not; separate words with spaces", "separator", "=", "' '", ...
https://github.com/wenwei202/caffe/blob/f54a74abaf6951d8485cbdcfa1d74a4c37839466/python/caffe/draw.py#L62-L114
google/mozc
7329757e1ad30e327c1ae823a8302c79482d6b9c
src/rewriter/gen_single_kanji_rewriter_data.py
python
ReadVariant
(stream)
return (variant_types, variant_items)
Parses variant data from stream.
Parses variant data from stream.
[ "Parses", "variant", "data", "from", "stream", "." ]
def ReadVariant(stream): """Parses variant data from stream.""" variant_types = [] variant_items = [] stream = code_generator_util.SkipLineComment(stream) stream = code_generator_util.ParseColumnStream(stream) for tokens in stream: if len(tokens) == 1: variant_types.append(tokens[0]) elif len(tokens) == 2 and variant_types: (target, original) = tokens variant_items.append([target, original, len(variant_types) - 1]) # For binary search by |target|, sort variant items here. variant_items.sort(key=lambda x: x[0]) return (variant_types, variant_items)
[ "def", "ReadVariant", "(", "stream", ")", ":", "variant_types", "=", "[", "]", "variant_items", "=", "[", "]", "stream", "=", "code_generator_util", ".", "SkipLineComment", "(", "stream", ")", "stream", "=", "code_generator_util", ".", "ParseColumnStream", "(", ...
https://github.com/google/mozc/blob/7329757e1ad30e327c1ae823a8302c79482d6b9c/src/rewriter/gen_single_kanji_rewriter_data.py#L61-L78
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/stringold.py
python
join
(words, sep = ' ')
return sep.join(words)
join(list [,sep]) -> string Return a string composed of the words in list, with intervening occurrences of sep. The default separator is a single space. (joinfields and join are synonymous)
join(list [,sep]) -> string
[ "join", "(", "list", "[", "sep", "]", ")", "-", ">", "string" ]
def join(words, sep = ' '): """join(list [,sep]) -> string Return a string composed of the words in list, with intervening occurrences of sep. The default separator is a single space. (joinfields and join are synonymous) """ return sep.join(words)
[ "def", "join", "(", "words", ",", "sep", "=", "' '", ")", ":", "return", "sep", ".", "join", "(", "words", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/stringold.py#L119-L129
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/slim/python/slim/nets/inception_v3.py
python
inception_v3_base
(inputs, final_endpoint='Mixed_7c', min_depth=16, depth_multiplier=1.0, scope=None)
Inception model from http://arxiv.org/abs/1512.00567. Constructs an Inception v3 network from inputs to the given final endpoint. This method can construct the network up to the final inception block Mixed_7c. Note that the names of the layers in the paper do not correspond to the names of the endpoints registered by this function although they build the same network. Here is a mapping from the old_names to the new names: Old name | New name ======================================= conv0 | Conv2d_1a_3x3 conv1 | Conv2d_2a_3x3 conv2 | Conv2d_2b_3x3 pool1 | MaxPool_3a_3x3 conv3 | Conv2d_3b_1x1 conv4 | Conv2d_4a_3x3 pool2 | MaxPool_5a_3x3 mixed_35x35x256a | Mixed_5b mixed_35x35x288a | Mixed_5c mixed_35x35x288b | Mixed_5d mixed_17x17x768a | Mixed_6a mixed_17x17x768b | Mixed_6b mixed_17x17x768c | Mixed_6c mixed_17x17x768d | Mixed_6d mixed_17x17x768e | Mixed_6e mixed_8x8x1280a | Mixed_7a mixed_8x8x2048a | Mixed_7b mixed_8x8x2048b | Mixed_7c Args: inputs: a tensor of size [batch_size, height, width, channels]. final_endpoint: specifies the endpoint to construct the network up to. It can be one of ['Conv2d_1a_3x3', 'Conv2d_2a_3x3', 'Conv2d_2b_3x3', 'MaxPool_3a_3x3', 'Conv2d_3b_1x1', 'Conv2d_4a_3x3', 'MaxPool_5a_3x3', 'Mixed_5b', 'Mixed_5c', 'Mixed_5d', 'Mixed_6a', 'Mixed_6b', 'Mixed_6c', 'Mixed_6d', 'Mixed_6e', 'Mixed_7a', 'Mixed_7b', 'Mixed_7c']. min_depth: Minimum depth value (number of channels) for all convolution ops. Enforced when depth_multiplier < 1, and not an active constraint when depth_multiplier >= 1. depth_multiplier: Float multiplier for the depth (number of channels) for all convolution ops. The value must be greater than zero. Typical usage will be to set this value in (0, 1) to reduce the number of parameters or computation cost of the model. scope: Optional variable_scope. Returns: tensor_out: output tensor corresponding to the final_endpoint. end_points: a set of activations for external use, for example summaries or losses. Raises: ValueError: if final_endpoint is not set to one of the predefined values, or depth_multiplier <= 0
Inception model from http://arxiv.org/abs/1512.00567.
[ "Inception", "model", "from", "http", ":", "//", "arxiv", ".", "org", "/", "abs", "/", "1512", ".", "00567", "." ]
def inception_v3_base(inputs, final_endpoint='Mixed_7c', min_depth=16, depth_multiplier=1.0, scope=None): """Inception model from http://arxiv.org/abs/1512.00567. Constructs an Inception v3 network from inputs to the given final endpoint. This method can construct the network up to the final inception block Mixed_7c. Note that the names of the layers in the paper do not correspond to the names of the endpoints registered by this function although they build the same network. Here is a mapping from the old_names to the new names: Old name | New name ======================================= conv0 | Conv2d_1a_3x3 conv1 | Conv2d_2a_3x3 conv2 | Conv2d_2b_3x3 pool1 | MaxPool_3a_3x3 conv3 | Conv2d_3b_1x1 conv4 | Conv2d_4a_3x3 pool2 | MaxPool_5a_3x3 mixed_35x35x256a | Mixed_5b mixed_35x35x288a | Mixed_5c mixed_35x35x288b | Mixed_5d mixed_17x17x768a | Mixed_6a mixed_17x17x768b | Mixed_6b mixed_17x17x768c | Mixed_6c mixed_17x17x768d | Mixed_6d mixed_17x17x768e | Mixed_6e mixed_8x8x1280a | Mixed_7a mixed_8x8x2048a | Mixed_7b mixed_8x8x2048b | Mixed_7c Args: inputs: a tensor of size [batch_size, height, width, channels]. final_endpoint: specifies the endpoint to construct the network up to. It can be one of ['Conv2d_1a_3x3', 'Conv2d_2a_3x3', 'Conv2d_2b_3x3', 'MaxPool_3a_3x3', 'Conv2d_3b_1x1', 'Conv2d_4a_3x3', 'MaxPool_5a_3x3', 'Mixed_5b', 'Mixed_5c', 'Mixed_5d', 'Mixed_6a', 'Mixed_6b', 'Mixed_6c', 'Mixed_6d', 'Mixed_6e', 'Mixed_7a', 'Mixed_7b', 'Mixed_7c']. min_depth: Minimum depth value (number of channels) for all convolution ops. Enforced when depth_multiplier < 1, and not an active constraint when depth_multiplier >= 1. depth_multiplier: Float multiplier for the depth (number of channels) for all convolution ops. The value must be greater than zero. Typical usage will be to set this value in (0, 1) to reduce the number of parameters or computation cost of the model. scope: Optional variable_scope. Returns: tensor_out: output tensor corresponding to the final_endpoint. end_points: a set of activations for external use, for example summaries or losses. Raises: ValueError: if final_endpoint is not set to one of the predefined values, or depth_multiplier <= 0 """ # end_points will collect relevant activations for external use, for example # summaries or losses. end_points = {} if depth_multiplier <= 0: raise ValueError('depth_multiplier is not greater than zero.') depth = lambda d: max(int(d * depth_multiplier), min_depth) with variable_scope.variable_scope(scope, 'InceptionV3', [inputs]): with arg_scope( [layers.conv2d, layers_lib.max_pool2d, layers_lib.avg_pool2d], stride=1, padding='VALID'): # 299 x 299 x 3 end_point = 'Conv2d_1a_3x3' net = layers.conv2d(inputs, depth(32), [3, 3], stride=2, scope=end_point) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # 149 x 149 x 32 end_point = 'Conv2d_2a_3x3' net = layers.conv2d(net, depth(32), [3, 3], scope=end_point) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # 147 x 147 x 32 end_point = 'Conv2d_2b_3x3' net = layers.conv2d( net, depth(64), [3, 3], padding='SAME', scope=end_point) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # 147 x 147 x 64 end_point = 'MaxPool_3a_3x3' net = layers_lib.max_pool2d(net, [3, 3], stride=2, scope=end_point) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # 73 x 73 x 64 end_point = 'Conv2d_3b_1x1' net = layers.conv2d(net, depth(80), [1, 1], scope=end_point) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # 73 x 73 x 80. end_point = 'Conv2d_4a_3x3' net = layers.conv2d(net, depth(192), [3, 3], scope=end_point) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # 71 x 71 x 192. end_point = 'MaxPool_5a_3x3' net = layers_lib.max_pool2d(net, [3, 3], stride=2, scope=end_point) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # 35 x 35 x 192. # Inception blocks with arg_scope( [layers.conv2d, layers_lib.max_pool2d, layers_lib.avg_pool2d], stride=1, padding='SAME'): # mixed: 35 x 35 x 256. end_point = 'Mixed_5b' with variable_scope.variable_scope(end_point): with variable_scope.variable_scope('Branch_0'): branch_0 = layers.conv2d( net, depth(64), [1, 1], scope='Conv2d_0a_1x1') with variable_scope.variable_scope('Branch_1'): branch_1 = layers.conv2d( net, depth(48), [1, 1], scope='Conv2d_0a_1x1') branch_1 = layers.conv2d( branch_1, depth(64), [5, 5], scope='Conv2d_0b_5x5') with variable_scope.variable_scope('Branch_2'): branch_2 = layers.conv2d( net, depth(64), [1, 1], scope='Conv2d_0a_1x1') branch_2 = layers.conv2d( branch_2, depth(96), [3, 3], scope='Conv2d_0b_3x3') branch_2 = layers.conv2d( branch_2, depth(96), [3, 3], scope='Conv2d_0c_3x3') with variable_scope.variable_scope('Branch_3'): branch_3 = layers_lib.avg_pool2d(net, [3, 3], scope='AvgPool_0a_3x3') branch_3 = layers.conv2d( branch_3, depth(32), [1, 1], scope='Conv2d_0b_1x1') net = array_ops.concat([branch_0, branch_1, branch_2, branch_3], 3) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # mixed_1: 35 x 35 x 288. end_point = 'Mixed_5c' with variable_scope.variable_scope(end_point): with variable_scope.variable_scope('Branch_0'): branch_0 = layers.conv2d( net, depth(64), [1, 1], scope='Conv2d_0a_1x1') with variable_scope.variable_scope('Branch_1'): branch_1 = layers.conv2d( net, depth(48), [1, 1], scope='Conv2d_0b_1x1') branch_1 = layers.conv2d( branch_1, depth(64), [5, 5], scope='Conv_1_0c_5x5') with variable_scope.variable_scope('Branch_2'): branch_2 = layers.conv2d( net, depth(64), [1, 1], scope='Conv2d_0a_1x1') branch_2 = layers.conv2d( branch_2, depth(96), [3, 3], scope='Conv2d_0b_3x3') branch_2 = layers.conv2d( branch_2, depth(96), [3, 3], scope='Conv2d_0c_3x3') with variable_scope.variable_scope('Branch_3'): branch_3 = layers_lib.avg_pool2d(net, [3, 3], scope='AvgPool_0a_3x3') branch_3 = layers.conv2d( branch_3, depth(64), [1, 1], scope='Conv2d_0b_1x1') net = array_ops.concat([branch_0, branch_1, branch_2, branch_3], 3) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # mixed_2: 35 x 35 x 288. end_point = 'Mixed_5d' with variable_scope.variable_scope(end_point): with variable_scope.variable_scope('Branch_0'): branch_0 = layers.conv2d( net, depth(64), [1, 1], scope='Conv2d_0a_1x1') with variable_scope.variable_scope('Branch_1'): branch_1 = layers.conv2d( net, depth(48), [1, 1], scope='Conv2d_0a_1x1') branch_1 = layers.conv2d( branch_1, depth(64), [5, 5], scope='Conv2d_0b_5x5') with variable_scope.variable_scope('Branch_2'): branch_2 = layers.conv2d( net, depth(64), [1, 1], scope='Conv2d_0a_1x1') branch_2 = layers.conv2d( branch_2, depth(96), [3, 3], scope='Conv2d_0b_3x3') branch_2 = layers.conv2d( branch_2, depth(96), [3, 3], scope='Conv2d_0c_3x3') with variable_scope.variable_scope('Branch_3'): branch_3 = layers_lib.avg_pool2d(net, [3, 3], scope='AvgPool_0a_3x3') branch_3 = layers.conv2d( branch_3, depth(64), [1, 1], scope='Conv2d_0b_1x1') net = array_ops.concat([branch_0, branch_1, branch_2, branch_3], 3) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # mixed_3: 17 x 17 x 768. end_point = 'Mixed_6a' with variable_scope.variable_scope(end_point): with variable_scope.variable_scope('Branch_0'): branch_0 = layers.conv2d( net, depth(384), [3, 3], stride=2, padding='VALID', scope='Conv2d_1a_1x1') with variable_scope.variable_scope('Branch_1'): branch_1 = layers.conv2d( net, depth(64), [1, 1], scope='Conv2d_0a_1x1') branch_1 = layers.conv2d( branch_1, depth(96), [3, 3], scope='Conv2d_0b_3x3') branch_1 = layers.conv2d( branch_1, depth(96), [3, 3], stride=2, padding='VALID', scope='Conv2d_1a_1x1') with variable_scope.variable_scope('Branch_2'): branch_2 = layers_lib.max_pool2d( net, [3, 3], stride=2, padding='VALID', scope='MaxPool_1a_3x3') net = array_ops.concat([branch_0, branch_1, branch_2], 3) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # mixed4: 17 x 17 x 768. end_point = 'Mixed_6b' with variable_scope.variable_scope(end_point): with variable_scope.variable_scope('Branch_0'): branch_0 = layers.conv2d( net, depth(192), [1, 1], scope='Conv2d_0a_1x1') with variable_scope.variable_scope('Branch_1'): branch_1 = layers.conv2d( net, depth(128), [1, 1], scope='Conv2d_0a_1x1') branch_1 = layers.conv2d( branch_1, depth(128), [1, 7], scope='Conv2d_0b_1x7') branch_1 = layers.conv2d( branch_1, depth(192), [7, 1], scope='Conv2d_0c_7x1') with variable_scope.variable_scope('Branch_2'): branch_2 = layers.conv2d( net, depth(128), [1, 1], scope='Conv2d_0a_1x1') branch_2 = layers.conv2d( branch_2, depth(128), [7, 1], scope='Conv2d_0b_7x1') branch_2 = layers.conv2d( branch_2, depth(128), [1, 7], scope='Conv2d_0c_1x7') branch_2 = layers.conv2d( branch_2, depth(128), [7, 1], scope='Conv2d_0d_7x1') branch_2 = layers.conv2d( branch_2, depth(192), [1, 7], scope='Conv2d_0e_1x7') with variable_scope.variable_scope('Branch_3'): branch_3 = layers_lib.avg_pool2d(net, [3, 3], scope='AvgPool_0a_3x3') branch_3 = layers.conv2d( branch_3, depth(192), [1, 1], scope='Conv2d_0b_1x1') net = array_ops.concat([branch_0, branch_1, branch_2, branch_3], 3) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # mixed_5: 17 x 17 x 768. end_point = 'Mixed_6c' with variable_scope.variable_scope(end_point): with variable_scope.variable_scope('Branch_0'): branch_0 = layers.conv2d( net, depth(192), [1, 1], scope='Conv2d_0a_1x1') with variable_scope.variable_scope('Branch_1'): branch_1 = layers.conv2d( net, depth(160), [1, 1], scope='Conv2d_0a_1x1') branch_1 = layers.conv2d( branch_1, depth(160), [1, 7], scope='Conv2d_0b_1x7') branch_1 = layers.conv2d( branch_1, depth(192), [7, 1], scope='Conv2d_0c_7x1') with variable_scope.variable_scope('Branch_2'): branch_2 = layers.conv2d( net, depth(160), [1, 1], scope='Conv2d_0a_1x1') branch_2 = layers.conv2d( branch_2, depth(160), [7, 1], scope='Conv2d_0b_7x1') branch_2 = layers.conv2d( branch_2, depth(160), [1, 7], scope='Conv2d_0c_1x7') branch_2 = layers.conv2d( branch_2, depth(160), [7, 1], scope='Conv2d_0d_7x1') branch_2 = layers.conv2d( branch_2, depth(192), [1, 7], scope='Conv2d_0e_1x7') with variable_scope.variable_scope('Branch_3'): branch_3 = layers_lib.avg_pool2d(net, [3, 3], scope='AvgPool_0a_3x3') branch_3 = layers.conv2d( branch_3, depth(192), [1, 1], scope='Conv2d_0b_1x1') net = array_ops.concat([branch_0, branch_1, branch_2, branch_3], 3) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # mixed_6: 17 x 17 x 768. end_point = 'Mixed_6d' with variable_scope.variable_scope(end_point): with variable_scope.variable_scope('Branch_0'): branch_0 = layers.conv2d( net, depth(192), [1, 1], scope='Conv2d_0a_1x1') with variable_scope.variable_scope('Branch_1'): branch_1 = layers.conv2d( net, depth(160), [1, 1], scope='Conv2d_0a_1x1') branch_1 = layers.conv2d( branch_1, depth(160), [1, 7], scope='Conv2d_0b_1x7') branch_1 = layers.conv2d( branch_1, depth(192), [7, 1], scope='Conv2d_0c_7x1') with variable_scope.variable_scope('Branch_2'): branch_2 = layers.conv2d( net, depth(160), [1, 1], scope='Conv2d_0a_1x1') branch_2 = layers.conv2d( branch_2, depth(160), [7, 1], scope='Conv2d_0b_7x1') branch_2 = layers.conv2d( branch_2, depth(160), [1, 7], scope='Conv2d_0c_1x7') branch_2 = layers.conv2d( branch_2, depth(160), [7, 1], scope='Conv2d_0d_7x1') branch_2 = layers.conv2d( branch_2, depth(192), [1, 7], scope='Conv2d_0e_1x7') with variable_scope.variable_scope('Branch_3'): branch_3 = layers_lib.avg_pool2d(net, [3, 3], scope='AvgPool_0a_3x3') branch_3 = layers.conv2d( branch_3, depth(192), [1, 1], scope='Conv2d_0b_1x1') net = array_ops.concat([branch_0, branch_1, branch_2, branch_3], 3) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # mixed_7: 17 x 17 x 768. end_point = 'Mixed_6e' with variable_scope.variable_scope(end_point): with variable_scope.variable_scope('Branch_0'): branch_0 = layers.conv2d( net, depth(192), [1, 1], scope='Conv2d_0a_1x1') with variable_scope.variable_scope('Branch_1'): branch_1 = layers.conv2d( net, depth(192), [1, 1], scope='Conv2d_0a_1x1') branch_1 = layers.conv2d( branch_1, depth(192), [1, 7], scope='Conv2d_0b_1x7') branch_1 = layers.conv2d( branch_1, depth(192), [7, 1], scope='Conv2d_0c_7x1') with variable_scope.variable_scope('Branch_2'): branch_2 = layers.conv2d( net, depth(192), [1, 1], scope='Conv2d_0a_1x1') branch_2 = layers.conv2d( branch_2, depth(192), [7, 1], scope='Conv2d_0b_7x1') branch_2 = layers.conv2d( branch_2, depth(192), [1, 7], scope='Conv2d_0c_1x7') branch_2 = layers.conv2d( branch_2, depth(192), [7, 1], scope='Conv2d_0d_7x1') branch_2 = layers.conv2d( branch_2, depth(192), [1, 7], scope='Conv2d_0e_1x7') with variable_scope.variable_scope('Branch_3'): branch_3 = layers_lib.avg_pool2d(net, [3, 3], scope='AvgPool_0a_3x3') branch_3 = layers.conv2d( branch_3, depth(192), [1, 1], scope='Conv2d_0b_1x1') net = array_ops.concat([branch_0, branch_1, branch_2, branch_3], 3) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # mixed_8: 8 x 8 x 1280. end_point = 'Mixed_7a' with variable_scope.variable_scope(end_point): with variable_scope.variable_scope('Branch_0'): branch_0 = layers.conv2d( net, depth(192), [1, 1], scope='Conv2d_0a_1x1') branch_0 = layers.conv2d( branch_0, depth(320), [3, 3], stride=2, padding='VALID', scope='Conv2d_1a_3x3') with variable_scope.variable_scope('Branch_1'): branch_1 = layers.conv2d( net, depth(192), [1, 1], scope='Conv2d_0a_1x1') branch_1 = layers.conv2d( branch_1, depth(192), [1, 7], scope='Conv2d_0b_1x7') branch_1 = layers.conv2d( branch_1, depth(192), [7, 1], scope='Conv2d_0c_7x1') branch_1 = layers.conv2d( branch_1, depth(192), [3, 3], stride=2, padding='VALID', scope='Conv2d_1a_3x3') with variable_scope.variable_scope('Branch_2'): branch_2 = layers_lib.max_pool2d( net, [3, 3], stride=2, padding='VALID', scope='MaxPool_1a_3x3') net = array_ops.concat([branch_0, branch_1, branch_2], 3) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # mixed_9: 8 x 8 x 2048. end_point = 'Mixed_7b' with variable_scope.variable_scope(end_point): with variable_scope.variable_scope('Branch_0'): branch_0 = layers.conv2d( net, depth(320), [1, 1], scope='Conv2d_0a_1x1') with variable_scope.variable_scope('Branch_1'): branch_1 = layers.conv2d( net, depth(384), [1, 1], scope='Conv2d_0a_1x1') branch_1 = array_ops.concat( [ layers.conv2d( branch_1, depth(384), [1, 3], scope='Conv2d_0b_1x3'), layers.conv2d( branch_1, depth(384), [3, 1], scope='Conv2d_0b_3x1') ], 3) with variable_scope.variable_scope('Branch_2'): branch_2 = layers.conv2d( net, depth(448), [1, 1], scope='Conv2d_0a_1x1') branch_2 = layers.conv2d( branch_2, depth(384), [3, 3], scope='Conv2d_0b_3x3') branch_2 = array_ops.concat( [ layers.conv2d( branch_2, depth(384), [1, 3], scope='Conv2d_0c_1x3'), layers.conv2d( branch_2, depth(384), [3, 1], scope='Conv2d_0d_3x1') ], 3) with variable_scope.variable_scope('Branch_3'): branch_3 = layers_lib.avg_pool2d(net, [3, 3], scope='AvgPool_0a_3x3') branch_3 = layers.conv2d( branch_3, depth(192), [1, 1], scope='Conv2d_0b_1x1') net = array_ops.concat([branch_0, branch_1, branch_2, branch_3], 3) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # mixed_10: 8 x 8 x 2048. end_point = 'Mixed_7c' with variable_scope.variable_scope(end_point): with variable_scope.variable_scope('Branch_0'): branch_0 = layers.conv2d( net, depth(320), [1, 1], scope='Conv2d_0a_1x1') with variable_scope.variable_scope('Branch_1'): branch_1 = layers.conv2d( net, depth(384), [1, 1], scope='Conv2d_0a_1x1') branch_1 = array_ops.concat( [ layers.conv2d( branch_1, depth(384), [1, 3], scope='Conv2d_0b_1x3'), layers.conv2d( branch_1, depth(384), [3, 1], scope='Conv2d_0c_3x1') ], 3) with variable_scope.variable_scope('Branch_2'): branch_2 = layers.conv2d( net, depth(448), [1, 1], scope='Conv2d_0a_1x1') branch_2 = layers.conv2d( branch_2, depth(384), [3, 3], scope='Conv2d_0b_3x3') branch_2 = array_ops.concat( [ layers.conv2d( branch_2, depth(384), [1, 3], scope='Conv2d_0c_1x3'), layers.conv2d( branch_2, depth(384), [3, 1], scope='Conv2d_0d_3x1') ], 3) with variable_scope.variable_scope('Branch_3'): branch_3 = layers_lib.avg_pool2d(net, [3, 3], scope='AvgPool_0a_3x3') branch_3 = layers.conv2d( branch_3, depth(192), [1, 1], scope='Conv2d_0b_1x1') net = array_ops.concat([branch_0, branch_1, branch_2, branch_3], 3) end_points[end_point] = net if end_point == final_endpoint: return net, end_points raise ValueError('Unknown final endpoint %s' % final_endpoint)
[ "def", "inception_v3_base", "(", "inputs", ",", "final_endpoint", "=", "'Mixed_7c'", ",", "min_depth", "=", "16", ",", "depth_multiplier", "=", "1.0", ",", "scope", "=", "None", ")", ":", "# end_points will collect relevant activations for external use, for example", "#...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/slim/python/slim/nets/inception_v3.py#L35-L510
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/logging/handlers.py
python
NTEventLogHandler.getEventType
(self, record)
return self.typemap.get(record.levelno, self.deftype)
Return the event type for the record. Override this if you want to specify your own types. This version does a mapping using the handler's typemap attribute, which is set up in __init__() to a dictionary which contains mappings for DEBUG, INFO, WARNING, ERROR and CRITICAL. If you are using your own levels you will either need to override this method or place a suitable dictionary in the handler's typemap attribute.
Return the event type for the record.
[ "Return", "the", "event", "type", "for", "the", "record", "." ]
def getEventType(self, record): """ Return the event type for the record. Override this if you want to specify your own types. This version does a mapping using the handler's typemap attribute, which is set up in __init__() to a dictionary which contains mappings for DEBUG, INFO, WARNING, ERROR and CRITICAL. If you are using your own levels you will either need to override this method or place a suitable dictionary in the handler's typemap attribute. """ return self.typemap.get(record.levelno, self.deftype)
[ "def", "getEventType", "(", "self", ",", "record", ")", ":", "return", "self", ".", "typemap", ".", "get", "(", "record", ".", "levelno", ",", "self", ".", "deftype", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/logging/handlers.py#L1125-L1136
google/llvm-propeller
45c226984fe8377ebfb2ad7713c680d652ba678d
clang/tools/scan-view/share/ScanView.py
python
ScanViewRequestHandler.do_POST
(self)
Serve a POST request.
Serve a POST request.
[ "Serve", "a", "POST", "request", "." ]
def do_POST(self): """Serve a POST request.""" try: length = self.headers.getheader('content-length') or "0" try: length = int(length) except: length = 0 content = self.rfile.read(length) fields = parse_query(content) f = self.send_head(fields) if f: self.copyfile(f, self.wfile) f.close() except Exception as e: self.handle_exception(e)
[ "def", "do_POST", "(", "self", ")", ":", "try", ":", "length", "=", "self", ".", "headers", ".", "getheader", "(", "'content-length'", ")", "or", "\"0\"", "try", ":", "length", "=", "int", "(", "length", ")", "except", ":", "length", "=", "0", "conte...
https://github.com/google/llvm-propeller/blob/45c226984fe8377ebfb2ad7713c680d652ba678d/clang/tools/scan-view/share/ScanView.py#L236-L251
ivansafrin/Polycode
37a40fefe194ec7f6e9d1257f3bb3517b0a168bc
Bindings/Scripts/create_lua_library/zipfile.py
python
_EndRecData
(fpin)
return
Return data from the "End of Central Directory" record, or None. The data is a list of the nine items in the ZIP "End of central dir" record followed by a tenth item, the file seek offset of this record.
Return data from the "End of Central Directory" record, or None.
[ "Return", "data", "from", "the", "End", "of", "Central", "Directory", "record", "or", "None", "." ]
def _EndRecData(fpin): """Return data from the "End of Central Directory" record, or None. The data is a list of the nine items in the ZIP "End of central dir" record followed by a tenth item, the file seek offset of this record.""" # Determine file size fpin.seek(0, 2) filesize = fpin.tell() # Check to see if this is ZIP file with no archive comment (the # "end of central directory" structure should be the last item in the # file if this is the case). try: fpin.seek(-sizeEndCentDir, 2) except IOError: return None data = fpin.read() if data[0:4] == stringEndArchive and data[-2:] == "\000\000": # the signature is correct and there's no comment, unpack structure endrec = struct.unpack(structEndArchive, data) endrec=list(endrec) # Append a blank comment and record start offset endrec.append("") endrec.append(filesize - sizeEndCentDir) # Try to read the "Zip64 end of central directory" structure return _EndRecData64(fpin, -sizeEndCentDir, endrec) # Either this is not a ZIP file, or it is a ZIP file with an archive # comment. Search the end of the file for the "end of central directory" # record signature. The comment is the last item in the ZIP file and may be # up to 64K long. It is assumed that the "end of central directory" magic # number does not appear in the comment. maxCommentStart = max(filesize - (1 << 16) - sizeEndCentDir, 0) fpin.seek(maxCommentStart, 0) data = fpin.read() start = data.rfind(stringEndArchive) if start >= 0: # found the magic number; attempt to unpack and interpret recData = data[start:start+sizeEndCentDir] endrec = list(struct.unpack(structEndArchive, recData)) commentSize = endrec[_ECD_COMMENT_SIZE] #as claimed by the zip file comment = data[start+sizeEndCentDir:start+sizeEndCentDir+commentSize] endrec.append(comment) endrec.append(maxCommentStart + start) # Try to read the "Zip64 end of central directory" structure return _EndRecData64(fpin, maxCommentStart + start - filesize, endrec) # Unable to find a valid end of central directory structure return
[ "def", "_EndRecData", "(", "fpin", ")", ":", "# Determine file size", "fpin", ".", "seek", "(", "0", ",", "2", ")", "filesize", "=", "fpin", ".", "tell", "(", ")", "# Check to see if this is ZIP file with no archive comment (the", "# \"end of central directory\" structu...
https://github.com/ivansafrin/Polycode/blob/37a40fefe194ec7f6e9d1257f3bb3517b0a168bc/Bindings/Scripts/create_lua_library/zipfile.py#L196-L249
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/debug/lib/source_utils.py
python
annotate_source
(dump, source_file_path, do_dumped_tensors=False, file_stack_top=False, min_line=None, max_line=None)
return line_to_op_names
Annotate a Python source file with a list of ops created at each line. (The annotation doesn't change the source file itself.) Args: dump: (`DebugDumpDir`) A `DebugDumpDir` object of which the Python graph has been loaded. source_file_path: (`str`) Path to the source file being annotated. do_dumped_tensors: (`str`) Whether dumped Tensors, instead of ops are to be used to annotate the source file. file_stack_top: (`bool`) Whether only the top stack trace in the specified source file is to be annotated. min_line: (`None` or `int`) The 1-based line to start annotate the source file from (inclusive). max_line: (`None` or `int`) The 1-based line number to end the annotation at (exclusive). Returns: A `dict` mapping 1-based line number to a list of op name(s) created at that line, or tensor names if `do_dumped_tensors` is True. Raises: ValueError: If the dump object does not have a Python graph set.
Annotate a Python source file with a list of ops created at each line.
[ "Annotate", "a", "Python", "source", "file", "with", "a", "list", "of", "ops", "created", "at", "each", "line", "." ]
def annotate_source(dump, source_file_path, do_dumped_tensors=False, file_stack_top=False, min_line=None, max_line=None): """Annotate a Python source file with a list of ops created at each line. (The annotation doesn't change the source file itself.) Args: dump: (`DebugDumpDir`) A `DebugDumpDir` object of which the Python graph has been loaded. source_file_path: (`str`) Path to the source file being annotated. do_dumped_tensors: (`str`) Whether dumped Tensors, instead of ops are to be used to annotate the source file. file_stack_top: (`bool`) Whether only the top stack trace in the specified source file is to be annotated. min_line: (`None` or `int`) The 1-based line to start annotate the source file from (inclusive). max_line: (`None` or `int`) The 1-based line number to end the annotation at (exclusive). Returns: A `dict` mapping 1-based line number to a list of op name(s) created at that line, or tensor names if `do_dumped_tensors` is True. Raises: ValueError: If the dump object does not have a Python graph set. """ py_graph = dump.python_graph if not py_graph: raise ValueError("Cannot perform source annotation due to a lack of set " "Python graph in the dump object") source_file_path = _norm_abs_path(source_file_path) line_to_op_names = {} for op in py_graph.get_operations(): for file_path, line_number, _, _ in reversed(dump.node_traceback(op.name)): if (min_line is not None and line_number < min_line or max_line is not None and line_number >= max_line): continue if _norm_abs_path(file_path) != source_file_path: continue if do_dumped_tensors: watch_keys = dump.debug_watch_keys(op.name) # Convert watch keys to unique Tensor names. items_to_append = list( set(map(_convert_watch_key_to_tensor_name, watch_keys))) else: items_to_append = [op.name] if line_number in line_to_op_names: line_to_op_names[line_number].extend(items_to_append) else: line_to_op_names[line_number] = items_to_append if file_stack_top: break return line_to_op_names
[ "def", "annotate_source", "(", "dump", ",", "source_file_path", ",", "do_dumped_tensors", "=", "False", ",", "file_stack_top", "=", "False", ",", "min_line", "=", "None", ",", "max_line", "=", "None", ")", ":", "py_graph", "=", "dump", ".", "python_graph", "...
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/debug/lib/source_utils.py#L152-L216
BestSonny/SSTD
174d452189f6bf9cf4b6957719392008bd974069
python/caffe/pycaffe.py
python
_Net_forward
(self, blobs=None, start=None, end=None, **kwargs)
return {out: self.blobs[out].data for out in outputs}
Forward pass: prepare inputs and run the net forward. Parameters ---------- blobs : list of blobs to return in addition to output blobs. kwargs : Keys are input blob names and values are blob ndarrays. For formatting inputs for Caffe, see Net.preprocess(). If None, input is taken from data layers. start : optional name of layer at which to begin the forward pass end : optional name of layer at which to finish the forward pass (inclusive) Returns ------- outs : {blob name: blob ndarray} dict.
Forward pass: prepare inputs and run the net forward.
[ "Forward", "pass", ":", "prepare", "inputs", "and", "run", "the", "net", "forward", "." ]
def _Net_forward(self, blobs=None, start=None, end=None, **kwargs): """ Forward pass: prepare inputs and run the net forward. Parameters ---------- blobs : list of blobs to return in addition to output blobs. kwargs : Keys are input blob names and values are blob ndarrays. For formatting inputs for Caffe, see Net.preprocess(). If None, input is taken from data layers. start : optional name of layer at which to begin the forward pass end : optional name of layer at which to finish the forward pass (inclusive) Returns ------- outs : {blob name: blob ndarray} dict. """ if blobs is None: blobs = [] if start is not None: start_ind = list(self._layer_names).index(start) else: start_ind = 0 if end is not None: end_ind = list(self._layer_names).index(end) outputs = set([end] + blobs) else: end_ind = len(self.layers) - 1 outputs = set(self.outputs + blobs) if kwargs: if set(kwargs.keys()) != set(self.inputs): raise Exception('Input blob arguments do not match net inputs.') # Set input according to defined shapes and make arrays single and # C-contiguous as Caffe expects. for in_, blob in six.iteritems(kwargs): if blob.shape[0] != self.blobs[in_].shape[0]: raise Exception('Input is not batch sized') self.blobs[in_].data[...] = blob self._forward(start_ind, end_ind) # Unpack blobs to extract return {out: self.blobs[out].data for out in outputs}
[ "def", "_Net_forward", "(", "self", ",", "blobs", "=", "None", ",", "start", "=", "None", ",", "end", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "blobs", "is", "None", ":", "blobs", "=", "[", "]", "if", "start", "is", "not", "None", ...
https://github.com/BestSonny/SSTD/blob/174d452189f6bf9cf4b6957719392008bd974069/python/caffe/pycaffe.py#L78-L124
bryanyzhu/Hidden-Two-Stream
f7f684adbdacb6df6b1cf196c3a476cd23484a0f
scripts/cpp_lint.py
python
CleansedLines._CollapseStrings
(elided)
return elided
Collapses strings and chars on a line to simple "" or '' blocks. We nix strings first so we're not fooled by text like '"http://"' Args: elided: The line being processed. Returns: The line with collapsed strings.
Collapses strings and chars on a line to simple "" or '' blocks.
[ "Collapses", "strings", "and", "chars", "on", "a", "line", "to", "simple", "or", "blocks", "." ]
def _CollapseStrings(elided): """Collapses strings and chars on a line to simple "" or '' blocks. We nix strings first so we're not fooled by text like '"http://"' Args: elided: The line being processed. Returns: The line with collapsed strings. """ if not _RE_PATTERN_INCLUDE.match(elided): # Remove escaped characters first to make quote/single quote collapsing # basic. Things that look like escaped characters shouldn't occur # outside of strings and chars. elided = _RE_PATTERN_CLEANSE_LINE_ESCAPES.sub('', elided) elided = _RE_PATTERN_CLEANSE_LINE_SINGLE_QUOTES.sub("''", elided) elided = _RE_PATTERN_CLEANSE_LINE_DOUBLE_QUOTES.sub('""', elided) return elided
[ "def", "_CollapseStrings", "(", "elided", ")", ":", "if", "not", "_RE_PATTERN_INCLUDE", ".", "match", "(", "elided", ")", ":", "# Remove escaped characters first to make quote/single quote collapsing", "# basic. Things that look like escaped characters shouldn't occur", "# outside...
https://github.com/bryanyzhu/Hidden-Two-Stream/blob/f7f684adbdacb6df6b1cf196c3a476cd23484a0f/scripts/cpp_lint.py#L1209-L1227
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/bsddb/dbutils.py
python
DeadlockWrap
(function, *_args, **_kwargs)
DeadlockWrap(function, *_args, **_kwargs) - automatically retries function in case of a database deadlock. This is a function intended to be used to wrap database calls such that they perform retrys with exponentially backing off sleeps in between when a DBLockDeadlockError exception is raised. A 'max_retries' parameter may optionally be passed to prevent it from retrying forever (in which case the exception will be reraised). d = DB(...) d.open(...) DeadlockWrap(d.put, "foo", data="bar") # set key "foo" to "bar"
DeadlockWrap(function, *_args, **_kwargs) - automatically retries function in case of a database deadlock.
[ "DeadlockWrap", "(", "function", "*", "_args", "**", "_kwargs", ")", "-", "automatically", "retries", "function", "in", "case", "of", "a", "database", "deadlock", "." ]
def DeadlockWrap(function, *_args, **_kwargs): """DeadlockWrap(function, *_args, **_kwargs) - automatically retries function in case of a database deadlock. This is a function intended to be used to wrap database calls such that they perform retrys with exponentially backing off sleeps in between when a DBLockDeadlockError exception is raised. A 'max_retries' parameter may optionally be passed to prevent it from retrying forever (in which case the exception will be reraised). d = DB(...) d.open(...) DeadlockWrap(d.put, "foo", data="bar") # set key "foo" to "bar" """ sleeptime = _deadlock_MinSleepTime max_retries = _kwargs.get('max_retries', -1) if 'max_retries' in _kwargs: del _kwargs['max_retries'] while True: try: return function(*_args, **_kwargs) except db.DBLockDeadlockError: if _deadlock_VerboseFile: _deadlock_VerboseFile.write( 'dbutils.DeadlockWrap: sleeping %1.3f\n' % sleeptime) _sleep(sleeptime) # exponential backoff in the sleep time sleeptime *= 2 if sleeptime > _deadlock_MaxSleepTime: sleeptime = _deadlock_MaxSleepTime max_retries -= 1 if max_retries == -1: raise
[ "def", "DeadlockWrap", "(", "function", ",", "*", "_args", ",", "*", "*", "_kwargs", ")", ":", "sleeptime", "=", "_deadlock_MinSleepTime", "max_retries", "=", "_kwargs", ".", "get", "(", "'max_retries'", ",", "-", "1", ")", "if", "'max_retries'", "in", "_k...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/bsddb/dbutils.py#L47-L80
ricardoquesada/Spidermonkey
4a75ea2543408bd1b2c515aa95901523eeef7858
dom/bindings/parser/WebIDL.py
python
Parser.p_PrimitiveOrStringTypeBoolean
(self, p)
PrimitiveOrStringType : BOOLEAN
PrimitiveOrStringType : BOOLEAN
[ "PrimitiveOrStringType", ":", "BOOLEAN" ]
def p_PrimitiveOrStringTypeBoolean(self, p): """ PrimitiveOrStringType : BOOLEAN """ p[0] = IDLBuiltinType.Types.boolean
[ "def", "p_PrimitiveOrStringTypeBoolean", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "IDLBuiltinType", ".", "Types", ".", "boolean" ]
https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/dom/bindings/parser/WebIDL.py#L5321-L5325
hfinkel/llvm-project-cxxjit
91084ef018240bbb8e24235ff5cd8c355a9c1a1e
llvm/examples/Kaleidoscope/MCJIT/cached/genk-timing.py
python
generateKScript
(filename, numFuncs, elementsPerFunc, funcsBetweenExec, callWeighting, timingScript)
Generate a random Kaleidoscope script based on the given parameters
Generate a random Kaleidoscope script based on the given parameters
[ "Generate", "a", "random", "Kaleidoscope", "script", "based", "on", "the", "given", "parameters" ]
def generateKScript(filename, numFuncs, elementsPerFunc, funcsBetweenExec, callWeighting, timingScript): """ Generate a random Kaleidoscope script based on the given parameters """ print("Generating " + filename) print(" %d functions, %d elements per function, %d functions between execution" % (numFuncs, elementsPerFunc, funcsBetweenExec)) print(" Call weighting = %f" % callWeighting) script = KScriptGenerator(filename) script.setCallWeighting(callWeighting) script.writeComment("===========================================================================") script.writeComment("Auto-generated script") script.writeComment(" %d functions, %d elements per function, %d functions between execution" % (numFuncs, elementsPerFunc, funcsBetweenExec)) script.writeComment(" call weighting = %f" % callWeighting) script.writeComment("===========================================================================") script.writeEmptyLine() script.writePredefinedFunctions() funcsSinceLastExec = 0 for i in range(numFuncs): script.writeFunction(elementsPerFunc) funcsSinceLastExec += 1 if funcsSinceLastExec == funcsBetweenExec: script.writeFunctionCall() funcsSinceLastExec = 0 # Always end with a function call if funcsSinceLastExec > 0: script.writeFunctionCall() script.writeEmptyLine() script.writeFinalFunctionCounts() funcsCalled = len(script.calledFunctions) print(" Called %d of %d functions, %d total" % (funcsCalled, numFuncs, script.totalCallsExecuted)) timingScript.writeTimingCall(filename, numFuncs, funcsCalled, script.totalCallsExecuted)
[ "def", "generateKScript", "(", "filename", ",", "numFuncs", ",", "elementsPerFunc", ",", "funcsBetweenExec", ",", "callWeighting", ",", "timingScript", ")", ":", "print", "(", "\"Generating \"", "+", "filename", ")", "print", "(", "\" %d functions, %d elements per fu...
https://github.com/hfinkel/llvm-project-cxxjit/blob/91084ef018240bbb8e24235ff5cd8c355a9c1a1e/llvm/examples/Kaleidoscope/MCJIT/cached/genk-timing.py#L176-L206
rdkit/rdkit
ede860ae316d12d8568daf5ee800921c3389c84e
rdkit/Chem/PandasTools.py
python
AddMoleculeColumnToFrame
(frame, smilesCol='Smiles', molCol='ROMol', includeFingerprints=False)
Converts the molecules contains in "smilesCol" to RDKit molecules and appends them to the dataframe "frame" using the specified column name. If desired, a fingerprint can be computed and stored with the molecule objects to accelerate substructure matching
Converts the molecules contains in "smilesCol" to RDKit molecules and appends them to the dataframe "frame" using the specified column name. If desired, a fingerprint can be computed and stored with the molecule objects to accelerate substructure matching
[ "Converts", "the", "molecules", "contains", "in", "smilesCol", "to", "RDKit", "molecules", "and", "appends", "them", "to", "the", "dataframe", "frame", "using", "the", "specified", "column", "name", ".", "If", "desired", "a", "fingerprint", "can", "be", "compu...
def AddMoleculeColumnToFrame(frame, smilesCol='Smiles', molCol='ROMol', includeFingerprints=False): '''Converts the molecules contains in "smilesCol" to RDKit molecules and appends them to the dataframe "frame" using the specified column name. If desired, a fingerprint can be computed and stored with the molecule objects to accelerate substructure matching ''' if not includeFingerprints: frame[molCol] = frame[smilesCol].map(Chem.MolFromSmiles) else: frame[molCol] = frame[smilesCol].map( lambda smiles: _MolPlusFingerprint(Chem.MolFromSmiles(smiles))) RenderImagesInAllDataFrames(images=True)
[ "def", "AddMoleculeColumnToFrame", "(", "frame", ",", "smilesCol", "=", "'Smiles'", ",", "molCol", "=", "'ROMol'", ",", "includeFingerprints", "=", "False", ")", ":", "if", "not", "includeFingerprints", ":", "frame", "[", "molCol", "]", "=", "frame", "[", "s...
https://github.com/rdkit/rdkit/blob/ede860ae316d12d8568daf5ee800921c3389c84e/rdkit/Chem/PandasTools.py#L415-L426
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/requests/sessions.py
python
Session.close
(self)
Closes all adapters and as such the session
Closes all adapters and as such the session
[ "Closes", "all", "adapters", "and", "as", "such", "the", "session" ]
def close(self): """Closes all adapters and as such the session""" for v in self.adapters.values(): v.close()
[ "def", "close", "(", "self", ")", ":", "for", "v", "in", "self", ".", "adapters", ".", "values", "(", ")", ":", "v", ".", "close", "(", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/requests/sessions.py#L730-L733
NVIDIA/TensorRT
42805f078052daad1a98bc5965974fcffaad0960
tools/pytorch-quantization/pytorch_quantization/tensor_quant.py
python
FakeAffineTensorQuantFunction.backward
(ctx, grad_outputs)
return grad_inputs, None, None, None
Args: ctx: Pytorch convention. grad_output: A tensor of gradient of outputs Returns: grad_inputs: A tensor of gradient
Args: ctx: Pytorch convention. grad_output: A tensor of gradient of outputs
[ "Args", ":", "ctx", ":", "Pytorch", "convention", ".", "grad_output", ":", "A", "tensor", "of", "gradient", "of", "outputs" ]
def backward(ctx, grad_outputs): """ Args: ctx: Pytorch convention. grad_output: A tensor of gradient of outputs Returns: grad_inputs: A tensor of gradient """ inputs, min_range, max_range = ctx.saved_tensors zero = grad_outputs.new_zeros(1) grad_inputs = torch.where((inputs <= max_range)*(inputs >= min_range), grad_outputs, zero) return grad_inputs, None, None, None
[ "def", "backward", "(", "ctx", ",", "grad_outputs", ")", ":", "inputs", ",", "min_range", ",", "max_range", "=", "ctx", ".", "saved_tensors", "zero", "=", "grad_outputs", ".", "new_zeros", "(", "1", ")", "grad_inputs", "=", "torch", ".", "where", "(", "(...
https://github.com/NVIDIA/TensorRT/blob/42805f078052daad1a98bc5965974fcffaad0960/tools/pytorch-quantization/pytorch_quantization/tensor_quant.py#L407-L420
macchina-io/macchina.io
ef24ba0e18379c3dd48fb84e6dbf991101cb8db0
platform/JS/V8/v8/tools/stats-viewer.py
python
StatsViewer.RebuildMainWindow
(self, groups)
Tear down and rebuild the main window. Args: groups: the groups of counters to display
Tear down and rebuild the main window.
[ "Tear", "down", "and", "rebuild", "the", "main", "window", "." ]
def RebuildMainWindow(self, groups): """Tear down and rebuild the main window. Args: groups: the groups of counters to display """ # Remove elements in the current ui self.ui_counters.clear() for child in self.root.children.values(): child.destroy() # Build new ui index = 0 sorted_groups = groups.keys() sorted_groups.sort() for counter_name in sorted_groups: counter_objs = groups[counter_name] if self.name_filter.match(counter_name): name = Tkinter.Label(self.root, width=50, anchor=Tkinter.W, text=counter_name) name.grid(row=index, column=0, padx=1, pady=1) count = len(counter_objs) for i in xrange(count): counter = counter_objs[i] name = counter.Name() var = Tkinter.StringVar() if self.name_filter.match(name): value = Tkinter.Label(self.root, width=15, anchor=Tkinter.W, textvariable=var) value.grid(row=index, column=(1 + i), padx=1, pady=1) # If we know how to interpret the prefix of this counter then # add an appropriate formatting to the variable if (":" in name) and (name[0] in COUNTER_LABELS): format = COUNTER_LABELS[name[0]] else: format = "%i" ui_counter = UiCounter(var, format) self.ui_counters[name] = ui_counter ui_counter.Set(counter.Value()) index += 1 self.root.update()
[ "def", "RebuildMainWindow", "(", "self", ",", "groups", ")", ":", "# Remove elements in the current ui", "self", ".", "ui_counters", ".", "clear", "(", ")", "for", "child", "in", "self", ".", "root", ".", "children", ".", "values", "(", ")", ":", "child", ...
https://github.com/macchina-io/macchina.io/blob/ef24ba0e18379c3dd48fb84e6dbf991101cb8db0/platform/JS/V8/v8/tools/stats-viewer.py#L214-L255
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/propgrid.py
python
PGVIterator.Next
(*args, **kwargs)
return _propgrid.PGVIterator_Next(*args, **kwargs)
Next(self)
Next(self)
[ "Next", "(", "self", ")" ]
def Next(*args, **kwargs): """Next(self)""" return _propgrid.PGVIterator_Next(*args, **kwargs)
[ "def", "Next", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_propgrid", ".", "PGVIterator_Next", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/propgrid.py#L1065-L1067
cyberbotics/webots
af7fa7d68dcf7b4550f1f2e132092b41e83698fc
projects/samples/robotbenchmark/highway_driving/controllers/highway_driving_benchmark/highway_driving_benchmark.py
python
enable_sensors_visualization
(supervisor, enable)
Hide or show the sensors visualization nodes.
Hide or show the sensors visualization nodes.
[ "Hide", "or", "show", "the", "sensors", "visualization", "nodes", "." ]
def enable_sensors_visualization(supervisor, enable): """Hide or show the sensors visualization nodes.""" for node in sensorVisualizationNodes: node.setVisibility(supervisor.getFromDef('VIEWPOINT'), enable)
[ "def", "enable_sensors_visualization", "(", "supervisor", ",", "enable", ")", ":", "for", "node", "in", "sensorVisualizationNodes", ":", "node", ".", "setVisibility", "(", "supervisor", ".", "getFromDef", "(", "'VIEWPOINT'", ")", ",", "enable", ")" ]
https://github.com/cyberbotics/webots/blob/af7fa7d68dcf7b4550f1f2e132092b41e83698fc/projects/samples/robotbenchmark/highway_driving/controllers/highway_driving_benchmark/highway_driving_benchmark.py#L101-L104
eclipse/sumo
7132a9b8b6eea734bdec38479026b4d8c4336d03
tools/contributed/sumopy/plugins/prt/prt.py
python
PrtStops.get_waitpositions
(self, ids, is_alight=False, offset=-0.0)
return positions+offset
Assign randomly a wait-position for each stop in ids offset is wait position relative to the vehicle nose.
Assign randomly a wait-position for each stop in ids
[ "Assign", "randomly", "a", "wait", "-", "position", "for", "each", "stop", "in", "ids" ]
def get_waitpositions(self, ids, is_alight=False, offset=-0.0): """ Assign randomly a wait-position for each stop in ids offset is wait position relative to the vehicle nose. """ # print 'get_waitpositions min(ids),max(ids)',min(ids),is_alight,max(ids),offset positions = np.zeros(len(ids), dtype=np.float32) randint = random.randint if is_alight: ids_berths = self.ids_berth_alight[ids] else: ids_berths = self.ids_berth_board[ids] stoppositions = self.get_berths().stoppositions # print ' ids_berths',ids_berths i = 0 for id_stop, ids_berth in zip(ids, ids_berths): #ids_berth = ids_berths[id_stop] ind_berth = randint(0, len(ids_berth)-1) positions[i] = stoppositions[ids_berth[ind_berth]] # print ' id_stop,ids_berth,posiions',id_stop,ids_berth,stoppositions[ids_berth[ind_berth]] i += 1 #positions[i] = stoppositions[ids_berth[randint(0,len(ids_berth))]] # for id_stop , pos in zip(ids, positions): # print ' id_stop %d, is_alight = %s, pos %.2fm'%(id_stop, is_alight ,pos) return positions+offset
[ "def", "get_waitpositions", "(", "self", ",", "ids", ",", "is_alight", "=", "False", ",", "offset", "=", "-", "0.0", ")", ":", "# print 'get_waitpositions min(ids),max(ids)',min(ids),is_alight,max(ids),offset", "positions", "=", "np", ".", "zeros", "(", "len", "(", ...
https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/contributed/sumopy/plugins/prt/prt.py#L2556-L2584
OpenMined/PyDP
a88ee73053aa2bdc1be327a77109dd5907ab41d6
src/pydp/ml/util/accountant.py
python
BudgetAccountant.spent_budget
(self)
return self.__spent_budget.copy()
List of tuples of the form (epsilon, delta) of spent privacy budget.
List of tuples of the form (epsilon, delta) of spent privacy budget.
[ "List", "of", "tuples", "of", "the", "form", "(", "epsilon", "delta", ")", "of", "spent", "privacy", "budget", "." ]
def spent_budget(self): """List of tuples of the form (epsilon, delta) of spent privacy budget.""" return self.__spent_budget.copy()
[ "def", "spent_budget", "(", "self", ")", ":", "return", "self", ".", "__spent_budget", ".", "copy", "(", ")" ]
https://github.com/OpenMined/PyDP/blob/a88ee73053aa2bdc1be327a77109dd5907ab41d6/src/pydp/ml/util/accountant.py#L141-L143
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/richtext.py
python
RichTextObject.HitTest
(*args, **kwargs)
return _richtext.RichTextObject_HitTest(*args, **kwargs)
HitTest(self, DC dc, RichTextDrawingContext context, Point pt, long OUTPUT, RichTextObject obj, RichTextObject contextObj, int flags=0) -> int
HitTest(self, DC dc, RichTextDrawingContext context, Point pt, long OUTPUT, RichTextObject obj, RichTextObject contextObj, int flags=0) -> int
[ "HitTest", "(", "self", "DC", "dc", "RichTextDrawingContext", "context", "Point", "pt", "long", "OUTPUT", "RichTextObject", "obj", "RichTextObject", "contextObj", "int", "flags", "=", "0", ")", "-", ">", "int" ]
def HitTest(*args, **kwargs): """ HitTest(self, DC dc, RichTextDrawingContext context, Point pt, long OUTPUT, RichTextObject obj, RichTextObject contextObj, int flags=0) -> int """ return _richtext.RichTextObject_HitTest(*args, **kwargs)
[ "def", "HitTest", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_richtext", ".", "RichTextObject_HitTest", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/richtext.py#L1179-L1185
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/psutil/_psaix.py
python
pids
()
return [int(x) for x in os.listdir(get_procfs_path()) if x.isdigit()]
Returns a list of PIDs currently running on the system.
Returns a list of PIDs currently running on the system.
[ "Returns", "a", "list", "of", "PIDs", "currently", "running", "on", "the", "system", "." ]
def pids(): """Returns a list of PIDs currently running on the system.""" return [int(x) for x in os.listdir(get_procfs_path()) if x.isdigit()]
[ "def", "pids", "(", ")", ":", "return", "[", "int", "(", "x", ")", "for", "x", "in", "os", ".", "listdir", "(", "get_procfs_path", "(", ")", ")", "if", "x", ".", "isdigit", "(", ")", "]" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/psutil/_psaix.py#L297-L299
moflow/moflow
2dfb27c799c90c6caf1477508eca3eec616ef7d2
bap/libtracewrap/libtrace/protobuf/python/google/protobuf/internal/encoder.py
python
BoolEncoder
(field_number, is_repeated, is_packed)
Returns an encoder for a boolean field.
Returns an encoder for a boolean field.
[ "Returns", "an", "encoder", "for", "a", "boolean", "field", "." ]
def BoolEncoder(field_number, is_repeated, is_packed): """Returns an encoder for a boolean field.""" false_byte = chr(0) true_byte = chr(1) if is_packed: tag_bytes = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED) local_EncodeVarint = _EncodeVarint def EncodePackedField(write, value): write(tag_bytes) local_EncodeVarint(write, len(value)) for element in value: if element: write(true_byte) else: write(false_byte) return EncodePackedField elif is_repeated: tag_bytes = TagBytes(field_number, wire_format.WIRETYPE_VARINT) def EncodeRepeatedField(write, value): for element in value: write(tag_bytes) if element: write(true_byte) else: write(false_byte) return EncodeRepeatedField else: tag_bytes = TagBytes(field_number, wire_format.WIRETYPE_VARINT) def EncodeField(write, value): write(tag_bytes) if value: return write(true_byte) return write(false_byte) return EncodeField
[ "def", "BoolEncoder", "(", "field_number", ",", "is_repeated", ",", "is_packed", ")", ":", "false_byte", "=", "chr", "(", "0", ")", "true_byte", "=", "chr", "(", "1", ")", "if", "is_packed", ":", "tag_bytes", "=", "TagBytes", "(", "field_number", ",", "w...
https://github.com/moflow/moflow/blob/2dfb27c799c90c6caf1477508eca3eec616ef7d2/bap/libtracewrap/libtrace/protobuf/python/google/protobuf/internal/encoder.py#L615-L649
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/math_ops.py
python
_add_dispatch
(x, y, name=None)
Dispatches to add for strings and add_v2 for all other types.
Dispatches to add for strings and add_v2 for all other types.
[ "Dispatches", "to", "add", "for", "strings", "and", "add_v2", "for", "all", "other", "types", "." ]
def _add_dispatch(x, y, name=None): """Dispatches to add for strings and add_v2 for all other types.""" if fwd_compat.forward_compatible(2019, 6, 25): if x.dtype == dtypes.string: return gen_math_ops.add(x, y, name=name) else: return gen_math_ops.add_v2(x, y, name=name) else: return gen_math_ops.add(x, y, name=name)
[ "def", "_add_dispatch", "(", "x", ",", "y", ",", "name", "=", "None", ")", ":", "if", "fwd_compat", ".", "forward_compatible", "(", "2019", ",", "6", ",", "25", ")", ":", "if", "x", ".", "dtype", "==", "dtypes", ".", "string", ":", "return", "gen_m...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/math_ops.py#L1191-L1199
kamyu104/LeetCode-Solutions
77605708a927ea3b85aee5a479db733938c7c211
Python/closest-dessert-cost.py
python
Solution3.closestCost
(self, baseCosts, toppingCosts, target)
return result
:type baseCosts: List[int] :type toppingCosts: List[int] :type target: int :rtype: int
:type baseCosts: List[int] :type toppingCosts: List[int] :type target: int :rtype: int
[ ":", "type", "baseCosts", ":", "List", "[", "int", "]", ":", "type", "toppingCosts", ":", "List", "[", "int", "]", ":", "type", "target", ":", "int", ":", "rtype", ":", "int" ]
def closestCost(self, baseCosts, toppingCosts, target): """ :type baseCosts: List[int] :type toppingCosts: List[int] :type target: int :rtype: int """ max_count = 2 combs = set([0]) for t in toppingCosts: combs = set([c+i*t for c in combs for i in xrange(max_count+1)]) result, combs = float("inf"), sorted(combs) for b in baseCosts: idx = bisect.bisect_left(combs, target-b) if idx < len(combs): result = min(result, b+combs[idx], key=lambda x: (abs(x-target), x)) if idx > 0: result = min(result, b+combs[idx-1], key=lambda x: (abs(x-target), x)) return result
[ "def", "closestCost", "(", "self", ",", "baseCosts", ",", "toppingCosts", ",", "target", ")", ":", "max_count", "=", "2", "combs", "=", "set", "(", "[", "0", "]", ")", "for", "t", "in", "toppingCosts", ":", "combs", "=", "set", "(", "[", "c", "+", ...
https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/closest-dessert-cost.py#L68-L86
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_controls.py
python
DirFilterListCtrl.Create
(*args, **kwargs)
return _controls_.DirFilterListCtrl_Create(*args, **kwargs)
Create(self, GenericDirCtrl parent, int id=-1, Point pos=DefaultPosition, Size size=DefaultSize, long style=0) -> bool
Create(self, GenericDirCtrl parent, int id=-1, Point pos=DefaultPosition, Size size=DefaultSize, long style=0) -> bool
[ "Create", "(", "self", "GenericDirCtrl", "parent", "int", "id", "=", "-", "1", "Point", "pos", "=", "DefaultPosition", "Size", "size", "=", "DefaultSize", "long", "style", "=", "0", ")", "-", ">", "bool" ]
def Create(*args, **kwargs): """ Create(self, GenericDirCtrl parent, int id=-1, Point pos=DefaultPosition, Size size=DefaultSize, long style=0) -> bool """ return _controls_.DirFilterListCtrl_Create(*args, **kwargs)
[ "def", "Create", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "DirFilterListCtrl_Create", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_controls.py#L5811-L5816
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/ops/distributions/bijector_impl.py
python
Bijector._cache
(self, mapping)
Helper which stores mapping info in forward/inverse dicts.
Helper which stores mapping info in forward/inverse dicts.
[ "Helper", "which", "stores", "mapping", "info", "in", "forward", "/", "inverse", "dicts", "." ]
def _cache(self, mapping): """Helper which stores mapping info in forward/inverse dicts.""" # Merging from lookup is an added check that we're not overwriting anything # which is not None. mapping = mapping.merge(mapping=self._lookup( mapping.x, mapping.y, mapping.kwargs)) if mapping.x is None and mapping.y is None: raise ValueError("Caching expects at least one of (x,y) to be known, " "i.e., not None.") self._from_x[mapping.x_key] = mapping self._from_y[mapping.y_key] = mapping
[ "def", "_cache", "(", "self", ",", "mapping", ")", ":", "# Merging from lookup is an added check that we're not overwriting anything", "# which is not None.", "mapping", "=", "mapping", ".", "merge", "(", "mapping", "=", "self", ".", "_lookup", "(", "mapping", ".", "x...
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/distributions/bijector_impl.py#L1007-L1017
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_controls.py
python
CollapsiblePaneEvent.__init__
(self, *args, **kwargs)
__init__(self, Object generator, int id, bool collapsed) -> CollapsiblePaneEvent
__init__(self, Object generator, int id, bool collapsed) -> CollapsiblePaneEvent
[ "__init__", "(", "self", "Object", "generator", "int", "id", "bool", "collapsed", ")", "-", ">", "CollapsiblePaneEvent" ]
def __init__(self, *args, **kwargs): """__init__(self, Object generator, int id, bool collapsed) -> CollapsiblePaneEvent""" _controls_.CollapsiblePaneEvent_swiginit(self,_controls_.new_CollapsiblePaneEvent(*args, **kwargs))
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_controls_", ".", "CollapsiblePaneEvent_swiginit", "(", "self", ",", "_controls_", ".", "new_CollapsiblePaneEvent", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_controls.py#L7403-L7405
thalium/icebox
99d147d5b9269222225443ce171b4fd46d8985d4
third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py
python
xmlTextReader.NewDoc
(self, cur, URL, encoding, options)
return ret
Setup an xmltextReader to parse an XML in-memory document. The parsing flags @options are a combination of xmlParserOption. This reuses the existing @reader xmlTextReader.
Setup an xmltextReader to parse an XML in-memory document. The parsing flags
[ "Setup", "an", "xmltextReader", "to", "parse", "an", "XML", "in", "-", "memory", "document", ".", "The", "parsing", "flags" ]
def NewDoc(self, cur, URL, encoding, options): """Setup an xmltextReader to parse an XML in-memory document. The parsing flags @options are a combination of xmlParserOption. This reuses the existing @reader xmlTextReader. """ ret = libxml2mod.xmlReaderNewDoc(self._o, cur, URL, encoding, options) return ret
[ "def", "NewDoc", "(", "self", ",", "cur", ",", "URL", ",", "encoding", ",", "options", ")", ":", "ret", "=", "libxml2mod", ".", "xmlReaderNewDoc", "(", "self", ".", "_o", ",", "cur", ",", "URL", ",", "encoding", ",", "options", ")", "return", "ret" ]
https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py#L6734-L6740
tzutalin/dlib-android
989627cb7fe81cd1d41d73434b0e91ce1dd2683f
tools/lint/cpplint.py
python
_SetFilters
(filters)
Sets the module's error-message filters. These filters are applied when deciding whether to emit a given error message. Args: filters: A string of comma-separated filters (eg "whitespace/indent"). Each filter should start with + or -; else we die.
Sets the module's error-message filters. These filters are applied when deciding whether to emit a given error message. Args: filters: A string of comma-separated filters (eg "whitespace/indent"). Each filter should start with + or -; else we die.
[ "Sets", "the", "module", "s", "error", "-", "message", "filters", ".", "These", "filters", "are", "applied", "when", "deciding", "whether", "to", "emit", "a", "given", "error", "message", ".", "Args", ":", "filters", ":", "A", "string", "of", "comma", "-...
def _SetFilters(filters): """Sets the module's error-message filters. These filters are applied when deciding whether to emit a given error message. Args: filters: A string of comma-separated filters (eg "whitespace/indent"). Each filter should start with + or -; else we die. """ _cpplint_state.SetFilters(filters)
[ "def", "_SetFilters", "(", "filters", ")", ":", "_cpplint_state", ".", "SetFilters", "(", "filters", ")" ]
https://github.com/tzutalin/dlib-android/blob/989627cb7fe81cd1d41d73434b0e91ce1dd2683f/tools/lint/cpplint.py#L916-L924
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/imaplib.py
python
IMAP4.deleteacl
(self, mailbox, who)
return self._simple_command('DELETEACL', mailbox, who)
Delete the ACLs (remove any rights) set for who on mailbox. (typ, [data]) = <instance>.deleteacl(mailbox, who)
Delete the ACLs (remove any rights) set for who on mailbox.
[ "Delete", "the", "ACLs", "(", "remove", "any", "rights", ")", "set", "for", "who", "on", "mailbox", "." ]
def deleteacl(self, mailbox, who): """Delete the ACLs (remove any rights) set for who on mailbox. (typ, [data]) = <instance>.deleteacl(mailbox, who) """ return self._simple_command('DELETEACL', mailbox, who)
[ "def", "deleteacl", "(", "self", ",", "mailbox", ",", "who", ")", ":", "return", "self", ".", "_simple_command", "(", "'DELETEACL'", ",", "mailbox", ",", "who", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/imaplib.py#L411-L416
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/setuptools/config.py
python
ConfigHandler._exclude_files_parser
(cls, key)
return parser
Returns a parser function to make sure field inputs are not files. Parses a value after getting the key so error messages are more informative. :param key: :rtype: callable
Returns a parser function to make sure field inputs are not files.
[ "Returns", "a", "parser", "function", "to", "make", "sure", "field", "inputs", "are", "not", "files", "." ]
def _exclude_files_parser(cls, key): """Returns a parser function to make sure field inputs are not files. Parses a value after getting the key so error messages are more informative. :param key: :rtype: callable """ def parser(value): exclude_directive = 'file:' if value.startswith(exclude_directive): raise ValueError( 'Only strings are accepted for the {0} field, ' 'files are not accepted'.format(key)) return value return parser
[ "def", "_exclude_files_parser", "(", "cls", ",", "key", ")", ":", "def", "parser", "(", "value", ")", ":", "exclude_directive", "=", "'file:'", "if", "value", ".", "startswith", "(", "exclude_directive", ")", ":", "raise", "ValueError", "(", "'Only strings are...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/setuptools/config.py#L291-L308
casadi/casadi
8d0f80a4d0fe2054384bfb9748f7a0f6bae540ff
misc/cpplint.py
python
CheckForBadCharacters
(filename, lines, error)
Logs an error for each line containing bad characters. Two kinds of bad characters: 1. Unicode replacement characters: These indicate that either the file contained invalid UTF-8 (likely) or Unicode replacement characters (which it shouldn't). Note that it's possible for this to throw off line numbering if the invalid UTF-8 occurred adjacent to a newline. 2. NUL bytes. These are problematic for some tools. Args: filename: The name of the current file. lines: An array of strings, each representing a line of the file. error: The function to call with any errors found.
Logs an error for each line containing bad characters.
[ "Logs", "an", "error", "for", "each", "line", "containing", "bad", "characters", "." ]
def CheckForBadCharacters(filename, lines, error): """Logs an error for each line containing bad characters. Two kinds of bad characters: 1. Unicode replacement characters: These indicate that either the file contained invalid UTF-8 (likely) or Unicode replacement characters (which it shouldn't). Note that it's possible for this to throw off line numbering if the invalid UTF-8 occurred adjacent to a newline. 2. NUL bytes. These are problematic for some tools. Args: filename: The name of the current file. lines: An array of strings, each representing a line of the file. error: The function to call with any errors found. """ for linenum, line in enumerate(lines): if '\ufffd' in line: error(filename, linenum, 'readability/utf8', 5, 'Line contains invalid UTF-8 (or Unicode replacement character).') if '\0' in line: error(filename, linenum, 'readability/nul', 5, 'Line contains NUL byte.')
[ "def", "CheckForBadCharacters", "(", "filename", ",", "lines", ",", "error", ")", ":", "for", "linenum", ",", "line", "in", "enumerate", "(", "lines", ")", ":", "if", "'\\ufffd'", "in", "line", ":", "error", "(", "filename", ",", "linenum", ",", "'readab...
https://github.com/casadi/casadi/blob/8d0f80a4d0fe2054384bfb9748f7a0f6bae540ff/misc/cpplint.py#L1477-L1499
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/oauth2client/oauth2client/appengine.py
python
OAuth2Decorator.callback_application
(self)
return webapp.WSGIApplication([ (self.callback_path, self.callback_handler()) ])
WSGI application for handling the OAuth 2.0 redirect callback. If you need finer grained control use `callback_handler` which returns just the webapp.RequestHandler. Returns: A webapp.WSGIApplication that handles the redirect back from the server during the OAuth 2.0 dance.
WSGI application for handling the OAuth 2.0 redirect callback.
[ "WSGI", "application", "for", "handling", "the", "OAuth", "2", ".", "0", "redirect", "callback", "." ]
def callback_application(self): """WSGI application for handling the OAuth 2.0 redirect callback. If you need finer grained control use `callback_handler` which returns just the webapp.RequestHandler. Returns: A webapp.WSGIApplication that handles the redirect back from the server during the OAuth 2.0 dance. """ return webapp.WSGIApplication([ (self.callback_path, self.callback_handler()) ])
[ "def", "callback_application", "(", "self", ")", ":", "return", "webapp", ".", "WSGIApplication", "(", "[", "(", "self", ".", "callback_path", ",", "self", ".", "callback_handler", "(", ")", ")", "]", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/oauth2client/oauth2client/appengine.py#L891-L903
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/eager/tape.py
python
watch_variable
(variable)
Marks this variable to be watched by all tapes in the stack. Args: variable: variable to be watched.
Marks this variable to be watched by all tapes in the stack.
[ "Marks", "this", "variable", "to", "be", "watched", "by", "all", "tapes", "in", "the", "stack", "." ]
def watch_variable(variable): """Marks this variable to be watched by all tapes in the stack. Args: variable: variable to be watched. """ for t in _tape_stack.stack: t.watch_variable(variable)
[ "def", "watch_variable", "(", "variable", ")", ":", "for", "t", "in", "_tape_stack", ".", "stack", ":", "t", ".", "watch_variable", "(", "variable", ")" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/eager/tape.py#L143-L150
forkineye/ESPixelStick
22926f1c0d1131f1369fc7cad405689a095ae3cb
dist/bin/pyserial/serial/serialutil.py
python
to_bytes
(seq)
convert a sequence to a bytes type
convert a sequence to a bytes type
[ "convert", "a", "sequence", "to", "a", "bytes", "type" ]
def to_bytes(seq): """convert a sequence to a bytes type""" if isinstance(seq, bytes): return seq elif isinstance(seq, bytearray): return bytes(seq) elif isinstance(seq, memoryview): return seq.tobytes() elif isinstance(seq, unicode): raise TypeError('unicode strings are not supported, please encode to bytes: {!r}'.format(seq)) else: # handle list of integers and bytes (one or more items) for Python 2 and 3 return bytes(bytearray(seq))
[ "def", "to_bytes", "(", "seq", ")", ":", "if", "isinstance", "(", "seq", ",", "bytes", ")", ":", "return", "seq", "elif", "isinstance", "(", "seq", ",", "bytearray", ")", ":", "return", "bytes", "(", "seq", ")", "elif", "isinstance", "(", "seq", ",",...
https://github.com/forkineye/ESPixelStick/blob/22926f1c0d1131f1369fc7cad405689a095ae3cb/dist/bin/pyserial/serial/serialutil.py#L54-L66
LiquidPlayer/LiquidCore
9405979363f2353ac9a71ad8ab59685dd7f919c9
deps/node-10.15.3/tools/jinja2/utils.py
python
open_if_exists
(filename, mode='rb')
Returns a file descriptor for the filename if that file exists, otherwise `None`.
Returns a file descriptor for the filename if that file exists, otherwise `None`.
[ "Returns", "a", "file", "descriptor", "for", "the", "filename", "if", "that", "file", "exists", "otherwise", "None", "." ]
def open_if_exists(filename, mode='rb'): """Returns a file descriptor for the filename if that file exists, otherwise `None`. """ try: return open(filename, mode) except IOError as e: if e.errno not in (errno.ENOENT, errno.EISDIR, errno.EINVAL): raise
[ "def", "open_if_exists", "(", "filename", ",", "mode", "=", "'rb'", ")", ":", "try", ":", "return", "open", "(", "filename", ",", "mode", ")", "except", "IOError", "as", "e", ":", "if", "e", ".", "errno", "not", "in", "(", "errno", ".", "ENOENT", "...
https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/tools/jinja2/utils.py#L149-L157
InsightSoftwareConsortium/ITK
87acfce9a93d928311c38bc371b666b515b9f19d
Modules/ThirdParty/pygccxml/src/pygccxml/declarations/type_traits_classes.py
python
is_noncopyable
(class_, already_visited_cls_vars=None)
return __is_noncopyable_single(class_decl, already_visited_cls_vars)
Checks if class is non copyable Args: class_ (declarations.class_t): the class to be checked already_visited_cls_vars (list): optional list of vars that should not be checked a second time, to prevent infinite recursions. In general you can ignore this argument, it is mainly used during recursive calls of is_noncopyable() done by pygccxml. Returns: bool: if the class is non copyable
Checks if class is non copyable
[ "Checks", "if", "class", "is", "non", "copyable" ]
def is_noncopyable(class_, already_visited_cls_vars=None): """ Checks if class is non copyable Args: class_ (declarations.class_t): the class to be checked already_visited_cls_vars (list): optional list of vars that should not be checked a second time, to prevent infinite recursions. In general you can ignore this argument, it is mainly used during recursive calls of is_noncopyable() done by pygccxml. Returns: bool: if the class is non copyable """ logger = utils.loggers.cxx_parser class_decl = class_traits.get_declaration(class_) true_header = "is_noncopyable(TRUE) - %s - " % class_.decl_string if is_union(class_): return False if class_decl.is_abstract: logger.debug(true_header + "abstract client") return True # if class has public, user defined copy constructor, than this class is # copyable copy_ = find_copy_constructor(class_decl) if copy_ and copy_.access_type == 'public' and not copy_.is_artificial: return False if already_visited_cls_vars is None: already_visited_cls_vars = [] for base_desc in class_decl.recursive_bases: assert isinstance(base_desc, class_declaration.hierarchy_info_t) if base_desc.related_class.decl_string in \ ('::boost::noncopyable', '::boost::noncopyable_::noncopyable'): logger.debug(true_header + "derives from boost::noncopyable") return True if not has_copy_constructor(base_desc.related_class): base_copy_ = find_copy_constructor(base_desc.related_class) if base_copy_ and base_copy_.access_type == 'private': logger.debug( true_header + "there is private copy constructor") return True elif __is_noncopyable_single( base_desc.related_class, already_visited_cls_vars): logger.debug( true_header + "__is_noncopyable_single returned True") return True if __is_noncopyable_single( base_desc.related_class, already_visited_cls_vars): logger.debug( true_header + "__is_noncopyable_single returned True") return True if not has_copy_constructor(class_decl): logger.debug(true_header + "does not have trivial copy constructor") return True elif not has_public_constructor(class_decl): logger.debug(true_header + "does not have a public constructor") return True elif has_destructor(class_decl) and not has_public_destructor(class_decl): logger.debug(true_header + "has private destructor") return True return __is_noncopyable_single(class_decl, already_visited_cls_vars)
[ "def", "is_noncopyable", "(", "class_", ",", "already_visited_cls_vars", "=", "None", ")", ":", "logger", "=", "utils", ".", "loggers", ".", "cxx_parser", "class_decl", "=", "class_traits", ".", "get_declaration", "(", "class_", ")", "true_header", "=", "\"is_no...
https://github.com/InsightSoftwareConsortium/ITK/blob/87acfce9a93d928311c38bc371b666b515b9f19d/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/type_traits_classes.py#L708-L785
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/grid.py
python
Grid.GoToCell
(*args, **kwargs)
return _grid.Grid_GoToCell(*args, **kwargs)
GoToCell(self, int row, int col)
GoToCell(self, int row, int col)
[ "GoToCell", "(", "self", "int", "row", "int", "col", ")" ]
def GoToCell(*args, **kwargs): """GoToCell(self, int row, int col)""" return _grid.Grid_GoToCell(*args, **kwargs)
[ "def", "GoToCell", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_grid", ".", "Grid_GoToCell", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/grid.py#L1426-L1428
hpi-xnor/BMXNet-v2
af2b1859eafc5c721b1397cef02f946aaf2ce20d
python/mxnet/ndarray/ndarray.py
python
onehot_encode
(indices, out)
return _internal._onehot_encode(indices, out, out=out)
One-hot encoding indices into matrix out. .. note:: `onehot_encode` is deprecated. Use `one_hot` instead.
One-hot encoding indices into matrix out.
[ "One", "-", "hot", "encoding", "indices", "into", "matrix", "out", "." ]
def onehot_encode(indices, out): """One-hot encoding indices into matrix out. .. note:: `onehot_encode` is deprecated. Use `one_hot` instead. """ # pylint: disable= no-member, protected-access return _internal._onehot_encode(indices, out, out=out)
[ "def", "onehot_encode", "(", "indices", ",", "out", ")", ":", "# pylint: disable= no-member, protected-access", "return", "_internal", ".", "_onehot_encode", "(", "indices", ",", "out", ",", "out", "=", "out", ")" ]
https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/python/mxnet/ndarray/ndarray.py#L2416-L2423
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
lts/tools/gyp/pylib/gyp/generator/make.py
python
EscapeCppDefine
(s)
return s.replace('#', r'\#')
Escapes a CPP define so that it will reach the compiler unaltered.
Escapes a CPP define so that it will reach the compiler unaltered.
[ "Escapes", "a", "CPP", "define", "so", "that", "it", "will", "reach", "the", "compiler", "unaltered", "." ]
def EscapeCppDefine(s): """Escapes a CPP define so that it will reach the compiler unaltered.""" s = EscapeShellArgument(s) s = EscapeMakeVariableExpansion(s) # '#' characters must be escaped even embedded in a string, else Make will # treat it as the start of a comment. return s.replace('#', r'\#')
[ "def", "EscapeCppDefine", "(", "s", ")", ":", "s", "=", "EscapeShellArgument", "(", "s", ")", "s", "=", "EscapeMakeVariableExpansion", "(", "s", ")", "# '#' characters must be escaped even embedded in a string, else Make will", "# treat it as the start of a comment.", "return...
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/tools/gyp/pylib/gyp/generator/make.py#L617-L623
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/ebmlib/backupmgr.py
python
FileBackupMgr.GetBackupWriter
(self, fileobj)
return nfile.Write
Create a backup filewriter method to backup a files contents with. @param fileobj: object implementing fileimpl.FileObjectImpl interface @return: callable(text) to create backup with
Create a backup filewriter method to backup a files contents with. @param fileobj: object implementing fileimpl.FileObjectImpl interface @return: callable(text) to create backup with
[ "Create", "a", "backup", "filewriter", "method", "to", "backup", "a", "files", "contents", "with", ".", "@param", "fileobj", ":", "object", "implementing", "fileimpl", ".", "FileObjectImpl", "interface", "@return", ":", "callable", "(", "text", ")", "to", "cre...
def GetBackupWriter(self, fileobj): """Create a backup filewriter method to backup a files contents with. @param fileobj: object implementing fileimpl.FileObjectImpl interface @return: callable(text) to create backup with """ nfile = fileobj.Clone() fname = self.GetBackupFilename(nfile.GetPath()) nfile.SetPath(fname) # Write the header if it is enabled if self.header and not self.checker.IsBinary(fname): nfile.Write(self.header + os.linesep) return nfile.Write
[ "def", "GetBackupWriter", "(", "self", ",", "fileobj", ")", ":", "nfile", "=", "fileobj", ".", "Clone", "(", ")", "fname", "=", "self", ".", "GetBackupFilename", "(", "nfile", ".", "GetPath", "(", ")", ")", "nfile", ".", "SetPath", "(", "fname", ")", ...
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/ebmlib/backupmgr.py#L93-L106
Illumina/hap.py
84011695b2ff2406c16a335106db6831fb67fdfe
src/python/Tools/bcftools.py
python
parseStats
(output, colname="count")
return result
Parse BCFTOOLS Stats Output
Parse BCFTOOLS Stats Output
[ "Parse", "BCFTOOLS", "Stats", "Output" ]
def parseStats(output, colname="count"): """ Parse BCFTOOLS Stats Output """ result = {} for x in output.split("\n"): if x.startswith("SN"): vx = x.split("\t") name = vx[2].replace("number of ", "").replace(":", "") count = int(vx[3]) result[name] = count result = pandas.DataFrame(list(result.iteritems()), columns=["type", colname]) return result
[ "def", "parseStats", "(", "output", ",", "colname", "=", "\"count\"", ")", ":", "result", "=", "{", "}", "for", "x", "in", "output", ".", "split", "(", "\"\\n\"", ")", ":", "if", "x", ".", "startswith", "(", "\"SN\"", ")", ":", "vx", "=", "x", "....
https://github.com/Illumina/hap.py/blob/84011695b2ff2406c16a335106db6831fb67fdfe/src/python/Tools/bcftools.py#L67-L79
eventql/eventql
7ca0dbb2e683b525620ea30dc40540a22d5eb227
deps/3rdparty/spidermonkey/mozjs/python/requests/requests/models.py
python
Request.prepare
(self)
return p
Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it.
Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it.
[ "Constructs", "a", ":", "class", ":", "PreparedRequest", "<PreparedRequest", ">", "for", "transmission", "and", "returns", "it", "." ]
def prepare(self): """Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it.""" p = PreparedRequest() p.prepare( method=self.method, url=self.url, headers=self.headers, files=self.files, data=self.data, json=self.json, params=self.params, auth=self.auth, cookies=self.cookies, hooks=self.hooks, ) return p
[ "def", "prepare", "(", "self", ")", ":", "p", "=", "PreparedRequest", "(", ")", "p", ".", "prepare", "(", "method", "=", "self", ".", "method", ",", "url", "=", "self", ".", "url", ",", "headers", "=", "self", ".", "headers", ",", "files", "=", "...
https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/python/requests/requests/models.py#L245-L260
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/logging/handlers.py
python
SocketHandler.close
(self)
Closes the socket.
Closes the socket.
[ "Closes", "the", "socket", "." ]
def close(self): """ Closes the socket. """ self.acquire() try: if self.sock: self.sock.close() self.sock = None finally: self.release() logging.Handler.close(self)
[ "def", "close", "(", "self", ")", ":", "self", ".", "acquire", "(", ")", "try", ":", "if", "self", ".", "sock", ":", "self", ".", "sock", ".", "close", "(", ")", "self", ".", "sock", "=", "None", "finally", ":", "self", ".", "release", "(", ")"...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/logging/handlers.py#L585-L596
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/asyncio/transports.py
python
BaseTransport.close
(self)
Close the transport. Buffered data will be flushed asynchronously. No more data will be received. After all buffered data is flushed, the protocol's connection_lost() method will (eventually) called with None as its argument.
Close the transport.
[ "Close", "the", "transport", "." ]
def close(self): """Close the transport. Buffered data will be flushed asynchronously. No more data will be received. After all buffered data is flushed, the protocol's connection_lost() method will (eventually) called with None as its argument. """ raise NotImplementedError
[ "def", "close", "(", "self", ")", ":", "raise", "NotImplementedError" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/asyncio/transports.py#L25-L33
cvxpy/cvxpy
5165b4fb750dfd237de8659383ef24b4b2e33aaf
cvxpy/atoms/eye_minus_inv.py
python
eye_minus_inv.shape_from_args
(self)
return self.args[0].shape
Returns the (row, col) shape of the expression.
Returns the (row, col) shape of the expression.
[ "Returns", "the", "(", "row", "col", ")", "shape", "of", "the", "expression", "." ]
def shape_from_args(self) -> Tuple[int, ...]: """Returns the (row, col) shape of the expression. """ return self.args[0].shape
[ "def", "shape_from_args", "(", "self", ")", "->", "Tuple", "[", "int", ",", "...", "]", ":", "return", "self", ".", "args", "[", "0", "]", ".", "shape" ]
https://github.com/cvxpy/cvxpy/blob/5165b4fb750dfd237de8659383ef24b4b2e33aaf/cvxpy/atoms/eye_minus_inv.py#L81-L84
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Path/PathScripts/PathSurfaceSupport.py
python
ProcessSelectedFaces._calculateOffsetValue
(self, isHole, isVoid=False)
return offset
_calculateOffsetValue(self.obj, isHole, isVoid) ... internal function. Calculate the offset for the Path.Area() function.
_calculateOffsetValue(self.obj, isHole, isVoid) ... internal function. Calculate the offset for the Path.Area() function.
[ "_calculateOffsetValue", "(", "self", ".", "obj", "isHole", "isVoid", ")", "...", "internal", "function", ".", "Calculate", "the", "offset", "for", "the", "Path", ".", "Area", "()", "function", "." ]
def _calculateOffsetValue(self, isHole, isVoid=False): """_calculateOffsetValue(self.obj, isHole, isVoid) ... internal function. Calculate the offset for the Path.Area() function.""" self.JOB = PathUtils.findParentJob(self.obj) # We need to offset by at least our linear tessellation deflection # (default GeometryTolerance / 4) to avoid false retracts at the # boundaries. tolrnc = max( self.JOB.GeometryTolerance.Value / 10.0, self.obj.LinearDeflection.Value ) if isVoid is False: if isHole is True: offset = -1 * self.obj.InternalFeaturesAdjustment.Value offset += self.radius + tolrnc else: offset = -1 * self.obj.BoundaryAdjustment.Value if self.obj.BoundaryEnforcement is True: offset += self.radius + tolrnc else: offset -= self.radius + tolrnc offset = 0.0 - offset else: offset = -1 * self.obj.BoundaryAdjustment.Value offset += self.radius + tolrnc return offset
[ "def", "_calculateOffsetValue", "(", "self", ",", "isHole", ",", "isVoid", "=", "False", ")", ":", "self", ".", "JOB", "=", "PathUtils", ".", "findParentJob", "(", "self", ".", "obj", ")", "# We need to offset by at least our linear tessellation deflection", "# (def...
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Path/PathScripts/PathSurfaceSupport.py#L977-L1003
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/protorpc/ez_setup.py
python
use_setuptools
( version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir, download_delay=15 )
return do_download()
Automatically find/download setuptools and make it available on sys.path `version` should be a valid setuptools version number that is available as an egg for download under the `download_base` URL (which should end with a '/'). `to_dir` is the directory where setuptools will be downloaded, if it is not already available. If `download_delay` is specified, it should be the number of seconds that will be paused before initiating a download, should one be required. If an older version of setuptools is installed, this routine will print a message to ``sys.stderr`` and raise SystemExit in an attempt to abort the calling script.
Automatically find/download setuptools and make it available on sys.path
[ "Automatically", "find", "/", "download", "setuptools", "and", "make", "it", "available", "on", "sys", ".", "path" ]
def use_setuptools( version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir, download_delay=15 ): """Automatically find/download setuptools and make it available on sys.path `version` should be a valid setuptools version number that is available as an egg for download under the `download_base` URL (which should end with a '/'). `to_dir` is the directory where setuptools will be downloaded, if it is not already available. If `download_delay` is specified, it should be the number of seconds that will be paused before initiating a download, should one be required. If an older version of setuptools is installed, this routine will print a message to ``sys.stderr`` and raise SystemExit in an attempt to abort the calling script. """ was_imported = 'pkg_resources' in sys.modules or 'setuptools' in sys.modules def do_download(): egg = download_setuptools(version, download_base, to_dir, download_delay) sys.path.insert(0, egg) import setuptools; setuptools.bootstrap_install_from = egg try: import pkg_resources except ImportError: return do_download() try: pkg_resources.require("setuptools>="+version); return except pkg_resources.VersionConflict, e: if was_imported: print >>sys.stderr, ( "The required version of setuptools (>=%s) is not available, and\n" "can't be installed while this script is running. Please install\n" " a more recent version first, using 'easy_install -U setuptools'." "\n\n(Currently using %r)" ) % (version, e.args[0]) sys.exit(2) except pkg_resources.DistributionNotFound: pass del pkg_resources, sys.modules['pkg_resources'] # reload ok return do_download()
[ "def", "use_setuptools", "(", "version", "=", "DEFAULT_VERSION", ",", "download_base", "=", "DEFAULT_URL", ",", "to_dir", "=", "os", ".", "curdir", ",", "download_delay", "=", "15", ")", ":", "was_imported", "=", "'pkg_resources'", "in", "sys", ".", "modules",...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/protorpc/ez_setup.py#L53-L92
facebook/proxygen
a9ca025af207787815cb01eee1971cd572c7a81e
build/fbcode_builder/getdeps.py
python
CachedProject.is_cacheable
(self)
return self.cache and self.m.shipit_project is None
We only cache third party projects
We only cache third party projects
[ "We", "only", "cache", "third", "party", "projects" ]
def is_cacheable(self): """We only cache third party projects""" return self.cache and self.m.shipit_project is None
[ "def", "is_cacheable", "(", "self", ")", ":", "return", "self", ".", "cache", "and", "self", ".", "m", ".", "shipit_project", "is", "None" ]
https://github.com/facebook/proxygen/blob/a9ca025af207787815cb01eee1971cd572c7a81e/build/fbcode_builder/getdeps.py#L238-L240
neoml-lib/neoml
a0d370fba05269a1b2258cef126f77bbd2054a3e
NeoML/Python/neoml/DifferentialEvolution.py
python
DifferentialEvolution.run
(self)
return self.internal.run()
Runs optimization until one of the stop conditions is fulfilled.
Runs optimization until one of the stop conditions is fulfilled.
[ "Runs", "optimization", "until", "one", "of", "the", "stop", "conditions", "is", "fulfilled", "." ]
def run(self): """Runs optimization until one of the stop conditions is fulfilled. """ return self.internal.run()
[ "def", "run", "(", "self", ")", ":", "return", "self", ".", "internal", ".", "run", "(", ")" ]
https://github.com/neoml-lib/neoml/blob/a0d370fba05269a1b2258cef126f77bbd2054a3e/NeoML/Python/neoml/DifferentialEvolution.py#L289-L292
yrnkrn/zapcc
c6a8aa30006d997eff0d60fd37b0e62b8aa0ea50
tools/clang/bindings/python/clang/cindex.py
python
Cursor.location
(self)
return self._loc
Return the source location (the starting character) of the entity pointed at by the cursor.
Return the source location (the starting character) of the entity pointed at by the cursor.
[ "Return", "the", "source", "location", "(", "the", "starting", "character", ")", "of", "the", "entity", "pointed", "at", "by", "the", "cursor", "." ]
def location(self): """ Return the source location (the starting character) of the entity pointed at by the cursor. """ if not hasattr(self, '_loc'): self._loc = conf.lib.clang_getCursorLocation(self) return self._loc
[ "def", "location", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_loc'", ")", ":", "self", ".", "_loc", "=", "conf", ".", "lib", ".", "clang_getCursorLocation", "(", "self", ")", "return", "self", ".", "_loc" ]
https://github.com/yrnkrn/zapcc/blob/c6a8aa30006d997eff0d60fd37b0e62b8aa0ea50/tools/clang/bindings/python/clang/cindex.py#L1550-L1558
thalium/icebox
99d147d5b9269222225443ce171b4fd46d8985d4
third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py
python
xmlDoc.parameterEntity
(self, name)
return __tmp
Do an entity lookup in the internal and external subsets and
Do an entity lookup in the internal and external subsets and
[ "Do", "an", "entity", "lookup", "in", "the", "internal", "and", "external", "subsets", "and" ]
def parameterEntity(self, name): """Do an entity lookup in the internal and external subsets and """ ret = libxml2mod.xmlGetParameterEntity(self._o, name) if ret is None:raise treeError('xmlGetParameterEntity() failed') __tmp = xmlEntity(_obj=ret) return __tmp
[ "def", "parameterEntity", "(", "self", ",", "name", ")", ":", "ret", "=", "libxml2mod", ".", "xmlGetParameterEntity", "(", "self", ".", "_o", ",", "name", ")", "if", "ret", "is", "None", ":", "raise", "treeError", "(", "'xmlGetParameterEntity() failed'", ")"...
https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py#L4166-L4171