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
grpc/grpc
27bc6fe7797e43298dc931b96dc57322d0852a9f
src/python/grpcio/grpc/beta/implementations.py
python
secure_channel
(host, port, channel_credentials)
return Channel(channel)
Creates a secure Channel to a remote host. Args: host: The name of the remote host to which to connect. port: The port of the remote host to which to connect. If None only the 'host' part will be used. channel_credentials: A ChannelCredentials. Returns: A secure Channel to the remote host through which RPCs may be conducted.
Creates a secure Channel to a remote host.
[ "Creates", "a", "secure", "Channel", "to", "a", "remote", "host", "." ]
def secure_channel(host, port, channel_credentials): """Creates a secure Channel to a remote host. Args: host: The name of the remote host to which to connect. port: The port of the remote host to which to connect. If None only the 'host' part will be used. channel_credentials: A ChannelCredentials. Returns: A secure Channel to the remote host through which RPCs may be conducted. """ channel = grpc.secure_channel( host if port is None else '%s:%d' % (host, port), channel_credentials) return Channel(channel)
[ "def", "secure_channel", "(", "host", ",", "port", ",", "channel_credentials", ")", ":", "channel", "=", "grpc", ".", "secure_channel", "(", "host", "if", "port", "is", "None", "else", "'%s:%d'", "%", "(", "host", ",", "port", ")", ",", "channel_credential...
https://github.com/grpc/grpc/blob/27bc6fe7797e43298dc931b96dc57322d0852a9f/src/python/grpcio/grpc/beta/implementations.py#L119-L133
vslavik/poedit
f7a9daa0a10037e090aa0a86f5ce0f24ececdf6a
deps/boost/tools/build/src/build/property_set.py
python
PropertySet.add_raw
(self, properties)
return self.add (create (properties))
Creates a new property set containing the properties in this one, plus the ones passed as argument.
Creates a new property set containing the properties in this one, plus the ones passed as argument.
[ "Creates", "a", "new", "property", "set", "containing", "the", "properties", "in", "this", "one", "plus", "the", "ones", "passed", "as", "argument", "." ]
def add_raw (self, properties): """ Creates a new property set containing the properties in this one, plus the ones passed as argument. """ return self.add (create (properties))
[ "def", "add_raw", "(", "self", ",", "properties", ")", ":", "return", "self", ".", "add", "(", "create", "(", "properties", ")", ")" ]
https://github.com/vslavik/poedit/blob/f7a9daa0a10037e090aa0a86f5ce0f24ececdf6a/deps/boost/tools/build/src/build/property_set.py#L450-L454
ufal/udpipe
e51f02d2744cdfd4a29efc1320644ea04d535f0b
doc/t2t_docsys/txt2tags.py
python
ConfigMaster._check_target
(self)
Checks if the target is already defined. If not, do it
Checks if the target is already defined. If not, do it
[ "Checks", "if", "the", "target", "is", "already", "defined", ".", "If", "not", "do", "it" ]
def _check_target(self): "Checks if the target is already defined. If not, do it" if not self.target: self.target = self.find_value('target')
[ "def", "_check_target", "(", "self", ")", ":", "if", "not", "self", ".", "target", ":", "self", ".", "target", "=", "self", ".", "find_value", "(", "'target'", ")" ]
https://github.com/ufal/udpipe/blob/e51f02d2744cdfd4a29efc1320644ea04d535f0b/doc/t2t_docsys/txt2tags.py#L2739-L2742
weolar/miniblink49
1c4678db0594a4abde23d3ebbcc7cd13c3170777
v8_5_1/tools/stats-viewer.py
python
SharedDataAccess.IntAt
(self, index)
return result
Return the little-endian 32-byte int at the specified byte index.
Return the little-endian 32-byte int at the specified byte index.
[ "Return", "the", "little", "-", "endian", "32", "-", "byte", "int", "at", "the", "specified", "byte", "index", "." ]
def IntAt(self, index): """Return the little-endian 32-byte int at the specified byte index.""" word_str = self.data[index:index+4] result, = struct.unpack("I", word_str) return result
[ "def", "IntAt", "(", "self", ",", "index", ")", ":", "word_str", "=", "self", ".", "data", "[", "index", ":", "index", "+", "4", "]", "result", ",", "=", "struct", ".", "unpack", "(", "\"I\"", ",", "word_str", ")", "return", "result" ]
https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/v8_5_1/tools/stats-viewer.py#L316-L320
qgis/QGIS
15a77662d4bb712184f6aa60d0bd663010a76a75
python/plugins/processing/tools/general.py
python
runAndLoadResults
(algOrName, parameters, feedback=None, context=None)
return Processing.runAlgorithm(alg, parameters=parameters, onFinish=handleAlgorithmResults, feedback=feedback, context=context)
Executes given algorithm and load its results into the current QGIS project when possible. :param algOrName: Either an instance of an algorithm, or an algorithm's ID :param parameters: Algorithm parameters dictionary :param feedback: Processing feedback object :param context: Processing context object :returns algorithm results as a dictionary, or None if execution failed :rtype: Union[dict, None]
Executes given algorithm and load its results into the current QGIS project when possible.
[ "Executes", "given", "algorithm", "and", "load", "its", "results", "into", "the", "current", "QGIS", "project", "when", "possible", "." ]
def runAndLoadResults(algOrName, parameters, feedback=None, context=None): """ Executes given algorithm and load its results into the current QGIS project when possible. :param algOrName: Either an instance of an algorithm, or an algorithm's ID :param parameters: Algorithm parameters dictionary :param feedback: Processing feedback object :param context: Processing context object :returns algorithm results as a dictionary, or None if execution failed :rtype: Union[dict, None] """ if isinstance(algOrName, QgsProcessingAlgorithm): alg = algOrName else: alg = QgsApplication.processingRegistry().createAlgorithmById(algOrName) # output destination parameters to point to current project for param in alg.parameterDefinitions(): if not param.name() in parameters: continue if isinstance(param, (QgsProcessingParameterFeatureSink, QgsProcessingParameterVectorDestination, QgsProcessingParameterRasterDestination)): p = parameters[param.name()] if not isinstance(p, QgsProcessingOutputLayerDefinition): parameters[param.name()] = QgsProcessingOutputLayerDefinition(p, QgsProject.instance()) else: p.destinationProject = QgsProject.instance() parameters[param.name()] = p return Processing.runAlgorithm(alg, parameters=parameters, onFinish=handleAlgorithmResults, feedback=feedback, context=context)
[ "def", "runAndLoadResults", "(", "algOrName", ",", "parameters", ",", "feedback", "=", "None", ",", "context", "=", "None", ")", ":", "if", "isinstance", "(", "algOrName", ",", "QgsProcessingAlgorithm", ")", ":", "alg", "=", "algOrName", "else", ":", "alg", ...
https://github.com/qgis/QGIS/blob/15a77662d4bb712184f6aa60d0bd663010a76a75/python/plugins/processing/tools/general.py#L119-L152
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/idlelib/configHelpSourceEdit.py
python
GetHelpSourceDialog.MenuOk
(self)
return menuOk
Simple validity check for a sensible menu item name
Simple validity check for a sensible menu item name
[ "Simple", "validity", "check", "for", "a", "sensible", "menu", "item", "name" ]
def MenuOk(self): "Simple validity check for a sensible menu item name" menuOk = True menu = self.menu.get() menu.strip() if not menu: tkMessageBox.showerror(title='Menu Item Error', message='No menu item specified', parent=self) self.entryMenu.focus_set() menuOk = False elif len(menu) > 30: tkMessageBox.showerror(title='Menu Item Error', message='Menu item too long:' '\nLimit 30 characters.', parent=self) self.entryMenu.focus_set() menuOk = False return menuOk
[ "def", "MenuOk", "(", "self", ")", ":", "menuOk", "=", "True", "menu", "=", "self", ".", "menu", ".", "get", "(", ")", "menu", ".", "strip", "(", ")", "if", "not", "menu", ":", "tkMessageBox", ".", "showerror", "(", "title", "=", "'Menu Item Error'",...
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/idlelib/configHelpSourceEdit.py#L99-L117
rodeofx/OpenWalter
6116fbe3f04f1146c854afbfbdbe944feaee647e
walter/maya/scripts/walterPanel/walterMayaTraverser.py
python
WalterMayaImplementation.saveMaterials
(self, origin, fileName=None)
return pm.walterSaveShaders(node=origin, file=fileName)
Save the materials to the external file.
Save the materials to the external file.
[ "Save", "the", "materials", "to", "the", "external", "file", "." ]
def saveMaterials(self, origin, fileName=None): """Save the materials to the external file.""" fileName = self.getFileDialog(fileName) if not fileName: return if not pm.pluginInfo('walterMtoaConnection', query=True, loaded=True): pm.loadPlugin('walterMtoaConnection', quiet=True) return pm.walterSaveShaders(node=origin, file=fileName)
[ "def", "saveMaterials", "(", "self", ",", "origin", ",", "fileName", "=", "None", ")", ":", "fileName", "=", "self", ".", "getFileDialog", "(", "fileName", ")", "if", "not", "fileName", ":", "return", "if", "not", "pm", ".", "pluginInfo", "(", "'walterMt...
https://github.com/rodeofx/OpenWalter/blob/6116fbe3f04f1146c854afbfbdbe944feaee647e/walter/maya/scripts/walterPanel/walterMayaTraverser.py#L588-L598
apache/singa
93fd9da72694e68bfe3fb29d0183a65263d238a1
python/singa/tensor.py
python
uniform
(low, high, t)
return t
Generate values following a Uniform distribution. Args: low (float): the lower bound high (float): the higher bound t (Tensor): the results are put into t Returns: t
Generate values following a Uniform distribution.
[ "Generate", "values", "following", "a", "Uniform", "distribution", "." ]
def uniform(low, high, t): '''Generate values following a Uniform distribution. Args: low (float): the lower bound high (float): the higher bound t (Tensor): the results are put into t Returns: t ''' singa.Uniform(float(low), float(high), t.data) return t
[ "def", "uniform", "(", "low", ",", "high", ",", "t", ")", ":", "singa", ".", "Uniform", "(", "float", "(", "low", ")", ",", "float", "(", "high", ")", ",", "t", ".", "data", ")", "return", "t" ]
https://github.com/apache/singa/blob/93fd9da72694e68bfe3fb29d0183a65263d238a1/python/singa/tensor.py#L1672-L1684
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Code/Tools/waf-1.7.13/waflib/Tools/msvc.py
python
gather_intel_composer_versions
(conf, versions)
Checks ICL compilers that are part of Intel Composer Suites :param versions: list to modify :type versions: list
Checks ICL compilers that are part of Intel Composer Suites
[ "Checks", "ICL", "compilers", "that", "are", "part", "of", "Intel", "Composer", "Suites" ]
def gather_intel_composer_versions(conf, versions): """ Checks ICL compilers that are part of Intel Composer Suites :param versions: list to modify :type versions: list """ version_pattern = re.compile('^...?.?\...?.?.?') try: all_versions = Utils.winreg.OpenKey(Utils.winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\\Wow6432node\\Intel\\Suites') except WindowsError: try: all_versions = Utils.winreg.OpenKey(Utils.winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\\Intel\\Suites') except WindowsError: return index = 0 while 1: try: version = Utils.winreg.EnumKey(all_versions, index) except WindowsError: break index = index + 1 if not version_pattern.match(version): continue targets = [] for target,arch in all_icl_platforms: try: if target=='intel64': targetDir='EM64T_NATIVE' else: targetDir=target try: defaults = Utils.winreg.OpenKey(all_versions,version+'\\Defaults\\C++\\'+targetDir) except WindowsError: if targetDir=='EM64T_NATIVE': defaults = Utils.winreg.OpenKey(all_versions,version+'\\Defaults\\C++\\EM64T') else: raise WindowsError uid,type = Utils.winreg.QueryValueEx(defaults, 'SubKey') Utils.winreg.OpenKey(all_versions,version+'\\'+uid+'\\C++\\'+targetDir) icl_version=Utils.winreg.OpenKey(all_versions,version+'\\'+uid+'\\C++') path,type=Utils.winreg.QueryValueEx(icl_version,'ProductDir') batch_file=os.path.join(path,'bin','iclvars.bat') if os.path.isfile(batch_file): try: targets.append((target,(arch,conf.get_msvc_version('intel',version,target,batch_file)))) except conf.errors.ConfigurationError as e: pass # The intel compilervar_arch.bat is broken when used with Visual Studio Express 2012 # http://software.intel.com/en-us/forums/topic/328487 compilervars_warning_attr = '_compilervars_warning_key' if version[0:2] == '13' and getattr(conf, compilervars_warning_attr, True): setattr(conf, compilervars_warning_attr, False) patch_url = 'http://software.intel.com/en-us/forums/topic/328487' compilervars_arch = os.path.join(path, 'bin', 'compilervars_arch.bat') for vscomntool in ['VS110COMNTOOLS', 'VS100COMNTOOLS']: if vscomntool in os.environ: vs_express_path = os.environ[vscomntool] + r'..\IDE\VSWinExpress.exe' dev_env_path = os.environ[vscomntool] + r'..\IDE\devenv.exe' if (r'if exist "%VS110COMNTOOLS%..\IDE\VSWinExpress.exe"' in Utils.readf(compilervars_arch) and not os.path.exists(vs_express_path) and not os.path.exists(dev_env_path)): Logs.warn(('The Intel compilervar_arch.bat only checks for one Visual Studio SKU ' '(VSWinExpress.exe) but it does not seem to be installed at %r. ' 'The intel command line set up will fail to configure unless the file %r' 'is patched. See: %s') % (vs_express_path, compilervars_arch, patch_url)) except WindowsError: pass major = version[0:2] versions.append(('intel ' + major, targets))
[ "def", "gather_intel_composer_versions", "(", "conf", ",", "versions", ")", ":", "version_pattern", "=", "re", ".", "compile", "(", "'^...?.?\\...?.?.?'", ")", "try", ":", "all_versions", "=", "Utils", ".", "winreg", ".", "OpenKey", "(", "Utils", ".", "winreg"...
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Code/Tools/waf-1.7.13/waflib/Tools/msvc.py#L446-L512
DaFuCoding/MTCNN_Caffe
09c30c3ff391bd9cb6b249c1910afaf147767ab3
scripts/cpp_lint.py
python
_CppLintState.SetCountingStyle
(self, counting_style)
Sets the module's counting options.
Sets the module's counting options.
[ "Sets", "the", "module", "s", "counting", "options", "." ]
def SetCountingStyle(self, counting_style): """Sets the module's counting options.""" self.counting = counting_style
[ "def", "SetCountingStyle", "(", "self", ",", "counting_style", ")", ":", "self", ".", "counting", "=", "counting_style" ]
https://github.com/DaFuCoding/MTCNN_Caffe/blob/09c30c3ff391bd9cb6b249c1910afaf147767ab3/scripts/cpp_lint.py#L713-L715
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/ipython/py2/IPython/core/interactiveshell.py
python
InteractiveShell.system_raw
(self, cmd)
Call the given cmd in a subprocess using os.system on Windows or subprocess.call using the system shell on other platforms. Parameters ---------- cmd : str Command to execute.
Call the given cmd in a subprocess using os.system on Windows or subprocess.call using the system shell on other platforms.
[ "Call", "the", "given", "cmd", "in", "a", "subprocess", "using", "os", ".", "system", "on", "Windows", "or", "subprocess", ".", "call", "using", "the", "system", "shell", "on", "other", "platforms", "." ]
def system_raw(self, cmd): """Call the given cmd in a subprocess using os.system on Windows or subprocess.call using the system shell on other platforms. Parameters ---------- cmd : str Command to execute. """ cmd = self.var_expand(cmd, depth=1) # protect os.system from UNC paths on Windows, which it can't handle: if sys.platform == 'win32': from IPython.utils._process_win32 import AvoidUNCPath with AvoidUNCPath() as path: if path is not None: cmd = '"pushd %s &&"%s' % (path, cmd) cmd = py3compat.unicode_to_str(cmd) try: ec = os.system(cmd) except KeyboardInterrupt: print('\n' + self.get_exception_only(), file=sys.stderr) ec = -2 else: cmd = py3compat.unicode_to_str(cmd) # For posix the result of the subprocess.call() below is an exit # code, which by convention is zero for success, positive for # program failure. Exit codes above 128 are reserved for signals, # and the formula for converting a signal to an exit code is usually # signal_number+128. To more easily differentiate between exit # codes and signals, ipython uses negative numbers. For instance # since control-c is signal 2 but exit code 130, ipython's # _exit_code variable will read -2. Note that some shells like # csh and fish don't follow sh/bash conventions for exit codes. executable = os.environ.get('SHELL', None) try: # Use env shell instead of default /bin/sh ec = subprocess.call(cmd, shell=True, executable=executable) except KeyboardInterrupt: # intercept control-C; a long traceback is not useful here print('\n' + self.get_exception_only(), file=sys.stderr) ec = 130 if ec > 128: ec = -(ec - 128) # We explicitly do NOT return the subprocess status code, because # a non-None value would trigger :func:`sys.displayhook` calls. # Instead, we store the exit_code in user_ns. Note the semantics # of _exit_code: for control-c, _exit_code == -signal.SIGNIT, # but raising SystemExit(_exit_code) will give status 254! self.user_ns['_exit_code'] = ec
[ "def", "system_raw", "(", "self", ",", "cmd", ")", ":", "cmd", "=", "self", ".", "var_expand", "(", "cmd", ",", "depth", "=", "1", ")", "# protect os.system from UNC paths on Windows, which it can't handle:", "if", "sys", ".", "platform", "==", "'win32'", ":", ...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py2/IPython/core/interactiveshell.py#L2213-L2262
mongodb/mongo
d8ff665343ad29cf286ee2cf4a1960d29371937b
buildscripts/idl/idl_compatibility_errors.py
python
IDLCompatibilityContext.add_command_removed_error
(self, command_name: str, file: str)
Add an error about a command that was removed.
Add an error about a command that was removed.
[ "Add", "an", "error", "about", "a", "command", "that", "was", "removed", "." ]
def add_command_removed_error(self, command_name: str, file: str) -> None: """Add an error about a command that was removed.""" self._add_error(ERROR_ID_REMOVED_COMMAND, command_name, "Old command '%s' was removed from new commands." % (command_name), file)
[ "def", "add_command_removed_error", "(", "self", ",", "command_name", ":", "str", ",", "file", ":", "str", ")", "->", "None", ":", "self", ".", "_add_error", "(", "ERROR_ID_REMOVED_COMMAND", ",", "command_name", ",", "\"Old command '%s' was removed from new commands.\...
https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/idl/idl_compatibility_errors.py#L271-L274
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/extern/aui/aui_utilities.py
python
MakeGray
(rgbTuple, factor, maskColour)
Make a pixel grayed-out. If the pixel matches the `maskColour`, it won't be changed. :param tuple `rgbTuple`: a tuple representing a pixel colour; :param integer `factor`: a graying-out factor; :param Colour `maskColour`: a colour mask.
Make a pixel grayed-out.
[ "Make", "a", "pixel", "grayed", "-", "out", "." ]
def MakeGray(rgbTuple, factor, maskColour): """ Make a pixel grayed-out. If the pixel matches the `maskColour`, it won't be changed. :param tuple `rgbTuple`: a tuple representing a pixel colour; :param integer `factor`: a graying-out factor; :param Colour `maskColour`: a colour mask. """ if rgbTuple != maskColour: r, g, b = rgbTuple return map(lambda x: int((230 - x) * factor) + x, (r, g, b)) else: return rgbTuple
[ "def", "MakeGray", "(", "rgbTuple", ",", "factor", ",", "maskColour", ")", ":", "if", "rgbTuple", "!=", "maskColour", ":", "r", ",", "g", ",", "b", "=", "rgbTuple", "return", "map", "(", "lambda", "x", ":", "int", "(", "(", "230", "-", "x", ")", ...
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/extern/aui/aui_utilities.py#L222-L237
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
tools/usb_gadget/composite_gadget.py
python
CompositeFeature.VendorControlRead
(self, recipient, request, value, index, length)
return None
Handle vendor-specific control transfers. Args: recipient: Request recipient (interface or endpoint) request: bRequest field of the setup packet. value: wValue field of the setup packet. index: wIndex field of the setup packet. length: Maximum amount of data the host expects the device to return. Returns: A buffer to return to the USB host with len <= length on success or None to stall the pipe.
Handle vendor-specific control transfers.
[ "Handle", "vendor", "-", "specific", "control", "transfers", "." ]
def VendorControlRead(self, recipient, request, value, index, length): """Handle vendor-specific control transfers. Args: recipient: Request recipient (interface or endpoint) request: bRequest field of the setup packet. value: wValue field of the setup packet. index: wIndex field of the setup packet. length: Maximum amount of data the host expects the device to return. Returns: A buffer to return to the USB host with len <= length on success or None to stall the pipe. """ _ = recipient, request, value, index, length return None
[ "def", "VendorControlRead", "(", "self", ",", "recipient", ",", "request", ",", "value", ",", "index", ",", "length", ")", ":", "_", "=", "recipient", ",", "request", ",", "value", ",", "index", ",", "length", "return", "None" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/usb_gadget/composite_gadget.py#L214-L229
esa/pykep
b410363653623730b577de257c04b0e0289f2014
pykep/trajopt/_indirect.py
python
indirect_or2or.__init__
(self, elem0=[149598261129.93335, 0.016711230601231957, 2.640492490927786e-07, 3.141592653589793, 4.938194050401601, 0], elemf=[227943822376.03537, 0.09339409892101332, 0.032283207367640024, 0.8649771996521327, 5.000312830124232, 0], mass=1000, thrust=0.3, isp=2500, atol=1e-12, rtol=1e-12, tof=[100, 700], freetime=True, alpha=0, bound=False, mu=pk.MU_SUN)
Initialises ``pykep.trajopt.indirect_or2or`` problem. Args: - elem0 (``list``, ``tuple``, ``numpy.ndarray``): Departure Keplerian elements (mutable eccentric anomaly). - elemf (``list``, ``tuple``, ``numpy.ndarray``): Arrival Keplerian elements (mutable eccentric anomaly). - mass (``float``, ``int``): Spacecraft wet mass [kg]. - thrust (``float``, ``int``): Spacecraft maximum thrust [N]. - isp (``float``, ``int``): Spacecraft specific impulse [s]. - atol (``float``, ``int``): Absolute integration solution tolerance. - rtol (``float``, ``int``): Relative integration solution tolerance. - tof (``list``): Transfer time bounds [days]. - freetime (``bool``): Activates final time transversality condition. Allows final time to vary. - alpha (``float``, ``int``): Homotopy parameter, governing the degree to which the theoretical control law is intended to reduce propellant expenditure or energy. - bound (``bool``): Activates bounded control, in which the control throttle is bounded between 0 and 1, otherwise the control throttle is allowed to unbounded. - mu (``float``): Gravitational parameter of primary body [m^3/s^2].
Initialises ``pykep.trajopt.indirect_or2or`` problem.
[ "Initialises", "pykep", ".", "trajopt", ".", "indirect_or2or", "problem", "." ]
def __init__(self, elem0=[149598261129.93335, 0.016711230601231957, 2.640492490927786e-07, 3.141592653589793, 4.938194050401601, 0], elemf=[227943822376.03537, 0.09339409892101332, 0.032283207367640024, 0.8649771996521327, 5.000312830124232, 0], mass=1000, thrust=0.3, isp=2500, atol=1e-12, rtol=1e-12, tof=[100, 700], freetime=True, alpha=0, bound=False, mu=pk.MU_SUN): """Initialises ``pykep.trajopt.indirect_or2or`` problem. Args: - elem0 (``list``, ``tuple``, ``numpy.ndarray``): Departure Keplerian elements (mutable eccentric anomaly). - elemf (``list``, ``tuple``, ``numpy.ndarray``): Arrival Keplerian elements (mutable eccentric anomaly). - mass (``float``, ``int``): Spacecraft wet mass [kg]. - thrust (``float``, ``int``): Spacecraft maximum thrust [N]. - isp (``float``, ``int``): Spacecraft specific impulse [s]. - atol (``float``, ``int``): Absolute integration solution tolerance. - rtol (``float``, ``int``): Relative integration solution tolerance. - tof (``list``): Transfer time bounds [days]. - freetime (``bool``): Activates final time transversality condition. Allows final time to vary. - alpha (``float``, ``int``): Homotopy parameter, governing the degree to which the theoretical control law is intended to reduce propellant expenditure or energy. - bound (``bool``): Activates bounded control, in which the control throttle is bounded between 0 and 1, otherwise the control throttle is allowed to unbounded. - mu (``float``): Gravitational parameter of primary body [m^3/s^2]. """ # initialise base _indirect_base.__init__( self, mass, thrust, isp, mu, True, freetime, alpha, bound, atol, rtol ) # Keplerian elements self.elem0 = np.asarray(elem0) self.elemf = np.asarray(elemf) # Time of flight bounds self.tof = tof
[ "def", "__init__", "(", "self", ",", "elem0", "=", "[", "149598261129.93335", ",", "0.016711230601231957", ",", "2.640492490927786e-07", ",", "3.141592653589793", ",", "4.938194050401601", ",", "0", "]", ",", "elemf", "=", "[", "227943822376.03537", ",", "0.093394...
https://github.com/esa/pykep/blob/b410363653623730b577de257c04b0e0289f2014/pykep/trajopt/_indirect.py#L297-L341
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_core.py
python
PyImageHandler._SetSelf
(*args, **kwargs)
return _core_.PyImageHandler__SetSelf(*args, **kwargs)
_SetSelf(self, PyObject self)
_SetSelf(self, PyObject self)
[ "_SetSelf", "(", "self", "PyObject", "self", ")" ]
def _SetSelf(*args, **kwargs): """_SetSelf(self, PyObject self)""" return _core_.PyImageHandler__SetSelf(*args, **kwargs)
[ "def", "_SetSelf", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "PyImageHandler__SetSelf", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L2734-L2736
SequoiaDB/SequoiaDB
2894ed7e5bd6fe57330afc900cf76d0ff0df9f64
tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py
python
xmlNode.prop
(self, name)
return ret
Search and get the value of an attribute associated to a node This does the entity substitution. This function looks in DTD attribute declaration for #FIXED or default declaration values unless DTD use has been turned off. NOTE: this function acts independently of namespaces associated to the attribute. Use xmlGetNsProp() or xmlGetNoNsProp() for namespace aware processing.
Search and get the value of an attribute associated to a node This does the entity substitution. This function looks in DTD attribute declaration for #FIXED or default declaration values unless DTD use has been turned off. NOTE: this function acts independently of namespaces associated to the attribute. Use xmlGetNsProp() or xmlGetNoNsProp() for namespace aware processing.
[ "Search", "and", "get", "the", "value", "of", "an", "attribute", "associated", "to", "a", "node", "This", "does", "the", "entity", "substitution", ".", "This", "function", "looks", "in", "DTD", "attribute", "declaration", "for", "#FIXED", "or", "default", "d...
def prop(self, name): """Search and get the value of an attribute associated to a node This does the entity substitution. This function looks in DTD attribute declaration for #FIXED or default declaration values unless DTD use has been turned off. NOTE: this function acts independently of namespaces associated to the attribute. Use xmlGetNsProp() or xmlGetNoNsProp() for namespace aware processing. """ ret = libxml2mod.xmlGetProp(self._o, name) return ret
[ "def", "prop", "(", "self", ",", "name", ")", ":", "ret", "=", "libxml2mod", ".", "xmlGetProp", "(", "self", ".", "_o", ",", "name", ")", "return", "ret" ]
https://github.com/SequoiaDB/SequoiaDB/blob/2894ed7e5bd6fe57330afc900cf76d0ff0df9f64/tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py#L3418-L3427
verilog-to-routing/vtr-verilog-to-routing
d9719cf7374821156c3cee31d66991cb85578562
libs/EXTERNAL/libcatch2/tools/scripts/extractFeaturesFromReleaseNotes.py
python
create_introduced_in_text
(version, bug_number = None)
Generate text to paste in to documentation file
Generate text to paste in to documentation file
[ "Generate", "text", "to", "paste", "in", "to", "documentation", "file" ]
def create_introduced_in_text(version, bug_number = None): """Generate text to paste in to documentation file""" if bug_number: return '> [Introduced](https://github.com/catchorg/Catch2/issues/%s) in Catch %s.' % (bug_number, version) else: # Use this text for changes that don't have issue numbers return '> Introduced in Catch %s.' % version
[ "def", "create_introduced_in_text", "(", "version", ",", "bug_number", "=", "None", ")", ":", "if", "bug_number", ":", "return", "'> [Introduced](https://github.com/catchorg/Catch2/issues/%s) in Catch %s.'", "%", "(", "bug_number", ",", "version", ")", "else", ":", "# U...
https://github.com/verilog-to-routing/vtr-verilog-to-routing/blob/d9719cf7374821156c3cee31d66991cb85578562/libs/EXTERNAL/libcatch2/tools/scripts/extractFeaturesFromReleaseNotes.py#L29-L35
gem5/gem5
141cc37c2d4b93959d4c249b8f7e6a8b2ef75338
ext/ply/example/ansic/cparse.py
python
p_enumerator_1
(t)
enumerator : ID
enumerator : ID
[ "enumerator", ":", "ID" ]
def p_enumerator_1(t): 'enumerator : ID' pass
[ "def", "p_enumerator_1", "(", "t", ")", ":", "pass" ]
https://github.com/gem5/gem5/blob/141cc37c2d4b93959d4c249b8f7e6a8b2ef75338/ext/ply/example/ansic/cparse.py#L253-L255
Tencent/CMONGO
c40380caa14e05509f46993aa8b8da966b09b0b5
buildscripts/resmokelib/core/network.py
python
_check_port
(func)
return wrapper
A decorator that verifies the port returned by the wrapped function is in the valid range. Returns the port if it is valid, and raises a PortAllocationError otherwise.
A decorator that verifies the port returned by the wrapped function is in the valid range.
[ "A", "decorator", "that", "verifies", "the", "port", "returned", "by", "the", "wrapped", "function", "is", "in", "the", "valid", "range", "." ]
def _check_port(func): """ A decorator that verifies the port returned by the wrapped function is in the valid range. Returns the port if it is valid, and raises a PortAllocationError otherwise. """ @functools.wraps(func) def wrapper(*args, **kwargs): port = func(*args, **kwargs) if port < 0: raise errors.PortAllocationError("Attempted to use a negative port") if port > PortAllocator.MAX_PORT: raise errors.PortAllocationError("Exhausted all available ports. Consider decreasing" " the number of jobs, or using a lower base port") return port return wrapper
[ "def", "_check_port", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "port", "=", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "if", "po...
https://github.com/Tencent/CMONGO/blob/c40380caa14e05509f46993aa8b8da966b09b0b5/buildscripts/resmokelib/core/network.py#L16-L38
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/urllib.py
python
FancyURLopener.http_error_302
(self, url, fp, errcode, errmsg, headers, data=None)
Error 302 -- relocated (temporarily).
Error 302 -- relocated (temporarily).
[ "Error", "302", "--", "relocated", "(", "temporarily", ")", "." ]
def http_error_302(self, url, fp, errcode, errmsg, headers, data=None): """Error 302 -- relocated (temporarily).""" self.tries += 1 try: if self.maxtries and self.tries >= self.maxtries: if hasattr(self, "http_error_500"): meth = self.http_error_500 else: meth = self.http_error_default return meth(url, fp, 500, "Internal Server Error: Redirect Recursion", headers) result = self.redirect_internal(url, fp, errcode, errmsg, headers, data) return result finally: self.tries = 0
[ "def", "http_error_302", "(", "self", ",", "url", ",", "fp", ",", "errcode", ",", "errmsg", ",", "headers", ",", "data", "=", "None", ")", ":", "self", ".", "tries", "+=", "1", "try", ":", "if", "self", ".", "maxtries", "and", "self", ".", "tries",...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/urllib.py#L629-L645
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/fractions.py
python
Fraction.__abs__
(a)
return Fraction(abs(a._numerator), a._denominator)
abs(a)
abs(a)
[ "abs", "(", "a", ")" ]
def __abs__(a): """abs(a)""" return Fraction(abs(a._numerator), a._denominator)
[ "def", "__abs__", "(", "a", ")", ":", "return", "Fraction", "(", "abs", "(", "a", ".", "_numerator", ")", ",", "a", ".", "_denominator", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/fractions.py#L497-L499
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/random.py
python
WichmannHill.random
(self)
return (x/30269.0 + y/30307.0 + z/30323.0) % 1.0
Get the next random number in the range [0.0, 1.0).
Get the next random number in the range [0.0, 1.0).
[ "Get", "the", "next", "random", "number", "in", "the", "range", "[", "0", ".", "0", "1", ".", "0", ")", "." ]
def random(self): """Get the next random number in the range [0.0, 1.0).""" # Wichman-Hill random number generator. # # Wichmann, B. A. & Hill, I. D. (1982) # Algorithm AS 183: # An efficient and portable pseudo-random number generator # Applied Statistics 31 (1982) 188-190 # # see also: # Correction to Algorithm AS 183 # Applied Statistics 33 (1984) 123 # # McLeod, A. I. (1985) # A remark on Algorithm AS 183 # Applied Statistics 34 (1985),198-200 # This part is thread-unsafe: # BEGIN CRITICAL SECTION x, y, z = self._seed x = (171 * x) % 30269 y = (172 * y) % 30307 z = (170 * z) % 30323 self._seed = x, y, z # END CRITICAL SECTION # Note: on a platform using IEEE-754 double arithmetic, this can # never return 0.0 (asserted by Tim; proof too long for a comment). return (x/30269.0 + y/30307.0 + z/30323.0) % 1.0
[ "def", "random", "(", "self", ")", ":", "# Wichman-Hill random number generator.", "#", "# Wichmann, B. A. & Hill, I. D. (1982)", "# Algorithm AS 183:", "# An efficient and portable pseudo-random number generator", "# Applied Statistics 31 (1982) 188-190", "#", "# see also:", "# C...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/random.py#L684-L713
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/fitting_widgets/tf_asymmetry_fitting/tf_asymmetry_fitting_view.py
python
TFAsymmetryFittingView.is_normalisation_fixed
(self, is_fixed: bool)
Sets whether the fix normalisation checkbox is ticked or not.
Sets whether the fix normalisation checkbox is ticked or not.
[ "Sets", "whether", "the", "fix", "normalisation", "checkbox", "is", "ticked", "or", "not", "." ]
def is_normalisation_fixed(self, is_fixed: bool) -> None: """Sets whether the fix normalisation checkbox is ticked or not.""" self.tf_asymmetry_fitting_options.is_normalisation_fixed = is_fixed
[ "def", "is_normalisation_fixed", "(", "self", ",", "is_fixed", ":", "bool", ")", "->", "None", ":", "self", ".", "tf_asymmetry_fitting_options", ".", "is_normalisation_fixed", "=", "is_fixed" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/fitting_widgets/tf_asymmetry_fitting/tf_asymmetry_fitting_view.py#L72-L74
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/prompt-toolkit/py3/prompt_toolkit/input/win32.py
python
ConsoleInputReader._is_paste
(keys: List[KeyPress])
return newline_count >= 1 and text_count >= 1
Return `True` when we should consider this list of keys as a paste event. Pasted text on windows will be turned into a `Keys.BracketedPaste` event. (It's not 100% correct, but it is probably the best possible way to detect pasting of text and handle that correctly.)
Return `True` when we should consider this list of keys as a paste event. Pasted text on windows will be turned into a `Keys.BracketedPaste` event. (It's not 100% correct, but it is probably the best possible way to detect pasting of text and handle that correctly.)
[ "Return", "True", "when", "we", "should", "consider", "this", "list", "of", "keys", "as", "a", "paste", "event", ".", "Pasted", "text", "on", "windows", "will", "be", "turned", "into", "a", "Keys", ".", "BracketedPaste", "event", ".", "(", "It", "s", "...
def _is_paste(keys: List[KeyPress]) -> bool: """ Return `True` when we should consider this list of keys as a paste event. Pasted text on windows will be turned into a `Keys.BracketedPaste` event. (It's not 100% correct, but it is probably the best possible way to detect pasting of text and handle that correctly.) """ # Consider paste when it contains at least one newline and at least one # other character. text_count = 0 newline_count = 0 for k in keys: if not isinstance(k.key, Keys): text_count += 1 if k.key == Keys.ControlM: newline_count += 1 return newline_count >= 1 and text_count >= 1
[ "def", "_is_paste", "(", "keys", ":", "List", "[", "KeyPress", "]", ")", "->", "bool", ":", "# Consider paste when it contains at least one newline and at least one", "# other character.", "text_count", "=", "0", "newline_count", "=", "0", "for", "k", "in", "keys", ...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/prompt-toolkit/py3/prompt_toolkit/input/win32.py#L366-L385
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/ops/confusion_matrix.py
python
remove_squeezable_dimensions
( labels, predictions, expected_rank_diff=0, name=None)
Squeeze last dim if ranks differ from expected by exactly 1. In the common case where we expect shapes to match, `expected_rank_diff` defaults to 0, and we squeeze the last dimension of the larger rank if they differ by 1. But, for example, if `labels` contains class IDs and `predictions` contains 1 probability per class, we expect `predictions` to have 1 more dimension than `labels`, so `expected_rank_diff` would be 1. In this case, we'd squeeze `labels` if `rank(predictions) - rank(labels) == 0`, and `predictions` if `rank(predictions) - rank(labels) == 2`. This will use static shape if available. Otherwise, it will add graph operations, which could result in a performance hit. Args: labels: Label values, a `Tensor` whose dimensions match `predictions`. predictions: Predicted values, a `Tensor` of arbitrary dimensions. expected_rank_diff: Expected result of `rank(predictions) - rank(labels)`. name: Name of the op. Returns: Tuple of `labels` and `predictions`, possibly with last dim squeezed.
Squeeze last dim if ranks differ from expected by exactly 1.
[ "Squeeze", "last", "dim", "if", "ranks", "differ", "from", "expected", "by", "exactly", "1", "." ]
def remove_squeezable_dimensions( labels, predictions, expected_rank_diff=0, name=None): """Squeeze last dim if ranks differ from expected by exactly 1. In the common case where we expect shapes to match, `expected_rank_diff` defaults to 0, and we squeeze the last dimension of the larger rank if they differ by 1. But, for example, if `labels` contains class IDs and `predictions` contains 1 probability per class, we expect `predictions` to have 1 more dimension than `labels`, so `expected_rank_diff` would be 1. In this case, we'd squeeze `labels` if `rank(predictions) - rank(labels) == 0`, and `predictions` if `rank(predictions) - rank(labels) == 2`. This will use static shape if available. Otherwise, it will add graph operations, which could result in a performance hit. Args: labels: Label values, a `Tensor` whose dimensions match `predictions`. predictions: Predicted values, a `Tensor` of arbitrary dimensions. expected_rank_diff: Expected result of `rank(predictions) - rank(labels)`. name: Name of the op. Returns: Tuple of `labels` and `predictions`, possibly with last dim squeezed. """ with ops.name_scope(name, 'remove_squeezable_dimensions', [labels, predictions]): predictions = ops.convert_to_tensor(predictions) labels = ops.convert_to_tensor(labels) predictions_shape = predictions.get_shape() predictions_rank = predictions_shape.ndims labels_shape = labels.get_shape() labels_rank = labels_shape.ndims if (labels_rank is not None) and (predictions_rank is not None): # Use static rank. rank_diff = predictions_rank - labels_rank if rank_diff == expected_rank_diff + 1: predictions = array_ops.squeeze(predictions, [-1]) elif rank_diff == expected_rank_diff - 1: labels = array_ops.squeeze(labels, [-1]) return labels, predictions # Use dynamic rank. rank_diff = array_ops.rank(predictions) - array_ops.rank(labels) if (predictions_rank is None) or ( predictions_shape.dims[-1].is_compatible_with(1)): predictions = control_flow_ops.cond( math_ops.equal(expected_rank_diff + 1, rank_diff), lambda: array_ops.squeeze(predictions, [-1]), lambda: predictions) if (labels_rank is None) or ( labels_shape.dims[-1].is_compatible_with(1)): labels = control_flow_ops.cond( math_ops.equal(expected_rank_diff - 1, rank_diff), lambda: array_ops.squeeze(labels, [-1]), lambda: labels) return labels, predictions
[ "def", "remove_squeezable_dimensions", "(", "labels", ",", "predictions", ",", "expected_rank_diff", "=", "0", ",", "name", "=", "None", ")", ":", "with", "ops", ".", "name_scope", "(", "name", ",", "'remove_squeezable_dimensions'", ",", "[", "labels", ",", "p...
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/ops/confusion_matrix.py#L36-L93
thalium/icebox
99d147d5b9269222225443ce171b4fd46d8985d4
third_party/retdec-3.2/scripts/type_extractor/extract_types.py
python
parse_header
(header_file, path, output_handler, output_dir, output_format, indent)
Get types information from header file and writes output in chosen format to file to output directory. Path to header set to functions is relative path from script's input path.
Get types information from header file and writes output in chosen format to file to output directory.
[ "Get", "types", "information", "from", "header", "file", "and", "writes", "output", "in", "chosen", "format", "to", "file", "to", "output", "directory", "." ]
def parse_header(header_file, path, output_handler, output_dir, output_format, indent): """Get types information from header file and writes output in chosen format to file to output directory. Path to header set to functions is relative path from script's input path. """ logging.info('Reading file: {}'.format(header_file)) content = read_text_file(header_file) if os.path.isfile(path): relative_path = os.path.basename(path) else: relative_path = os.path.relpath(header_file, path) functions, types, structs, unions, enums = get_types_info_from_text( relative_path, content, output_format) out_f = get_output_file(header_file, path, output_format, output_dir) with open(out_f, 'w') as output_file: output_handler( output_file, functions, types, structs, unions, enums, indent )
[ "def", "parse_header", "(", "header_file", ",", "path", ",", "output_handler", ",", "output_dir", ",", "output_format", ",", "indent", ")", ":", "logging", ".", "info", "(", "'Reading file: {}'", ".", "format", "(", "header_file", ")", ")", "content", "=", "...
https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/retdec-3.2/scripts/type_extractor/extract_types.py#L45-L65
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/inspect.py
python
isframe
(object)
return isinstance(object, types.FrameType)
Return true if the object is a frame object. Frame objects provide these attributes: f_back next outer frame object (this frame's caller) f_builtins built-in namespace seen by this frame f_code code object being executed in this frame f_globals global namespace seen by this frame f_lasti index of last attempted instruction in bytecode f_lineno current line number in Python source code f_locals local namespace seen by this frame f_trace tracing function for this frame, or None
Return true if the object is a frame object.
[ "Return", "true", "if", "the", "object", "is", "a", "frame", "object", "." ]
def isframe(object): """Return true if the object is a frame object. Frame objects provide these attributes: f_back next outer frame object (this frame's caller) f_builtins built-in namespace seen by this frame f_code code object being executed in this frame f_globals global namespace seen by this frame f_lasti index of last attempted instruction in bytecode f_lineno current line number in Python source code f_locals local namespace seen by this frame f_trace tracing function for this frame, or None""" return isinstance(object, types.FrameType)
[ "def", "isframe", "(", "object", ")", ":", "return", "isinstance", "(", "object", ",", "types", ".", "FrameType", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/inspect.py#L238-L250
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_core.py
python
UpdateUIEvent.GetSetShown
(*args, **kwargs)
return _core_.UpdateUIEvent_GetSetShown(*args, **kwargs)
GetSetShown(self) -> bool Returns ``True`` if the application has called `Show`. For wxWidgets internal use only.
GetSetShown(self) -> bool
[ "GetSetShown", "(", "self", ")", "-", ">", "bool" ]
def GetSetShown(*args, **kwargs): """ GetSetShown(self) -> bool Returns ``True`` if the application has called `Show`. For wxWidgets internal use only. """ return _core_.UpdateUIEvent_GetSetShown(*args, **kwargs)
[ "def", "GetSetShown", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "UpdateUIEvent_GetSetShown", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L6808-L6815
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
torch/package/analyze/trace_dependencies.py
python
trace_dependencies
( callable: Callable[[Any], Any], inputs: Iterable[Tuple[Any, ...]] )
return list(modules_used)
Trace the execution of a callable in order to determine which modules it uses. Args: callable: The callable to execute and trace. inputs: The input to use during tracing. The modules used by 'callable' when invoked by each set of inputs are union-ed to determine all modules used by the callable for the purpooses of packaging. Returns: A list of the names of all modules used during callable execution.
Trace the execution of a callable in order to determine which modules it uses.
[ "Trace", "the", "execution", "of", "a", "callable", "in", "order", "to", "determine", "which", "modules", "it", "uses", "." ]
def trace_dependencies( callable: Callable[[Any], Any], inputs: Iterable[Tuple[Any, ...]] ) -> List[str]: """Trace the execution of a callable in order to determine which modules it uses. Args: callable: The callable to execute and trace. inputs: The input to use during tracing. The modules used by 'callable' when invoked by each set of inputs are union-ed to determine all modules used by the callable for the purpooses of packaging. Returns: A list of the names of all modules used during callable execution. """ modules_used = set() def record_used_modules(frame, event, arg): # If the event being profiled is not a Python function # call, there is nothing to do. if event != "call": return # This is the name of the function that was called. name = frame.f_code.co_name module = None # Try to determine the name of the module that the function # is in: # 1) Check the global namespace of the frame. # 2) Check the local namespace of the frame. # 3) To handle class instance method calls, check # the attribute named 'name' of the object # in the local namespace corresponding to "self". if name in frame.f_globals: module = frame.f_globals[name].__module__ elif name in frame.f_locals: module = frame.f_locals[name].__module__ elif "self" in frame.f_locals: method = getattr(frame.f_locals["self"], name, None) module = method.__module__ if method else None # If a module was found, add it to the set of used modules. if module: modules_used.add(module) try: # Attach record_used_modules as the profiler function. sys.setprofile(record_used_modules) # Execute the callable with all inputs. for inp in inputs: callable(*inp) finally: # Detach the profiler function. sys.setprofile(None) return list(modules_used)
[ "def", "trace_dependencies", "(", "callable", ":", "Callable", "[", "[", "Any", "]", ",", "Any", "]", ",", "inputs", ":", "Iterable", "[", "Tuple", "[", "Any", ",", "...", "]", "]", ")", "->", "List", "[", "str", "]", ":", "modules_used", "=", "set...
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/package/analyze/trace_dependencies.py#L5-L60
stellar-deprecated/stellard
67eabb2217bdfa9a6ea317f62338fb6bca458c90
src/protobuf/python/google/protobuf/text_format.py
python
_MergeScalarField
(tokenizer, message, field)
Merges a single protocol message scalar field into a message. Args: tokenizer: A tokenizer to parse the field value. message: A protocol message to record the data. field: The descriptor of the field to be merged. Raises: ParseError: In case of ASCII parsing problems. RuntimeError: On runtime errors.
Merges a single protocol message scalar field into a message.
[ "Merges", "a", "single", "protocol", "message", "scalar", "field", "into", "a", "message", "." ]
def _MergeScalarField(tokenizer, message, field): """Merges a single protocol message scalar field into a message. Args: tokenizer: A tokenizer to parse the field value. message: A protocol message to record the data. field: The descriptor of the field to be merged. Raises: ParseError: In case of ASCII parsing problems. RuntimeError: On runtime errors. """ tokenizer.Consume(':') value = None if field.type in (descriptor.FieldDescriptor.TYPE_INT32, descriptor.FieldDescriptor.TYPE_SINT32, descriptor.FieldDescriptor.TYPE_SFIXED32): value = tokenizer.ConsumeInt32() elif field.type in (descriptor.FieldDescriptor.TYPE_INT64, descriptor.FieldDescriptor.TYPE_SINT64, descriptor.FieldDescriptor.TYPE_SFIXED64): value = tokenizer.ConsumeInt64() elif field.type in (descriptor.FieldDescriptor.TYPE_UINT32, descriptor.FieldDescriptor.TYPE_FIXED32): value = tokenizer.ConsumeUint32() elif field.type in (descriptor.FieldDescriptor.TYPE_UINT64, descriptor.FieldDescriptor.TYPE_FIXED64): value = tokenizer.ConsumeUint64() elif field.type in (descriptor.FieldDescriptor.TYPE_FLOAT, descriptor.FieldDescriptor.TYPE_DOUBLE): value = tokenizer.ConsumeFloat() elif field.type == descriptor.FieldDescriptor.TYPE_BOOL: value = tokenizer.ConsumeBool() elif field.type == descriptor.FieldDescriptor.TYPE_STRING: value = tokenizer.ConsumeString() elif field.type == descriptor.FieldDescriptor.TYPE_BYTES: value = tokenizer.ConsumeByteString() elif field.type == descriptor.FieldDescriptor.TYPE_ENUM: value = tokenizer.ConsumeEnum(field) else: raise RuntimeError('Unknown field type %d' % field.type) if field.label == descriptor.FieldDescriptor.LABEL_REPEATED: if field.is_extension: message.Extensions[field].append(value) else: getattr(message, field.name).append(value) else: if field.is_extension: message.Extensions[field] = value else: setattr(message, field.name, value)
[ "def", "_MergeScalarField", "(", "tokenizer", ",", "message", ",", "field", ")", ":", "tokenizer", ".", "Consume", "(", "':'", ")", "value", "=", "None", "if", "field", ".", "type", "in", "(", "descriptor", ".", "FieldDescriptor", ".", "TYPE_INT32", ",", ...
https://github.com/stellar-deprecated/stellard/blob/67eabb2217bdfa9a6ea317f62338fb6bca458c90/src/protobuf/python/google/protobuf/text_format.py#L241-L293
miyosuda/TensorFlowAndroidMNIST
7b5a4603d2780a8a2834575706e9001977524007
jni-build/jni/include/tensorflow/contrib/lookup/lookup_ops.py
python
index_to_string
(tensor, mapping, default_value="UNK", name=None)
Maps `tensor` of indices into string values based on `mapping`. This operation converts `int64` indices into string values. The mapping is initialized from a string `mapping` tensor where each element is a value and the corresponding index within the tensor is the key. Any input which does not have a corresponding index in 'mapping' (an out-of-vocabulary entry) is assigned the `default_value` The underlying table must be initialized by calling `tf.initialize_all_tables.run()` once. For example: ```python mapping_string = t.constant(["emerson", "lake", "palmer") indices = tf.constant([1, 5], tf.int64) values = tf.contrib.lookup.index_to_string( indices, mapping=mapping_string, default_value="UNKNOWN") ... tf.initialize_all_tables().run() values.eval() ==> ["lake", "UNKNOWN"] ``` Args: tensor: A `int64` `Tensor` with the indices to map to strings. mapping: A 1-D string `Tensor` that specifies the strings to map from indices. default_value: The string value to use for out-of-vocabulary indices. name: A name for this op (optional). Returns: The strings values associated to the indices. The resultant dense feature value tensor has the same shape as the corresponding `indices`.
Maps `tensor` of indices into string values based on `mapping`.
[ "Maps", "tensor", "of", "indices", "into", "string", "values", "based", "on", "mapping", "." ]
def index_to_string(tensor, mapping, default_value="UNK", name=None): """Maps `tensor` of indices into string values based on `mapping`. This operation converts `int64` indices into string values. The mapping is initialized from a string `mapping` tensor where each element is a value and the corresponding index within the tensor is the key. Any input which does not have a corresponding index in 'mapping' (an out-of-vocabulary entry) is assigned the `default_value` The underlying table must be initialized by calling `tf.initialize_all_tables.run()` once. For example: ```python mapping_string = t.constant(["emerson", "lake", "palmer") indices = tf.constant([1, 5], tf.int64) values = tf.contrib.lookup.index_to_string( indices, mapping=mapping_string, default_value="UNKNOWN") ... tf.initialize_all_tables().run() values.eval() ==> ["lake", "UNKNOWN"] ``` Args: tensor: A `int64` `Tensor` with the indices to map to strings. mapping: A 1-D string `Tensor` that specifies the strings to map from indices. default_value: The string value to use for out-of-vocabulary indices. name: A name for this op (optional). Returns: The strings values associated to the indices. The resultant dense feature value tensor has the same shape as the corresponding `indices`. """ with ops.op_scope([tensor], name, "index_to_string") as scope: shared_name = "" values = ops.convert_to_tensor(mapping, dtypes.string) vocab_size = array_ops.size(values) keys = math_ops.cast(math_ops.range(vocab_size), dtypes.int64) init = KeyValueTensorInitializer(keys, values, dtypes.int64, dtypes.string, name="table_init") t = HashTable(init, default_value, shared_name=shared_name, name="hash_table") return t.lookup(tensor, name=scope)
[ "def", "index_to_string", "(", "tensor", ",", "mapping", ",", "default_value", "=", "\"UNK\"", ",", "name", "=", "None", ")", ":", "with", "ops", ".", "op_scope", "(", "[", "tensor", "]", ",", "name", ",", "\"index_to_string\"", ")", "as", "scope", ":", ...
https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/contrib/lookup/lookup_ops.py#L636-L687
jeog/TOSDataBridge
6a5a08ca5cf3883db1f12e9bc89ef374d098df5a
python/tosdb/_common.py
python
_TOSDB_DataBlock.info
()
Returns a more readable dict of info about the underlying block
Returns a more readable dict of info about the underlying block
[ "Returns", "a", "more", "readable", "dict", "of", "info", "about", "the", "underlying", "block" ]
def info(): """ Returns a more readable dict of info about the underlying block """ pass
[ "def", "info", "(", ")", ":", "pass" ]
https://github.com/jeog/TOSDataBridge/blob/6a5a08ca5cf3883db1f12e9bc89ef374d098df5a/python/tosdb/_common.py#L75-L77
adobe/chromium
cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7
third_party/closure_linter/closure_linter/statetracker.py
python
_GetNextIdentifierToken
(start_token)
return None
Searches for and returns the first identifier at the beginning of a token. Searches each token after the start to see if it starts with an identifier. If found, will split the token into at most 3 piecies: leading whitespace, identifier, rest of token, returning the identifier token. If no identifier is found returns None and changes no tokens. Search is abandoned when a FLAG_ENDING_TYPE token is found. Args: start_token: The token to start searching after. Returns: The identifier token is found, None otherwise.
Searches for and returns the first identifier at the beginning of a token.
[ "Searches", "for", "and", "returns", "the", "first", "identifier", "at", "the", "beginning", "of", "a", "token", "." ]
def _GetNextIdentifierToken(start_token): """Searches for and returns the first identifier at the beginning of a token. Searches each token after the start to see if it starts with an identifier. If found, will split the token into at most 3 piecies: leading whitespace, identifier, rest of token, returning the identifier token. If no identifier is found returns None and changes no tokens. Search is abandoned when a FLAG_ENDING_TYPE token is found. Args: start_token: The token to start searching after. Returns: The identifier token is found, None otherwise. """ token = start_token.next while token and not token.type in Type.FLAG_ENDING_TYPES: match = javascripttokenizer.JavaScriptTokenizer.IDENTIFIER.match( token.string) if (match is not None and token.type == Type.COMMENT and len(token.string) == len(match.group(0))): return token token = token.next return None
[ "def", "_GetNextIdentifierToken", "(", "start_token", ")", ":", "token", "=", "start_token", ".", "next", "while", "token", "and", "not", "token", ".", "type", "in", "Type", ".", "FLAG_ENDING_TYPES", ":", "match", "=", "javascripttokenizer", ".", "JavaScriptToke...
https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/third_party/closure_linter/closure_linter/statetracker.py#L438-L464
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/Jinja2/py3/jinja2/compiler.py
python
CodeGenerator._output_const_repr
(self, group: t.Iterable[t.Any])
return repr(concat(group))
Given a group of constant values converted from ``Output`` child nodes, produce a string to write to the template module source.
Given a group of constant values converted from ``Output`` child nodes, produce a string to write to the template module source.
[ "Given", "a", "group", "of", "constant", "values", "converted", "from", "Output", "child", "nodes", "produce", "a", "string", "to", "write", "to", "the", "template", "module", "source", "." ]
def _output_const_repr(self, group: t.Iterable[t.Any]) -> str: """Given a group of constant values converted from ``Output`` child nodes, produce a string to write to the template module source. """ return repr(concat(group))
[ "def", "_output_const_repr", "(", "self", ",", "group", ":", "t", ".", "Iterable", "[", "t", ".", "Any", "]", ")", "->", "str", ":", "return", "repr", "(", "concat", "(", "group", ")", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/Jinja2/py3/jinja2/compiler.py#L1424-L1429
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/third_party/lib_x86_64/python2.7/dist-packages/rospkg/manifest.py
python
_check_optional
(name, allowXHTML=False, merge_multiple=False)
return check
Validator for optional elements. :raise: :exc:`InvalidManifest` If validation fails
Validator for optional elements.
[ "Validator", "for", "optional", "elements", "." ]
def _check_optional(name, allowXHTML=False, merge_multiple=False): """ Validator for optional elements. :raise: :exc:`InvalidManifest` If validation fails """ def check(n, filename): n = _get_nodes_by_name(n, name) if len(n) > 1 and not merge_multiple: raise InvalidManifest("Invalid manifest file [%s]: must have a single '%s' element"%(filename, name)) if n: values = [] for child in n: if allowXHTML: values.append(''.join([x.toxml() for x in child.childNodes])) else: values.append(_get_text(child.childNodes).strip()) return ', '.join(values) return check
[ "def", "_check_optional", "(", "name", ",", "allowXHTML", "=", "False", ",", "merge_multiple", "=", "False", ")", ":", "def", "check", "(", "n", ",", "filename", ")", ":", "n", "=", "_get_nodes_by_name", "(", "n", ",", "name", ")", "if", "len", "(", ...
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/rospkg/manifest.py#L59-L77
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/ctypes/macholib/dyld.py
python
dyld_find
(name, executable_path=None, env=None)
Find a library or framework using dyld semantics
Find a library or framework using dyld semantics
[ "Find", "a", "library", "or", "framework", "using", "dyld", "semantics" ]
def dyld_find(name, executable_path=None, env=None): """ Find a library or framework using dyld semantics """ for path in dyld_image_suffix_search(chain( dyld_override_search(name, env), dyld_executable_path_search(name, executable_path), dyld_default_search(name, env), ), env): if os.path.isfile(path): return path try: if _dyld_shared_cache_contains_path(path): return path except NotImplementedError: pass raise ValueError("dylib %s could not be found" % (name,))
[ "def", "dyld_find", "(", "name", ",", "executable_path", "=", "None", ",", "env", "=", "None", ")", ":", "for", "path", "in", "dyld_image_suffix_search", "(", "chain", "(", "dyld_override_search", "(", "name", ",", "env", ")", ",", "dyld_executable_path_search...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/ctypes/macholib/dyld.py#L121-L139
openmm/openmm
cb293447c4fc8b03976dfe11399f107bab70f3d9
wrappers/python/openmm/app/element.py
python
Element.getBySymbol
(symbol)
return Element._elements_by_symbol[s]
Get the Element with a particular chemical symbol.
Get the Element with a particular chemical symbol.
[ "Get", "the", "Element", "with", "a", "particular", "chemical", "symbol", "." ]
def getBySymbol(symbol): """Get the Element with a particular chemical symbol.""" s = symbol.strip().upper() return Element._elements_by_symbol[s]
[ "def", "getBySymbol", "(", "symbol", ")", ":", "s", "=", "symbol", ".", "strip", "(", ")", ".", "upper", "(", ")", "return", "Element", ".", "_elements_by_symbol", "[", "s", "]" ]
https://github.com/openmm/openmm/blob/cb293447c4fc8b03976dfe11399f107bab70f3d9/wrappers/python/openmm/app/element.py#L100-L103
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/ed_style.py
python
MergeStyles
(styles1, styles2)
return styles1
Merges the styles from styles2 into styles1 overwriting any duplicate values already set in styles1 with the new data from styles2. @param styles1: dictionary of StyleItems to receive merge @param styles2: dictionary of StyleItems to merge from @return: style1 with all values from styles2 merged into it
Merges the styles from styles2 into styles1 overwriting any duplicate values already set in styles1 with the new data from styles2. @param styles1: dictionary of StyleItems to receive merge @param styles2: dictionary of StyleItems to merge from @return: style1 with all values from styles2 merged into it
[ "Merges", "the", "styles", "from", "styles2", "into", "styles1", "overwriting", "any", "duplicate", "values", "already", "set", "in", "styles1", "with", "the", "new", "data", "from", "styles2", ".", "@param", "styles1", ":", "dictionary", "of", "StyleItems", "...
def MergeStyles(styles1, styles2): """Merges the styles from styles2 into styles1 overwriting any duplicate values already set in styles1 with the new data from styles2. @param styles1: dictionary of StyleItems to receive merge @param styles2: dictionary of StyleItems to merge from @return: style1 with all values from styles2 merged into it """ for style in styles2: styles1[style] = styles2[style] return styles1
[ "def", "MergeStyles", "(", "styles1", ",", "styles2", ")", ":", "for", "style", "in", "styles2", ":", "styles1", "[", "style", "]", "=", "styles2", "[", "style", "]", "return", "styles1" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/ed_style.py#L1076-L1087
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/python/client/device_lib.py
python
list_local_devices
()
return [_convert(s) for s in pywrap_tensorflow.list_devices()]
List the available devices available in the local process. Returns: A list of `DeviceAttribute` protocol buffers.
List the available devices available in the local process.
[ "List", "the", "available", "devices", "available", "in", "the", "local", "process", "." ]
def list_local_devices(): """List the available devices available in the local process. Returns: A list of `DeviceAttribute` protocol buffers. """ def _convert(pb_str): m = device_attributes_pb2.DeviceAttributes() m.ParseFromString(pb_str) return m return [_convert(s) for s in pywrap_tensorflow.list_devices()]
[ "def", "list_local_devices", "(", ")", ":", "def", "_convert", "(", "pb_str", ")", ":", "m", "=", "device_attributes_pb2", ".", "DeviceAttributes", "(", ")", "m", ".", "ParseFromString", "(", "pb_str", ")", "return", "m", "return", "[", "_convert", "(", "s...
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/client/device_lib.py#L25-L36
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/inspect.py
python
getsourcelines
(object)
Return a list of source lines and starting line number for an object. The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a list of the lines corresponding to the object and the line number indicates where in the original source file the first line of code was found. An IOError is raised if the source code cannot be retrieved.
Return a list of source lines and starting line number for an object.
[ "Return", "a", "list", "of", "source", "lines", "and", "starting", "line", "number", "for", "an", "object", "." ]
def getsourcelines(object): """Return a list of source lines and starting line number for an object. The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a list of the lines corresponding to the object and the line number indicates where in the original source file the first line of code was found. An IOError is raised if the source code cannot be retrieved.""" lines, lnum = findsource(object) if ismodule(object): return lines, 0 else: return getblock(lines[lnum:]), lnum + 1
[ "def", "getsourcelines", "(", "object", ")", ":", "lines", ",", "lnum", "=", "findsource", "(", "object", ")", "if", "ismodule", "(", "object", ")", ":", "return", "lines", ",", "0", "else", ":", "return", "getblock", "(", "lines", "[", "lnum", ":", ...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/inspect.py#L682-L693
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/configure.py
python
get_python_path
(environ_cp, python_bin_path)
return paths
Get the python site package paths.
Get the python site package paths.
[ "Get", "the", "python", "site", "package", "paths", "." ]
def get_python_path(environ_cp, python_bin_path): """Get the python site package paths.""" python_paths = [] if environ_cp.get('PYTHONPATH'): python_paths = environ_cp.get('PYTHONPATH').split(':') try: library_paths = run_shell([ python_bin_path, '-c', 'import site; print("\\n".join(site.getsitepackages()))' ]).split('\n') except subprocess.CalledProcessError: library_paths = [ run_shell([ python_bin_path, '-c', 'from distutils.sysconfig import get_python_lib;' 'print(get_python_lib())' ]) ] all_paths = set(python_paths + library_paths) paths = [] for path in all_paths: if os.path.isdir(path): paths.append(path) return paths
[ "def", "get_python_path", "(", "environ_cp", ",", "python_bin_path", ")", ":", "python_paths", "=", "[", "]", "if", "environ_cp", ".", "get", "(", "'PYTHONPATH'", ")", ":", "python_paths", "=", "environ_cp", ".", "get", "(", "'PYTHONPATH'", ")", ".", "split"...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/configure.py#L165-L190
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/wizard.py
python
Wizard.ShowPage
(*args, **kwargs)
return _wizard.Wizard_ShowPage(*args, **kwargs)
ShowPage(self, WizardPage page, bool goingForward=True) -> bool
ShowPage(self, WizardPage page, bool goingForward=True) -> bool
[ "ShowPage", "(", "self", "WizardPage", "page", "bool", "goingForward", "=", "True", ")", "-", ">", "bool" ]
def ShowPage(*args, **kwargs): """ShowPage(self, WizardPage page, bool goingForward=True) -> bool""" return _wizard.Wizard_ShowPage(*args, **kwargs)
[ "def", "ShowPage", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_wizard", ".", "Wizard_ShowPage", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/wizard.py#L443-L445
klzgrad/naiveproxy
ed2c513637c77b18721fe428d7ed395b4d284c83
src/build/fuchsia/target.py
python
Target.PutFiles
(self, sources, dest, recursive=False, for_package=None, for_realms=())
Copies files from the local filesystem to the target filesystem. sources: List of local file paths to copy from, or a single path. dest: The path on the remote filesystem which will be copied to. recursive: If true, performs a recursive copy. for_package: If specified, /data in the |dest| is mapped to the package's isolated /data location. for_realms: If specified, identifies the sub-realm of 'sys' under which isolated paths (see |for_package|) are stored.
Copies files from the local filesystem to the target filesystem.
[ "Copies", "files", "from", "the", "local", "filesystem", "to", "the", "target", "filesystem", "." ]
def PutFiles(self, sources, dest, recursive=False, for_package=None, for_realms=()): """Copies files from the local filesystem to the target filesystem. sources: List of local file paths to copy from, or a single path. dest: The path on the remote filesystem which will be copied to. recursive: If true, performs a recursive copy. for_package: If specified, /data in the |dest| is mapped to the package's isolated /data location. for_realms: If specified, identifies the sub-realm of 'sys' under which isolated paths (see |for_package|) are stored. """ assert type(sources) is tuple or type(sources) is list if for_package: self.EnsureIsolatedPathsExist(for_package, for_realms) dest = _MapIsolatedPathsForPackage(for_package, 0, for_realms)(dest) logging.debug('copy local:%s => remote:%s', sources, dest) self.GetCommandRunner().RunScp(sources, dest, remote_cmd.COPY_TO_TARGET, recursive)
[ "def", "PutFiles", "(", "self", ",", "sources", ",", "dest", ",", "recursive", "=", "False", ",", "for_package", "=", "None", ",", "for_realms", "=", "(", ")", ")", ":", "assert", "type", "(", "sources", ")", "is", "tuple", "or", "type", "(", "source...
https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/build/fuchsia/target.py#L197-L219
eventql/eventql
7ca0dbb2e683b525620ea30dc40540a22d5eb227
deps/3rdparty/spidermonkey/mozjs/media/webrtc/trunk/tools/gyp/pylib/gyp/xcode_emulation.py
python
MacPrefixHeader.GetInclude
(self, lang)
Gets the cflags to include the prefix header for language |lang|.
Gets the cflags to include the prefix header for language |lang|.
[ "Gets", "the", "cflags", "to", "include", "the", "prefix", "header", "for", "language", "|lang|", "." ]
def GetInclude(self, lang): """Gets the cflags to include the prefix header for language |lang|.""" if self.compile_headers and lang in self.compiled_headers: return '-include %s' % self.compiled_headers[lang] elif self.header: return '-include %s' % self.header else: return ''
[ "def", "GetInclude", "(", "self", ",", "lang", ")", ":", "if", "self", ".", "compile_headers", "and", "lang", "in", "self", ".", "compiled_headers", ":", "return", "'-include %s'", "%", "self", ".", "compiled_headers", "[", "lang", "]", "elif", "self", "."...
https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/media/webrtc/trunk/tools/gyp/pylib/gyp/xcode_emulation.py#L745-L752
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/ipython/py2/IPython/lib/pretty.py
python
PrettyPrinter.breakable
(self, sep=' ')
Add a breakable separator to the output. This does not mean that it will automatically break here. If no breaking on this position takes place the `sep` is inserted which default to one space.
Add a breakable separator to the output. This does not mean that it will automatically break here. If no breaking on this position takes place the `sep` is inserted which default to one space.
[ "Add", "a", "breakable", "separator", "to", "the", "output", ".", "This", "does", "not", "mean", "that", "it", "will", "automatically", "break", "here", ".", "If", "no", "breaking", "on", "this", "position", "takes", "place", "the", "sep", "is", "inserted"...
def breakable(self, sep=' '): """ Add a breakable separator to the output. This does not mean that it will automatically break here. If no breaking on this position takes place the `sep` is inserted which default to one space. """ width = len(sep) group = self.group_stack[-1] if group.want_break: self.flush() self.output.write(self.newline) self.output.write(' ' * self.indentation) self.output_width = self.indentation self.buffer_width = 0 else: self.buffer.append(Breakable(sep, width, self)) self.buffer_width += width self._break_outer_groups()
[ "def", "breakable", "(", "self", ",", "sep", "=", "' '", ")", ":", "width", "=", "len", "(", "sep", ")", "group", "=", "self", ".", "group_stack", "[", "-", "1", "]", "if", "group", ".", "want_break", ":", "self", ".", "flush", "(", ")", "self", ...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py2/IPython/lib/pretty.py#L232-L249
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/cryptography/x509/base.py
python
CertificateBuilder.add_extension
(self, extension, critical)
return CertificateBuilder( self._issuer_name, self._subject_name, self._public_key, self._serial_number, self._not_valid_before, self._not_valid_after, self._extensions + [extension] )
Adds an X.509 extension to the certificate.
Adds an X.509 extension to the certificate.
[ "Adds", "an", "X", ".", "509", "extension", "to", "the", "certificate", "." ]
def add_extension(self, extension, critical): """ Adds an X.509 extension to the certificate. """ if not isinstance(extension, ExtensionType): raise TypeError("extension must be an ExtensionType") extension = Extension(extension.oid, critical, extension) _reject_duplicate_extension(extension, self._extensions) return CertificateBuilder( self._issuer_name, self._subject_name, self._public_key, self._serial_number, self._not_valid_before, self._not_valid_after, self._extensions + [extension] )
[ "def", "add_extension", "(", "self", ",", "extension", ",", "critical", ")", ":", "if", "not", "isinstance", "(", "extension", ",", "ExtensionType", ")", ":", "raise", "TypeError", "(", "\"extension must be an ExtensionType\"", ")", "extension", "=", "Extension", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/cryptography/x509/base.py#L562-L576
ablab/quast
5f6709528129a6ad266a6b24ef3f40b88f0fe04b
quast_libs/site_packages/joblib2/memory.py
python
MemorizedFunc._persist_input
(self, output_dir, *args, **kwargs)
return input_repr
Save a small summary of the call using json format in the output directory.
Save a small summary of the call using json format in the output directory.
[ "Save", "a", "small", "summary", "of", "the", "call", "using", "json", "format", "in", "the", "output", "directory", "." ]
def _persist_input(self, output_dir, *args, **kwargs): """ Save a small summary of the call using json format in the output directory. """ argument_dict = filter_args(self.func, self.ignore, args, kwargs) input_repr = dict((k, repr(v)) for k, v in argument_dict.iteritems()) if json is not None: # This can fail do to race-conditions with multiple # concurrent joblibs removing the file or the directory try: mkdirp(output_dir) json.dump( input_repr, file(os.path.join(output_dir, 'input_args.json'), 'w'), ) except: pass return input_repr
[ "def", "_persist_input", "(", "self", ",", "output_dir", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "argument_dict", "=", "filter_args", "(", "self", ".", "func", ",", "self", ".", "ignore", ",", "args", ",", "kwargs", ")", "input_repr", "=",...
https://github.com/ablab/quast/blob/5f6709528129a6ad266a6b24ef3f40b88f0fe04b/quast_libs/site_packages/joblib2/memory.py#L385-L404
gemrb/gemrb
730206eed8d1dd358ca5e69a62f9e099aa22ffc6
gemrb/GUIScripts/bg2/CharGenCommon.py
python
ImportPress
()
return
Opens the character import window.
Opens the character import window.
[ "Opens", "the", "character", "import", "window", "." ]
def ImportPress(): """Opens the character import window.""" step = GemRB.GetVar ("Step") # TODO: check why this is handled differently if step == 1: GemRB.SetNextScript("GUICG24") else: GemRB.SetToken ("NextScript", "CharGen9") GemRB.SetNextScript ("ImportFile") #import return
[ "def", "ImportPress", "(", ")", ":", "step", "=", "GemRB", ".", "GetVar", "(", "\"Step\"", ")", "# TODO: check why this is handled differently", "if", "step", "==", "1", ":", "GemRB", ".", "SetNextScript", "(", "\"GUICG24\"", ")", "else", ":", "GemRB", ".", ...
https://github.com/gemrb/gemrb/blob/730206eed8d1dd358ca5e69a62f9e099aa22ffc6/gemrb/GUIScripts/bg2/CharGenCommon.py#L317-L327
kungfu-origin/kungfu
90c84b2b590855654cb9a6395ed050e0f7763512
core/deps/SQLiteCpp-2.3.0/cpplint.py
python
_FunctionState.Check
(self, error, filename, linenum)
Report if too many lines in function body. Args: error: The function to call with any errors found. filename: The name of the current file. linenum: The number of the line to check.
Report if too many lines in function body.
[ "Report", "if", "too", "many", "lines", "in", "function", "body", "." ]
def Check(self, error, filename, linenum): """Report if too many lines in function body. Args: error: The function to call with any errors found. filename: The name of the current file. linenum: The number of the line to check. """ if Match(r'T(EST|est)', self.current_function): base_trigger = self._TEST_TRIGGER else: base_trigger = self._NORMAL_TRIGGER trigger = base_trigger * 2**_VerboseLevel() if self.lines_in_function > trigger: error_level = int(math.log(self.lines_in_function / base_trigger, 2)) # 50 => 0, 100 => 1, 200 => 2, 400 => 3, 800 => 4, 1600 => 5, ... if error_level > 5: error_level = 5 error(filename, linenum, 'readability/fn_size', error_level, 'Small and focused functions are preferred:' ' %s has %d non-comment lines' ' (error triggered by exceeding %d lines).' % ( self.current_function, self.lines_in_function, trigger))
[ "def", "Check", "(", "self", ",", "error", ",", "filename", ",", "linenum", ")", ":", "if", "Match", "(", "r'T(EST|est)'", ",", "self", ".", "current_function", ")", ":", "base_trigger", "=", "self", ".", "_TEST_TRIGGER", "else", ":", "base_trigger", "=", ...
https://github.com/kungfu-origin/kungfu/blob/90c84b2b590855654cb9a6395ed050e0f7763512/core/deps/SQLiteCpp-2.3.0/cpplint.py#L827-L850
domino-team/openwrt-cc
8b181297c34d14d3ca521cc9f31430d561dbc688
package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/tools/gyp/pylib/gyp/MSVSVersion.py
python
_RegistryQuery
(key, value=None)
return text
r"""Use reg.exe to read a particular key through _RegistryQueryBase. First tries to launch from %WinDir%\Sysnative to avoid WoW64 redirection. If that fails, it falls back to System32. Sysnative is available on Vista and up and available on Windows Server 2003 and XP through KB patch 942589. Note that Sysnative will always fail if using 64-bit python due to it being a virtual directory and System32 will work correctly in the first place. KB 942589 - http://support.microsoft.com/kb/942589/en-us. Arguments: key: The registry key. value: The particular registry value to read (optional). Return: stdout from reg.exe, or None for failure.
r"""Use reg.exe to read a particular key through _RegistryQueryBase.
[ "r", "Use", "reg", ".", "exe", "to", "read", "a", "particular", "key", "through", "_RegistryQueryBase", "." ]
def _RegistryQuery(key, value=None): r"""Use reg.exe to read a particular key through _RegistryQueryBase. First tries to launch from %WinDir%\Sysnative to avoid WoW64 redirection. If that fails, it falls back to System32. Sysnative is available on Vista and up and available on Windows Server 2003 and XP through KB patch 942589. Note that Sysnative will always fail if using 64-bit python due to it being a virtual directory and System32 will work correctly in the first place. KB 942589 - http://support.microsoft.com/kb/942589/en-us. Arguments: key: The registry key. value: The particular registry value to read (optional). Return: stdout from reg.exe, or None for failure. """ text = None try: text = _RegistryQueryBase('Sysnative', key, value) except OSError, e: if e.errno == errno.ENOENT: text = _RegistryQueryBase('System32', key, value) else: raise return text
[ "def", "_RegistryQuery", "(", "key", ",", "value", "=", "None", ")", ":", "text", "=", "None", "try", ":", "text", "=", "_RegistryQueryBase", "(", "'Sysnative'", ",", "key", ",", "value", ")", "except", "OSError", ",", "e", ":", "if", "e", ".", "errn...
https://github.com/domino-team/openwrt-cc/blob/8b181297c34d14d3ca521cc9f31430d561dbc688/package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/tools/gyp/pylib/gyp/MSVSVersion.py#L141-L166
synfig/synfig
a5ec91db5b751dc12e4400ccfb5c063fd6d2d928
synfig-studio/plugins/lottie-exporter/common/DashItemList.py
python
DashItemList.__init__
(self, dash_item, parent)
This parent should be parameter
This parent should be parameter
[ "This", "parent", "should", "be", "parameter" ]
def __init__(self, dash_item, parent): """ This parent should be parameter """ self.parent = parent self.dash_item = dash_item self.type = dash_item.attrib["type"] self.entry_list = [] self.extract_entries(self.entry_list)
[ "def", "__init__", "(", "self", ",", "dash_item", ",", "parent", ")", ":", "self", ".", "parent", "=", "parent", "self", ".", "dash_item", "=", "dash_item", "self", ".", "type", "=", "dash_item", ".", "attrib", "[", "\"type\"", "]", "self", ".", "entry...
https://github.com/synfig/synfig/blob/a5ec91db5b751dc12e4400ccfb5c063fd6d2d928/synfig-studio/plugins/lottie-exporter/common/DashItemList.py#L18-L26
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
ppapi/generators/idl_parser.py
python
IDLParser.p_value_lshift
(self, p)
value : integer LSHIFT INT
value : integer LSHIFT INT
[ "value", ":", "integer", "LSHIFT", "INT" ]
def p_value_lshift(self, p): """value : integer LSHIFT INT""" p[0] = "%s << %s" % (p[1], p[3]) if self.parse_debug: DumpReduction('value', p)
[ "def", "p_value_lshift", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "\"%s << %s\"", "%", "(", "p", "[", "1", "]", ",", "p", "[", "3", "]", ")", "if", "self", ".", "parse_debug", ":", "DumpReduction", "(", "'value'", ",", "p", ")"...
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/ppapi/generators/idl_parser.py#L491-L494
cyberbotics/webots
af7fa7d68dcf7b4550f1f2e132092b41e83698fc
resources/osm_importer/webots_objects/road.py
python
Crossroad.add_road
(self, road)
Add a road.
Add a road.
[ "Add", "a", "road", "." ]
def add_road(self, road): """Add a road.""" self.roads.add(road)
[ "def", "add_road", "(", "self", ",", "road", ")", ":", "self", ".", "roads", ".", "add", "(", "road", ")" ]
https://github.com/cyberbotics/webots/blob/af7fa7d68dcf7b4550f1f2e132092b41e83698fc/resources/osm_importer/webots_objects/road.py#L654-L656
naver/sling
5671cd445a2caae0b4dd0332299e4cfede05062c
webkit/Tools/Scripts/webkitpy/thirdparty/mod_pywebsocket/_stream_base.py
python
StreamBase.receive_bytes
(self, length)
return ''.join(read_bytes)
Receives multiple bytes. Retries read when we couldn't receive the specified amount. Raises: ConnectionTerminatedException: when read returns empty string.
Receives multiple bytes. Retries read when we couldn't receive the specified amount.
[ "Receives", "multiple", "bytes", ".", "Retries", "read", "when", "we", "couldn", "t", "receive", "the", "specified", "amount", "." ]
def receive_bytes(self, length): """Receives multiple bytes. Retries read when we couldn't receive the specified amount. Raises: ConnectionTerminatedException: when read returns empty string. """ read_bytes = [] while length > 0: new_read_bytes = self._read(length) read_bytes.append(new_read_bytes) length -= len(new_read_bytes) return ''.join(read_bytes)
[ "def", "receive_bytes", "(", "self", ",", "length", ")", ":", "read_bytes", "=", "[", "]", "while", "length", ">", "0", ":", "new_read_bytes", "=", "self", ".", "_read", "(", "length", ")", "read_bytes", ".", "append", "(", "new_read_bytes", ")", "length...
https://github.com/naver/sling/blob/5671cd445a2caae0b4dd0332299e4cfede05062c/webkit/Tools/Scripts/webkitpy/thirdparty/mod_pywebsocket/_stream_base.py#L149-L162
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/contrib/distributions/python/ops/wishart.py
python
_WishartLinearOperator.mean_log_det
(self, name="mean_log_det")
Computes E[log(det(X))] under this Wishart distribution.
Computes E[log(det(X))] under this Wishart distribution.
[ "Computes", "E", "[", "log", "(", "det", "(", "X", "))", "]", "under", "this", "Wishart", "distribution", "." ]
def mean_log_det(self, name="mean_log_det"): """Computes E[log(det(X))] under this Wishart distribution.""" with self._name_scope(name): return (self._multi_digamma(0.5 * self.df, self.dimension) + self.dimension * math.log(2.) + 2 * self.scale_operator.log_abs_determinant())
[ "def", "mean_log_det", "(", "self", ",", "name", "=", "\"mean_log_det\"", ")", ":", "with", "self", ".", "_name_scope", "(", "name", ")", ":", "return", "(", "self", ".", "_multi_digamma", "(", "0.5", "*", "self", ".", "df", ",", "self", ".", "dimensio...
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/distributions/python/ops/wishart.py#L399-L404
Samsung/veles
95ed733c2e49bc011ad98ccf2416ecec23fbf352
libVeles/cpplint.py
python
CheckAltTokens
(filename, clean_lines, linenum, error)
Check alternative keywords being used in boolean expressions. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found.
Check alternative keywords being used in boolean expressions.
[ "Check", "alternative", "keywords", "being", "used", "in", "boolean", "expressions", "." ]
def CheckAltTokens(filename, clean_lines, linenum, error): """Check alternative keywords being used in boolean expressions. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # Avoid preprocessor lines if Match(r'^\s*#', line): return # Last ditch effort to avoid multi-line comments. This will not help # if the comment started before the current line or ended after the # current line, but it catches most of the false positives. At least, # it provides a way to workaround this warning for people who use # multi-line comments in preprocessor macros. # # TODO(unknown): remove this once cpplint has better support for # multi-line comments. if line.find('/*') >= 0 or line.find('*/') >= 0: return for match in _ALT_TOKEN_REPLACEMENT_PATTERN.finditer(line): error(filename, linenum, 'readability/alt_tokens', 2, 'Use operator %s instead of %s' % ( _ALT_TOKEN_REPLACEMENT[match.group(1)], match.group(1)))
[ "def", "CheckAltTokens", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "# Avoid preprocessor lines", "if", "Match", "(", "r'^\\s*#'", ",", "line", ")", ":", "retur...
https://github.com/Samsung/veles/blob/95ed733c2e49bc011ad98ccf2416ecec23fbf352/libVeles/cpplint.py#L2740-L2769
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/ops/array_ops.py
python
tile_one_dimension
(data, axis, multiple)
return tile(data, multiples)
Tiles a single dimension of a tensor.
Tiles a single dimension of a tensor.
[ "Tiles", "a", "single", "dimension", "of", "a", "tensor", "." ]
def tile_one_dimension(data, axis, multiple): """Tiles a single dimension of a tensor.""" # Assumes axis is a nonnegative int. if data.shape.ndims is not None: multiples = [1] * data.shape.ndims multiples[axis] = multiple else: ones_value = ones(rank(data), dtypes.int32) multiples = concat([ones_value[:axis], [multiple], ones_value[axis + 1:]], axis=0) return tile(data, multiples)
[ "def", "tile_one_dimension", "(", "data", ",", "axis", ",", "multiple", ")", ":", "# Assumes axis is a nonnegative int.", "if", "data", ".", "shape", ".", "ndims", "is", "not", "None", ":", "multiples", "=", "[", "1", "]", "*", "data", ".", "shape", ".", ...
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/array_ops.py#L6867-L6877
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/oldnumeric/ma.py
python
count
(a, axis = None)
return a.count(axis)
Count of the non-masked elements in a, or along a certain axis.
Count of the non-masked elements in a, or along a certain axis.
[ "Count", "of", "the", "non", "-", "masked", "elements", "in", "a", "or", "along", "a", "certain", "axis", "." ]
def count (a, axis = None): "Count of the non-masked elements in a, or along a certain axis." a = masked_array(a) return a.count(axis)
[ "def", "count", "(", "a", ",", "axis", "=", "None", ")", ":", "a", "=", "masked_array", "(", "a", ")", "return", "a", ".", "count", "(", "axis", ")" ]
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/oldnumeric/ma.py#L1586-L1589
stepcode/stepcode
2a50010e6f6b8bd4843561e48fdb0fd4e8b87f39
src/exp2python/python/SCL/Part21.py
python
Lexer.t_PART21_END
(self, t)
return t
r'END-ISO-10303-21;
r'END-ISO-10303-21;
[ "r", "END", "-", "ISO", "-", "10303", "-", "21", ";" ]
def t_PART21_END(self, t): r'END-ISO-10303-21;' t.lexer.begin('slurp') return t
[ "def", "t_PART21_END", "(", "self", ",", "t", ")", ":", "t", ".", "lexer", ".", "begin", "(", "'slurp'", ")", "return", "t" ]
https://github.com/stepcode/stepcode/blob/2a50010e6f6b8bd4843561e48fdb0fd4e8b87f39/src/exp2python/python/SCL/Part21.py#L146-L149
cksystemsgroup/scalloc
049857919b5fa1d539c9e4206e353daca2e87394
tools/cpplint.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/cksystemsgroup/scalloc/blob/049857919b5fa1d539c9e4206e353daca2e87394/tools/cpplint.py#L2531-L2876
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
chrome/common/extensions/docs/server2/patcher.py
python
Patcher.GetPatchedFiles
(self, version=None)
Returns patched files as(added_files, deleted_files, modified_files) from the patchset specified by |version|.
Returns patched files as(added_files, deleted_files, modified_files) from the patchset specified by |version|.
[ "Returns", "patched", "files", "as", "(", "added_files", "deleted_files", "modified_files", ")", "from", "the", "patchset", "specified", "by", "|version|", "." ]
def GetPatchedFiles(self, version=None): '''Returns patched files as(added_files, deleted_files, modified_files) from the patchset specified by |version|. ''' raise NotImplementedError(self.__class__)
[ "def", "GetPatchedFiles", "(", "self", ",", "version", "=", "None", ")", ":", "raise", "NotImplementedError", "(", "self", ".", "__class__", ")" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/chrome/common/extensions/docs/server2/patcher.py#L6-L10
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/python/framework/ops.py
python
Operation.values
(self)
return tuple(self.outputs)
DEPRECATED: Use outputs.
DEPRECATED: Use outputs.
[ "DEPRECATED", ":", "Use", "outputs", "." ]
def values(self): """DEPRECATED: Use outputs.""" return tuple(self.outputs)
[ "def", "values", "(", "self", ")", ":", "return", "tuple", "(", "self", ".", "outputs", ")" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/framework/ops.py#L1328-L1330
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/botocore/handlers.py
python
conditionally_calculate_md5
(params, context, request_signer, **kwargs)
Only add a Content-MD5 if the system supports it.
Only add a Content-MD5 if the system supports it.
[ "Only", "add", "a", "Content", "-", "MD5", "if", "the", "system", "supports", "it", "." ]
def conditionally_calculate_md5(params, context, request_signer, **kwargs): """Only add a Content-MD5 if the system supports it.""" if MD5_AVAILABLE: calculate_md5(params, **kwargs)
[ "def", "conditionally_calculate_md5", "(", "params", ",", "context", ",", "request_signer", ",", "*", "*", "kwargs", ")", ":", "if", "MD5_AVAILABLE", ":", "calculate_md5", "(", "params", ",", "*", "*", "kwargs", ")" ]
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/handlers.py#L213-L216
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/profiler/parser/framework_parser.py
python
FrameworkParser._special_process_tensor_data
(item_binary_data, data_type, tensor_num)
return unpack_data
The tensor data depends tensor num, so need to special process.
The tensor data depends tensor num, so need to special process.
[ "The", "tensor", "data", "depends", "tensor", "num", "so", "need", "to", "special", "process", "." ]
def _special_process_tensor_data(item_binary_data, data_type, tensor_num): """The tensor data depends tensor num, so need to special process.""" start = 0 op_attr_struct = data_type[0] op_attr_size = StructType.sizeof(op_attr_struct) unpack_data = [] for _ in range(tensor_num): buffer = item_binary_data[start:start + op_attr_size] values = struct.unpack(StructType.format(op_attr_struct), buffer) one_data = dict( tensorType=values[0], format=values[1], dataType=values[2], shape=list(filter(lambda x: x != 0, values[3:])) ) unpack_data.append(one_data) start += op_attr_size return unpack_data
[ "def", "_special_process_tensor_data", "(", "item_binary_data", ",", "data_type", ",", "tensor_num", ")", ":", "start", "=", "0", "op_attr_struct", "=", "data_type", "[", "0", "]", "op_attr_size", "=", "StructType", ".", "sizeof", "(", "op_attr_struct", ")", "un...
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/profiler/parser/framework_parser.py#L268-L287
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Arch/ArchSite.py
python
makeSolarDiagram
(longitude,latitude,scale=1,complete=False,tz=None)
return mastersep
makeSolarDiagram(longitude,latitude,[scale,complete,tz]): returns a solar diagram as a pivy node. If complete is True, the 12 months are drawn. Tz is the timezone related to UTC (ex: -3 = UTC-3)
makeSolarDiagram(longitude,latitude,[scale,complete,tz]): returns a solar diagram as a pivy node. If complete is True, the 12 months are drawn. Tz is the timezone related to UTC (ex: -3 = UTC-3)
[ "makeSolarDiagram", "(", "longitude", "latitude", "[", "scale", "complete", "tz", "]", ")", ":", "returns", "a", "solar", "diagram", "as", "a", "pivy", "node", ".", "If", "complete", "is", "True", "the", "12", "months", "are", "drawn", ".", "Tz", "is", ...
def makeSolarDiagram(longitude,latitude,scale=1,complete=False,tz=None): """makeSolarDiagram(longitude,latitude,[scale,complete,tz]): returns a solar diagram as a pivy node. If complete is True, the 12 months are drawn. Tz is the timezone related to UTC (ex: -3 = UTC-3)""" oldversion = False ladybug = False try: import ladybug from ladybug import location from ladybug import sunpath except Exception: # TODO - remove pysolar dependency # FreeCAD.Console.PrintWarning("Ladybug module not found, using pysolar instead. Warning, this will be deprecated in the future\n") ladybug = False try: import pysolar except Exception: try: import Pysolar as pysolar except Exception: FreeCAD.Console.PrintError("The pysolar module was not found. Unable to generate solar diagrams\n") return None else: oldversion = True if tz: tz = datetime.timezone(datetime.timedelta(hours=tz)) else: tz = datetime.timezone.utc else: loc = ladybug.location.Location(latitude=latitude,longitude=longitude,time_zone=tz) sunpath = ladybug.sunpath.Sunpath.from_location(loc) from pivy import coin if not scale: return None circles = [] sunpaths = [] hourpaths = [] circlepos = [] hourpos = [] # build the base circle + number positions import Part for i in range(1,9): circles.append(Part.makeCircle(scale*(i/8.0))) for ad in range(0,360,15): a = math.radians(ad) p1 = FreeCAD.Vector(math.cos(a)*scale,math.sin(a)*scale,0) p2 = FreeCAD.Vector(math.cos(a)*scale*0.125,math.sin(a)*scale*0.125,0) p3 = FreeCAD.Vector(math.cos(a)*scale*1.08,math.sin(a)*scale*1.08,0) circles.append(Part.LineSegment(p1,p2).toShape()) circlepos.append((ad,p3)) # build the sun curves at solstices and equinoxe year = datetime.datetime.now().year hpts = [ [] for i in range(24) ] m = [(6,21),(7,21),(8,21),(9,21),(10,21),(11,21),(12,21)] if complete: m.extend([(1,21),(2,21),(3,21),(4,21),(5,21)]) for i,d in enumerate(m): pts = [] for h in range(24): if ladybug: sun = sunpath.calculate_sun(month=d[0], day=d[1], hour=h) alt = math.radians(sun.altitude) az = 90 + sun.azimuth elif oldversion: dt = datetime.datetime(year, d[0], d[1], h) alt = math.radians(pysolar.solar.GetAltitudeFast(latitude, longitude, dt)) az = pysolar.solar.GetAzimuth(latitude, longitude, dt) az = -90 + az # pysolar's zero is south, ours is X direction else: dt = datetime.datetime(year, d[0], d[1], h, tzinfo=tz) alt = math.radians(pysolar.solar.get_altitude_fast(latitude, longitude, dt)) az = pysolar.solar.get_azimuth(latitude, longitude, dt) az = 90 + az # pysolar's zero is north, ours is X direction if az < 0: az = 360 + az az = math.radians(az) zc = math.sin(alt)*scale ic = math.cos(alt)*scale xc = math.cos(az)*ic yc = math.sin(az)*ic p = FreeCAD.Vector(xc,yc,zc) pts.append(p) hpts[h].append(p) if i in [0,6]: ep = FreeCAD.Vector(p) ep.multiply(1.08) if ep.z >= 0: if not oldversion: h = 24-h # not sure why this is needed now... But it is. if h == 12: if i == 0: h = "SUMMER" else: h = "WINTER" if latitude < 0: if h == "SUMMER": h = "WINTER" else: h = "SUMMER" hourpos.append((h,ep)) if i < 7: sunpaths.append(Part.makePolygon(pts)) for h in hpts: if complete: h.append(h[0]) hourpaths.append(Part.makePolygon(h)) # cut underground lines sz = 2.1*scale cube = Part.makeBox(sz,sz,sz) cube.translate(FreeCAD.Vector(-sz/2,-sz/2,-sz)) sunpaths = [sp.cut(cube) for sp in sunpaths] hourpaths = [hp.cut(cube) for hp in hourpaths] # build nodes ts = 0.005*scale # text scale mastersep = coin.SoSeparator() circlesep = coin.SoSeparator() numsep = coin.SoSeparator() pathsep = coin.SoSeparator() hoursep = coin.SoSeparator() #hournumsep = coin.SoSeparator() mastersep.addChild(circlesep) mastersep.addChild(numsep) mastersep.addChild(pathsep) mastersep.addChild(hoursep) for item in circles: circlesep.addChild(toNode(item)) for item in sunpaths: for w in item.Edges: pathsep.addChild(toNode(w)) for item in hourpaths: for w in item.Edges: hoursep.addChild(toNode(w)) for p in circlepos: text = coin.SoText2() s = p[0]-90 s = -s if s > 360: s = s - 360 if s < 0: s = 360 + s if s == 0: s = "N" elif s == 90: s = "E" elif s == 180: s = "S" elif s == 270: s = "W" else: s = str(s) text.string = s text.justification = coin.SoText2.CENTER coords = coin.SoTransform() coords.translation.setValue([p[1].x,p[1].y,p[1].z]) coords.scaleFactor.setValue([ts,ts,ts]) item = coin.SoSeparator() item.addChild(coords) item.addChild(text) numsep.addChild(item) for p in hourpos: text = coin.SoText2() s = str(p[0]) text.string = s text.justification = coin.SoText2.CENTER coords = coin.SoTransform() coords.translation.setValue([p[1].x,p[1].y,p[1].z]) coords.scaleFactor.setValue([ts,ts,ts]) item = coin.SoSeparator() item.addChild(coords) item.addChild(text) numsep.addChild(item) return mastersep
[ "def", "makeSolarDiagram", "(", "longitude", ",", "latitude", ",", "scale", "=", "1", ",", "complete", "=", "False", ",", "tz", "=", "None", ")", ":", "oldversion", "=", "False", "ladybug", "=", "False", "try", ":", "import", "ladybug", "from", "ladybug"...
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Arch/ArchSite.py#L105-L287
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/python2_version/klampt/math/spline.py
python
hermite_deriv
(x1,v1,x2,v2,u,order=1)
Returns the derivative of a hermite curve with control points x1, v1, x2, v2 at the parameter u in [0,1]. If order > 1, higher order derivatives are returned.
Returns the derivative of a hermite curve with control points x1, v1, x2, v2 at the parameter u in [0,1]. If order > 1, higher order derivatives are returned.
[ "Returns", "the", "derivative", "of", "a", "hermite", "curve", "with", "control", "points", "x1", "v1", "x2", "v2", "at", "the", "parameter", "u", "in", "[", "0", "1", "]", ".", "If", "order", ">", "1", "higher", "order", "derivatives", "are", "returne...
def hermite_deriv(x1,v1,x2,v2,u,order=1): """Returns the derivative of a hermite curve with control points x1, v1, x2, v2 at the parameter u in [0,1]. If order > 1, higher order derivatives are returned.""" assert len(x1)==len(v1) assert len(x1)==len(x2) assert len(x1)==len(v2) if order == 1: u2 = u*u dcx1 = (6.0*u2-6.0*u) dcx2 = (-6.0*u2+6.0*u) dcv1 = 3.0*u2-4.0*u+1.0 dcv2 = 3.0*u2-2.0*u dx = [0]*len(x1) for i in xrange(len(x1)): dx[i] = dcx1*x1[i] + dcx2*x2[i] + dcv1*v1[i] + dcv2*v2[i]; return dx elif order == 2: ddcx1 = 12*u ddcx2 = -12.0*u ddcv1 = 6.0*u-4.0 ddcv2 = 6.0*u-2.0 ddx = [0]*len(x1) for i in xrange(len(x1)): ddx[i] = ddcx1*x1[i] + ddcx2*x2[i] + ddcv1*v1[i] + ddcv2*v2[i] return ddx elif order == 3: cx1 = 12 cx2 = -12.0 cv1 = 6.0 cv2 = 6.0 dddx = [0]*len(x1) for i in xrange(len(x1)): dddx[i] = cx1*x1[i] + cx2*x2[i] + cv1*v1[i] + cv2*v2[i] return dddx elif order == 0: return hermite_eval(x1,v1,x2,v2,u) else: return [0]*len(x1)
[ "def", "hermite_deriv", "(", "x1", ",", "v1", ",", "x2", ",", "v2", ",", "u", ",", "order", "=", "1", ")", ":", "assert", "len", "(", "x1", ")", "==", "len", "(", "v1", ")", "assert", "len", "(", "x1", ")", "==", "len", "(", "x2", ")", "ass...
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/math/spline.py#L22-L60
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/plugins/codebrowser/codebrowser/gentag/cpptags.py
python
GenerateTags
(buff)
return formatter.rtags
GenTag interface method @return: taglib.DocStruct
GenTag interface method @return: taglib.DocStruct
[ "GenTag", "interface", "method", "@return", ":", "taglib", ".", "DocStruct" ]
def GenerateTags(buff): """GenTag interface method @return: taglib.DocStruct """ code = buff.read() # print "CODE", code lexer = get_lexer_by_name( "cpp", stripall = False ) formatter = CppFormatter() highlight( code, lexer, formatter) return formatter.rtags
[ "def", "GenerateTags", "(", "buff", ")", ":", "code", "=", "buff", ".", "read", "(", ")", "# print \"CODE\", code", "lexer", "=", "get_lexer_by_name", "(", "\"cpp\"", ",", "stripall", "=", "False", ")", "formatter", "=", "CppFormatter", "(", ")", "highlight"...
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/plugins/codebrowser/codebrowser/gentag/cpptags.py#L85-L96
rampageX/firmware-mod-kit
c94cd6aeee50d92ec5280a6dba6d74828fd3606b
src/binwalk-2.1.1/src/binwalk/core/plugin.py
python
Plugin.post_scan
(self)
Child class should override this if needed.
Child class should override this if needed.
[ "Child", "class", "should", "override", "this", "if", "needed", "." ]
def post_scan(self): ''' Child class should override this if needed. ''' pass
[ "def", "post_scan", "(", "self", ")", ":", "pass" ]
https://github.com/rampageX/firmware-mod-kit/blob/c94cd6aeee50d92ec5280a6dba6d74828fd3606b/src/binwalk-2.1.1/src/binwalk/core/plugin.py#L60-L64
facebook/fbthrift
fb9c8562aba04c4fd9b17716eb5d970cc88a75bb
build/fbcode_builder/getdeps/platform.py
python
get_available_ram
()
Returns a platform-appropriate available RAM metric in MiB.
Returns a platform-appropriate available RAM metric in MiB.
[ "Returns", "a", "platform", "-", "appropriate", "available", "RAM", "metric", "in", "MiB", "." ]
def get_available_ram() -> int: """ Returns a platform-appropriate available RAM metric in MiB. """ if sys.platform == "linux": return _get_available_ram_linux() elif sys.platform == "darwin": return _get_available_ram_macos() elif sys.platform == "win32": return _get_available_ram_windows() else: raise NotImplementedError( f"platform {sys.platform} does not have an implementation of get_available_ram" )
[ "def", "get_available_ram", "(", ")", "->", "int", ":", "if", "sys", ".", "platform", "==", "\"linux\"", ":", "return", "_get_available_ram_linux", "(", ")", "elif", "sys", ".", "platform", "==", "\"darwin\"", ":", "return", "_get_available_ram_macos", "(", ")...
https://github.com/facebook/fbthrift/blob/fb9c8562aba04c4fd9b17716eb5d970cc88a75bb/build/fbcode_builder/getdeps/platform.py#L133-L146
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/klampt/src/robotsim.py
python
ObjectPoser.__init__
(self, object: "RigidObjectModel")
r""" __init__(ObjectPoser self, RigidObjectModel object) -> ObjectPoser
r""" __init__(ObjectPoser self, RigidObjectModel object) -> ObjectPoser
[ "r", "__init__", "(", "ObjectPoser", "self", "RigidObjectModel", "object", ")", "-", ">", "ObjectPoser" ]
def __init__(self, object: "RigidObjectModel"): r""" __init__(ObjectPoser self, RigidObjectModel object) -> ObjectPoser """ _robotsim.ObjectPoser_swiginit(self, _robotsim.new_ObjectPoser(object))
[ "def", "__init__", "(", "self", ",", "object", ":", "\"RigidObjectModel\"", ")", ":", "_robotsim", ".", "ObjectPoser_swiginit", "(", "self", ",", "_robotsim", ".", "new_ObjectPoser", "(", "object", ")", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/src/robotsim.py#L3613-L3619
Tencent/CMONGO
c40380caa14e05509f46993aa8b8da966b09b0b5
buildscripts/resmokelib/selector.py
python
filter_jstests
(roots, include_files=None, include_with_all_tags=None, include_with_any_tags=None, exclude_files=None, exclude_with_all_tags=None, exclude_with_any_tags=None)
Filters out what jstests to run.
Filters out what jstests to run.
[ "Filters", "out", "what", "jstests", "to", "run", "." ]
def filter_jstests(roots, include_files=None, include_with_all_tags=None, include_with_any_tags=None, exclude_files=None, exclude_with_all_tags=None, exclude_with_any_tags=None): """ Filters out what jstests to run. """ include_files = utils.default_if_none(include_files, []) exclude_files = utils.default_if_none(exclude_files, []) # Command line options override the YAML options, and all should be defaulted to an empty list # if not specified. tags = { "exclude_with_all_tags": exclude_with_all_tags, "exclude_with_any_tags": exclude_with_any_tags, "include_with_all_tags": include_with_all_tags, "include_with_any_tags": include_with_any_tags, } cmd_line_values = ( ("exclude_with_all_tags", config.EXCLUDE_WITH_ALL_TAGS), ("exclude_with_any_tags", config.EXCLUDE_WITH_ANY_TAGS), ("include_with_all_tags", config.INCLUDE_WITH_ALL_TAGS), ("include_with_any_tags", config.INCLUDE_WITH_ANY_TAGS), ) for (tag_category, cmd_line_val) in cmd_line_values: if cmd_line_val is not None: # Ignore the empty string when it is used as a tag. Specifying an empty string on the # command line allows a user to unset the list of tags specified in the YAML # configuration. tags[tag_category] = set([tag for tag in cmd_line_val.split(",") if tag != ""]) else: tags[tag_category] = set(utils.default_if_none(tags[tag_category], [])) using_tags = 0 for name in tags: if not utils.is_string_set(tags[name]): raise TypeError("%s must be a list of strings" % (name)) if len(tags[name]) > 0: using_tags += 1 if using_tags > 1: raise ValueError("Can only specify one of 'include_with_all_tags', 'include_with_any_tags'," " 'exclude_with_all_tags', and 'exclude_with_any_tags'. If you wish to" " unset one of these options, use --includeWithAllTags='' or similar") jstests = [] for root in roots: jstests.extend(globstar.iglob(root)) (remaining, included, _) = _filter_by_filename("jstest", jstests, include_files, exclude_files) # Skip parsing comments if not using tags if not using_tags: if include_files: return list(included) elif exclude_files: return list(remaining) return jstests jstests = set(remaining) excluded = set() for filename in jstests: file_tags = set(jscomment.get_tags(filename)) if tags["include_with_all_tags"] and not tags["include_with_all_tags"] - file_tags: included.add(filename) elif tags["include_with_any_tags"] and tags["include_with_any_tags"] & file_tags: included.add(filename) elif tags["exclude_with_all_tags"] and not tags["exclude_with_all_tags"] - file_tags: excluded.add(filename) elif tags["exclude_with_any_tags"] and tags["exclude_with_any_tags"] & file_tags: excluded.add(filename) if tags["include_with_all_tags"] or tags["include_with_any_tags"]: if exclude_files: return list((included & jstests) - excluded) return list(included) else: if include_files: return list(included | (jstests - excluded)) return list(jstests - excluded)
[ "def", "filter_jstests", "(", "roots", ",", "include_files", "=", "None", ",", "include_with_all_tags", "=", "None", ",", "include_with_any_tags", "=", "None", ",", "exclude_files", "=", "None", ",", "exclude_with_all_tags", "=", "None", ",", "exclude_with_any_tags"...
https://github.com/Tencent/CMONGO/blob/c40380caa14e05509f46993aa8b8da966b09b0b5/buildscripts/resmokelib/selector.py#L105-L192
albertz/openlierox
d316c14a8eb57848ef56e9bfa7b23a56f694a51b
tools/DedicatedServerVideo/gdata/tlslite/X509CertChain.py
python
X509CertChain.validate
(self, x509TrustList)
Check the validity of the certificate chain. This checks that every certificate in the chain validates with the subsequent one, until some certificate validates with (or is identical to) one of the passed-in root certificates. The cryptlib_py module must be installed in order to use this function. @type x509TrustList: list of L{tlslite.X509.X509} @param x509TrustList: A list of trusted root certificates. The certificate chain must extend to one of these certificates to be considered valid.
Check the validity of the certificate chain.
[ "Check", "the", "validity", "of", "the", "certificate", "chain", "." ]
def validate(self, x509TrustList): """Check the validity of the certificate chain. This checks that every certificate in the chain validates with the subsequent one, until some certificate validates with (or is identical to) one of the passed-in root certificates. The cryptlib_py module must be installed in order to use this function. @type x509TrustList: list of L{tlslite.X509.X509} @param x509TrustList: A list of trusted root certificates. The certificate chain must extend to one of these certificates to be considered valid. """ import cryptlib_py c1 = None c2 = None lastC = None rootC = None try: rootFingerprints = [c.getFingerprint() for c in x509TrustList] #Check that every certificate in the chain validates with the #next one for cert1, cert2 in zip(self.x509List, self.x509List[1:]): #If we come upon a root certificate, we're done. if cert1.getFingerprint() in rootFingerprints: return True c1 = cryptlib_py.cryptImportCert(cert1.writeBytes(), cryptlib_py.CRYPT_UNUSED) c2 = cryptlib_py.cryptImportCert(cert2.writeBytes(), cryptlib_py.CRYPT_UNUSED) try: cryptlib_py.cryptCheckCert(c1, c2) except: return False cryptlib_py.cryptDestroyCert(c1) c1 = None cryptlib_py.cryptDestroyCert(c2) c2 = None #If the last certificate is one of the root certificates, we're #done. if self.x509List[-1].getFingerprint() in rootFingerprints: return True #Otherwise, find a root certificate that the last certificate #chains to, and validate them. lastC = cryptlib_py.cryptImportCert(self.x509List[-1].writeBytes(), cryptlib_py.CRYPT_UNUSED) for rootCert in x509TrustList: rootC = cryptlib_py.cryptImportCert(rootCert.writeBytes(), cryptlib_py.CRYPT_UNUSED) if self._checkChaining(lastC, rootC): try: cryptlib_py.cryptCheckCert(lastC, rootC) return True except: return False return False finally: if not (c1 is None): cryptlib_py.cryptDestroyCert(c1) if not (c2 is None): cryptlib_py.cryptDestroyCert(c2) if not (lastC is None): cryptlib_py.cryptDestroyCert(lastC) if not (rootC is None): cryptlib_py.cryptDestroyCert(rootC)
[ "def", "validate", "(", "self", ",", "x509TrustList", ")", ":", "import", "cryptlib_py", "c1", "=", "None", "c2", "=", "None", "lastC", "=", "None", "rootC", "=", "None", "try", ":", "rootFingerprints", "=", "[", "c", ".", "getFingerprint", "(", ")", "...
https://github.com/albertz/openlierox/blob/d316c14a8eb57848ef56e9bfa7b23a56f694a51b/tools/DedicatedServerVideo/gdata/tlslite/X509CertChain.py#L67-L140
adobe/chromium
cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7
native_client_sdk/src/build_tools/nacl_sdk_scons/site_tools/nacl_tools.py
python
AppendOptCCFlags
(env, is_debug=False)
Append a set of CCFLAGS that will build a debug or optimized variant depending on the value of |is_debug|. Uses optional build-specific flags for debug and optimized builds. To set these in your build.scons files you can do something like this: nacl_env.Append(DEBUG_CCFLAGS=['-gfull'], OPT_CCFLAGS=['-ffast-math', '-mfpmath=sse', '-msse2']) Args: env: Environment to modify. is_debug: Whether to set the option flags for debugging or not. Default value is False.
Append a set of CCFLAGS that will build a debug or optimized variant depending on the value of |is_debug|.
[ "Append", "a", "set", "of", "CCFLAGS", "that", "will", "build", "a", "debug", "or", "optimized", "variant", "depending", "on", "the", "value", "of", "|is_debug|", "." ]
def AppendOptCCFlags(env, is_debug=False): '''Append a set of CCFLAGS that will build a debug or optimized variant depending on the value of |is_debug|. Uses optional build-specific flags for debug and optimized builds. To set these in your build.scons files you can do something like this: nacl_env.Append(DEBUG_CCFLAGS=['-gfull'], OPT_CCFLAGS=['-ffast-math', '-mfpmath=sse', '-msse2']) Args: env: Environment to modify. is_debug: Whether to set the option flags for debugging or not. Default value is False. ''' if is_debug: env.Append(CCFLAGS=['${DEBUG_CCFLAGS}', '-O0', '-g', ]) else: env.Append(CCFLAGS=['${OPT_CCFLAGS}', '-O3', '-fno-stack-protector', '-fomit-frame-pointer', ])
[ "def", "AppendOptCCFlags", "(", "env", ",", "is_debug", "=", "False", ")", ":", "if", "is_debug", ":", "env", ".", "Append", "(", "CCFLAGS", "=", "[", "'${DEBUG_CCFLAGS}'", ",", "'-O0'", ",", "'-g'", ",", "]", ")", "else", ":", "env", ".", "Append", ...
https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/native_client_sdk/src/build_tools/nacl_sdk_scons/site_tools/nacl_tools.py#L41-L68
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/pdb.py
python
Pdb.do_p
(self, arg)
p expression Print the value of the expression.
p expression Print the value of the expression.
[ "p", "expression", "Print", "the", "value", "of", "the", "expression", "." ]
def do_p(self, arg): """p expression Print the value of the expression. """ try: self.message(repr(self._getval(arg))) except: pass
[ "def", "do_p", "(", "self", ",", "arg", ")", ":", "try", ":", "self", ".", "message", "(", "repr", "(", "self", ".", "_getval", "(", "arg", ")", ")", ")", "except", ":", "pass" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/pdb.py#L1174-L1181
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib-tk/Tkinter.py
python
Misc.winfo_rgb
(self, color)
return self._getints( self.tk.call('winfo', 'rgb', self._w, color))
Return tuple of decimal values for red, green, blue for COLOR in this widget.
Return tuple of decimal values for red, green, blue for COLOR in this widget.
[ "Return", "tuple", "of", "decimal", "values", "for", "red", "green", "blue", "for", "COLOR", "in", "this", "widget", "." ]
def winfo_rgb(self, color): """Return tuple of decimal values for red, green, blue for COLOR in this widget.""" return self._getints( self.tk.call('winfo', 'rgb', self._w, color))
[ "def", "winfo_rgb", "(", "self", ",", "color", ")", ":", "return", "self", ".", "_getints", "(", "self", ".", "tk", ".", "call", "(", "'winfo'", ",", "'rgb'", ",", "self", ".", "_w", ",", "color", ")", ")" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib-tk/Tkinter.py#L833-L837
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/logging/__init__.py
python
Handler.__init__
(self, level=NOTSET)
Initializes the instance - basically setting the formatter to None and the filter list to empty.
Initializes the instance - basically setting the formatter to None and the filter list to empty.
[ "Initializes", "the", "instance", "-", "basically", "setting", "the", "formatter", "to", "None", "and", "the", "filter", "list", "to", "empty", "." ]
def __init__(self, level=NOTSET): """ Initializes the instance - basically setting the formatter to None and the filter list to empty. """ Filterer.__init__(self) self._name = None self.level = _checkLevel(level) self.formatter = None # Add the handler to the global _handlerList (for cleanup on shutdown) _addHandlerRef(self) self.createLock()
[ "def", "__init__", "(", "self", ",", "level", "=", "NOTSET", ")", ":", "Filterer", ".", "__init__", "(", "self", ")", "self", ".", "_name", "=", "None", "self", ".", "level", "=", "_checkLevel", "(", "level", ")", "self", ".", "formatter", "=", "None...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/logging/__init__.py#L802-L813
microsoft/onnxruntime
f92e47e95b13a240e37caf7b36577983544f98fc
orttraining/orttraining/python/training/optim/fused_adam.py
python
FusedAdam.step
(self, closure=None)
return loss
Performs a single optimization step. Arguments: closure (callable, optional): A closure that reevaluates the model and returns the loss. The remaining arguments are deprecated, and are only retained (for the moment) for error-checking purposes.
Performs a single optimization step.
[ "Performs", "a", "single", "optimization", "step", "." ]
def step(self, closure=None): """Performs a single optimization step. Arguments: closure (callable, optional): A closure that reevaluates the model and returns the loss. The remaining arguments are deprecated, and are only retained (for the moment) for error-checking purposes. """ loss = None if closure is not None: loss = closure() for group in self.param_groups: bias_correction = 1 if group['bias_correction'] else 0 beta1, beta2 = group['betas'] # assume same step across group now to simplify things # per parameter step can be easily support by making it tensor, or pass list into kernel if 'step' in group: group['step'] += 1 else: group['step'] = 1 # create lists for multi-tensor apply g_16, p_16, m_16, v_16 = [], [], [], [] g_32, p_32, m_32, v_32 = [], [], [], [] for p in group['params']: if p.grad is None: continue if p.grad.data.is_sparse: raise RuntimeError( 'FusedAdam does not support sparse gradients, please consider SparseAdam instead' ) state = self.state[p] # State initialization if len(state) == 0: # Exponential moving average of gradient values state['exp_avg'] = torch.zeros_like(p.data) # Exponential moving average of squared gradient values state['exp_avg_sq'] = torch.zeros_like(p.data) if p.dtype == torch.float16: g_16.append(p.grad.data) p_16.append(p.data) m_16.append(state['exp_avg']) v_16.append(state['exp_avg_sq']) elif p.dtype == torch.float32: g_32.append(p.grad.data) p_32.append(p.data) m_32.append(state['exp_avg']) v_32.append(state['exp_avg_sq']) else: raise RuntimeError('FusedAdam only support fp16 and fp32.') if (len(g_16) > 0): self._multi_tensor_applier(self._multi_tensor_adam, self._dummy_overflow_buf, [self._TorchTensorVector(g_16), self._TorchTensorVector(p_16), self._TorchTensorVector(m_16), self._TorchTensorVector(v_16)], group['lr'], beta1, beta2, group['eps'], group['step'], self._adam_w_mode, bias_correction, group['weight_decay']) if (len(g_32) > 0): self._multi_tensor_applier(self._multi_tensor_adam, self._dummy_overflow_buf, [self._TorchTensorVector(g_32), self._TorchTensorVector(p_32), self._TorchTensorVector(m_32), self._TorchTensorVector(v_32)], group['lr'], beta1, beta2, group['eps'], group['step'], self._adam_w_mode, bias_correction, group['weight_decay']) return loss
[ "def", "step", "(", "self", ",", "closure", "=", "None", ")", ":", "loss", "=", "None", "if", "closure", "is", "not", "None", ":", "loss", "=", "closure", "(", ")", "for", "group", "in", "self", ".", "param_groups", ":", "bias_correction", "=", "1", ...
https://github.com/microsoft/onnxruntime/blob/f92e47e95b13a240e37caf7b36577983544f98fc/orttraining/orttraining/python/training/optim/fused_adam.py#L102-L190
turi-code/SFrame
796b9bdfb2fa1b881d82080754643c7e68629cd2
oss_src/unity/python/sframe/data_structures/sarray.py
python
SArray.__materialize__
(self)
For a SArray that is lazily evaluated, force persist this sarray to disk, committing all lazy evaluated operations.
For a SArray that is lazily evaluated, force persist this sarray to disk, committing all lazy evaluated operations.
[ "For", "a", "SArray", "that", "is", "lazily", "evaluated", "force", "persist", "this", "sarray", "to", "disk", "committing", "all", "lazy", "evaluated", "operations", "." ]
def __materialize__(self): """ For a SArray that is lazily evaluated, force persist this sarray to disk, committing all lazy evaluated operations. """ with cython_context(): self.__proxy__.materialize()
[ "def", "__materialize__", "(", "self", ")", ":", "with", "cython_context", "(", ")", ":", "self", ".", "__proxy__", ".", "materialize", "(", ")" ]
https://github.com/turi-code/SFrame/blob/796b9bdfb2fa1b881d82080754643c7e68629cd2/oss_src/unity/python/sframe/data_structures/sarray.py#L1275-L1281
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/grid.py
python
Grid.InsertRows
(*args, **kwargs)
return _grid.Grid_InsertRows(*args, **kwargs)
InsertRows(self, int pos=0, int numRows=1, bool updateLabels=True) -> bool
InsertRows(self, int pos=0, int numRows=1, bool updateLabels=True) -> bool
[ "InsertRows", "(", "self", "int", "pos", "=", "0", "int", "numRows", "=", "1", "bool", "updateLabels", "=", "True", ")", "-", ">", "bool" ]
def InsertRows(*args, **kwargs): """InsertRows(self, int pos=0, int numRows=1, bool updateLabels=True) -> bool""" return _grid.Grid_InsertRows(*args, **kwargs)
[ "def", "InsertRows", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_grid", ".", "Grid_InsertRows", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/grid.py#L1267-L1269
su2code/SU2
72b2fa977b64b9683a388920f05298a40d39e5c5
SU2_PY/SU2_Nastran/pysu2_nastran.py
python
Solver.updateSolution
(self)
This method updates the solution.
This method updates the solution.
[ "This", "method", "updates", "the", "solution", "." ]
def updateSolution(self): """ This method updates the solution. """ self.q_n = np.copy(self.q) self.qdot_n = np.copy(self.qdot) self.qddot_n = np.copy(self.qddot) self.a_n = np.copy(self.a) self.__reset(self.q) self.__reset(self.qdot) self.__reset(self.qddot) self.__reset(self.a) for iPoint in range(self.nPoint): self.node[iPoint].updateCoordVel()
[ "def", "updateSolution", "(", "self", ")", ":", "self", ".", "q_n", "=", "np", ".", "copy", "(", "self", ".", "q", ")", "self", ".", "qdot_n", "=", "np", ".", "copy", "(", "self", ".", "qdot", ")", "self", ".", "qddot_n", "=", "np", ".", "copy"...
https://github.com/su2code/SU2/blob/72b2fa977b64b9683a388920f05298a40d39e5c5/SU2_PY/SU2_Nastran/pysu2_nastran.py#L966-L981
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/build/waf-1.7.13/waflib/Tools/ruby.py
python
check_ruby_version
(self, minver=())
Checks if ruby is installed. If installed the variable RUBY will be set in environment. The ruby binary can be overridden by ``--with-ruby-binary`` command-line option.
Checks if ruby is installed. If installed the variable RUBY will be set in environment. The ruby binary can be overridden by ``--with-ruby-binary`` command-line option.
[ "Checks", "if", "ruby", "is", "installed", ".", "If", "installed", "the", "variable", "RUBY", "will", "be", "set", "in", "environment", ".", "The", "ruby", "binary", "can", "be", "overridden", "by", "--", "with", "-", "ruby", "-", "binary", "command", "-...
def check_ruby_version(self, minver=()): """ Checks if ruby is installed. If installed the variable RUBY will be set in environment. The ruby binary can be overridden by ``--with-ruby-binary`` command-line option. """ if Options.options.rubybinary: self.env.RUBY = Options.options.rubybinary else: self.find_program('ruby', var='RUBY') ruby = self.env.RUBY try: version = self.cmd_and_log([ruby, '-e', 'puts defined?(VERSION) ? VERSION : RUBY_VERSION']).strip() except Exception: self.fatal('could not determine ruby version') self.env.RUBY_VERSION = version try: ver = tuple(map(int, version.split("."))) except Exception: self.fatal('unsupported ruby version %r' % version) cver = '' if minver: if ver < minver: self.fatal('ruby is too old %r' % ver) cver = '.'.join([str(x) for x in minver]) else: cver = ver self.msg('Checking for ruby version %s' % str(minver or ''), cver)
[ "def", "check_ruby_version", "(", "self", ",", "minver", "=", "(", ")", ")", ":", "if", "Options", ".", "options", ".", "rubybinary", ":", "self", ".", "env", ".", "RUBY", "=", "Options", ".", "options", ".", "rubybinary", "else", ":", "self", ".", "...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/build/waf-1.7.13/waflib/Tools/ruby.py#L52-L85
gnuradio/gnuradio
09c3c4fa4bfb1a02caac74cb5334dfe065391e3b
gr-digital/python/digital/generic_mod_demod.py
python
generic_demod.add_options
(parser)
Adds generic demodulation options to the standard parser
Adds generic demodulation options to the standard parser
[ "Adds", "generic", "demodulation", "options", "to", "the", "standard", "parser" ]
def add_options(parser): """ Adds generic demodulation options to the standard parser """ # Add options shared with modulator. add_common_options(parser) # Add options specific to demodulator. parser.add_option("", "--freq-bw", type="float", default=_def_freq_bw, help="set frequency lock loop lock-in bandwidth [default=%default]") parser.add_option("", "--phase-bw", type="float", default=_def_phase_bw, help="set phase tracking loop lock-in bandwidth [default=%default]") parser.add_option("", "--timing-bw", type="float", default=_def_timing_bw, help="set timing symbol sync loop gain lock-in bandwidth [default=%default]")
[ "def", "add_options", "(", "parser", ")", ":", "# Add options shared with modulator.", "add_common_options", "(", "parser", ")", "# Add options specific to demodulator.", "parser", ".", "add_option", "(", "\"\"", ",", "\"--freq-bw\"", ",", "type", "=", "\"float\"", ",",...
https://github.com/gnuradio/gnuradio/blob/09c3c4fa4bfb1a02caac74cb5334dfe065391e3b/gr-digital/python/digital/generic_mod_demod.py#L374-L386
balloonwj/TeamTalk
dc79c40687e4c9d7bec07ff5c9782be586fd9b41
win-client/3rdParty/src/json/amalgamate.py
python
amalgamate_source
( source_top_dir=None, target_source_path=None, header_include_path=None )
Produces amalgated source. Parameters: source_top_dir: top-directory target_source_path: output .cpp path header_include_path: generated header path relative to target_source_path.
Produces amalgated source. Parameters: source_top_dir: top-directory target_source_path: output .cpp path header_include_path: generated header path relative to target_source_path.
[ "Produces", "amalgated", "source", ".", "Parameters", ":", "source_top_dir", ":", "top", "-", "directory", "target_source_path", ":", "output", ".", "cpp", "path", "header_include_path", ":", "generated", "header", "path", "relative", "to", "target_source_path", "."...
def amalgamate_source( source_top_dir=None, target_source_path=None, header_include_path=None ): """Produces amalgated source. Parameters: source_top_dir: top-directory target_source_path: output .cpp path header_include_path: generated header path relative to target_source_path. """ print 'Amalgating header...' header = AmalgamationFile( source_top_dir ) header.add_text( '/// Json-cpp amalgated header (http://jsoncpp.sourceforge.net/).' ) header.add_text( '/// It is intented to be used with #include <%s>' % header_include_path ) header.add_file( 'LICENSE', wrap_in_comment=True ) header.add_text( '#ifndef JSON_AMALGATED_H_INCLUDED' ) header.add_text( '# define JSON_AMALGATED_H_INCLUDED' ) header.add_text( '/// If defined, indicates that the source file is amalgated' ) header.add_text( '/// to prevent private header inclusion.' ) header.add_text( '#define JSON_IS_AMALGAMATION' ) #header.add_file( 'include/json/version.h' ) header.add_file( 'include/json/config.h' ) header.add_file( 'include/json/forwards.h' ) header.add_file( 'include/json/features.h' ) header.add_file( 'include/json/value.h' ) header.add_file( 'include/json/reader.h' ) header.add_file( 'include/json/writer.h' ) header.add_file( 'include/json/assertions.h' ) header.add_text( '#endif //ifndef JSON_AMALGATED_H_INCLUDED' ) target_header_path = os.path.join( os.path.dirname(target_source_path), header_include_path ) print 'Writing amalgated header to %r' % target_header_path header.write_to( target_header_path ) base, ext = os.path.splitext( header_include_path ) forward_header_include_path = base + '-forwards' + ext print 'Amalgating forward header...' header = AmalgamationFile( source_top_dir ) header.add_text( '/// Json-cpp amalgated forward header (http://jsoncpp.sourceforge.net/).' ) header.add_text( '/// It is intented to be used with #include <%s>' % forward_header_include_path ) header.add_text( '/// This header provides forward declaration for all JsonCpp types.' ) header.add_file( 'LICENSE', wrap_in_comment=True ) header.add_text( '#ifndef JSON_FORWARD_AMALGATED_H_INCLUDED' ) header.add_text( '# define JSON_FORWARD_AMALGATED_H_INCLUDED' ) header.add_text( '/// If defined, indicates that the source file is amalgated' ) header.add_text( '/// to prevent private header inclusion.' ) header.add_text( '#define JSON_IS_AMALGAMATION' ) header.add_file( 'include/json/config.h' ) header.add_file( 'include/json/forwards.h' ) header.add_text( '#endif //ifndef JSON_FORWARD_AMALGATED_H_INCLUDED' ) target_forward_header_path = os.path.join( os.path.dirname(target_source_path), forward_header_include_path ) print 'Writing amalgated forward header to %r' % target_forward_header_path header.write_to( target_forward_header_path ) print 'Amalgating source...' source = AmalgamationFile( source_top_dir ) source.add_text( '/// Json-cpp amalgated source (http://jsoncpp.sourceforge.net/).' ) source.add_text( '/// It is intented to be used with #include "%s"' % target_source_path ) source.add_file( 'LICENSE', wrap_in_comment=True ) source.add_text( '' ) source.add_text( '#include "%s"' % header_include_path ) source.add_text( '' ) lib_json = 'src/lib_json' source.add_file( os.path.join(lib_json, 'json_tool.h') ) source.add_file( os.path.join(lib_json, 'json_reader.cpp') ) source.add_file( os.path.join(lib_json, 'json_batchallocator.h') ) source.add_file( os.path.join(lib_json, 'json_valueiterator.inl') ) source.add_file( os.path.join(lib_json, 'json_value.cpp') ) source.add_file( os.path.join(lib_json, 'json_writer.cpp') ) print 'Writing amalgated source to %r' % target_source_path source.write_to( target_source_path )
[ "def", "amalgamate_source", "(", "source_top_dir", "=", "None", ",", "target_source_path", "=", "None", ",", "header_include_path", "=", "None", ")", ":", "print", "'Amalgating header...'", "header", "=", "AmalgamationFile", "(", "source_top_dir", ")", "header", "."...
https://github.com/balloonwj/TeamTalk/blob/dc79c40687e4c9d7bec07ff5c9782be586fd9b41/win-client/3rdParty/src/json/amalgamate.py#L50-L122
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
samples/ide/activegrid/tool/process.py
python
IOBuffer._doReadline
(self, n)
return retval
Pop the front line (or n bytes of it, whichever is less) from the internal buffer and return it.
Pop the front line (or n bytes of it, whichever is less) from the internal buffer and return it.
[ "Pop", "the", "front", "line", "(", "or", "n", "bytes", "of", "it", "whichever", "is", "less", ")", "from", "the", "internal", "buffer", "and", "return", "it", "." ]
def _doReadline(self, n): """Pop the front line (or n bytes of it, whichever is less) from the internal buffer and return it. """ idx = self.__buf.find('\n') if idx == -1: idx = len(self.__buf) else: idx += 1 # include the '\n' if n is not None: idx = min(idx, n) retval, self.__buf = self.__buf[:idx], self.__buf[idx:] return retval
[ "def", "_doReadline", "(", "self", ",", "n", ")", ":", "idx", "=", "self", ".", "__buf", ".", "find", "(", "'\\n'", ")", "if", "idx", "==", "-", "1", ":", "idx", "=", "len", "(", "self", ".", "__buf", ")", "else", ":", "idx", "+=", "1", "# in...
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/samples/ide/activegrid/tool/process.py#L2020-L2032
microsoft/TSS.MSR
0f2516fca2cd9929c31d5450e39301c9bde43688
TSS.Py/src/TpmTypes.py
python
TPM2_EncryptDecrypt2_REQUEST.initFromTpm
(self, buf)
TpmMarshaller method
TpmMarshaller method
[ "TpmMarshaller", "method" ]
def initFromTpm(self, buf): """ TpmMarshaller method """ self.inData = buf.readSizedByteBuf() self.decrypt = buf.readByte() self.mode = buf.readShort() self.ivIn = buf.readSizedByteBuf()
[ "def", "initFromTpm", "(", "self", ",", "buf", ")", ":", "self", ".", "inData", "=", "buf", ".", "readSizedByteBuf", "(", ")", "self", ".", "decrypt", "=", "buf", ".", "readByte", "(", ")", "self", ".", "mode", "=", "buf", ".", "readShort", "(", ")...
https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L11481-L11486
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqt/mantidqt/widgets/fitpropertybrowser/fitpropertybrowser.py
python
FitPropertyBrowser._get_allowed_spectra
(self)
return allowed_spectra
Get the workspaces and spectra that can be fitted from the tracked workspaces.
Get the workspaces and spectra that can be fitted from the tracked workspaces.
[ "Get", "the", "workspaces", "and", "spectra", "that", "can", "be", "fitted", "from", "the", "tracked", "workspaces", "." ]
def _get_allowed_spectra(self): """ Get the workspaces and spectra that can be fitted from the tracked workspaces. """ allowed_spectra = {} output_wsnames = [self.getWorkspaceList().item(ii).text() for ii in range(self.getWorkspaceList().count())] for ax in self.canvas.figure.get_axes(): try: for ws_name, artists in ax.tracked_workspaces.items(): # we don't want to include the fit workspace in our selection if ws_name in output_wsnames: continue #loop through arists and get relevant spec numbers if spec_num represents a spectrum as opposed to a bin axes. spectrum_list = [artist.spec_num for artist in artists if artist.is_spec] if spectrum_list: spectrum_list = sorted(list(set(spectrum_list))) allowed_spectra[ws_name] = spectrum_list except AttributeError: # scripted plots have no tracked_workspaces pass self.allowed_spectra = allowed_spectra return allowed_spectra
[ "def", "_get_allowed_spectra", "(", "self", ")", ":", "allowed_spectra", "=", "{", "}", "output_wsnames", "=", "[", "self", ".", "getWorkspaceList", "(", ")", ".", "item", "(", "ii", ")", ".", "text", "(", ")", "for", "ii", "in", "range", "(", "self", ...
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqt/mantidqt/widgets/fitpropertybrowser/fitpropertybrowser.py#L107-L130
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/dtypes/common.py
python
is_categorical
(arr)
return isinstance(arr, ABCCategorical) or is_categorical_dtype(arr)
Check whether an array-like is a Categorical instance. Parameters ---------- arr : array-like The array-like to check. Returns ------- boolean Whether or not the array-like is of a Categorical instance. Examples -------- >>> is_categorical([1, 2, 3]) False Categoricals, Series Categoricals, and CategoricalIndex will return True. >>> cat = pd.Categorical([1, 2, 3]) >>> is_categorical(cat) True >>> is_categorical(pd.Series(cat)) True >>> is_categorical(pd.CategoricalIndex([1, 2, 3])) True
Check whether an array-like is a Categorical instance.
[ "Check", "whether", "an", "array", "-", "like", "is", "a", "Categorical", "instance", "." ]
def is_categorical(arr) -> bool: """ Check whether an array-like is a Categorical instance. Parameters ---------- arr : array-like The array-like to check. Returns ------- boolean Whether or not the array-like is of a Categorical instance. Examples -------- >>> is_categorical([1, 2, 3]) False Categoricals, Series Categoricals, and CategoricalIndex will return True. >>> cat = pd.Categorical([1, 2, 3]) >>> is_categorical(cat) True >>> is_categorical(pd.Series(cat)) True >>> is_categorical(pd.CategoricalIndex([1, 2, 3])) True """ return isinstance(arr, ABCCategorical) or is_categorical_dtype(arr)
[ "def", "is_categorical", "(", "arr", ")", "->", "bool", ":", "return", "isinstance", "(", "arr", ",", "ABCCategorical", ")", "or", "is_categorical_dtype", "(", "arr", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/dtypes/common.py#L339-L369
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/autograph/pyct/cfg.py
python
GraphBuilder.exit_cond_section
(self, section_id)
Exits a conditional section.
Exits a conditional section.
[ "Exits", "a", "conditional", "section", "." ]
def exit_cond_section(self, section_id): """Exits a conditional section.""" for split in self.cond_leaves[section_id]: self.leaves |= split del self.cond_entry[section_id] del self.cond_leaves[section_id]
[ "def", "exit_cond_section", "(", "self", ",", "section_id", ")", ":", "for", "split", "in", "self", ".", "cond_leaves", "[", "section_id", "]", ":", "self", ".", "leaves", "|=", "split", "del", "self", ".", "cond_entry", "[", "section_id", "]", "del", "s...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/autograph/pyct/cfg.py#L538-L543
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/contrib/learn/python/learn/graph_actions.py
python
train
(graph, output_dir, train_op, loss_op, global_step_tensor=None, init_op=None, init_feed_dict=None, init_fn=None, log_every_steps=10, supervisor_is_chief=True, supervisor_master='', supervisor_save_model_secs=600, keep_checkpoint_max=5, supervisor_save_summaries_steps=100, feed_fn=None, steps=None, fail_on_nan_loss=True, monitors=None, max_steps=None)
Train a model. Given `graph`, a directory to write outputs to (`output_dir`), and some ops, run a training loop. The given `train_op` performs one step of training on the model. The `loss_op` represents the objective function of the training. It is expected to increment the `global_step_tensor`, a scalar integer tensor counting training steps. This function uses `Supervisor` to initialize the graph (from a checkpoint if one is available in `output_dir`), write summaries defined in the graph, and write regular checkpoints as defined by `supervisor_save_model_secs`. Training continues until `global_step_tensor` evaluates to `max_steps`, or, if `fail_on_nan_loss`, until `loss_op` evaluates to `NaN`. In that case the program is terminated with exit code 1. Args: graph: A graph to train. It is expected that this graph is not in use elsewhere. output_dir: A directory to write outputs to. train_op: An op that performs one training step when run. loss_op: A scalar loss tensor. global_step_tensor: A tensor representing the global step. If none is given, one is extracted from the graph using the same logic as in `Supervisor`. init_op: An op that initializes the graph. If `None`, use `Supervisor`'s default. init_feed_dict: A dictionary that maps `Tensor` objects to feed values. This feed dictionary will be used when `init_op` is evaluated. init_fn: Optional callable passed to Supervisor to initialize the model. log_every_steps: Output logs regularly. The logs contain timing data and the current loss. supervisor_is_chief: Whether the current process is the chief supervisor in charge of restoring the model and running standard services. supervisor_master: The master string to use when preparing the session. supervisor_save_model_secs: Save a checkpoint every `supervisor_save_model_secs` seconds when training. keep_checkpoint_max: The maximum number of recent checkpoint files to keep. As new files are created, older files are deleted. If None or 0, all checkpoint files are kept. This is simply passed as the max_to_keep arg to tf.Saver constructor. supervisor_save_summaries_steps: Save summaries every `supervisor_save_summaries_steps` seconds when training. feed_fn: A function that is called every iteration to produce a `feed_dict` passed to `session.run` calls. Optional. steps: Trains for this many steps (e.g. current global step + `steps`). fail_on_nan_loss: If true, raise `NanLossDuringTrainingError` if `loss_op` evaluates to `NaN`. If false, continue training as if nothing happened. monitors: List of `BaseMonitor` subclass instances. Used for callbacks inside the training loop. max_steps: Number of total steps for which to train model. If `None`, train forever. Two calls fit(steps=100) means 200 training iterations. On the other hand two calls of fit(max_steps=100) means, second call will not do any iteration since first call did all 100 steps. Returns: The final loss value. Raises: ValueError: If `output_dir`, `train_op`, `loss_op`, or `global_step_tensor` is not provided. See `tf.contrib.framework.get_global_step` for how we look up the latter if not provided explicitly. NanLossDuringTrainingError: If `fail_on_nan_loss` is `True`, and loss ever evaluates to `NaN`. ValueError: If both `steps` and `max_steps` are not `None`.
Train a model.
[ "Train", "a", "model", "." ]
def train(graph, output_dir, train_op, loss_op, global_step_tensor=None, init_op=None, init_feed_dict=None, init_fn=None, log_every_steps=10, supervisor_is_chief=True, supervisor_master='', supervisor_save_model_secs=600, keep_checkpoint_max=5, supervisor_save_summaries_steps=100, feed_fn=None, steps=None, fail_on_nan_loss=True, monitors=None, max_steps=None): """Train a model. Given `graph`, a directory to write outputs to (`output_dir`), and some ops, run a training loop. The given `train_op` performs one step of training on the model. The `loss_op` represents the objective function of the training. It is expected to increment the `global_step_tensor`, a scalar integer tensor counting training steps. This function uses `Supervisor` to initialize the graph (from a checkpoint if one is available in `output_dir`), write summaries defined in the graph, and write regular checkpoints as defined by `supervisor_save_model_secs`. Training continues until `global_step_tensor` evaluates to `max_steps`, or, if `fail_on_nan_loss`, until `loss_op` evaluates to `NaN`. In that case the program is terminated with exit code 1. Args: graph: A graph to train. It is expected that this graph is not in use elsewhere. output_dir: A directory to write outputs to. train_op: An op that performs one training step when run. loss_op: A scalar loss tensor. global_step_tensor: A tensor representing the global step. If none is given, one is extracted from the graph using the same logic as in `Supervisor`. init_op: An op that initializes the graph. If `None`, use `Supervisor`'s default. init_feed_dict: A dictionary that maps `Tensor` objects to feed values. This feed dictionary will be used when `init_op` is evaluated. init_fn: Optional callable passed to Supervisor to initialize the model. log_every_steps: Output logs regularly. The logs contain timing data and the current loss. supervisor_is_chief: Whether the current process is the chief supervisor in charge of restoring the model and running standard services. supervisor_master: The master string to use when preparing the session. supervisor_save_model_secs: Save a checkpoint every `supervisor_save_model_secs` seconds when training. keep_checkpoint_max: The maximum number of recent checkpoint files to keep. As new files are created, older files are deleted. If None or 0, all checkpoint files are kept. This is simply passed as the max_to_keep arg to tf.Saver constructor. supervisor_save_summaries_steps: Save summaries every `supervisor_save_summaries_steps` seconds when training. feed_fn: A function that is called every iteration to produce a `feed_dict` passed to `session.run` calls. Optional. steps: Trains for this many steps (e.g. current global step + `steps`). fail_on_nan_loss: If true, raise `NanLossDuringTrainingError` if `loss_op` evaluates to `NaN`. If false, continue training as if nothing happened. monitors: List of `BaseMonitor` subclass instances. Used for callbacks inside the training loop. max_steps: Number of total steps for which to train model. If `None`, train forever. Two calls fit(steps=100) means 200 training iterations. On the other hand two calls of fit(max_steps=100) means, second call will not do any iteration since first call did all 100 steps. Returns: The final loss value. Raises: ValueError: If `output_dir`, `train_op`, `loss_op`, or `global_step_tensor` is not provided. See `tf.contrib.framework.get_global_step` for how we look up the latter if not provided explicitly. NanLossDuringTrainingError: If `fail_on_nan_loss` is `True`, and loss ever evaluates to `NaN`. ValueError: If both `steps` and `max_steps` are not `None`. """ while True: try: return _train_internal(graph, output_dir, train_op, loss_op, global_step_tensor, init_op, init_feed_dict, init_fn, log_every_steps, supervisor_is_chief, supervisor_master, supervisor_save_model_secs, keep_checkpoint_max, supervisor_save_summaries_steps, feed_fn, steps, fail_on_nan_loss, monitors, max_steps) except errors.AbortedError: # Happens when PS restarts, keep training. logging.warning('Training got Aborted error. Keep training.')
[ "def", "train", "(", "graph", ",", "output_dir", ",", "train_op", ",", "loss_op", ",", "global_step_tensor", "=", "None", ",", "init_op", "=", "None", ",", "init_feed_dict", "=", "None", ",", "init_fn", "=", "None", ",", "log_every_steps", "=", "10", ",", ...
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/contrib/learn/python/learn/graph_actions.py#L286-L392
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/saved_model/utils_impl.py
python
get_variables_path
(export_dir)
return os.path.join( compat.as_text(get_variables_dir(export_dir)), compat.as_text(constants.VARIABLES_FILENAME))
Return the variables path, used as the prefix for checkpoint files.
Return the variables path, used as the prefix for checkpoint files.
[ "Return", "the", "variables", "path", "used", "as", "the", "prefix", "for", "checkpoint", "files", "." ]
def get_variables_path(export_dir): """Return the variables path, used as the prefix for checkpoint files.""" return os.path.join( compat.as_text(get_variables_dir(export_dir)), compat.as_text(constants.VARIABLES_FILENAME))
[ "def", "get_variables_path", "(", "export_dir", ")", ":", "return", "os", ".", "path", ".", "join", "(", "compat", ".", "as_text", "(", "get_variables_dir", "(", "export_dir", ")", ")", ",", "compat", ".", "as_text", "(", "constants", ".", "VARIABLES_FILENAM...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/saved_model/utils_impl.py#L225-L229
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/ops/mask_ops.py
python
kleene_or
( left: Union[bool, np.ndarray], right: Union[bool, np.ndarray], left_mask: Optional[np.ndarray], right_mask: Optional[np.ndarray], )
return result, mask
Boolean ``or`` using Kleene logic. Values are NA where we have ``NA | NA`` or ``NA | False``. ``NA | True`` is considered True. Parameters ---------- left, right : ndarray, NA, or bool The values of the array. left_mask, right_mask : ndarray, optional The masks. Only one of these may be None, which implies that the associated `left` or `right` value is a scalar. Returns ------- result, mask: ndarray[bool] The result of the logical or, and the new mask.
Boolean ``or`` using Kleene logic.
[ "Boolean", "or", "using", "Kleene", "logic", "." ]
def kleene_or( left: Union[bool, np.ndarray], right: Union[bool, np.ndarray], left_mask: Optional[np.ndarray], right_mask: Optional[np.ndarray], ): """ Boolean ``or`` using Kleene logic. Values are NA where we have ``NA | NA`` or ``NA | False``. ``NA | True`` is considered True. Parameters ---------- left, right : ndarray, NA, or bool The values of the array. left_mask, right_mask : ndarray, optional The masks. Only one of these may be None, which implies that the associated `left` or `right` value is a scalar. Returns ------- result, mask: ndarray[bool] The result of the logical or, and the new mask. """ # To reduce the number of cases, we ensure that `left` & `left_mask` # always come from an array, not a scalar. This is safe, since because # A | B == B | A if left_mask is None: return kleene_or(right, left, right_mask, left_mask) assert isinstance(left, np.ndarray) raise_for_nan(right, method="or") if right is libmissing.NA: result = left.copy() else: result = left | right if right_mask is not None: # output is unknown where (False & NA), (NA & False), (NA & NA) left_false = ~(left | left_mask) right_false = ~(right | right_mask) mask = ( (left_false & right_mask) | (right_false & left_mask) | (left_mask & right_mask) ) else: if right is True: mask = np.zeros_like(left_mask) elif right is libmissing.NA: mask = (~left & ~left_mask) | left_mask else: # False mask = left_mask.copy() return result, mask
[ "def", "kleene_or", "(", "left", ":", "Union", "[", "bool", ",", "np", ".", "ndarray", "]", ",", "right", ":", "Union", "[", "bool", ",", "np", ".", "ndarray", "]", ",", "left_mask", ":", "Optional", "[", "np", ".", "ndarray", "]", ",", "right_mask...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/ops/mask_ops.py#L11-L69
psi4/psi4
be533f7f426b6ccc263904e55122899b16663395
psi4/driver/driver_cbs.py
python
_expand_scheme_orders
(scheme, basisname, basiszeta, wfnname, options, natom)
return NEED
Check that the length of *basiszeta* array matches the implied degree of extrapolation in *scheme* name. Return a dictionary of same length as basiszeta, with *basisname* and *basiszeta* distributed therein.
Check that the length of *basiszeta* array matches the implied degree of extrapolation in *scheme* name. Return a dictionary of same length as basiszeta, with *basisname* and *basiszeta* distributed therein.
[ "Check", "that", "the", "length", "of", "*", "basiszeta", "*", "array", "matches", "the", "implied", "degree", "of", "extrapolation", "in", "*", "scheme", "*", "name", ".", "Return", "a", "dictionary", "of", "same", "length", "as", "basiszeta", "with", "*"...
def _expand_scheme_orders(scheme, basisname, basiszeta, wfnname, options, natom): """Check that the length of *basiszeta* array matches the implied degree of extrapolation in *scheme* name. Return a dictionary of same length as basiszeta, with *basisname* and *basiszeta* distributed therein. """ Nxtpl = len(basiszeta) if int(scheme.__name__.split('_')[-1]) != Nxtpl: raise ValidationError("""Call to '%s' not valid with '%s' basis sets.""" % (scheme.__name__, len(basiszeta))) f_fields = ['f_wfn', 'f_basis', 'f_zeta', 'f_energy', 'f_gradient', 'f_hessian', 'f_options'] NEED = {} for idx in range(Nxtpl): NEED[_lmh_labels[Nxtpl][idx]] = dict( zip(f_fields, [ wfnname, basisname[idx], basiszeta[idx], 0.0, core.Matrix(natom, 3), core.Matrix(3 * natom, 3 * natom), options ])) return NEED
[ "def", "_expand_scheme_orders", "(", "scheme", ",", "basisname", ",", "basiszeta", ",", "wfnname", ",", "options", ",", "natom", ")", ":", "Nxtpl", "=", "len", "(", "basiszeta", ")", "if", "int", "(", "scheme", ".", "__name__", ".", "split", "(", "'_'", ...
https://github.com/psi4/psi4/blob/be533f7f426b6ccc263904e55122899b16663395/psi4/driver/driver_cbs.py#L1792-L1812
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_core.py
python
SettableHeaderColumn.SetSortable
(*args, **kwargs)
return _core_.SettableHeaderColumn_SetSortable(*args, **kwargs)
SetSortable(self, bool sortable)
SetSortable(self, bool sortable)
[ "SetSortable", "(", "self", "bool", "sortable", ")" ]
def SetSortable(*args, **kwargs): """SetSortable(self, bool sortable)""" return _core_.SettableHeaderColumn_SetSortable(*args, **kwargs)
[ "def", "SetSortable", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "SettableHeaderColumn_SetSortable", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L16504-L16506
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/propgrid.py
python
PyLongStringDialogAdapter.__init__
(self, *args, **kwargs)
__init__(self) -> PyLongStringDialogAdapter
__init__(self) -> PyLongStringDialogAdapter
[ "__init__", "(", "self", ")", "-", ">", "PyLongStringDialogAdapter" ]
def __init__(self, *args, **kwargs): """__init__(self) -> PyLongStringDialogAdapter""" _propgrid.PyLongStringDialogAdapter_swiginit(self,_propgrid.new_PyLongStringDialogAdapter(*args, **kwargs)) self._SetSelf(self); self._RegisterMethods()
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_propgrid", ".", "PyLongStringDialogAdapter_swiginit", "(", "self", ",", "_propgrid", ".", "new_PyLongStringDialogAdapter", "(", "*", "args", ",", "*", "*", "kwargs", ")", ...
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/propgrid.py#L4059-L4062
KhronosGroup/SPIRV-LLVM
1eb85593f3fe2c39379b9a9b088d51eda4f42b8b
examples/Kaleidoscope/MCJIT/cached/genk-timing.py
python
generateKScript
(filename, numFuncs, elementsPerFunc, funcsBetweenExec, callWeighting, timingScript)
Generate a random Kaleidoscope script based on the given parameters
Generate a random Kaleidoscope script based on the given parameters
[ "Generate", "a", "random", "Kaleidoscope", "script", "based", "on", "the", "given", "parameters" ]
def generateKScript(filename, numFuncs, elementsPerFunc, funcsBetweenExec, callWeighting, timingScript): """ Generate a random Kaleidoscope script based on the given parameters """ print "Generating " + filename print(" %d functions, %d elements per function, %d functions between execution" % (numFuncs, elementsPerFunc, funcsBetweenExec)) print(" Call weighting = %f" % callWeighting) script = KScriptGenerator(filename) script.setCallWeighting(callWeighting) script.writeComment("===========================================================================") script.writeComment("Auto-generated script") script.writeComment(" %d functions, %d elements per function, %d functions between execution" % (numFuncs, elementsPerFunc, funcsBetweenExec)) script.writeComment(" call weighting = %f" % callWeighting) script.writeComment("===========================================================================") script.writeEmptyLine() script.writePredefinedFunctions() funcsSinceLastExec = 0 for i in range(numFuncs): script.writeFunction(elementsPerFunc) funcsSinceLastExec += 1 if funcsSinceLastExec == funcsBetweenExec: script.writeFunctionCall() funcsSinceLastExec = 0 # Always end with a function call if funcsSinceLastExec > 0: script.writeFunctionCall() script.writeEmptyLine() script.writeFinalFunctionCounts() funcsCalled = len(script.calledFunctions) print " Called %d of %d functions, %d total" % (funcsCalled, numFuncs, script.totalCallsExecuted) timingScript.writeTimingCall(filename, numFuncs, funcsCalled, script.totalCallsExecuted)
[ "def", "generateKScript", "(", "filename", ",", "numFuncs", ",", "elementsPerFunc", ",", "funcsBetweenExec", ",", "callWeighting", ",", "timingScript", ")", ":", "print", "\"Generating \"", "+", "filename", "print", "(", "\" %d functions, %d elements per function, %d fun...
https://github.com/KhronosGroup/SPIRV-LLVM/blob/1eb85593f3fe2c39379b9a9b088d51eda4f42b8b/examples/Kaleidoscope/MCJIT/cached/genk-timing.py#L174-L204
wyrover/book-code
7f4883d9030d553bc6bcfa3da685e34789839900
3rdparty/protobuf/python/setup.py
python
generate_proto
(source, require = True)
Invokes the Protocol Compiler to generate a _pb2.py from the given .proto file. Does nothing if the output already exists and is newer than the input.
Invokes the Protocol Compiler to generate a _pb2.py from the given .proto file. Does nothing if the output already exists and is newer than the input.
[ "Invokes", "the", "Protocol", "Compiler", "to", "generate", "a", "_pb2", ".", "py", "from", "the", "given", ".", "proto", "file", ".", "Does", "nothing", "if", "the", "output", "already", "exists", "and", "is", "newer", "than", "the", "input", "." ]
def generate_proto(source, require = True): """Invokes the Protocol Compiler to generate a _pb2.py from the given .proto file. Does nothing if the output already exists and is newer than the input.""" if not require and not os.path.exists(source): return output = source.replace(".proto", "_pb2.py").replace("../src/", "") if (not os.path.exists(output) or (os.path.exists(source) and os.path.getmtime(source) > os.path.getmtime(output))): print("Generating %s..." % output) if not os.path.exists(source): sys.stderr.write("Can't find required file: %s\n" % source) sys.exit(-1) if protoc is None: sys.stderr.write( "protoc is not installed nor found in ../src. Please compile it " "or install the binary package.\n") sys.exit(-1) protoc_command = [ protoc, "-I../src", "-I.", "--python_out=.", source ] if subprocess.call(protoc_command) != 0: sys.exit(-1)
[ "def", "generate_proto", "(", "source", ",", "require", "=", "True", ")", ":", "if", "not", "require", "and", "not", "os", ".", "path", ".", "exists", "(", "source", ")", ":", "return", "output", "=", "source", ".", "replace", "(", "\".proto\"", ",", ...
https://github.com/wyrover/book-code/blob/7f4883d9030d553bc6bcfa3da685e34789839900/3rdparty/protobuf/python/setup.py#L49-L76
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
src/python/turicreate/toolkits/_feature_engineering/_word_trimmer.py
python
RareWordTrimmer.__repr__
(self)
return out + "\n" + out2
Return a string description of the model, including a description of the training data, training statistics, and model hyper-parameters. Returns ------- out : string A description of the model.
Return a string description of the model, including a description of the training data, training statistics, and model hyper-parameters.
[ "Return", "a", "string", "description", "of", "the", "model", "including", "a", "description", "of", "the", "training", "data", "training", "statistics", "and", "model", "hyper", "-", "parameters", "." ]
def __repr__(self): """ Return a string description of the model, including a description of the training data, training statistics, and model hyper-parameters. Returns ------- out : string A description of the model. """ accessible_fields = {"vocabulary": "The vocabulary of the trimmed input."} (sections, section_titles) = self._get_summary_struct() out = _toolkit_repr_print(self, sections, section_titles, width=30) out2 = _summarize_accessible_fields(accessible_fields, width=30) return out + "\n" + out2
[ "def", "__repr__", "(", "self", ")", ":", "accessible_fields", "=", "{", "\"vocabulary\"", ":", "\"The vocabulary of the trimmed input.\"", "}", "(", "sections", ",", "section_titles", ")", "=", "self", ".", "_get_summary_struct", "(", ")", "out", "=", "_toolkit_r...
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/python/turicreate/toolkits/_feature_engineering/_word_trimmer.py#L392-L406
facebook/openr
ed38bdfd6bf290084bfab4821b59f83e7b59315d
openr/py/openr/cli/utils/commands.py
python
OpenrCtrlCmd._run
(self, client: Any, *args, **kwargs)
To be implemented by sub-command. @param: client - Client to connect to the Open/R server. Set it to `Any` type here for the overridden method to choose the type in its parameter. Currently, we have two types of the clients: 1. OpenrCtrl.Client for common APIs; 2. OpenrCtrlCpp client which implements stream APIs.
To be implemented by sub-command.
[ "To", "be", "implemented", "by", "sub", "-", "command", "." ]
def _run(self, client: Any, *args, **kwargs) -> Any: """ To be implemented by sub-command. @param: client - Client to connect to the Open/R server. Set it to `Any` type here for the overridden method to choose the type in its parameter. Currently, we have two types of the clients: 1. OpenrCtrl.Client for common APIs; 2. OpenrCtrlCpp client which implements stream APIs. """ raise NotImplementedError
[ "def", "_run", "(", "self", ",", "client", ":", "Any", ",", "*", "args", ",", "*", "*", "kwargs", ")", "->", "Any", ":", "raise", "NotImplementedError" ]
https://github.com/facebook/openr/blob/ed38bdfd6bf290084bfab4821b59f83e7b59315d/openr/py/openr/cli/utils/commands.py#L48-L58
PixarAnimationStudios/USD
faed18ce62c8736b02413635b584a2f637156bad
pxr/usdImaging/usdAppUtils/rendererArgs.py
python
GetPluginIdFromArgument
(argumentString)
return None
Returns plugin id, if found, for the passed in argument string. Valid argument strings are returned by GetAllPluginArguments().
Returns plugin id, if found, for the passed in argument string.
[ "Returns", "plugin", "id", "if", "found", "for", "the", "passed", "in", "argument", "string", "." ]
def GetPluginIdFromArgument(argumentString): """ Returns plugin id, if found, for the passed in argument string. Valid argument strings are returned by GetAllPluginArguments(). """ from pxr import UsdImagingGL for p in UsdImagingGL.Engine.GetRendererPlugins(): if argumentString == UsdImagingGL.Engine.GetRendererDisplayName(p): return p return None
[ "def", "GetPluginIdFromArgument", "(", "argumentString", ")", ":", "from", "pxr", "import", "UsdImagingGL", "for", "p", "in", "UsdImagingGL", ".", "Engine", ".", "GetRendererPlugins", "(", ")", ":", "if", "argumentString", "==", "UsdImagingGL", ".", "Engine", "....
https://github.com/PixarAnimationStudios/USD/blob/faed18ce62c8736b02413635b584a2f637156bad/pxr/usdImaging/usdAppUtils/rendererArgs.py#L37-L48