nwo
stringlengths
5
86
sha
stringlengths
40
40
path
stringlengths
4
189
language
stringclasses
1 value
identifier
stringlengths
1
94
parameters
stringlengths
2
4.03k
argument_list
stringclasses
1 value
return_statement
stringlengths
0
11.5k
docstring
stringlengths
1
33.2k
docstring_summary
stringlengths
0
5.15k
docstring_tokens
list
function
stringlengths
34
151k
function_tokens
list
url
stringlengths
90
278
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/Tkinter.py
python
Wm.wm_frame
(self)
return self.tk.call('wm', 'frame', self._w)
Return identifier for decorative frame of this widget if present.
Return identifier for decorative frame of this widget if present.
[ "Return", "identifier", "for", "decorative", "frame", "of", "this", "widget", "if", "present", "." ]
def wm_frame(self): """Return identifier for decorative frame of this widget if present.""" return self.tk.call('wm', 'frame', self._w)
[ "def", "wm_frame", "(", "self", ")", ":", "return", "self", ".", "tk", ".", "call", "(", "'wm'", ",", "'frame'", ",", "self", ".", "_w", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/Tkinter.py#L1587-L1589
thalium/icebox
99d147d5b9269222225443ce171b4fd46d8985d4
third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py
python
parseMemory
(buffer, size)
return xmlDoc(_obj=ret)
parse an XML in-memory block and build a tree.
parse an XML in-memory block and build a tree.
[ "parse", "an", "XML", "in", "-", "memory", "block", "and", "build", "a", "tree", "." ]
def parseMemory(buffer, size): """parse an XML in-memory block and build a tree. """ ret = libxml2mod.xmlParseMemory(buffer, size) if ret is None:raise parserError('xmlParseMemory() failed') return xmlDoc(_obj=ret)
[ "def", "parseMemory", "(", "buffer", ",", "size", ")", ":", "ret", "=", "libxml2mod", ".", "xmlParseMemory", "(", "buffer", ",", "size", ")", "if", "ret", "is", "None", ":", "raise", "parserError", "(", "'xmlParseMemory() failed'", ")", "return", "xmlDoc", ...
https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py#L1346-L1350
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/protobuf/python/google/protobuf/internal/well_known_types.py
python
Duration.ToTimedelta
(self)
return timedelta( seconds=self.seconds, microseconds=_RoundTowardZero( self.nanos, _NANOS_PER_MICROSECOND))
Converts Duration to timedelta.
Converts Duration to timedelta.
[ "Converts", "Duration", "to", "timedelta", "." ]
def ToTimedelta(self): """Converts Duration to timedelta.""" return timedelta( seconds=self.seconds, microseconds=_RoundTowardZero( self.nanos, _NANOS_PER_MICROSECOND))
[ "def", "ToTimedelta", "(", "self", ")", ":", "return", "timedelta", "(", "seconds", "=", "self", ".", "seconds", ",", "microseconds", "=", "_RoundTowardZero", "(", "self", ".", "nanos", ",", "_NANOS_PER_MICROSECOND", ")", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/protobuf/python/google/protobuf/internal/well_known_types.py#L341-L345
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Editor/Python/windows/Lib/site-packages/pip/utils/outdated.py
python
pip_version_check
(session)
Check for an update for pip. Limit the frequency of checks to once per week. State is stored either in the active virtualenv or in the user's USER_CACHE_DIR keyed off the prefix of the pip script path.
Check for an update for pip.
[ "Check", "for", "an", "update", "for", "pip", "." ]
def pip_version_check(session): """Check for an update for pip. Limit the frequency of checks to once per week. State is stored either in the active virtualenv or in the user's USER_CACHE_DIR keyed off the prefix of the pip script path. """ import pip # imported here to prevent circular imports pypi_version = None try: state = load_selfcheck_statefile() current_time = datetime.datetime.utcnow() # Determine if we need to refresh the state if "last_check" in state.state and "pypi_version" in state.state: last_check = datetime.datetime.strptime( state.state["last_check"], SELFCHECK_DATE_FMT ) if total_seconds(current_time - last_check) < 7 * 24 * 60 * 60: pypi_version = state.state["pypi_version"] # Refresh the version if we need to or just see if we need to warn if pypi_version is None: resp = session.get( PyPI.pip_json_url, headers={"Accept": "application/json"}, ) resp.raise_for_status() pypi_version = [ v for v in sorted( list(resp.json()["releases"]), key=packaging_version.parse, ) if not packaging_version.parse(v).is_prerelease ][-1] # save that we've performed a check state.save(pypi_version, current_time) pip_version = packaging_version.parse(pip.__version__) remote_version = packaging_version.parse(pypi_version) # Determine if our pypi_version is older if (pip_version < remote_version and pip_version.base_version != remote_version.base_version): logger.warning( "You are using pip version %s, however version %s is " "available.\nYou should consider upgrading via the " "'pip install --upgrade pip' command." % (pip.__version__, pypi_version) ) except Exception: logger.debug( "There was an error checking the latest version of pip", exc_info=True, )
[ "def", "pip_version_check", "(", "session", ")", ":", "import", "pip", "# imported here to prevent circular imports", "pypi_version", "=", "None", "try", ":", "state", "=", "load_selfcheck_statefile", "(", ")", "current_time", "=", "datetime", ".", "datetime", ".", ...
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/pip/utils/outdated.py#L95-L153
rapidsai/cudf
d5b2448fc69f17509304d594f029d0df56984962
python/cudf/cudf/core/column/timedelta.py
python
TimeDeltaColumn.nanoseconds
(self)
return ( self % cudf.Scalar( np.timedelta64(_numpy_to_pandas_conversion["us"], "ns") ) ) // cudf.Scalar( np.timedelta64(_numpy_to_pandas_conversion["ns"], "ns") )
Return the number of nanoseconds (n), where 0 <= n < 1 microsecond. Returns ------- NumericalColumn
Return the number of nanoseconds (n), where 0 <= n < 1 microsecond.
[ "Return", "the", "number", "of", "nanoseconds", "(", "n", ")", "where", "0", "<", "=", "n", "<", "1", "microsecond", "." ]
def nanoseconds(self) -> "cudf.core.column.NumericalColumn": """ Return the number of nanoseconds (n), where 0 <= n < 1 microsecond. Returns ------- NumericalColumn """ # This property must return the number of nanoseconds (>= 0 and # less than 1 microsecond) for each element, hence first performing # mod operation to remove the number of microseconds and then # performing division operation to extract the number # of nanoseconds. return ( self % cudf.Scalar( np.timedelta64(_numpy_to_pandas_conversion["us"], "ns") ) ) // cudf.Scalar( np.timedelta64(_numpy_to_pandas_conversion["ns"], "ns") )
[ "def", "nanoseconds", "(", "self", ")", "->", "\"cudf.core.column.NumericalColumn\"", ":", "# This property must return the number of nanoseconds (>= 0 and", "# less than 1 microsecond) for each element, hence first performing", "# mod operation to remove the number of microseconds and then", ...
https://github.com/rapidsai/cudf/blob/d5b2448fc69f17509304d594f029d0df56984962/python/cudf/cudf/core/column/timedelta.py#L555-L576
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
lts/tools/gyp/pylib/gyp/xcode_emulation.py
python
XcodeSettings.GetBundleSharedSupportFolderPath
(self)
Returns the qualified path to the bundle's shared support folder. E.g, Chromium.app/Contents/SharedSupport. Only valid for bundles.
Returns the qualified path to the bundle's shared support folder. E.g, Chromium.app/Contents/SharedSupport. Only valid for bundles.
[ "Returns", "the", "qualified", "path", "to", "the", "bundle", "s", "shared", "support", "folder", ".", "E", ".", "g", "Chromium", ".", "app", "/", "Contents", "/", "SharedSupport", ".", "Only", "valid", "for", "bundles", "." ]
def GetBundleSharedSupportFolderPath(self): """Returns the qualified path to the bundle's shared support folder. E.g, Chromium.app/Contents/SharedSupport. Only valid for bundles.""" assert self._IsBundle() if self.spec['type'] == 'shared_library': return self.GetBundleResourceFolder() else: return os.path.join(self.GetBundleContentsFolderPath(), 'SharedSupport')
[ "def", "GetBundleSharedSupportFolderPath", "(", "self", ")", ":", "assert", "self", ".", "_IsBundle", "(", ")", "if", "self", ".", "spec", "[", "'type'", "]", "==", "'shared_library'", ":", "return", "self", ".", "GetBundleResourceFolder", "(", ")", "else", ...
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/tools/gyp/pylib/gyp/xcode_emulation.py#L347-L355
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/keras/utils/metrics_utils.py
python
is_evenly_distributed_thresholds
(thresholds)
return np.allclose(thresholds, even_thresholds, atol=backend.epsilon())
Check if the thresholds list is evenly distributed. We could leverage evenly distributed thresholds to use less memory when calculate metrcis like AUC where each individual threshold need to be evaluted. Args: thresholds: A python list or tuple, or 1D numpy array whose value is ranged in [0, 1]. Returns: boolean, whether the values in the inputs are evenly distributed.
Check if the thresholds list is evenly distributed.
[ "Check", "if", "the", "thresholds", "list", "is", "evenly", "distributed", "." ]
def is_evenly_distributed_thresholds(thresholds): """Check if the thresholds list is evenly distributed. We could leverage evenly distributed thresholds to use less memory when calculate metrcis like AUC where each individual threshold need to be evaluted. Args: thresholds: A python list or tuple, or 1D numpy array whose value is ranged in [0, 1]. Returns: boolean, whether the values in the inputs are evenly distributed. """ # Check the list value and see if it is evenly distributed. num_thresholds = len(thresholds) if num_thresholds < 3: return False even_thresholds = np.arange(num_thresholds, dtype=np.float32) / (num_thresholds - 1) return np.allclose(thresholds, even_thresholds, atol=backend.epsilon())
[ "def", "is_evenly_distributed_thresholds", "(", "thresholds", ")", ":", "# Check the list value and see if it is evenly distributed.", "num_thresholds", "=", "len", "(", "thresholds", ")", "if", "num_thresholds", "<", "3", ":", "return", "False", "even_thresholds", "=", "...
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/keras/utils/metrics_utils.py#L482-L502
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/richtext.py
python
RichTextCtrl.PageDown
(*args, **kwargs)
return _richtext.RichTextCtrl_PageDown(*args, **kwargs)
PageDown(self, int noPages=1, int flags=0) -> bool Move n pages down
PageDown(self, int noPages=1, int flags=0) -> bool
[ "PageDown", "(", "self", "int", "noPages", "=", "1", "int", "flags", "=", "0", ")", "-", ">", "bool" ]
def PageDown(*args, **kwargs): """ PageDown(self, int noPages=1, int flags=0) -> bool Move n pages down """ return _richtext.RichTextCtrl_PageDown(*args, **kwargs)
[ "def", "PageDown", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_richtext", ".", "RichTextCtrl_PageDown", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/richtext.py#L3808-L3814
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/email/message.py
python
Message.del_param
(self, param, header='content-type', requote=True)
Remove the given parameter completely from the Content-Type header. The header will be re-written in place without the parameter or its value. All values will be quoted as necessary unless requote is False. Optional header specifies an alternative to the Content-Type header.
Remove the given parameter completely from the Content-Type header.
[ "Remove", "the", "given", "parameter", "completely", "from", "the", "Content", "-", "Type", "header", "." ]
def del_param(self, param, header='content-type', requote=True): """Remove the given parameter completely from the Content-Type header. The header will be re-written in place without the parameter or its value. All values will be quoted as necessary unless requote is False. Optional header specifies an alternative to the Content-Type header. """ if header not in self: return new_ctype = '' for p, v in self.get_params(header=header, unquote=requote): if p.lower() != param.lower(): if not new_ctype: new_ctype = _formatparam(p, v, requote) else: new_ctype = SEMISPACE.join([new_ctype, _formatparam(p, v, requote)]) if new_ctype != self.get(header): del self[header] self[header] = new_ctype
[ "def", "del_param", "(", "self", ",", "param", ",", "header", "=", "'content-type'", ",", "requote", "=", "True", ")", ":", "if", "header", "not", "in", "self", ":", "return", "new_ctype", "=", "''", "for", "p", ",", "v", "in", "self", ".", "get_para...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/email/message.py#L619-L639
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/prompt-toolkit/py3/prompt_toolkit/input/vt100_parser.py
python
Vt100Parser._start_parser
(self)
Start the parser coroutine.
Start the parser coroutine.
[ "Start", "the", "parser", "coroutine", "." ]
def _start_parser(self) -> None: """ Start the parser coroutine. """ self._input_parser = self._input_parser_generator() self._input_parser.send(None)
[ "def", "_start_parser", "(", "self", ")", "->", "None", ":", "self", ".", "_input_parser", "=", "self", ".", "_input_parser_generator", "(", ")", "self", ".", "_input_parser", ".", "send", "(", "None", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/prompt-toolkit/py3/prompt_toolkit/input/vt100_parser.py#L94-L99
ceph/ceph
959663007321a369c83218414a29bd9dbc8bda3a
qa/tasks/ceph.py
python
assign_devs
(roles, devs)
return dict(zip(roles, devs))
Create a dictionary of devs indexed by roles :param roles: List of roles :param devs: Corresponding list of devices. :returns: Dictionary of devs indexed by roles.
Create a dictionary of devs indexed by roles
[ "Create", "a", "dictionary", "of", "devs", "indexed", "by", "roles" ]
def assign_devs(roles, devs): """ Create a dictionary of devs indexed by roles :param roles: List of roles :param devs: Corresponding list of devices. :returns: Dictionary of devs indexed by roles. """ return dict(zip(roles, devs))
[ "def", "assign_devs", "(", "roles", ",", "devs", ")", ":", "return", "dict", "(", "zip", "(", "roles", ",", "devs", ")", ")" ]
https://github.com/ceph/ceph/blob/959663007321a369c83218414a29bd9dbc8bda3a/qa/tasks/ceph.py#L300-L308
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/httplib.py
python
HTTPConnection.send
(self, data)
Send `data' to the server.
Send `data' to the server.
[ "Send", "data", "to", "the", "server", "." ]
def send(self, data): """Send `data' to the server.""" if self.sock is None: if self.auto_open: self.connect() else: raise NotConnected() if self.debuglevel > 0: print "send:", repr(data) blocksize = 8192 if hasattr(data,'read') and not isinstance(data, array): if self.debuglevel > 0: print "sendIng a read()able" datablock = data.read(blocksize) while datablock: self.sock.sendall(datablock) datablock = data.read(blocksize) else: self.sock.sendall(data)
[ "def", "send", "(", "self", ",", "data", ")", ":", "if", "self", ".", "sock", "is", "None", ":", "if", "self", ".", "auto_open", ":", "self", ".", "connect", "(", ")", "else", ":", "raise", "NotConnected", "(", ")", "if", "self", ".", "debuglevel",...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/httplib.py#L840-L858
pyne/pyne
0c2714d7c0d1b5e20be6ae6527da2c660dd6b1b3
pyne/njoy.py
python
Njoy99.makefp
(self, eaf=0)
Creates a PENDF, GENDF, and DRAGLIB file for a single fission product. Parameters ---------- eaf : int If eaf is 1, simplified processing is performed to be compatible with the EAF nuclear library.
Creates a PENDF, GENDF, and DRAGLIB file for a single fission product.
[ "Creates", "a", "PENDF", "GENDF", "and", "DRAGLIB", "file", "for", "a", "single", "fission", "product", "." ]
def makefp(self, eaf=0): """Creates a PENDF, GENDF, and DRAGLIB file for a single fission product. Parameters ---------- eaf : int If eaf is 1, simplified processing is performed to be compatible with the EAF nuclear library. """ self.scattering_law = None self.fission = None self.dilutions = None keeplegendre = self.legendre self.legendre = 0 self.pendf(eaf) self.gendf(eaf) self.draglib(fp=1) self.legendre = keeplegendre
[ "def", "makefp", "(", "self", ",", "eaf", "=", "0", ")", ":", "self", ".", "scattering_law", "=", "None", "self", ".", "fission", "=", "None", "self", ".", "dilutions", "=", "None", "keeplegendre", "=", "self", ".", "legendre", "self", ".", "legendre",...
https://github.com/pyne/pyne/blob/0c2714d7c0d1b5e20be6ae6527da2c660dd6b1b3/pyne/njoy.py#L555-L575
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/klampt/model/sensing.py
python
visible
(camera : Union[SimRobotSensor,GLViewport], object, full=True, robot=None)
return visible(camera,object.getBB(),full,robot)
Tests whether the given object is visible in a SimRobotSensor or a GLViewport. If you are doing this multiple times, first convert to GLViewport. Args: camera (SimRobotSensor or GLViewport): the camera. object: a 3-vector, a (center,radius) pair indicating a sphere, an axis-aligned bounding box (bmin,bmax), a Geometry3D, or an object that has a geometry() method, e.g., RigidObjectModel, RobotModelLink. full (bool, optional): if True, the entire object must be in the viewing frustum for it to be considered visible. If False, any part of the object can be in the viewing frustum. robot (RobotModel): if camera is a SimRobotSensor, this will be used to derive the transform.
Tests whether the given object is visible in a SimRobotSensor or a GLViewport.
[ "Tests", "whether", "the", "given", "object", "is", "visible", "in", "a", "SimRobotSensor", "or", "a", "GLViewport", "." ]
def visible(camera : Union[SimRobotSensor,GLViewport], object, full=True, robot=None) -> bool: """Tests whether the given object is visible in a SimRobotSensor or a GLViewport. If you are doing this multiple times, first convert to GLViewport. Args: camera (SimRobotSensor or GLViewport): the camera. object: a 3-vector, a (center,radius) pair indicating a sphere, an axis-aligned bounding box (bmin,bmax), a Geometry3D, or an object that has a geometry() method, e.g., RigidObjectModel, RobotModelLink. full (bool, optional): if True, the entire object must be in the viewing frustum for it to be considered visible. If False, any part of the object can be in the viewing frustum. robot (RobotModel): if camera is a SimRobotSensor, this will be used to derive the transform. """ if isinstance(camera,SimRobotSensor): camera = camera_to_viewport(camera,robot) if hasattr(object,'geometry'): return visible(camera,object.geometry(),full,robot) if hasattr(object,'__iter__'): if not hasattr(object[0],'__iter__'): #vector if len(object) != 3: raise ValueError("Object must be a 3-vector") return camera.project(object) != None elif hasattr(object[1],'__iter__'): if len(object[0]) != 3 or len(object[1]) != 3: raise ValueError("Object must be a bounding box") bmin,bmax = object if not full: #test whether center is in bmin,bmax center = vectorops.interpolate(bmin,bmax,0.5) cproj = camera.project(center) if cproj is not None: return True if all(a <= v <= b for (a,b,v) in zip(bmin,bmax,camera.getTransform()[1])): return True points = [camera.project(bmin,full),camera.project(bmax,full)] pt = [bmin[0],bmin[1],bmax[2]] points.append(camera.project(pt,full)) pt = [bmin[0],bmax[1],bmax[2]] points.append(camera.project(pt,full)) pt = [bmin[0],bmax[1],bmin[2]] points.append(camera.project(pt,full)) pt = [bmax[0],bmin[1],bmin[2]] points.append(camera.project(pt,full)) pt = [bmax[0],bmin[1],bmax[2]] points.append(camera.project(pt,full)) pt = [bmax[0],bmax[1],bmin[2]] points.append(camera.project(pt,full)) if any(p is None for p in points): return False if full: return True if min(p[2] for p in points) > camera.clippingplanes[1]: return False if max(p[2] for p in points) < camera.clippingplanes[0]: return False points = [p for p in points if p[2] > 0] for p in points: if 0 <= p[0] <= camera.w and 0 <= p[1] <= camera.h: return True #TODO: intersection of projected polygon return False else: #sphere if len(object[0]) != 3: raise ValueError("Object must be a sphere") c,r = object if full: cproj = camera.project(c,True) if cproj is None: return False rproj = camera.w/cproj[2]*r if cproj[2] - r < camera.clippingplanes[0] or cproj[2] + r > camera.clippingplanes[1]: return False return 0 <= cproj[0] - rproj and cproj[0] + rproj <= camera.w and 0 <= cproj[1] - rproj and cproj[1] + rproj <= camera.h else: cproj = camera.project(c,False) if cproj is None: dist = r - vectorops.distance(camera.getTransform()[1],c) if dist >= camera.clippingplanes[0]: return True return False if 0 <= cproj[0] <= camera.w and 0 <= cproj[1] <= camera.h: if cproj[2] + r > camera.clippingplanes[0] and cproj[2] - r < camera.clippingplanes[1]: return True return False rproj = camera.w/cproj[2]*r xclosest = max(min(cproj[0],camera.w),0) yclosest = max(min(cproj[1],camera.h),0) zclosest = max(min(cproj[2],camera.clippingplanes[1]),camera.clippingplanes[0]) return vectorops.distance((xclosest,yclosest),cproj[0:2]) <= rproj if not isinstance(object,Geometry3D): raise ValueError("Object must be a point, sphere, bounding box, or Geometry3D") return visible(camera,object.getBB(),full,robot)
[ "def", "visible", "(", "camera", ":", "Union", "[", "SimRobotSensor", ",", "GLViewport", "]", ",", "object", ",", "full", "=", "True", ",", "robot", "=", "None", ")", "->", "bool", ":", "if", "isinstance", "(", "camera", ",", "SimRobotSensor", ")", ":"...
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/model/sensing.py#L889-L985
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/ros_comm/rosgraph/src/rosgraph/xmlrpc.py
python
XmlRpcNode._run
(self)
Main processing thread body. :raises: :exc:`socket.error` If server cannot bind
Main processing thread body. :raises: :exc:`socket.error` If server cannot bind
[ "Main", "processing", "thread", "body", ".", ":", "raises", ":", ":", "exc", ":", "socket", ".", "error", "If", "server", "cannot", "bind" ]
def _run(self): """ Main processing thread body. :raises: :exc:`socket.error` If server cannot bind """ self._run_init() while not self.is_shutdown: try: self.server.serve_forever() except (IOError, select.error) as e: # check for interrupted call, which can occur if we're # embedded in a program using signals. All other # exceptions break _run. if self.is_shutdown: pass elif e.errno != 4: self.is_shutdown = True logging.getLogger('xmlrpc').error("serve forever IOError: %s, %s"%(e.errno, e.strerror))
[ "def", "_run", "(", "self", ")", ":", "self", ".", "_run_init", "(", ")", "while", "not", "self", ".", "is_shutdown", ":", "try", ":", "self", ".", "server", ".", "serve_forever", "(", ")", "except", "(", "IOError", ",", "select", ".", "error", ")", ...
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/ros_comm/rosgraph/src/rosgraph/xmlrpc.py#L278-L296
ChenglongChen/kaggle-CrowdFlower
a72eabb2e53c308c345905eff79c3c8e3a389239
Code/Feat/ngram.py
python
getUnigram
(words)
return words
Input: a list of words, e.g., ['I', 'am', 'Denny'] Output: a list of unigram
Input: a list of words, e.g., ['I', 'am', 'Denny'] Output: a list of unigram
[ "Input", ":", "a", "list", "of", "words", "e", ".", "g", ".", "[", "I", "am", "Denny", "]", "Output", ":", "a", "list", "of", "unigram" ]
def getUnigram(words): """ Input: a list of words, e.g., ['I', 'am', 'Denny'] Output: a list of unigram """ assert type(words) == list return words
[ "def", "getUnigram", "(", "words", ")", ":", "assert", "type", "(", "words", ")", "==", "list", "return", "words" ]
https://github.com/ChenglongChen/kaggle-CrowdFlower/blob/a72eabb2e53c308c345905eff79c3c8e3a389239/Code/Feat/ngram.py#L18-L24
bairdzhang/smallhardface
76fa1d87a9602d9b13d7a7fe693fc7aec91cab80
lib/layers/generate_anchors.py
python
_whctrs
(anchor)
return w, h, x_ctr, y_ctr
Return width, height, x center, and y center for an anchor (window).
Return width, height, x center, and y center for an anchor (window).
[ "Return", "width", "height", "x", "center", "and", "y", "center", "for", "an", "anchor", "(", "window", ")", "." ]
def _whctrs(anchor): """ Return width, height, x center, and y center for an anchor (window). """ w = anchor[2] - anchor[0] + 1 h = anchor[3] - anchor[1] + 1 x_ctr = anchor[0] + 0.5 * (w - 1) y_ctr = anchor[1] + 0.5 * (h - 1) return w, h, x_ctr, y_ctr
[ "def", "_whctrs", "(", "anchor", ")", ":", "w", "=", "anchor", "[", "2", "]", "-", "anchor", "[", "0", "]", "+", "1", "h", "=", "anchor", "[", "3", "]", "-", "anchor", "[", "1", "]", "+", "1", "x_ctr", "=", "anchor", "[", "0", "]", "+", "...
https://github.com/bairdzhang/smallhardface/blob/76fa1d87a9602d9b13d7a7fe693fc7aec91cab80/lib/layers/generate_anchors.py#L29-L38
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/AWSPythonSDK/1.5.8/docutils/utils/math/math2html.py
python
LimitsProcessor.process
(self, contents, index)
Process the limits for an element.
Process the limits for an element.
[ "Process", "the", "limits", "for", "an", "element", "." ]
def process(self, contents, index): "Process the limits for an element." if Options.simplemath: return if self.checklimits(contents, index): self.modifylimits(contents, index) if self.checkscript(contents, index) and self.checkscript(contents, index + 1): self.modifyscripts(contents, index)
[ "def", "process", "(", "self", ",", "contents", ",", "index", ")", ":", "if", "Options", ".", "simplemath", ":", "return", "if", "self", ".", "checklimits", "(", "contents", ",", "index", ")", ":", "self", ".", "modifylimits", "(", "contents", ",", "in...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/docutils/utils/math/math2html.py#L4668-L4675
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/indexes/numeric.py
python
UInt64Index.inferred_type
(self)
return "integer"
Always 'integer' for ``UInt64Index``
Always 'integer' for ``UInt64Index``
[ "Always", "integer", "for", "UInt64Index" ]
def inferred_type(self) -> str: """ Always 'integer' for ``UInt64Index`` """ return "integer"
[ "def", "inferred_type", "(", "self", ")", "->", "str", ":", "return", "\"integer\"" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/indexes/numeric.py#L307-L311
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/telemetry/third_party/web-page-replay/third_party/dns/update.py
python
Update.replace
(self, name, *args)
Replace records. The first argument is always a name. The other arguments can be: - rdataset... - ttl, rdata... - ttl, rdtype, string... Note that if you want to replace the entire node, you should do a delete of the name followed by one or more calls to add.
Replace records. The first argument is always a name. The other arguments can be:
[ "Replace", "records", ".", "The", "first", "argument", "is", "always", "a", "name", ".", "The", "other", "arguments", "can", "be", ":" ]
def replace(self, name, *args): """Replace records. The first argument is always a name. The other arguments can be: - rdataset... - ttl, rdata... - ttl, rdtype, string... Note that if you want to replace the entire node, you should do a delete of the name followed by one or more calls to add.""" self._add(True, self.authority, name, *args)
[ "def", "replace", "(", "self", ",", "name", ",", "*", "args", ")", ":", "self", ".", "_add", "(", "True", ",", "self", ".", "authority", ",", "name", ",", "*", "args", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/third_party/web-page-replay/third_party/dns/update.py#L165-L178
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/ops/ragged/ragged_array_ops.py
python
reverse
(tensor: ragged_tensor.Ragged, axis, name=None)
Reverses a RaggedTensor along the specified axes. #### Example: >>> data = tf.ragged.constant([ ... [[1, 2], [3, 4]], [[5, 6]], [[7, 8], [9, 10], [11, 12]]]) >>> tf.reverse(data, axis=[0, 2]) <tf.RaggedTensor [[[8, 7], [10, 9], [12, 11]], [[6, 5]], [[2, 1], [4, 3]]]> Args: tensor: A 'RaggedTensor' to reverse. axis: A list or tuple of 'int' or a constant 1D 'tf.Tensor'. The indices of the axes to reverse. name: A name prefix for the returned tensor (optional). Returns: A 'RaggedTensor'.
Reverses a RaggedTensor along the specified axes.
[ "Reverses", "a", "RaggedTensor", "along", "the", "specified", "axes", "." ]
def reverse(tensor: ragged_tensor.Ragged, axis, name=None): """Reverses a RaggedTensor along the specified axes. #### Example: >>> data = tf.ragged.constant([ ... [[1, 2], [3, 4]], [[5, 6]], [[7, 8], [9, 10], [11, 12]]]) >>> tf.reverse(data, axis=[0, 2]) <tf.RaggedTensor [[[8, 7], [10, 9], [12, 11]], [[6, 5]], [[2, 1], [4, 3]]]> Args: tensor: A 'RaggedTensor' to reverse. axis: A list or tuple of 'int' or a constant 1D 'tf.Tensor'. The indices of the axes to reverse. name: A name prefix for the returned tensor (optional). Returns: A 'RaggedTensor'. """ type_error_msg = ('`axis` must be a list of int or a constant tensor' 'when reversing axes in a ragged tensor') with ops.name_scope(name, 'Reverse', [tensor, axis]): if isinstance(axis, ops.Tensor): axis = tensor_util.constant_value(axis) if axis is None: raise TypeError(type_error_msg) elif not (isinstance(axis, (list, tuple)) and all(isinstance(dim, int) for dim in axis)): raise TypeError(type_error_msg) tensor = ragged_tensor.convert_to_tensor_or_ragged_tensor( tensor, name='tensor') # Allow usage of negative values to specify innermost axes. axis = [ array_ops.get_positive_axis(dim, tensor.shape.rank, 'axis[%d]' % i, 'rank(tensor)') for i, dim in enumerate(axis) ] # We only need to slice up to the max axis. If the axis list # is empty, it should be 0. slices = [slice(None)] * (max(axis) + 1 if axis else 0) for dim in axis: slices[dim] = slice(None, None, -1) return tensor[tuple(slices)]
[ "def", "reverse", "(", "tensor", ":", "ragged_tensor", ".", "Ragged", ",", "axis", ",", "name", "=", "None", ")", ":", "type_error_msg", "=", "(", "'`axis` must be a list of int or a constant tensor'", "'when reversing axes in a ragged tensor'", ")", "with", "ops", "....
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/ragged/ragged_array_ops.py#L676-L724
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/richtext.py
python
RichTextPrinting.SetRichTextBufferPrinting
(*args, **kwargs)
return _richtext.RichTextPrinting_SetRichTextBufferPrinting(*args, **kwargs)
SetRichTextBufferPrinting(self, RichTextBuffer buf)
SetRichTextBufferPrinting(self, RichTextBuffer buf)
[ "SetRichTextBufferPrinting", "(", "self", "RichTextBuffer", "buf", ")" ]
def SetRichTextBufferPrinting(*args, **kwargs): """SetRichTextBufferPrinting(self, RichTextBuffer buf)""" return _richtext.RichTextPrinting_SetRichTextBufferPrinting(*args, **kwargs)
[ "def", "SetRichTextBufferPrinting", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_richtext", ".", "RichTextPrinting_SetRichTextBufferPrinting", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/richtext.py#L4572-L4574
kamyu104/LeetCode-Solutions
77605708a927ea3b85aee5a479db733938c7c211
Python/path-with-maximum-probability.py
python
Solution.maxProbability
(self, n, edges, succProb, start, end)
return result[end]
:type n: int :type edges: List[List[int]] :type succProb: List[float] :type start: int :type end: int :rtype: float
:type n: int :type edges: List[List[int]] :type succProb: List[float] :type start: int :type end: int :rtype: float
[ ":", "type", "n", ":", "int", ":", "type", "edges", ":", "List", "[", "List", "[", "int", "]]", ":", "type", "succProb", ":", "List", "[", "float", "]", ":", "type", "start", ":", "int", ":", "type", "end", ":", "int", ":", "rtype", ":", "float...
def maxProbability(self, n, edges, succProb, start, end): """ :type n: int :type edges: List[List[int]] :type succProb: List[float] :type start: int :type end: int :rtype: float """ adj = collections.defaultdict(list) for (u, v), p in itertools.izip(edges, succProb): adj[u].append((v, p)) adj[v].append((u, p)) max_heap = [(-1.0, start)] result, lookup = collections.defaultdict(float), set() result[start] = 1.0 while max_heap and len(lookup) != len(adj): curr, u = heapq.heappop(max_heap) if u in lookup: continue lookup.add(u) for v, w in adj[u]: if v in lookup: continue if v in result and result[v] >= -curr*w: continue result[v] = -curr*w heapq.heappush(max_heap, (-result[v], v)) return result[end]
[ "def", "maxProbability", "(", "self", ",", "n", ",", "edges", ",", "succProb", ",", "start", ",", "end", ")", ":", "adj", "=", "collections", ".", "defaultdict", "(", "list", ")", "for", "(", "u", ",", "v", ")", ",", "p", "in", "itertools", ".", ...
https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/path-with-maximum-probability.py#L11-L39
baidu/bigflow
449245016c0df7d1252e85581e588bfc60cefad3
bigflow_python/python/bigflow/core/serde/cloudpickle.py
python
CloudPickler.save_xrange
(self, obj)
Save an xrange object in python 2.5 Python 2.6 supports this natively
Save an xrange object in python 2.5 Python 2.6 supports this natively
[ "Save", "an", "xrange", "object", "in", "python", "2", ".", "5", "Python", "2", ".", "6", "supports", "this", "natively" ]
def save_xrange(self, obj): """Save an xrange object in python 2.5 Python 2.6 supports this natively """ range_params = xrange_params(obj) self.save_reduce(_build_xrange,range_params)
[ "def", "save_xrange", "(", "self", ",", "obj", ")", ":", "range_params", "=", "xrange_params", "(", "obj", ")", "self", ".", "save_reduce", "(", "_build_xrange", ",", "range_params", ")" ]
https://github.com/baidu/bigflow/blob/449245016c0df7d1252e85581e588bfc60cefad3/bigflow_python/python/bigflow/core/serde/cloudpickle.py#L659-L664
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/fitting_widgets/basic_fitting/basic_fitting_model.py
python
BasicFittingModel._do_single_fit
(self, parameters: dict)
return function, fit_status, chi_squared
Does a single fit and returns the fit function, status and chi squared. Adds the results to the ADS.
Does a single fit and returns the fit function, status and chi squared. Adds the results to the ADS.
[ "Does", "a", "single", "fit", "and", "returns", "the", "fit", "function", "status", "and", "chi", "squared", ".", "Adds", "the", "results", "to", "the", "ADS", "." ]
def _do_single_fit(self, parameters: dict) -> tuple: """Does a single fit and returns the fit function, status and chi squared. Adds the results to the ADS.""" output_workspace, parameter_table, function, fit_status, chi_squared, covariance_matrix = \ self._do_single_fit_and_return_workspace_parameters_and_fit_function(parameters) self._add_single_fit_results_to_ADS_and_context(parameters["InputWorkspace"], parameter_table, output_workspace, covariance_matrix) return function, fit_status, chi_squared
[ "def", "_do_single_fit", "(", "self", ",", "parameters", ":", "dict", ")", "->", "tuple", ":", "output_workspace", ",", "parameter_table", ",", "function", ",", "fit_status", ",", "chi_squared", ",", "covariance_matrix", "=", "self", ".", "_do_single_fit_and_retur...
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/fitting_widgets/basic_fitting/basic_fitting_model.py#L673-L680
nasa/fprime
595cf3682d8365943d86c1a6fe7c78f0a116acf0
Autocoders/Python/src/fprime_ac/utils/EnumGenerator.py
python
open_file
(name, type)
return fp
Open the file for writing
Open the file for writing
[ "Open", "the", "file", "for", "writing" ]
def open_file(name, type): """ Open the file for writing """ filename = name + "EnumAc." + type fp = open(filename, "w") if fp is None: print("Could not open file %s" % filename) sys.exit(-1) return fp
[ "def", "open_file", "(", "name", ",", "type", ")", ":", "filename", "=", "name", "+", "\"EnumAc.\"", "+", "type", "fp", "=", "open", "(", "filename", ",", "\"w\"", ")", "if", "fp", "is", "None", ":", "print", "(", "\"Could not open file %s\"", "%", "fi...
https://github.com/nasa/fprime/blob/595cf3682d8365943d86c1a6fe7c78f0a116acf0/Autocoders/Python/src/fprime_ac/utils/EnumGenerator.py#L27-L37
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_gdi.py
python
DC.Blit
(*args, **kwargs)
return _gdi_.DC_Blit(*args, **kwargs)
Blit(self, int xdest, int ydest, int width, int height, DC source, int xsrc, int ysrc, int rop=COPY, bool useMask=False, int xsrcMask=-1, int ysrcMask=-1) -> bool Copy from a source DC to this DC. Parameters specify the destination coordinates, size of area to copy, source DC, source coordinates, logical function, whether to use a bitmap mask, and mask source position.
Blit(self, int xdest, int ydest, int width, int height, DC source, int xsrc, int ysrc, int rop=COPY, bool useMask=False, int xsrcMask=-1, int ysrcMask=-1) -> bool
[ "Blit", "(", "self", "int", "xdest", "int", "ydest", "int", "width", "int", "height", "DC", "source", "int", "xsrc", "int", "ysrc", "int", "rop", "=", "COPY", "bool", "useMask", "=", "False", "int", "xsrcMask", "=", "-", "1", "int", "ysrcMask", "=", ...
def Blit(*args, **kwargs): """ Blit(self, int xdest, int ydest, int width, int height, DC source, int xsrc, int ysrc, int rop=COPY, bool useMask=False, int xsrcMask=-1, int ysrcMask=-1) -> bool Copy from a source DC to this DC. Parameters specify the destination coordinates, size of area to copy, source DC, source coordinates, logical function, whether to use a bitmap mask, and mask source position. """ return _gdi_.DC_Blit(*args, **kwargs)
[ "def", "Blit", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gdi_", ".", "DC_Blit", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_gdi.py#L3771-L3782
i42output/neoGFX
529857e006466271f9775e1a77882c3919e1c3e1
3rdparty/harfbuzz/harfbuzz-3.2.0/src/gen-tag-table.py
python
BCP47Parser._get_name_piece
(self, subtag)
return self.names[subtag].split ('\n')[0] + self.scopes.get (subtag, '')
Return the first name of a subtag plus its scope suffix. Args: subtag (str): A BCP 47 subtag. Returns: The name form of ``subtag``.
Return the first name of a subtag plus its scope suffix.
[ "Return", "the", "first", "name", "of", "a", "subtag", "plus", "its", "scope", "suffix", "." ]
def _get_name_piece (self, subtag): """Return the first name of a subtag plus its scope suffix. Args: subtag (str): A BCP 47 subtag. Returns: The name form of ``subtag``. """ return self.names[subtag].split ('\n')[0] + self.scopes.get (subtag, '')
[ "def", "_get_name_piece", "(", "self", ",", "subtag", ")", ":", "return", "self", ".", "names", "[", "subtag", "]", ".", "split", "(", "'\\n'", ")", "[", "0", "]", "+", "self", ".", "scopes", ".", "get", "(", "subtag", ",", "''", ")" ]
https://github.com/i42output/neoGFX/blob/529857e006466271f9775e1a77882c3919e1c3e1/3rdparty/harfbuzz/harfbuzz-3.2.0/src/gen-tag-table.py#L629-L638
yuxng/DA-RNN
77fbb50b4272514588a10a9f90b7d5f8d46974fb
lib/datasets/shapenet_scene.py
python
shapenet_scene._get_default_path
(self)
return os.path.join(datasets.ROOT_DIR, 'data', 'ShapeNetScene')
Return the default path where KITTI is expected to be installed.
Return the default path where KITTI is expected to be installed.
[ "Return", "the", "default", "path", "where", "KITTI", "is", "expected", "to", "be", "installed", "." ]
def _get_default_path(self): """ Return the default path where KITTI is expected to be installed. """ return os.path.join(datasets.ROOT_DIR, 'data', 'ShapeNetScene')
[ "def", "_get_default_path", "(", "self", ")", ":", "return", "os", ".", "path", ".", "join", "(", "datasets", ".", "ROOT_DIR", ",", "'data'", ",", "'ShapeNetScene'", ")" ]
https://github.com/yuxng/DA-RNN/blob/77fbb50b4272514588a10a9f90b7d5f8d46974fb/lib/datasets/shapenet_scene.py#L111-L115
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/ops/image_ops_impl.py
python
_ssim_helper
(x, y, reducer, max_val, compensation=1.0, k1=0.01, k2=0.03)
return luminance, cs
r"""Helper function for computing SSIM. SSIM estimates covariances with weighted sums. The default parameters use a biased estimate of the covariance: Suppose `reducer` is a weighted sum, then the mean estimators are \mu_x = \sum_i w_i x_i, \mu_y = \sum_i w_i y_i, where w_i's are the weighted-sum weights, and covariance estimator is cov_{xy} = \sum_i w_i (x_i - \mu_x) (y_i - \mu_y) with assumption \sum_i w_i = 1. This covariance estimator is biased, since E[cov_{xy}] = (1 - \sum_i w_i ^ 2) Cov(X, Y). For SSIM measure with unbiased covariance estimators, pass as `compensation` argument (1 - \sum_i w_i ^ 2). Args: x: First set of images. y: Second set of images. reducer: Function that computes 'local' averages from the set of images. For non-convolutional version, this is usually tf.reduce_mean(x, [1, 2]), and for convolutional version, this is usually tf.nn.avg_pool2d or tf.nn.conv2d with weighted-sum kernel. max_val: The dynamic range (i.e., the difference between the maximum possible allowed value and the minimum allowed value). compensation: Compensation factor. See above. k1: Default value 0.01 k2: Default value 0.03 (SSIM is less sensitivity to K2 for lower values, so it would be better if we took the values in the range of 0 < K2 < 0.4). Returns: A pair containing the luminance measure, and the contrast-structure measure.
r"""Helper function for computing SSIM.
[ "r", "Helper", "function", "for", "computing", "SSIM", "." ]
def _ssim_helper(x, y, reducer, max_val, compensation=1.0, k1=0.01, k2=0.03): r"""Helper function for computing SSIM. SSIM estimates covariances with weighted sums. The default parameters use a biased estimate of the covariance: Suppose `reducer` is a weighted sum, then the mean estimators are \mu_x = \sum_i w_i x_i, \mu_y = \sum_i w_i y_i, where w_i's are the weighted-sum weights, and covariance estimator is cov_{xy} = \sum_i w_i (x_i - \mu_x) (y_i - \mu_y) with assumption \sum_i w_i = 1. This covariance estimator is biased, since E[cov_{xy}] = (1 - \sum_i w_i ^ 2) Cov(X, Y). For SSIM measure with unbiased covariance estimators, pass as `compensation` argument (1 - \sum_i w_i ^ 2). Args: x: First set of images. y: Second set of images. reducer: Function that computes 'local' averages from the set of images. For non-convolutional version, this is usually tf.reduce_mean(x, [1, 2]), and for convolutional version, this is usually tf.nn.avg_pool2d or tf.nn.conv2d with weighted-sum kernel. max_val: The dynamic range (i.e., the difference between the maximum possible allowed value and the minimum allowed value). compensation: Compensation factor. See above. k1: Default value 0.01 k2: Default value 0.03 (SSIM is less sensitivity to K2 for lower values, so it would be better if we took the values in the range of 0 < K2 < 0.4). Returns: A pair containing the luminance measure, and the contrast-structure measure. """ c1 = (k1 * max_val)**2 c2 = (k2 * max_val)**2 # SSIM luminance measure is # (2 * mu_x * mu_y + c1) / (mu_x ** 2 + mu_y ** 2 + c1). mean0 = reducer(x) mean1 = reducer(y) num0 = mean0 * mean1 * 2.0 den0 = math_ops.square(mean0) + math_ops.square(mean1) luminance = (num0 + c1) / (den0 + c1) # SSIM contrast-structure measure is # (2 * cov_{xy} + c2) / (cov_{xx} + cov_{yy} + c2). # Note that `reducer` is a weighted sum with weight w_k, \sum_i w_i = 1, then # cov_{xy} = \sum_i w_i (x_i - \mu_x) (y_i - \mu_y) # = \sum_i w_i x_i y_i - (\sum_i w_i x_i) (\sum_j w_j y_j). num1 = reducer(x * y) * 2.0 den1 = reducer(math_ops.square(x) + math_ops.square(y)) c2 *= compensation cs = (num1 - num0 + c2) / (den1 - den0 + c2) # SSIM score is the product of the luminance and contrast-structure measures. return luminance, cs
[ "def", "_ssim_helper", "(", "x", ",", "y", ",", "reducer", ",", "max_val", ",", "compensation", "=", "1.0", ",", "k1", "=", "0.01", ",", "k2", "=", "0.03", ")", ":", "c1", "=", "(", "k1", "*", "max_val", ")", "**", "2", "c2", "=", "(", "k2", ...
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/image_ops_impl.py#L4102-L4157
tzutalin/dlib-android
989627cb7fe81cd1d41d73434b0e91ce1dd2683f
tools/lint/cpplint.py
python
CloseExpression
(clean_lines, linenum, pos)
return (line, clean_lines.NumLines(), -1)
If input points to ( or { or [ or <, finds the position that closes it. If lines[linenum][pos] points to a '(' or '{' or '[' or '<', finds the linenum/pos that correspond to the closing of the expression. TODO(unknown): cpplint spends a fair bit of time matching parentheses. Ideally we would want to index all opening and closing parentheses once and have CloseExpression be just a simple lookup, but due to preprocessor tricks, this is not so easy. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. pos: A position on the line. Returns: A tuple (line, linenum, pos) pointer *past* the closing brace, or (line, len(lines), -1) if we never find a close. Note we ignore strings and comments when matching; and the line we return is the 'cleansed' line at linenum.
If input points to ( or { or [ or <, finds the position that closes it. If lines[linenum][pos] points to a '(' or '{' or '[' or '<', finds the linenum/pos that correspond to the closing of the expression. TODO(unknown): cpplint spends a fair bit of time matching parentheses. Ideally we would want to index all opening and closing parentheses once and have CloseExpression be just a simple lookup, but due to preprocessor tricks, this is not so easy. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. pos: A position on the line. Returns: A tuple (line, linenum, pos) pointer *past* the closing brace, or (line, len(lines), -1) if we never find a close. Note we ignore strings and comments when matching; and the line we return is the 'cleansed' line at linenum.
[ "If", "input", "points", "to", "(", "or", "{", "or", "[", "or", "<", "finds", "the", "position", "that", "closes", "it", ".", "If", "lines", "[", "linenum", "]", "[", "pos", "]", "points", "to", "a", "(", "or", "{", "or", "[", "or", "<", "finds...
def CloseExpression(clean_lines, linenum, pos): """If input points to ( or { or [ or <, finds the position that closes it. If lines[linenum][pos] points to a '(' or '{' or '[' or '<', finds the linenum/pos that correspond to the closing of the expression. TODO(unknown): cpplint spends a fair bit of time matching parentheses. Ideally we would want to index all opening and closing parentheses once and have CloseExpression be just a simple lookup, but due to preprocessor tricks, this is not so easy. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. pos: A position on the line. Returns: A tuple (line, linenum, pos) pointer *past* the closing brace, or (line, len(lines), -1) if we never find a close. Note we ignore strings and comments when matching; and the line we return is the 'cleansed' line at linenum. """ line = clean_lines.elided[linenum] if (line[pos] not in '({[<') or Match(r'<[<=]', line[pos:]): return (line, clean_lines.NumLines(), -1) # Check first line (end_pos, stack) = FindEndOfExpressionInLine(line, pos, []) if end_pos > -1: return (line, linenum, end_pos) # Continue scanning forward while stack and linenum < clean_lines.NumLines() - 1: linenum += 1 line = clean_lines.elided[linenum] (end_pos, stack) = FindEndOfExpressionInLine(line, 0, stack) if end_pos > -1: return (line, linenum, end_pos) # Did not find end of expression before end of file, give up return (line, clean_lines.NumLines(), -1)
[ "def", "CloseExpression", "(", "clean_lines", ",", "linenum", ",", "pos", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "if", "(", "line", "[", "pos", "]", "not", "in", "'({[<'", ")", "or", "Match", "(", "r'<[<=]'", ",", "...
https://github.com/tzutalin/dlib-android/blob/989627cb7fe81cd1d41d73434b0e91ce1dd2683f/tools/lint/cpplint.py#L1484-L1521
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/robotparser.py
python
RobotFileParser.parse
(self, lines)
parse the input lines from a robots.txt file. We allow that a user-agent: line is not preceded by one or more blank lines.
parse the input lines from a robots.txt file. We allow that a user-agent: line is not preceded by one or more blank lines.
[ "parse", "the", "input", "lines", "from", "a", "robots", ".", "txt", "file", ".", "We", "allow", "that", "a", "user", "-", "agent", ":", "line", "is", "not", "preceded", "by", "one", "or", "more", "blank", "lines", "." ]
def parse(self, lines): """parse the input lines from a robots.txt file. We allow that a user-agent: line is not preceded by one or more blank lines.""" # states: # 0: start state # 1: saw user-agent line # 2: saw an allow or disallow line state = 0 linenumber = 0 entry = Entry() for line in lines: linenumber += 1 if not line: if state == 1: entry = Entry() state = 0 elif state == 2: self._add_entry(entry) entry = Entry() state = 0 # remove optional comment and strip line i = line.find('#') if i >= 0: line = line[:i] line = line.strip() if not line: continue line = line.split(':', 1) if len(line) == 2: line[0] = line[0].strip().lower() line[1] = urllib.unquote(line[1].strip()) if line[0] == "user-agent": if state == 2: self._add_entry(entry) entry = Entry() entry.useragents.append(line[1]) state = 1 elif line[0] == "disallow": if state != 0: entry.rulelines.append(RuleLine(line[1], False)) state = 2 elif line[0] == "allow": if state != 0: entry.rulelines.append(RuleLine(line[1], True)) state = 2 if state == 2: self._add_entry(entry)
[ "def", "parse", "(", "self", ",", "lines", ")", ":", "# states:", "# 0: start state", "# 1: saw user-agent line", "# 2: saw an allow or disallow line", "state", "=", "0", "linenumber", "=", "0", "entry", "=", "Entry", "(", ")", "for", "line", "in", "lines", ...
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/robotparser.py#L77-L125
oracle/graaljs
36a56e8e993d45fc40939a3a4d9c0c24990720f1
graal-nodejs/tools/inspector_protocol/jinja2/compiler.py
python
Frame.inner
(self, isolated=False)
return Frame(self.eval_ctx, self)
Return an inner frame.
Return an inner frame.
[ "Return", "an", "inner", "frame", "." ]
def inner(self, isolated=False): """Return an inner frame.""" if isolated: return Frame(self.eval_ctx, level=self.symbols.level + 1) return Frame(self.eval_ctx, self)
[ "def", "inner", "(", "self", ",", "isolated", "=", "False", ")", ":", "if", "isolated", ":", "return", "Frame", "(", "self", ".", "eval_ctx", ",", "level", "=", "self", ".", "symbols", ".", "level", "+", "1", ")", "return", "Frame", "(", "self", "....
https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/tools/inspector_protocol/jinja2/compiler.py#L172-L176
OAID/Caffe-HRT
aae71e498ab842c6f92bcc23fc668423615a4d65
scripts/cpp_lint.py
python
CheckSpacing
(filename, clean_lines, linenum, nesting_state, error)
Checks for the correctness of various spacing issues in the code. Things we check for: spaces around operators, spaces after if/for/while/switch, no spaces around parens in function calls, two spaces between code and comment, don't start a block with a blank line, don't end a function with a blank line, don't add a blank line after public/protected/private, don't have too many blank lines in a row. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. nesting_state: A _NestingState instance which maintains information about the current stack of nested blocks being parsed. error: The function to call with any errors found.
Checks for the correctness of various spacing issues in the code.
[ "Checks", "for", "the", "correctness", "of", "various", "spacing", "issues", "in", "the", "code", "." ]
def CheckSpacing(filename, clean_lines, linenum, nesting_state, error): """Checks for the correctness of various spacing issues in the code. Things we check for: spaces around operators, spaces after if/for/while/switch, no spaces around parens in function calls, two spaces between code and comment, don't start a block with a blank line, don't end a function with a blank line, don't add a blank line after public/protected/private, don't have too many blank lines in a row. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. nesting_state: A _NestingState instance which maintains information about the current stack of nested blocks being parsed. error: The function to call with any errors found. """ # Don't use "elided" lines here, otherwise we can't check commented lines. # Don't want to use "raw" either, because we don't want to check inside C++11 # raw strings, raw = clean_lines.lines_without_raw_strings line = raw[linenum] # Before nixing comments, check if the line is blank for no good # reason. This includes the first line after a block is opened, and # blank lines at the end of a function (ie, right before a line like '}' # # Skip all the blank line checks if we are immediately inside a # namespace body. In other words, don't issue blank line warnings # for this block: # namespace { # # } # # A warning about missing end of namespace comments will be issued instead. if IsBlankLine(line) and not nesting_state.InNamespaceBody(): elided = clean_lines.elided prev_line = elided[linenum - 1] prevbrace = prev_line.rfind('{') # TODO(unknown): Don't complain if line before blank line, and line after, # both start with alnums and are indented the same amount. # This ignores whitespace at the start of a namespace block # because those are not usually indented. if prevbrace != -1 and prev_line[prevbrace:].find('}') == -1: # OK, we have a blank line at the start of a code block. Before we # complain, we check if it is an exception to the rule: The previous # non-empty line has the parameters of a function header that are indented # 4 spaces (because they did not fit in a 80 column line when placed on # the same line as the function name). We also check for the case where # the previous line is indented 6 spaces, which may happen when the # initializers of a constructor do not fit into a 80 column line. exception = False if Match(r' {6}\w', prev_line): # Initializer list? # We are looking for the opening column of initializer list, which # should be indented 4 spaces to cause 6 space indentation afterwards. search_position = linenum-2 while (search_position >= 0 and Match(r' {6}\w', elided[search_position])): search_position -= 1 exception = (search_position >= 0 and elided[search_position][:5] == ' :') else: # Search for the function arguments or an initializer list. We use a # simple heuristic here: If the line is indented 4 spaces; and we have a # closing paren, without the opening paren, followed by an opening brace # or colon (for initializer lists) we assume that it is the last line of # a function header. If we have a colon indented 4 spaces, it is an # initializer list. exception = (Match(r' {4}\w[^\(]*\)\s*(const\s*)?(\{\s*$|:)', prev_line) or Match(r' {4}:', prev_line)) if not exception: error(filename, linenum, 'whitespace/blank_line', 2, 'Redundant blank line at the start of a code block ' 'should be deleted.') # Ignore blank lines at the end of a block in a long if-else # chain, like this: # if (condition1) { # // Something followed by a blank line # # } else if (condition2) { # // Something else # } if linenum + 1 < clean_lines.NumLines(): next_line = raw[linenum + 1] if (next_line and Match(r'\s*}', next_line) and next_line.find('} else ') == -1): error(filename, linenum, 'whitespace/blank_line', 3, 'Redundant blank line at the end of a code block ' 'should be deleted.') matched = Match(r'\s*(public|protected|private):', prev_line) if matched: error(filename, linenum, 'whitespace/blank_line', 3, 'Do not leave a blank line after "%s:"' % matched.group(1)) # Next, we complain if there's a comment too near the text commentpos = line.find('//') if commentpos != -1: # Check if the // may be in quotes. If so, ignore it # Comparisons made explicit for clarity -- pylint: disable=g-explicit-bool-comparison if (line.count('"', 0, commentpos) - line.count('\\"', 0, commentpos)) % 2 == 0: # not in quotes # Allow one space for new scopes, two spaces otherwise: if (not Match(r'^\s*{ //', line) and ((commentpos >= 1 and line[commentpos-1] not in string.whitespace) or (commentpos >= 2 and line[commentpos-2] not in string.whitespace))): error(filename, linenum, 'whitespace/comments', 2, 'At least two spaces is best between code and comments') # There should always be a space between the // and the comment commentend = commentpos + 2 if commentend < len(line) and not line[commentend] == ' ': # but some lines are exceptions -- e.g. if they're big # comment delimiters like: # //---------------------------------------------------------- # or are an empty C++ style Doxygen comment, like: # /// # or C++ style Doxygen comments placed after the variable: # ///< Header comment # //!< Header comment # or they begin with multiple slashes followed by a space: # //////// Header comment match = (Search(r'[=/-]{4,}\s*$', line[commentend:]) or Search(r'^/$', line[commentend:]) or Search(r'^!< ', line[commentend:]) or Search(r'^/< ', line[commentend:]) or Search(r'^/+ ', line[commentend:])) if not match: error(filename, linenum, 'whitespace/comments', 4, 'Should have a space between // and comment') CheckComment(line[commentpos:], filename, linenum, error) line = clean_lines.elided[linenum] # get rid of comments and strings # Don't try to do spacing checks for operator methods line = re.sub(r'operator(==|!=|<|<<|<=|>=|>>|>)\(', 'operator\(', line) # We allow no-spaces around = within an if: "if ( (a=Foo()) == 0 )". # Otherwise not. Note we only check for non-spaces on *both* sides; # sometimes people put non-spaces on one side when aligning ='s among # many lines (not that this is behavior that I approve of...) if Search(r'[\w.]=[\w.]', line) and not Search(r'\b(if|while) ', line): error(filename, linenum, 'whitespace/operators', 4, 'Missing spaces around =') # It's ok not to have spaces around binary operators like + - * /, but if # there's too little whitespace, we get concerned. It's hard to tell, # though, so we punt on this one for now. TODO. # You should always have whitespace around binary operators. # # Check <= and >= first to avoid false positives with < and >, then # check non-include lines for spacing around < and >. match = Search(r'[^<>=!\s](==|!=|<=|>=)[^<>=!\s]', line) if match: error(filename, linenum, 'whitespace/operators', 3, 'Missing spaces around %s' % match.group(1)) # We allow no-spaces around << when used like this: 10<<20, but # not otherwise (particularly, not when used as streams) # Also ignore using ns::operator<<; match = Search(r'(operator|\S)(?:L|UL|ULL|l|ul|ull)?<<(\S)', line) if (match and not (match.group(1).isdigit() and match.group(2).isdigit()) and not (match.group(1) == 'operator' and match.group(2) == ';')): error(filename, linenum, 'whitespace/operators', 3, 'Missing spaces around <<') elif not Match(r'#.*include', line): # Avoid false positives on -> reduced_line = line.replace('->', '') # Look for < that is not surrounded by spaces. This is only # triggered if both sides are missing spaces, even though # technically should should flag if at least one side is missing a # space. This is done to avoid some false positives with shifts. match = Search(r'[^\s<]<([^\s=<].*)', reduced_line) if (match and not FindNextMatchingAngleBracket(clean_lines, linenum, match.group(1))): error(filename, linenum, 'whitespace/operators', 3, 'Missing spaces around <') # Look for > that is not surrounded by spaces. Similar to the # above, we only trigger if both sides are missing spaces to avoid # false positives with shifts. match = Search(r'^(.*[^\s>])>[^\s=>]', reduced_line) if (match and not FindPreviousMatchingAngleBracket(clean_lines, linenum, match.group(1))): error(filename, linenum, 'whitespace/operators', 3, 'Missing spaces around >') # We allow no-spaces around >> for almost anything. This is because # C++11 allows ">>" to close nested templates, which accounts for # most cases when ">>" is not followed by a space. # # We still warn on ">>" followed by alpha character, because that is # likely due to ">>" being used for right shifts, e.g.: # value >> alpha # # When ">>" is used to close templates, the alphanumeric letter that # follows would be part of an identifier, and there should still be # a space separating the template type and the identifier. # type<type<type>> alpha match = Search(r'>>[a-zA-Z_]', line) if match: error(filename, linenum, 'whitespace/operators', 3, 'Missing spaces around >>') # There shouldn't be space around unary operators match = Search(r'(!\s|~\s|[\s]--[\s;]|[\s]\+\+[\s;])', line) if match: error(filename, linenum, 'whitespace/operators', 4, 'Extra space for operator %s' % match.group(1)) # A pet peeve of mine: no spaces after an if, while, switch, or for match = Search(r' (if\(|for\(|while\(|switch\()', line) if match: error(filename, linenum, 'whitespace/parens', 5, 'Missing space before ( in %s' % match.group(1)) # For if/for/while/switch, the left and right parens should be # consistent about how many spaces are inside the parens, and # there should either be zero or one spaces inside the parens. # We don't want: "if ( foo)" or "if ( foo )". # Exception: "for ( ; foo; bar)" and "for (foo; bar; )" are allowed. match = Search(r'\b(if|for|while|switch)\s*' r'\(([ ]*)(.).*[^ ]+([ ]*)\)\s*{\s*$', line) if match: if len(match.group(2)) != len(match.group(4)): if not (match.group(3) == ';' and len(match.group(2)) == 1 + len(match.group(4)) or not match.group(2) and Search(r'\bfor\s*\(.*; \)', line)): error(filename, linenum, 'whitespace/parens', 5, 'Mismatching spaces inside () in %s' % match.group(1)) if len(match.group(2)) not in [0, 1]: error(filename, linenum, 'whitespace/parens', 5, 'Should have zero or one spaces inside ( and ) in %s' % match.group(1)) # You should always have a space after a comma (either as fn arg or operator) # # This does not apply when the non-space character following the # comma is another comma, since the only time when that happens is # for empty macro arguments. # # We run this check in two passes: first pass on elided lines to # verify that lines contain missing whitespaces, second pass on raw # lines to confirm that those missing whitespaces are not due to # elided comments. if Search(r',[^,\s]', line) and Search(r',[^,\s]', raw[linenum]): error(filename, linenum, 'whitespace/comma', 3, 'Missing space after ,') # You should always have a space after a semicolon # except for few corner cases # TODO(unknown): clarify if 'if (1) { return 1;}' is requires one more # space after ; if Search(r';[^\s};\\)/]', line): error(filename, linenum, 'whitespace/semicolon', 3, 'Missing space after ;') # Next we will look for issues with function calls. CheckSpacingForFunctionCall(filename, line, linenum, error) # Except after an opening paren, or after another opening brace (in case of # an initializer list, for instance), you should have spaces before your # braces. And since you should never have braces at the beginning of a line, # this is an easy test. match = Match(r'^(.*[^ ({]){', line) if match: # Try a bit harder to check for brace initialization. This # happens in one of the following forms: # Constructor() : initializer_list_{} { ... } # Constructor{}.MemberFunction() # Type variable{}; # FunctionCall(type{}, ...); # LastArgument(..., type{}); # LOG(INFO) << type{} << " ..."; # map_of_type[{...}] = ...; # # We check for the character following the closing brace, and # silence the warning if it's one of those listed above, i.e. # "{.;,)<]". # # To account for nested initializer list, we allow any number of # closing braces up to "{;,)<". We can't simply silence the # warning on first sight of closing brace, because that would # cause false negatives for things that are not initializer lists. # Silence this: But not this: # Outer{ if (...) { # Inner{...} if (...){ // Missing space before { # }; } # # There is a false negative with this approach if people inserted # spurious semicolons, e.g. "if (cond){};", but we will catch the # spurious semicolon with a separate check. (endline, endlinenum, endpos) = CloseExpression( clean_lines, linenum, len(match.group(1))) trailing_text = '' if endpos > -1: trailing_text = endline[endpos:] for offset in xrange(endlinenum + 1, min(endlinenum + 3, clean_lines.NumLines() - 1)): trailing_text += clean_lines.elided[offset] if not Match(r'^[\s}]*[{.;,)<\]]', trailing_text): error(filename, linenum, 'whitespace/braces', 5, 'Missing space before {') # Make sure '} else {' has spaces. if Search(r'}else', line): error(filename, linenum, 'whitespace/braces', 5, 'Missing space before else') # You shouldn't have spaces before your brackets, except maybe after # 'delete []' or 'new char * []'. if Search(r'\w\s+\[', line) and not Search(r'delete\s+\[', line): error(filename, linenum, 'whitespace/braces', 5, 'Extra space before [') # You shouldn't have a space before a semicolon at the end of the line. # There's a special case for "for" since the style guide allows space before # the semicolon there. if Search(r':\s*;\s*$', line): error(filename, linenum, 'whitespace/semicolon', 5, 'Semicolon defining empty statement. Use {} instead.') elif Search(r'^\s*;\s*$', line): error(filename, linenum, 'whitespace/semicolon', 5, 'Line contains only semicolon. If this should be an empty statement, ' 'use {} instead.') elif (Search(r'\s+;\s*$', line) and not Search(r'\bfor\b', line)): error(filename, linenum, 'whitespace/semicolon', 5, 'Extra space before last semicolon. If this should be an empty ' 'statement, use {} instead.') # In range-based for, we wanted spaces before and after the colon, but # not around "::" tokens that might appear. if (Search('for *\(.*[^:]:[^: ]', line) or Search('for *\(.*[^: ]:[^:]', line)): error(filename, linenum, 'whitespace/forcolon', 2, 'Missing space around colon in range-based for loop')
[ "def", "CheckSpacing", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "nesting_state", ",", "error", ")", ":", "# Don't use \"elided\" lines here, otherwise we can't check commented lines.", "# Don't want to use \"raw\" either, because we don't want to check inside C++11", ...
https://github.com/OAID/Caffe-HRT/blob/aae71e498ab842c6f92bcc23fc668423615a4d65/scripts/cpp_lint.py#L2643-L2988
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/lite/experiment/HPC-generator/generator.py
python
print_line
(line)
return "\"".join(result)
Convert line to a python string :param line: :return:
Convert line to a python string :param line: :return:
[ "Convert", "line", "to", "a", "python", "string", ":", "param", "line", ":", ":", "return", ":" ]
def print_line(line): """ Convert line to a python string :param line: :return: """ global python_indent global generate_code_indent if line.strip()[0] == "}" or line.strip()[0] == ")": python_indent = -1 split_str = line.split("@") if line.strip()[0] != "@" and len(split_str) == 1: if get_indent(line) == python_indent or python_indent == -1: result = ["print(", line, ", file=OUT_STREAM)"] python_indent = -1 if "{" in line or "asm volatile(" in line: generate_code_indent = get_indent(line) if line.strip().startswith("}") and "{" not in line: generate_code_indent -= 4 if len(line) == 1 and line[0] == "}": # modify next fun generate_code_indent generate_code_indent = -4 return "\"".join(result) if line.strip()[0] == '@': # get python indent and first generate_code_indent if python_indent == -1: generate_code_indent = get_indent(line) - 4 python_indent = get_indent(line) result = split_str[0][python_indent:] + split_str[1] return result index = get_indent(split_str[0]) result = [split_str[0][python_indent:index] + "print("] Prefix = " " * (generate_code_indent + 4) + split_str[0].lstrip() Suffix = " %(" for str_tmp in split_str[1:]: second = str_tmp.find("}") Suffix += str_tmp[1:second] + ', ' str_tmp = str_tmp.replace(str_tmp[0:second + 1], "%d") Prefix += str_tmp result.append(Prefix) result.append(Suffix + "), file=OUT_STREAM)") return "\"".join(result)
[ "def", "print_line", "(", "line", ")", ":", "global", "python_indent", "global", "generate_code_indent", "if", "line", ".", "strip", "(", ")", "[", "0", "]", "==", "\"}\"", "or", "line", ".", "strip", "(", ")", "[", "0", "]", "==", "\")\"", ":", "pyt...
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/lite/experiment/HPC-generator/generator.py#L57-L101
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/plugdlg.py
python
PluginDialog.OnDestroy
(self, evt)
Cleanup message handlers on delete
Cleanup message handlers on delete
[ "Cleanup", "message", "handlers", "on", "delete" ]
def OnDestroy(self, evt): """Cleanup message handlers on delete""" if evt.GetId() == self.GetId(): ed_msg.Unsubscribe(self.OnThemeChange) evt.Skip()
[ "def", "OnDestroy", "(", "self", ",", "evt", ")", ":", "if", "evt", ".", "GetId", "(", ")", "==", "self", ".", "GetId", "(", ")", ":", "ed_msg", ".", "Unsubscribe", "(", "self", ".", "OnThemeChange", ")", "evt", ".", "Skip", "(", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/plugdlg.py#L147-L151
Kitware/ParaView
f760af9124ff4634b23ebbeab95a4f56e0261955
Wrapping/Python/paraview/simple.py
python
GetScalarBar
(ctf, view=None)
return sb
Returns the scalar bar for color transfer function in the given view. If view is None, the active view will be used, if possible. This will either return an existing scalar bar or create a new one.
Returns the scalar bar for color transfer function in the given view. If view is None, the active view will be used, if possible. This will either return an existing scalar bar or create a new one.
[ "Returns", "the", "scalar", "bar", "for", "color", "transfer", "function", "in", "the", "given", "view", ".", "If", "view", "is", "None", "the", "active", "view", "will", "be", "used", "if", "possible", ".", "This", "will", "either", "return", "an", "exi...
def GetScalarBar(ctf, view=None): """Returns the scalar bar for color transfer function in the given view. If view is None, the active view will be used, if possible. This will either return an existing scalar bar or create a new one.""" view = view if view else active_objects.view if not view: raise ValueError ("'view' argument cannot be None when no active view is present") tfmgr = servermanager.vtkSMTransferFunctionManager() sb = servermanager._getPyProxy(\ tfmgr.GetScalarBarRepresentation(ctf.SMProxy, view.SMProxy)) return sb
[ "def", "GetScalarBar", "(", "ctf", ",", "view", "=", "None", ")", ":", "view", "=", "view", "if", "view", "else", "active_objects", ".", "view", "if", "not", "view", ":", "raise", "ValueError", "(", "\"'view' argument cannot be None when no active view is present\...
https://github.com/Kitware/ParaView/blob/f760af9124ff4634b23ebbeab95a4f56e0261955/Wrapping/Python/paraview/simple.py#L1805-L1815
sofa-framework/sofa
70628e35a44fcc258cf8250109b5e4eba8c5abe9
applications/plugins/PSL/python/pslloader.py
python
SetPath
(newpath)
This context manager is setting & restoring the current path. This is very practical to insure that all the processing is done where the file is located.
This context manager is setting & restoring the current path. This is very practical to insure that all the processing is done where the file is located.
[ "This", "context", "manager", "is", "setting", "&", "restoring", "the", "current", "path", ".", "This", "is", "very", "practical", "to", "insure", "that", "all", "the", "processing", "is", "done", "where", "the", "file", "is", "located", "." ]
def SetPath(newpath): '''This context manager is setting & restoring the current path. This is very practical to insure that all the processing is done where the file is located. ''' curdir= os.getcwd() os.chdir(newpath) try: yield finally: os.chdir(curdir)
[ "def", "SetPath", "(", "newpath", ")", ":", "curdir", "=", "os", ".", "getcwd", "(", ")", "os", ".", "chdir", "(", "newpath", ")", "try", ":", "yield", "finally", ":", "os", ".", "chdir", "(", "curdir", ")" ]
https://github.com/sofa-framework/sofa/blob/70628e35a44fcc258cf8250109b5e4eba8c5abe9/applications/plugins/PSL/python/pslloader.py#L43-L51
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/ribbon/toolbar.py
python
RibbonToolBar.GetToolByPos
(self, pos)
return None
Returns a pointer to the tool opaque structure by `pos` or ``None`` if no corresponding tool is found. :param `pos`: zero-based position of the tool to retrieve. :returns: An instance of :class:`RibbonToolBarToolBase` if the tool was found, ``None`` if it was not found. .. versionadded:: 0.9.5
Returns a pointer to the tool opaque structure by `pos` or ``None`` if no corresponding tool is found.
[ "Returns", "a", "pointer", "to", "the", "tool", "opaque", "structure", "by", "pos", "or", "None", "if", "no", "corresponding", "tool", "is", "found", "." ]
def GetToolByPos(self, pos): """ Returns a pointer to the tool opaque structure by `pos` or ``None`` if no corresponding tool is found. :param `pos`: zero-based position of the tool to retrieve. :returns: An instance of :class:`RibbonToolBarToolBase` if the tool was found, ``None`` if it was not found. .. versionadded:: 0.9.5 """ for group in self._groups: tool_count = len(group.tools) if pos < tool_count: return group.tools[pos] elif pos >= tool_count: return None return None
[ "def", "GetToolByPos", "(", "self", ",", "pos", ")", ":", "for", "group", "in", "self", ".", "_groups", ":", "tool_count", "=", "len", "(", "group", ".", "tools", ")", "if", "pos", "<", "tool_count", ":", "return", "group", ".", "tools", "[", "pos", ...
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/ribbon/toolbar.py#L574-L596
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Arch/ArchMaterial.py
python
makeMaterial
(name="Material",color=None,transparency=None)
return obj
makeMaterial(name): makes an Material object
makeMaterial(name): makes an Material object
[ "makeMaterial", "(", "name", ")", ":", "makes", "an", "Material", "object" ]
def makeMaterial(name="Material",color=None,transparency=None): '''makeMaterial(name): makes an Material object''' if not FreeCAD.ActiveDocument: FreeCAD.Console.PrintError("No active document. Aborting\n") return obj = FreeCAD.ActiveDocument.addObject("App::MaterialObjectPython","Material") obj.Label = name _ArchMaterial(obj) if FreeCAD.GuiUp: _ViewProviderArchMaterial(obj.ViewObject) getMaterialContainer().addObject(obj) if color: obj.Color = color[:3] if len(color) > 3: obj.Transparency = color[3]*100 if transparency: obj.Transparency = transparency return obj
[ "def", "makeMaterial", "(", "name", "=", "\"Material\"", ",", "color", "=", "None", ",", "transparency", "=", "None", ")", ":", "if", "not", "FreeCAD", ".", "ActiveDocument", ":", "FreeCAD", ".", "Console", ".", "PrintError", "(", "\"No active document. Aborti...
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Arch/ArchMaterial.py#L48-L66
bumptop/BumpTop
466d23597a07ae738f4265262fa01087fc6e257c
trunk/win/Source/bin/jinja2/filters.py
python
do_indent
(s, width=4, indentfirst=False)
return rv
Return a copy of the passed string, each line indented by 4 spaces. The first line is not indented. If you want to change the number of spaces or indent the first line too you can pass additional parameters to the filter: .. sourcecode:: jinja {{ mytext|indent(2, true) }} indent by two spaces and indent the first line too.
Return a copy of the passed string, each line indented by 4 spaces. The first line is not indented. If you want to change the number of spaces or indent the first line too you can pass additional parameters to the filter:
[ "Return", "a", "copy", "of", "the", "passed", "string", "each", "line", "indented", "by", "4", "spaces", ".", "The", "first", "line", "is", "not", "indented", ".", "If", "you", "want", "to", "change", "the", "number", "of", "spaces", "or", "indent", "t...
def do_indent(s, width=4, indentfirst=False): """Return a copy of the passed string, each line indented by 4 spaces. The first line is not indented. If you want to change the number of spaces or indent the first line too you can pass additional parameters to the filter: .. sourcecode:: jinja {{ mytext|indent(2, true) }} indent by two spaces and indent the first line too. """ indention = u' ' * width rv = (u'\n' + indention).join(s.splitlines()) if indentfirst: rv = indention + rv return rv
[ "def", "do_indent", "(", "s", ",", "width", "=", "4", ",", "indentfirst", "=", "False", ")", ":", "indention", "=", "u' '", "*", "width", "rv", "=", "(", "u'\\n'", "+", "indention", ")", ".", "join", "(", "s", ".", "splitlines", "(", ")", ")", "i...
https://github.com/bumptop/BumpTop/blob/466d23597a07ae738f4265262fa01087fc6e257c/trunk/win/Source/bin/jinja2/filters.py#L331-L346
apple/swift-lldb
d74be846ef3e62de946df343e8c234bde93a8912
scripts/Python/static-binding/lldb.py
python
SBModuleSpec.SetObjectName
(self, name)
return _lldb.SBModuleSpec_SetObjectName(self, name)
SetObjectName(SBModuleSpec self, char const * name)
SetObjectName(SBModuleSpec self, char const * name)
[ "SetObjectName", "(", "SBModuleSpec", "self", "char", "const", "*", "name", ")" ]
def SetObjectName(self, name): """SetObjectName(SBModuleSpec self, char const * name)""" return _lldb.SBModuleSpec_SetObjectName(self, name)
[ "def", "SetObjectName", "(", "self", ",", "name", ")", ":", "return", "_lldb", ".", "SBModuleSpec_SetObjectName", "(", "self", ",", "name", ")" ]
https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L7810-L7812
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/pkg_resources/__init__.py
python
safe_version
(version)
Convert an arbitrary string to a standard version string
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 """ try: # normalize the version return str(packaging.version.Version(version)) except packaging.version.InvalidVersion: version = version.replace(' ', '.') return re.sub('[^A-Za-z0-9.]+', '-', version)
[ "def", "safe_version", "(", "version", ")", ":", "try", ":", "# normalize the version", "return", "str", "(", "packaging", ".", "version", ".", "Version", "(", "version", ")", ")", "except", "packaging", ".", "version", ".", "InvalidVersion", ":", "version", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/pkg_resources/__init__.py#L1325-L1334
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/richtext.py
python
RichTextObject.AdjustAvailableSpace
(*args, **kwargs)
return _richtext.RichTextObject_AdjustAvailableSpace(*args, **kwargs)
AdjustAvailableSpace(DC dc, RichTextBuffer buffer, RichTextAttr parentAttr, RichTextAttr childAttr, Rect availableParentSpace, Rect availableContainerSpace) -> Rect
AdjustAvailableSpace(DC dc, RichTextBuffer buffer, RichTextAttr parentAttr, RichTextAttr childAttr, Rect availableParentSpace, Rect availableContainerSpace) -> Rect
[ "AdjustAvailableSpace", "(", "DC", "dc", "RichTextBuffer", "buffer", "RichTextAttr", "parentAttr", "RichTextAttr", "childAttr", "Rect", "availableParentSpace", "Rect", "availableContainerSpace", ")", "-", ">", "Rect" ]
def AdjustAvailableSpace(*args, **kwargs): """ AdjustAvailableSpace(DC dc, RichTextBuffer buffer, RichTextAttr parentAttr, RichTextAttr childAttr, Rect availableParentSpace, Rect availableContainerSpace) -> Rect """ return _richtext.RichTextObject_AdjustAvailableSpace(*args, **kwargs)
[ "def", "AdjustAvailableSpace", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_richtext", ".", "RichTextObject_AdjustAvailableSpace", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/richtext.py#L1442-L1448
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/graphy/graphy/common.py
python
BaseChart.GetDependentAxis
(self)
return self.left
Return this chart's main dependent axis (often 'left', but horizontal bar-charts use 'bottom').
Return this chart's main dependent axis (often 'left', but horizontal bar-charts use 'bottom').
[ "Return", "this", "chart", "s", "main", "dependent", "axis", "(", "often", "left", "but", "horizontal", "bar", "-", "charts", "use", "bottom", ")", "." ]
def GetDependentAxis(self): """Return this chart's main dependent axis (often 'left', but horizontal bar-charts use 'bottom'). """ return self.left
[ "def", "GetDependentAxis", "(", "self", ")", ":", "return", "self", ".", "left" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/graphy/graphy/common.py#L282-L286
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/decimal.py
python
Decimal.compare_total_mag
(self, other)
return s.compare_total(o)
Compares self to other using abstract repr., ignoring sign. Like compare_total, but with operand's sign ignored and assumed to be 0.
Compares self to other using abstract repr., ignoring sign.
[ "Compares", "self", "to", "other", "using", "abstract", "repr", ".", "ignoring", "sign", "." ]
def compare_total_mag(self, other): """Compares self to other using abstract repr., ignoring sign. Like compare_total, but with operand's sign ignored and assumed to be 0. """ other = _convert_other(other, raiseit=True) s = self.copy_abs() o = other.copy_abs() return s.compare_total(o)
[ "def", "compare_total_mag", "(", "self", ",", "other", ")", ":", "other", "=", "_convert_other", "(", "other", ",", "raiseit", "=", "True", ")", "s", "=", "self", ".", "copy_abs", "(", ")", "o", "=", "other", ".", "copy_abs", "(", ")", "return", "s",...
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/decimal.py#L2749-L2758
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/cython/Cython/Compiler/Code.py
python
UtilityCode.wrap_c_strings
(self, impl)
return impl
Replace CSTRING('''xyz''') by a C compatible string
Replace CSTRING('''xyz''') by a C compatible string
[ "Replace", "CSTRING", "(", "xyz", ")", "by", "a", "C", "compatible", "string" ]
def wrap_c_strings(self, impl): """Replace CSTRING('''xyz''') by a C compatible string """ if 'CSTRING(' not in impl: return impl def split_string(matchobj): content = matchobj.group(1).replace('"', '\042') return ''.join( '"%s\\n"\n' % line if not line.endswith('\\') or line.endswith('\\\\') else '"%s"\n' % line[:-1] for line in content.splitlines()) impl = re.sub(r'CSTRING\(\s*"""([^"]*(?:"[^"]+)*)"""\s*\)', split_string, impl) assert 'CSTRING(' not in impl return impl
[ "def", "wrap_c_strings", "(", "self", ",", "impl", ")", ":", "if", "'CSTRING('", "not", "in", "impl", ":", "return", "impl", "def", "split_string", "(", "matchobj", ")", ":", "content", "=", "matchobj", ".", "group", "(", "1", ")", ".", "replace", "(",...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/cython/Cython/Compiler/Code.py#L575-L589
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/multiprocessing/shared_memory.py
python
ShareableList._get_packing_format
(self, position)
return fmt_as_str
Gets the packing format for a single value stored in the list.
Gets the packing format for a single value stored in the list.
[ "Gets", "the", "packing", "format", "for", "a", "single", "value", "stored", "in", "the", "list", "." ]
def _get_packing_format(self, position): "Gets the packing format for a single value stored in the list." position = position if position >= 0 else position + self._list_len if (position >= self._list_len) or (self._list_len < 0): raise IndexError("Requested position out of range.") v = struct.unpack_from( "8s", self.shm.buf, self._offset_packing_formats + position * 8 )[0] fmt = v.rstrip(b'\x00') fmt_as_str = fmt.decode(_encoding) return fmt_as_str
[ "def", "_get_packing_format", "(", "self", ",", "position", ")", ":", "position", "=", "position", "if", "position", ">=", "0", "else", "position", "+", "self", ".", "_list_len", "if", "(", "position", ">=", "self", ".", "_list_len", ")", "or", "(", "sel...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/multiprocessing/shared_memory.py#L369-L383
microsoft/ELL
a1d6bacc37a14879cc025d9be2ba40b1a0632315
tools/utilities/pythonlibs/audio/view_audio.py
python
AudioDemo.clear_output
(self)
remove some of the Output based a the timeout callback
remove some of the Output based a the timeout callback
[ "remove", "some", "of", "the", "Output", "based", "a", "the", "timeout", "callback" ]
def clear_output(self): """ remove some of the Output based a the timeout callback """ self.output_text.delete(1.0, 2.0)
[ "def", "clear_output", "(", "self", ")", ":", "self", ".", "output_text", ".", "delete", "(", "1.0", ",", "2.0", ")" ]
https://github.com/microsoft/ELL/blob/a1d6bacc37a14879cc025d9be2ba40b1a0632315/tools/utilities/pythonlibs/audio/view_audio.py#L373-L375
klzgrad/naiveproxy
ed2c513637c77b18721fe428d7ed395b4d284c83
src/build/android/pylib/results/json_results.py
python
GenerateJsonTestResultFormatFile
(test_run_result, interrupted, file_path, **kwargs)
Write |test_run_result| to JSON. This uses the official Chromium Test Results Format. Args: test_run_result: a base_test_result.TestRunResults object. interrupted: True if tests were interrupted, e.g. timeout listing tests file_path: The path to the JSON file to write.
Write |test_run_result| to JSON.
[ "Write", "|test_run_result|", "to", "JSON", "." ]
def GenerateJsonTestResultFormatFile(test_run_result, interrupted, file_path, **kwargs): """Write |test_run_result| to JSON. This uses the official Chromium Test Results Format. Args: test_run_result: a base_test_result.TestRunResults object. interrupted: True if tests were interrupted, e.g. timeout listing tests file_path: The path to the JSON file to write. """ with open(file_path, 'w') as json_result_file: json_result_file.write( json.dumps( GenerateJsonTestResultFormatDict(test_run_result, interrupted), **kwargs)) logging.info('Generated json results file at %s', file_path)
[ "def", "GenerateJsonTestResultFormatFile", "(", "test_run_result", ",", "interrupted", ",", "file_path", ",", "*", "*", "kwargs", ")", ":", "with", "open", "(", "file_path", ",", "'w'", ")", "as", "json_result_file", ":", "json_result_file", ".", "write", "(", ...
https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/build/android/pylib/results/json_results.py#L197-L213
tuttleofx/TuttleOFX
36fc4cae15092a84ea8c29b9c6658c7cabfadb6e
applications/sam/common/samDoUtils.py
python
SplitCmdNode.getArgument
(self, name)
return (None, None)
If not found, returns (None, None)
If not found, returns (None, None)
[ "If", "not", "found", "returns", "(", "None", "None", ")" ]
def getArgument(self, name): """ If not found, returns (None, None) """ for argName, argvalue in self._arguments: if argName == name: return (argName, argvalue) return (None, None)
[ "def", "getArgument", "(", "self", ",", "name", ")", ":", "for", "argName", ",", "argvalue", "in", "self", ".", "_arguments", ":", "if", "argName", "==", "name", ":", "return", "(", "argName", ",", "argvalue", ")", "return", "(", "None", ",", "None", ...
https://github.com/tuttleofx/TuttleOFX/blob/36fc4cae15092a84ea8c29b9c6658c7cabfadb6e/applications/sam/common/samDoUtils.py#L292-L299
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/uu.py
python
decode
(in_file, out_file=None, mode=None, quiet=False)
Decode uuencoded file
Decode uuencoded file
[ "Decode", "uuencoded", "file" ]
def decode(in_file, out_file=None, mode=None, quiet=False): """Decode uuencoded file""" # # Open the input file, if needed. # opened_files = [] if in_file == '-': in_file = sys.stdin.buffer elif isinstance(in_file, str): in_file = open(in_file, 'rb') opened_files.append(in_file) try: # # Read until a begin is encountered or we've exhausted the file # while True: hdr = in_file.readline() if not hdr: raise Error('No valid begin line found in input file') if not hdr.startswith(b'begin'): continue hdrfields = hdr.split(b' ', 2) if len(hdrfields) == 3 and hdrfields[0] == b'begin': try: int(hdrfields[1], 8) break except ValueError: pass if out_file is None: # If the filename isn't ASCII, what's up with that?!? out_file = hdrfields[2].rstrip(b' \t\r\n\f').decode("ascii") if os.path.exists(out_file): raise Error('Cannot overwrite existing file: %s' % out_file) if mode is None: mode = int(hdrfields[1], 8) # # Open the output file # if out_file == '-': out_file = sys.stdout.buffer elif isinstance(out_file, str): fp = open(out_file, 'wb') os.chmod(out_file, mode) out_file = fp opened_files.append(out_file) # # Main decoding loop # s = in_file.readline() while s and s.strip(b' \t\r\n\f') != b'end': try: data = binascii.a2b_uu(s) except binascii.Error as v: # Workaround for broken uuencoders by /Fredrik Lundh nbytes = (((s[0]-32) & 63) * 4 + 5) // 3 data = binascii.a2b_uu(s[:nbytes]) if not quiet: sys.stderr.write("Warning: %s\n" % v) out_file.write(data) s = in_file.readline() if not s: raise Error('Truncated input file') finally: for f in opened_files: f.close()
[ "def", "decode", "(", "in_file", ",", "out_file", "=", "None", ",", "mode", "=", "None", ",", "quiet", "=", "False", ")", ":", "#", "# Open the input file, if needed.", "#", "opened_files", "=", "[", "]", "if", "in_file", "==", "'-'", ":", "in_file", "="...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/uu.py#L100-L165
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/ops/linalg/linalg_impl.py
python
matrix_exponential
(input, name=None)
r"""Computes the matrix exponential of one or more square matrices. $$exp(A) = \sum_{n=0}^\infty A^n/n!$$ The exponential is computed using a combination of the scaling and squaring method and the Pade approximation. Details can be found in: Nicholas J. Higham, "The scaling and squaring method for the matrix exponential revisited," SIAM J. Matrix Anal. Applic., 26:1179-1193, 2005. The input is a tensor of shape `[..., M, M]` whose inner-most 2 dimensions form square matrices. The output is a tensor of the same shape as the input containing the exponential for all input submatrices `[..., :, :]`. Args: input: A `Tensor`. Must be `float16`, `float32`, `float64`, `complex64`, or `complex128` with shape `[..., M, M]`. name: A name to give this `Op` (optional). Returns: the matrix exponential of the input. Raises: ValueError: An unsupported type is provided as input. @compatibility(scipy) Equivalent to scipy.linalg.expm @end_compatibility
r"""Computes the matrix exponential of one or more square matrices.
[ "r", "Computes", "the", "matrix", "exponential", "of", "one", "or", "more", "square", "matrices", "." ]
def matrix_exponential(input, name=None): # pylint: disable=redefined-builtin r"""Computes the matrix exponential of one or more square matrices. $$exp(A) = \sum_{n=0}^\infty A^n/n!$$ The exponential is computed using a combination of the scaling and squaring method and the Pade approximation. Details can be found in: Nicholas J. Higham, "The scaling and squaring method for the matrix exponential revisited," SIAM J. Matrix Anal. Applic., 26:1179-1193, 2005. The input is a tensor of shape `[..., M, M]` whose inner-most 2 dimensions form square matrices. The output is a tensor of the same shape as the input containing the exponential for all input submatrices `[..., :, :]`. Args: input: A `Tensor`. Must be `float16`, `float32`, `float64`, `complex64`, or `complex128` with shape `[..., M, M]`. name: A name to give this `Op` (optional). Returns: the matrix exponential of the input. Raises: ValueError: An unsupported type is provided as input. @compatibility(scipy) Equivalent to scipy.linalg.expm @end_compatibility """ with ops.name_scope(name, 'matrix_exponential', [input]): matrix = ops.convert_to_tensor(input, name='input') if matrix.shape[-2:] == [0, 0]: return matrix batch_shape = matrix.shape[:-2] if not batch_shape.is_fully_defined(): batch_shape = array_ops.shape(matrix)[:-2] # reshaping the batch makes the where statements work better matrix = array_ops.reshape( matrix, array_ops.concat(([-1], array_ops.shape(matrix)[-2:]), axis=0)) l1_norm = math_ops.reduce_max( math_ops.reduce_sum( math_ops.abs(matrix), axis=array_ops.size(array_ops.shape(matrix)) - 2), axis=-1)[..., array_ops.newaxis, array_ops.newaxis] const = lambda x: constant_op.constant(x, l1_norm.dtype) def _nest_where(vals, cases): assert len(vals) == len(cases) - 1 if len(vals) == 1: return array_ops.where_v2( math_ops.less(l1_norm, const(vals[0])), cases[0], cases[1]) else: return array_ops.where_v2( math_ops.less(l1_norm, const(vals[0])), cases[0], _nest_where(vals[1:], cases[1:])) if matrix.dtype in [dtypes.float16, dtypes.float32, dtypes.complex64]: maxnorm = const(3.925724783138660) squarings = math_ops.maximum( math_ops.floor( math_ops.log(l1_norm / maxnorm) / math_ops.log(const(2.0))), 0) u3, v3 = _matrix_exp_pade3(matrix) u5, v5 = _matrix_exp_pade5(matrix) u7, v7 = _matrix_exp_pade7( matrix / math_ops.cast(math_ops.pow(const(2.0), squarings), matrix.dtype)) conds = (4.258730016922831e-001, 1.880152677804762e+000) u = _nest_where(conds, (u3, u5, u7)) v = _nest_where(conds, (v3, v5, v7)) elif matrix.dtype in [dtypes.float64, dtypes.complex128]: maxnorm = const(5.371920351148152) squarings = math_ops.maximum( math_ops.floor( math_ops.log(l1_norm / maxnorm) / math_ops.log(const(2.0))), 0) u3, v3 = _matrix_exp_pade3(matrix) u5, v5 = _matrix_exp_pade5(matrix) u7, v7 = _matrix_exp_pade7(matrix) u9, v9 = _matrix_exp_pade9(matrix) u13, v13 = _matrix_exp_pade13( matrix / math_ops.cast(math_ops.pow(const(2.0), squarings), matrix.dtype)) conds = (1.495585217958292e-002, 2.539398330063230e-001, 9.504178996162932e-001, 2.097847961257068e+000) u = _nest_where(conds, (u3, u5, u7, u9, u13)) v = _nest_where(conds, (v3, v5, v7, v9, v13)) else: raise ValueError('tf.linalg.expm does not support matrices of type %s' % matrix.dtype) is_finite = math_ops.is_finite(math_ops.reduce_max(l1_norm)) nan = constant_op.constant(np.nan, matrix.dtype) result = control_flow_ops.cond( is_finite, lambda: linalg_ops.matrix_solve(-u + v, u + v), lambda: array_ops.fill(array_ops.shape(matrix), nan)) max_squarings = math_ops.reduce_max(squarings) i = const(0.0) def c(i, _): return control_flow_ops.cond(is_finite, lambda: math_ops.less(i, max_squarings), lambda: constant_op.constant(False)) def b(i, r): return i + 1, array_ops.where_v2( math_ops.less(i, squarings), math_ops.matmul(r, r), r) _, result = control_flow_ops.while_loop(c, b, [i, result]) if not matrix.shape.is_fully_defined(): return array_ops.reshape( result, array_ops.concat((batch_shape, array_ops.shape(result)[-2:]), axis=0)) return array_ops.reshape(result, batch_shape.concatenate(result.shape[-2:]))
[ "def", "matrix_exponential", "(", "input", ",", "name", "=", "None", ")", ":", "# pylint: disable=redefined-builtin", "with", "ops", ".", "name_scope", "(", "name", ",", "'matrix_exponential'", ",", "[", "input", "]", ")", ":", "matrix", "=", "ops", ".", "co...
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/linalg/linalg_impl.py#L231-L344
thalium/icebox
99d147d5b9269222225443ce171b4fd46d8985d4
third_party/virtualbox/src/VBox/ValidationKit/common/utils.py
python
getTimePrefixAndIsoTimestamp
()
return (sTsPrf, sTsIso)
Returns current UTC as log prefix and iso timestamp.
Returns current UTC as log prefix and iso timestamp.
[ "Returns", "current", "UTC", "as", "log", "prefix", "and", "iso", "timestamp", "." ]
def getTimePrefixAndIsoTimestamp(): """ Returns current UTC as log prefix and iso timestamp. """ try: oNow = datetime.datetime.utcnow(); sTsPrf = '%02u:%02u:%02u.%06u' % (oNow.hour, oNow.minute, oNow.second, oNow.microsecond); sTsIso = formatIsoTimestamp(oNow); except: sTsPrf = sTsIso = 'getTimePrefix-exception'; return (sTsPrf, sTsIso);
[ "def", "getTimePrefixAndIsoTimestamp", "(", ")", ":", "try", ":", "oNow", "=", "datetime", ".", "datetime", ".", "utcnow", "(", ")", "sTsPrf", "=", "'%02u:%02u:%02u.%06u'", "%", "(", "oNow", ".", "hour", ",", "oNow", ".", "minute", ",", "oNow", ".", "sec...
https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/VBox/ValidationKit/common/utils.py#L1306-L1316
AXErunners/axe
53f14e8112ab6370b96e1e78d2858dabc886bba4
contrib/devtools/security-check.py
python
get_PE_dll_characteristics
(executable)
return (arch,bits)
Get PE DllCharacteristics bits. Returns a tuple (arch,bits) where arch is 'i386:x86-64' or 'i386' and bits is the DllCharacteristics value.
Get PE DllCharacteristics bits. Returns a tuple (arch,bits) where arch is 'i386:x86-64' or 'i386' and bits is the DllCharacteristics value.
[ "Get", "PE", "DllCharacteristics", "bits", ".", "Returns", "a", "tuple", "(", "arch", "bits", ")", "where", "arch", "is", "i386", ":", "x86", "-", "64", "or", "i386", "and", "bits", "is", "the", "DllCharacteristics", "value", "." ]
def get_PE_dll_characteristics(executable): ''' Get PE DllCharacteristics bits. Returns a tuple (arch,bits) where arch is 'i386:x86-64' or 'i386' and bits is the DllCharacteristics value. ''' p = subprocess.Popen([OBJDUMP_CMD, '-x', executable], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE, universal_newlines=True) (stdout, stderr) = p.communicate() if p.returncode: raise IOError('Error opening file') arch = '' bits = 0 for line in stdout.splitlines(): tokens = line.split() if len(tokens)>=2 and tokens[0] == 'architecture:': arch = tokens[1].rstrip(',') if len(tokens)>=2 and tokens[0] == 'DllCharacteristics': bits = int(tokens[1],16) return (arch,bits)
[ "def", "get_PE_dll_characteristics", "(", "executable", ")", ":", "p", "=", "subprocess", ".", "Popen", "(", "[", "OBJDUMP_CMD", ",", "'-x'", ",", "executable", "]", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "PIP...
https://github.com/AXErunners/axe/blob/53f14e8112ab6370b96e1e78d2858dabc886bba4/contrib/devtools/security-check.py#L118-L136
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/flatmenu.py
python
FlatMenu.OnChar
(self, key)
return processed
Handles key events for :class:`FlatMenu`. :param `key`: the keyboard key integer code.
Handles key events for :class:`FlatMenu`.
[ "Handles", "key", "events", "for", ":", "class", ":", "FlatMenu", "." ]
def OnChar(self, key): """ Handles key events for :class:`FlatMenu`. :param `key`: the keyboard key integer code. """ processed = True if key == wx.WXK_ESCAPE: if self._parentMenu: self._parentMenu.CloseSubMenu(-1) else: self.Dismiss(True, True) elif key == wx.WXK_LEFT: if self._parentMenu: # We are a submenu, dismiss us. self._parentMenu.CloseSubMenu(-1) else: # try to find our root menu, if we are attached to menubar, # let it try and open the previous menu root = self.GetRootMenu() if root: if root._mb: root._mb.ActivatePreviousMenu() elif key == wx.WXK_RIGHT: if not self.TryOpenSubMenu(self._selectedItem, True): # try to find our root menu, if we are attached to menubar, # let it try and open the previous menu root = self.GetRootMenu() if root: if root._mb: root._mb.ActivateNextMenu() elif key == wx.WXK_UP: self.AdvanceSelection(False) elif key == wx.WXK_DOWN: self.AdvanceSelection() elif key in [wx.WXK_RETURN, wx.WXK_NUMPAD_ENTER]: self.DoAction(self._selectedItem) elif key == wx.WXK_HOME: # Select first item of the menu if self._selectedItem != 0: oldSel = self._selectedItem self._selectedItem = 0 dc = wx.ClientDC(self) self.DrawSelection(dc, oldSel) elif key == wx.WXK_END: # Select last item of the menu if self._selectedItem != len(self._itemsArr)-1: oldSel = self._selectedItem self._selectedItem = len(self._itemsArr)-1 dc = wx.ClientDC(self) self.DrawSelection(dc, oldSel) elif key in [wx.WXK_CONTROL, wx.WXK_ALT]: # Alt was pressed root = self.GetRootMenu() root.Dismiss(False, True) else: try: chrkey = chr(key) except: return processed if chrkey.isalnum(): ch = chrkey.lower() # Iterate over all the menu items itemIdx = -1 occur = 0 for i in xrange(len(self._itemsArr)): item = self._itemsArr[i] mnemonic = item.GetMnemonicChar() if mnemonic == ch: if itemIdx == -1: itemIdx = i # We keep the index of only # the first occurence occur += 1 # Keep on looping until no more items for self menu if itemIdx != -1: if occur > 1: # We select the first item if self._selectedItem == itemIdx: return processed oldSel = self._selectedItem self._selectedItem = itemIdx dc = wx.ClientDC(self) self.DrawSelection(dc, oldSel) elif occur == 1: # Activate the item, if self is a submenu item we first select it item = self._itemsArr[itemIdx] if item.IsSubMenu() and self._selectedItem != itemIdx: oldSel = self._selectedItem self._selectedItem = itemIdx dc = wx.ClientDC(self) self.DrawSelection(dc, oldSel) self.DoAction(itemIdx) else: processed = False return processed
[ "def", "OnChar", "(", "self", ",", "key", ")", ":", "processed", "=", "True", "if", "key", "==", "wx", ".", "WXK_ESCAPE", ":", "if", "self", ".", "_parentMenu", ":", "self", ".", "_parentMenu", ".", "CloseSubMenu", "(", "-", "1", ")", "else", ":", ...
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/flatmenu.py#L5846-L5979
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/urllib3/util/ssl_.py
python
ssl_wrap_socket
( sock, keyfile=None, certfile=None, cert_reqs=None, ca_certs=None, server_hostname=None, ssl_version=None, ciphers=None, ssl_context=None, ca_cert_dir=None, key_password=None, )
return context.wrap_socket(sock)
All arguments except for server_hostname, ssl_context, and ca_cert_dir have the same meaning as they do when using :func:`ssl.wrap_socket`. :param server_hostname: When SNI is supported, the expected hostname of the certificate :param ssl_context: A pre-made :class:`SSLContext` object. If none is provided, one will be created using :func:`create_urllib3_context`. :param ciphers: A string of ciphers we wish the client to support. :param ca_cert_dir: A directory containing CA certificates in multiple separate files, as supported by OpenSSL's -CApath flag or the capath argument to SSLContext.load_verify_locations(). :param key_password: Optional password if the keyfile is encrypted.
All arguments except for server_hostname, ssl_context, and ca_cert_dir have the same meaning as they do when using :func:`ssl.wrap_socket`.
[ "All", "arguments", "except", "for", "server_hostname", "ssl_context", "and", "ca_cert_dir", "have", "the", "same", "meaning", "as", "they", "do", "when", "using", ":", "func", ":", "ssl", ".", "wrap_socket", "." ]
def ssl_wrap_socket( sock, keyfile=None, certfile=None, cert_reqs=None, ca_certs=None, server_hostname=None, ssl_version=None, ciphers=None, ssl_context=None, ca_cert_dir=None, key_password=None, ): """ All arguments except for server_hostname, ssl_context, and ca_cert_dir have the same meaning as they do when using :func:`ssl.wrap_socket`. :param server_hostname: When SNI is supported, the expected hostname of the certificate :param ssl_context: A pre-made :class:`SSLContext` object. If none is provided, one will be created using :func:`create_urllib3_context`. :param ciphers: A string of ciphers we wish the client to support. :param ca_cert_dir: A directory containing CA certificates in multiple separate files, as supported by OpenSSL's -CApath flag or the capath argument to SSLContext.load_verify_locations(). :param key_password: Optional password if the keyfile is encrypted. """ context = ssl_context if context is None: # Note: This branch of code and all the variables in it are no longer # used by urllib3 itself. We should consider deprecating and removing # this code. context = create_urllib3_context(ssl_version, cert_reqs, ciphers=ciphers) if ca_certs or ca_cert_dir: try: context.load_verify_locations(ca_certs, ca_cert_dir) except IOError as e: # Platform-specific: Python 2.7 raise SSLError(e) # Py33 raises FileNotFoundError which subclasses OSError # These are not equivalent unless we check the errno attribute except OSError as e: # Platform-specific: Python 3.3 and beyond if e.errno == errno.ENOENT: raise SSLError(e) raise elif ssl_context is None and hasattr(context, "load_default_certs"): # try to load OS default certs; works well on Windows (require Python3.4+) context.load_default_certs() # Attempt to detect if we get the goofy behavior of the # keyfile being encrypted and OpenSSL asking for the # passphrase via the terminal and instead error out. if keyfile and key_password is None and _is_key_file_encrypted(keyfile): raise SSLError("Client private key is encrypted, password is required") if certfile: if key_password is None: context.load_cert_chain(certfile, keyfile) else: context.load_cert_chain(certfile, keyfile, key_password) # If we detect server_hostname is an IP address then the SNI # extension should not be used according to RFC3546 Section 3.1 # We shouldn't warn the user if SNI isn't available but we would # not be using SNI anyways due to IP address for server_hostname. if ( server_hostname is not None and not is_ipaddress(server_hostname) ) or IS_SECURETRANSPORT: if HAS_SNI and server_hostname is not None: return context.wrap_socket(sock, server_hostname=server_hostname) warnings.warn( "An HTTPS request has been made, but the SNI (Server Name " "Indication) extension to TLS is not available on this platform. " "This may cause the server to present an incorrect TLS " "certificate, which can cause validation failures. You can upgrade to " "a newer version of Python to solve this. For more information, see " "https://urllib3.readthedocs.io/en/latest/advanced-usage.html" "#ssl-warnings", SNIMissingWarning, ) return context.wrap_socket(sock)
[ "def", "ssl_wrap_socket", "(", "sock", ",", "keyfile", "=", "None", ",", "certfile", "=", "None", ",", "cert_reqs", "=", "None", ",", "ca_certs", "=", "None", ",", "server_hostname", "=", "None", ",", "ssl_version", "=", "None", ",", "ciphers", "=", "Non...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/urllib3/util/ssl_.py#L296-L383
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Editor/Python/windows/Lib/site-packages/setuptools/command/build_py.py
python
build_py.find_data_files
(self, package, src_dir)
return self.exclude_data_files(package, src_dir, files)
Return filenames for package's data files in 'src_dir
Return filenames for package's data files in 'src_dir
[ "Return", "filenames", "for", "package", "s", "data", "files", "in", "src_dir" ]
def find_data_files(self, package, src_dir): """Return filenames for package's data files in 'src_dir'""" patterns = self._get_platform_patterns( self.package_data, package, src_dir, ) globs_expanded = map(glob, patterns) # flatten the expanded globs into an iterable of matches globs_matches = itertools.chain.from_iterable(globs_expanded) glob_files = filter(os.path.isfile, globs_matches) files = itertools.chain( self.manifest_files.get(package, []), glob_files, ) return self.exclude_data_files(package, src_dir, files)
[ "def", "find_data_files", "(", "self", ",", "package", ",", "src_dir", ")", ":", "patterns", "=", "self", ".", "_get_platform_patterns", "(", "self", ".", "package_data", ",", "package", ",", "src_dir", ",", ")", "globs_expanded", "=", "map", "(", "glob", ...
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/setuptools/command/build_py.py#L99-L114
SFTtech/openage
d6a08c53c48dc1e157807471df92197f6ca9e04d
openage/convert/entity_object/conversion/aoc/genie_effect.py
python
GenieEffectBundle.__init__
(self, bundle_id, effects, full_data_set, members=None)
Creates a new Genie effect bundle. :param bundle_id: The index of the effect in the .dat file's effect block. (the index is referenced as tech_effect_id by techs) :param effects: Effects of the bundle as list of GenieEffectObject. :param full_data_set: GenieObjectContainer instance that contains all relevant data for the conversion process. :param members: An already existing member dict.
Creates a new Genie effect bundle.
[ "Creates", "a", "new", "Genie", "effect", "bundle", "." ]
def __init__(self, bundle_id, effects, full_data_set, members=None): """ Creates a new Genie effect bundle. :param bundle_id: The index of the effect in the .dat file's effect block. (the index is referenced as tech_effect_id by techs) :param effects: Effects of the bundle as list of GenieEffectObject. :param full_data_set: GenieObjectContainer instance that contains all relevant data for the conversion process. :param members: An already existing member dict. """ super().__init__(bundle_id, members=members) self.effects = effects # Sanitized bundles should not contain 'garbage' effects, e.g. # - effects that do nothing # - effects without a type # # Processors should set this to True, once the bundle is sanitized. self.sanitized = False self.data = full_data_set
[ "def", "__init__", "(", "self", ",", "bundle_id", ",", "effects", ",", "full_data_set", ",", "members", "=", "None", ")", ":", "super", "(", ")", ".", "__init__", "(", "bundle_id", ",", "members", "=", "members", ")", "self", ".", "effects", "=", "effe...
https://github.com/SFTtech/openage/blob/d6a08c53c48dc1e157807471df92197f6ca9e04d/openage/convert/entity_object/conversion/aoc/genie_effect.py#L52-L75
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
build/android/buildbot/bb_device_steps.py
python
RebootDevices
()
Reboot all attached and online devices.
Reboot all attached and online devices.
[ "Reboot", "all", "attached", "and", "online", "devices", "." ]
def RebootDevices(): """Reboot all attached and online devices.""" # Early return here to avoid presubmit dependence on adb, # which might not exist in this checkout. if bb_utils.TESTING: return devices = android_commands.GetAttachedDevices(emulator=False) print 'Rebooting: %s' % devices if devices: pool = multiprocessing.Pool(len(devices)) results = pool.map_async(RebootDeviceSafe, devices).get(99999) for device, result in zip(devices, results): if result: print '%s failed to startup.' % device if any(results): bb_annotations.PrintWarning() else: print 'Reboots complete.'
[ "def", "RebootDevices", "(", ")", ":", "# Early return here to avoid presubmit dependence on adb,", "# which might not exist in this checkout.", "if", "bb_utils", ".", "TESTING", ":", "return", "devices", "=", "android_commands", ".", "GetAttachedDevices", "(", "emulator", "=...
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/build/android/buildbot/bb_device_steps.py#L110-L129
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/distutils/ccompiler.py
python
CCompiler.has_function
(self, funcname, includes=None, include_dirs=None, libraries=None, library_dirs=None)
return True
Return a boolean indicating whether funcname is supported on the current platform. The optional arguments can be used to augment the compilation environment.
Return a boolean indicating whether funcname is supported on the current platform. The optional arguments can be used to augment the compilation environment.
[ "Return", "a", "boolean", "indicating", "whether", "funcname", "is", "supported", "on", "the", "current", "platform", ".", "The", "optional", "arguments", "can", "be", "used", "to", "augment", "the", "compilation", "environment", "." ]
def has_function(self, funcname, includes=None, include_dirs=None, libraries=None, library_dirs=None): """Return a boolean indicating whether funcname is supported on the current platform. The optional arguments can be used to augment the compilation environment. """ # this can't be included at module scope because it tries to # import math which might not be available at that point - maybe # the necessary logic should just be inlined? import tempfile if includes is None: includes = [] if include_dirs is None: include_dirs = [] if libraries is None: libraries = [] if library_dirs is None: library_dirs = [] fd, fname = tempfile.mkstemp(".c", funcname, text=True) f = os.fdopen(fd, "w") try: for incl in includes: f.write("""#include "%s"\n""" % incl) f.write("""\ main (int argc, char **argv) { %s(); } """ % funcname) finally: f.close() try: objects = self.compile([fname], include_dirs=include_dirs) except CompileError: return False try: self.link_executable(objects, "a.out", libraries=libraries, library_dirs=library_dirs) except (LinkError, TypeError): return False return True
[ "def", "has_function", "(", "self", ",", "funcname", ",", "includes", "=", "None", ",", "include_dirs", "=", "None", ",", "libraries", "=", "None", ",", "library_dirs", "=", "None", ")", ":", "# this can't be included at module scope because it tries to", "# import ...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/distutils/ccompiler.py#L726-L768
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/cgi.py
python
print_directory
()
Dump the current directory as HTML.
Dump the current directory as HTML.
[ "Dump", "the", "current", "directory", "as", "HTML", "." ]
def print_directory(): """Dump the current directory as HTML.""" print() print("<H3>Current Working Directory:</H3>") try: pwd = os.getcwd() except OSError as msg: print("OSError:", html.escape(str(msg))) else: print(html.escape(pwd)) print()
[ "def", "print_directory", "(", ")", ":", "print", "(", ")", "print", "(", "\"<H3>Current Working Directory:</H3>\"", ")", "try", ":", "pwd", "=", "os", ".", "getcwd", "(", ")", "except", "OSError", "as", "msg", ":", "print", "(", "\"OSError:\"", ",", "html...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/cgi.py#L939-L949
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/ma/core.py
python
MaskedArray.all
(self, axis=None, out=None)
return out
Check if all of the elements of `a` are true. Performs a :func:`logical_and` over the given axis and returns the result. Masked values are considered as True during computation. For convenience, the output array is masked where ALL the values along the current axis are masked: if the output would have been a scalar and that all the values are masked, then the output is `masked`. Parameters ---------- axis : {None, integer} Axis to perform the operation over. If None, perform over flattened array. out : {None, array}, optional Array into which the result can be placed. Its type is preserved and it must be of the right shape to hold the output. See Also -------- all : equivalent function Examples -------- >>> np.ma.array([1,2,3]).all() True >>> a = np.ma.array([1,2,3], mask=True) >>> (a.all() is np.ma.masked) True
Check if all of the elements of `a` are true.
[ "Check", "if", "all", "of", "the", "elements", "of", "a", "are", "true", "." ]
def all(self, axis=None, out=None): """ Check if all of the elements of `a` are true. Performs a :func:`logical_and` over the given axis and returns the result. Masked values are considered as True during computation. For convenience, the output array is masked where ALL the values along the current axis are masked: if the output would have been a scalar and that all the values are masked, then the output is `masked`. Parameters ---------- axis : {None, integer} Axis to perform the operation over. If None, perform over flattened array. out : {None, array}, optional Array into which the result can be placed. Its type is preserved and it must be of the right shape to hold the output. See Also -------- all : equivalent function Examples -------- >>> np.ma.array([1,2,3]).all() True >>> a = np.ma.array([1,2,3], mask=True) >>> (a.all() is np.ma.masked) True """ mask = _check_mask_axis(self._mask, axis) if out is None: d = self.filled(True).all(axis=axis).view(type(self)) if d.ndim: d.__setmask__(mask) elif mask: return masked return d self.filled(True).all(axis=axis, out=out) if isinstance(out, MaskedArray): if out.ndim or mask: out.__setmask__(mask) return out
[ "def", "all", "(", "self", ",", "axis", "=", "None", ",", "out", "=", "None", ")", ":", "mask", "=", "_check_mask_axis", "(", "self", ".", "_mask", ",", "axis", ")", "if", "out", "is", "None", ":", "d", "=", "self", ".", "filled", "(", "True", ...
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/ma/core.py#L4237-L4281
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/pydoc.py
python
getdoc
(object)
return result and re.sub('^ *\n', '', rstrip(result)) or ''
Get the doc string or comments for an object.
Get the doc string or comments for an object.
[ "Get", "the", "doc", "string", "or", "comments", "for", "an", "object", "." ]
def getdoc(object): """Get the doc string or comments for an object.""" result = inspect.getdoc(object) or inspect.getcomments(object) result = _encode(result) return result and re.sub('^ *\n', '', rstrip(result)) or ''
[ "def", "getdoc", "(", "object", ")", ":", "result", "=", "inspect", ".", "getdoc", "(", "object", ")", "or", "inspect", ".", "getcomments", "(", "object", ")", "result", "=", "_encode", "(", "result", ")", "return", "result", "and", "re", ".", "sub", ...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/pydoc.py#L82-L86
microsoft/TSS.MSR
0f2516fca2cd9929c31d5450e39301c9bde43688
TSS.Py/src/TpmTypes.py
python
CertifyCreationResponse.__init__
(self, certifyInfo = None, signature = None)
This command is used to prove the association between an object and its creation data. The TPM will validate that the ticket was produced by the TPM and that the ticket validates the association between a loaded public area and the provided hash of the creation data (creationHash). Attributes: certifyInfo (TPMS_ATTEST): The structure that was signed signature (TPMU_SIGNATURE): The signature over certifyInfo One of: TPMS_SIGNATURE_RSASSA, TPMS_SIGNATURE_RSAPSS, TPMS_SIGNATURE_ECDSA, TPMS_SIGNATURE_ECDAA, TPMS_SIGNATURE_SM2, TPMS_SIGNATURE_ECSCHNORR, TPMT_HA, TPMS_SCHEME_HASH, TPMS_NULL_SIGNATURE.
This command is used to prove the association between an object and its creation data. The TPM will validate that the ticket was produced by the TPM and that the ticket validates the association between a loaded public area and the provided hash of the creation data (creationHash).
[ "This", "command", "is", "used", "to", "prove", "the", "association", "between", "an", "object", "and", "its", "creation", "data", ".", "The", "TPM", "will", "validate", "that", "the", "ticket", "was", "produced", "by", "the", "TPM", "and", "that", "the", ...
def __init__(self, certifyInfo = None, signature = None): """ This command is used to prove the association between an object and its creation data. The TPM will validate that the ticket was produced by the TPM and that the ticket validates the association between a loaded public area and the provided hash of the creation data (creationHash). Attributes: certifyInfo (TPMS_ATTEST): The structure that was signed signature (TPMU_SIGNATURE): The signature over certifyInfo One of: TPMS_SIGNATURE_RSASSA, TPMS_SIGNATURE_RSAPSS, TPMS_SIGNATURE_ECDSA, TPMS_SIGNATURE_ECDAA, TPMS_SIGNATURE_SM2, TPMS_SIGNATURE_ECSCHNORR, TPMT_HA, TPMS_SCHEME_HASH, TPMS_NULL_SIGNATURE. """ self.certifyInfo = certifyInfo self.signature = signature
[ "def", "__init__", "(", "self", ",", "certifyInfo", "=", "None", ",", "signature", "=", "None", ")", ":", "self", ".", "certifyInfo", "=", "certifyInfo", "self", ".", "signature", "=", "signature" ]
https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L12586-L12601
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/concurrent/futures/thread.py
python
__init__
(self, max_workers=None, thread_name_prefix='', initializer=None, initargs=())
Initializes a new ThreadPoolExecutor instance. Args: max_workers: The maximum number of threads that can be used to execute the given calls. thread_name_prefix: An optional name prefix to give our threads. initializer: A callable used to initialize worker threads. initargs: A tuple of arguments to pass to the initializer.
Initializes a new ThreadPoolExecutor instance.
[ "Initializes", "a", "new", "ThreadPoolExecutor", "instance", "." ]
def __init__(self, max_workers=None, thread_name_prefix='', initializer=None, initargs=()): """Initializes a new ThreadPoolExecutor instance. Args: max_workers: The maximum number of threads that can be used to execute the given calls. thread_name_prefix: An optional name prefix to give our threads. initializer: A callable used to initialize worker threads. initargs: A tuple of arguments to pass to the initializer. """ if max_workers is None: # ThreadPoolExecutor is often used to: # * CPU bound task which releases GIL # * I/O bound task (which releases GIL, of course) # # We use cpu_count + 4 for both types of tasks. # But we limit it to 32 to avoid consuming surprisingly large resource # on many core machine. max_workers = min(32, (os.cpu_count() or 1) + 4) if max_workers <= 0: raise ValueError("max_workers must be greater than 0") if initializer is not None and not callable(initializer): raise TypeError("initializer must be a callable") self._max_workers = max_workers self._work_queue = queue.SimpleQueue() self._idle_semaphore = threading.Semaphore(0) self._threads = set() self._broken = False self._shutdown = False self._shutdown_lock = threading.Lock() self._thread_name_prefix = (thread_name_prefix or ("ThreadPoolExecutor-%d" % self._counter())) self._initializer = initializer self._initargs = initargs
[ "def", "__init__", "(", "self", ",", "max_workers", "=", "None", ",", "thread_name_prefix", "=", "''", ",", "initializer", "=", "None", ",", "initargs", "=", "(", ")", ")", ":", "if", "max_workers", "is", "None", ":", "# ThreadPoolExecutor is often used to:", ...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/concurrent/futures/thread.py#L123-L159
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
third_party/jinja2/runtime.py
python
Context.get
(self, key, default=None)
Returns an item from the template context, if it doesn't exist `default` is returned.
Returns an item from the template context, if it doesn't exist `default` is returned.
[ "Returns", "an", "item", "from", "the", "template", "context", "if", "it", "doesn", "t", "exist", "default", "is", "returned", "." ]
def get(self, key, default=None): """Returns an item from the template context, if it doesn't exist `default` is returned. """ try: return self[key] except KeyError: return default
[ "def", "get", "(", "self", ",", "key", ",", "default", "=", "None", ")", ":", "try", ":", "return", "self", "[", "key", "]", "except", "KeyError", ":", "return", "default" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/jinja2/runtime.py#L137-L144
johmathe/shotdetect
1ecf93a695c96fd7601a41ab5834f1117b9d7d50
tools/cpplint.py
python
CheckSpacingForFunctionCall
(filename, line, linenum, error)
Checks for the correctness of various spacing around function calls. Args: filename: The name of the current file. line: The text of the line to check. linenum: The number of the line to check. error: The function to call with any errors found.
Checks for the correctness of various spacing around function calls.
[ "Checks", "for", "the", "correctness", "of", "various", "spacing", "around", "function", "calls", "." ]
def CheckSpacingForFunctionCall(filename, line, linenum, error): """Checks for the correctness of various spacing around function calls. Args: filename: The name of the current file. line: The text of the line to check. linenum: The number of the line to check. error: The function to call with any errors found. """ # Since function calls often occur inside if/for/while/switch # expressions - which have their own, more liberal conventions - we # first see if we should be looking inside such an expression for a # function call, to which we can apply more strict standards. fncall = line # if there's no control flow construct, look at whole line for pattern in (r'\bif\s*\((.*)\)\s*{', r'\bfor\s*\((.*)\)\s*{', r'\bwhile\s*\((.*)\)\s*[{;]', r'\bswitch\s*\((.*)\)\s*{'): match = Search(pattern, line) if match: fncall = match.group(1) # look inside the parens for function calls break # Except in if/for/while/switch, there should never be space # immediately inside parens (eg "f( 3, 4 )"). We make an exception # for nested parens ( (a+b) + c ). Likewise, there should never be # a space before a ( when it's a function argument. I assume it's a # function argument when the char before the whitespace is legal in # a function name (alnum + _) and we're not starting a macro. Also ignore # pointers and references to arrays and functions coz they're too tricky: # we use a very simple way to recognize these: # " (something)(maybe-something)" or # " (something)(maybe-something," or # " (something)[something]" # Note that we assume the contents of [] to be short enough that # they'll never need to wrap. if ( # Ignore control structures. not Search(r'\b(if|for|while|switch|return|delete)\b', fncall) and # Ignore pointers/references to functions. not Search(r' \([^)]+\)\([^)]*(\)|,$)', fncall) and # Ignore pointers/references to arrays. not Search(r' \([^)]+\)\[[^\]]+\]', fncall)): if Search(r'\w\s*\(\s(?!\s*\\$)', fncall): # a ( used for a fn call error(filename, linenum, 'whitespace/parens', 4, 'Extra space after ( in function call') elif Search(r'\(\s+(?!(\s*\\)|\()', fncall): error(filename, linenum, 'whitespace/parens', 2, 'Extra space after (') if (Search(r'\w\s+\(', fncall) and not Search(r'#\s*define|typedef', fncall)): error(filename, linenum, 'whitespace/parens', 4, 'Extra space before ( in function call') # If the ) is followed only by a newline or a { + newline, assume it's # part of a control statement (if/while/etc), and don't complain if Search(r'[^)]\s+\)\s*[^{\s]', fncall): # If the closing parenthesis is preceded by only whitespaces, # try to give a more descriptive error message. if Search(r'^\s+\)', fncall): error(filename, linenum, 'whitespace/parens', 2, 'Closing ) should be moved to the previous line') else: error(filename, linenum, 'whitespace/parens', 2, 'Extra space before )')
[ "def", "CheckSpacingForFunctionCall", "(", "filename", ",", "line", ",", "linenum", ",", "error", ")", ":", "# Since function calls often occur inside if/for/while/switch", "# expressions - which have their own, more liberal conventions - we", "# first see if we should be looking inside ...
https://github.com/johmathe/shotdetect/blob/1ecf93a695c96fd7601a41ab5834f1117b9d7d50/tools/cpplint.py#L1488-L1551
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/idlelib/rpc.py
python
SocketIO.handle_EOF
(self)
action taken upon link being closed by peer
action taken upon link being closed by peer
[ "action", "taken", "upon", "link", "being", "closed", "by", "peer" ]
def handle_EOF(self): "action taken upon link being closed by peer" self.EOFhook() self.debug("handle_EOF") for key in self.cvars: cv = self.cvars[key] cv.acquire() self.responses[key] = ('EOF', None) cv.notify() cv.release() # call our (possibly overridden) exit function self.exithook()
[ "def", "handle_EOF", "(", "self", ")", ":", "self", ".", "EOFhook", "(", ")", "self", ".", "debug", "(", "\"handle_EOF\"", ")", "for", "key", "in", "self", ".", "cvars", ":", "cv", "=", "self", ".", "cvars", "[", "key", "]", "cv", ".", "acquire", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/idlelib/rpc.py#L471-L482
weolar/miniblink49
1c4678db0594a4abde23d3ebbcc7cd13c3170777
third_party/jinja2/parser.py
python
Parser.is_tuple_end
(self, extra_end_rules=None)
return False
Are we at the end of a tuple?
Are we at the end of a tuple?
[ "Are", "we", "at", "the", "end", "of", "a", "tuple?" ]
def is_tuple_end(self, extra_end_rules=None): """Are we at the end of a tuple?""" if self.stream.current.type in ('variable_end', 'block_end', 'rparen'): return True elif extra_end_rules is not None: return self.stream.current.test_any(extra_end_rules) return False
[ "def", "is_tuple_end", "(", "self", ",", "extra_end_rules", "=", "None", ")", ":", "if", "self", ".", "stream", ".", "current", ".", "type", "in", "(", "'variable_end'", ",", "'block_end'", ",", "'rparen'", ")", ":", "return", "True", "elif", "extra_end_ru...
https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/jinja2/parser.py#L98-L104
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/contrib/distributions/python/ops/uniform.py
python
Uniform.prob
(self, x, name="prob")
The PDF of observations in `x` under these Uniform distribution(s). Args: x: tensor of dtype `dtype`, must be broadcastable with `a` and `b`. name: The name to give this op. Returns: prob: tensor of dtype `dtype`, the prob values of `x`. If `x` is `nan`, will return `nan`.
The PDF of observations in `x` under these Uniform distribution(s).
[ "The", "PDF", "of", "observations", "in", "x", "under", "these", "Uniform", "distribution", "(", "s", ")", "." ]
def prob(self, x, name="prob"): """The PDF of observations in `x` under these Uniform distribution(s). Args: x: tensor of dtype `dtype`, must be broadcastable with `a` and `b`. name: The name to give this op. Returns: prob: tensor of dtype `dtype`, the prob values of `x`. If `x` is `nan`, will return `nan`. """ with ops.name_scope(self.name): with ops.op_scope([self.a, self.b, x], name): x = ops.convert_to_tensor(x, name="x") if x.dtype != self.dtype: raise TypeError("Input x dtype does not match dtype: %s vs. %s" % (x.dtype, self.dtype)) broadcasted_x = x * self._ones() return math_ops.select( math_ops.is_nan(broadcasted_x), broadcasted_x, math_ops.select( math_ops.logical_or(broadcasted_x < self.a, broadcasted_x > self.b), array_ops.zeros_like(broadcasted_x), (1.0 / self.range()) * array_ops.ones_like(broadcasted_x)))
[ "def", "prob", "(", "self", ",", "x", ",", "name", "=", "\"prob\"", ")", ":", "with", "ops", ".", "name_scope", "(", "self", ".", "name", ")", ":", "with", "ops", ".", "op_scope", "(", "[", "self", ".", "a", ",", "self", ".", "b", ",", "x", "...
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/contrib/distributions/python/ops/uniform.py#L142-L166
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/pycc/platform.py
python
Toolchain.get_python_include_dirs
(self)
return list(self._py_include_dirs) + self._math_info['include_dirs']
Get the include directories necessary to compile against the Python and Numpy C APIs.
Get the include directories necessary to compile against the Python and Numpy C APIs.
[ "Get", "the", "include", "directories", "necessary", "to", "compile", "against", "the", "Python", "and", "Numpy", "C", "APIs", "." ]
def get_python_include_dirs(self): """ Get the include directories necessary to compile against the Python and Numpy C APIs. """ return list(self._py_include_dirs) + self._math_info['include_dirs']
[ "def", "get_python_include_dirs", "(", "self", ")", ":", "return", "list", "(", "self", ".", "_py_include_dirs", ")", "+", "self", ".", "_math_info", "[", "'include_dirs'", "]" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/pycc/platform.py#L179-L184
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
Framework/PythonInterface/plugins/algorithms/RefinePowderDiffProfileSeq.py
python
RefineProfileParameters.calculate
(self, startx, endx)
return
Do Le bail calculation
Do Le bail calculation
[ "Do", "Le", "bail", "calculation" ]
def calculate(self, startx, endx): """ Do Le bail calculation """ if (self._inputIsSetup and self._outputIsSetup) is False: raise NotImplementedError("Either input or output is not setup: inputIsStepUp = %s, outputIsSetup = %s" % (str(self._inputIsSetup), str(self._outputIsSetup))) self.glog.information("**** Calculate: DataWorksapce = %s" % (str(self.datawsname))) self.glog.information("**** Fit range: %f, %f" % (startx, endx)) self.glog.information("**** Profile workspace = %s, Reflection workspace = %s" % ( self.inprofilewsname, self.inreflectionwsname)) api.LeBailFit( Function = 'Calculation', InputWorkspace = self.datawsname, OutputWorkspace = self.outwsname, InputParameterWorkspace = self.inprofilewsname, OutputParameterWorkspace= self.outprofilewsname, InputHKLWorkspace = self.inreflectionwsname, OutputPeaksWorkspace = self.outreflectionwsname, FitRegion = '%f, %f' % (startx, endx), PeakType = self.peaktype, BackgroundType = self.bkgdtype, UseInputPeakHeights = False, PeakRadius = '8', BackgroundParametersWorkspace = self.bkgdtablewsname ) return
[ "def", "calculate", "(", "self", ",", "startx", ",", "endx", ")", ":", "if", "(", "self", ".", "_inputIsSetup", "and", "self", ".", "_outputIsSetup", ")", "is", "False", ":", "raise", "NotImplementedError", "(", "\"Either input or output is not setup: inputIsStepU...
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/Framework/PythonInterface/plugins/algorithms/RefinePowderDiffProfileSeq.py#L831-L859
psnonis/FinBERT
c0c555d833a14e2316a3701e59c0b5156f804b4e
bert-gpu/tensorrt-inference-server/src/clients/python/__init__.py
python
ServerHealthContext.get_last_request_id
(self)
return self._last_request_id
Get the request ID of the most recent is_ready() or is_live() request. Returns ------- int The request ID, or None if a request has not yet been made or if the last request was not successful.
Get the request ID of the most recent is_ready() or is_live() request.
[ "Get", "the", "request", "ID", "of", "the", "most", "recent", "is_ready", "()", "or", "is_live", "()", "request", "." ]
def get_last_request_id(self): """Get the request ID of the most recent is_ready() or is_live() request. Returns ------- int The request ID, or None if a request has not yet been made or if the last request was not successful. """ return self._last_request_id
[ "def", "get_last_request_id", "(", "self", ")", ":", "return", "self", ".", "_last_request_id" ]
https://github.com/psnonis/FinBERT/blob/c0c555d833a14e2316a3701e59c0b5156f804b4e/bert-gpu/tensorrt-inference-server/src/clients/python/__init__.py#L383-L394
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py3/sklearn/metrics/_plot/roc_curve.py
python
RocCurveDisplay.plot
(self, ax=None, name=None, **kwargs)
return self
Plot visualization Extra keyword arguments will be passed to matplotlib's ``plot``. Parameters ---------- ax : matplotlib axes, default=None Axes object to plot on. If `None`, a new figure and axes is created. name : str, default=None Name of ROC Curve for labeling. If `None`, use the name of the estimator. Returns ------- display : :class:`~sklearn.metrics.plot.RocCurveDisplay` Object that stores computed values.
Plot visualization
[ "Plot", "visualization" ]
def plot(self, ax=None, name=None, **kwargs): """Plot visualization Extra keyword arguments will be passed to matplotlib's ``plot``. Parameters ---------- ax : matplotlib axes, default=None Axes object to plot on. If `None`, a new figure and axes is created. name : str, default=None Name of ROC Curve for labeling. If `None`, use the name of the estimator. Returns ------- display : :class:`~sklearn.metrics.plot.RocCurveDisplay` Object that stores computed values. """ check_matplotlib_support('RocCurveDisplay.plot') import matplotlib.pyplot as plt if ax is None: fig, ax = plt.subplots() name = self.estimator_name if name is None else name line_kwargs = { 'label': "{} (AUC = {:0.2f})".format(name, self.roc_auc) } line_kwargs.update(**kwargs) self.line_ = ax.plot(self.fpr, self.tpr, **line_kwargs)[0] ax.set_xlabel("False Positive Rate") ax.set_ylabel("True Positive Rate") ax.legend(loc='lower right') self.ax_ = ax self.figure_ = ax.figure return self
[ "def", "plot", "(", "self", ",", "ax", "=", "None", ",", "name", "=", "None", ",", "*", "*", "kwargs", ")", ":", "check_matplotlib_support", "(", "'RocCurveDisplay.plot'", ")", "import", "matplotlib", ".", "pyplot", "as", "plt", "if", "ax", "is", "None",...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/metrics/_plot/roc_curve.py#L63-L103
nasa/fprime
595cf3682d8365943d86c1a6fe7c78f0a116acf0
Autocoders/Python/src/fprime_ac/models/Port.py
python
Port.get_direction
(self)
return self.__direction
Return the direction for port.
Return the direction for port.
[ "Return", "the", "direction", "for", "port", "." ]
def get_direction(self): """ Return the direction for port. """ return self.__direction
[ "def", "get_direction", "(", "self", ")", ":", "return", "self", ".", "__direction" ]
https://github.com/nasa/fprime/blob/595cf3682d8365943d86c1a6fe7c78f0a116acf0/Autocoders/Python/src/fprime_ac/models/Port.py#L159-L163
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/telemetry/third_party/altgraph/altgraph/Graph.py
python
Graph.add_node
(self, node, node_data=None)
Adds a new node to the graph. Arbitrary data can be attached to the node via the node_data parameter. Adding the same node twice will be silently ignored. The node must be a hashable value.
Adds a new node to the graph. Arbitrary data can be attached to the node via the node_data parameter. Adding the same node twice will be silently ignored.
[ "Adds", "a", "new", "node", "to", "the", "graph", ".", "Arbitrary", "data", "can", "be", "attached", "to", "the", "node", "via", "the", "node_data", "parameter", ".", "Adding", "the", "same", "node", "twice", "will", "be", "silently", "ignored", "." ]
def add_node(self, node, node_data=None): """ Adds a new node to the graph. Arbitrary data can be attached to the node via the node_data parameter. Adding the same node twice will be silently ignored. The node must be a hashable value. """ # # the nodes will contain tuples that will store incoming edges, # outgoing edges and data # # index 0 -> incoming edges # index 1 -> outgoing edges if node in self.hidden_nodes: # Node is present, but hidden return if node not in self.nodes: self.nodes[node] = ([], [], node_data)
[ "def", "add_node", "(", "self", ",", "node", ",", "node_data", "=", "None", ")", ":", "#", "# the nodes will contain tuples that will store incoming edges,", "# outgoing edges and data", "#", "# index 0 -> incoming edges", "# index 1 -> outgoing edges", "if", "node", "in", ...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/third_party/altgraph/altgraph/Graph.py#L64-L84
apache/incubator-mxnet
f03fb23f1d103fec9541b5ae59ee06b1734a51d9
python/mxnet/ndarray/numpy/_op.py
python
row_stack
(arrays)
return _api_internal.vstack(*arrays)
r"""Stack arrays in sequence vertically (row wise). This is equivalent to concatenation along the first axis after 1-D arrays of shape `(N,)` have been reshaped to `(1,N)`. Rebuilds arrays divided by `vsplit`. This function makes most sense for arrays with up to 3 dimensions. For instance, for pixel-data with a height (first axis), width (second axis), and r/g/b channels (third axis). The functions `concatenate` and `stack` provide more general stacking and concatenation operations. Parameters ---------- tup : sequence of ndarrays The arrays must have the same shape along all but the first axis. 1-D arrays must have the same length. Returns ------- stacked : ndarray The array formed by stacking the given arrays, will be at least 2-D. Examples -------- >>> a = np.array([1, 2, 3]) >>> b = np.array([2, 3, 4]) >>> np.vstack((a, b)) array([[1., 2., 3.], [2., 3., 4.]]) >>> a = np.array([[1], [2], [3]]) >>> b = np.array([[2], [3], [4]]) >>> np.vstack((a, b)) array([[1.], [2.], [3.], [2.], [3.], [4.]])
r"""Stack arrays in sequence vertically (row wise). This is equivalent to concatenation along the first axis after 1-D arrays of shape `(N,)` have been reshaped to `(1,N)`. Rebuilds arrays divided by `vsplit`. This function makes most sense for arrays with up to 3 dimensions. For instance, for pixel-data with a height (first axis), width (second axis), and r/g/b channels (third axis). The functions `concatenate` and `stack` provide more general stacking and concatenation operations. Parameters ---------- tup : sequence of ndarrays The arrays must have the same shape along all but the first axis. 1-D arrays must have the same length. Returns ------- stacked : ndarray The array formed by stacking the given arrays, will be at least 2-D. Examples -------- >>> a = np.array([1, 2, 3]) >>> b = np.array([2, 3, 4]) >>> np.vstack((a, b)) array([[1., 2., 3.], [2., 3., 4.]]) >>> a = np.array([[1], [2], [3]]) >>> b = np.array([[2], [3], [4]]) >>> np.vstack((a, b)) array([[1.], [2.], [3.], [2.], [3.], [4.]])
[ "r", "Stack", "arrays", "in", "sequence", "vertically", "(", "row", "wise", ")", ".", "This", "is", "equivalent", "to", "concatenation", "along", "the", "first", "axis", "after", "1", "-", "D", "arrays", "of", "shape", "(", "N", ")", "have", "been", "r...
def row_stack(arrays): r"""Stack arrays in sequence vertically (row wise). This is equivalent to concatenation along the first axis after 1-D arrays of shape `(N,)` have been reshaped to `(1,N)`. Rebuilds arrays divided by `vsplit`. This function makes most sense for arrays with up to 3 dimensions. For instance, for pixel-data with a height (first axis), width (second axis), and r/g/b channels (third axis). The functions `concatenate` and `stack` provide more general stacking and concatenation operations. Parameters ---------- tup : sequence of ndarrays The arrays must have the same shape along all but the first axis. 1-D arrays must have the same length. Returns ------- stacked : ndarray The array formed by stacking the given arrays, will be at least 2-D. Examples -------- >>> a = np.array([1, 2, 3]) >>> b = np.array([2, 3, 4]) >>> np.vstack((a, b)) array([[1., 2., 3.], [2., 3., 4.]]) >>> a = np.array([[1], [2], [3]]) >>> b = np.array([[2], [3], [4]]) >>> np.vstack((a, b)) array([[1.], [2.], [3.], [2.], [3.], [4.]]) """ def get_list(arrays): if not hasattr(arrays, '__getitem__') and hasattr(arrays, '__iter__'): raise ValueError("expected iterable for arrays but got {}".format(type(arrays))) return [arr for arr in arrays] arrays = get_list(arrays) return _api_internal.vstack(*arrays)
[ "def", "row_stack", "(", "arrays", ")", ":", "def", "get_list", "(", "arrays", ")", ":", "if", "not", "hasattr", "(", "arrays", ",", "'__getitem__'", ")", "and", "hasattr", "(", "arrays", ",", "'__iter__'", ")", ":", "raise", "ValueError", "(", "\"expect...
https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/ndarray/numpy/_op.py#L4797-L4838
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqt/mantidqt/widgets/messagedisplay.py
python
MessageDisplay.ReadSettingSafely
(self,qsettings,key,default,type)
Reads a value from qsettings, returning the default if the value is missing or the type is wrong :param qsettings: the qsettings object :param key: the key to read :param default: the default value :param type: the type to check the returned value for :return: The value from qsettings, or default if the value is missing or the type is wrong
Reads a value from qsettings, returning the default if the value is missing or the type is wrong :param qsettings: the qsettings object :param key: the key to read :param default: the default value :param type: the type to check the returned value for :return: The value from qsettings, or default if the value is missing or the type is wrong
[ "Reads", "a", "value", "from", "qsettings", "returning", "the", "default", "if", "the", "value", "is", "missing", "or", "the", "type", "is", "wrong", ":", "param", "qsettings", ":", "the", "qsettings", "object", ":", "param", "key", ":", "the", "key", "t...
def ReadSettingSafely(self,qsettings,key,default,type): """ Reads a value from qsettings, returning the default if the value is missing or the type is wrong :param qsettings: the qsettings object :param key: the key to read :param default: the default value :param type: the type to check the returned value for :return: The value from qsettings, or default if the value is missing or the type is wrong """ try: settingValue = qsettings.value(key, default) return settingValue if isinstance(settingValue, type) else default except TypeError: return default
[ "def", "ReadSettingSafely", "(", "self", ",", "qsettings", ",", "key", ",", "default", ",", "type", ")", ":", "try", ":", "settingValue", "=", "qsettings", ".", "value", "(", "key", ",", "default", ")", "return", "settingValue", "if", "isinstance", "(", ...
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqt/mantidqt/widgets/messagedisplay.py#L49-L62
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/botocore/docs/bcdoc/restdoc.py
python
DocumentStructure.delete_section
(self, name)
Delete a section
Delete a section
[ "Delete", "a", "section" ]
def delete_section(self, name): """Delete a section""" del self._structure[name]
[ "def", "delete_section", "(", "self", ",", "name", ")", ":", "del", "self", ".", "_structure", "[", "name", "]" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/botocore/docs/bcdoc/restdoc.py#L189-L191
vector-of-bool/dds
b35d87245e8174506df780fd9fe112d89351a85b
tools/dds_ci/main.py
python
parse_argv
(argv: Sequence[str])
return make_argparser().parse_args(argv)
Parse the given dds-ci command-line argument list
Parse the given dds-ci command-line argument list
[ "Parse", "the", "given", "dds", "-", "ci", "command", "-", "line", "argument", "list" ]
def parse_argv(argv: Sequence[str]) -> CommandArguments: """Parse the given dds-ci command-line argument list""" return make_argparser().parse_args(argv)
[ "def", "parse_argv", "(", "argv", ":", "Sequence", "[", "str", "]", ")", "->", "CommandArguments", ":", "return", "make_argparser", "(", ")", ".", "parse_args", "(", "argv", ")" ]
https://github.com/vector-of-bool/dds/blob/b35d87245e8174506df780fd9fe112d89351a85b/tools/dds_ci/main.py#L71-L73
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/genericpath.py
python
_splitext
(p, sep, altsep, extsep)
return p, p[:0]
Split the extension from a pathname. Extension is everything from the last dot to the end, ignoring leading dots. Returns "(root, ext)"; ext may be empty.
Split the extension from a pathname.
[ "Split", "the", "extension", "from", "a", "pathname", "." ]
def _splitext(p, sep, altsep, extsep): """Split the extension from a pathname. Extension is everything from the last dot to the end, ignoring leading dots. Returns "(root, ext)"; ext may be empty.""" # NOTE: This code must work for text and bytes strings. sepIndex = p.rfind(sep) if altsep: altsepIndex = p.rfind(altsep) sepIndex = max(sepIndex, altsepIndex) dotIndex = p.rfind(extsep) if dotIndex > sepIndex: # skip all leading dots filenameIndex = sepIndex + 1 while filenameIndex < dotIndex: if p[filenameIndex:filenameIndex+1] != extsep: return p[:dotIndex], p[dotIndex:] filenameIndex += 1 return p, p[:0]
[ "def", "_splitext", "(", "p", ",", "sep", ",", "altsep", ",", "extsep", ")", ":", "# NOTE: This code must work for text and bytes strings.", "sepIndex", "=", "p", ".", "rfind", "(", "sep", ")", "if", "altsep", ":", "altsepIndex", "=", "p", ".", "rfind", "(",...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/genericpath.py#L121-L142
OSGeo/gdal
3748fc4ba4fba727492774b2b908a2130c864a83
swig/python/osgeo/gdal.py
python
GDALBuildVRTOptions.__init__
(self, *args)
r"""__init__(GDALBuildVRTOptions self, char ** options) -> GDALBuildVRTOptions
r"""__init__(GDALBuildVRTOptions self, char ** options) -> GDALBuildVRTOptions
[ "r", "__init__", "(", "GDALBuildVRTOptions", "self", "char", "**", "options", ")", "-", ">", "GDALBuildVRTOptions" ]
def __init__(self, *args): r"""__init__(GDALBuildVRTOptions self, char ** options) -> GDALBuildVRTOptions""" _gdal.GDALBuildVRTOptions_swiginit(self, _gdal.new_GDALBuildVRTOptions(*args))
[ "def", "__init__", "(", "self", ",", "*", "args", ")", ":", "_gdal", ".", "GDALBuildVRTOptions_swiginit", "(", "self", ",", "_gdal", ".", "new_GDALBuildVRTOptions", "(", "*", "args", ")", ")" ]
https://github.com/OSGeo/gdal/blob/3748fc4ba4fba727492774b2b908a2130c864a83/swig/python/osgeo/gdal.py#L4339-L4341
RamadhanAmizudin/malware
2c6c53c8b0d556f5d8078d6ca0fc4448f4697cf1
Fuzzbunch/fuzzbunch/pyreadline/rlmain.py
python
Readline.clear_history
(self)
Clear readline history
Clear readline history
[ "Clear", "readline", "history" ]
def clear_history(self): '''Clear readline history''' self._history.clear_history()
[ "def", "clear_history", "(", "self", ")", ":", "self", ".", "_history", ".", "clear_history", "(", ")" ]
https://github.com/RamadhanAmizudin/malware/blob/2c6c53c8b0d556f5d8078d6ca0fc4448f4697cf1/Fuzzbunch/fuzzbunch/pyreadline/rlmain.py#L174-L176
OSGeo/gdal
3748fc4ba4fba727492774b2b908a2130c864a83
swig/python/osgeo/gdal.py
python
MultiDimInfoOptions
(options=None, detailed=False, array=None, arrayoptions=None, limit=None, as_text=False)
return GDALMultiDimInfoOptions(new_options), as_text
Create a MultiDimInfoOptions() object that can be passed to gdal.MultiDimInfo() options can be be an array of strings, a string or let empty and filled from other keywords.
Create a MultiDimInfoOptions() object that can be passed to gdal.MultiDimInfo() options can be be an array of strings, a string or let empty and filled from other keywords.
[ "Create", "a", "MultiDimInfoOptions", "()", "object", "that", "can", "be", "passed", "to", "gdal", ".", "MultiDimInfo", "()", "options", "can", "be", "be", "an", "array", "of", "strings", "a", "string", "or", "let", "empty", "and", "filled", "from", "other...
def MultiDimInfoOptions(options=None, detailed=False, array=None, arrayoptions=None, limit=None, as_text=False): """ Create a MultiDimInfoOptions() object that can be passed to gdal.MultiDimInfo() options can be be an array of strings, a string or let empty and filled from other keywords.""" options = [] if options is None else options if isinstance(options, str): new_options = ParseCommandLine(options) else: new_options = options if detailed: new_options += ['-detailed'] if array: new_options += ['-array', array] if limit: new_options += ['-limit', str(limit)] if arrayoptions: for option in arrayoptions: new_options += ['-arrayoption', option] return GDALMultiDimInfoOptions(new_options), as_text
[ "def", "MultiDimInfoOptions", "(", "options", "=", "None", ",", "detailed", "=", "False", ",", "array", "=", "None", ",", "arrayoptions", "=", "None", ",", "limit", "=", "None", ",", "as_text", "=", "False", ")", ":", "options", "=", "[", "]", "if", ...
https://github.com/OSGeo/gdal/blob/3748fc4ba4fba727492774b2b908a2130c864a83/swig/python/osgeo/gdal.py#L251-L271
LLNL/lbann
26083e6c86050302ce33148aea70f62e61cacb92
model_zoo/models/python/common.py
python
bindir
()
return b
Returns the directory that contains the lbann executable. This may be specified on the command line via the --bindir=<string> option; else, returns the relative directory: '../../..build/<hostname()>.llnl.gov/model_zoo
Returns the directory that contains the lbann executable. This may be specified on the command line via the --bindir=<string> option; else, returns the relative directory: '../../..build/<hostname()>.llnl.gov/model_zoo
[ "Returns", "the", "directory", "that", "contains", "the", "lbann", "executable", ".", "This", "may", "be", "specified", "on", "the", "command", "line", "via", "the", "--", "bindir", "=", "<string", ">", "option", ";", "else", "returns", "the", "relative", ...
def bindir() : '''Returns the directory that contains the lbann executable. This may be specified on the command line via the --bindir=<string> option; else, returns the relative directory: '../../..build/<hostname()>.llnl.gov/model_zoo ''' b = '../../../build/' + hostname() + '.llnl.gov/model_zoo' for n in sys.argv : if n.find('--bindir=') != -1 : t = n.split('=') b = t[0][2:] return b
[ "def", "bindir", "(", ")", ":", "b", "=", "'../../../build/'", "+", "hostname", "(", ")", "+", "'.llnl.gov/model_zoo'", "for", "n", "in", "sys", ".", "argv", ":", "if", "n", ".", "find", "(", "'--bindir='", ")", "!=", "-", "1", ":", "t", "=", "n", ...
https://github.com/LLNL/lbann/blob/26083e6c86050302ce33148aea70f62e61cacb92/model_zoo/models/python/common.py#L57-L67
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
third_party/protobuf/python/google/protobuf/internal/encoder.py
python
_TagSize
(field_number)
return _VarintSize(wire_format.PackTag(field_number, 0))
Returns the number of bytes required to serialize a tag with this field number.
Returns the number of bytes required to serialize a tag with this field number.
[ "Returns", "the", "number", "of", "bytes", "required", "to", "serialize", "a", "tag", "with", "this", "field", "number", "." ]
def _TagSize(field_number): """Returns the number of bytes required to serialize a tag with this field number.""" # Just pass in type 0, since the type won't affect the tag+type size. return _VarintSize(wire_format.PackTag(field_number, 0))
[ "def", "_TagSize", "(", "field_number", ")", ":", "# Just pass in type 0, since the type won't affect the tag+type size.", "return", "_VarintSize", "(", "wire_format", ".", "PackTag", "(", "field_number", ",", "0", ")", ")" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/protobuf/python/google/protobuf/internal/encoder.py#L108-L112
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
build/plugins/pybuild.py
python
onpy_srcs
(unit, *args)
@usage PY_SRCS({| CYTHON_C} { | TOP_LEVEL | NAMESPACE ns} Files...) PY_SRCS() - is rule to build extended versions of Python interpreters and containing all application code in its executable file. It can be used to collect only the executables but not shared libraries, and, in particular, not to collect the modules that are imported using import directive. The main disadvantage is the lack of IDE support; There is also no readline yet. The application can be collect from any of the sources from which the C library, and with the help of PY_SRCS .py , .pyx,.proto and .swg files. At the same time extensions for Python on C language generating from .pyx and .swg, will be registered in Python's as built-in modules, and sources on .py are stored as static data: when the interpreter starts, the initialization code will add a custom loader of these modules to sys.meta_path. By default .pyx files are collected as C++-extensions. To collect them as C (similar to BUILDWITH_CYTHON_C, but with the ability to specify namespace), you must specify the Directive CYTHON_C. Building with pyx automatically registers modules, you do not need to call PY_REGISTER for them __init__.py never required, but if present (and specified in PY_SRCS), it will be imported when you import package modules with __init__.py Oh. Example of library declaration with PY_SRCS(): PY2_LIBRARY(mymodule) PY_SRCS(a.py sub/dir/b.py e.proto sub/dir/f.proto c.pyx sub/dir/d.pyx g.swg sub/dir/h.swg) END() PY_REGISTER honors Python2 and Python3 differences and adjusts itself to Python version of a current module Documentation: https://wiki.yandex-team.ru/arcadia/python/pysrcs/#modulipylibrarypy3libraryimakrospysrcs
@usage PY_SRCS({| CYTHON_C} { | TOP_LEVEL | NAMESPACE ns} Files...)
[ "@usage", "PY_SRCS", "(", "{", "|", "CYTHON_C", "}", "{", "|", "TOP_LEVEL", "|", "NAMESPACE", "ns", "}", "Files", "...", ")" ]
def onpy_srcs(unit, *args): """ @usage PY_SRCS({| CYTHON_C} { | TOP_LEVEL | NAMESPACE ns} Files...) PY_SRCS() - is rule to build extended versions of Python interpreters and containing all application code in its executable file. It can be used to collect only the executables but not shared libraries, and, in particular, not to collect the modules that are imported using import directive. The main disadvantage is the lack of IDE support; There is also no readline yet. The application can be collect from any of the sources from which the C library, and with the help of PY_SRCS .py , .pyx,.proto and .swg files. At the same time extensions for Python on C language generating from .pyx and .swg, will be registered in Python's as built-in modules, and sources on .py are stored as static data: when the interpreter starts, the initialization code will add a custom loader of these modules to sys.meta_path. By default .pyx files are collected as C++-extensions. To collect them as C (similar to BUILDWITH_CYTHON_C, but with the ability to specify namespace), you must specify the Directive CYTHON_C. Building with pyx automatically registers modules, you do not need to call PY_REGISTER for them __init__.py never required, but if present (and specified in PY_SRCS), it will be imported when you import package modules with __init__.py Oh. Example of library declaration with PY_SRCS(): PY2_LIBRARY(mymodule) PY_SRCS(a.py sub/dir/b.py e.proto sub/dir/f.proto c.pyx sub/dir/d.pyx g.swg sub/dir/h.swg) END() PY_REGISTER honors Python2 and Python3 differences and adjusts itself to Python version of a current module Documentation: https://wiki.yandex-team.ru/arcadia/python/pysrcs/#modulipylibrarypy3libraryimakrospysrcs """ # Each file arg must either be a path, or "${...}/buildpath=modname", where # "${...}/buildpath" part will be used as a file source in a future macro, # and "modname" will be used as a module name. upath = unit.path()[3:] py3 = is_py3(unit) py_main_only = unit.get('PROCESS_PY_MAIN_ONLY') with_py = not unit.get('PYBUILD_NO_PY') with_pyc = not unit.get('PYBUILD_NO_PYC') in_proto_library = unit.get('PY_PROTO') or unit.get('PY3_PROTO') venv = unit.get(YA_IDE_VENV_VAR) need_gazetteer_peerdir = False trim = 0 if not upath.startswith('contrib/tools/python') and not upath.startswith('library/python/runtime') and unit.get('NO_PYTHON_INCLS') != 'yes': unit.onpeerdir(['contrib/libs/python']) unit_needs_main = unit.get('MODULE_TYPE') in ('PROGRAM', 'DLL') if unit_needs_main: py_program(unit, py3) py_namespace_value = unit.get('PY_NAMESPACE_VALUE') if py_namespace_value == ".": ns = "" else: ns = (unit.get('PY_NAMESPACE_VALUE') or upath.replace('/', '.')) + '.' cython_coverage = unit.get('CYTHON_COVERAGE') == 'yes' cythonize_py = False optimize_proto = unit.get('OPTIMIZE_PY_PROTOS_FLAG') == 'yes' cython_directives = [] if cython_coverage: cython_directives += ['-X', 'linetrace=True'] pyxs_c = [] pyxs_c_h = [] pyxs_c_api_h = [] pyxs_cpp = [] pyxs = pyxs_cpp swigs_c = [] swigs_cpp = [] swigs = swigs_cpp pys = [] protos = [] evs = [] fbss = [] py_namespaces = {} dump_dir = unit.get('PYTHON_BUILD_DUMP_DIR') dump_output = None if dump_dir: import thread pid = os.getpid() tid = thread.get_ident() dump_name = '{}-{}.dump'.format(pid, tid) dump_output = open(os.path.join(dump_dir, dump_name), 'a') args = iter(args) for arg in args: # Namespace directives. if arg == 'TOP_LEVEL': ns = '' elif arg == 'NAMESPACE': ns = next(args) + '.' # Cython directives. elif arg == 'CYTHON_C': pyxs = pyxs_c elif arg == 'CYTHON_C_H': pyxs = pyxs_c_h elif arg == 'CYTHON_C_API_H': pyxs = pyxs_c_api_h elif arg == 'CYTHON_CPP': pyxs = pyxs_cpp elif arg == 'CYTHON_DIRECTIVE': cython_directives += ['-X', next(args)] elif arg == 'CYTHONIZE_PY': cythonize_py = True # SWIG. elif arg == 'SWIG_C': swigs = swigs_c elif arg == 'SWIG_CPP': swigs = swigs_cpp # Unsupported but legal PROTO_LIBRARY arguments. elif arg == 'GLOBAL' or not in_proto_library and arg.endswith('.gztproto'): pass elif arg == '_MR': # GLOB support: convert arcadia-root-relative paths to module-relative # srcs are assumed to start with ${ARCADIA_ROOT} trim = len(unit.path()) + 14 # Sources. else: main_mod = arg == 'MAIN' if main_mod: arg = next(args) if '=' in arg: main_py = False path, mod = arg.split('=', 1) else: if trim: arg = arg[trim:] if arg.endswith('.gztproto'): need_gazetteer_peerdir = True path = '{}.proto'.format(arg[:-9]) else: path = arg main_py = (path == '__main__.py' or path.endswith('/__main__.py')) if not py3 and unit_needs_main and main_py: mod = '__main__' else: if arg.startswith('../'): ymake.report_configure_error('PY_SRCS item starts with "../": {!r}'.format(arg)) if arg.startswith('/'): ymake.report_configure_error('PY_SRCS item starts with "/": {!r}'.format(arg)) continue mod_name = stripext(arg).replace('/', '.') if py3 and path.endswith('.py') and is_extended_source_search_enabled(path, unit): # Dig out real path from the file path. Unit.path is not enough because of SRCDIR and ADDINCL root_rel_path = rootrel_arc_src(path, unit) mod_root_path = root_rel_path[:-(len(path) + 1)] py_namespaces.setdefault(mod_root_path, set()).add(ns if ns else '.') mod = ns + mod_name if main_mod: py_main(unit, mod + ":main") elif py3 and unit_needs_main and main_py: py_main(unit, mod) if py_main_only: continue if py3 and mod == '__main__': ymake.report_configure_error('TOP_LEVEL __main__.py is not allowed in PY3_PROGRAM') pathmod = (path, mod) if dump_output is not None: dump_output.write('{path}\t{module}\n'.format(path=rootrel_arc_src(path, unit), module=mod)) if path.endswith('.py'): if cythonize_py: pyxs.append(pathmod) else: pys.append(pathmod) elif path.endswith('.pyx'): pyxs.append(pathmod) elif path.endswith('.proto'): protos.append(pathmod) elif path.endswith('.ev'): evs.append(pathmod) elif path.endswith('.swg'): swigs.append(pathmod) # Allow pyi files in PY_SRCS for autocomplete in IDE, but skip it during building elif path.endswith('.pyi'): pass elif path.endswith('.fbs'): fbss.append(pathmod) else: ymake.report_configure_error('in PY_SRCS: unrecognized arg {!r}'.format(path)) if dump_output is not None: dump_output.close() if pyxs: files2res = set() # Include map stores files which were included in the processing pyx file, # to be able to find source code of the included file inside generated file # for currently processing pyx file. include_map = collections.defaultdict(set) if cython_coverage: def process_pyx(filename, path, out_suffix, noext): # skip generated files if not is_arc_src(path, unit): return # source file files2res.add((filename, path)) # generated if noext: files2res.add((os.path.splitext(filename)[0] + out_suffix, os.path.splitext(path)[0] + out_suffix)) else: files2res.add((filename + out_suffix, path + out_suffix)) # used includes for entry in parse_pyx_includes(filename, path, unit.resolve('$S')): files2res.add(entry) include_arc_rel = entry[0] include_map[filename].add(include_arc_rel) else: def process_pyx(filename, path, out_suffix, noext): pass for pyxs, cython, out_suffix, noext in [ (pyxs_c, unit.on_buildwith_cython_c_dep, ".c", False), (pyxs_c_h, unit.on_buildwith_cython_c_h, ".c", True), (pyxs_c_api_h, unit.on_buildwith_cython_c_api_h, ".c", True), (pyxs_cpp, unit.on_buildwith_cython_cpp_dep, ".cpp", False), ]: for path, mod in pyxs: filename = rootrel_arc_src(path, unit) cython_args = [path] dep = path if path.endswith('.py'): pxd = '/'.join(mod.split('.')) + '.pxd' if unit.resolve_arc_path(pxd): dep = pxd cython_args.append(dep) cython_args += [ '--module-name', mod, '--init-suffix', mangle(mod), '--source-root', '${ARCADIA_ROOT}', # set arcadia root relative __file__ for generated modules '-X', 'set_initial_path={}'.format(filename), ] + cython_directives cython(cython_args) py_register(unit, mod, py3) process_pyx(filename, path, out_suffix, noext) if files2res: # Compile original and generated sources into target for proper cython coverage calculation unit.onresource_files([x for name, path in files2res for x in ('DEST', name, path)]) if include_map: data = [] prefix = 'resfs/cython/include' for line in sorted('{}/{}={}'.format(prefix, filename, ':'.join(sorted(files))) for filename, files in include_map.iteritems()): data += ['-', line] unit.onresource(data) for swigs, on_swig_python in [ (swigs_c, unit.on_swig_python_c), (swigs_cpp, unit.on_swig_python_cpp), ]: for path, mod in swigs: # Make output prefix basename match swig module name. prefix = path[:path.rfind('/') + 1] + mod.rsplit('.', 1)[-1] swg_py = '{}/{}/{}.py'.format('${ARCADIA_BUILD_ROOT}', upath, prefix) on_swig_python([path, prefix]) onpy_register(unit, mod + '_swg') onpy_srcs(unit, swg_py + '=' + mod) if pys: pys_seen = set() pys_dups = {m for _, m in pys if (m in pys_seen or pys_seen.add(m))} if pys_dups: ymake.report_configure_error('Duplicate(s) is found in the PY_SRCS macro: {}'.format(pys_dups)) res = [] if py3: mod_list_md5 = md5() for path, mod in pys: mod_list_md5.update(mod) if not (venv and is_extended_source_search_enabled(path, unit)): dest = 'py/' + mod.replace('.', '/') + '.py' if with_py: res += ['DEST', dest, path] if with_pyc: root_rel_path = rootrel_arc_src(path, unit) dst = path + uniq_suffix(path, unit) unit.on_py3_compile_bytecode([root_rel_path + '-', path, dst]) res += ['DEST', dest + '.yapyc3', dst + '.yapyc3'] if py_namespaces: # Note: Add md5 to key to prevent key collision if two or more PY_SRCS() used in the same ya.make ns_res = [] for path, ns in sorted(py_namespaces.items()): key = '{}/{}/{}'.format(PY_NAMESPACE_PREFIX, mod_list_md5.hexdigest(), path) namespaces = ':'.join(sorted(ns)) ns_res += ['-', '{}="{}"'.format(key, namespaces)] unit.onresource(ns_res) unit.onresource_files(res) add_python_lint_checks(unit, 3, [path for path, mod in pys] + unit.get(['_PY_EXTRA_LINT_FILES_VALUE']).split()) else: for path, mod in pys: root_rel_path = rootrel_arc_src(path, unit) if with_py: key = '/py_modules/' + mod res += [ path, key, '-', 'resfs/src/{}={}'.format(key, root_rel_path), ] if with_pyc: src = unit.resolve_arc_path(path) or path dst = path + uniq_suffix(path, unit) unit.on_py_compile_bytecode([root_rel_path + '-', src, dst]) res += [dst + '.yapyc', '/py_code/' + mod] unit.onresource(res) add_python_lint_checks(unit, 2, [path for path, mod in pys] + unit.get(['_PY_EXTRA_LINT_FILES_VALUE']).split()) use_vanilla_protoc = unit.get('USE_VANILLA_PROTOC') == 'yes' if use_vanilla_protoc: cpp_runtime_path = 'contrib/libs/protobuf_std' py_runtime_path = 'contrib/python/protobuf_std' builtin_proto_path = cpp_runtime_path + '/' + BUILTIN_PROTO else: cpp_runtime_path = 'contrib/libs/protobuf' py_runtime_path = 'contrib/python/protobuf' builtin_proto_path = cpp_runtime_path + '/' + BUILTIN_PROTO if protos: if not upath.startswith(py_runtime_path) and not upath.startswith(builtin_proto_path): unit.onpeerdir(py_runtime_path) unit.onpeerdir(unit.get("PY_PROTO_DEPS").split()) proto_paths = [path for path, mod in protos] unit.on_generate_py_protos_internal(proto_paths) unit.onpy_srcs([ pb2_arg(py_suf, path, mod, unit) for path, mod in protos for py_suf in unit.get("PY_PROTO_SUFFIXES").split() ]) if optimize_proto and need_gazetteer_peerdir: unit.onpeerdir(['kernel/gazetteer/proto']) if evs: unit.onpeerdir([cpp_runtime_path]) unit.on_generate_py_evs_internal([path for path, mod in evs]) unit.onpy_srcs([ev_arg(path, mod, unit) for path, mod in evs]) if fbss: unit.onpeerdir(unit.get('_PY_FBS_DEPS').split()) pysrc_base_name = listid(fbss) unit.onfbs_to_pysrc([pysrc_base_name] + [path for path, _ in fbss]) unit.onsrcs(['GLOBAL', '{}.fbs.pysrc'.format(pysrc_base_name)])
[ "def", "onpy_srcs", "(", "unit", ",", "*", "args", ")", ":", "# Each file arg must either be a path, or \"${...}/buildpath=modname\", where", "# \"${...}/buildpath\" part will be used as a file source in a future macro,", "# and \"modname\" will be used as a module name.", "upath", "=", ...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/build/plugins/pybuild.py#L171-L522
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/grid.py
python
Grid.SelectAll
(*args, **kwargs)
return _grid.Grid_SelectAll(*args, **kwargs)
SelectAll(self)
SelectAll(self)
[ "SelectAll", "(", "self", ")" ]
def SelectAll(*args, **kwargs): """SelectAll(self)""" return _grid.Grid_SelectAll(*args, **kwargs)
[ "def", "SelectAll", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_grid", ".", "Grid_SelectAll", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/grid.py#L2041-L2043
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/numpy/py2/numpy/core/fromnumeric.py
python
sort
(a, axis=-1, kind='quicksort', order=None)
return a
Return a sorted copy of an array. Parameters ---------- a : array_like Array to be sorted. axis : int or None, optional Axis along which to sort. If None, the array is flattened before sorting. The default is -1, which sorts along the last axis. kind : {'quicksort', 'mergesort', 'heapsort', 'stable'}, optional Sorting algorithm. Default is 'quicksort'. order : str or list of str, optional When `a` is an array with fields defined, this argument specifies which fields to compare first, second, etc. A single field can be specified as a string, and not all fields need be specified, but unspecified fields will still be used, in the order in which they come up in the dtype, to break ties. Returns ------- sorted_array : ndarray Array of the same type and shape as `a`. See Also -------- ndarray.sort : Method to sort an array in-place. argsort : Indirect sort. lexsort : Indirect stable sort on multiple keys. searchsorted : Find elements in a sorted array. partition : Partial sort. Notes ----- The various sorting algorithms are characterized by their average speed, worst case performance, work space size, and whether they are stable. A stable sort keeps items with the same key in the same relative order. The three available algorithms have the following properties: =========== ======= ============= ============ ======== kind speed worst case work space stable =========== ======= ============= ============ ======== 'quicksort' 1 O(n^2) 0 no 'mergesort' 2 O(n*log(n)) ~n/2 yes 'heapsort' 3 O(n*log(n)) 0 no =========== ======= ============= ============ ======== All the sort algorithms make temporary copies of the data when sorting along any but the last axis. Consequently, sorting along the last axis is faster and uses less space than sorting along any other axis. The sort order for complex numbers is lexicographic. If both the real and imaginary parts are non-nan then the order is determined by the real parts except when they are equal, in which case the order is determined by the imaginary parts. Previous to numpy 1.4.0 sorting real and complex arrays containing nan values led to undefined behaviour. In numpy versions >= 1.4.0 nan values are sorted to the end. The extended sort order is: * Real: [R, nan] * Complex: [R + Rj, R + nanj, nan + Rj, nan + nanj] where R is a non-nan real value. Complex values with the same nan placements are sorted according to the non-nan part if it exists. Non-nan values are sorted as before. .. versionadded:: 1.12.0 quicksort has been changed to an introsort which will switch heapsort when it does not make enough progress. This makes its worst case O(n*log(n)). 'stable' automatically choses the best stable sorting algorithm for the data type being sorted. It is currently mapped to merge sort. Examples -------- >>> a = np.array([[1,4],[3,1]]) >>> np.sort(a) # sort along the last axis array([[1, 4], [1, 3]]) >>> np.sort(a, axis=None) # sort the flattened array array([1, 1, 3, 4]) >>> np.sort(a, axis=0) # sort along the first axis array([[1, 1], [3, 4]]) Use the `order` keyword to specify a field to use when sorting a structured array: >>> dtype = [('name', 'S10'), ('height', float), ('age', int)] >>> values = [('Arthur', 1.8, 41), ('Lancelot', 1.9, 38), ... ('Galahad', 1.7, 38)] >>> a = np.array(values, dtype=dtype) # create a structured array >>> np.sort(a, order='height') # doctest: +SKIP array([('Galahad', 1.7, 38), ('Arthur', 1.8, 41), ('Lancelot', 1.8999999999999999, 38)], dtype=[('name', '|S10'), ('height', '<f8'), ('age', '<i4')]) Sort by age, then height if ages are equal: >>> np.sort(a, order=['age', 'height']) # doctest: +SKIP array([('Galahad', 1.7, 38), ('Lancelot', 1.8999999999999999, 38), ('Arthur', 1.8, 41)], dtype=[('name', '|S10'), ('height', '<f8'), ('age', '<i4')])
Return a sorted copy of an array.
[ "Return", "a", "sorted", "copy", "of", "an", "array", "." ]
def sort(a, axis=-1, kind='quicksort', order=None): """ Return a sorted copy of an array. Parameters ---------- a : array_like Array to be sorted. axis : int or None, optional Axis along which to sort. If None, the array is flattened before sorting. The default is -1, which sorts along the last axis. kind : {'quicksort', 'mergesort', 'heapsort', 'stable'}, optional Sorting algorithm. Default is 'quicksort'. order : str or list of str, optional When `a` is an array with fields defined, this argument specifies which fields to compare first, second, etc. A single field can be specified as a string, and not all fields need be specified, but unspecified fields will still be used, in the order in which they come up in the dtype, to break ties. Returns ------- sorted_array : ndarray Array of the same type and shape as `a`. See Also -------- ndarray.sort : Method to sort an array in-place. argsort : Indirect sort. lexsort : Indirect stable sort on multiple keys. searchsorted : Find elements in a sorted array. partition : Partial sort. Notes ----- The various sorting algorithms are characterized by their average speed, worst case performance, work space size, and whether they are stable. A stable sort keeps items with the same key in the same relative order. The three available algorithms have the following properties: =========== ======= ============= ============ ======== kind speed worst case work space stable =========== ======= ============= ============ ======== 'quicksort' 1 O(n^2) 0 no 'mergesort' 2 O(n*log(n)) ~n/2 yes 'heapsort' 3 O(n*log(n)) 0 no =========== ======= ============= ============ ======== All the sort algorithms make temporary copies of the data when sorting along any but the last axis. Consequently, sorting along the last axis is faster and uses less space than sorting along any other axis. The sort order for complex numbers is lexicographic. If both the real and imaginary parts are non-nan then the order is determined by the real parts except when they are equal, in which case the order is determined by the imaginary parts. Previous to numpy 1.4.0 sorting real and complex arrays containing nan values led to undefined behaviour. In numpy versions >= 1.4.0 nan values are sorted to the end. The extended sort order is: * Real: [R, nan] * Complex: [R + Rj, R + nanj, nan + Rj, nan + nanj] where R is a non-nan real value. Complex values with the same nan placements are sorted according to the non-nan part if it exists. Non-nan values are sorted as before. .. versionadded:: 1.12.0 quicksort has been changed to an introsort which will switch heapsort when it does not make enough progress. This makes its worst case O(n*log(n)). 'stable' automatically choses the best stable sorting algorithm for the data type being sorted. It is currently mapped to merge sort. Examples -------- >>> a = np.array([[1,4],[3,1]]) >>> np.sort(a) # sort along the last axis array([[1, 4], [1, 3]]) >>> np.sort(a, axis=None) # sort the flattened array array([1, 1, 3, 4]) >>> np.sort(a, axis=0) # sort along the first axis array([[1, 1], [3, 4]]) Use the `order` keyword to specify a field to use when sorting a structured array: >>> dtype = [('name', 'S10'), ('height', float), ('age', int)] >>> values = [('Arthur', 1.8, 41), ('Lancelot', 1.9, 38), ... ('Galahad', 1.7, 38)] >>> a = np.array(values, dtype=dtype) # create a structured array >>> np.sort(a, order='height') # doctest: +SKIP array([('Galahad', 1.7, 38), ('Arthur', 1.8, 41), ('Lancelot', 1.8999999999999999, 38)], dtype=[('name', '|S10'), ('height', '<f8'), ('age', '<i4')]) Sort by age, then height if ages are equal: >>> np.sort(a, order=['age', 'height']) # doctest: +SKIP array([('Galahad', 1.7, 38), ('Lancelot', 1.8999999999999999, 38), ('Arthur', 1.8, 41)], dtype=[('name', '|S10'), ('height', '<f8'), ('age', '<i4')]) """ if axis is None: # flatten returns (1, N) for np.matrix, so always use the last axis a = asanyarray(a).flatten() axis = -1 else: a = asanyarray(a).copy(order="K") a.sort(axis=axis, kind=kind, order=order) return a
[ "def", "sort", "(", "a", ",", "axis", "=", "-", "1", ",", "kind", "=", "'quicksort'", ",", "order", "=", "None", ")", ":", "if", "axis", "is", "None", ":", "# flatten returns (1, N) for np.matrix, so always use the last axis", "a", "=", "asanyarray", "(", "a...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py2/numpy/core/fromnumeric.py#L816-L935
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/klampt/robotsim.py
python
Simulator.fakeSimulate
(self, t: float)
return _robotsim.Simulator_fakeSimulate(self, t)
r""" Advances a faked simulation by time t, and updates the world model from the faked simulation state. Args: t (float)
r""" Advances a faked simulation by time t, and updates the world model from the faked simulation state.
[ "r", "Advances", "a", "faked", "simulation", "by", "time", "t", "and", "updates", "the", "world", "model", "from", "the", "faked", "simulation", "state", "." ]
def fakeSimulate(self, t: float) ->None: r""" Advances a faked simulation by time t, and updates the world model from the faked simulation state. Args: t (float) """ return _robotsim.Simulator_fakeSimulate(self, t)
[ "def", "fakeSimulate", "(", "self", ",", "t", ":", "float", ")", "->", "None", ":", "return", "_robotsim", ".", "Simulator_fakeSimulate", "(", "self", ",", "t", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/robotsim.py#L7854-L7862
microsoft/DirectXShaderCompiler
8348ff8d9e0287610ba05d3a828e10af981a1c05
tools/clang/bindings/python/clang/cindex.py
python
Cursor.get_tokens
(self)
return TokenGroup.get_tokens(self._tu, self.extent)
Obtain Token instances formulating that compose this Cursor. This is a generator for Token instances. It returns all tokens which occupy the extent this cursor occupies.
Obtain Token instances formulating that compose this Cursor.
[ "Obtain", "Token", "instances", "formulating", "that", "compose", "this", "Cursor", "." ]
def get_tokens(self): """Obtain Token instances formulating that compose this Cursor. This is a generator for Token instances. It returns all tokens which occupy the extent this cursor occupies. """ return TokenGroup.get_tokens(self._tu, self.extent)
[ "def", "get_tokens", "(", "self", ")", ":", "return", "TokenGroup", ".", "get_tokens", "(", "self", ".", "_tu", ",", "self", ".", "extent", ")" ]
https://github.com/microsoft/DirectXShaderCompiler/blob/8348ff8d9e0287610ba05d3a828e10af981a1c05/tools/clang/bindings/python/clang/cindex.py#L1471-L1477
SoarGroup/Soar
a1c5e249499137a27da60533c72969eef3b8ab6b
scons/scons-local-4.1.0/SCons/Node/__init__.py
python
Node.has_explicit_builder
(self)
Return whether this Node has an explicit builder This allows an internal Builder created by SCons to be marked non-explicit, so that it can be overridden by an explicit builder that the user supplies (the canonical example being directories).
Return whether this Node has an explicit builder
[ "Return", "whether", "this", "Node", "has", "an", "explicit", "builder" ]
def has_explicit_builder(self): """Return whether this Node has an explicit builder This allows an internal Builder created by SCons to be marked non-explicit, so that it can be overridden by an explicit builder that the user supplies (the canonical example being directories).""" try: return self.is_explicit except AttributeError: self.is_explicit = None return self.is_explicit
[ "def", "has_explicit_builder", "(", "self", ")", ":", "try", ":", "return", "self", ".", "is_explicit", "except", "AttributeError", ":", "self", ".", "is_explicit", "=", "None", "return", "self", ".", "is_explicit" ]
https://github.com/SoarGroup/Soar/blob/a1c5e249499137a27da60533c72969eef3b8ab6b/scons/scons-local-4.1.0/SCons/Node/__init__.py#L904-L915
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/tensorflow/python/ops/io_ops.py
python
_RestoreShape
(op)
return [tensor_shape.unknown_shape()]
Shape function for Restore op.
Shape function for Restore op.
[ "Shape", "function", "for", "Restore", "op", "." ]
def _RestoreShape(op): """Shape function for Restore op.""" # Validate input shapes. unused_file_pattern = op.inputs[0].get_shape().merge_with( tensor_shape.scalar()) unused_tensor_name = op.inputs[1].get_shape().merge_with( tensor_shape.scalar()) return [tensor_shape.unknown_shape()]
[ "def", "_RestoreShape", "(", "op", ")", ":", "# Validate input shapes.", "unused_file_pattern", "=", "op", ".", "inputs", "[", "0", "]", ".", "get_shape", "(", ")", ".", "merge_with", "(", "tensor_shape", ".", "scalar", "(", ")", ")", "unused_tensor_name", "...
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/ops/io_ops.py#L207-L214
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/dataview.py
python
DataViewListCtrl.SetItemData
(*args, **kwargs)
return _dataview.DataViewListCtrl_SetItemData(*args, **kwargs)
SetItemData(self, DataViewItem item, UIntPtr data)
SetItemData(self, DataViewItem item, UIntPtr data)
[ "SetItemData", "(", "self", "DataViewItem", "item", "UIntPtr", "data", ")" ]
def SetItemData(*args, **kwargs): """SetItemData(self, DataViewItem item, UIntPtr data)""" return _dataview.DataViewListCtrl_SetItemData(*args, **kwargs)
[ "def", "SetItemData", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_dataview", ".", "DataViewListCtrl_SetItemData", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/dataview.py#L2200-L2202
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/ops/gradients_impl.py
python
gradients
(ys, xs, grad_ys=None, name="gradients", colocate_gradients_with_ops=False, gate_gradients=False, aggregation_method=None, stop_gradients=None)
return [_GetGrad(grads, x) for x in xs]
Constructs symbolic derivatives of sum of `ys` w.r.t. x in `xs`. `ys` and `xs` are each a `Tensor` or a list of tensors. `grad_ys` is a list of `Tensor`, holding the gradients received by the `ys`. The list must be the same length as `ys`. `gradients()` adds ops to the graph to output the derivatives of `ys` with respect to `xs`. It returns a list of `Tensor` of length `len(xs)` where each tensor is the `sum(dy/dx)` for y in `ys`. `grad_ys` is a list of tensors of the same length as `ys` that holds the initial gradients for each y in `ys`. When `grad_ys` is None, we fill in a tensor of '1's of the shape of y for each y in `ys`. A user can provide their own initial `grad_ys` to compute the derivatives using a different initial gradient for each y (e.g., if one wanted to weight the gradient differently for each value in each y). `stop_gradients` is a `Tensor` or a list of tensors to be considered constant with respect to all `xs`. These tensors will not be backpropagated through, as though they had been explicitly disconnected using `stop_gradient`. Among other things, this allows computation of partial derivatives as opposed to total derivatives. For example: a = tf.constant(0.) b = 2 * a g = tf.gradients(a + b, [a, b], stop_gradients=[a, b]) Here the partial derivatives `g` evaluate to `[1.0, 1.0]`, compared to the total derivatives `tf.gradients(a + b, [a, b])`, which take into account the influence of `a` on `b` and evaluate to `[3.0, 1.0]`. Note that the above is equivalent to: a = tf.stop_gradient(tf.constant(0.)) b = tf.stop_gradient(2 * a) g = tf.gradients(a + b, [a, b]) `stop_gradients` provides a way of stopping gradient after the graph has already been constructed, as compared to `tf.stop_gradient` which is used during graph construction. When the two approaches are combined, backpropagation stops at both `tf.stop_gradient` nodes and nodes in `stop_gradients`, whichever is encountered first. Args: ys: A `Tensor` or list of tensors to be differentiated. xs: A `Tensor` or list of tensors to be used for differentiation. grad_ys: Optional. A `Tensor` or list of tensors the same size as `ys` and holding the gradients computed for each y in `ys`. name: Optional name to use for grouping all the gradient ops together. defaults to 'gradients'. colocate_gradients_with_ops: If True, try colocating gradients with the corresponding op. gate_gradients: If True, add a tuple around the gradients returned for an operations. This avoids some race conditions. aggregation_method: Specifies the method used to combine gradient terms. Accepted values are constants defined in the class `AggregationMethod`. stop_gradients: Optional. A `Tensor` or list of tensors not to differentiate through. Returns: A list of `sum(dy/dx)` for each x in `xs`. Raises: LookupError: if one of the operations between `x` and `y` does not have a registered gradient function. ValueError: if the arguments are invalid. RuntimeError: if called in Eager mode.
Constructs symbolic derivatives of sum of `ys` w.r.t. x in `xs`.
[ "Constructs", "symbolic", "derivatives", "of", "sum", "of", "ys", "w", ".", "r", ".", "t", ".", "x", "in", "xs", "." ]
def gradients(ys, xs, grad_ys=None, name="gradients", colocate_gradients_with_ops=False, gate_gradients=False, aggregation_method=None, stop_gradients=None): """Constructs symbolic derivatives of sum of `ys` w.r.t. x in `xs`. `ys` and `xs` are each a `Tensor` or a list of tensors. `grad_ys` is a list of `Tensor`, holding the gradients received by the `ys`. The list must be the same length as `ys`. `gradients()` adds ops to the graph to output the derivatives of `ys` with respect to `xs`. It returns a list of `Tensor` of length `len(xs)` where each tensor is the `sum(dy/dx)` for y in `ys`. `grad_ys` is a list of tensors of the same length as `ys` that holds the initial gradients for each y in `ys`. When `grad_ys` is None, we fill in a tensor of '1's of the shape of y for each y in `ys`. A user can provide their own initial `grad_ys` to compute the derivatives using a different initial gradient for each y (e.g., if one wanted to weight the gradient differently for each value in each y). `stop_gradients` is a `Tensor` or a list of tensors to be considered constant with respect to all `xs`. These tensors will not be backpropagated through, as though they had been explicitly disconnected using `stop_gradient`. Among other things, this allows computation of partial derivatives as opposed to total derivatives. For example: a = tf.constant(0.) b = 2 * a g = tf.gradients(a + b, [a, b], stop_gradients=[a, b]) Here the partial derivatives `g` evaluate to `[1.0, 1.0]`, compared to the total derivatives `tf.gradients(a + b, [a, b])`, which take into account the influence of `a` on `b` and evaluate to `[3.0, 1.0]`. Note that the above is equivalent to: a = tf.stop_gradient(tf.constant(0.)) b = tf.stop_gradient(2 * a) g = tf.gradients(a + b, [a, b]) `stop_gradients` provides a way of stopping gradient after the graph has already been constructed, as compared to `tf.stop_gradient` which is used during graph construction. When the two approaches are combined, backpropagation stops at both `tf.stop_gradient` nodes and nodes in `stop_gradients`, whichever is encountered first. Args: ys: A `Tensor` or list of tensors to be differentiated. xs: A `Tensor` or list of tensors to be used for differentiation. grad_ys: Optional. A `Tensor` or list of tensors the same size as `ys` and holding the gradients computed for each y in `ys`. name: Optional name to use for grouping all the gradient ops together. defaults to 'gradients'. colocate_gradients_with_ops: If True, try colocating gradients with the corresponding op. gate_gradients: If True, add a tuple around the gradients returned for an operations. This avoids some race conditions. aggregation_method: Specifies the method used to combine gradient terms. Accepted values are constants defined in the class `AggregationMethod`. stop_gradients: Optional. A `Tensor` or list of tensors not to differentiate through. Returns: A list of `sum(dy/dx)` for each x in `xs`. Raises: LookupError: if one of the operations between `x` and `y` does not have a registered gradient function. ValueError: if the arguments are invalid. RuntimeError: if called in Eager mode. """ if context.in_eager_mode(): raise RuntimeError("tf.gradients not supported in EAGER mode. Use " "functions in tf.contrib.eager.backprop instead.") ys = _AsList(ys) xs = _AsList(xs) stop_gradients = [] if stop_gradients is None else _AsList(stop_gradients) if grad_ys is None: grad_ys = [None] * len(ys) else: grad_ys = _AsList(grad_ys) with ops.name_scope( name, "gradients", list(ys) + list(xs) + list(stop_gradients) + list(grad_ys)) as grad_scope: ys = ops.convert_n_to_tensor_or_indexed_slices(ys, name="y") xs = [x.handle if isinstance(x, resource_variable_ops.ResourceVariable) else x for x in xs] xs = ops.internal_convert_n_to_tensor_or_indexed_slices(xs, name="x", as_ref=True) grad_ys = _DefaultGradYs(grad_ys, ys, colocate_gradients_with_ops) # The approach we take here is as follows: Create a list of all ops in the # subgraph between the ys and xs. Visit these ops in reverse order of ids # to ensure that when we visit an op the gradients w.r.t its outputs have # been collected. Then aggregate these gradients if needed, call the op's # gradient function, and add the generated gradients to the gradients for # its input. # Initialize the pending count for ops in the connected subgraph from ys # to the xs. if len(ys) > 1: ys = [array_ops.identity(y) if y.consumers() else y for y in ys] to_ops = [t.op for t in ys] from_ops = [t.op for t in xs] stop_gradient_ops = [t.op for t in stop_gradients] pending_count, loop_state = _PendingCount(ops.get_default_graph(), to_ops, from_ops, colocate_gradients_with_ops) # Iterate over the collected ops. # # grads: op => list of gradients received on each output endpoint of the # op. The gradients for each endpoint are initially collected as a list. # When it is time to call the op's gradient function, for each endpoint we # aggregate the list of received gradients into a Add() Operation if there # is more than one. grads = {} # Add the initial gradients for the ys. for y, grad_y in zip(ys, grad_ys): _SetGrad(grads, y, grad_y) # Initialize queue with to_ops. queue = collections.deque() # Add the ops in 'to_ops' into the queue. to_ops_set = set() for op in to_ops: # 'ready' handles the case where one output gradient relies on # another output's gradient. # pylint: disable=protected-access ready = (pending_count[op._id] == 0) if ready and op._id not in to_ops_set: to_ops_set.add(op._id) queue.append(op) # pylint: enable=protected-access if loop_state: loop_exits = loop_state.ProcessUnusedLoopExits(pending_count, to_ops_set) for y in loop_exits: if _IsTrainable(y): _SetGrad(grads, y, loop_state.ZerosLikeForExit(y)) queue.append(y.op) stop_ops = _StopOps(from_ops, stop_gradient_ops, pending_count) while queue: # generate gradient subgraph for op. op = queue.popleft() with _maybe_colocate_with(op, colocate_gradients_with_ops): if loop_state: loop_state.EnterGradWhileContext(op, before=True) out_grads = _AggregatedGrads(grads, op, loop_state, aggregation_method) if loop_state: loop_state.ExitGradWhileContext(op, before=True) grad_fn = None # pylint: disable=protected-access func_call = None is_func_call = ops.get_default_graph()._is_function(op.type) has_out_grads = any(isinstance(g, ops.Tensor) or g for g in out_grads) if has_out_grads and (op._id not in stop_ops): if is_func_call: func_call = ops.get_default_graph()._get_function(op.type) grad_fn = func_call.python_grad_func # pylint: enable=protected-access else: # A grad_fn must be defined, either as a function or as None # for ops that do not have gradients. try: grad_fn = ops.get_gradient_function(op) except LookupError: raise LookupError( "No gradient defined for operation '%s' (op type: %s)" % (op.name, op.type)) if loop_state: loop_state.EnterGradWhileContext(op, before=False) if (grad_fn or is_func_call) and has_out_grads: # NOTE: If _AggregatedGrads didn't compute a value for the i'th # output, it means that the cost does not depend on output[i], # therefore dC/doutput[i] is 0. for i, out_grad in enumerate(out_grads): if (not isinstance(out_grad, ops.Tensor) and not out_grad) and _IsTrainable(op.outputs[i]): # Only floating-point outputs get a zero gradient. Gradient # functions should ignore the gradient for other outputs. # TODO(apassos) gradients of resource handles might be an # issue here because of zeros. if loop_state: out_grads[i] = loop_state.ZerosLike(op, i) else: out_grads[i] = control_flow_ops.ZerosLikeOutsideLoop(op, i) with ops.name_scope(op.name + "_grad"): # pylint: disable=protected-access with ops.get_default_graph()._original_op(op): # pylint: enable=protected-access if grad_fn: # If grad_fn was found, do not use SymbolicGradient even for # functions. in_grads = _MaybeCompile( grad_scope, op, func_call, lambda: grad_fn(op, *out_grads)) else: # For function call ops, we add a 'SymbolicGradient' # node to the graph to compute gradients. in_grads = _MaybeCompile( grad_scope, op, func_call, lambda: _SymGrad(op, out_grads)) in_grads = _AsList(in_grads) _VerifyGeneratedGradients(in_grads, op) if gate_gradients and len( [x for x in in_grads if x is not None]) > 1: in_grads = control_flow_ops.tuple(in_grads) _LogOpGradients(op, out_grads, in_grads) else: # If no grad_fn is defined or none of out_grads is available, # just propagate a list of None backwards. in_grads = [None] * len(op.inputs) for i, (t_in, in_grad) in enumerate(zip(op.inputs, in_grads)): if in_grad is not None: if (isinstance(in_grad, ops.Tensor) and t_in.dtype != dtypes.resource): try: in_grad.set_shape(t_in.get_shape()) except ValueError: raise ValueError( "Incompatible shapes between op input and calculated " "input gradient. Forward operation: %s. Input index: %d. " "Original input shape: %s. " "Calculated input gradient shape: %s" % (op.name, i, t_in.shape, in_grad.shape)) _SetGrad(grads, t_in, in_grad) if loop_state: loop_state.ExitGradWhileContext(op, before=False) # Update pending count for the inputs of op and enqueue ready ops. _UpdatePendingAndEnqueueReady(grads, op, queue, pending_count, loop_state) if loop_state: loop_state.PostProcessing() return [_GetGrad(grads, x) for x in xs]
[ "def", "gradients", "(", "ys", ",", "xs", ",", "grad_ys", "=", "None", ",", "name", "=", "\"gradients\"", ",", "colocate_gradients_with_ops", "=", "False", ",", "gate_gradients", "=", "False", ",", "aggregation_method", "=", "None", ",", "stop_gradients", "=",...
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/ops/gradients_impl.py#L396-L640
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/coverage/coverage/collector.py
python
Collector.tracer_name
(self)
return self._trace_class.__name__
Return the class name of the tracer we're using.
Return the class name of the tracer we're using.
[ "Return", "the", "class", "name", "of", "the", "tracer", "we", "re", "using", "." ]
def tracer_name(self): """Return the class name of the tracer we're using.""" return self._trace_class.__name__
[ "def", "tracer_name", "(", "self", ")", ":", "return", "self", ".", "_trace_class", ".", "__name__" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/coverage/coverage/collector.py#L139-L141
turtlecoin/turtlecoin
02ee0f0551f4552e7d2fd48df23f4b4ff84f4dd8
external/rocksdb/tools/block_cache_analyzer/block_cache_pysim.py
python
Cache.access
(self, trace_record)
Access a trace record. The simulator calls this function to access a trace record.
Access a trace record. The simulator calls this function to access a trace record.
[ "Access", "a", "trace", "record", ".", "The", "simulator", "calls", "this", "function", "to", "access", "a", "trace", "record", "." ]
def access(self, trace_record): """ Access a trace record. The simulator calls this function to access a trace record. """ assert self.used_size <= self.cache_size if ( self.enable_cache_row_key > 0 and trace_record.caller == 1 and trace_record.key_id != 0 and trace_record.get_id != 0 ): # This is a get request. self._access_row(trace_record) return is_hit = self._access_kv( trace_record, self.block_key(trace_record), trace_record.block_id, trace_record.block_size, trace_record.no_insert, ) self._update_stats( trace_record.access_time, is_hit=is_hit, miss_bytes=trace_record.block_size )
[ "def", "access", "(", "self", ",", "trace_record", ")", ":", "assert", "self", ".", "used_size", "<=", "self", ".", "cache_size", "if", "(", "self", ".", "enable_cache_row_key", ">", "0", "and", "trace_record", ".", "caller", "==", "1", "and", "trace_recor...
https://github.com/turtlecoin/turtlecoin/blob/02ee0f0551f4552e7d2fd48df23f4b4ff84f4dd8/external/rocksdb/tools/block_cache_analyzer/block_cache_pysim.py#L724-L748
emsec/hal
58d15b895723b8527302b740582613b82cb9aa80
tools/skywater_to_liberty.py
python
convert_latch_block
(lib_json_data)
return "latch (\"IQ\", \"IQ_N\") {{\n{}}}\n".format(indent_block(latch_inner))
Generate a string in liberty format that represents a latch block of a certain cell, contained in a .lib.json file. :param lib_json_data: json data of a .lib.json file :returns: The latch block string. Empty string if no latch information were found.
Generate a string in liberty format that represents a latch block of a certain cell, contained in a .lib.json file.
[ "Generate", "a", "string", "in", "liberty", "format", "that", "represents", "a", "latch", "block", "of", "a", "certain", "cell", "contained", "in", "a", ".", "lib", ".", "json", "file", "." ]
def convert_latch_block(lib_json_data): """ Generate a string in liberty format that represents a latch block of a certain cell, contained in a .lib.json file. :param lib_json_data: json data of a .lib.json file :returns: The latch block string. Empty string if no latch information were found. """ if lib_json_data is None: return "" if not ("latch,IQ,IQ_N" in lib_json_data): return "" latch_data = lib_json_data["latch,IQ,IQ_N"] latch_inner = "" for k in ["clear", "data_in", "preset", "enable"]: if k in latch_data: latch_inner += "{}: \"{}\";\n".format(k, latch_data[k]) for k in ["clear_preset_var1", "clear_preset_var2"]: if k in latch_data: latch_inner += "{}: {};\n".format(k, latch_data[k]) return "latch (\"IQ\", \"IQ_N\") {{\n{}}}\n".format(indent_block(latch_inner))
[ "def", "convert_latch_block", "(", "lib_json_data", ")", ":", "if", "lib_json_data", "is", "None", ":", "return", "\"\"", "if", "not", "(", "\"latch,IQ,IQ_N\"", "in", "lib_json_data", ")", ":", "return", "\"\"", "latch_data", "=", "lib_json_data", "[", "\"latch,...
https://github.com/emsec/hal/blob/58d15b895723b8527302b740582613b82cb9aa80/tools/skywater_to_liberty.py#L76-L98
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqt/mantidqt/widgets/superplot/presenter.py
python
SuperplotPresenter.on_del_button_clicked
(self, ws_name=None)
Triggered when the del button is pressed. This function removes the selected workspace from the selection list.
Triggered when the del button is pressed. This function removes the selected workspace from the selection list.
[ "Triggered", "when", "the", "del", "button", "is", "pressed", ".", "This", "function", "removes", "the", "selected", "workspace", "from", "the", "selection", "list", "." ]
def on_del_button_clicked(self, ws_name=None): """ Triggered when the del button is pressed. This function removes the selected workspace from the selection list. """ selection = self._view.get_selection() if ws_name is None: selected_workspaces = selection.copy() else: selected_workspaces = [ws_name] for selected_workspace in selected_workspaces: self._model.del_workspace(selected_workspace) self._update_list() if not self._model.is_bin_mode() and not self._model.is_spectrum_mode(): mode = self._view.get_mode() self._view.set_available_modes([self.SPECTRUM_MODE_TEXT, self.BIN_MODE_TEXT]) self._view.set_mode(mode) self._view.set_selection(selection) if all(name in selected_workspaces for name in selection.keys()): self._update_spectrum_slider() self._update_plot()
[ "def", "on_del_button_clicked", "(", "self", ",", "ws_name", "=", "None", ")", ":", "selection", "=", "self", ".", "_view", ".", "get_selection", "(", ")", "if", "ws_name", "is", "None", ":", "selected_workspaces", "=", "selection", ".", "copy", "(", ")", ...
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqt/mantidqt/widgets/superplot/presenter.py#L266-L287