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
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/build/waf-1.7.13/lmbrwaflib/default_settings.py
python
load_user_settings
(ctx)
return ctx.user_settings
Get the user_settings (values that override default_settings) :param ctx: Context :return: The override settings contained in a ConfigParser object
Get the user_settings (values that override default_settings)
[ "Get", "the", "user_settings", "(", "values", "that", "override", "default_settings", ")" ]
def load_user_settings(ctx): """ Get the user_settings (values that override default_settings) :param ctx: Context :return: The override settings contained in a ConfigParser object """ try: return ctx.user_settings except AttributeError: pass ctx.user_settings = LUMBERYARD_SETTINGS return ctx.user_settings
[ "def", "load_user_settings", "(", "ctx", ")", ":", "try", ":", "return", "ctx", ".", "user_settings", "except", "AttributeError", ":", "pass", "ctx", ".", "user_settings", "=", "LUMBERYARD_SETTINGS", "return", "ctx", ".", "user_settings" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/build/waf-1.7.13/lmbrwaflib/default_settings.py#L152-L164
microsoft/TSS.MSR
0f2516fca2cd9929c31d5450e39301c9bde43688
TSS.Py/src/TpmTypes.py
python
TPML_AC_CAPABILITIES.toTpm
(self, buf)
TpmMarshaller method
TpmMarshaller method
[ "TpmMarshaller", "method" ]
def toTpm(self, buf): """ TpmMarshaller method """ buf.writeObjArr(self.acCapabilities)
[ "def", "toTpm", "(", "self", ",", "buf", ")", ":", "buf", ".", "writeObjArr", "(", "self", ".", "acCapabilities", ")" ]
https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L9028-L9030
ycm-core/ycmd
fc0fb7e5e15176cc5a2a30c80956335988c6b59a
ycmd/completers/language_server/language_server_protocol.py
python
ServerFileState.GetFileCloseAction
( self )
return ServerFileState.NO_ACTION
Progress the state for a file which was closed in the client. Returns one of the actions to perform: either NO_ACTION or CLOSE_FILE.
Progress the state for a file which was closed in the client. Returns one of the actions to perform: either NO_ACTION or CLOSE_FILE.
[ "Progress", "the", "state", "for", "a", "file", "which", "was", "closed", "in", "the", "client", ".", "Returns", "one", "of", "the", "actions", "to", "perform", ":", "either", "NO_ACTION", "or", "CLOSE_FILE", "." ]
def GetFileCloseAction( self ): """Progress the state for a file which was closed in the client. Returns one of the actions to perform: either NO_ACTION or CLOSE_FILE.""" if self.state == ServerFileState.OPEN: self.state = ServerFileState.CLOSED return ServerFileState.CLOSE_FILE self.state = ServerFileState.CLOSED return ServerFileState.NO_ACTION
[ "def", "GetFileCloseAction", "(", "self", ")", ":", "if", "self", ".", "state", "==", "ServerFileState", ".", "OPEN", ":", "self", ".", "state", "=", "ServerFileState", ".", "CLOSED", "return", "ServerFileState", ".", "CLOSE_FILE", "self", ".", "state", "=", "ServerFileState", ".", "CLOSED", "return", "ServerFileState", ".", "NO_ACTION" ]
https://github.com/ycm-core/ycmd/blob/fc0fb7e5e15176cc5a2a30c80956335988c6b59a/ycmd/completers/language_server/language_server_protocol.py#L212-L220
jackaudio/jack2
21b293dbc37d42446141a08922cdec0d2550c6a0
waflib/Task.py
python
Task.hash_constraints
(self)
return (tuple(self.before), tuple(self.after), tuple(self.ext_in), tuple(self.ext_out), self.__class__.__name__, self.hcode)
Identifies a task type for all the constraints relevant for the scheduler: precedence, file production :return: a hash value :rtype: string
Identifies a task type for all the constraints relevant for the scheduler: precedence, file production
[ "Identifies", "a", "task", "type", "for", "all", "the", "constraints", "relevant", "for", "the", "scheduler", ":", "precedence", "file", "production" ]
def hash_constraints(self): """ Identifies a task type for all the constraints relevant for the scheduler: precedence, file production :return: a hash value :rtype: string """ return (tuple(self.before), tuple(self.after), tuple(self.ext_in), tuple(self.ext_out), self.__class__.__name__, self.hcode)
[ "def", "hash_constraints", "(", "self", ")", ":", "return", "(", "tuple", "(", "self", ".", "before", ")", ",", "tuple", "(", "self", ".", "after", ")", ",", "tuple", "(", "self", ".", "ext_in", ")", ",", "tuple", "(", "self", ".", "ext_out", ")", ",", "self", ".", "__class__", ".", "__name__", ",", "self", ".", "hcode", ")" ]
https://github.com/jackaudio/jack2/blob/21b293dbc37d42446141a08922cdec0d2550c6a0/waflib/Task.py#L430-L437
apple/swift-lldb
d74be846ef3e62de946df343e8c234bde93a8912
utils/vim-lldb/python-vim-lldb/lldb_controller.py
python
LLDBController.completeCommand
(self, a, l, p)
Returns a list of viable completions for command a with length l and cursor at p
Returns a list of viable completions for command a with length l and cursor at p
[ "Returns", "a", "list", "of", "viable", "completions", "for", "command", "a", "with", "length", "l", "and", "cursor", "at", "p" ]
def completeCommand(self, a, l, p): """ Returns a list of viable completions for command a with length l and cursor at p """ assert l[0] == 'L' # Remove first 'L' character that all commands start with l = l[1:] # Adjust length as string has 1 less character p = int(p) - 1 result = lldb.SBStringList() num = self.commandInterpreter.HandleCompletion(l, p, 1, -1, result) if num == -1: # FIXME: insert completion character... what's a completion # character? pass elif num == -2: # FIXME: replace line with result.GetStringAtIndex(0) pass if result.GetSize() > 0: results = [_f for _f in [result.GetStringAtIndex(x) for x in range(result.GetSize())] if _f] return results else: return []
[ "def", "completeCommand", "(", "self", ",", "a", ",", "l", ",", "p", ")", ":", "assert", "l", "[", "0", "]", "==", "'L'", "# Remove first 'L' character that all commands start with", "l", "=", "l", "[", "1", ":", "]", "# Adjust length as string has 1 less character", "p", "=", "int", "(", "p", ")", "-", "1", "result", "=", "lldb", ".", "SBStringList", "(", ")", "num", "=", "self", ".", "commandInterpreter", ".", "HandleCompletion", "(", "l", ",", "p", ",", "1", ",", "-", "1", ",", "result", ")", "if", "num", "==", "-", "1", ":", "# FIXME: insert completion character... what's a completion", "# character?", "pass", "elif", "num", "==", "-", "2", ":", "# FIXME: replace line with result.GetStringAtIndex(0)", "pass", "if", "result", ".", "GetSize", "(", ")", ">", "0", ":", "results", "=", "[", "_f", "for", "_f", "in", "[", "result", ".", "GetStringAtIndex", "(", "x", ")", "for", "x", "in", "range", "(", "result", ".", "GetSize", "(", ")", ")", "]", "if", "_f", "]", "return", "results", "else", ":", "return", "[", "]" ]
https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/utils/vim-lldb/python-vim-lldb/lldb_controller.py#L85-L111
trailofbits/llvm-sanitizer-tutorial
d29dfeec7f51fbf234fd0080f28f2b30cd0b6e99
llvm/utils/benchmark/tools/gbench/util.py
python
classify_input_file
(filename)
return ftype, err_msg
Return a tuple (type, msg) where 'type' specifies the classified type of 'filename'. If 'type' is 'IT_Invalid' then 'msg' is a human readable string represeting the error.
Return a tuple (type, msg) where 'type' specifies the classified type of 'filename'. If 'type' is 'IT_Invalid' then 'msg' is a human readable string represeting the error.
[ "Return", "a", "tuple", "(", "type", "msg", ")", "where", "type", "specifies", "the", "classified", "type", "of", "filename", ".", "If", "type", "is", "IT_Invalid", "then", "msg", "is", "a", "human", "readable", "string", "represeting", "the", "error", "." ]
def classify_input_file(filename): """ Return a tuple (type, msg) where 'type' specifies the classified type of 'filename'. If 'type' is 'IT_Invalid' then 'msg' is a human readable string represeting the error. """ ftype = IT_Invalid err_msg = None if not os.path.exists(filename): err_msg = "'%s' does not exist" % filename elif not os.path.isfile(filename): err_msg = "'%s' does not name a file" % filename elif is_executable_file(filename): ftype = IT_Executable elif is_json_file(filename): ftype = IT_JSON else: err_msg = "'%s' does not name a valid benchmark executable or JSON file" % filename return ftype, err_msg
[ "def", "classify_input_file", "(", "filename", ")", ":", "ftype", "=", "IT_Invalid", "err_msg", "=", "None", "if", "not", "os", ".", "path", ".", "exists", "(", "filename", ")", ":", "err_msg", "=", "\"'%s' does not exist\"", "%", "filename", "elif", "not", "os", ".", "path", ".", "isfile", "(", "filename", ")", ":", "err_msg", "=", "\"'%s' does not name a file\"", "%", "filename", "elif", "is_executable_file", "(", "filename", ")", ":", "ftype", "=", "IT_Executable", "elif", "is_json_file", "(", "filename", ")", ":", "ftype", "=", "IT_JSON", "else", ":", "err_msg", "=", "\"'%s' does not name a valid benchmark executable or JSON file\"", "%", "filename", "return", "ftype", ",", "err_msg" ]
https://github.com/trailofbits/llvm-sanitizer-tutorial/blob/d29dfeec7f51fbf234fd0080f28f2b30cd0b6e99/llvm/utils/benchmark/tools/gbench/util.py#L54-L72
livecode/livecode
4606a10ea10b16d5071d0f9f263ccdd7ede8b31d
gyp/pylib/gyp/generator/ninja.py
python
NinjaWriter.AppendPostbuildVariable
(self, variables, spec, output, binary, is_command_start=False)
Adds a 'postbuild' variable if there is a postbuild for |output|.
Adds a 'postbuild' variable if there is a postbuild for |output|.
[ "Adds", "a", "postbuild", "variable", "if", "there", "is", "a", "postbuild", "for", "|output|", "." ]
def AppendPostbuildVariable(self, variables, spec, output, binary, is_command_start=False): """Adds a 'postbuild' variable if there is a postbuild for |output|.""" postbuild = self.GetPostbuildCommand(spec, output, binary, is_command_start) if postbuild: variables.append(('postbuilds', postbuild))
[ "def", "AppendPostbuildVariable", "(", "self", ",", "variables", ",", "spec", ",", "output", ",", "binary", ",", "is_command_start", "=", "False", ")", ":", "postbuild", "=", "self", ".", "GetPostbuildCommand", "(", "spec", ",", "output", ",", "binary", ",", "is_command_start", ")", "if", "postbuild", ":", "variables", ".", "append", "(", "(", "'postbuilds'", ",", "postbuild", ")", ")" ]
https://github.com/livecode/livecode/blob/4606a10ea10b16d5071d0f9f263ccdd7ede8b31d/gyp/pylib/gyp/generator/ninja.py#L1350-L1355
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/klampt/src/robotsim.py
python
SimBody.getID
(self)
return _robotsim.SimBody_getID(self)
r""" getID(SimBody self) -> int Returns the object ID that this body associated with.
r""" getID(SimBody self) -> int
[ "r", "getID", "(", "SimBody", "self", ")", "-", ">", "int" ]
def getID(self) -> "int": r""" getID(SimBody self) -> int Returns the object ID that this body associated with. """ return _robotsim.SimBody_getID(self)
[ "def", "getID", "(", "self", ")", "->", "\"int\"", ":", "return", "_robotsim", ".", "SimBody_getID", "(", "self", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/src/robotsim.py#L7807-L7815
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/distutils/cmd.py
python
Command.copy_tree
(self, infile, outfile, preserve_mode=1, preserve_times=1, preserve_symlinks=0, level=1)
return dir_util.copy_tree(infile, outfile, preserve_mode, preserve_times, preserve_symlinks, not self.force, dry_run=self.dry_run)
Copy an entire directory tree respecting verbose, dry-run, and force flags.
Copy an entire directory tree respecting verbose, dry-run, and force flags.
[ "Copy", "an", "entire", "directory", "tree", "respecting", "verbose", "dry", "-", "run", "and", "force", "flags", "." ]
def copy_tree(self, infile, outfile, preserve_mode=1, preserve_times=1, preserve_symlinks=0, level=1): """Copy an entire directory tree respecting verbose, dry-run, and force flags. """ return dir_util.copy_tree(infile, outfile, preserve_mode, preserve_times, preserve_symlinks, not self.force, dry_run=self.dry_run)
[ "def", "copy_tree", "(", "self", ",", "infile", ",", "outfile", ",", "preserve_mode", "=", "1", ",", "preserve_times", "=", "1", ",", "preserve_symlinks", "=", "0", ",", "level", "=", "1", ")", ":", "return", "dir_util", ".", "copy_tree", "(", "infile", ",", "outfile", ",", "preserve_mode", ",", "preserve_times", ",", "preserve_symlinks", ",", "not", "self", ".", "force", ",", "dry_run", "=", "self", ".", "dry_run", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/distutils/cmd.py#L349-L356
francinexue/xuefu
b6ff79747a42e020588c0c0a921048e08fe4680c
ctpx/ctp2/ctptd.py
python
CtpTd.onRtnRepealFromBankToFutureByFuture
(self, RspRepealField)
期货发起冲正银行转期货请求,银行处理完毕后报盘发回的通知
期货发起冲正银行转期货请求,银行处理完毕后报盘发回的通知
[ "期货发起冲正银行转期货请求,银行处理完毕后报盘发回的通知" ]
def onRtnRepealFromBankToFutureByFuture(self, RspRepealField): """期货发起冲正银行转期货请求,银行处理完毕后报盘发回的通知""" pass
[ "def", "onRtnRepealFromBankToFutureByFuture", "(", "self", ",", "RspRepealField", ")", ":", "pass" ]
https://github.com/francinexue/xuefu/blob/b6ff79747a42e020588c0c0a921048e08fe4680c/ctpx/ctp2/ctptd.py#L515-L517
ricardoquesada/Spidermonkey
4a75ea2543408bd1b2c515aa95901523eeef7858
python/psutil/psutil/_psbsd.py
python
Process.get_process_name
(self)
return _psutil_bsd.get_process_name(self.pid)
Return process name as a string of limited len (15).
Return process name as a string of limited len (15).
[ "Return", "process", "name", "as", "a", "string", "of", "limited", "len", "(", "15", ")", "." ]
def get_process_name(self): """Return process name as a string of limited len (15).""" return _psutil_bsd.get_process_name(self.pid)
[ "def", "get_process_name", "(", "self", ")", ":", "return", "_psutil_bsd", ".", "get_process_name", "(", "self", ".", "pid", ")" ]
https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/python/psutil/psutil/_psbsd.py#L197-L199
google/syzygy
8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5
third_party/numpy/files/numpy/distutils/fcompiler/gnu.py
python
GnuFCompiler.gnu_version_match
(self, version_string)
Handle the different versions of GNU fortran compilers
Handle the different versions of GNU fortran compilers
[ "Handle", "the", "different", "versions", "of", "GNU", "fortran", "compilers" ]
def gnu_version_match(self, version_string): """Handle the different versions of GNU fortran compilers""" m = re.match(r'GNU Fortran', version_string) if not m: return None m = re.match(r'GNU Fortran\s+95.*?([0-9-.]+)', version_string) if m: return ('gfortran', m.group(1)) m = re.match(r'GNU Fortran.*?([0-9-.]+)', version_string) if m: v = m.group(1) if v.startswith('0') or v.startswith('2') or v.startswith('3'): # the '0' is for early g77's return ('g77', v) else: # at some point in the 4.x series, the ' 95' was dropped # from the version string return ('gfortran', v)
[ "def", "gnu_version_match", "(", "self", ",", "version_string", ")", ":", "m", "=", "re", ".", "match", "(", "r'GNU Fortran'", ",", "version_string", ")", "if", "not", "m", ":", "return", "None", "m", "=", "re", ".", "match", "(", "r'GNU Fortran\\s+95.*?([0-9-.]+)'", ",", "version_string", ")", "if", "m", ":", "return", "(", "'gfortran'", ",", "m", ".", "group", "(", "1", ")", ")", "m", "=", "re", ".", "match", "(", "r'GNU Fortran.*?([0-9-.]+)'", ",", "version_string", ")", "if", "m", ":", "v", "=", "m", ".", "group", "(", "1", ")", "if", "v", ".", "startswith", "(", "'0'", ")", "or", "v", ".", "startswith", "(", "'2'", ")", "or", "v", ".", "startswith", "(", "'3'", ")", ":", "# the '0' is for early g77's", "return", "(", "'g77'", ",", "v", ")", "else", ":", "# at some point in the 4.x series, the ' 95' was dropped", "# from the version string", "return", "(", "'gfortran'", ",", "v", ")" ]
https://github.com/google/syzygy/blob/8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5/third_party/numpy/files/numpy/distutils/fcompiler/gnu.py#L34-L51
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/setuptools/command/easy_install.py
python
ScriptWriter.get_args
(cls, dist, header=None)
Yield write_script() argument tuples for a distribution's console_scripts and gui_scripts entry points.
Yield write_script() argument tuples for a distribution's console_scripts and gui_scripts entry points.
[ "Yield", "write_script", "()", "argument", "tuples", "for", "a", "distribution", "s", "console_scripts", "and", "gui_scripts", "entry", "points", "." ]
def get_args(cls, dist, header=None): """ Yield write_script() argument tuples for a distribution's console_scripts and gui_scripts entry points. """ if header is None: header = cls.get_header() spec = str(dist.as_requirement()) for type_ in 'console', 'gui': group = type_ + '_scripts' for name, ep in dist.get_entry_map(group).items(): cls._ensure_safe_name(name) script_text = cls.template % locals() args = cls._get_script_args(type_, name, header, script_text) for res in args: yield res
[ "def", "get_args", "(", "cls", ",", "dist", ",", "header", "=", "None", ")", ":", "if", "header", "is", "None", ":", "header", "=", "cls", ".", "get_header", "(", ")", "spec", "=", "str", "(", "dist", ".", "as_requirement", "(", ")", ")", "for", "type_", "in", "'console'", ",", "'gui'", ":", "group", "=", "type_", "+", "'_scripts'", "for", "name", ",", "ep", "in", "dist", ".", "get_entry_map", "(", "group", ")", ".", "items", "(", ")", ":", "cls", ".", "_ensure_safe_name", "(", "name", ")", "script_text", "=", "cls", ".", "template", "%", "locals", "(", ")", "args", "=", "cls", ".", "_get_script_args", "(", "type_", ",", "name", ",", "header", ",", "script_text", ")", "for", "res", "in", "args", ":", "yield", "res" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/setuptools/command/easy_install.py#L2108-L2123
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/aui.py
python
AuiDefaultDockArt.__init__
(self, *args, **kwargs)
__init__(self) -> AuiDefaultDockArt
__init__(self) -> AuiDefaultDockArt
[ "__init__", "(", "self", ")", "-", ">", "AuiDefaultDockArt" ]
def __init__(self, *args, **kwargs): """__init__(self) -> AuiDefaultDockArt""" _aui.AuiDefaultDockArt_swiginit(self,_aui.new_AuiDefaultDockArt(*args, **kwargs))
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_aui", ".", "AuiDefaultDockArt_swiginit", "(", "self", ",", "_aui", ".", "new_AuiDefaultDockArt", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/aui.py#L1031-L1033
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/setuptools/py3/setuptools/command/bdist_egg.py
python
bdist_egg.call_command
(self, cmdname, **kw)
return cmd
Invoke reinitialized command `cmdname` with keyword args
Invoke reinitialized command `cmdname` with keyword args
[ "Invoke", "reinitialized", "command", "cmdname", "with", "keyword", "args" ]
def call_command(self, cmdname, **kw): """Invoke reinitialized command `cmdname` with keyword args""" for dirname in INSTALL_DIRECTORY_ATTRS: kw.setdefault(dirname, self.bdist_dir) kw.setdefault('skip_build', self.skip_build) kw.setdefault('dry_run', self.dry_run) cmd = self.reinitialize_command(cmdname, **kw) self.run_command(cmdname) return cmd
[ "def", "call_command", "(", "self", ",", "cmdname", ",", "*", "*", "kw", ")", ":", "for", "dirname", "in", "INSTALL_DIRECTORY_ATTRS", ":", "kw", ".", "setdefault", "(", "dirname", ",", "self", ".", "bdist_dir", ")", "kw", ".", "setdefault", "(", "'skip_build'", ",", "self", ".", "skip_build", ")", "kw", ".", "setdefault", "(", "'dry_run'", ",", "self", ".", "dry_run", ")", "cmd", "=", "self", ".", "reinitialize_command", "(", "cmdname", ",", "*", "*", "kw", ")", "self", ".", "run_command", "(", "cmdname", ")", "return", "cmd" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py3/setuptools/command/bdist_egg.py#L143-L151
glotzerlab/hoomd-blue
f7f97abfa3fcc2522fa8d458d65d0aeca7ba781a
hoomd/data/typeconverter.py
python
OnlyFrom.__str__
(self)
return "OnlyFrom[{self.options}]"
str: String representation of the validator.
str: String representation of the validator.
[ "str", ":", "String", "representation", "of", "the", "validator", "." ]
def __str__(self): """str: String representation of the validator.""" return "OnlyFrom[{self.options}]"
[ "def", "__str__", "(", "self", ")", ":", "return", "\"OnlyFrom[{self.options}]\"" ]
https://github.com/glotzerlab/hoomd-blue/blob/f7f97abfa3fcc2522fa8d458d65d0aeca7ba781a/hoomd/data/typeconverter.py#L273-L275
apache/incubator-mxnet
f03fb23f1d103fec9541b5ae59ee06b1734a51d9
python/mxnet/base.py
python
c_array_buf
(ctype, buf)
return (ctype * len(buf)).from_buffer(buf)
Create ctypes array from a Python buffer. For primitive types, using the buffer created with array.array is faster than a c_array call. Parameters ---------- ctype : ctypes data type Data type of the array we want to convert to, such as mx_float. buf : buffer type Data content. Returns ------- out : ctypes array Created ctypes array. Examples -------- >>> x = mx.base.c_array_buf(mx.base.mx_float, array.array('i', [1, 2, 3])) >>> print len(x) 3 >>> x[1] 2.0
Create ctypes array from a Python buffer. For primitive types, using the buffer created with array.array is faster than a c_array call.
[ "Create", "ctypes", "array", "from", "a", "Python", "buffer", ".", "For", "primitive", "types", "using", "the", "buffer", "created", "with", "array", ".", "array", "is", "faster", "than", "a", "c_array", "call", "." ]
def c_array_buf(ctype, buf): """Create ctypes array from a Python buffer. For primitive types, using the buffer created with array.array is faster than a c_array call. Parameters ---------- ctype : ctypes data type Data type of the array we want to convert to, such as mx_float. buf : buffer type Data content. Returns ------- out : ctypes array Created ctypes array. Examples -------- >>> x = mx.base.c_array_buf(mx.base.mx_float, array.array('i', [1, 2, 3])) >>> print len(x) 3 >>> x[1] 2.0 """ return (ctype * len(buf)).from_buffer(buf)
[ "def", "c_array_buf", "(", "ctype", ",", "buf", ")", ":", "return", "(", "ctype", "*", "len", "(", "buf", ")", ")", ".", "from_buffer", "(", "buf", ")" ]
https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/base.py#L418-L444
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_core.py
python
Menu.SetParent
(*args, **kwargs)
return _core_.Menu_SetParent(*args, **kwargs)
SetParent(self, Menu parent)
SetParent(self, Menu parent)
[ "SetParent", "(", "self", "Menu", "parent", ")" ]
def SetParent(*args, **kwargs): """SetParent(self, Menu parent)""" return _core_.Menu_SetParent(*args, **kwargs)
[ "def", "SetParent", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "Menu_SetParent", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L12242-L12244
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
tools/json_schema_compiler/json_schema.py
python
CachedLoad
(filename)
return copy.deepcopy(_cache[filename])
Equivalent to Load(filename), but caches results for subsequent calls
Equivalent to Load(filename), but caches results for subsequent calls
[ "Equivalent", "to", "Load", "(", "filename", ")", "but", "caches", "results", "for", "subsequent", "calls" ]
def CachedLoad(filename): """Equivalent to Load(filename), but caches results for subsequent calls""" if filename not in _cache: _cache[filename] = Load(filename) # Return a copy of the object so that any changes a caller makes won't affect # the next caller. return copy.deepcopy(_cache[filename])
[ "def", "CachedLoad", "(", "filename", ")", ":", "if", "filename", "not", "in", "_cache", ":", "_cache", "[", "filename", "]", "=", "Load", "(", "filename", ")", "# Return a copy of the object so that any changes a caller makes won't affect", "# the next caller.", "return", "copy", ".", "deepcopy", "(", "_cache", "[", "filename", "]", ")" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/json_schema_compiler/json_schema.py#L43-L49
miyosuda/TensorFlowAndroidMNIST
7b5a4603d2780a8a2834575706e9001977524007
jni-build/jni/include/tensorflow/python/training/supervisor.py
python
Supervisor._default_global_step_tensor
(self)
Returns the global_step from the default graph. Returns: The global step `Tensor` or `None`.
Returns the global_step from the default graph.
[ "Returns", "the", "global_step", "from", "the", "default", "graph", "." ]
def _default_global_step_tensor(self): """Returns the global_step from the default graph. Returns: The global step `Tensor` or `None`. """ try: gs = ops.get_default_graph().get_tensor_by_name("global_step:0") if gs.dtype.base_dtype in [dtypes.int32, dtypes.int64]: return gs else: logging.warning("Found 'global_step' is not an int type: %s", gs.dtype) return None except KeyError: return None
[ "def", "_default_global_step_tensor", "(", "self", ")", ":", "try", ":", "gs", "=", "ops", ".", "get_default_graph", "(", ")", ".", "get_tensor_by_name", "(", "\"global_step:0\"", ")", "if", "gs", ".", "dtype", ".", "base_dtype", "in", "[", "dtypes", ".", "int32", ",", "dtypes", ".", "int64", "]", ":", "return", "gs", "else", ":", "logging", ".", "warning", "(", "\"Found 'global_step' is not an int type: %s\"", ",", "gs", ".", "dtype", ")", "return", "None", "except", "KeyError", ":", "return", "None" ]
https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/python/training/supervisor.py#L824-L838
cksystemsgroup/scalloc
049857919b5fa1d539c9e4206e353daca2e87394
tools/cpplint.py
python
_BlockInfo.CheckBegin
(self, filename, clean_lines, linenum, error)
Run checks that applies to text up to the opening brace. This is mostly for checking the text after the class identifier and the "{", usually where the base class is specified. For other blocks, there isn't much to check, so we always pass. 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.
Run checks that applies to text up to the opening brace.
[ "Run", "checks", "that", "applies", "to", "text", "up", "to", "the", "opening", "brace", "." ]
def CheckBegin(self, filename, clean_lines, linenum, error): """Run checks that applies to text up to the opening brace. This is mostly for checking the text after the class identifier and the "{", usually where the base class is specified. For other blocks, there isn't much to check, so we always pass. 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. """ pass
[ "def", "CheckBegin", "(", "self", ",", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "pass" ]
https://github.com/cksystemsgroup/scalloc/blob/049857919b5fa1d539c9e4206e353daca2e87394/tools/cpplint.py#L1651-L1664
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/ipython/py2/IPython/core/formatters.py
python
BaseFormatter.lookup
(self, obj)
return self.lookup_by_type(_get_type(obj))
Look up the formatter for a given instance. Parameters ---------- obj : object instance Returns ------- f : callable The registered formatting callable for the type. Raises ------ KeyError if the type has not been registered.
Look up the formatter for a given instance. Parameters ---------- obj : object instance
[ "Look", "up", "the", "formatter", "for", "a", "given", "instance", ".", "Parameters", "----------", "obj", ":", "object", "instance" ]
def lookup(self, obj): """Look up the formatter for a given instance. Parameters ---------- obj : object instance Returns ------- f : callable The registered formatting callable for the type. Raises ------ KeyError if the type has not been registered. """ # look for singleton first obj_id = id(obj) if obj_id in self.singleton_printers: return self.singleton_printers[obj_id] # then lookup by type return self.lookup_by_type(_get_type(obj))
[ "def", "lookup", "(", "self", ",", "obj", ")", ":", "# look for singleton first", "obj_id", "=", "id", "(", "obj", ")", "if", "obj_id", "in", "self", ".", "singleton_printers", ":", "return", "self", ".", "singleton_printers", "[", "obj_id", "]", "# then lookup by type", "return", "self", ".", "lookup_by_type", "(", "_get_type", "(", "obj", ")", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py2/IPython/core/formatters.py#L367-L388
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/tensor_array_ops.py
python
_EagerTensorArray.handle
(self)
return self._handle
For compatibility; handles are not meaningful when eager is enabled.
For compatibility; handles are not meaningful when eager is enabled.
[ "For", "compatibility", ";", "handles", "are", "not", "meaningful", "when", "eager", "is", "enabled", "." ]
def handle(self): """For compatibility; handles are not meaningful when eager is enabled.""" return self._handle
[ "def", "handle", "(", "self", ")", ":", "return", "self", ".", "_handle" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/tensor_array_ops.py#L711-L713
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/setuptools/py2/setuptools/extern/__init__.py
python
VendorImporter.find_module
(self, fullname, path=None)
return self
Return self when fullname starts with root_name and the target module is one vendored through this importer.
Return self when fullname starts with root_name and the target module is one vendored through this importer.
[ "Return", "self", "when", "fullname", "starts", "with", "root_name", "and", "the", "target", "module", "is", "one", "vendored", "through", "this", "importer", "." ]
def find_module(self, fullname, path=None): """ Return self when fullname starts with root_name and the target module is one vendored through this importer. """ root, base, target = fullname.partition(self.root_name + '.') if root: return if not any(map(target.startswith, self.vendored_names)): return return self
[ "def", "find_module", "(", "self", ",", "fullname", ",", "path", "=", "None", ")", ":", "root", ",", "base", ",", "target", "=", "fullname", ".", "partition", "(", "self", ".", "root_name", "+", "'.'", ")", "if", "root", ":", "return", "if", "not", "any", "(", "map", "(", "target", ".", "startswith", ",", "self", ".", "vendored_names", ")", ")", ":", "return", "return", "self" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py2/setuptools/extern/__init__.py#L23-L33
eventql/eventql
7ca0dbb2e683b525620ea30dc40540a22d5eb227
deps/3rdparty/spidermonkey/mozjs/python/bitstring/bitstring.py
python
ConstBitStream._getbytepos
(self)
return self._pos // 8
Return the current position in the stream in bytes. Must be byte aligned.
Return the current position in the stream in bytes. Must be byte aligned.
[ "Return", "the", "current", "position", "in", "the", "stream", "in", "bytes", ".", "Must", "be", "byte", "aligned", "." ]
def _getbytepos(self): """Return the current position in the stream in bytes. Must be byte aligned.""" if self._pos % 8: raise ByteAlignError("Not byte aligned in _getbytepos().") return self._pos // 8
[ "def", "_getbytepos", "(", "self", ")", ":", "if", "self", ".", "_pos", "%", "8", ":", "raise", "ByteAlignError", "(", "\"Not byte aligned in _getbytepos().\"", ")", "return", "self", ".", "_pos", "//", "8" ]
https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/python/bitstring/bitstring.py#L3792-L3796
indutny/candor
48e7260618f5091c80a3416828e2808cad3ea22e
tools/gyp/pylib/gyp/xcodeproj_file.py
python
XCObject.Descendants
(self)
return descendants
Returns a list of all of this object's descendants, including this object.
Returns a list of all of this object's descendants, including this object.
[ "Returns", "a", "list", "of", "all", "of", "this", "object", "s", "descendants", "including", "this", "object", "." ]
def Descendants(self): """Returns a list of all of this object's descendants, including this object. """ children = self.Children() descendants = [self] for child in children: descendants.extend(child.Descendants()) return descendants
[ "def", "Descendants", "(", "self", ")", ":", "children", "=", "self", ".", "Children", "(", ")", "descendants", "=", "[", "self", "]", "for", "child", "in", "children", ":", "descendants", ".", "extend", "(", "child", ".", "Descendants", "(", ")", ")", "return", "descendants" ]
https://github.com/indutny/candor/blob/48e7260618f5091c80a3416828e2808cad3ea22e/tools/gyp/pylib/gyp/xcodeproj_file.py#L474-L483
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/klampt/vis/ipython/widgets.py
python
KlamptWidget.addXform
(self,name="Xform1",length=DEFAULT_AXIS_LENGTH,width=DEFAULT_AXIS_WIDTH)
Adds a new transform widget to the world with the given line length and width
Adds a new transform widget to the world with the given line length and width
[ "Adds", "a", "new", "transform", "widget", "to", "the", "world", "with", "the", "given", "line", "length", "and", "width" ]
def addXform(self,name="Xform1",length=DEFAULT_AXIS_LENGTH,width=DEFAULT_AXIS_WIDTH): """Adds a new transform widget to the world with the given line length and width""" self._extras[name] = ('RigidTransform',(length,width)) self._do_rpc({'type':'add_xform','name':name,'length':length,'width':width})
[ "def", "addXform", "(", "self", ",", "name", "=", "\"Xform1\"", ",", "length", "=", "DEFAULT_AXIS_LENGTH", ",", "width", "=", "DEFAULT_AXIS_WIDTH", ")", ":", "self", ".", "_extras", "[", "name", "]", "=", "(", "'RigidTransform'", ",", "(", "length", ",", "width", ")", ")", "self", ".", "_do_rpc", "(", "{", "'type'", ":", "'add_xform'", ",", "'name'", ":", "name", ",", "'length'", ":", "length", ",", "'width'", ":", "width", "}", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/vis/ipython/widgets.py#L481-L484
cvxpy/cvxpy
5165b4fb750dfd237de8659383ef24b4b2e33aaf
cvxpy/atoms/norm_nuc.py
python
normNuc.numeric
(self, values)
return np.linalg.norm(values[0], 'nuc')
Returns the nuclear norm (i.e. the sum of the singular values) of A.
Returns the nuclear norm (i.e. the sum of the singular values) of A.
[ "Returns", "the", "nuclear", "norm", "(", "i", ".", "e", ".", "the", "sum", "of", "the", "singular", "values", ")", "of", "A", "." ]
def numeric(self, values): """Returns the nuclear norm (i.e. the sum of the singular values) of A. """ return np.linalg.norm(values[0], 'nuc')
[ "def", "numeric", "(", "self", ",", "values", ")", ":", "return", "np", ".", "linalg", ".", "norm", "(", "values", "[", "0", "]", ",", "'nuc'", ")" ]
https://github.com/cvxpy/cvxpy/blob/5165b4fb750dfd237de8659383ef24b4b2e33aaf/cvxpy/atoms/norm_nuc.py#L33-L36
PaddlePaddle/PaddleOCR
b756bf5f8c90142e0d89d3db0163965c686b6ffe
ppstructure/table/table_metric/table_metric.py
python
TEDS.load_html_tree
(self, node, parent=None)
Converts HTML tree to the format required by apted
Converts HTML tree to the format required by apted
[ "Converts", "HTML", "tree", "to", "the", "format", "required", "by", "apted" ]
def load_html_tree(self, node, parent=None): ''' Converts HTML tree to the format required by apted ''' global __tokens__ if node.tag == 'td': if self.structure_only: cell = [] else: self.__tokens__ = [] self.tokenize(node) cell = self.__tokens__[1:-1].copy() new_node = TableTree(node.tag, int(node.attrib.get('colspan', '1')), int(node.attrib.get('rowspan', '1')), cell, *deque()) else: new_node = TableTree(node.tag, None, None, None, *deque()) if parent is not None: parent.children.append(new_node) if node.tag != 'td': for n in node.getchildren(): self.load_html_tree(n, new_node) if parent is None: return new_node
[ "def", "load_html_tree", "(", "self", ",", "node", ",", "parent", "=", "None", ")", ":", "global", "__tokens__", "if", "node", ".", "tag", "==", "'td'", ":", "if", "self", ".", "structure_only", ":", "cell", "=", "[", "]", "else", ":", "self", ".", "__tokens__", "=", "[", "]", "self", ".", "tokenize", "(", "node", ")", "cell", "=", "self", ".", "__tokens__", "[", "1", ":", "-", "1", "]", ".", "copy", "(", ")", "new_node", "=", "TableTree", "(", "node", ".", "tag", ",", "int", "(", "node", ".", "attrib", ".", "get", "(", "'colspan'", ",", "'1'", ")", ")", ",", "int", "(", "node", ".", "attrib", ".", "get", "(", "'rowspan'", ",", "'1'", ")", ")", ",", "cell", ",", "*", "deque", "(", ")", ")", "else", ":", "new_node", "=", "TableTree", "(", "node", ".", "tag", ",", "None", ",", "None", ",", "None", ",", "*", "deque", "(", ")", ")", "if", "parent", "is", "not", "None", ":", "parent", ".", "children", ".", "append", "(", "new_node", ")", "if", "node", ".", "tag", "!=", "'td'", ":", "for", "n", "in", "node", ".", "getchildren", "(", ")", ":", "self", ".", "load_html_tree", "(", "n", ",", "new_node", ")", "if", "parent", "is", "None", ":", "return", "new_node" ]
https://github.com/PaddlePaddle/PaddleOCR/blob/b756bf5f8c90142e0d89d3db0163965c686b6ffe/ppstructure/table/table_metric/table_metric.py#L151-L174
Geant4/geant4
84f33a068c5e0acb278dc4e4acb6a2822c6e7bca
environments/g4py/source/g4thread.py
python
_TBeamOn
(self, nevent)
generate events in a thread
generate events in a thread
[ "generate", "events", "in", "a", "thread" ]
def _TBeamOn(self, nevent): "generate events in a thread" args = (nevent,) thread.start_new_thread(self.BeamOn, args)
[ "def", "_TBeamOn", "(", "self", ",", "nevent", ")", ":", "args", "=", "(", "nevent", ",", ")", "thread", ".", "start_new_thread", "(", "self", ".", "BeamOn", ",", "args", ")" ]
https://github.com/Geant4/geant4/blob/84f33a068c5e0acb278dc4e4acb6a2822c6e7bca/environments/g4py/source/g4thread.py#L17-L20
netket/netket
0d534e54ecbf25b677ea72af6b85947979420652
netket/graph/graph.py
python
Graph._compute_automorphisms
(self)
return result
Compute the graph autmorphisms of this graph.
Compute the graph autmorphisms of this graph.
[ "Compute", "the", "graph", "autmorphisms", "of", "this", "graph", "." ]
def _compute_automorphisms(self): """ Compute the graph autmorphisms of this graph. """ colors = self.edge_colors result = self._igraph.get_isomorphisms_vf2( edge_color1=colors, edge_color2=colors ) # sort them s.t. the identity comes first result = np.unique(result, axis=0).tolist() result = PermutationGroup([Permutation(i) for i in result], self.n_nodes) return result
[ "def", "_compute_automorphisms", "(", "self", ")", ":", "colors", "=", "self", ".", "edge_colors", "result", "=", "self", ".", "_igraph", ".", "get_isomorphisms_vf2", "(", "edge_color1", "=", "colors", ",", "edge_color2", "=", "colors", ")", "# sort them s.t. the identity comes first", "result", "=", "np", ".", "unique", "(", "result", ",", "axis", "=", "0", ")", ".", "tolist", "(", ")", "result", "=", "PermutationGroup", "(", "[", "Permutation", "(", "i", ")", "for", "i", "in", "result", "]", ",", "self", ".", "n_nodes", ")", "return", "result" ]
https://github.com/netket/netket/blob/0d534e54ecbf25b677ea72af6b85947979420652/netket/graph/graph.py#L196-L208
facebook/ThreatExchange
31914a51820c73c8a0daffe62ccca29a6e3d359e
python-threatexchange/threatexchange/cli/tag_fetch.py
python
TagFetchCommand.determine_fetch_type
(self, checkpoint: FetchCheckpoint)
return FetchType.Incremental(checkpoint.last_fetch)
Based on the checkpoint and options, determine what fetch we are doing
Based on the checkpoint and options, determine what fetch we are doing
[ "Based", "on", "the", "checkpoint", "and", "options", "determine", "what", "fetch", "we", "are", "doing" ]
def determine_fetch_type(self, checkpoint: FetchCheckpoint) -> FetchType: """Based on the checkpoint and options, determine what fetch we are doing""" if self.force_full or self.sample: return FetchType.Full() fetch_from_timestamp = checkpoint.last_fetch if not checkpoint.last_fetch: return FetchType.Full() if ( not self.force_incremental and time.time() - checkpoint.last_full_fetch > self.DEFAULT_REFETCH_SEC ): self.stderr("It's been a long time since a full fetch, forcing one now.") return FetchType.Full() return FetchType.Incremental(checkpoint.last_fetch)
[ "def", "determine_fetch_type", "(", "self", ",", "checkpoint", ":", "FetchCheckpoint", ")", "->", "FetchType", ":", "if", "self", ".", "force_full", "or", "self", ".", "sample", ":", "return", "FetchType", ".", "Full", "(", ")", "fetch_from_timestamp", "=", "checkpoint", ".", "last_fetch", "if", "not", "checkpoint", ".", "last_fetch", ":", "return", "FetchType", ".", "Full", "(", ")", "if", "(", "not", "self", ".", "force_incremental", "and", "time", ".", "time", "(", ")", "-", "checkpoint", ".", "last_full_fetch", ">", "self", ".", "DEFAULT_REFETCH_SEC", ")", ":", "self", ".", "stderr", "(", "\"It's been a long time since a full fetch, forcing one now.\"", ")", "return", "FetchType", ".", "Full", "(", ")", "return", "FetchType", ".", "Incremental", "(", "checkpoint", ".", "last_fetch", ")" ]
https://github.com/facebook/ThreatExchange/blob/31914a51820c73c8a0daffe62ccca29a6e3d359e/python-threatexchange/threatexchange/cli/tag_fetch.py#L151-L168
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
current/deps/v8/third_party/jinja2/filters.py
python
do_reverse
(value)
Reverse the object or return an iterator that iterates over it the other way round.
Reverse the object or return an iterator that iterates over it the other way round.
[ "Reverse", "the", "object", "or", "return", "an", "iterator", "that", "iterates", "over", "it", "the", "other", "way", "round", "." ]
def do_reverse(value): """Reverse the object or return an iterator that iterates over it the other way round. """ if isinstance(value, string_types): return value[::-1] try: return reversed(value) except TypeError: try: rv = list(value) rv.reverse() return rv except TypeError: raise FilterArgumentError('argument must be iterable')
[ "def", "do_reverse", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "string_types", ")", ":", "return", "value", "[", ":", ":", "-", "1", "]", "try", ":", "return", "reversed", "(", "value", ")", "except", "TypeError", ":", "try", ":", "rv", "=", "list", "(", "value", ")", "rv", ".", "reverse", "(", ")", "return", "rv", "except", "TypeError", ":", "raise", "FilterArgumentError", "(", "'argument must be iterable'", ")" ]
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/current/deps/v8/third_party/jinja2/filters.py#L895-L909
MythTV/mythtv
d282a209cb8be85d036f85a62a8ec971b67d45f4
mythtv/programs/scripts/internetcontent/nv_python_libs/vimeo/vimeo_api.py
python
CurlyRequest.do_rest_call
(self, url)
Send a simple GET request and interpret the answer as a REST reply.
Send a simple GET request and interpret the answer as a REST reply.
[ "Send", "a", "simple", "GET", "request", "and", "interpret", "the", "answer", "as", "a", "REST", "reply", "." ]
def do_rest_call(self, url): """ Send a simple GET request and interpret the answer as a REST reply. """ res = self.do_request(url) try: t = ET.fromstring(res) if t.attrib['stat'] == 'fail': err_code = t.find('err').attrib['code'] err_msg = t.find('err').attrib['msg'] raise Exception(err_code, err_msg, ET.tostring(t)) return t except Exception as e: raise Exception('%s' % (e))
[ "def", "do_rest_call", "(", "self", ",", "url", ")", ":", "res", "=", "self", ".", "do_request", "(", "url", ")", "try", ":", "t", "=", "ET", ".", "fromstring", "(", "res", ")", "if", "t", ".", "attrib", "[", "'stat'", "]", "==", "'fail'", ":", "err_code", "=", "t", ".", "find", "(", "'err'", ")", ".", "attrib", "[", "'code'", "]", "err_msg", "=", "t", ".", "find", "(", "'err'", ")", ".", "attrib", "[", "'msg'", "]", "raise", "Exception", "(", "err_code", ",", "err_msg", ",", "ET", ".", "tostring", "(", "t", ")", ")", "return", "t", "except", "Exception", "as", "e", ":", "raise", "Exception", "(", "'%s'", "%", "(", "e", ")", ")" ]
https://github.com/MythTV/mythtv/blob/d282a209cb8be85d036f85a62a8ec971b67d45f4/mythtv/programs/scripts/internetcontent/nv_python_libs/vimeo/vimeo_api.py#L120-L135
GeometryCollective/boundary-first-flattening
8250e5a0e85980ec50b5e8aa8f49dd6519f915cd
deps/nanogui/ext/pybind11/tools/clang/cindex.py
python
Type.get_fields
(self)
return iter(fields)
Return an iterator for accessing the fields of this type.
Return an iterator for accessing the fields of this type.
[ "Return", "an", "iterator", "for", "accessing", "the", "fields", "of", "this", "type", "." ]
def get_fields(self): """Return an iterator for accessing the fields of this type.""" def visitor(field, children): assert field != conf.lib.clang_getNullCursor() # Create reference to TU so it isn't GC'd before Cursor. field._tu = self._tu fields.append(field) return 1 # continue fields = [] conf.lib.clang_Type_visitFields(self, callbacks['fields_visit'](visitor), fields) return iter(fields)
[ "def", "get_fields", "(", "self", ")", ":", "def", "visitor", "(", "field", ",", "children", ")", ":", "assert", "field", "!=", "conf", ".", "lib", ".", "clang_getNullCursor", "(", ")", "# Create reference to TU so it isn't GC'd before Cursor.", "field", ".", "_tu", "=", "self", ".", "_tu", "fields", ".", "append", "(", "field", ")", "return", "1", "# continue", "fields", "=", "[", "]", "conf", ".", "lib", ".", "clang_Type_visitFields", "(", "self", ",", "callbacks", "[", "'fields_visit'", "]", "(", "visitor", ")", ",", "fields", ")", "return", "iter", "(", "fields", ")" ]
https://github.com/GeometryCollective/boundary-first-flattening/blob/8250e5a0e85980ec50b5e8aa8f49dd6519f915cd/deps/nanogui/ext/pybind11/tools/clang/cindex.py#L1983-L1996
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/ipython/py2/IPython/utils/text.py
python
_find_optimal
(rlist, row_first=False, separator_size=2, displaywidth=80)
return {'num_columns': ncols, 'optimal_separator_width': (displaywidth - sumlength) / (ncols - 1) if (ncols - 1) else 0, 'max_rows': max_rows, 'column_widths': col_widths }
Calculate optimal info to columnize a list of string
Calculate optimal info to columnize a list of string
[ "Calculate", "optimal", "info", "to", "columnize", "a", "list", "of", "string" ]
def _find_optimal(rlist, row_first=False, separator_size=2, displaywidth=80): """Calculate optimal info to columnize a list of string""" for max_rows in range(1, len(rlist) + 1): col_widths = list(map(max, _col_chunks(rlist, max_rows, row_first))) sumlength = sum(col_widths) ncols = len(col_widths) if sumlength + separator_size * (ncols - 1) <= displaywidth: break return {'num_columns': ncols, 'optimal_separator_width': (displaywidth - sumlength) / (ncols - 1) if (ncols - 1) else 0, 'max_rows': max_rows, 'column_widths': col_widths }
[ "def", "_find_optimal", "(", "rlist", ",", "row_first", "=", "False", ",", "separator_size", "=", "2", ",", "displaywidth", "=", "80", ")", ":", "for", "max_rows", "in", "range", "(", "1", ",", "len", "(", "rlist", ")", "+", "1", ")", ":", "col_widths", "=", "list", "(", "map", "(", "max", ",", "_col_chunks", "(", "rlist", ",", "max_rows", ",", "row_first", ")", ")", ")", "sumlength", "=", "sum", "(", "col_widths", ")", "ncols", "=", "len", "(", "col_widths", ")", "if", "sumlength", "+", "separator_size", "*", "(", "ncols", "-", "1", ")", "<=", "displaywidth", ":", "break", "return", "{", "'num_columns'", ":", "ncols", ",", "'optimal_separator_width'", ":", "(", "displaywidth", "-", "sumlength", ")", "/", "(", "ncols", "-", "1", ")", "if", "(", "ncols", "-", "1", ")", "else", "0", ",", "'max_rows'", ":", "max_rows", ",", "'column_widths'", ":", "col_widths", "}" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py2/IPython/utils/text.py#L633-L645
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pluggy/py2/pluggy/manager.py
python
PluginManager.register
(self, plugin, name=None)
return plugin_name
Register a plugin and return its canonical name or ``None`` if the name is blocked from registering. Raise a :py:class:`ValueError` if the plugin is already registered.
Register a plugin and return its canonical name or ``None`` if the name is blocked from registering. Raise a :py:class:`ValueError` if the plugin is already registered.
[ "Register", "a", "plugin", "and", "return", "its", "canonical", "name", "or", "None", "if", "the", "name", "is", "blocked", "from", "registering", ".", "Raise", "a", ":", "py", ":", "class", ":", "ValueError", "if", "the", "plugin", "is", "already", "registered", "." ]
def register(self, plugin, name=None): """ Register a plugin and return its canonical name or ``None`` if the name is blocked from registering. Raise a :py:class:`ValueError` if the plugin is already registered. """ plugin_name = name or self.get_canonical_name(plugin) if plugin_name in self._name2plugin or plugin in self._plugin2hookcallers: if self._name2plugin.get(plugin_name, -1) is None: return # blocked plugin, return None to indicate no registration raise ValueError( "Plugin already registered: %s=%s\n%s" % (plugin_name, plugin, self._name2plugin) ) # XXX if an error happens we should make sure no state has been # changed at point of return self._name2plugin[plugin_name] = plugin # register matching hook implementations of the plugin self._plugin2hookcallers[plugin] = hookcallers = [] for name in dir(plugin): hookimpl_opts = self.parse_hookimpl_opts(plugin, name) if hookimpl_opts is not None: normalize_hookimpl_opts(hookimpl_opts) method = getattr(plugin, name) hookimpl = HookImpl(plugin, plugin_name, method, hookimpl_opts) hook = getattr(self.hook, name, None) if hook is None: hook = _HookCaller(name, self._hookexec) setattr(self.hook, name, hook) elif hook.has_spec(): self._verify_hook(hook, hookimpl) hook._maybe_apply_history(hookimpl) hook._add_hookimpl(hookimpl) hookcallers.append(hook) return plugin_name
[ "def", "register", "(", "self", ",", "plugin", ",", "name", "=", "None", ")", ":", "plugin_name", "=", "name", "or", "self", ".", "get_canonical_name", "(", "plugin", ")", "if", "plugin_name", "in", "self", ".", "_name2plugin", "or", "plugin", "in", "self", ".", "_plugin2hookcallers", ":", "if", "self", ".", "_name2plugin", ".", "get", "(", "plugin_name", ",", "-", "1", ")", "is", "None", ":", "return", "# blocked plugin, return None to indicate no registration", "raise", "ValueError", "(", "\"Plugin already registered: %s=%s\\n%s\"", "%", "(", "plugin_name", ",", "plugin", ",", "self", ".", "_name2plugin", ")", ")", "# XXX if an error happens we should make sure no state has been", "# changed at point of return", "self", ".", "_name2plugin", "[", "plugin_name", "]", "=", "plugin", "# register matching hook implementations of the plugin", "self", ".", "_plugin2hookcallers", "[", "plugin", "]", "=", "hookcallers", "=", "[", "]", "for", "name", "in", "dir", "(", "plugin", ")", ":", "hookimpl_opts", "=", "self", ".", "parse_hookimpl_opts", "(", "plugin", ",", "name", ")", "if", "hookimpl_opts", "is", "not", "None", ":", "normalize_hookimpl_opts", "(", "hookimpl_opts", ")", "method", "=", "getattr", "(", "plugin", ",", "name", ")", "hookimpl", "=", "HookImpl", "(", "plugin", ",", "plugin_name", ",", "method", ",", "hookimpl_opts", ")", "hook", "=", "getattr", "(", "self", ".", "hook", ",", "name", ",", "None", ")", "if", "hook", "is", "None", ":", "hook", "=", "_HookCaller", "(", "name", ",", "self", ".", "_hookexec", ")", "setattr", "(", "self", ".", "hook", ",", "name", ",", "hook", ")", "elif", "hook", ".", "has_spec", "(", ")", ":", "self", ".", "_verify_hook", "(", "hook", ",", "hookimpl", ")", "hook", ".", "_maybe_apply_history", "(", "hookimpl", ")", "hook", ".", "_add_hookimpl", "(", "hookimpl", ")", "hookcallers", ".", "append", "(", "hook", ")", "return", "plugin_name" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pluggy/py2/pluggy/manager.py#L95-L130
HackWebRTC/webrtc
7abfc990c00ab35090fff285fcf635d1d7892433
PRESUBMIT.py
python
CheckPublicDepsIsNotUsed
(gn_files, input_api, output_api)
return result
Checks that public_deps is not used without a good reason.
Checks that public_deps is not used without a good reason.
[ "Checks", "that", "public_deps", "is", "not", "used", "without", "a", "good", "reason", "." ]
def CheckPublicDepsIsNotUsed(gn_files, input_api, output_api): """Checks that public_deps is not used without a good reason.""" result = [] no_presubmit_check_re = input_api.re.compile( r'# no-presubmit-check TODO\(webrtc:\d+\)') error_msg = ('public_deps is not recommended in WebRTC BUILD.gn files ' 'because it doesn\'t map well to downstream build systems.\n' 'Used in: %s (line %d).\n' 'If you are not adding this code (e.g. you are just moving ' 'existing code) or you have a good reason, you can add this ' 'comment (verbatim) on the line that causes the problem:\n\n' 'public_deps = [ # no-presubmit-check TODO(webrtc:8603)\n') for affected_file in gn_files: for (line_number, affected_line) in affected_file.ChangedContents(): if 'public_deps' in affected_line: surpressed = no_presubmit_check_re.search(affected_line) if not surpressed: result.append( output_api.PresubmitError(error_msg % (affected_file.LocalPath(), line_number))) return result
[ "def", "CheckPublicDepsIsNotUsed", "(", "gn_files", ",", "input_api", ",", "output_api", ")", ":", "result", "=", "[", "]", "no_presubmit_check_re", "=", "input_api", ".", "re", ".", "compile", "(", "r'# no-presubmit-check TODO\\(webrtc:\\d+\\)'", ")", "error_msg", "=", "(", "'public_deps is not recommended in WebRTC BUILD.gn files '", "'because it doesn\\'t map well to downstream build systems.\\n'", "'Used in: %s (line %d).\\n'", "'If you are not adding this code (e.g. you are just moving '", "'existing code) or you have a good reason, you can add this '", "'comment (verbatim) on the line that causes the problem:\\n\\n'", "'public_deps = [ # no-presubmit-check TODO(webrtc:8603)\\n'", ")", "for", "affected_file", "in", "gn_files", ":", "for", "(", "line_number", ",", "affected_line", ")", "in", "affected_file", ".", "ChangedContents", "(", ")", ":", "if", "'public_deps'", "in", "affected_line", ":", "surpressed", "=", "no_presubmit_check_re", ".", "search", "(", "affected_line", ")", "if", "not", "surpressed", ":", "result", ".", "append", "(", "output_api", ".", "PresubmitError", "(", "error_msg", "%", "(", "affected_file", ".", "LocalPath", "(", ")", ",", "line_number", ")", ")", ")", "return", "result" ]
https://github.com/HackWebRTC/webrtc/blob/7abfc990c00ab35090fff285fcf635d1d7892433/PRESUBMIT.py#L523-L543
chuckcho/video-caffe
fc232b3e3a90ea22dd041b9fc5c542f170581f20
examples/pycaffe/layers/pascal_multilabel_datalayers.py
python
PascalMultilabelDataLayerSync.reshape
(self, bottom, top)
There is no need to reshape the data, since the input is of fixed size (rows and columns)
There is no need to reshape the data, since the input is of fixed size (rows and columns)
[ "There", "is", "no", "need", "to", "reshape", "the", "data", "since", "the", "input", "is", "of", "fixed", "size", "(", "rows", "and", "columns", ")" ]
def reshape(self, bottom, top): """ There is no need to reshape the data, since the input is of fixed size (rows and columns) """ pass
[ "def", "reshape", "(", "self", ",", "bottom", ",", "top", ")", ":", "pass" ]
https://github.com/chuckcho/video-caffe/blob/fc232b3e3a90ea22dd041b9fc5c542f170581f20/examples/pycaffe/layers/pascal_multilabel_datalayers.py#L67-L72
apple/swift
469f72fdae2ea828b3b6c0d7d62d7e4cf98c4893
utils/jobstats/jobstats.py
python
JobStats.driver_jobs_skipped
(self)
return self.stats.get("Driver.NumDriverJobsSkipped", 0)
Return the count of a driver job's skipped sub-jobs
Return the count of a driver job's skipped sub-jobs
[ "Return", "the", "count", "of", "a", "driver", "job", "s", "skipped", "sub", "-", "jobs" ]
def driver_jobs_skipped(self): """Return the count of a driver job's skipped sub-jobs""" assert(self.is_driver_job()) return self.stats.get("Driver.NumDriverJobsSkipped", 0)
[ "def", "driver_jobs_skipped", "(", "self", ")", ":", "assert", "(", "self", ".", "is_driver_job", "(", ")", ")", "return", "self", ".", "stats", ".", "get", "(", "\"Driver.NumDriverJobsSkipped\"", ",", "0", ")" ]
https://github.com/apple/swift/blob/469f72fdae2ea828b3b6c0d7d62d7e4cf98c4893/utils/jobstats/jobstats.py#L72-L75
freeorion/freeorion
c266a40eccd3a99a17de8fe57c36ef6ba3771665
default/python/AI/character/character_module.py
python
Trait.may_invade_with_bases
(self)
return True
Return True if permitted to invade with bases.
Return True if permitted to invade with bases.
[ "Return", "True", "if", "permitted", "to", "invade", "with", "bases", "." ]
def may_invade_with_bases(self): # pylint: disable=no-self-use,unused-argument """Return True if permitted to invade with bases.""" return True
[ "def", "may_invade_with_bases", "(", "self", ")", ":", "# pylint: disable=no-self-use,unused-argument", "return", "True" ]
https://github.com/freeorion/freeorion/blob/c266a40eccd3a99a17de8fe57c36ef6ba3771665/default/python/AI/character/character_module.py#L169-L171
kamyu104/LeetCode-Solutions
77605708a927ea3b85aee5a479db733938c7c211
Python/simple-bank-system.py
python
Bank.withdraw
(self, account, money)
return False
:type account: int :type money: int :rtype: bool
:type account: int :type money: int :rtype: bool
[ ":", "type", "account", ":", "int", ":", "type", "money", ":", "int", ":", "rtype", ":", "bool" ]
def withdraw(self, account, money): """ :type account: int :type money: int :rtype: bool """ if 1 <= account <= len(self.__balance) and self.__balance[account-1] >= money: self.__balance[account-1] -= money return True return False
[ "def", "withdraw", "(", "self", ",", "account", ",", "money", ")", ":", "if", "1", "<=", "account", "<=", "len", "(", "self", ".", "__balance", ")", "and", "self", ".", "__balance", "[", "account", "-", "1", "]", ">=", "money", ":", "self", ".", "__balance", "[", "account", "-", "1", "]", "-=", "money", "return", "True", "return", "False" ]
https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/simple-bank-system.py#L37-L46
RamadhanAmizudin/malware
2c6c53c8b0d556f5d8078d6ca0fc4448f4697cf1
Fuzzbunch/exploits/ZIBE/pyreadline/console/ironpython_console.py
python
Console.text
(self, x, y, text, attr=None)
u'''Write text at the given position.
u'''Write text at the given position.
[ "u", "Write", "text", "at", "the", "given", "position", "." ]
def text(self, x, y, text, attr=None): u'''Write text at the given position.''' self.pos(x, y) self.write_color(text, attr)
[ "def", "text", "(", "self", ",", "x", ",", "y", ",", "text", ",", "attr", "=", "None", ")", ":", "self", ".", "pos", "(", "x", ",", "y", ")", "self", ".", "write_color", "(", "text", ",", "attr", ")" ]
https://github.com/RamadhanAmizudin/malware/blob/2c6c53c8b0d556f5d8078d6ca0fc4448f4697cf1/Fuzzbunch/exploits/ZIBE/pyreadline/console/ironpython_console.py#L258-L261
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
tools/json_schema_compiler/ppapi_generator.py
python
_PpapiGeneratorBase.NeedsOptionalArray
(self, type_)
return self._NameComponents(type_) in self._optional_array_types
Returns True if an optional array of |type_| is required.
Returns True if an optional array of |type_| is required.
[ "Returns", "True", "if", "an", "optional", "array", "of", "|type_|", "is", "required", "." ]
def NeedsOptionalArray(self, type_): """Returns True if an optional array of |type_| is required.""" return self._NameComponents(type_) in self._optional_array_types
[ "def", "NeedsOptionalArray", "(", "self", ",", "type_", ")", ":", "return", "self", ".", "_NameComponents", "(", "type_", ")", "in", "self", ".", "_optional_array_types" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/json_schema_compiler/ppapi_generator.py#L230-L232
hluk/CopyQ
ff4f670588df9ae15bd6d86c3f49cdd28aea5cd8
utils/update_icon_font.py
python
rename_font_family
(path)
Adds suffix to font family it doesn't conflict with font installed on system, which could be in incorrect version. See: https://github.com/fonttools/fonttools/blob/master/Snippets/rename-fonts.py
Adds suffix to font family it doesn't conflict with font installed on system, which could be in incorrect version.
[ "Adds", "suffix", "to", "font", "family", "it", "doesn", "t", "conflict", "with", "font", "installed", "on", "system", "which", "could", "be", "in", "incorrect", "version", "." ]
def rename_font_family(path): """ Adds suffix to font family it doesn't conflict with font installed on system, which could be in incorrect version. See: https://github.com/fonttools/fonttools/blob/master/Snippets/rename-fonts.py """ font = TTFont(path) name_table = font['name'] FAMILY_RELATED_IDS = dict( LEGACY_FAMILY=1, TRUETYPE_UNIQUE_ID=3, FULL_NAME=4, POSTSCRIPT_NAME=6, PREFERRED_FAMILY=16, WWS_FAMILY=21, ) for rec in name_table.names: if rec.nameID not in FAMILY_RELATED_IDS.values(): continue name = rec.toUnicode() if name.startswith('Font Awesome'): rec.string = name + ' (CopyQ)' elif name.startswith('FontAwesome'): rec.string = name + '(CopyQ)' assert rec.toUnicode().endswith('(CopyQ)') font.save(path)
[ "def", "rename_font_family", "(", "path", ")", ":", "font", "=", "TTFont", "(", "path", ")", "name_table", "=", "font", "[", "'name'", "]", "FAMILY_RELATED_IDS", "=", "dict", "(", "LEGACY_FAMILY", "=", "1", ",", "TRUETYPE_UNIQUE_ID", "=", "3", ",", "FULL_NAME", "=", "4", ",", "POSTSCRIPT_NAME", "=", "6", ",", "PREFERRED_FAMILY", "=", "16", ",", "WWS_FAMILY", "=", "21", ",", ")", "for", "rec", "in", "name_table", ".", "names", ":", "if", "rec", ".", "nameID", "not", "in", "FAMILY_RELATED_IDS", ".", "values", "(", ")", ":", "continue", "name", "=", "rec", ".", "toUnicode", "(", ")", "if", "name", ".", "startswith", "(", "'Font Awesome'", ")", ":", "rec", ".", "string", "=", "name", "+", "' (CopyQ)'", "elif", "name", ".", "startswith", "(", "'FontAwesome'", ")", ":", "rec", ".", "string", "=", "name", "+", "'(CopyQ)'", "assert", "rec", ".", "toUnicode", "(", ")", ".", "endswith", "(", "'(CopyQ)'", ")", "font", ".", "save", "(", "path", ")" ]
https://github.com/hluk/CopyQ/blob/ff4f670588df9ae15bd6d86c3f49cdd28aea5cd8/utils/update_icon_font.py#L88-L120
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/klampt/src/robotsim.py
python
IKObjective.numRotDims
(self)
return _robotsim.IKObjective_numRotDims(self)
r""" numRotDims(IKObjective self) -> int Returns: The number of rotation dimensions constrained (0-3)
r""" numRotDims(IKObjective self) -> int
[ "r", "numRotDims", "(", "IKObjective", "self", ")", "-", ">", "int" ]
def numRotDims(self) -> "int": r""" numRotDims(IKObjective self) -> int Returns: The number of rotation dimensions constrained (0-3) """ return _robotsim.IKObjective_numRotDims(self)
[ "def", "numRotDims", "(", "self", ")", "->", "\"int\"", ":", "return", "_robotsim", ".", "IKObjective_numRotDims", "(", "self", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/src/robotsim.py#L6326-L6334
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/codecs.py
python
StreamWriter.__init__
(self, stream, errors='strict')
Creates a StreamWriter instance. stream must be a file-like object open for writing (binary) data. The StreamWriter may use different error handling schemes by providing the errors keyword argument. These parameters are predefined: 'strict' - raise a ValueError (or a subclass) 'ignore' - ignore the character and continue with the next 'replace'- replace with a suitable replacement character 'xmlcharrefreplace' - Replace with the appropriate XML character reference. 'backslashreplace' - Replace with backslashed escape sequences (only for encoding). The set of allowed parameter values can be extended via register_error.
Creates a StreamWriter instance.
[ "Creates", "a", "StreamWriter", "instance", "." ]
def __init__(self, stream, errors='strict'): """ Creates a StreamWriter instance. stream must be a file-like object open for writing (binary) data. The StreamWriter may use different error handling schemes by providing the errors keyword argument. These parameters are predefined: 'strict' - raise a ValueError (or a subclass) 'ignore' - ignore the character and continue with the next 'replace'- replace with a suitable replacement character 'xmlcharrefreplace' - Replace with the appropriate XML character reference. 'backslashreplace' - Replace with backslashed escape sequences (only for encoding). The set of allowed parameter values can be extended via register_error. """ self.stream = stream self.errors = errors
[ "def", "__init__", "(", "self", ",", "stream", ",", "errors", "=", "'strict'", ")", ":", "self", ".", "stream", "=", "stream", "self", ".", "errors", "=", "errors" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/codecs.py#L322-L345
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/requests/sessions.py
python
Session.get
(self, url, **kwargs)
return self.request('GET', url, **kwargs)
r"""Sends a GET request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response
r"""Sends a GET request. Returns :class:`Response` object.
[ "r", "Sends", "a", "GET", "request", ".", "Returns", ":", "class", ":", "Response", "object", "." ]
def get(self, url, **kwargs): r"""Sends a GET request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response """ kwargs.setdefault('allow_redirects', True) return self.request('GET', url, **kwargs)
[ "def", "get", "(", "self", ",", "url", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "setdefault", "(", "'allow_redirects'", ",", "True", ")", "return", "self", ".", "request", "(", "'GET'", ",", "url", ",", "*", "*", "kwargs", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/requests/sessions.py#L546-L555
danxuhk/ContinuousCRF-CNN
2b6dcaf179620f118b225ed12c890414ca828e21
python/MultilabelDataLayer_seg.py
python
check_params
(params)
A utility function to check the parameters for the data layers.
A utility function to check the parameters for the data layers.
[ "A", "utility", "function", "to", "check", "the", "parameters", "for", "the", "data", "layers", "." ]
def check_params(params): """ A utility function to check the parameters for the data layers. """ assert 'split' in params.keys( ), 'Params must include split (train, val, or test).' required = ['batch_size', 'root_dir', 'list_file', 'scale_factors', 'mean_values', 'root_dir', 'list_file'] for r in required: assert r in params.keys(), 'Params must include {}'.format(r)
[ "def", "check_params", "(", "params", ")", ":", "assert", "'split'", "in", "params", ".", "keys", "(", ")", ",", "'Params must include split (train, val, or test).'", "required", "=", "[", "'batch_size'", ",", "'root_dir'", ",", "'list_file'", ",", "'scale_factors'", ",", "'mean_values'", ",", "'root_dir'", ",", "'list_file'", "]", "for", "r", "in", "required", ":", "assert", "r", "in", "params", ".", "keys", "(", ")", ",", "'Params must include {}'", ".", "format", "(", "r", ")" ]
https://github.com/danxuhk/ContinuousCRF-CNN/blob/2b6dcaf179620f118b225ed12c890414ca828e21/python/MultilabelDataLayer_seg.py#L193-L202
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/klampt/robotsim.py
python
RobotModelLink.getName
(self)
return _robotsim.RobotModelLink_getName(self)
r""" Returns the name of the robot link.
r""" Returns the name of the robot link.
[ "r", "Returns", "the", "name", "of", "the", "robot", "link", "." ]
def getName(self) ->str: r""" Returns the name of the robot link. """ return _robotsim.RobotModelLink_getName(self)
[ "def", "getName", "(", "self", ")", "->", "str", ":", "return", "_robotsim", ".", "RobotModelLink_getName", "(", "self", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/robotsim.py#L3926-L3931
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/train/summary/writer.py
python
ExportWriter.export_data
(self, data, export_option)
export the tensor data. Args: data (dict): Export data info. export_option (Union[None, str]): The export options.
export the tensor data.
[ "export", "the", "tensor", "data", "." ]
def export_data(self, data, export_option): """ export the tensor data. Args: data (dict): Export data info. export_option (Union[None, str]): The export options. """ options = { 'npy': self._export_npy } if export_option in options: options[export_option](data, self._filepath)
[ "def", "export_data", "(", "self", ",", "data", ",", "export_option", ")", ":", "options", "=", "{", "'npy'", ":", "self", ".", "_export_npy", "}", "if", "export_option", "in", "options", ":", "options", "[", "export_option", "]", "(", "data", ",", "self", ".", "_filepath", ")" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/train/summary/writer.py#L129-L142
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/Jinja2/py3/jinja2/lexer.py
python
Lexer._normalize_newlines
(self, value: str)
return newline_re.sub(self.newline_sequence, value)
Replace all newlines with the configured sequence in strings and template data.
Replace all newlines with the configured sequence in strings and template data.
[ "Replace", "all", "newlines", "with", "the", "configured", "sequence", "in", "strings", "and", "template", "data", "." ]
def _normalize_newlines(self, value: str) -> str: """Replace all newlines with the configured sequence in strings and template data. """ return newline_re.sub(self.newline_sequence, value)
[ "def", "_normalize_newlines", "(", "self", ",", "value", ":", "str", ")", "->", "str", ":", "return", "newline_re", ".", "sub", "(", "self", ".", "newline_sequence", ",", "value", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/Jinja2/py3/jinja2/lexer.py#L598-L602
alexgkendall/caffe-segnet
344c113bf1832886f1cbe9f33ffe28a3beeaf412
scripts/cpp_lint.py
python
_FunctionState.Count
(self)
Count line in current function body.
Count line in current function body.
[ "Count", "line", "in", "current", "function", "body", "." ]
def Count(self): """Count line in current function body.""" if self.in_a_function: self.lines_in_function += 1
[ "def", "Count", "(", "self", ")", ":", "if", "self", ".", "in_a_function", ":", "self", ".", "lines_in_function", "+=", "1" ]
https://github.com/alexgkendall/caffe-segnet/blob/344c113bf1832886f1cbe9f33ffe28a3beeaf412/scripts/cpp_lint.py#L831-L834
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/ros_comm/roslaunch/src/roslaunch/server.py
python
ROSLaunchParentHandler.__init__
(self, pm, child_processes, listeners)
@param child_processes: Map of remote processes so that server can update processes with information as children register. Handler will not modify keys. @type child_processes: {name : ChildROSLaunchProcess}. @param listeners [ProcessListener]: list of listeners to notify when process_died events occur.
[]
def __init__(self, pm, child_processes, listeners): """ @param child_processes: Map of remote processes so that server can update processes with information as children register. Handler will not modify keys. @type child_processes: {name : ChildROSLaunchProcess}. @param listeners [ProcessListener]: list of listeners to notify when process_died events occur. """ super(ROSLaunchParentHandler, self).__init__(pm) self.child_processes = child_processes self.listeners = listeners
[ "def", "__init__", "(", "self", ",", "pm", ",", "child_processes", ",", "listeners", ")", ":", "super", "(", "ROSLaunchParentHandler", ",", "self", ")", ".", "__init__", "(", "pm", ")", "self", ".", "child_processes", "=", "child_processes", "self", ".", "listeners", "=", "listeners" ]
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/ros_comm/roslaunch/src/roslaunch/server.py#L159-L170
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/contrib/grid_rnn/python/ops/grid_rnn_cell.py
python
GridRNNCell.__call__
(self, inputs, state, scope=None)
return output, states
Run one step of GridRNN. Args: inputs: input Tensor, 2D, batch x input_size. Or None state: state Tensor, 2D, batch x state_size. Note that state_size = cell_state_size * recurrent_dims scope: VariableScope for the created subgraph; defaults to "GridRNNCell". Returns: A tuple containing: - A 2D, batch x output_size, Tensor representing the output of the cell after reading "inputs" when previous state was "state". - A 2D, batch x state_size, Tensor representing the new state of the cell after reading "inputs" when previous state was "state".
Run one step of GridRNN.
[ "Run", "one", "step", "of", "GridRNN", "." ]
def __call__(self, inputs, state, scope=None): """Run one step of GridRNN. Args: inputs: input Tensor, 2D, batch x input_size. Or None state: state Tensor, 2D, batch x state_size. Note that state_size = cell_state_size * recurrent_dims scope: VariableScope for the created subgraph; defaults to "GridRNNCell". Returns: A tuple containing: - A 2D, batch x output_size, Tensor representing the output of the cell after reading "inputs" when previous state was "state". - A 2D, batch x state_size, Tensor representing the new state of the cell after reading "inputs" when previous state was "state". """ state_sz = state.get_shape().as_list()[1] if self.state_size != state_sz: raise ValueError('Actual state size not same as specified: {} vs {}.'.format(state_sz, self.state_size)) conf = self._config dtype = inputs.dtype if inputs is not None else state.dtype # c_prev is `m`, and m_prev is `h` in the paper. Keep c and m here for consistency with the codebase c_prev = [None] * self._config.num_dims m_prev = [None] * self._config.num_dims cell_output_size = self._cell.state_size - conf.num_units # for LSTM : state = memory cell + output, hence cell_output_size > 0 # for GRU/RNN: state = output (whose size is equal to _num_units), hence cell_output_size = 0 for recurrent_dim, start_idx in zip(self._config.recurrents, range(0, self.state_size, self._cell.state_size)): if cell_output_size > 0: c_prev[recurrent_dim] = array_ops.slice(state, [0, start_idx], [-1, conf.num_units]) m_prev[recurrent_dim] = array_ops.slice(state, [0, start_idx + conf.num_units], [-1, cell_output_size]) else: m_prev[recurrent_dim] = array_ops.slice(state, [0, start_idx], [-1, conf.num_units]) new_output = [None] * conf.num_dims new_state = [None] * conf.num_dims with vs.variable_scope(scope or type(self).__name__): # GridRNNCell # project input if inputs is not None and sum(inputs.get_shape().as_list()) > 0 and len(conf.inputs) > 0: input_splits = array_ops.split(1, len(conf.inputs), inputs) input_sz = input_splits[0].get_shape().as_list()[1] for i, j in enumerate(conf.inputs): input_project_m = vs.get_variable('project_m_{}'.format(j), [input_sz, conf.num_units], dtype=dtype) m_prev[j] = math_ops.matmul(input_splits[i], input_project_m) if cell_output_size > 0: input_project_c = vs.get_variable('project_c_{}'.format(j), [input_sz, conf.num_units], dtype=dtype) c_prev[j] = math_ops.matmul(input_splits[i], input_project_c) _propagate(conf.non_priority, conf, self._cell, c_prev, m_prev, new_output, new_state, True) _propagate(conf.priority, conf, self._cell, c_prev, m_prev, new_output, new_state, False) output_tensors = [new_output[i] for i in self._config.outputs] output = array_ops.zeros([0, 0], dtype) if len(output_tensors) == 0 else array_ops.concat(1, output_tensors) state_tensors = [new_state[i] for i in self._config.recurrents] states = array_ops.zeros([0, 0], dtype) if len(state_tensors) == 0 else array_ops.concat(1, state_tensors) return output, states
[ "def", "__call__", "(", "self", ",", "inputs", ",", "state", ",", "scope", "=", "None", ")", ":", "state_sz", "=", "state", ".", "get_shape", "(", ")", ".", "as_list", "(", ")", "[", "1", "]", "if", "self", ".", "state_size", "!=", "state_sz", ":", "raise", "ValueError", "(", "'Actual state size not same as specified: {} vs {}.'", ".", "format", "(", "state_sz", ",", "self", ".", "state_size", ")", ")", "conf", "=", "self", ".", "_config", "dtype", "=", "inputs", ".", "dtype", "if", "inputs", "is", "not", "None", "else", "state", ".", "dtype", "# c_prev is `m`, and m_prev is `h` in the paper. Keep c and m here for consistency with the codebase", "c_prev", "=", "[", "None", "]", "*", "self", ".", "_config", ".", "num_dims", "m_prev", "=", "[", "None", "]", "*", "self", ".", "_config", ".", "num_dims", "cell_output_size", "=", "self", ".", "_cell", ".", "state_size", "-", "conf", ".", "num_units", "# for LSTM : state = memory cell + output, hence cell_output_size > 0", "# for GRU/RNN: state = output (whose size is equal to _num_units), hence cell_output_size = 0", "for", "recurrent_dim", ",", "start_idx", "in", "zip", "(", "self", ".", "_config", ".", "recurrents", ",", "range", "(", "0", ",", "self", ".", "state_size", ",", "self", ".", "_cell", ".", "state_size", ")", ")", ":", "if", "cell_output_size", ">", "0", ":", "c_prev", "[", "recurrent_dim", "]", "=", "array_ops", ".", "slice", "(", "state", ",", "[", "0", ",", "start_idx", "]", ",", "[", "-", "1", ",", "conf", ".", "num_units", "]", ")", "m_prev", "[", "recurrent_dim", "]", "=", "array_ops", ".", "slice", "(", "state", ",", "[", "0", ",", "start_idx", "+", "conf", ".", "num_units", "]", ",", "[", "-", "1", ",", "cell_output_size", "]", ")", "else", ":", "m_prev", "[", "recurrent_dim", "]", "=", "array_ops", ".", "slice", "(", "state", ",", "[", "0", ",", "start_idx", "]", ",", "[", "-", "1", ",", "conf", ".", "num_units", "]", ")", "new_output", "=", "[", "None", "]", "*", "conf", ".", "num_dims", "new_state", "=", "[", "None", "]", "*", "conf", ".", "num_dims", "with", "vs", ".", "variable_scope", "(", "scope", "or", "type", "(", "self", ")", ".", "__name__", ")", ":", "# GridRNNCell", "# project input", "if", "inputs", "is", "not", "None", "and", "sum", "(", "inputs", ".", "get_shape", "(", ")", ".", "as_list", "(", ")", ")", ">", "0", "and", "len", "(", "conf", ".", "inputs", ")", ">", "0", ":", "input_splits", "=", "array_ops", ".", "split", "(", "1", ",", "len", "(", "conf", ".", "inputs", ")", ",", "inputs", ")", "input_sz", "=", "input_splits", "[", "0", "]", ".", "get_shape", "(", ")", ".", "as_list", "(", ")", "[", "1", "]", "for", "i", ",", "j", "in", "enumerate", "(", "conf", ".", "inputs", ")", ":", "input_project_m", "=", "vs", ".", "get_variable", "(", "'project_m_{}'", ".", "format", "(", "j", ")", ",", "[", "input_sz", ",", "conf", ".", "num_units", "]", ",", "dtype", "=", "dtype", ")", "m_prev", "[", "j", "]", "=", "math_ops", ".", "matmul", "(", "input_splits", "[", "i", "]", ",", "input_project_m", ")", "if", "cell_output_size", ">", "0", ":", "input_project_c", "=", "vs", ".", "get_variable", "(", "'project_c_{}'", ".", "format", "(", "j", ")", ",", "[", "input_sz", ",", "conf", ".", "num_units", "]", ",", "dtype", "=", "dtype", ")", "c_prev", "[", "j", "]", "=", "math_ops", ".", "matmul", "(", "input_splits", "[", "i", "]", ",", "input_project_c", ")", "_propagate", "(", "conf", ".", "non_priority", ",", "conf", ",", "self", ".", "_cell", ",", "c_prev", ",", "m_prev", ",", "new_output", ",", "new_state", ",", "True", ")", "_propagate", "(", "conf", ".", "priority", ",", "conf", ",", "self", ".", "_cell", ",", "c_prev", ",", "m_prev", ",", "new_output", ",", "new_state", ",", "False", ")", "output_tensors", "=", "[", "new_output", "[", "i", "]", "for", "i", "in", "self", ".", "_config", ".", "outputs", "]", "output", "=", "array_ops", ".", "zeros", "(", "[", "0", ",", "0", "]", ",", "dtype", ")", "if", "len", "(", "output_tensors", ")", "==", "0", "else", "array_ops", ".", "concat", "(", "1", ",", "output_tensors", ")", "state_tensors", "=", "[", "new_state", "[", "i", "]", "for", "i", "in", "self", ".", "_config", ".", "recurrents", "]", "states", "=", "array_ops", ".", "zeros", "(", "[", "0", ",", "0", "]", ",", "dtype", ")", "if", "len", "(", "state_tensors", ")", "==", "0", "else", "array_ops", ".", "concat", "(", "1", ",", "state_tensors", ")", "return", "output", ",", "states" ]
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/contrib/grid_rnn/python/ops/grid_rnn_cell.py#L98-L163
eventql/eventql
7ca0dbb2e683b525620ea30dc40540a22d5eb227
deps/3rdparty/spidermonkey/mozjs/python/requests/requests/packages/urllib3/poolmanager.py
python
ProxyManager.urlopen
(self, method, url, redirect=True, **kw)
return super(ProxyManager, self).urlopen(method, url, redirect=redirect, **kw)
Same as HTTP(S)ConnectionPool.urlopen, ``url`` must be absolute.
Same as HTTP(S)ConnectionPool.urlopen, ``url`` must be absolute.
[ "Same", "as", "HTTP", "(", "S", ")", "ConnectionPool", ".", "urlopen", "url", "must", "be", "absolute", "." ]
def urlopen(self, method, url, redirect=True, **kw): "Same as HTTP(S)ConnectionPool.urlopen, ``url`` must be absolute." u = parse_url(url) if u.scheme == "http": # For proxied HTTPS requests, httplib sets the necessary headers # on the CONNECT to the proxy. For HTTP, we'll definitely # need to set 'Host' at the very least. headers = kw.get('headers', self.headers) kw['headers'] = self._set_proxy_headers(url, headers) return super(ProxyManager, self).urlopen(method, url, redirect=redirect, **kw)
[ "def", "urlopen", "(", "self", ",", "method", ",", "url", ",", "redirect", "=", "True", ",", "*", "*", "kw", ")", ":", "u", "=", "parse_url", "(", "url", ")", "if", "u", ".", "scheme", "==", "\"http\"", ":", "# For proxied HTTPS requests, httplib sets the necessary headers", "# on the CONNECT to the proxy. For HTTP, we'll definitely", "# need to set 'Host' at the very least.", "headers", "=", "kw", ".", "get", "(", "'headers'", ",", "self", ".", "headers", ")", "kw", "[", "'headers'", "]", "=", "self", ".", "_set_proxy_headers", "(", "url", ",", "headers", ")", "return", "super", "(", "ProxyManager", ",", "self", ")", ".", "urlopen", "(", "method", ",", "url", ",", "redirect", "=", "redirect", ",", "*", "*", "kw", ")" ]
https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/python/requests/requests/packages/urllib3/poolmanager.py#L250-L261
kamyu104/LeetCode-Solutions
77605708a927ea3b85aee5a479db733938c7c211
Python/special-array-with-x-elements-greater-than-or-equal-x.py
python
Solution.specialArray
(self, nums)
return -1
:type nums: List[int] :rtype: int
:type nums: List[int] :rtype: int
[ ":", "type", "nums", ":", "List", "[", "int", "]", ":", "rtype", ":", "int" ]
def specialArray(self, nums): """ :type nums: List[int] :rtype: int """ MAX_NUM = 1000 count = [0]*(MAX_NUM+1) for num in nums: count[num] += 1 n = len(nums) for i in xrange(len(count)): if i == n: return i n -= count[i] return -1
[ "def", "specialArray", "(", "self", ",", "nums", ")", ":", "MAX_NUM", "=", "1000", "count", "=", "[", "0", "]", "*", "(", "MAX_NUM", "+", "1", ")", "for", "num", "in", "nums", ":", "count", "[", "num", "]", "+=", "1", "n", "=", "len", "(", "nums", ")", "for", "i", "in", "xrange", "(", "len", "(", "count", ")", ")", ":", "if", "i", "==", "n", ":", "return", "i", "n", "-=", "count", "[", "i", "]", "return", "-", "1" ]
https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/special-array-with-x-elements-greater-than-or-equal-x.py#L6-L20
devsisters/libquic
8954789a056d8e7d5fcb6452fd1572ca57eb5c4e
src/third_party/protobuf/python/google/protobuf/descriptor_pool.py
python
DescriptorPool.AddDescriptor
(self, desc)
Adds a Descriptor to the pool, non-recursively. If the Descriptor contains nested messages or enums, the caller must explicitly register them. This method also registers the FileDescriptor associated with the message. Args: desc: A Descriptor.
Adds a Descriptor to the pool, non-recursively.
[ "Adds", "a", "Descriptor", "to", "the", "pool", "non", "-", "recursively", "." ]
def AddDescriptor(self, desc): """Adds a Descriptor to the pool, non-recursively. If the Descriptor contains nested messages or enums, the caller must explicitly register them. This method also registers the FileDescriptor associated with the message. Args: desc: A Descriptor. """ if not isinstance(desc, descriptor.Descriptor): raise TypeError('Expected instance of descriptor.Descriptor.') self._descriptors[desc.full_name] = desc self.AddFileDescriptor(desc.file)
[ "def", "AddDescriptor", "(", "self", ",", "desc", ")", ":", "if", "not", "isinstance", "(", "desc", ",", "descriptor", ".", "Descriptor", ")", ":", "raise", "TypeError", "(", "'Expected instance of descriptor.Descriptor.'", ")", "self", ".", "_descriptors", "[", "desc", ".", "full_name", "]", "=", "desc", "self", ".", "AddFileDescriptor", "(", "desc", ".", "file", ")" ]
https://github.com/devsisters/libquic/blob/8954789a056d8e7d5fcb6452fd1572ca57eb5c4e/src/third_party/protobuf/python/google/protobuf/descriptor_pool.py#L134-L148
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/AWSPythonSDK/1.5.8/botocore/docs/shape.py
python
ShapeDocumenter.traverse_and_document_shape
(self, section, shape, history, include=None, exclude=None, name=None, is_required=False)
Traverses and documents a shape Will take a self class and call its appropriate methods as a shape is traversed. :param section: The section to document. :param history: A list of the names of the shapes that have been traversed. :type include: Dictionary where keys are parameter names and values are the shapes of the parameter names. :param include: The parameter shapes to include in the documentation. :type exclude: List of the names of the parameters to exclude. :param exclude: The names of the parameters to exclude from documentation. :param name: The name of the shape. :param is_required: If the shape is a required member.
Traverses and documents a shape
[ "Traverses", "and", "documents", "a", "shape" ]
def traverse_and_document_shape(self, section, shape, history, include=None, exclude=None, name=None, is_required=False): """Traverses and documents a shape Will take a self class and call its appropriate methods as a shape is traversed. :param section: The section to document. :param history: A list of the names of the shapes that have been traversed. :type include: Dictionary where keys are parameter names and values are the shapes of the parameter names. :param include: The parameter shapes to include in the documentation. :type exclude: List of the names of the parameters to exclude. :param exclude: The names of the parameters to exclude from documentation. :param name: The name of the shape. :param is_required: If the shape is a required member. """ param_type = shape.type_name if shape.name in history: self.document_recursive_shape(section, shape, name=name) else: history.append(shape.name) is_top_level_param = (len(history) == 2) getattr(self, 'document_shape_type_%s' % param_type, self.document_shape_default)( section, shape, history=history, name=name, include=include, exclude=exclude, is_top_level_param=is_top_level_param, is_required=is_required) if is_top_level_param: self._event_emitter.emit( 'docs.%s.%s.%s.%s' % (self.EVENT_NAME, self._service_name, self._operation_name, name), section=section) at_overlying_method_section = (len(history) == 1) if at_overlying_method_section: self._event_emitter.emit( 'docs.%s.%s.%s.complete-section' % (self.EVENT_NAME, self._service_name, self._operation_name), section=section) history.pop()
[ "def", "traverse_and_document_shape", "(", "self", ",", "section", ",", "shape", ",", "history", ",", "include", "=", "None", ",", "exclude", "=", "None", ",", "name", "=", "None", ",", "is_required", "=", "False", ")", ":", "param_type", "=", "shape", ".", "type_name", "if", "shape", ".", "name", "in", "history", ":", "self", ".", "document_recursive_shape", "(", "section", ",", "shape", ",", "name", "=", "name", ")", "else", ":", "history", ".", "append", "(", "shape", ".", "name", ")", "is_top_level_param", "=", "(", "len", "(", "history", ")", "==", "2", ")", "getattr", "(", "self", ",", "'document_shape_type_%s'", "%", "param_type", ",", "self", ".", "document_shape_default", ")", "(", "section", ",", "shape", ",", "history", "=", "history", ",", "name", "=", "name", ",", "include", "=", "include", ",", "exclude", "=", "exclude", ",", "is_top_level_param", "=", "is_top_level_param", ",", "is_required", "=", "is_required", ")", "if", "is_top_level_param", ":", "self", ".", "_event_emitter", ".", "emit", "(", "'docs.%s.%s.%s.%s'", "%", "(", "self", ".", "EVENT_NAME", ",", "self", ".", "_service_name", ",", "self", ".", "_operation_name", ",", "name", ")", ",", "section", "=", "section", ")", "at_overlying_method_section", "=", "(", "len", "(", "history", ")", "==", "1", ")", "if", "at_overlying_method_section", ":", "self", ".", "_event_emitter", ".", "emit", "(", "'docs.%s.%s.%s.complete-section'", "%", "(", "self", ".", "EVENT_NAME", ",", "self", ".", "_service_name", ",", "self", ".", "_operation_name", ")", ",", "section", "=", "section", ")", "history", ".", "pop", "(", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/botocore/docs/shape.py#L36-L87
Polidea/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
SymbolExtractorAndRenamer/lldb/examples/customization/import-python/importcmd.py
python
pyimport_cmd
(debugger, args, result, dict)
return None
Import a Python module given its full path
Import a Python module given its full path
[ "Import", "a", "Python", "module", "given", "its", "full", "path" ]
def pyimport_cmd(debugger, args, result, dict): """Import a Python module given its full path""" print 'WARNING: obsolete feature - use native command "command script import"' if args == "": return "no module path given" if not (os.sep in args): modname = args ensure_has_dir_in_path('.') else: endofdir = args.rfind(os.sep) modname = args[endofdir + 1:] args = args[0:endofdir] ensure_has_dir_in_path(args) do_import(debugger, modname) return None
[ "def", "pyimport_cmd", "(", "debugger", ",", "args", ",", "result", ",", "dict", ")", ":", "print", "'WARNING: obsolete feature - use native command \"command script import\"'", "if", "args", "==", "\"\"", ":", "return", "\"no module path given\"", "if", "not", "(", "os", ".", "sep", "in", "args", ")", ":", "modname", "=", "args", "ensure_has_dir_in_path", "(", "'.'", ")", "else", ":", "endofdir", "=", "args", ".", "rfind", "(", "os", ".", "sep", ")", "modname", "=", "args", "[", "endofdir", "+", "1", ":", "]", "args", "=", "args", "[", "0", ":", "endofdir", "]", "ensure_has_dir_in_path", "(", "args", ")", "do_import", "(", "debugger", ",", "modname", ")", "return", "None" ]
https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/examples/customization/import-python/importcmd.py#L24-L38
yrnkrn/zapcc
c6a8aa30006d997eff0d60fd37b0e62b8aa0ea50
utils/lit/lit/llvm/config.py
python
LLVMConfig.use_llvm_tool
(self, name, search_env=None, required=False, quiet=False)
return tool
Find the executable program 'name', optionally using the specified environment variable as an override before searching the configuration's PATH.
Find the executable program 'name', optionally using the specified environment variable as an override before searching the configuration's PATH.
[ "Find", "the", "executable", "program", "name", "optionally", "using", "the", "specified", "environment", "variable", "as", "an", "override", "before", "searching", "the", "configuration", "s", "PATH", "." ]
def use_llvm_tool(self, name, search_env=None, required=False, quiet=False): """Find the executable program 'name', optionally using the specified environment variable as an override before searching the configuration's PATH.""" # If the override is specified in the environment, use it without # validation. if search_env: tool = self.config.environment.get(search_env) if tool: return tool # Otherwise look in the path. tool = lit.util.which(name, self.config.environment['PATH']) if required and not tool: message = "couldn't find '{}' program".format(name) if search_env: message = message + \ ', try setting {} in your environment'.format(search_env) self.lit_config.fatal(message) if tool: tool = os.path.normpath(tool) if not self.lit_config.quiet and not quiet: self.lit_config.note('using {}: {}'.format(name, tool)) return tool
[ "def", "use_llvm_tool", "(", "self", ",", "name", ",", "search_env", "=", "None", ",", "required", "=", "False", ",", "quiet", "=", "False", ")", ":", "# If the override is specified in the environment, use it without", "# validation.", "if", "search_env", ":", "tool", "=", "self", ".", "config", ".", "environment", ".", "get", "(", "search_env", ")", "if", "tool", ":", "return", "tool", "# Otherwise look in the path.", "tool", "=", "lit", ".", "util", ".", "which", "(", "name", ",", "self", ".", "config", ".", "environment", "[", "'PATH'", "]", ")", "if", "required", "and", "not", "tool", ":", "message", "=", "\"couldn't find '{}' program\"", ".", "format", "(", "name", ")", "if", "search_env", ":", "message", "=", "message", "+", "', try setting {} in your environment'", ".", "format", "(", "search_env", ")", "self", ".", "lit_config", ".", "fatal", "(", "message", ")", "if", "tool", ":", "tool", "=", "os", ".", "path", ".", "normpath", "(", "tool", ")", "if", "not", "self", ".", "lit_config", ".", "quiet", "and", "not", "quiet", ":", "self", ".", "lit_config", ".", "note", "(", "'using {}: {}'", ".", "format", "(", "name", ",", "tool", ")", ")", "return", "tool" ]
https://github.com/yrnkrn/zapcc/blob/c6a8aa30006d997eff0d60fd37b0e62b8aa0ea50/utils/lit/lit/llvm/config.py#L310-L335
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Editor/Python/windows/Lib/site-packages/pip/commands/install.py
python
InstallCommand._build_package_finder
(self, options, index_urls, session)
return PackageFinder( find_links=options.find_links, format_control=options.format_control, index_urls=index_urls, allow_external=options.allow_external, allow_unverified=options.allow_unverified, allow_all_external=options.allow_all_external, trusted_hosts=options.trusted_hosts, allow_all_prereleases=options.pre, process_dependency_links=options.process_dependency_links, session=session, )
Create a package finder appropriate to this install command. This method is meant to be overridden by subclasses, not called directly.
Create a package finder appropriate to this install command. This method is meant to be overridden by subclasses, not called directly.
[ "Create", "a", "package", "finder", "appropriate", "to", "this", "install", "command", ".", "This", "method", "is", "meant", "to", "be", "overridden", "by", "subclasses", "not", "called", "directly", "." ]
def _build_package_finder(self, options, index_urls, session): """ Create a package finder appropriate to this install command. This method is meant to be overridden by subclasses, not called directly. """ return PackageFinder( find_links=options.find_links, format_control=options.format_control, index_urls=index_urls, allow_external=options.allow_external, allow_unverified=options.allow_unverified, allow_all_external=options.allow_all_external, trusted_hosts=options.trusted_hosts, allow_all_prereleases=options.pre, process_dependency_links=options.process_dependency_links, session=session, )
[ "def", "_build_package_finder", "(", "self", ",", "options", ",", "index_urls", ",", "session", ")", ":", "return", "PackageFinder", "(", "find_links", "=", "options", ".", "find_links", ",", "format_control", "=", "options", ".", "format_control", ",", "index_urls", "=", "index_urls", ",", "allow_external", "=", "options", ".", "allow_external", ",", "allow_unverified", "=", "options", ".", "allow_unverified", ",", "allow_all_external", "=", "options", ".", "allow_all_external", ",", "trusted_hosts", "=", "options", ".", "trusted_hosts", ",", "allow_all_prereleases", "=", "options", ".", "pre", ",", "process_dependency_links", "=", "options", ".", "process_dependency_links", ",", "session", "=", "session", ",", ")" ]
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/pip/commands/install.py#L176-L193
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
torch/quantization/__init__.py
python
default_eval_fn
(model, calib_data)
r""" Default evaluation function takes a torch.utils.data.Dataset or a list of input Tensors and run the model on the dataset
r""" Default evaluation function takes a torch.utils.data.Dataset or a list of input Tensors and run the model on the dataset
[ "r", "Default", "evaluation", "function", "takes", "a", "torch", ".", "utils", ".", "data", ".", "Dataset", "or", "a", "list", "of", "input", "Tensors", "and", "run", "the", "model", "on", "the", "dataset" ]
def default_eval_fn(model, calib_data): r""" Default evaluation function takes a torch.utils.data.Dataset or a list of input Tensors and run the model on the dataset """ for data, target in calib_data: model(data)
[ "def", "default_eval_fn", "(", "model", ",", "calib_data", ")", ":", "for", "data", ",", "target", "in", "calib_data", ":", "model", "(", "data", ")" ]
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/quantization/__init__.py#L13-L19
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/fitting_widgets/basic_fitting/basic_fitting_view.py
python
BasicFittingView.disable_view
(self)
Disable all widgets in this fitting widget.
Disable all widgets in this fitting widget.
[ "Disable", "all", "widgets", "in", "this", "fitting", "widget", "." ]
def disable_view(self) -> None: """Disable all widgets in this fitting widget.""" self.setEnabled(False)
[ "def", "disable_view", "(", "self", ")", "->", "None", ":", "self", ".", "setEnabled", "(", "False", ")" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/fitting_widgets/basic_fitting/basic_fitting_view.py#L373-L375
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemFramework/v1/ResourceManager/lib/Crypto/Cipher/_mode_eax.py
python
EaxMode.hexdigest
(self)
return "".join(["%02x" % bord(x) for x in self.digest()])
Compute the *printable* MAC tag. This method is like `digest`. :Return: the MAC, as a hexadecimal string.
Compute the *printable* MAC tag.
[ "Compute", "the", "*", "printable", "*", "MAC", "tag", "." ]
def hexdigest(self): """Compute the *printable* MAC tag. This method is like `digest`. :Return: the MAC, as a hexadecimal string. """ return "".join(["%02x" % bord(x) for x in self.digest()])
[ "def", "hexdigest", "(", "self", ")", ":", "return", "\"\"", ".", "join", "(", "[", "\"%02x\"", "%", "bord", "(", "x", ")", "for", "x", "in", "self", ".", "digest", "(", ")", "]", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/ResourceManager/lib/Crypto/Cipher/_mode_eax.py#L266-L273
PixarAnimationStudios/USD
faed18ce62c8736b02413635b584a2f637156bad
pxr/usdImaging/usdviewq/usdviewApi.py
python
UsdviewApi.qMainWindow
(self)
return self.__appController._mainWindow
A QWidget object that other widgets can use as a parent.
A QWidget object that other widgets can use as a parent.
[ "A", "QWidget", "object", "that", "other", "widgets", "can", "use", "as", "a", "parent", "." ]
def qMainWindow(self): """A QWidget object that other widgets can use as a parent.""" return self.__appController._mainWindow
[ "def", "qMainWindow", "(", "self", ")", ":", "return", "self", ".", "__appController", ".", "_mainWindow" ]
https://github.com/PixarAnimationStudios/USD/blob/faed18ce62c8736b02413635b584a2f637156bad/pxr/usdImaging/usdviewq/usdviewApi.py#L141-L144
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/cond_v2.py
python
_make_inputs_match
(branch_graphs, branch_inputs)
return new_inputs
Modifies branch_graphs so they have the same input signature. This method reorders and/or adds parameters to each graph in branch_graphs so they have the same input signature, and updates the 'inputs' and 'captured' fields of each graph accordingly. It uses the input tensors from the outer graph to avoid duplicating shared arguments. Args: branch_graphs: a `list` of `FuncGraph` branch_inputs: a `list` of `list`s of `Tensor`s in the outer graph. The inputs for the corresponding graph in `branch_graphs`. Returns: A new list of Tensors from the outer graph that are the new inputs for each branch_graph. This is a deduped version of `sum(branch_inputs)`.
Modifies branch_graphs so they have the same input signature.
[ "Modifies", "branch_graphs", "so", "they", "have", "the", "same", "input", "signature", "." ]
def _make_inputs_match(branch_graphs, branch_inputs): """Modifies branch_graphs so they have the same input signature. This method reorders and/or adds parameters to each graph in branch_graphs so they have the same input signature, and updates the 'inputs' and 'captured' fields of each graph accordingly. It uses the input tensors from the outer graph to avoid duplicating shared arguments. Args: branch_graphs: a `list` of `FuncGraph` branch_inputs: a `list` of `list`s of `Tensor`s in the outer graph. The inputs for the corresponding graph in `branch_graphs`. Returns: A new list of Tensors from the outer graph that are the new inputs for each branch_graph. This is a deduped version of `sum(branch_inputs)`. """ assert len(branch_graphs) == len(branch_inputs) added_inputs = set() new_inputs = [] for branch_in in branch_inputs: for tensor in branch_in: tensor_id = ops.tensor_id(tensor) if tensor_id not in added_inputs: added_inputs.add(tensor_id) new_inputs.append(tensor) for branch_graph, branch_in in zip(branch_graphs, branch_inputs): input_ids = [ops.tensor_id(t) for t in branch_in] branch_input_to_param = dict(zip(input_ids, branch_graph.inputs)) input_list = [] for in_t in new_inputs: param = branch_input_to_param.get(ops.tensor_id(in_t)) if param is None: param = _create_dummy_input(branch_graph, in_t) input_list.append(param) branch_graph.inputs = input_list # Rewrite the FuncGraphs' state to reflect the new inputs. branch_graph.reset_captures(zip(new_inputs, branch_graph.inputs)) return new_inputs
[ "def", "_make_inputs_match", "(", "branch_graphs", ",", "branch_inputs", ")", ":", "assert", "len", "(", "branch_graphs", ")", "==", "len", "(", "branch_inputs", ")", "added_inputs", "=", "set", "(", ")", "new_inputs", "=", "[", "]", "for", "branch_in", "in", "branch_inputs", ":", "for", "tensor", "in", "branch_in", ":", "tensor_id", "=", "ops", ".", "tensor_id", "(", "tensor", ")", "if", "tensor_id", "not", "in", "added_inputs", ":", "added_inputs", ".", "add", "(", "tensor_id", ")", "new_inputs", ".", "append", "(", "tensor", ")", "for", "branch_graph", ",", "branch_in", "in", "zip", "(", "branch_graphs", ",", "branch_inputs", ")", ":", "input_ids", "=", "[", "ops", ".", "tensor_id", "(", "t", ")", "for", "t", "in", "branch_in", "]", "branch_input_to_param", "=", "dict", "(", "zip", "(", "input_ids", ",", "branch_graph", ".", "inputs", ")", ")", "input_list", "=", "[", "]", "for", "in_t", "in", "new_inputs", ":", "param", "=", "branch_input_to_param", ".", "get", "(", "ops", ".", "tensor_id", "(", "in_t", ")", ")", "if", "param", "is", "None", ":", "param", "=", "_create_dummy_input", "(", "branch_graph", ",", "in_t", ")", "input_list", ".", "append", "(", "param", ")", "branch_graph", ".", "inputs", "=", "input_list", "# Rewrite the FuncGraphs' state to reflect the new inputs.", "branch_graph", ".", "reset_captures", "(", "zip", "(", "new_inputs", ",", "branch_graph", ".", "inputs", ")", ")", "return", "new_inputs" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/cond_v2.py#L508-L550
apache/mesos
97d9a4063332aae3825d78de71611657e05cf5e2
src/python/interface/src/mesos/interface/__init__.py
python
SchedulerDriver.start
(self)
Starts the scheduler driver. This needs to be called before any other driver calls are made.
Starts the scheduler driver. This needs to be called before any other driver calls are made.
[ "Starts", "the", "scheduler", "driver", ".", "This", "needs", "to", "be", "called", "before", "any", "other", "driver", "calls", "are", "made", "." ]
def start(self): """ Starts the scheduler driver. This needs to be called before any other driver calls are made. """
[ "def", "start", "(", "self", ")", ":" ]
https://github.com/apache/mesos/blob/97d9a4063332aae3825d78de71611657e05cf5e2/src/python/interface/src/mesos/interface/__init__.py#L145-L149
infinit/memo
3a8394d0f647efe03ccb8bfe885a7279cb8be8a6
elle/drake/src/drake/__init__.py
python
Builder.targets
(self)
return self.__targets
The list of target nodes.
The list of target nodes.
[ "The", "list", "of", "target", "nodes", "." ]
def targets(self): """The list of target nodes.""" return self.__targets
[ "def", "targets", "(", "self", ")", ":", "return", "self", ".", "__targets" ]
https://github.com/infinit/memo/blob/3a8394d0f647efe03ccb8bfe885a7279cb8be8a6/elle/drake/src/drake/__init__.py#L1936-L1938
BitMEX/api-connectors
37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812
auto-generated/python/swagger_client/models/margin.py
python
Margin.excess_margin
(self, excess_margin)
Sets the excess_margin of this Margin. :param excess_margin: The excess_margin of this Margin. # noqa: E501 :type: float
Sets the excess_margin of this Margin.
[ "Sets", "the", "excess_margin", "of", "this", "Margin", "." ]
def excess_margin(self, excess_margin): """Sets the excess_margin of this Margin. :param excess_margin: The excess_margin of this Margin. # noqa: E501 :type: float """ self._excess_margin = excess_margin
[ "def", "excess_margin", "(", "self", ",", "excess_margin", ")", ":", "self", ".", "_excess_margin", "=", "excess_margin" ]
https://github.com/BitMEX/api-connectors/blob/37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812/auto-generated/python/swagger_client/models/margin.py#L977-L985
hpi-xnor/BMXNet-v2
af2b1859eafc5c721b1397cef02f946aaf2ce20d
python/mxnet/rnn/io.py
python
BucketSentenceIter.reset
(self)
Resets the iterator to the beginning of the data.
Resets the iterator to the beginning of the data.
[ "Resets", "the", "iterator", "to", "the", "beginning", "of", "the", "data", "." ]
def reset(self): """Resets the iterator to the beginning of the data.""" self.curr_idx = 0 random.shuffle(self.idx) for buck in self.data: np.random.shuffle(buck) self.nddata = [] self.ndlabel = [] for buck in self.data: label = np.empty_like(buck) label[:, :-1] = buck[:, 1:] label[:, -1] = self.invalid_label self.nddata.append(ndarray.array(buck, dtype=self.dtype)) self.ndlabel.append(ndarray.array(label, dtype=self.dtype))
[ "def", "reset", "(", "self", ")", ":", "self", ".", "curr_idx", "=", "0", "random", ".", "shuffle", "(", "self", ".", "idx", ")", "for", "buck", "in", "self", ".", "data", ":", "np", ".", "random", ".", "shuffle", "(", "buck", ")", "self", ".", "nddata", "=", "[", "]", "self", ".", "ndlabel", "=", "[", "]", "for", "buck", "in", "self", ".", "data", ":", "label", "=", "np", ".", "empty_like", "(", "buck", ")", "label", "[", ":", ",", ":", "-", "1", "]", "=", "buck", "[", ":", ",", "1", ":", "]", "label", "[", ":", ",", "-", "1", "]", "=", "self", ".", "invalid_label", "self", ".", "nddata", ".", "append", "(", "ndarray", ".", "array", "(", "buck", ",", "dtype", "=", "self", ".", "dtype", ")", ")", "self", ".", "ndlabel", ".", "append", "(", "ndarray", ".", "array", "(", "label", ",", "dtype", "=", "self", ".", "dtype", ")", ")" ]
https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/python/mxnet/rnn/io.py#L174-L188
htcondor/htcondor
4829724575176d1d6c936e4693dfd78a728569b0
src/condor_contrib/condor_pigeon/src/condor_pigeon_client/skype_linux_tools/Skype4Py/skype.py
python
ISkype.Conference
(self, Id=0)
return o
Queries a call conference object. @param Id: Conference Id. @type Id: int @return: A conference object. @rtype: L{IConference}
Queries a call conference object.
[ "Queries", "a", "call", "conference", "object", "." ]
def Conference(self, Id=0): '''Queries a call conference object. @param Id: Conference Id. @type Id: int @return: A conference object. @rtype: L{IConference} ''' o = IConference(Id, self) if Id <= 0 or not o.Calls: raise ISkypeError(0, 'Unknown conference') return o
[ "def", "Conference", "(", "self", ",", "Id", "=", "0", ")", ":", "o", "=", "IConference", "(", "Id", ",", "self", ")", "if", "Id", "<=", "0", "or", "not", "o", ".", "Calls", ":", "raise", "ISkypeError", "(", "0", ",", "'Unknown conference'", ")", "return", "o" ]
https://github.com/htcondor/htcondor/blob/4829724575176d1d6c936e4693dfd78a728569b0/src/condor_contrib/condor_pigeon/src/condor_pigeon_client/skype_linux_tools/Skype4Py/skype.py#L586-L597
mongodb/mongo
d8ff665343ad29cf286ee2cf4a1960d29371937b
buildscripts/idl/idl/ast.py
python
Validator.__init__
(self, file_name, line, column)
Construct a Validator.
Construct a Validator.
[ "Construct", "a", "Validator", "." ]
def __init__(self, file_name, line, column): # type: (str, int, int) -> None """Construct a Validator.""" # Don't lint gt/lt as bad attribute names. # pylint: disable=C0103 self.gt = None # type: Expression self.lt = None # type: Expression self.gte = None # type: Expression self.lte = None # type: Expression self.callback = None # type: Optional[str] super(Validator, self).__init__(file_name, line, column)
[ "def", "__init__", "(", "self", ",", "file_name", ",", "line", ",", "column", ")", ":", "# type: (str, int, int) -> None", "# Don't lint gt/lt as bad attribute names.", "# pylint: disable=C0103", "self", ".", "gt", "=", "None", "# type: Expression", "self", ".", "lt", "=", "None", "# type: Expression", "self", ".", "gte", "=", "None", "# type: Expression", "self", ".", "lte", "=", "None", "# type: Expression", "self", ".", "callback", "=", "None", "# type: Optional[str]", "super", "(", "Validator", ",", "self", ")", ".", "__init__", "(", "file_name", ",", "line", ",", "column", ")" ]
https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/idl/idl/ast.py#L172-L183
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/setuptools/py2/setuptools/dist.py
python
Distribution._clean_req
(self, req)
return req
Given a Requirement, remove environment markers and return it.
Given a Requirement, remove environment markers and return it.
[ "Given", "a", "Requirement", "remove", "environment", "markers", "and", "return", "it", "." ]
def _clean_req(self, req): """ Given a Requirement, remove environment markers and return it. """ req.marker = None return req
[ "def", "_clean_req", "(", "self", ",", "req", ")", ":", "req", ".", "marker", "=", "None", "return", "req" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py2/setuptools/dist.py#L558-L563
takemaru/graphillion
51879f92bb96b53ef8f914ef37a05252ce383617
graphillion/graphset.py
python
GraphSet.intersection_update
(self, *others)
return self
Updates `self`, keeping only graphs found in it and all others. Examples: >>> graph1 = [] >>> graph2 = [(1, 2)] >>> graph3 = [(1, 2), (1, 4)] >>> gs1 = GraphSet([graph1, graph2]) >>> gs2 = GraphSet([graph2, graph3]) >>> gs1 &= gs2 >>> gs1 GraphSet([[(1, 2)]]) Returns: A new GraphSet object. See Also: intersection()
Updates `self`, keeping only graphs found in it and all others.
[ "Updates", "self", "keeping", "only", "graphs", "found", "in", "it", "and", "all", "others", "." ]
def intersection_update(self, *others): """Updates `self`, keeping only graphs found in it and all others. Examples: >>> graph1 = [] >>> graph2 = [(1, 2)] >>> graph3 = [(1, 2), (1, 4)] >>> gs1 = GraphSet([graph1, graph2]) >>> gs2 = GraphSet([graph2, graph3]) >>> gs1 &= gs2 >>> gs1 GraphSet([[(1, 2)]]) Returns: A new GraphSet object. See Also: intersection() """ self._ss.intersection_update(*[gs._ss for gs in others]) return self
[ "def", "intersection_update", "(", "self", ",", "*", "others", ")", ":", "self", ".", "_ss", ".", "intersection_update", "(", "*", "[", "gs", ".", "_ss", "for", "gs", "in", "others", "]", ")", "return", "self" ]
https://github.com/takemaru/graphillion/blob/51879f92bb96b53ef8f914ef37a05252ce383617/graphillion/graphset.py#L333-L353
mongodb/mongo
d8ff665343ad29cf286ee2cf4a1960d29371937b
src/third_party/abseil-cpp-master/abseil-cpp/absl/abseil.podspec.gen.py
python
get_spec_var
(depth)
return "s" if depth == 0 else "s{}".format(depth)
Returns the name of variable for spec with given depth.
Returns the name of variable for spec with given depth.
[ "Returns", "the", "name", "of", "variable", "for", "spec", "with", "given", "depth", "." ]
def get_spec_var(depth): """Returns the name of variable for spec with given depth.""" return "s" if depth == 0 else "s{}".format(depth)
[ "def", "get_spec_var", "(", "depth", ")", ":", "return", "\"s\"", "if", "depth", "==", "0", "else", "\"s{}\"", ".", "format", "(", "depth", ")" ]
https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/src/third_party/abseil-cpp-master/abseil-cpp/absl/abseil.podspec.gen.py#L122-L124
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
third_party/closure_linter/closure_linter/tokenutil.py
python
InsertTokenAfter
(new_token, token)
Insert new_token after token. Args: new_token: A token to be added to the stream token: A token already in the stream
Insert new_token after token.
[ "Insert", "new_token", "after", "token", "." ]
def InsertTokenAfter(new_token, token): """Insert new_token after token. Args: new_token: A token to be added to the stream token: A token already in the stream """ new_token.previous = token new_token.next = token.next new_token.metadata = copy.copy(token.metadata) if token.IsCode(): new_token.metadata.last_code = token if new_token.IsCode(): following_token = token.next while following_token and following_token.metadata.last_code == token: following_token.metadata.last_code = new_token following_token = following_token.next token.next = new_token if new_token.next: new_token.next.previous = new_token if new_token.start_index is None: if new_token.line_number == token.line_number: new_token.start_index = token.start_index + len(token.string) else: new_token.start_index = 0 iterator = new_token.next while iterator and iterator.line_number == new_token.line_number: iterator.start_index += len(new_token.string) iterator = iterator.next
[ "def", "InsertTokenAfter", "(", "new_token", ",", "token", ")", ":", "new_token", ".", "previous", "=", "token", "new_token", ".", "next", "=", "token", ".", "next", "new_token", ".", "metadata", "=", "copy", ".", "copy", "(", "token", ".", "metadata", ")", "if", "token", ".", "IsCode", "(", ")", ":", "new_token", ".", "metadata", ".", "last_code", "=", "token", "if", "new_token", ".", "IsCode", "(", ")", ":", "following_token", "=", "token", ".", "next", "while", "following_token", "and", "following_token", ".", "metadata", ".", "last_code", "==", "token", ":", "following_token", ".", "metadata", ".", "last_code", "=", "new_token", "following_token", "=", "following_token", ".", "next", "token", ".", "next", "=", "new_token", "if", "new_token", ".", "next", ":", "new_token", ".", "next", ".", "previous", "=", "new_token", "if", "new_token", ".", "start_index", "is", "None", ":", "if", "new_token", ".", "line_number", "==", "token", ".", "line_number", ":", "new_token", ".", "start_index", "=", "token", ".", "start_index", "+", "len", "(", "token", ".", "string", ")", "else", ":", "new_token", ".", "start_index", "=", "0", "iterator", "=", "new_token", ".", "next", "while", "iterator", "and", "iterator", ".", "line_number", "==", "new_token", ".", "line_number", ":", "iterator", ".", "start_index", "+=", "len", "(", "new_token", ".", "string", ")", "iterator", "=", "iterator", ".", "next" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/closure_linter/closure_linter/tokenutil.py#L241-L275
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/keras/distribute/distributed_training_utils.py
python
_copy_weights_to_original_model
(model, mode)
Copies weights from first distributed model back to original model.
Copies weights from first distributed model back to original model.
[ "Copies", "weights", "from", "first", "distributed", "model", "back", "to", "original", "model", "." ]
def _copy_weights_to_original_model(model, mode): """Copies weights from first distributed model back to original model.""" if model._distribution_strategy and mode == ModeKeys.TRAIN: distributed_model = get_distributed_model(model, mode) updated_weights = model._distribution_strategy.unwrap( distributed_model)[0].get_weights() model.set_weights(updated_weights)
[ "def", "_copy_weights_to_original_model", "(", "model", ",", "mode", ")", ":", "if", "model", ".", "_distribution_strategy", "and", "mode", "==", "ModeKeys", ".", "TRAIN", ":", "distributed_model", "=", "get_distributed_model", "(", "model", ",", "mode", ")", "updated_weights", "=", "model", ".", "_distribution_strategy", ".", "unwrap", "(", "distributed_model", ")", "[", "0", "]", ".", "get_weights", "(", ")", "model", ".", "set_weights", "(", "updated_weights", ")" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/keras/distribute/distributed_training_utils.py#L1045-L1051
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/telemetry/telemetry/core/tracing_controller.py
python
TracingController.StopTracing
(self)
return self._tracing_controller_backend.StopTracing()
Stops tracing and returns a TraceValue.
Stops tracing and returns a TraceValue.
[ "Stops", "tracing", "and", "returns", "a", "TraceValue", "." ]
def StopTracing(self): """Stops tracing and returns a TraceValue.""" return self._tracing_controller_backend.StopTracing()
[ "def", "StopTracing", "(", "self", ")", ":", "return", "self", ".", "_tracing_controller_backend", ".", "StopTracing", "(", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/telemetry/core/tracing_controller.py#L45-L47
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/plat-mac/lib-scriptpackages/Finder/Finder_items.py
python
Finder_items_Events.empty
(self, _object=None, _attributes={}, **_arguments)
empty: Empty the trash Required argument: \xd2empty\xd3 and \xd2empty trash\xd3 both do the same thing Keyword argument _attributes: AppleEvent attribute dictionary
empty: Empty the trash Required argument: \xd2empty\xd3 and \xd2empty trash\xd3 both do the same thing Keyword argument _attributes: AppleEvent attribute dictionary
[ "empty", ":", "Empty", "the", "trash", "Required", "argument", ":", "\\", "xd2empty", "\\", "xd3", "and", "\\", "xd2empty", "trash", "\\", "xd3", "both", "do", "the", "same", "thing", "Keyword", "argument", "_attributes", ":", "AppleEvent", "attribute", "dictionary" ]
def empty(self, _object=None, _attributes={}, **_arguments): """empty: Empty the trash Required argument: \xd2empty\xd3 and \xd2empty trash\xd3 both do the same thing Keyword argument _attributes: AppleEvent attribute dictionary """ _code = 'fndr' _subcode = 'empt' if _arguments: raise TypeError, 'No optional args expected' _arguments['----'] = _object _reply, _arguments, _attributes = self.send(_code, _subcode, _arguments, _attributes) if _arguments.get('errn', 0): raise aetools.Error, aetools.decodeerror(_arguments) # XXXX Optionally decode result if _arguments.has_key('----'): return _arguments['----']
[ "def", "empty", "(", "self", ",", "_object", "=", "None", ",", "_attributes", "=", "{", "}", ",", "*", "*", "_arguments", ")", ":", "_code", "=", "'fndr'", "_subcode", "=", "'empt'", "if", "_arguments", ":", "raise", "TypeError", ",", "'No optional args expected'", "_arguments", "[", "'----'", "]", "=", "_object", "_reply", ",", "_arguments", ",", "_attributes", "=", "self", ".", "send", "(", "_code", ",", "_subcode", ",", "_arguments", ",", "_attributes", ")", "if", "_arguments", ".", "get", "(", "'errn'", ",", "0", ")", ":", "raise", "aetools", ".", "Error", ",", "aetools", ".", "decodeerror", "(", "_arguments", ")", "# XXXX Optionally decode result", "if", "_arguments", ".", "has_key", "(", "'----'", ")", ":", "return", "_arguments", "[", "'----'", "]" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/plat-mac/lib-scriptpackages/Finder/Finder_items.py#L80-L98
Slicer/Slicer
ba9fadf332cb0303515b68d8d06a344c82e3e3e5
Base/Python/slicer/util.py
python
getNewModuleWidget
(module)
Create new module widget instance. In general, not recommended, as module widget may be developed expecting that there is only a single instance of this widget. Instead, of instantiating a complete module GUI, it is recommended to create only selected widgets that are used in the module GUI. :param module: module name or module object :return: module widget object :raises RuntimeError: if the module does not have widget.
Create new module widget instance.
[ "Create", "new", "module", "widget", "instance", "." ]
def getNewModuleWidget(module): """Create new module widget instance. In general, not recommended, as module widget may be developed expecting that there is only a single instance of this widget. Instead, of instantiating a complete module GUI, it is recommended to create only selected widgets that are used in the module GUI. :param module: module name or module object :return: module widget object :raises RuntimeError: if the module does not have widget. """ import slicer if isinstance(module, str): module = getModule(module) widgetRepr = module.createNewWidgetRepresentation() if not widgetRepr: raise RuntimeError("Could not find module widget representation with name '%s'" % module.name) if isinstance(widgetRepr, slicer.qSlicerScriptedLoadableModuleWidget): # Scripted module, return the Python class return widgetRepr.self() else: # C++ module return widgetRepr
[ "def", "getNewModuleWidget", "(", "module", ")", ":", "import", "slicer", "if", "isinstance", "(", "module", ",", "str", ")", ":", "module", "=", "getModule", "(", "module", ")", "widgetRepr", "=", "module", ".", "createNewWidgetRepresentation", "(", ")", "if", "not", "widgetRepr", ":", "raise", "RuntimeError", "(", "\"Could not find module widget representation with name '%s'\"", "%", "module", ".", "name", ")", "if", "isinstance", "(", "widgetRepr", ",", "slicer", ".", "qSlicerScriptedLoadableModuleWidget", ")", ":", "# Scripted module, return the Python class", "return", "widgetRepr", ".", "self", "(", ")", "else", ":", "# C++ module", "return", "widgetRepr" ]
https://github.com/Slicer/Slicer/blob/ba9fadf332cb0303515b68d8d06a344c82e3e3e5/Base/Python/slicer/util.py#L1068-L1090
kamyu104/LeetCode-Solutions
77605708a927ea3b85aee5a479db733938c7c211
Python/power-of-four.py
python
Solution3.isPowerOfFour
(self, num)
return True if num[2:].startswith('1') and len(num[2:]) == num.count('0') and num.count('0') % 2 and '-' not in num else False
:type num: int :rtype: bool
:type num: int :rtype: bool
[ ":", "type", "num", ":", "int", ":", "rtype", ":", "bool" ]
def isPowerOfFour(self, num): """ :type num: int :rtype: bool """ num = bin(num) return True if num[2:].startswith('1') and len(num[2:]) == num.count('0') and num.count('0') % 2 and '-' not in num else False
[ "def", "isPowerOfFour", "(", "self", ",", "num", ")", ":", "num", "=", "bin", "(", "num", ")", "return", "True", "if", "num", "[", "2", ":", "]", ".", "startswith", "(", "'1'", ")", "and", "len", "(", "num", "[", "2", ":", "]", ")", "==", "num", ".", "count", "(", "'0'", ")", "and", "num", ".", "count", "(", "'0'", ")", "%", "2", "and", "'-'", "not", "in", "num", "else", "False" ]
https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/power-of-four.py#L28-L34
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/configure.py
python
set_tf_cudnn_version
(environ_cp)
Set TF_CUDNN_VERSION.
Set TF_CUDNN_VERSION.
[ "Set", "TF_CUDNN_VERSION", "." ]
def set_tf_cudnn_version(environ_cp): """Set TF_CUDNN_VERSION.""" ask_cudnn_version = ( 'Please specify the cuDNN version you want to use. ' '[Leave empty to default to cuDNN %s]: ') % _DEFAULT_CUDNN_VERSION tf_cudnn_version = get_from_env_or_user_or_default(environ_cp, 'TF_CUDNN_VERSION', ask_cudnn_version, _DEFAULT_CUDNN_VERSION) environ_cp['TF_CUDNN_VERSION'] = tf_cudnn_version
[ "def", "set_tf_cudnn_version", "(", "environ_cp", ")", ":", "ask_cudnn_version", "=", "(", "'Please specify the cuDNN version you want to use. '", "'[Leave empty to default to cuDNN %s]: '", ")", "%", "_DEFAULT_CUDNN_VERSION", "tf_cudnn_version", "=", "get_from_env_or_user_or_default", "(", "environ_cp", ",", "'TF_CUDNN_VERSION'", ",", "ask_cudnn_version", ",", "_DEFAULT_CUDNN_VERSION", ")", "environ_cp", "[", "'TF_CUDNN_VERSION'", "]", "=", "tf_cudnn_version" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/configure.py#L892-L901
telefonicaid/fiware-orion
27c3202b9ddcfb9e3635a0af8d373f76e89b1d24
scripts/pdi-pep8.py
python
ignore_code
(code)
Check if options.ignore contains a prefix of the error code. If options.select contains a prefix of the error code, do not ignore it.
Check if options.ignore contains a prefix of the error code. If options.select contains a prefix of the error code, do not ignore it.
[ "Check", "if", "options", ".", "ignore", "contains", "a", "prefix", "of", "the", "error", "code", ".", "If", "options", ".", "select", "contains", "a", "prefix", "of", "the", "error", "code", "do", "not", "ignore", "it", "." ]
def ignore_code(code): """ Check if options.ignore contains a prefix of the error code. If options.select contains a prefix of the error code, do not ignore it. """ for select in options.select: if code.startswith(select): return False for ignore in options.ignore: if code.startswith(ignore): return True
[ "def", "ignore_code", "(", "code", ")", ":", "for", "select", "in", "options", ".", "select", ":", "if", "code", ".", "startswith", "(", "select", ")", ":", "return", "False", "for", "ignore", "in", "options", ".", "ignore", ":", "if", "code", ".", "startswith", "(", "ignore", ")", ":", "return", "True" ]
https://github.com/telefonicaid/fiware-orion/blob/27c3202b9ddcfb9e3635a0af8d373f76e89b1d24/scripts/pdi-pep8.py#L1079-L1089
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/flatnotebook.py
python
PageInfo.GetColour
(self)
return self._colour
Returns the tab colour.
Returns the tab colour.
[ "Returns", "the", "tab", "colour", "." ]
def GetColour(self): """ Returns the tab colour. """ return self._colour
[ "def", "GetColour", "(", "self", ")", ":", "return", "self", ".", "_colour" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/flatnotebook.py#L1289-L1292
ros-perception/vision_opencv
c791220cefd0abf02c6719e2ce0fea465857a88e
image_geometry/src/image_geometry/cameramodels.py
python
PinholeCameraModel.rectifyPoint
(self, uv_raw)
return dst[0,0]
:param uv_raw: pixel coordinates :type uv_raw: (u, v) Applies the rectification specified by camera parameters :math:`K` and and :math:`D` to point (u, v) and returns the pixel coordinates of the rectified point.
:param uv_raw: pixel coordinates :type uv_raw: (u, v)
[ ":", "param", "uv_raw", ":", "pixel", "coordinates", ":", "type", "uv_raw", ":", "(", "u", "v", ")" ]
def rectifyPoint(self, uv_raw): """ :param uv_raw: pixel coordinates :type uv_raw: (u, v) Applies the rectification specified by camera parameters :math:`K` and and :math:`D` to point (u, v) and returns the pixel coordinates of the rectified point. """ src = mkmat(1, 2, list(uv_raw)) src.resize((1,1,2)) dst = cv2.undistortPoints(src, self.K, self.D, R=self.R, P=self.P) return dst[0,0]
[ "def", "rectifyPoint", "(", "self", ",", "uv_raw", ")", ":", "src", "=", "mkmat", "(", "1", ",", "2", ",", "list", "(", "uv_raw", ")", ")", "src", ".", "resize", "(", "(", "1", ",", "1", ",", "2", ")", ")", "dst", "=", "cv2", ".", "undistortPoints", "(", "src", ",", "self", ".", "K", ",", "self", ".", "D", ",", "R", "=", "self", ".", "R", ",", "P", "=", "self", ".", "P", ")", "return", "dst", "[", "0", ",", "0", "]" ]
https://github.com/ros-perception/vision_opencv/blob/c791220cefd0abf02c6719e2ce0fea465857a88e/image_geometry/src/image_geometry/cameramodels.py#L94-L107
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Draft/draftobjects/rectangle.py
python
Rectangle.execute
(self, obj)
This method is run when the object is created or recomputed.
This method is run when the object is created or recomputed.
[ "This", "method", "is", "run", "when", "the", "object", "is", "created", "or", "recomputed", "." ]
def execute(self, obj): """This method is run when the object is created or recomputed.""" import Part if (obj.Length.Value == 0) or (obj.Height.Value == 0): obj.positionBySupport() return plm = obj.Placement shape = None if hasattr(obj,"Rows") and hasattr(obj,"Columns"): # TODO: verify if this is needed: if obj.Rows > 1: rows = obj.Rows else: rows = 1 if obj.Columns > 1: columns = obj.Columns else: columns = 1 # TODO: till here if (rows > 1) or (columns > 1): shapes = [] l = obj.Length.Value/columns h = obj.Height.Value/rows for i in range(columns): for j in range(rows): p1 = App.Vector(i*l,j*h,0) p2 = App.Vector(p1.x+l,p1.y,p1.z) p3 = App.Vector(p1.x+l,p1.y+h,p1.z) p4 = App.Vector(p1.x,p1.y+h,p1.z) p = Part.makePolygon([p1,p2,p3,p4,p1]) if "ChamferSize" in obj.PropertiesList: if obj.ChamferSize.Value != 0: w = DraftGeomUtils.filletWire(p, obj.ChamferSize.Value, chamfer=True) if w: p = w if "FilletRadius" in obj.PropertiesList: if obj.FilletRadius.Value != 0: w = DraftGeomUtils.filletWire(p, obj.FilletRadius.Value) if w: p = w if hasattr(obj,"MakeFace"): if obj.MakeFace: p = Part.Face(p) shapes.append(p) if shapes: shape = Part.makeCompound(shapes) if not shape: p1 = App.Vector(0,0,0) p2 = App.Vector(p1.x+obj.Length.Value, p1.y, p1.z) p3 = App.Vector(p1.x+obj.Length.Value, p1.y+obj.Height.Value, p1.z) p4 = App.Vector(p1.x, p1.y+obj.Height.Value, p1.z) shape = Part.makePolygon([p1, p2, p3, p4, p1]) if "ChamferSize" in obj.PropertiesList: if obj.ChamferSize.Value != 0: w = DraftGeomUtils.filletWire(shape, obj.ChamferSize.Value, chamfer=True) if w: shape = w if "FilletRadius" in obj.PropertiesList: if obj.FilletRadius.Value != 0: w = DraftGeomUtils.filletWire(shape, obj.FilletRadius.Value) if w: shape = w if hasattr(obj,"MakeFace"): if obj.MakeFace: shape = Part.Face(shape) else: shape = Part.Face(shape) obj.Shape = shape if hasattr(obj,"Area") and hasattr(shape,"Area"): obj.Area = shape.Area obj.Placement = plm obj.positionBySupport()
[ "def", "execute", "(", "self", ",", "obj", ")", ":", "import", "Part", "if", "(", "obj", ".", "Length", ".", "Value", "==", "0", ")", "or", "(", "obj", ".", "Height", ".", "Value", "==", "0", ")", ":", "obj", ".", "positionBySupport", "(", ")", "return", "plm", "=", "obj", ".", "Placement", "shape", "=", "None", "if", "hasattr", "(", "obj", ",", "\"Rows\"", ")", "and", "hasattr", "(", "obj", ",", "\"Columns\"", ")", ":", "# TODO: verify if this is needed:", "if", "obj", ".", "Rows", ">", "1", ":", "rows", "=", "obj", ".", "Rows", "else", ":", "rows", "=", "1", "if", "obj", ".", "Columns", ">", "1", ":", "columns", "=", "obj", ".", "Columns", "else", ":", "columns", "=", "1", "# TODO: till here", "if", "(", "rows", ">", "1", ")", "or", "(", "columns", ">", "1", ")", ":", "shapes", "=", "[", "]", "l", "=", "obj", ".", "Length", ".", "Value", "/", "columns", "h", "=", "obj", ".", "Height", ".", "Value", "/", "rows", "for", "i", "in", "range", "(", "columns", ")", ":", "for", "j", "in", "range", "(", "rows", ")", ":", "p1", "=", "App", ".", "Vector", "(", "i", "*", "l", ",", "j", "*", "h", ",", "0", ")", "p2", "=", "App", ".", "Vector", "(", "p1", ".", "x", "+", "l", ",", "p1", ".", "y", ",", "p1", ".", "z", ")", "p3", "=", "App", ".", "Vector", "(", "p1", ".", "x", "+", "l", ",", "p1", ".", "y", "+", "h", ",", "p1", ".", "z", ")", "p4", "=", "App", ".", "Vector", "(", "p1", ".", "x", ",", "p1", ".", "y", "+", "h", ",", "p1", ".", "z", ")", "p", "=", "Part", ".", "makePolygon", "(", "[", "p1", ",", "p2", ",", "p3", ",", "p4", ",", "p1", "]", ")", "if", "\"ChamferSize\"", "in", "obj", ".", "PropertiesList", ":", "if", "obj", ".", "ChamferSize", ".", "Value", "!=", "0", ":", "w", "=", "DraftGeomUtils", ".", "filletWire", "(", "p", ",", "obj", ".", "ChamferSize", ".", "Value", ",", "chamfer", "=", "True", ")", "if", "w", ":", "p", "=", "w", "if", "\"FilletRadius\"", "in", "obj", ".", "PropertiesList", ":", "if", "obj", ".", "FilletRadius", ".", "Value", "!=", "0", ":", "w", "=", "DraftGeomUtils", ".", "filletWire", "(", "p", ",", "obj", ".", "FilletRadius", ".", "Value", ")", "if", "w", ":", "p", "=", "w", "if", "hasattr", "(", "obj", ",", "\"MakeFace\"", ")", ":", "if", "obj", ".", "MakeFace", ":", "p", "=", "Part", ".", "Face", "(", "p", ")", "shapes", ".", "append", "(", "p", ")", "if", "shapes", ":", "shape", "=", "Part", ".", "makeCompound", "(", "shapes", ")", "if", "not", "shape", ":", "p1", "=", "App", ".", "Vector", "(", "0", ",", "0", ",", "0", ")", "p2", "=", "App", ".", "Vector", "(", "p1", ".", "x", "+", "obj", ".", "Length", ".", "Value", ",", "p1", ".", "y", ",", "p1", ".", "z", ")", "p3", "=", "App", ".", "Vector", "(", "p1", ".", "x", "+", "obj", ".", "Length", ".", "Value", ",", "p1", ".", "y", "+", "obj", ".", "Height", ".", "Value", ",", "p1", ".", "z", ")", "p4", "=", "App", ".", "Vector", "(", "p1", ".", "x", ",", "p1", ".", "y", "+", "obj", ".", "Height", ".", "Value", ",", "p1", ".", "z", ")", "shape", "=", "Part", ".", "makePolygon", "(", "[", "p1", ",", "p2", ",", "p3", ",", "p4", ",", "p1", "]", ")", "if", "\"ChamferSize\"", "in", "obj", ".", "PropertiesList", ":", "if", "obj", ".", "ChamferSize", ".", "Value", "!=", "0", ":", "w", "=", "DraftGeomUtils", ".", "filletWire", "(", "shape", ",", "obj", ".", "ChamferSize", ".", "Value", ",", "chamfer", "=", "True", ")", "if", "w", ":", "shape", "=", "w", "if", "\"FilletRadius\"", "in", "obj", ".", "PropertiesList", ":", "if", "obj", ".", "FilletRadius", ".", "Value", "!=", "0", ":", "w", "=", "DraftGeomUtils", ".", "filletWire", "(", "shape", ",", "obj", ".", "FilletRadius", ".", "Value", ")", "if", "w", ":", "shape", "=", "w", "if", "hasattr", "(", "obj", ",", "\"MakeFace\"", ")", ":", "if", "obj", ".", "MakeFace", ":", "shape", "=", "Part", ".", "Face", "(", "shape", ")", "else", ":", "shape", "=", "Part", ".", "Face", "(", "shape", ")", "obj", ".", "Shape", "=", "shape", "if", "hasattr", "(", "obj", ",", "\"Area\"", ")", "and", "hasattr", "(", "shape", ",", "\"Area\"", ")", ":", "obj", ".", "Area", "=", "shape", ".", "Area", "obj", ".", "Placement", "=", "plm", "obj", ".", "positionBySupport", "(", ")" ]
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Draft/draftobjects/rectangle.py#L75-L168
astra-toolbox/astra-toolbox
1e7ec8af702e595b76654f2e500f4c00344b273f
python/astra/matlab.py
python
data3d
(command, *args)
return getattr(data3d_c, command)(*args)
MATLAB-like interface to the :mod:`astra.data3d` module For example: ``astra.m.data3d('get',i)`` -- Get 3D object data.
MATLAB-like interface to the :mod:`astra.data3d` module For example: ``astra.m.data3d('get',i)`` -- Get 3D object data.
[ "MATLAB", "-", "like", "interface", "to", "the", ":", "mod", ":", "astra", ".", "data3d", "module", "For", "example", ":", "astra", ".", "m", ".", "data3d", "(", "get", "i", ")", "--", "Get", "3D", "object", "data", "." ]
def data3d(command, *args): """MATLAB-like interface to the :mod:`astra.data3d` module For example: ``astra.m.data3d('get',i)`` -- Get 3D object data. """ return getattr(data3d_c, command)(*args)
[ "def", "data3d", "(", "command", ",", "*", "args", ")", ":", "return", "getattr", "(", "data3d_c", ",", "command", ")", "(", "*", "args", ")" ]
https://github.com/astra-toolbox/astra-toolbox/blob/1e7ec8af702e595b76654f2e500f4c00344b273f/python/astra/matlab.py#L69-L77
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
third_party/bintrees/bintrees/treemixin.py
python
TreeMixin.get
(self, key, default=None)
T.get(k[,d]) -> T[k] if k in T, else d. d defaults to None.
T.get(k[,d]) -> T[k] if k in T, else d. d defaults to None.
[ "T", ".", "get", "(", "k", "[", "d", "]", ")", "-", ">", "T", "[", "k", "]", "if", "k", "in", "T", "else", "d", ".", "d", "defaults", "to", "None", "." ]
def get(self, key, default=None): """ T.get(k[,d]) -> T[k] if k in T, else d. d defaults to None. """ try: return self.get_value(key) except KeyError: return default
[ "def", "get", "(", "self", ",", "key", ",", "default", "=", "None", ")", ":", "try", ":", "return", "self", ".", "get_value", "(", "key", ")", "except", "KeyError", ":", "return", "default" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/bintrees/bintrees/treemixin.py#L402-L407
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Editor/Python/windows/Lib/site-packages/pip/_vendor/requests/packages/urllib3/util/url.py
python
Url.url
(self)
return url
Convert self into a url This function should more or less round-trip with :func:`.parse_url`. The returned url may not be exactly the same as the url inputted to :func:`.parse_url`, but it should be equivalent by the RFC (e.g., urls with a blank port will have : removed). Example: :: >>> U = parse_url('http://google.com/mail/') >>> U.url 'http://google.com/mail/' >>> Url('http', 'username:password', 'host.com', 80, ... '/path', 'query', 'fragment').url 'http://username:password@host.com:80/path?query#fragment'
Convert self into a url
[ "Convert", "self", "into", "a", "url" ]
def url(self): """ Convert self into a url This function should more or less round-trip with :func:`.parse_url`. The returned url may not be exactly the same as the url inputted to :func:`.parse_url`, but it should be equivalent by the RFC (e.g., urls with a blank port will have : removed). Example: :: >>> U = parse_url('http://google.com/mail/') >>> U.url 'http://google.com/mail/' >>> Url('http', 'username:password', 'host.com', 80, ... '/path', 'query', 'fragment').url 'http://username:password@host.com:80/path?query#fragment' """ scheme, auth, host, port, path, query, fragment = self url = '' # We use "is not None" we want things to happen with empty strings (or 0 port) if scheme is not None: url += scheme + '://' if auth is not None: url += auth + '@' if host is not None: url += host if port is not None: url += ':' + str(port) if path is not None: url += path if query is not None: url += '?' + query if fragment is not None: url += '#' + fragment return url
[ "def", "url", "(", "self", ")", ":", "scheme", ",", "auth", ",", "host", ",", "port", ",", "path", ",", "query", ",", "fragment", "=", "self", "url", "=", "''", "# We use \"is not None\" we want things to happen with empty strings (or 0 port)", "if", "scheme", "is", "not", "None", ":", "url", "+=", "scheme", "+", "'://'", "if", "auth", "is", "not", "None", ":", "url", "+=", "auth", "+", "'@'", "if", "host", "is", "not", "None", ":", "url", "+=", "host", "if", "port", "is", "not", "None", ":", "url", "+=", "':'", "+", "str", "(", "port", ")", "if", "path", "is", "not", "None", ":", "url", "+=", "path", "if", "query", "is", "not", "None", ":", "url", "+=", "'?'", "+", "query", "if", "fragment", "is", "not", "None", ":", "url", "+=", "'#'", "+", "fragment", "return", "url" ]
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/pip/_vendor/requests/packages/urllib3/util/url.py#L46-L83
martinrotter/textosaurus
4e2ad75abaf5b7e6a823766a2aa8a30f0c965cb8
src/libtextosaurus/3rd-party/scintilla/scripts/FileGenerator.py
python
UpdateFileFromLines
(path, lines, lineEndToUse)
Join the lines with the lineEndToUse then update file if the result is different.
Join the lines with the lineEndToUse then update file if the result is different.
[ "Join", "the", "lines", "with", "the", "lineEndToUse", "then", "update", "file", "if", "the", "result", "is", "different", "." ]
def UpdateFileFromLines(path, lines, lineEndToUse): """Join the lines with the lineEndToUse then update file if the result is different. """ contents = lineEndToUse.join(lines) + lineEndToUse UpdateFile(path, contents)
[ "def", "UpdateFileFromLines", "(", "path", ",", "lines", ",", "lineEndToUse", ")", ":", "contents", "=", "lineEndToUse", ".", "join", "(", "lines", ")", "+", "lineEndToUse", "UpdateFile", "(", "path", ",", "contents", ")" ]
https://github.com/martinrotter/textosaurus/blob/4e2ad75abaf5b7e6a823766a2aa8a30f0c965cb8/src/libtextosaurus/3rd-party/scintilla/scripts/FileGenerator.py#L179-L183
pgRouting/osm2pgrouting
8491929fc4037d308f271e84d59bb96da3c28aa2
tools/cpplint.py
python
_FunctionState.Begin
(self, function_name)
Start analyzing function body. Args: function_name: The name of the function being tracked.
Start analyzing function body.
[ "Start", "analyzing", "function", "body", "." ]
def Begin(self, function_name): """Start analyzing function body. Args: function_name: The name of the function being tracked. """ self.in_a_function = True self.lines_in_function = 0 self.current_function = function_name
[ "def", "Begin", "(", "self", ",", "function_name", ")", ":", "self", ".", "in_a_function", "=", "True", "self", ".", "lines_in_function", "=", "0", "self", ".", "current_function", "=", "function_name" ]
https://github.com/pgRouting/osm2pgrouting/blob/8491929fc4037d308f271e84d59bb96da3c28aa2/tools/cpplint.py#L922-L930
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/build/waf-1.7.13/waflib/Logs.py
python
warn
(*k, **kw)
Wrap logging.warn
Wrap logging.warn
[ "Wrap", "logging", ".", "warn" ]
def warn(*k, **kw): """ Wrap logging.warn """ global log log.warn(*k, **kw)
[ "def", "warn", "(", "*", "k", ",", "*", "*", "kw", ")", ":", "global", "log", "log", ".", "warn", "(", "*", "k", ",", "*", "*", "kw", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/build/waf-1.7.13/waflib/Logs.py#L250-L255
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/RNN/rnn_quantizer/pytorch_binding/pytorch_nndct/quantization/quant_aware_training.py
python
QatProcessor._insert_quantizer
(self, model_topo, allow_reused_module)
Insert quantizer for quantizing input/output of a module. The quantization of weight/bias is handled by quantized module itself.
Insert quantizer for quantizing input/output of a module. The quantization of weight/bias is handled by quantized module itself.
[ "Insert", "quantizer", "for", "quantizing", "input", "/", "output", "of", "a", "module", ".", "The", "quantization", "of", "weight", "/", "bias", "is", "handled", "by", "quantized", "module", "itself", "." ]
def _insert_quantizer(self, model_topo, allow_reused_module): """Insert quantizer for quantizing input/output of a module. The quantization of weight/bias is handled by quantized module itself. """ quantized_modules = set() for node in model_topo.nodes: qconfig = node.qconfig if not qconfig: continue # Check if there are parameterized modules that have not been # transformed to the corresponding quantized version. if qconfig.weight or qconfig.bias: if not hasattr(node.module, 'is_quantized'): raise NotImplementedError( ('The quantization of {} not implemented ' 'yet. (Node name: {})').format(type(node.module), node.name)) if node.name in quantized_modules: continue logging.vlog( 3, 'Inserting quantizer for node {}: {}'.format(node.graph_node.name, qconfig)) quantized_modules.add(node.name) if qconfig.input: # Reserved support for multiple inputs, currently will always be 0. quantize_input(node.module, 0, qconfig.input) if qconfig.output: quantize_output(node.module, qconfig.output)
[ "def", "_insert_quantizer", "(", "self", ",", "model_topo", ",", "allow_reused_module", ")", ":", "quantized_modules", "=", "set", "(", ")", "for", "node", "in", "model_topo", ".", "nodes", ":", "qconfig", "=", "node", ".", "qconfig", "if", "not", "qconfig", ":", "continue", "# Check if there are parameterized modules that have not been", "# transformed to the corresponding quantized version.", "if", "qconfig", ".", "weight", "or", "qconfig", ".", "bias", ":", "if", "not", "hasattr", "(", "node", ".", "module", ",", "'is_quantized'", ")", ":", "raise", "NotImplementedError", "(", "(", "'The quantization of {} not implemented '", "'yet. (Node name: {})'", ")", ".", "format", "(", "type", "(", "node", ".", "module", ")", ",", "node", ".", "name", ")", ")", "if", "node", ".", "name", "in", "quantized_modules", ":", "continue", "logging", ".", "vlog", "(", "3", ",", "'Inserting quantizer for node {}: {}'", ".", "format", "(", "node", ".", "graph_node", ".", "name", ",", "qconfig", ")", ")", "quantized_modules", ".", "add", "(", "node", ".", "name", ")", "if", "qconfig", ".", "input", ":", "# Reserved support for multiple inputs, currently will always be 0.", "quantize_input", "(", "node", ".", "module", ",", "0", ",", "qconfig", ".", "input", ")", "if", "qconfig", ".", "output", ":", "quantize_output", "(", "node", ".", "module", ",", "qconfig", ".", "output", ")" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/RNN/rnn_quantizer/pytorch_binding/pytorch_nndct/quantization/quant_aware_training.py#L449-L481
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/oldnumeric/ma.py
python
MaskedArray.dot
(self, other)
return innerproduct(self, other)
s.dot(other) = innerproduct(s, other)
s.dot(other) = innerproduct(s, other)
[ "s", ".", "dot", "(", "other", ")", "=", "innerproduct", "(", "s", "other", ")" ]
def dot (self, other): "s.dot(other) = innerproduct(s, other)" return innerproduct(self, other)
[ "def", "dot", "(", "self", ",", "other", ")", ":", "return", "innerproduct", "(", "self", ",", "other", ")" ]
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/oldnumeric/ma.py#L1228-L1230
eclipse/sumo
7132a9b8b6eea734bdec38479026b4d8c4336d03
tools/simpla/_platoon.py
python
Platoon.size
(self)
return len(self._vehicles)
size() -> int Returns number of vehicles currently in the platoon
size() -> int
[ "size", "()", "-", ">", "int" ]
def size(self): '''size() -> int Returns number of vehicles currently in the platoon ''' return len(self._vehicles)
[ "def", "size", "(", "self", ")", ":", "return", "len", "(", "self", ".", "_vehicles", ")" ]
https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/simpla/_platoon.py#L115-L120
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_core.py
python
GBSpan.__eq__
(*args, **kwargs)
return _core_.GBSpan___eq__(*args, **kwargs)
__eq__(self, PyObject other) -> bool Compare wxGBSpan for equality.
__eq__(self, PyObject other) -> bool
[ "__eq__", "(", "self", "PyObject", "other", ")", "-", ">", "bool" ]
def __eq__(*args, **kwargs): """ __eq__(self, PyObject other) -> bool Compare wxGBSpan for equality. """ return _core_.GBSpan___eq__(*args, **kwargs)
[ "def", "__eq__", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "GBSpan___eq__", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L15668-L15674
assimp/assimp
97c7e084c2f7f8c9355ea42f73605890481bddc5
port/PyAssimp/scripts/fixed_pipeline_3d_viewer.py
python
GLRenderer.render
(self, filename=None, fullscreen = False, autofit = True, postprocess = None)
:param autofit: if true, scale the scene to fit the whole geometry in the viewport.
[]
def render(self, filename=None, fullscreen = False, autofit = True, postprocess = None): """ :param autofit: if true, scale the scene to fit the whole geometry in the viewport. """ # First initialize the openGL context glutInit(sys.argv) glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH) if not fullscreen: glutInitWindowSize(width, height) glutCreateWindow(name) else: glutGameModeString("1024x768") if glutGameModeGet(GLUT_GAME_MODE_POSSIBLE): glutEnterGameMode() else: print("Fullscreen mode not available!") sys.exit(1) self.load_model(filename, postprocess = postprocess) glClearColor(0.1,0.1,0.1,1.) #glShadeModel(GL_SMOOTH) glEnable(GL_LIGHTING) glEnable(GL_CULL_FACE) glEnable(GL_DEPTH_TEST) glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE) glEnable(GL_NORMALIZE) glEnable(GL_LIGHT0) glutDisplayFunc(self.display) glMatrixMode(GL_PROJECTION) glLoadIdentity() gluPerspective(35.0, width/float(height) , 0.10, 100.0) glMatrixMode(GL_MODELVIEW) self.set_default_camera() if autofit: # scale the whole asset to fit into our view frustum· self.fit_scene() glPushMatrix() glutKeyboardFunc(self.onkeypress) glutIgnoreKeyRepeat(1) glutMainLoop()
[ "def", "render", "(", "self", ",", "filename", "=", "None", ",", "fullscreen", "=", "False", ",", "autofit", "=", "True", ",", "postprocess", "=", "None", ")", ":", "# First initialize the openGL context", "glutInit", "(", "sys", ".", "argv", ")", "glutInitDisplayMode", "(", "GLUT_DOUBLE", "|", "GLUT_RGB", "|", "GLUT_DEPTH", ")", "if", "not", "fullscreen", ":", "glutInitWindowSize", "(", "width", ",", "height", ")", "glutCreateWindow", "(", "name", ")", "else", ":", "glutGameModeString", "(", "\"1024x768\"", ")", "if", "glutGameModeGet", "(", "GLUT_GAME_MODE_POSSIBLE", ")", ":", "glutEnterGameMode", "(", ")", "else", ":", "print", "(", "\"Fullscreen mode not available!\"", ")", "sys", ".", "exit", "(", "1", ")", "self", ".", "load_model", "(", "filename", ",", "postprocess", "=", "postprocess", ")", "glClearColor", "(", "0.1", ",", "0.1", ",", "0.1", ",", "1.", ")", "#glShadeModel(GL_SMOOTH)", "glEnable", "(", "GL_LIGHTING", ")", "glEnable", "(", "GL_CULL_FACE", ")", "glEnable", "(", "GL_DEPTH_TEST", ")", "glLightModeli", "(", "GL_LIGHT_MODEL_TWO_SIDE", ",", "GL_TRUE", ")", "glEnable", "(", "GL_NORMALIZE", ")", "glEnable", "(", "GL_LIGHT0", ")", "glutDisplayFunc", "(", "self", ".", "display", ")", "glMatrixMode", "(", "GL_PROJECTION", ")", "glLoadIdentity", "(", ")", "gluPerspective", "(", "35.0", ",", "width", "/", "float", "(", "height", ")", ",", "0.10", ",", "100.0", ")", "glMatrixMode", "(", "GL_MODELVIEW", ")", "self", ".", "set_default_camera", "(", ")", "if", "autofit", ":", "# scale the whole asset to fit into our view frustum·", "self", ".", "fit_scene", "(", ")", "glPushMatrix", "(", ")", "glutKeyboardFunc", "(", "self", ".", "onkeypress", ")", "glutIgnoreKeyRepeat", "(", "1", ")", "glutMainLoop", "(", ")" ]
https://github.com/assimp/assimp/blob/97c7e084c2f7f8c9355ea42f73605890481bddc5/port/PyAssimp/scripts/fixed_pipeline_3d_viewer.py#L308-L362
lyxok1/Tiny-DSOD
94d15450699bea0dd3720e75e2d273e476174fba
python/caffe/pycaffe.py
python
_Net_get_id_name
(func, field)
return get_id_name
Generic property that maps func to the layer names into an OrderedDict. Used for top_names and bottom_names. Parameters ---------- func: function id -> [id] field: implementation field name (cache) Returns ------ A one-parameter function that can be set as a property.
Generic property that maps func to the layer names into an OrderedDict.
[ "Generic", "property", "that", "maps", "func", "to", "the", "layer", "names", "into", "an", "OrderedDict", "." ]
def _Net_get_id_name(func, field): """ Generic property that maps func to the layer names into an OrderedDict. Used for top_names and bottom_names. Parameters ---------- func: function id -> [id] field: implementation field name (cache) Returns ------ A one-parameter function that can be set as a property. """ @property def get_id_name(self): if not hasattr(self, field): id_to_name = list(self.blobs) res = OrderedDict([(self._layer_names[i], [id_to_name[j] for j in func(self, i)]) for i in range(len(self.layers))]) setattr(self, field, res) return getattr(self, field) return get_id_name
[ "def", "_Net_get_id_name", "(", "func", ",", "field", ")", ":", "@", "property", "def", "get_id_name", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "field", ")", ":", "id_to_name", "=", "list", "(", "self", ".", "blobs", ")", "res", "=", "OrderedDict", "(", "[", "(", "self", ".", "_layer_names", "[", "i", "]", ",", "[", "id_to_name", "[", "j", "]", "for", "j", "in", "func", "(", "self", ",", "i", ")", "]", ")", "for", "i", "in", "range", "(", "len", "(", "self", ".", "layers", ")", ")", "]", ")", "setattr", "(", "self", ",", "field", ",", "res", ")", "return", "getattr", "(", "self", ",", "field", ")", "return", "get_id_name" ]
https://github.com/lyxok1/Tiny-DSOD/blob/94d15450699bea0dd3720e75e2d273e476174fba/python/caffe/pycaffe.py#L295-L319
InsightSoftwareConsortium/ITK
87acfce9a93d928311c38bc371b666b515b9f19d
Modules/ThirdParty/pygccxml/src/pygccxml/declarations/traits_impl_details.py
python
impl_details.find_value_type
(global_ns, value_type_str)
return None
implementation details
implementation details
[ "implementation", "details" ]
def find_value_type(global_ns, value_type_str): """implementation details""" if not value_type_str.startswith('::'): value_type_str = '::' + value_type_str found = global_ns.decls( name=value_type_str, function=lambda decl: not isinstance(decl, calldef.calldef_t), allow_empty=True) if not found: no_global_ns_value_type_str = value_type_str[2:] if no_global_ns_value_type_str in cpptypes.FUNDAMENTAL_TYPES: return cpptypes.FUNDAMENTAL_TYPES[no_global_ns_value_type_str] elif type_traits.is_std_string(value_type_str): string_ = global_ns.typedef('::std::string') return type_traits.remove_declarated(string_) elif type_traits.is_std_wstring(value_type_str): string_ = global_ns.typedef('::std::wstring') return type_traits.remove_declarated(string_) else: value_type_str = no_global_ns_value_type_str has_const = value_type_str.startswith('const ') if has_const: value_type_str = value_type_str[len('const '):] has_pointer = value_type_str.endswith('*') if has_pointer: value_type_str = value_type_str[:-1] found = None if has_const or has_pointer: found = impl_details.find_value_type( global_ns, value_type_str) if not found: return None else: if isinstance(found, class_declaration.class_types): return cpptypes.declarated_t(found) if has_const: return cpptypes.const_t(found) if has_pointer: return cpptypes.pointer_t(found) if len(found) == 1: return found[0] return None
[ "def", "find_value_type", "(", "global_ns", ",", "value_type_str", ")", ":", "if", "not", "value_type_str", ".", "startswith", "(", "'::'", ")", ":", "value_type_str", "=", "'::'", "+", "value_type_str", "found", "=", "global_ns", ".", "decls", "(", "name", "=", "value_type_str", ",", "function", "=", "lambda", "decl", ":", "not", "isinstance", "(", "decl", ",", "calldef", ".", "calldef_t", ")", ",", "allow_empty", "=", "True", ")", "if", "not", "found", ":", "no_global_ns_value_type_str", "=", "value_type_str", "[", "2", ":", "]", "if", "no_global_ns_value_type_str", "in", "cpptypes", ".", "FUNDAMENTAL_TYPES", ":", "return", "cpptypes", ".", "FUNDAMENTAL_TYPES", "[", "no_global_ns_value_type_str", "]", "elif", "type_traits", ".", "is_std_string", "(", "value_type_str", ")", ":", "string_", "=", "global_ns", ".", "typedef", "(", "'::std::string'", ")", "return", "type_traits", ".", "remove_declarated", "(", "string_", ")", "elif", "type_traits", ".", "is_std_wstring", "(", "value_type_str", ")", ":", "string_", "=", "global_ns", ".", "typedef", "(", "'::std::wstring'", ")", "return", "type_traits", ".", "remove_declarated", "(", "string_", ")", "else", ":", "value_type_str", "=", "no_global_ns_value_type_str", "has_const", "=", "value_type_str", ".", "startswith", "(", "'const '", ")", "if", "has_const", ":", "value_type_str", "=", "value_type_str", "[", "len", "(", "'const '", ")", ":", "]", "has_pointer", "=", "value_type_str", ".", "endswith", "(", "'*'", ")", "if", "has_pointer", ":", "value_type_str", "=", "value_type_str", "[", ":", "-", "1", "]", "found", "=", "None", "if", "has_const", "or", "has_pointer", ":", "found", "=", "impl_details", ".", "find_value_type", "(", "global_ns", ",", "value_type_str", ")", "if", "not", "found", ":", "return", "None", "else", ":", "if", "isinstance", "(", "found", ",", "class_declaration", ".", "class_types", ")", ":", "return", "cpptypes", ".", "declarated_t", "(", "found", ")", "if", "has_const", ":", "return", "cpptypes", ".", "const_t", "(", "found", ")", "if", "has_pointer", ":", "return", "cpptypes", ".", "pointer_t", "(", "found", ")", "if", "len", "(", "found", ")", "==", "1", ":", "return", "found", "[", "0", "]", "return", "None" ]
https://github.com/InsightSoftwareConsortium/ITK/blob/87acfce9a93d928311c38bc371b666b515b9f19d/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/traits_impl_details.py#L45-L88