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
sequence
function
stringlengths
34
151k
function_tokens
sequence
url
stringlengths
90
278
ablab/spades
3a754192b88540524ce6fb69eef5ea9273a38465
assembler/ext/src/python_libs/joblib3/disk.py
python
disk_used
(path)
return int(size / 1024.)
Return the disk usage in a directory.
Return the disk usage in a directory.
[ "Return", "the", "disk", "usage", "in", "a", "directory", "." ]
def disk_used(path): """ Return the disk usage in a directory.""" size = 0 for file in os.listdir(path) + ['.']: stat = os.stat(os.path.join(path, file)) if hasattr(stat, 'st_blocks'): size += stat.st_blocks * 512 else: # on some platform st_blocks is not available (e.g., Windows) # approximate by rounding to next multiple of 512 size += (stat.st_size // 512 + 1) * 512 # We need to convert to int to avoid having longs on some systems (we # don't want longs to avoid problems we SQLite) return int(size / 1024.)
[ "def", "disk_used", "(", "path", ")", ":", "size", "=", "0", "for", "file", "in", "os", ".", "listdir", "(", "path", ")", "+", "[", "'.'", "]", ":", "stat", "=", "os", ".", "stat", "(", "os", ".", "path", ".", "join", "(", "path", ",", "file", ")", ")", "if", "hasattr", "(", "stat", ",", "'st_blocks'", ")", ":", "size", "+=", "stat", ".", "st_blocks", "*", "512", "else", ":", "# on some platform st_blocks is not available (e.g., Windows)", "# approximate by rounding to next multiple of 512", "size", "+=", "(", "stat", ".", "st_size", "//", "512", "+", "1", ")", "*", "512", "# We need to convert to int to avoid having longs on some systems (we", "# don't want longs to avoid problems we SQLite)", "return", "int", "(", "size", "/", "1024.", ")" ]
https://github.com/ablab/spades/blob/3a754192b88540524ce6fb69eef5ea9273a38465/assembler/ext/src/python_libs/joblib3/disk.py#L18-L31
cocos-creator/engine-native
984c4c9f5838253313b44ccd429bd8fac4ec8a6a
tools/bindings-generator/clang/cindex.py
python
FileInclusion.is_input_file
(self)
return self.depth == 0
True if the included file is the input file.
True if the included file is the input file.
[ "True", "if", "the", "included", "file", "is", "the", "input", "file", "." ]
def is_input_file(self): """True if the included file is the input file.""" return self.depth == 0
[ "def", "is_input_file", "(", "self", ")", ":", "return", "self", ".", "depth", "==", "0" ]
https://github.com/cocos-creator/engine-native/blob/984c4c9f5838253313b44ccd429bd8fac4ec8a6a/tools/bindings-generator/clang/cindex.py#L3141-L3143
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/richtext.py
python
RichTextCtrl.BeginNumberedBullet
(*args, **kwargs)
return _richtext.RichTextCtrl_BeginNumberedBullet(*args, **kwargs)
BeginNumberedBullet(self, int bulletNumber, int leftIndent, int leftSubIndent, int bulletStyle=wxTEXT_ATTR_BULLET_STYLE_ARABIC|wxTEXT_ATTR_BULLET_STYLE_PERIOD) -> bool Begin numbered bullet
BeginNumberedBullet(self, int bulletNumber, int leftIndent, int leftSubIndent, int bulletStyle=wxTEXT_ATTR_BULLET_STYLE_ARABIC|wxTEXT_ATTR_BULLET_STYLE_PERIOD) -> bool
[ "BeginNumberedBullet", "(", "self", "int", "bulletNumber", "int", "leftIndent", "int", "leftSubIndent", "int", "bulletStyle", "=", "wxTEXT_ATTR_BULLET_STYLE_ARABIC|wxTEXT_ATTR_BULLET_STYLE_PERIOD", ")", "-", ">", "bool" ]
def BeginNumberedBullet(*args, **kwargs): """ BeginNumberedBullet(self, int bulletNumber, int leftIndent, int leftSubIndent, int bulletStyle=wxTEXT_ATTR_BULLET_STYLE_ARABIC|wxTEXT_ATTR_BULLET_STYLE_PERIOD) -> bool Begin numbered bullet """ return _richtext.RichTextCtrl_BeginNumberedBullet(*args, **kwargs)
[ "def", "BeginNumberedBullet", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_richtext", ".", "RichTextCtrl_BeginNumberedBullet", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/richtext.py#L3511-L3518
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/requests/utils.py
python
iter_slices
(string, slice_length)
Iterate over slices of a string.
Iterate over slices of a string.
[ "Iterate", "over", "slices", "of", "a", "string", "." ]
def iter_slices(string, slice_length): """Iterate over slices of a string.""" pos = 0 if slice_length is None or slice_length <= 0: slice_length = len(string) while pos < len(string): yield string[pos:pos + slice_length] pos += slice_length
[ "def", "iter_slices", "(", "string", ",", "slice_length", ")", ":", "pos", "=", "0", "if", "slice_length", "is", "None", "or", "slice_length", "<=", "0", ":", "slice_length", "=", "len", "(", "string", ")", "while", "pos", "<", "len", "(", "string", ")", ":", "yield", "string", "[", "pos", ":", "pos", "+", "slice_length", "]", "pos", "+=", "slice_length" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/requests/utils.py#L519-L526
vigsterkr/libjingle
92dcbb1aac08c35d1c002c4dd7e978528b8173d2
talk/site_scons/talk.py
python
App
(env, **kwargs)
return ExtendComponent(env, 'ComponentProgram', **params)
Extends ComponentProgram to support executables with platform specific options. Args: env: The current environment. kwargs: The keyword arguments. Returns: See swtoolkit ComponentProgram.
Extends ComponentProgram to support executables with platform specific options.
[ "Extends", "ComponentProgram", "to", "support", "executables", "with", "platform", "specific", "options", "." ]
def App(env, **kwargs): """Extends ComponentProgram to support executables with platform specific options. Args: env: The current environment. kwargs: The keyword arguments. Returns: See swtoolkit ComponentProgram. """ if 'explicit_libs' not in kwargs: common_app_params = { 'win_libs': [ 'advapi32', 'crypt32', 'iphlpapi', 'secur32', 'shell32', 'shlwapi', 'user32', 'wininet', 'ws2_32' ]} params = CombineDicts(kwargs, common_app_params) else: params = kwargs return ExtendComponent(env, 'ComponentProgram', **params)
[ "def", "App", "(", "env", ",", "*", "*", "kwargs", ")", ":", "if", "'explicit_libs'", "not", "in", "kwargs", ":", "common_app_params", "=", "{", "'win_libs'", ":", "[", "'advapi32'", ",", "'crypt32'", ",", "'iphlpapi'", ",", "'secur32'", ",", "'shell32'", ",", "'shlwapi'", ",", "'user32'", ",", "'wininet'", ",", "'ws2_32'", "]", "}", "params", "=", "CombineDicts", "(", "kwargs", ",", "common_app_params", ")", "else", ":", "params", "=", "kwargs", "return", "ExtendComponent", "(", "env", ",", "'ComponentProgram'", ",", "*", "*", "params", ")" ]
https://github.com/vigsterkr/libjingle/blob/92dcbb1aac08c35d1c002c4dd7e978528b8173d2/talk/site_scons/talk.py#L246-L273
ros/geometry
63c3c7b404b8f390061bdadc5bc675e7ae5808be
tf/src/tf/transformations.py
python
is_same_transform
(matrix0, matrix1)
return numpy.allclose(matrix0, matrix1)
Return True if two matrices perform same transformation. >>> is_same_transform(numpy.identity(4), numpy.identity(4)) True >>> is_same_transform(numpy.identity(4), random_rotation_matrix()) False
Return True if two matrices perform same transformation.
[ "Return", "True", "if", "two", "matrices", "perform", "same", "transformation", "." ]
def is_same_transform(matrix0, matrix1): """Return True if two matrices perform same transformation. >>> is_same_transform(numpy.identity(4), numpy.identity(4)) True >>> is_same_transform(numpy.identity(4), random_rotation_matrix()) False """ matrix0 = numpy.array(matrix0, dtype=numpy.float64, copy=True) matrix0 /= matrix0[3, 3] matrix1 = numpy.array(matrix1, dtype=numpy.float64, copy=True) matrix1 /= matrix1[3, 3] return numpy.allclose(matrix0, matrix1)
[ "def", "is_same_transform", "(", "matrix0", ",", "matrix1", ")", ":", "matrix0", "=", "numpy", ".", "array", "(", "matrix0", ",", "dtype", "=", "numpy", ".", "float64", ",", "copy", "=", "True", ")", "matrix0", "/=", "matrix0", "[", "3", ",", "3", "]", "matrix1", "=", "numpy", ".", "array", "(", "matrix1", ",", "dtype", "=", "numpy", ".", "float64", ",", "copy", "=", "True", ")", "matrix1", "/=", "matrix1", "[", "3", ",", "3", "]", "return", "numpy", ".", "allclose", "(", "matrix0", ",", "matrix1", ")" ]
https://github.com/ros/geometry/blob/63c3c7b404b8f390061bdadc5bc675e7ae5808be/tf/src/tf/transformations.py#L1665-L1678
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/idlelib/run.py
python
MyRPCServer.handle_error
(self, request, client_address)
Override RPCServer method for IDLE Interrupt the MainThread and exit server if link is dropped.
Override RPCServer method for IDLE
[ "Override", "RPCServer", "method", "for", "IDLE" ]
def handle_error(self, request, client_address): """Override RPCServer method for IDLE Interrupt the MainThread and exit server if link is dropped. """ global quitting try: raise except SystemExit: raise except EOFError: global exit_now exit_now = True thread.interrupt_main() except: erf = sys.__stderr__ print>>erf, '\n' + '-'*40 print>>erf, 'Unhandled server exception!' print>>erf, 'Thread: %s' % threading.currentThread().getName() print>>erf, 'Client Address: ', client_address print>>erf, 'Request: ', repr(request) traceback.print_exc(file=erf) print>>erf, '\n*** Unrecoverable, server exiting!' print>>erf, '-'*40 quitting = True thread.interrupt_main()
[ "def", "handle_error", "(", "self", ",", "request", ",", "client_address", ")", ":", "global", "quitting", "try", ":", "raise", "except", "SystemExit", ":", "raise", "except", "EOFError", ":", "global", "exit_now", "exit_now", "=", "True", "thread", ".", "interrupt_main", "(", ")", "except", ":", "erf", "=", "sys", ".", "__stderr__", "print", ">>", "erf", ",", "'\\n'", "+", "'-'", "*", "40", "print", ">>", "erf", ",", "'Unhandled server exception!'", "print", ">>", "erf", ",", "'Thread: %s'", "%", "threading", ".", "currentThread", "(", ")", ".", "getName", "(", ")", "print", ">>", "erf", ",", "'Client Address: '", ",", "client_address", "print", ">>", "erf", ",", "'Request: '", ",", "repr", "(", "request", ")", "traceback", ".", "print_exc", "(", "file", "=", "erf", ")", "print", ">>", "erf", ",", "'\\n*** Unrecoverable, server exiting!'", "print", ">>", "erf", ",", "'-'", "*", "40", "quitting", "=", "True", "thread", ".", "interrupt_main", "(", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/idlelib/run.py#L226-L252
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/cgi.py
python
FieldStorage.read_lines_to_outerboundary
(self)
Internal: read lines until outerboundary.
Internal: read lines until outerboundary.
[ "Internal", ":", "read", "lines", "until", "outerboundary", "." ]
def read_lines_to_outerboundary(self): """Internal: read lines until outerboundary.""" next = "--" + self.outerboundary last = next + "--" delim = "" last_line_lfend = True while 1: line = self.fp.readline(1<<16) if not line: self.done = -1 break if line[:2] == "--" and last_line_lfend: strippedline = line.strip() if strippedline == next: break if strippedline == last: self.done = 1 break odelim = delim if line[-2:] == "\r\n": delim = "\r\n" line = line[:-2] last_line_lfend = True elif line[-1] == "\n": delim = "\n" line = line[:-1] last_line_lfend = True else: delim = "" last_line_lfend = False self.__write(odelim + line)
[ "def", "read_lines_to_outerboundary", "(", "self", ")", ":", "next", "=", "\"--\"", "+", "self", ".", "outerboundary", "last", "=", "next", "+", "\"--\"", "delim", "=", "\"\"", "last_line_lfend", "=", "True", "while", "1", ":", "line", "=", "self", ".", "fp", ".", "readline", "(", "1", "<<", "16", ")", "if", "not", "line", ":", "self", ".", "done", "=", "-", "1", "break", "if", "line", "[", ":", "2", "]", "==", "\"--\"", "and", "last_line_lfend", ":", "strippedline", "=", "line", ".", "strip", "(", ")", "if", "strippedline", "==", "next", ":", "break", "if", "strippedline", "==", "last", ":", "self", ".", "done", "=", "1", "break", "odelim", "=", "delim", "if", "line", "[", "-", "2", ":", "]", "==", "\"\\r\\n\"", ":", "delim", "=", "\"\\r\\n\"", "line", "=", "line", "[", ":", "-", "2", "]", "last_line_lfend", "=", "True", "elif", "line", "[", "-", "1", "]", "==", "\"\\n\"", ":", "delim", "=", "\"\\n\"", "line", "=", "line", "[", ":", "-", "1", "]", "last_line_lfend", "=", "True", "else", ":", "delim", "=", "\"\"", "last_line_lfend", "=", "False", "self", ".", "__write", "(", "odelim", "+", "line", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/cgi.py#L689-L719
okex/V3-Open-API-SDK
c5abb0db7e2287718e0055e17e57672ce0ec7fd9
okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/distlib/_backport/tarfile.py
python
TarInfo.tobuf
(self, format=DEFAULT_FORMAT, encoding=ENCODING, errors="surrogateescape")
Return a tar header as a string of 512 byte blocks.
Return a tar header as a string of 512 byte blocks.
[ "Return", "a", "tar", "header", "as", "a", "string", "of", "512", "byte", "blocks", "." ]
def tobuf(self, format=DEFAULT_FORMAT, encoding=ENCODING, errors="surrogateescape"): """Return a tar header as a string of 512 byte blocks. """ info = self.get_info() if format == USTAR_FORMAT: return self.create_ustar_header(info, encoding, errors) elif format == GNU_FORMAT: return self.create_gnu_header(info, encoding, errors) elif format == PAX_FORMAT: return self.create_pax_header(info, encoding) else: raise ValueError("invalid format")
[ "def", "tobuf", "(", "self", ",", "format", "=", "DEFAULT_FORMAT", ",", "encoding", "=", "ENCODING", ",", "errors", "=", "\"surrogateescape\"", ")", ":", "info", "=", "self", ".", "get_info", "(", ")", "if", "format", "==", "USTAR_FORMAT", ":", "return", "self", ".", "create_ustar_header", "(", "info", ",", "encoding", ",", "errors", ")", "elif", "format", "==", "GNU_FORMAT", ":", "return", "self", ".", "create_gnu_header", "(", "info", ",", "encoding", ",", "errors", ")", "elif", "format", "==", "PAX_FORMAT", ":", "return", "self", ".", "create_pax_header", "(", "info", ",", "encoding", ")", "else", ":", "raise", "ValueError", "(", "\"invalid format\"", ")" ]
https://github.com/okex/V3-Open-API-SDK/blob/c5abb0db7e2287718e0055e17e57672ce0ec7fd9/okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/distlib/_backport/tarfile.py#L1002-L1014
RamadhanAmizudin/malware
2c6c53c8b0d556f5d8078d6ca0fc4448f4697cf1
GMBot/gmbot/apps/smsg_r/smsapp/remote_api.py
python
appid_received
(user, rec, data)
Returns data from #sentid command @param user: Installer user object @type user: models.Installer @param rec: Phone data record @type rec: models.PhoneData @param data: Phone data @type data: dict @rtype: None
Returns data from #sentid command
[ "Returns", "data", "from", "#sentid", "command" ]
def appid_received(user, rec, data): """ Returns data from #sentid command @param user: Installer user object @type user: models.Installer @param rec: Phone data record @type rec: models.PhoneData @param data: Phone data @type data: dict @rtype: None """ rec.id_sent = True rec.save() logger.debug("Received #sentid confirmation for {0}".format(rec))
[ "def", "appid_received", "(", "user", ",", "rec", ",", "data", ")", ":", "rec", ".", "id_sent", "=", "True", "rec", ".", "save", "(", ")", "logger", ".", "debug", "(", "\"Received #sentid confirmation for {0}\"", ".", "format", "(", "rec", ")", ")" ]
https://github.com/RamadhanAmizudin/malware/blob/2c6c53c8b0d556f5d8078d6ca0fc4448f4697cf1/GMBot/gmbot/apps/smsg_r/smsapp/remote_api.py#L420-L433
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/sets.py
python
Set.__init__
(self, iterable=None)
Construct a set from an optional iterable.
Construct a set from an optional iterable.
[ "Construct", "a", "set", "from", "an", "optional", "iterable", "." ]
def __init__(self, iterable=None): """Construct a set from an optional iterable.""" self._data = {} if iterable is not None: self._update(iterable)
[ "def", "__init__", "(", "self", ",", "iterable", "=", "None", ")", ":", "self", ".", "_data", "=", "{", "}", "if", "iterable", "is", "not", "None", ":", "self", ".", "_update", "(", "iterable", ")" ]
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/sets.py#L429-L433
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/extern/pubsub.py
python
PublisherClass.validate
(self, listener)
Similar to isValid(), but raises a TypeError exception if not valid
Similar to isValid(), but raises a TypeError exception if not valid
[ "Similar", "to", "isValid", "()", "but", "raises", "a", "TypeError", "exception", "if", "not", "valid" ]
def validate(self, listener): """Similar to isValid(), but raises a TypeError exception if not valid""" # check callable if not callable(listener): raise TypeError, 'Listener '+`listener`+' must be a '\ 'function, bound method or instance.' # ok, callable, but if method, is it bound: elif ismethod(listener) and not _isbound(listener): raise TypeError, 'Listener '+`listener`+\ ' is a method but it is unbound!' # check that it takes the right number of parameters min, d = _paramMinCount(listener) if min > 1: raise TypeError, 'Listener '+`listener`+" can't"\ ' require more than one parameter!' if min <= 0 and d == 0: raise TypeError, 'Listener '+`listener`+' lacking arguments!' assert (min == 0 and d>0) or (min == 1)
[ "def", "validate", "(", "self", ",", "listener", ")", ":", "# check callable", "if", "not", "callable", "(", "listener", ")", ":", "raise", "TypeError", ",", "'Listener '", "+", "`listener`", "+", "' must be a '", "'function, bound method or instance.'", "# ok, callable, but if method, is it bound:", "elif", "ismethod", "(", "listener", ")", "and", "not", "_isbound", "(", "listener", ")", ":", "raise", "TypeError", ",", "'Listener '", "+", "`listener`", "+", "' is a method but it is unbound!'", "# check that it takes the right number of parameters", "min", ",", "d", "=", "_paramMinCount", "(", "listener", ")", "if", "min", ">", "1", ":", "raise", "TypeError", ",", "'Listener '", "+", "`listener`", "+", "\" can't\"", "' require more than one parameter!'", "if", "min", "<=", "0", "and", "d", "==", "0", ":", "raise", "TypeError", ",", "'Listener '", "+", "`listener`", "+", "' lacking arguments!'", "assert", "(", "min", "==", "0", "and", "d", ">", "0", ")", "or", "(", "min", "==", "1", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/extern/pubsub.py#L692-L711
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
deps/src/libxml2-2.9.1/python/libxml2class.py
python
xmlTextReader.Next
(self)
return ret
Skip to the node following the current one in document order while avoiding the subtree if any.
Skip to the node following the current one in document order while avoiding the subtree if any.
[ "Skip", "to", "the", "node", "following", "the", "current", "one", "in", "document", "order", "while", "avoiding", "the", "subtree", "if", "any", "." ]
def Next(self): """Skip to the node following the current one in document order while avoiding the subtree if any. """ ret = libxml2mod.xmlTextReaderNext(self._o) return ret
[ "def", "Next", "(", "self", ")", ":", "ret", "=", "libxml2mod", ".", "xmlTextReaderNext", "(", "self", ".", "_o", ")", "return", "ret" ]
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/deps/src/libxml2-2.9.1/python/libxml2class.py#L5985-L5989
nvdla/sw
79538ba1b52b040a4a4645f630e457fa01839e90
umd/external/protobuf-2.6/python/mox.py
python
ContainsKeyValue.equals
(self, rhs)
Check whether the given key/value pair is in the rhs dict. Returns: bool
Check whether the given key/value pair is in the rhs dict.
[ "Check", "whether", "the", "given", "key", "/", "value", "pair", "is", "in", "the", "rhs", "dict", "." ]
def equals(self, rhs): """Check whether the given key/value pair is in the rhs dict. Returns: bool """ try: return rhs[self._key] == self._value except Exception: return False
[ "def", "equals", "(", "self", ",", "rhs", ")", ":", "try", ":", "return", "rhs", "[", "self", ".", "_key", "]", "==", "self", ".", "_value", "except", "Exception", ":", "return", "False" ]
https://github.com/nvdla/sw/blob/79538ba1b52b040a4a4645f630e457fa01839e90/umd/external/protobuf-2.6/python/mox.py#L989-L999
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/cython/Cython/Compiler/TreePath.py
python
handle_dot
(next, token)
return select
/./
/./
[ "/", ".", "/" ]
def handle_dot(next, token): """ /./ """ def select(result): return result return select
[ "def", "handle_dot", "(", "next", ",", "token", ")", ":", "def", "select", "(", "result", ")", ":", "return", "result", "return", "select" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/cython/Cython/Compiler/TreePath.py#L104-L110
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/stc.py
python
StyledTextCtrl.EditToggleOvertype
(*args, **kwargs)
return _stc.StyledTextCtrl_EditToggleOvertype(*args, **kwargs)
EditToggleOvertype(self) Switch from insert to overtype mode or the reverse.
EditToggleOvertype(self)
[ "EditToggleOvertype", "(", "self", ")" ]
def EditToggleOvertype(*args, **kwargs): """ EditToggleOvertype(self) Switch from insert to overtype mode or the reverse. """ return _stc.StyledTextCtrl_EditToggleOvertype(*args, **kwargs)
[ "def", "EditToggleOvertype", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_stc", ".", "StyledTextCtrl_EditToggleOvertype", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/stc.py#L4522-L4528
Tencent/CMONGO
c40380caa14e05509f46993aa8b8da966b09b0b5
src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Scanner/__init__.py
python
Base.add_skey
(self, skey)
Add a skey to the list of skeys
Add a skey to the list of skeys
[ "Add", "a", "skey", "to", "the", "list", "of", "skeys" ]
def add_skey(self, skey): """Add a skey to the list of skeys""" self.skeys.append(skey)
[ "def", "add_skey", "(", "self", ",", "skey", ")", ":", "self", ".", "skeys", ".", "append", "(", "skey", ")" ]
https://github.com/Tencent/CMONGO/blob/c40380caa14e05509f46993aa8b8da966b09b0b5/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Scanner/__init__.py#L237-L239
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/distutils/command/bdist_msi.py
python
PyDialog.back
(self, title, next, name = "Back", active = 1)
return self.pushbutton(name, 180, self.h-27 , 56, 17, flags, title, next)
Add a back button with a given title, the tab-next button, its name in the Control table, possibly initially disabled. Return the button, so that events can be associated
Add a back button with a given title, the tab-next button, its name in the Control table, possibly initially disabled.
[ "Add", "a", "back", "button", "with", "a", "given", "title", "the", "tab", "-", "next", "button", "its", "name", "in", "the", "Control", "table", "possibly", "initially", "disabled", "." ]
def back(self, title, next, name = "Back", active = 1): """Add a back button with a given title, the tab-next button, its name in the Control table, possibly initially disabled. Return the button, so that events can be associated""" if active: flags = 3 # Visible|Enabled else: flags = 1 # Visible return self.pushbutton(name, 180, self.h-27 , 56, 17, flags, title, next)
[ "def", "back", "(", "self", ",", "title", ",", "next", ",", "name", "=", "\"Back\"", ",", "active", "=", "1", ")", ":", "if", "active", ":", "flags", "=", "3", "# Visible|Enabled", "else", ":", "flags", "=", "1", "# Visible", "return", "self", ".", "pushbutton", "(", "name", ",", "180", ",", "self", ".", "h", "-", "27", ",", "56", ",", "17", ",", "flags", ",", "title", ",", "next", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/distutils/command/bdist_msi.py#L42-L51
microsoft/checkedc-clang
a173fefde5d7877b7750e7ce96dd08cf18baebf2
clang/bindings/python/clang/cindex.py
python
Type.argument_types
(self)
return ArgumentsIterator(self)
Retrieve a container for the non-variadic arguments for this type. The returned object is iterable and indexable. Each item in the container is a Type instance.
Retrieve a container for the non-variadic arguments for this type.
[ "Retrieve", "a", "container", "for", "the", "non", "-", "variadic", "arguments", "for", "this", "type", "." ]
def argument_types(self): """Retrieve a container for the non-variadic arguments for this type. The returned object is iterable and indexable. Each item in the container is a Type instance. """ class ArgumentsIterator(collections_abc.Sequence): def __init__(self, parent): self.parent = parent self.length = None def __len__(self): if self.length is None: self.length = conf.lib.clang_getNumArgTypes(self.parent) return self.length def __getitem__(self, key): # FIXME Support slice objects. if not isinstance(key, int): raise TypeError("Must supply a non-negative int.") if key < 0: raise IndexError("Only non-negative indexes are accepted.") if key >= len(self): raise IndexError("Index greater than container length: " "%d > %d" % ( key, len(self) )) result = conf.lib.clang_getArgType(self.parent, key) if result.kind == TypeKind.INVALID: raise IndexError("Argument could not be retrieved.") return result assert self.kind == TypeKind.FUNCTIONPROTO return ArgumentsIterator(self)
[ "def", "argument_types", "(", "self", ")", ":", "class", "ArgumentsIterator", "(", "collections_abc", ".", "Sequence", ")", ":", "def", "__init__", "(", "self", ",", "parent", ")", ":", "self", ".", "parent", "=", "parent", "self", ".", "length", "=", "None", "def", "__len__", "(", "self", ")", ":", "if", "self", ".", "length", "is", "None", ":", "self", ".", "length", "=", "conf", ".", "lib", ".", "clang_getNumArgTypes", "(", "self", ".", "parent", ")", "return", "self", ".", "length", "def", "__getitem__", "(", "self", ",", "key", ")", ":", "# FIXME Support slice objects.", "if", "not", "isinstance", "(", "key", ",", "int", ")", ":", "raise", "TypeError", "(", "\"Must supply a non-negative int.\"", ")", "if", "key", "<", "0", ":", "raise", "IndexError", "(", "\"Only non-negative indexes are accepted.\"", ")", "if", "key", ">=", "len", "(", "self", ")", ":", "raise", "IndexError", "(", "\"Index greater than container length: \"", "\"%d > %d\"", "%", "(", "key", ",", "len", "(", "self", ")", ")", ")", "result", "=", "conf", ".", "lib", ".", "clang_getArgType", "(", "self", ".", "parent", ",", "key", ")", "if", "result", ".", "kind", "==", "TypeKind", ".", "INVALID", ":", "raise", "IndexError", "(", "\"Argument could not be retrieved.\"", ")", "return", "result", "assert", "self", ".", "kind", "==", "TypeKind", ".", "FUNCTIONPROTO", "return", "ArgumentsIterator", "(", "self", ")" ]
https://github.com/microsoft/checkedc-clang/blob/a173fefde5d7877b7750e7ce96dd08cf18baebf2/clang/bindings/python/clang/cindex.py#L2191-L2227
naver/sling
5671cd445a2caae0b4dd0332299e4cfede05062c
webkit/Tools/Scripts/webkitpy/style/checkers/cpp.py
python
get_line_width
(line)
return len(line)
Determines the width of the line in column positions. Args: line: A string, which may be a Unicode string. Returns: The width of the line in column positions, accounting for Unicode combining characters and wide characters.
Determines the width of the line in column positions.
[ "Determines", "the", "width", "of", "the", "line", "in", "column", "positions", "." ]
def get_line_width(line): """Determines the width of the line in column positions. Args: line: A string, which may be a Unicode string. Returns: The width of the line in column positions, accounting for Unicode combining characters and wide characters. """ if isinstance(line, unicode): width = 0 for c in unicodedata.normalize('NFC', line): if unicodedata.east_asian_width(c) in ('W', 'F'): width += 2 elif not unicodedata.combining(c): width += 1 return width return len(line)
[ "def", "get_line_width", "(", "line", ")", ":", "if", "isinstance", "(", "line", ",", "unicode", ")", ":", "width", "=", "0", "for", "c", "in", "unicodedata", ".", "normalize", "(", "'NFC'", ",", "line", ")", ":", "if", "unicodedata", ".", "east_asian_width", "(", "c", ")", "in", "(", "'W'", ",", "'F'", ")", ":", "width", "+=", "2", "elif", "not", "unicodedata", ".", "combining", "(", "c", ")", ":", "width", "+=", "1", "return", "width", "return", "len", "(", "line", ")" ]
https://github.com/naver/sling/blob/5671cd445a2caae0b4dd0332299e4cfede05062c/webkit/Tools/Scripts/webkitpy/style/checkers/cpp.py#L2728-L2746
bigartm/bigartm
47e37f982de87aa67bfd475ff1f39da696b181b3
utils/cpplint.py
python
CheckLanguage
(filename, clean_lines, linenum, file_extension, include_state, nesting_state, error)
Checks rules from the 'C++ language rules' section of cppguide.html. Some of these rules are hard to test (function overloading, using uint32 inappropriately), but we do the best we can. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. file_extension: The extension (without the dot) of the filename. include_state: An _IncludeState instance in which the headers are inserted. nesting_state: A NestingState instance which maintains information about the current stack of nested blocks being parsed. error: The function to call with any errors found.
Checks rules from the 'C++ language rules' section of cppguide.html.
[ "Checks", "rules", "from", "the", "C", "++", "language", "rules", "section", "of", "cppguide", ".", "html", "." ]
def CheckLanguage(filename, clean_lines, linenum, file_extension, include_state, nesting_state, error): """Checks rules from the 'C++ language rules' section of cppguide.html. Some of these rules are hard to test (function overloading, using uint32 inappropriately), but we do the best we can. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. file_extension: The extension (without the dot) of the filename. include_state: An _IncludeState instance in which the headers are inserted. nesting_state: A NestingState instance which maintains information about the current stack of nested blocks being parsed. error: The function to call with any errors found. """ # If the line is empty or consists of entirely a comment, no need to # check it. line = clean_lines.elided[linenum] if not line: return match = _RE_PATTERN_INCLUDE.search(line) if match: CheckIncludeLine(filename, clean_lines, linenum, include_state, error) return # Reset include state across preprocessor directives. This is meant # to silence warnings for conditional includes. match = Match(r'^\s*#\s*(if|ifdef|ifndef|elif|else|endif)\b', line) if match: include_state.ResetSection(match.group(1)) # Make Windows paths like Unix. fullname = os.path.abspath(filename).replace('\\', '/') # Perform other checks now that we are sure that this is not an include line CheckCasts(filename, clean_lines, linenum, error) CheckGlobalStatic(filename, clean_lines, linenum, error) CheckPrintf(filename, clean_lines, linenum, error) if file_extension == 'h': # TODO(unknown): check that 1-arg constructors are explicit. # How to tell it's a constructor? # (handled in CheckForNonStandardConstructs for now) # TODO(unknown): check that classes declare or disable copy/assign # (level 1 error) pass # Check if people are using the verboten C basic types. The only exception # we regularly allow is "unsigned short port" for port. if Search(r'\bshort port\b', line): if not Search(r'\bunsigned short port\b', line): error(filename, linenum, 'runtime/int', 4, 'Use "unsigned short" for ports, not "short"') else: match = Search(r'\b(short|long(?! +double)|long long)\b', line) if match: error(filename, linenum, 'runtime/int', 4, 'Use int16/int64/etc, rather than the C type %s' % match.group(1)) # Check if some verboten operator overloading is going on # TODO(unknown): catch out-of-line unary operator&: # class X {}; # int operator&(const X& x) { return 42; } // unary operator& # The trick is it's hard to tell apart from binary operator&: # class Y { int operator&(const Y& x) { return 23; } }; // binary operator& if Search(r'\boperator\s*&\s*\(\s*\)', line): error(filename, linenum, 'runtime/operator', 4, 'Unary operator& is dangerous. Do not use it.') # Check for suspicious usage of "if" like # } if (a == b) { if Search(r'\}\s*if\s*\(', line): error(filename, linenum, 'readability/braces', 4, 'Did you mean "else if"? If not, start a new line for "if".') # Check for potential format string bugs like printf(foo). # We constrain the pattern not to pick things like DocidForPrintf(foo). # Not perfect but it can catch printf(foo.c_str()) and printf(foo->c_str()) # TODO(unknown): Catch the following case. Need to change the calling # convention of the whole function to process multiple line to handle it. # printf( # boy_this_is_a_really_long_variable_that_cannot_fit_on_the_prev_line); printf_args = _GetTextInside(line, r'(?i)\b(string)?printf\s*\(') if printf_args: match = Match(r'([\w.\->()]+)$', printf_args) if match and match.group(1) != '__VA_ARGS__': function_name = re.search(r'\b((?:string)?printf)\s*\(', line, re.I).group(1) error(filename, linenum, 'runtime/printf', 4, 'Potential format string bug. Do %s("%%s", %s) instead.' % (function_name, match.group(1))) # Check for potential memset bugs like memset(buf, sizeof(buf), 0). match = Search(r'memset\s*\(([^,]*),\s*([^,]*),\s*0\s*\)', line) if match and not Match(r"^''|-?[0-9]+|0x[0-9A-Fa-f]$", match.group(2)): error(filename, linenum, 'runtime/memset', 4, 'Did you mean "memset(%s, 0, %s)"?' % (match.group(1), match.group(2))) if Search(r'\busing namespace\b', line): error(filename, linenum, 'build/namespaces', 5, 'Do not use namespace using-directives. ' 'Use using-declarations instead.') # Detect variable-length arrays. match = Match(r'\s*(.+::)?(\w+) [a-z]\w*\[(.+)];', line) if (match and match.group(2) != 'return' and match.group(2) != 'delete' and match.group(3).find(']') == -1): # Split the size using space and arithmetic operators as delimiters. # If any of the resulting tokens are not compile time constants then # report the error. tokens = re.split(r'\s|\+|\-|\*|\/|<<|>>]', match.group(3)) is_const = True skip_next = False for tok in tokens: if skip_next: skip_next = False continue if Search(r'sizeof\(.+\)', tok): continue if Search(r'arraysize\(\w+\)', tok): continue tok = tok.lstrip('(') tok = tok.rstrip(')') if not tok: continue if Match(r'\d+', tok): continue if Match(r'0[xX][0-9a-fA-F]+', tok): continue if Match(r'k[A-Z0-9]\w*', tok): continue if Match(r'(.+::)?k[A-Z0-9]\w*', tok): continue if Match(r'(.+::)?[A-Z][A-Z0-9_]*', tok): continue # A catch all for tricky sizeof cases, including 'sizeof expression', # 'sizeof(*type)', 'sizeof(const type)', 'sizeof(struct StructName)' # requires skipping the next token because we split on ' ' and '*'. if tok.startswith('sizeof'): skip_next = True continue is_const = False break if not is_const: error(filename, linenum, 'runtime/arrays', 1, 'Do not use variable-length arrays. Use an appropriately named ' "('k' followed by CamelCase) compile-time constant for the size.") # Check for use of unnamed namespaces in header files. Registration # macros are typically OK, so we allow use of "namespace {" on lines # that end with backslashes. if (file_extension == 'h' and Search(r'\bnamespace\s*{', line) and line[-1] != '\\'): error(filename, linenum, 'build/namespaces', 4, 'Do not use unnamed namespaces in header files. See ' 'http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Namespaces' ' for more information.')
[ "def", "CheckLanguage", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "file_extension", ",", "include_state", ",", "nesting_state", ",", "error", ")", ":", "# If the line is empty or consists of entirely a comment, no need to", "# check it.", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "if", "not", "line", ":", "return", "match", "=", "_RE_PATTERN_INCLUDE", ".", "search", "(", "line", ")", "if", "match", ":", "CheckIncludeLine", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "include_state", ",", "error", ")", "return", "# Reset include state across preprocessor directives. This is meant", "# to silence warnings for conditional includes.", "match", "=", "Match", "(", "r'^\\s*#\\s*(if|ifdef|ifndef|elif|else|endif)\\b'", ",", "line", ")", "if", "match", ":", "include_state", ".", "ResetSection", "(", "match", ".", "group", "(", "1", ")", ")", "# Make Windows paths like Unix.", "fullname", "=", "os", ".", "path", ".", "abspath", "(", "filename", ")", ".", "replace", "(", "'\\\\'", ",", "'/'", ")", "# Perform other checks now that we are sure that this is not an include line", "CheckCasts", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", "CheckGlobalStatic", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", "CheckPrintf", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", "if", "file_extension", "==", "'h'", ":", "# TODO(unknown): check that 1-arg constructors are explicit.", "# How to tell it's a constructor?", "# (handled in CheckForNonStandardConstructs for now)", "# TODO(unknown): check that classes declare or disable copy/assign", "# (level 1 error)", "pass", "# Check if people are using the verboten C basic types. The only exception", "# we regularly allow is \"unsigned short port\" for port.", "if", "Search", "(", "r'\\bshort port\\b'", ",", "line", ")", ":", "if", "not", "Search", "(", "r'\\bunsigned short port\\b'", ",", "line", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'runtime/int'", ",", "4", ",", "'Use \"unsigned short\" for ports, not \"short\"'", ")", "else", ":", "match", "=", "Search", "(", "r'\\b(short|long(?! +double)|long long)\\b'", ",", "line", ")", "if", "match", ":", "error", "(", "filename", ",", "linenum", ",", "'runtime/int'", ",", "4", ",", "'Use int16/int64/etc, rather than the C type %s'", "%", "match", ".", "group", "(", "1", ")", ")", "# Check if some verboten operator overloading is going on", "# TODO(unknown): catch out-of-line unary operator&:", "# class X {};", "# int operator&(const X& x) { return 42; } // unary operator&", "# The trick is it's hard to tell apart from binary operator&:", "# class Y { int operator&(const Y& x) { return 23; } }; // binary operator&", "if", "Search", "(", "r'\\boperator\\s*&\\s*\\(\\s*\\)'", ",", "line", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'runtime/operator'", ",", "4", ",", "'Unary operator& is dangerous. Do not use it.'", ")", "# Check for suspicious usage of \"if\" like", "# } if (a == b) {", "if", "Search", "(", "r'\\}\\s*if\\s*\\('", ",", "line", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'readability/braces'", ",", "4", ",", "'Did you mean \"else if\"? If not, start a new line for \"if\".'", ")", "# Check for potential format string bugs like printf(foo).", "# We constrain the pattern not to pick things like DocidForPrintf(foo).", "# Not perfect but it can catch printf(foo.c_str()) and printf(foo->c_str())", "# TODO(unknown): Catch the following case. Need to change the calling", "# convention of the whole function to process multiple line to handle it.", "# printf(", "# boy_this_is_a_really_long_variable_that_cannot_fit_on_the_prev_line);", "printf_args", "=", "_GetTextInside", "(", "line", ",", "r'(?i)\\b(string)?printf\\s*\\('", ")", "if", "printf_args", ":", "match", "=", "Match", "(", "r'([\\w.\\->()]+)$'", ",", "printf_args", ")", "if", "match", "and", "match", ".", "group", "(", "1", ")", "!=", "'__VA_ARGS__'", ":", "function_name", "=", "re", ".", "search", "(", "r'\\b((?:string)?printf)\\s*\\('", ",", "line", ",", "re", ".", "I", ")", ".", "group", "(", "1", ")", "error", "(", "filename", ",", "linenum", ",", "'runtime/printf'", ",", "4", ",", "'Potential format string bug. Do %s(\"%%s\", %s) instead.'", "%", "(", "function_name", ",", "match", ".", "group", "(", "1", ")", ")", ")", "# Check for potential memset bugs like memset(buf, sizeof(buf), 0).", "match", "=", "Search", "(", "r'memset\\s*\\(([^,]*),\\s*([^,]*),\\s*0\\s*\\)'", ",", "line", ")", "if", "match", "and", "not", "Match", "(", "r\"^''|-?[0-9]+|0x[0-9A-Fa-f]$\"", ",", "match", ".", "group", "(", "2", ")", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'runtime/memset'", ",", "4", ",", "'Did you mean \"memset(%s, 0, %s)\"?'", "%", "(", "match", ".", "group", "(", "1", ")", ",", "match", ".", "group", "(", "2", ")", ")", ")", "if", "Search", "(", "r'\\busing namespace\\b'", ",", "line", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'build/namespaces'", ",", "5", ",", "'Do not use namespace using-directives. '", "'Use using-declarations instead.'", ")", "# Detect variable-length arrays.", "match", "=", "Match", "(", "r'\\s*(.+::)?(\\w+) [a-z]\\w*\\[(.+)];'", ",", "line", ")", "if", "(", "match", "and", "match", ".", "group", "(", "2", ")", "!=", "'return'", "and", "match", ".", "group", "(", "2", ")", "!=", "'delete'", "and", "match", ".", "group", "(", "3", ")", ".", "find", "(", "']'", ")", "==", "-", "1", ")", ":", "# Split the size using space and arithmetic operators as delimiters.", "# If any of the resulting tokens are not compile time constants then", "# report the error.", "tokens", "=", "re", ".", "split", "(", "r'\\s|\\+|\\-|\\*|\\/|<<|>>]'", ",", "match", ".", "group", "(", "3", ")", ")", "is_const", "=", "True", "skip_next", "=", "False", "for", "tok", "in", "tokens", ":", "if", "skip_next", ":", "skip_next", "=", "False", "continue", "if", "Search", "(", "r'sizeof\\(.+\\)'", ",", "tok", ")", ":", "continue", "if", "Search", "(", "r'arraysize\\(\\w+\\)'", ",", "tok", ")", ":", "continue", "tok", "=", "tok", ".", "lstrip", "(", "'('", ")", "tok", "=", "tok", ".", "rstrip", "(", "')'", ")", "if", "not", "tok", ":", "continue", "if", "Match", "(", "r'\\d+'", ",", "tok", ")", ":", "continue", "if", "Match", "(", "r'0[xX][0-9a-fA-F]+'", ",", "tok", ")", ":", "continue", "if", "Match", "(", "r'k[A-Z0-9]\\w*'", ",", "tok", ")", ":", "continue", "if", "Match", "(", "r'(.+::)?k[A-Z0-9]\\w*'", ",", "tok", ")", ":", "continue", "if", "Match", "(", "r'(.+::)?[A-Z][A-Z0-9_]*'", ",", "tok", ")", ":", "continue", "# A catch all for tricky sizeof cases, including 'sizeof expression',", "# 'sizeof(*type)', 'sizeof(const type)', 'sizeof(struct StructName)'", "# requires skipping the next token because we split on ' ' and '*'.", "if", "tok", ".", "startswith", "(", "'sizeof'", ")", ":", "skip_next", "=", "True", "continue", "is_const", "=", "False", "break", "if", "not", "is_const", ":", "error", "(", "filename", ",", "linenum", ",", "'runtime/arrays'", ",", "1", ",", "'Do not use variable-length arrays. Use an appropriately named '", "\"('k' followed by CamelCase) compile-time constant for the size.\"", ")", "# Check for use of unnamed namespaces in header files. Registration", "# macros are typically OK, so we allow use of \"namespace {\" on lines", "# that end with backslashes.", "if", "(", "file_extension", "==", "'h'", "and", "Search", "(", "r'\\bnamespace\\s*{'", ",", "line", ")", "and", "line", "[", "-", "1", "]", "!=", "'\\\\'", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'build/namespaces'", ",", "4", ",", "'Do not use unnamed namespaces in header files. See '", "'http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Namespaces'", "' for more information.'", ")" ]
https://github.com/bigartm/bigartm/blob/47e37f982de87aa67bfd475ff1f39da696b181b3/utils/cpplint.py#L4765-L4920
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib-tk/Tkinter.py
python
Misc.clipboard_clear
(self, **kw)
Clear the data in the Tk clipboard. A widget specified for the optional displayof keyword argument specifies the target display.
Clear the data in the Tk clipboard.
[ "Clear", "the", "data", "in", "the", "Tk", "clipboard", "." ]
def clipboard_clear(self, **kw): """Clear the data in the Tk clipboard. A widget specified for the optional displayof keyword argument specifies the target display.""" if 'displayof' not in kw: kw['displayof'] = self._w self.tk.call(('clipboard', 'clear') + self._options(kw))
[ "def", "clipboard_clear", "(", "self", ",", "*", "*", "kw", ")", ":", "if", "'displayof'", "not", "in", "kw", ":", "kw", "[", "'displayof'", "]", "=", "self", ".", "_w", "self", ".", "tk", ".", "call", "(", "(", "'clipboard'", ",", "'clear'", ")", "+", "self", ".", "_options", "(", "kw", ")", ")" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib-tk/Tkinter.py#L588-L594
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/codecs.py
python
StreamReader.next
(self)
Return the next decoded line from the input stream.
Return the next decoded line from the input stream.
[ "Return", "the", "next", "decoded", "line", "from", "the", "input", "stream", "." ]
def next(self): """ Return the next decoded line from the input stream.""" line = self.readline() if line: return line raise StopIteration
[ "def", "next", "(", "self", ")", ":", "line", "=", "self", ".", "readline", "(", ")", "if", "line", ":", "return", "line", "raise", "StopIteration" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/codecs.py#L612-L618
hughperkins/tf-coriander
970d3df6c11400ad68405f22b0c42a52374e94ca
tensorflow/python/summary/event_accumulator.py
python
EventAccumulator.FirstEventTimestamp
(self)
Returns the timestamp in seconds of the first event. If the first event has been loaded (either by this method or by `Reload`, this returns immediately. Otherwise, it will load in the first event. Note that this means that calling `Reload` will cause this to block until `Reload` has finished. Returns: The timestamp in seconds of the first event that was loaded. Raises: ValueError: If no events have been loaded and there were no events found on disk.
Returns the timestamp in seconds of the first event.
[ "Returns", "the", "timestamp", "in", "seconds", "of", "the", "first", "event", "." ]
def FirstEventTimestamp(self): """Returns the timestamp in seconds of the first event. If the first event has been loaded (either by this method or by `Reload`, this returns immediately. Otherwise, it will load in the first event. Note that this means that calling `Reload` will cause this to block until `Reload` has finished. Returns: The timestamp in seconds of the first event that was loaded. Raises: ValueError: If no events have been loaded and there were no events found on disk. """ if self._first_event_timestamp is not None: return self._first_event_timestamp with self._generator_mutex: try: event = next(self._generator.Load()) self._ProcessEvent(event) return self._first_event_timestamp except StopIteration: raise ValueError('No event timestamp could be found')
[ "def", "FirstEventTimestamp", "(", "self", ")", ":", "if", "self", ".", "_first_event_timestamp", "is", "not", "None", ":", "return", "self", ".", "_first_event_timestamp", "with", "self", ".", "_generator_mutex", ":", "try", ":", "event", "=", "next", "(", "self", ".", "_generator", ".", "Load", "(", ")", ")", "self", ".", "_ProcessEvent", "(", "event", ")", "return", "self", ".", "_first_event_timestamp", "except", "StopIteration", ":", "raise", "ValueError", "(", "'No event timestamp could be found'", ")" ]
https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/summary/event_accumulator.py#L202-L226
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/json/decoder.py
python
JSONDecoder.raw_decode
(self, s, idx=0)
return obj, end
Decode a JSON document from ``s`` (a ``str`` or ``unicode`` beginning with a JSON document) and return a 2-tuple of the Python representation and the index in ``s`` where the document ended. This can be used to decode a JSON document from a string that may have extraneous data at the end.
Decode a JSON document from ``s`` (a ``str`` or ``unicode`` beginning with a JSON document) and return a 2-tuple of the Python representation and the index in ``s`` where the document ended.
[ "Decode", "a", "JSON", "document", "from", "s", "(", "a", "str", "or", "unicode", "beginning", "with", "a", "JSON", "document", ")", "and", "return", "a", "2", "-", "tuple", "of", "the", "Python", "representation", "and", "the", "index", "in", "s", "where", "the", "document", "ended", "." ]
def raw_decode(self, s, idx=0): """Decode a JSON document from ``s`` (a ``str`` or ``unicode`` beginning with a JSON document) and return a 2-tuple of the Python representation and the index in ``s`` where the document ended. This can be used to decode a JSON document from a string that may have extraneous data at the end. """ try: obj, end = self.scan_once(s, idx) except StopIteration: raise ValueError("No JSON object could be decoded") return obj, end
[ "def", "raw_decode", "(", "self", ",", "s", ",", "idx", "=", "0", ")", ":", "try", ":", "obj", ",", "end", "=", "self", ".", "scan_once", "(", "s", ",", "idx", ")", "except", "StopIteration", ":", "raise", "ValueError", "(", "\"No JSON object could be decoded\"", ")", "return", "obj", ",", "end" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/json/decoder.py#L371-L384
sofa-framework/sofa
70628e35a44fcc258cf8250109b5e4eba8c5abe9
applications/plugins/image/python/SofaImage/Tools.py
python
Controller.__new__
(cls, node, name='pythonScriptController', filename='')
:param filename: you may have to define it (at least once) to create a controller for which the class is defined in an external file. Be aware the file will then be read several times.
:param filename: you may have to define it (at least once) to create a controller for which the class is defined in an external file. Be aware the file will then be read several times.
[ ":", "param", "filename", ":", "you", "may", "have", "to", "define", "it", "(", "at", "least", "once", ")", "to", "create", "a", "controller", "for", "which", "the", "class", "is", "defined", "in", "an", "external", "file", ".", "Be", "aware", "the", "file", "will", "then", "be", "read", "several", "times", "." ]
def __new__(cls, node, name='pythonScriptController', filename=''): """ :param filename: you may have to define it (at least once) to create a controller for which the class is defined in an external file. Be aware the file will then be read several times. """ node.createObject('PythonScriptController', filename = filename, classname = cls.__name__, name = name) try: res = Controller.instance del Controller.instance return res except AttributeError: # if this fails, you need to call # Controller.onLoaded(self, node) in derived classes print "[SofaImage.Controller.__new__] instance not found, did you call 'SofaImage.Controller.onLoaded' on your overloaded 'onLoaded' in {} ?".format(cls) raise
[ "def", "__new__", "(", "cls", ",", "node", ",", "name", "=", "'pythonScriptController'", ",", "filename", "=", "''", ")", ":", "node", ".", "createObject", "(", "'PythonScriptController'", ",", "filename", "=", "filename", ",", "classname", "=", "cls", ".", "__name__", ",", "name", "=", "name", ")", "try", ":", "res", "=", "Controller", ".", "instance", "del", "Controller", ".", "instance", "return", "res", "except", "AttributeError", ":", "# if this fails, you need to call", "# Controller.onLoaded(self, node) in derived classes", "print", "\"[SofaImage.Controller.__new__] instance not found, did you call 'SofaImage.Controller.onLoaded' on your overloaded 'onLoaded' in {} ?\"", ".", "format", "(", "cls", ")", "raise" ]
https://github.com/sofa-framework/sofa/blob/70628e35a44fcc258cf8250109b5e4eba8c5abe9/applications/plugins/image/python/SofaImage/Tools.py#L134-L153
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/aui/framemanager.py
python
AuiPaneInfo.DestroyOnClose
(self, b=True)
return self.SetFlag(self.optionDestroyOnClose, b)
Indicates whether a pane should be destroyed when it is closed. Normally a pane is simply hidden when the close button is clicked. Setting `b` to ``True`` will cause the window to be destroyed when the user clicks the pane's close button. :param bool `b`: whether the pane should be destroyed when it is closed or not.
Indicates whether a pane should be destroyed when it is closed.
[ "Indicates", "whether", "a", "pane", "should", "be", "destroyed", "when", "it", "is", "closed", "." ]
def DestroyOnClose(self, b=True): """ Indicates whether a pane should be destroyed when it is closed. Normally a pane is simply hidden when the close button is clicked. Setting `b` to ``True`` will cause the window to be destroyed when the user clicks the pane's close button. :param bool `b`: whether the pane should be destroyed when it is closed or not. """ return self.SetFlag(self.optionDestroyOnClose, b)
[ "def", "DestroyOnClose", "(", "self", ",", "b", "=", "True", ")", ":", "return", "self", ".", "SetFlag", "(", "self", ".", "optionDestroyOnClose", ",", "b", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/aui/framemanager.py#L1512-L1523
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/botocore/session.py
python
Session.unregister
(self, event_name, handler=None, unique_id=None, unique_id_uses_count=False)
Unregister a handler with an event. :type event_name: str :param event_name: The name of the event. :type handler: callable :param handler: The callback to unregister. :type unique_id: str :param unique_id: A unique identifier identifying the callback to unregister. You can provide either the handler or the unique_id, you do not have to provide both. :param unique_id_uses_count: boolean :param unique_id_uses_count: Specifies if the event should maintain a count when a ``unique_id`` is registered and unregisted. The event can only be completely unregistered once every ``register`` call using the ``unique_id`` has been matched by an ``unregister`` call. If the ``unique_id`` is specified, subsequent ``unregister`` calls must use the same value for ``unique_id_uses_count`` as the ``register`` call that first registered the event. :raises ValueError: If the call to ``unregister`` uses ``unique_id`` but the value for ``unique_id_uses_count`` differs from the ``unique_id_uses_count`` value declared by the very first ``register`` call for that ``unique_id``.
Unregister a handler with an event.
[ "Unregister", "a", "handler", "with", "an", "event", "." ]
def unregister(self, event_name, handler=None, unique_id=None, unique_id_uses_count=False): """Unregister a handler with an event. :type event_name: str :param event_name: The name of the event. :type handler: callable :param handler: The callback to unregister. :type unique_id: str :param unique_id: A unique identifier identifying the callback to unregister. You can provide either the handler or the unique_id, you do not have to provide both. :param unique_id_uses_count: boolean :param unique_id_uses_count: Specifies if the event should maintain a count when a ``unique_id`` is registered and unregisted. The event can only be completely unregistered once every ``register`` call using the ``unique_id`` has been matched by an ``unregister`` call. If the ``unique_id`` is specified, subsequent ``unregister`` calls must use the same value for ``unique_id_uses_count`` as the ``register`` call that first registered the event. :raises ValueError: If the call to ``unregister`` uses ``unique_id`` but the value for ``unique_id_uses_count`` differs from the ``unique_id_uses_count`` value declared by the very first ``register`` call for that ``unique_id``. """ self._events.unregister(event_name, handler=handler, unique_id=unique_id, unique_id_uses_count=unique_id_uses_count)
[ "def", "unregister", "(", "self", ",", "event_name", ",", "handler", "=", "None", ",", "unique_id", "=", "None", ",", "unique_id_uses_count", "=", "False", ")", ":", "self", ".", "_events", ".", "unregister", "(", "event_name", ",", "handler", "=", "handler", ",", "unique_id", "=", "unique_id", ",", "unique_id_uses_count", "=", "unique_id_uses_count", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/botocore/session.py#L639-L671
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/ops/operations/math_ops.py
python
Abs.__init__
(self)
Initialize Abs
Initialize Abs
[ "Initialize", "Abs" ]
def __init__(self): """Initialize Abs""" self.init_prim_io_names(inputs=['input_x'], outputs=['output'])
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "init_prim_io_names", "(", "inputs", "=", "[", "'input_x'", "]", ",", "outputs", "=", "[", "'output'", "]", ")" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/operations/math_ops.py#L4576-L4578
francinexue/xuefu
b6ff79747a42e020588c0c0a921048e08fe4680c
ctpx/ctp2/ctptd.py
python
CtpTd.reqQryOrder
(self)
return self._requestId
查询委托
查询委托
[ "查询委托" ]
def reqQryOrder(self): """查询委托""" qryOrderField = td.QryOrderField() qryOrderField.brokerID = self._brokerID qryOrderField.investorID = self._userID # qryOrderField.instrumentID = "" self._requestId += 1 super(CtpTd, self).reqQryOrder(qryOrderField, self._requestId) return self._requestId
[ "def", "reqQryOrder", "(", "self", ")", ":", "qryOrderField", "=", "td", ".", "QryOrderField", "(", ")", "qryOrderField", ".", "brokerID", "=", "self", ".", "_brokerID", "qryOrderField", ".", "investorID", "=", "self", ".", "_userID", "# qryOrderField.instrumentID = \"\"", "self", ".", "_requestId", "+=", "1", "super", "(", "CtpTd", ",", "self", ")", ".", "reqQryOrder", "(", "qryOrderField", ",", "self", ".", "_requestId", ")", "return", "self", ".", "_requestId" ]
https://github.com/francinexue/xuefu/blob/b6ff79747a42e020588c0c0a921048e08fe4680c/ctpx/ctp2/ctptd.py#L609-L617
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/ros_comm/rosgraph/src/rosgraph/xmlrpc.py
python
ThreadingXMLRPCServer.__init__
(self, addr, log_requests=1)
Overrides SimpleXMLRPCServer to set option to allow_reuse_address.
Overrides SimpleXMLRPCServer to set option to allow_reuse_address.
[ "Overrides", "SimpleXMLRPCServer", "to", "set", "option", "to", "allow_reuse_address", "." ]
def __init__(self, addr, log_requests=1): """ Overrides SimpleXMLRPCServer to set option to allow_reuse_address. """ # allow_reuse_address defaults to False in Python 2.4. We set it # to True to allow quick restart on the same port. This is equivalent # to calling setsockopt(SOL_SOCKET,SO_REUSEADDR,1) self.allow_reuse_address = True # Increase request_queue_size to handle issues with many simultaneous # connections in OSX 10.11 self.request_queue_size = min(socket.SOMAXCONN, 128) if rosgraph.network.use_ipv6(): logger = logging.getLogger('xmlrpc') # The XMLRPC library does not support IPv6 out of the box # We have to monipulate private members and duplicate # code from the constructor. # TODO IPV6: Get this into SimpleXMLRPCServer SimpleXMLRPCServer.__init__(self, addr, SilenceableXMLRPCRequestHandler, log_requests, bind_and_activate=False) self.address_family = socket.AF_INET6 self.socket = socket.socket(self.address_family, self.socket_type) logger.info('binding ipv6 xmlrpc socket to' + str(addr)) # TODO: set IPV6_V6ONLY to 0: # self.socket.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 0) self.server_bind() self.server_activate() logger.info('bound to ' + str(self.socket.getsockname()[0:2])) else: SimpleXMLRPCServer.__init__(self, addr, SilenceableXMLRPCRequestHandler, log_requests)
[ "def", "__init__", "(", "self", ",", "addr", ",", "log_requests", "=", "1", ")", ":", "# allow_reuse_address defaults to False in Python 2.4. We set it ", "# to True to allow quick restart on the same port. This is equivalent ", "# to calling setsockopt(SOL_SOCKET,SO_REUSEADDR,1)", "self", ".", "allow_reuse_address", "=", "True", "# Increase request_queue_size to handle issues with many simultaneous", "# connections in OSX 10.11", "self", ".", "request_queue_size", "=", "min", "(", "socket", ".", "SOMAXCONN", ",", "128", ")", "if", "rosgraph", ".", "network", ".", "use_ipv6", "(", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "'xmlrpc'", ")", "# The XMLRPC library does not support IPv6 out of the box", "# We have to monipulate private members and duplicate", "# code from the constructor.", "# TODO IPV6: Get this into SimpleXMLRPCServer ", "SimpleXMLRPCServer", ".", "__init__", "(", "self", ",", "addr", ",", "SilenceableXMLRPCRequestHandler", ",", "log_requests", ",", "bind_and_activate", "=", "False", ")", "self", ".", "address_family", "=", "socket", ".", "AF_INET6", "self", ".", "socket", "=", "socket", ".", "socket", "(", "self", ".", "address_family", ",", "self", ".", "socket_type", ")", "logger", ".", "info", "(", "'binding ipv6 xmlrpc socket to'", "+", "str", "(", "addr", ")", ")", "# TODO: set IPV6_V6ONLY to 0:", "# self.socket.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 0)", "self", ".", "server_bind", "(", ")", "self", ".", "server_activate", "(", ")", "logger", ".", "info", "(", "'bound to '", "+", "str", "(", "self", ".", "socket", ".", "getsockname", "(", ")", "[", "0", ":", "2", "]", ")", ")", "else", ":", "SimpleXMLRPCServer", ".", "__init__", "(", "self", ",", "addr", ",", "SilenceableXMLRPCRequestHandler", ",", "log_requests", ")" ]
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/ros_comm/rosgraph/src/rosgraph/xmlrpc.py#L88-L115
okex/V3-Open-API-SDK
c5abb0db7e2287718e0055e17e57672ce0ec7fd9
okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/ipaddress.py
python
IPv6Address.teredo
(self)
return (IPv4Address((self._ip >> 64) & 0xFFFFFFFF), IPv4Address(~self._ip & 0xFFFFFFFF))
Tuple of embedded teredo IPs. Returns: Tuple of the (server, client) IPs or None if the address doesn't appear to be a teredo address (doesn't start with 2001::/32)
Tuple of embedded teredo IPs.
[ "Tuple", "of", "embedded", "teredo", "IPs", "." ]
def teredo(self): """Tuple of embedded teredo IPs. Returns: Tuple of the (server, client) IPs or None if the address doesn't appear to be a teredo address (doesn't start with 2001::/32) """ if (self._ip >> 96) != 0x20010000: return None return (IPv4Address((self._ip >> 64) & 0xFFFFFFFF), IPv4Address(~self._ip & 0xFFFFFFFF))
[ "def", "teredo", "(", "self", ")", ":", "if", "(", "self", ".", "_ip", ">>", "96", ")", "!=", "0x20010000", ":", "return", "None", "return", "(", "IPv4Address", "(", "(", "self", ".", "_ip", ">>", "64", ")", "&", "0xFFFFFFFF", ")", ",", "IPv4Address", "(", "~", "self", ".", "_ip", "&", "0xFFFFFFFF", ")", ")" ]
https://github.com/okex/V3-Open-API-SDK/blob/c5abb0db7e2287718e0055e17e57672ce0ec7fd9/okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/ipaddress.py#L2148-L2160
blackberry/Boost
fc90c3fde129c62565c023f091eddc4a7ed9902b
tools/build/v2/build/toolset.py
python
__add_flag
(rule_or_module, variable_name, condition, values)
Adds a new flag setting with the specified values. Does no checking.
Adds a new flag setting with the specified values. Does no checking.
[ "Adds", "a", "new", "flag", "setting", "with", "the", "specified", "values", ".", "Does", "no", "checking", "." ]
def __add_flag (rule_or_module, variable_name, condition, values): """ Adds a new flag setting with the specified values. Does no checking. """ f = Flag(variable_name, values, condition, rule_or_module) # Grab the name of the module m = __re_first_segment.match (rule_or_module) assert m module = m.group(1) __module_flags.setdefault(m, []).append(f) __flags.setdefault(rule_or_module, []).append(f)
[ "def", "__add_flag", "(", "rule_or_module", ",", "variable_name", ",", "condition", ",", "values", ")", ":", "f", "=", "Flag", "(", "variable_name", ",", "values", ",", "condition", ",", "rule_or_module", ")", "# Grab the name of the module", "m", "=", "__re_first_segment", ".", "match", "(", "rule_or_module", ")", "assert", "m", "module", "=", "m", ".", "group", "(", "1", ")", "__module_flags", ".", "setdefault", "(", "m", ",", "[", "]", ")", ".", "append", "(", "f", ")", "__flags", ".", "setdefault", "(", "rule_or_module", ",", "[", "]", ")", ".", "append", "(", "f", ")" ]
https://github.com/blackberry/Boost/blob/fc90c3fde129c62565c023f091eddc4a7ed9902b/tools/build/v2/build/toolset.py#L354-L366
Polidea/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
SymbolExtractorAndRenamer/lldb/examples/customization/pwd-cd-and-system/utils.py
python
chdir
(debugger, args, result, dict)
Change the working directory, or cd to ${HOME}. You can also issue 'cd -' to change to the previous working directory.
Change the working directory, or cd to ${HOME}. You can also issue 'cd -' to change to the previous working directory.
[ "Change", "the", "working", "directory", "or", "cd", "to", "$", "{", "HOME", "}", ".", "You", "can", "also", "issue", "cd", "-", "to", "change", "to", "the", "previous", "working", "directory", "." ]
def chdir(debugger, args, result, dict): """Change the working directory, or cd to ${HOME}. You can also issue 'cd -' to change to the previous working directory.""" new_dir = args.strip() if not new_dir: new_dir = os.path.expanduser('~') elif new_dir == '-': if not Holder.prev_dir(): # Bad directory, not changing. print "bad directory, not changing" return else: new_dir = Holder.prev_dir() Holder.swap(os.getcwd()) os.chdir(new_dir) print "Current working directory: %s" % os.getcwd()
[ "def", "chdir", "(", "debugger", ",", "args", ",", "result", ",", "dict", ")", ":", "new_dir", "=", "args", ".", "strip", "(", ")", "if", "not", "new_dir", ":", "new_dir", "=", "os", ".", "path", ".", "expanduser", "(", "'~'", ")", "elif", "new_dir", "==", "'-'", ":", "if", "not", "Holder", ".", "prev_dir", "(", ")", ":", "# Bad directory, not changing.", "print", "\"bad directory, not changing\"", "return", "else", ":", "new_dir", "=", "Holder", ".", "prev_dir", "(", ")", "Holder", ".", "swap", "(", "os", ".", "getcwd", "(", ")", ")", "os", ".", "chdir", "(", "new_dir", ")", "print", "\"Current working directory: %s\"", "%", "os", ".", "getcwd", "(", ")" ]
https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/examples/customization/pwd-cd-and-system/utils.py#L23-L39
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/cmd.py
python
Cmd.emptyline
(self)
Called when an empty line is entered in response to the prompt. If this method is not overridden, it repeats the last nonempty command entered.
Called when an empty line is entered in response to the prompt.
[ "Called", "when", "an", "empty", "line", "is", "entered", "in", "response", "to", "the", "prompt", "." ]
def emptyline(self): """Called when an empty line is entered in response to the prompt. If this method is not overridden, it repeats the last nonempty command entered. """ if self.lastcmd: return self.onecmd(self.lastcmd)
[ "def", "emptyline", "(", "self", ")", ":", "if", "self", ".", "lastcmd", ":", "return", "self", ".", "onecmd", "(", "self", ".", "lastcmd", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/cmd.py#L223-L231
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqt/mantidqt/widgets/workspacecalculator/model.py
python
WorkspaceCalculatorModel.__init__
(self, lhs_scale=1.0, lhs_ws=None, rhs_scale=1.0, rhs_ws=None, output_ws=None, operation='+')
Initializes the model with all parameters necessary for performing the desired operation. Default parameters do not pass the validation step.
Initializes the model with all parameters necessary for performing the desired operation. Default parameters do not pass the validation step.
[ "Initializes", "the", "model", "with", "all", "parameters", "necessary", "for", "performing", "the", "desired", "operation", ".", "Default", "parameters", "do", "not", "pass", "the", "validation", "step", "." ]
def __init__(self, lhs_scale=1.0, lhs_ws=None, rhs_scale=1.0, rhs_ws=None, output_ws=None, operation='+'): """Initializes the model with all parameters necessary for performing the desired operation. Default parameters do not pass the validation step.""" self._lhs_scale = lhs_scale self._lhs_ws = lhs_ws self._rhs_scale = rhs_scale self._rhs_ws = rhs_ws self._output_ws = output_ws self._operation = operation self._md_lhs = None self._md_rhs = None
[ "def", "__init__", "(", "self", ",", "lhs_scale", "=", "1.0", ",", "lhs_ws", "=", "None", ",", "rhs_scale", "=", "1.0", ",", "rhs_ws", "=", "None", ",", "output_ws", "=", "None", ",", "operation", "=", "'+'", ")", ":", "self", ".", "_lhs_scale", "=", "lhs_scale", "self", ".", "_lhs_ws", "=", "lhs_ws", "self", ".", "_rhs_scale", "=", "rhs_scale", "self", ".", "_rhs_ws", "=", "rhs_ws", "self", ".", "_output_ws", "=", "output_ws", "self", ".", "_operation", "=", "operation", "self", ".", "_md_lhs", "=", "None", "self", ".", "_md_rhs", "=", "None" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqt/mantidqt/widgets/workspacecalculator/model.py#L23-L34
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/f2py/capi_maps.py
python
sign2map
(a, var)
return ret
varname,ctype,atype init,init.r,init.i,pytype vardebuginfo,vardebugshowvalue,varshowvalue varrfromat intent
varname,ctype,atype init,init.r,init.i,pytype vardebuginfo,vardebugshowvalue,varshowvalue varrfromat intent
[ "varname", "ctype", "atype", "init", "init", ".", "r", "init", ".", "i", "pytype", "vardebuginfo", "vardebugshowvalue", "varshowvalue", "varrfromat", "intent" ]
def sign2map(a, var): """ varname,ctype,atype init,init.r,init.i,pytype vardebuginfo,vardebugshowvalue,varshowvalue varrfromat intent """ global lcb_map, cb_map out_a = a if isintent_out(var): for k in var['intent']: if k[:4] == 'out=': out_a = k[4:] break ret = {'varname': a, 'outvarname': out_a, 'ctype': getctype(var)} intent_flags = [] for f, s in isintent_dict.items(): if f(var): intent_flags.append('F2PY_%s' % s) if intent_flags: # XXX: Evaluate intent_flags here. ret['intent'] = '|'.join(intent_flags) else: ret['intent'] = 'F2PY_INTENT_IN' if isarray(var): ret['varrformat'] = 'N' elif ret['ctype'] in c2buildvalue_map: ret['varrformat'] = c2buildvalue_map[ret['ctype']] else: ret['varrformat'] = 'O' ret['init'], ret['showinit'] = getinit(a, var) if hasinitvalue(var) and iscomplex(var) and not isarray(var): ret['init.r'], ret['init.i'] = markoutercomma( ret['init'][1:-1]).split('@,@') if isexternal(var): ret['cbnamekey'] = a if a in lcb_map: ret['cbname'] = lcb_map[a] ret['maxnofargs'] = lcb2_map[lcb_map[a]]['maxnofargs'] ret['nofoptargs'] = lcb2_map[lcb_map[a]]['nofoptargs'] ret['cbdocstr'] = lcb2_map[lcb_map[a]]['docstr'] ret['cblatexdocstr'] = lcb2_map[lcb_map[a]]['latexdocstr'] else: ret['cbname'] = a errmess('sign2map: Confused: external %s is not in lcb_map%s.\n' % ( a, list(lcb_map.keys()))) if isstring(var): ret['length'] = getstrlength(var) if isarray(var): ret = dictappend(ret, getarrdims(a, var)) dim = copy.copy(var['dimension']) if ret['ctype'] in c2capi_map: ret['atype'] = c2capi_map[ret['ctype']] # Debug info if debugcapi(var): il = [isintent_in, 'input', isintent_out, 'output', isintent_inout, 'inoutput', isrequired, 'required', isoptional, 'optional', isintent_hide, 'hidden', iscomplex, 'complex scalar', l_and(isscalar, l_not(iscomplex)), 'scalar', isstring, 'string', isarray, 'array', iscomplexarray, 'complex array', isstringarray, 'string array', iscomplexfunction, 'complex function', l_and(isfunction, l_not(iscomplexfunction)), 'function', isexternal, 'callback', isintent_callback, 'callback', isintent_aux, 'auxiliary', ] rl = [] for i in range(0, len(il), 2): if il[i](var): rl.append(il[i + 1]) if isstring(var): rl.append('slen(%s)=%s' % (a, ret['length'])) if isarray(var): ddim = ','.join( map(lambda x, y: '%s|%s' % (x, y), var['dimension'], dim)) rl.append('dims(%s)' % ddim) if isexternal(var): ret['vardebuginfo'] = 'debug-capi:%s=>%s:%s' % ( a, ret['cbname'], ','.join(rl)) else: ret['vardebuginfo'] = 'debug-capi:%s %s=%s:%s' % ( ret['ctype'], a, ret['showinit'], ','.join(rl)) if isscalar(var): if ret['ctype'] in cformat_map: ret['vardebugshowvalue'] = 'debug-capi:%s=%s' % ( a, cformat_map[ret['ctype']]) if isstring(var): ret['vardebugshowvalue'] = 'debug-capi:slen(%s)=%%d %s=\\"%%s\\"' % ( a, a) if isexternal(var): ret['vardebugshowvalue'] = 'debug-capi:%s=%%p' % (a) if ret['ctype'] in cformat_map: ret['varshowvalue'] = '#name#:%s=%s' % (a, cformat_map[ret['ctype']]) ret['showvalueformat'] = '%s' % (cformat_map[ret['ctype']]) if isstring(var): ret['varshowvalue'] = '#name#:slen(%s)=%%d %s=\\"%%s\\"' % (a, a) ret['pydocsign'], ret['pydocsignout'] = getpydocsign(a, var) if hasnote(var): ret['note'] = var['note'] return ret
[ "def", "sign2map", "(", "a", ",", "var", ")", ":", "global", "lcb_map", ",", "cb_map", "out_a", "=", "a", "if", "isintent_out", "(", "var", ")", ":", "for", "k", "in", "var", "[", "'intent'", "]", ":", "if", "k", "[", ":", "4", "]", "==", "'out='", ":", "out_a", "=", "k", "[", "4", ":", "]", "break", "ret", "=", "{", "'varname'", ":", "a", ",", "'outvarname'", ":", "out_a", ",", "'ctype'", ":", "getctype", "(", "var", ")", "}", "intent_flags", "=", "[", "]", "for", "f", ",", "s", "in", "isintent_dict", ".", "items", "(", ")", ":", "if", "f", "(", "var", ")", ":", "intent_flags", ".", "append", "(", "'F2PY_%s'", "%", "s", ")", "if", "intent_flags", ":", "# XXX: Evaluate intent_flags here.", "ret", "[", "'intent'", "]", "=", "'|'", ".", "join", "(", "intent_flags", ")", "else", ":", "ret", "[", "'intent'", "]", "=", "'F2PY_INTENT_IN'", "if", "isarray", "(", "var", ")", ":", "ret", "[", "'varrformat'", "]", "=", "'N'", "elif", "ret", "[", "'ctype'", "]", "in", "c2buildvalue_map", ":", "ret", "[", "'varrformat'", "]", "=", "c2buildvalue_map", "[", "ret", "[", "'ctype'", "]", "]", "else", ":", "ret", "[", "'varrformat'", "]", "=", "'O'", "ret", "[", "'init'", "]", ",", "ret", "[", "'showinit'", "]", "=", "getinit", "(", "a", ",", "var", ")", "if", "hasinitvalue", "(", "var", ")", "and", "iscomplex", "(", "var", ")", "and", "not", "isarray", "(", "var", ")", ":", "ret", "[", "'init.r'", "]", ",", "ret", "[", "'init.i'", "]", "=", "markoutercomma", "(", "ret", "[", "'init'", "]", "[", "1", ":", "-", "1", "]", ")", ".", "split", "(", "'@,@'", ")", "if", "isexternal", "(", "var", ")", ":", "ret", "[", "'cbnamekey'", "]", "=", "a", "if", "a", "in", "lcb_map", ":", "ret", "[", "'cbname'", "]", "=", "lcb_map", "[", "a", "]", "ret", "[", "'maxnofargs'", "]", "=", "lcb2_map", "[", "lcb_map", "[", "a", "]", "]", "[", "'maxnofargs'", "]", "ret", "[", "'nofoptargs'", "]", "=", "lcb2_map", "[", "lcb_map", "[", "a", "]", "]", "[", "'nofoptargs'", "]", "ret", "[", "'cbdocstr'", "]", "=", "lcb2_map", "[", "lcb_map", "[", "a", "]", "]", "[", "'docstr'", "]", "ret", "[", "'cblatexdocstr'", "]", "=", "lcb2_map", "[", "lcb_map", "[", "a", "]", "]", "[", "'latexdocstr'", "]", "else", ":", "ret", "[", "'cbname'", "]", "=", "a", "errmess", "(", "'sign2map: Confused: external %s is not in lcb_map%s.\\n'", "%", "(", "a", ",", "list", "(", "lcb_map", ".", "keys", "(", ")", ")", ")", ")", "if", "isstring", "(", "var", ")", ":", "ret", "[", "'length'", "]", "=", "getstrlength", "(", "var", ")", "if", "isarray", "(", "var", ")", ":", "ret", "=", "dictappend", "(", "ret", ",", "getarrdims", "(", "a", ",", "var", ")", ")", "dim", "=", "copy", ".", "copy", "(", "var", "[", "'dimension'", "]", ")", "if", "ret", "[", "'ctype'", "]", "in", "c2capi_map", ":", "ret", "[", "'atype'", "]", "=", "c2capi_map", "[", "ret", "[", "'ctype'", "]", "]", "# Debug info", "if", "debugcapi", "(", "var", ")", ":", "il", "=", "[", "isintent_in", ",", "'input'", ",", "isintent_out", ",", "'output'", ",", "isintent_inout", ",", "'inoutput'", ",", "isrequired", ",", "'required'", ",", "isoptional", ",", "'optional'", ",", "isintent_hide", ",", "'hidden'", ",", "iscomplex", ",", "'complex scalar'", ",", "l_and", "(", "isscalar", ",", "l_not", "(", "iscomplex", ")", ")", ",", "'scalar'", ",", "isstring", ",", "'string'", ",", "isarray", ",", "'array'", ",", "iscomplexarray", ",", "'complex array'", ",", "isstringarray", ",", "'string array'", ",", "iscomplexfunction", ",", "'complex function'", ",", "l_and", "(", "isfunction", ",", "l_not", "(", "iscomplexfunction", ")", ")", ",", "'function'", ",", "isexternal", ",", "'callback'", ",", "isintent_callback", ",", "'callback'", ",", "isintent_aux", ",", "'auxiliary'", ",", "]", "rl", "=", "[", "]", "for", "i", "in", "range", "(", "0", ",", "len", "(", "il", ")", ",", "2", ")", ":", "if", "il", "[", "i", "]", "(", "var", ")", ":", "rl", ".", "append", "(", "il", "[", "i", "+", "1", "]", ")", "if", "isstring", "(", "var", ")", ":", "rl", ".", "append", "(", "'slen(%s)=%s'", "%", "(", "a", ",", "ret", "[", "'length'", "]", ")", ")", "if", "isarray", "(", "var", ")", ":", "ddim", "=", "','", ".", "join", "(", "map", "(", "lambda", "x", ",", "y", ":", "'%s|%s'", "%", "(", "x", ",", "y", ")", ",", "var", "[", "'dimension'", "]", ",", "dim", ")", ")", "rl", ".", "append", "(", "'dims(%s)'", "%", "ddim", ")", "if", "isexternal", "(", "var", ")", ":", "ret", "[", "'vardebuginfo'", "]", "=", "'debug-capi:%s=>%s:%s'", "%", "(", "a", ",", "ret", "[", "'cbname'", "]", ",", "','", ".", "join", "(", "rl", ")", ")", "else", ":", "ret", "[", "'vardebuginfo'", "]", "=", "'debug-capi:%s %s=%s:%s'", "%", "(", "ret", "[", "'ctype'", "]", ",", "a", ",", "ret", "[", "'showinit'", "]", ",", "','", ".", "join", "(", "rl", ")", ")", "if", "isscalar", "(", "var", ")", ":", "if", "ret", "[", "'ctype'", "]", "in", "cformat_map", ":", "ret", "[", "'vardebugshowvalue'", "]", "=", "'debug-capi:%s=%s'", "%", "(", "a", ",", "cformat_map", "[", "ret", "[", "'ctype'", "]", "]", ")", "if", "isstring", "(", "var", ")", ":", "ret", "[", "'vardebugshowvalue'", "]", "=", "'debug-capi:slen(%s)=%%d %s=\\\\\"%%s\\\\\"'", "%", "(", "a", ",", "a", ")", "if", "isexternal", "(", "var", ")", ":", "ret", "[", "'vardebugshowvalue'", "]", "=", "'debug-capi:%s=%%p'", "%", "(", "a", ")", "if", "ret", "[", "'ctype'", "]", "in", "cformat_map", ":", "ret", "[", "'varshowvalue'", "]", "=", "'#name#:%s=%s'", "%", "(", "a", ",", "cformat_map", "[", "ret", "[", "'ctype'", "]", "]", ")", "ret", "[", "'showvalueformat'", "]", "=", "'%s'", "%", "(", "cformat_map", "[", "ret", "[", "'ctype'", "]", "]", ")", "if", "isstring", "(", "var", ")", ":", "ret", "[", "'varshowvalue'", "]", "=", "'#name#:slen(%s)=%%d %s=\\\\\"%%s\\\\\"'", "%", "(", "a", ",", "a", ")", "ret", "[", "'pydocsign'", "]", ",", "ret", "[", "'pydocsignout'", "]", "=", "getpydocsign", "(", "a", ",", "var", ")", "if", "hasnote", "(", "var", ")", ":", "ret", "[", "'note'", "]", "=", "var", "[", "'note'", "]", "return", "ret" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/f2py/capi_maps.py#L516-L618
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/Pygments/py2/pygments/formatters/img.py
python
ImageFormatter._get_text_color
(self, style)
return fill
Get the correct color for the token from the style.
Get the correct color for the token from the style.
[ "Get", "the", "correct", "color", "for", "the", "token", "from", "the", "style", "." ]
def _get_text_color(self, style): """ Get the correct color for the token from the style. """ if style['color'] is not None: fill = '#' + style['color'] else: fill = '#000' return fill
[ "def", "_get_text_color", "(", "self", ",", "style", ")", ":", "if", "style", "[", "'color'", "]", "is", "not", "None", ":", "fill", "=", "'#'", "+", "style", "[", "'color'", "]", "else", ":", "fill", "=", "'#000'", "return", "fill" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/Pygments/py2/pygments/formatters/img.py#L427-L435
alibaba/weex_js_engine
2bdf4b6f020c1fc99c63f649718f6faf7e27fdde
jni/v8core/v8/build/gyp/pylib/gyp/xcode_emulation.py
python
XcodeSettings.GetBundleResourceFolder
(self)
return os.path.join(self.GetBundleContentsFolderPath(), 'Resources')
Returns the qualified path to the bundle's resource folder. E.g. Chromium.app/Contents/Resources. Only valid for bundles.
Returns the qualified path to the bundle's resource folder. E.g. Chromium.app/Contents/Resources. Only valid for bundles.
[ "Returns", "the", "qualified", "path", "to", "the", "bundle", "s", "resource", "folder", ".", "E", ".", "g", ".", "Chromium", ".", "app", "/", "Contents", "/", "Resources", ".", "Only", "valid", "for", "bundles", "." ]
def GetBundleResourceFolder(self): """Returns the qualified path to the bundle's resource folder. E.g. Chromium.app/Contents/Resources. Only valid for bundles.""" assert self._IsBundle() return os.path.join(self.GetBundleContentsFolderPath(), 'Resources')
[ "def", "GetBundleResourceFolder", "(", "self", ")", ":", "assert", "self", ".", "_IsBundle", "(", ")", "return", "os", ".", "path", ".", "join", "(", "self", ".", "GetBundleContentsFolderPath", "(", ")", ",", "'Resources'", ")" ]
https://github.com/alibaba/weex_js_engine/blob/2bdf4b6f020c1fc99c63f649718f6faf7e27fdde/jni/v8core/v8/build/gyp/pylib/gyp/xcode_emulation.py#L112-L116
kamyu104/LeetCode-Solutions
77605708a927ea3b85aee5a479db733938c7c211
Python/h-index.py
python
Solution3.hIndex
(self, citations)
return sum(x >= i + 1 for i, x in enumerate(sorted(citations, reverse=True)))
:type citations: List[int] :rtype: int
:type citations: List[int] :rtype: int
[ ":", "type", "citations", ":", "List", "[", "int", "]", ":", "rtype", ":", "int" ]
def hIndex(self, citations): """ :type citations: List[int] :rtype: int """ return sum(x >= i + 1 for i, x in enumerate(sorted(citations, reverse=True)))
[ "def", "hIndex", "(", "self", ",", "citations", ")", ":", "return", "sum", "(", "x", ">=", "i", "+", "1", "for", "i", ",", "x", "in", "enumerate", "(", "sorted", "(", "citations", ",", "reverse", "=", "True", ")", ")", ")" ]
https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/h-index.py#L46-L51
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/ultimatelistctrl.py
python
UltimateListItem.Enable
(self, enable=True)
Enables or disables the item. :param `enable`: ``True`` to enable the item, ``False`` to disable it.
Enables or disables the item.
[ "Enables", "or", "disables", "the", "item", "." ]
def Enable(self, enable=True): """ Enables or disables the item. :param `enable`: ``True`` to enable the item, ``False`` to disable it. """ self.Attributes().Enable(enable)
[ "def", "Enable", "(", "self", ",", "enable", "=", "True", ")", ":", "self", ".", "Attributes", "(", ")", ".", "Enable", "(", "enable", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/ultimatelistctrl.py#L1674-L1681
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/richtext.py
python
RichTextObject.SetSameMargins
(*args, **kwargs)
return _richtext.RichTextObject_SetSameMargins(*args, **kwargs)
SetSameMargins(self, int margin)
SetSameMargins(self, int margin)
[ "SetSameMargins", "(", "self", "int", "margin", ")" ]
def SetSameMargins(*args, **kwargs): """SetSameMargins(self, int margin)""" return _richtext.RichTextObject_SetSameMargins(*args, **kwargs)
[ "def", "SetSameMargins", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_richtext", ".", "RichTextObject_SetSameMargins", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/richtext.py#L1329-L1331
giuspen/cherrytree
84712f206478fcf9acf30174009ad28c648c6344
pygtk2/modules/core.py
python
CherryTree.nodes_add_from_plain_text_folder
(self, action)
Add Nodes from Plain Text File(s) in Selected Folder
Add Nodes from Plain Text File(s) in Selected Folder
[ "Add", "Nodes", "from", "Plain", "Text", "File", "(", "s", ")", "in", "Selected", "Folder" ]
def nodes_add_from_plain_text_folder(self, action): """Add Nodes from Plain Text File(s) in Selected Folder""" if not hasattr(self, "ext_plain_import"): self.ext_plain_import = "txt" if cons.IS_WIN_OS: ext_plain_import = support.dialog_img_n_entry(self.window, _("Plain Text Document"), self.ext_plain_import, gtk.STOCK_FILE) if not ext_plain_import: return self.ext_plain_import = ext_plain_import folderpath = support.dialog_folder_select(curr_folder=self.pick_dir_import, parent=self.window) if not folderpath: return self.pick_dir_import = os.path.dirname(folderpath) plain = imports.PlainTextHandler(self) cherrytree_string = plain.get_cherrytree_xml(folderpath=folderpath) self.nodes_add_from_cherrytree_data(cherrytree_string)
[ "def", "nodes_add_from_plain_text_folder", "(", "self", ",", "action", ")", ":", "if", "not", "hasattr", "(", "self", ",", "\"ext_plain_import\"", ")", ":", "self", ".", "ext_plain_import", "=", "\"txt\"", "if", "cons", ".", "IS_WIN_OS", ":", "ext_plain_import", "=", "support", ".", "dialog_img_n_entry", "(", "self", ".", "window", ",", "_", "(", "\"Plain Text Document\"", ")", ",", "self", ".", "ext_plain_import", ",", "gtk", ".", "STOCK_FILE", ")", "if", "not", "ext_plain_import", ":", "return", "self", ".", "ext_plain_import", "=", "ext_plain_import", "folderpath", "=", "support", ".", "dialog_folder_select", "(", "curr_folder", "=", "self", ".", "pick_dir_import", ",", "parent", "=", "self", ".", "window", ")", "if", "not", "folderpath", ":", "return", "self", ".", "pick_dir_import", "=", "os", ".", "path", ".", "dirname", "(", "folderpath", ")", "plain", "=", "imports", ".", "PlainTextHandler", "(", "self", ")", "cherrytree_string", "=", "plain", ".", "get_cherrytree_xml", "(", "folderpath", "=", "folderpath", ")", "self", ".", "nodes_add_from_cherrytree_data", "(", "cherrytree_string", ")" ]
https://github.com/giuspen/cherrytree/blob/84712f206478fcf9acf30174009ad28c648c6344/pygtk2/modules/core.py#L1036-L1049
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/boto/boto/ec2/connection.py
python
EC2Connection.revoke_security_group_deprecated
(self, group_name, src_security_group_name=None, src_security_group_owner_id=None, ip_protocol=None, from_port=None, to_port=None, cidr_ip=None, dry_run=False)
return self.get_status('RevokeSecurityGroupIngress', params)
NOTE: This method uses the old-style request parameters that did not allow a port to be specified when authorizing a group. Remove an existing rule from an existing security group. You need to pass in either src_security_group_name and src_security_group_owner_id OR ip_protocol, from_port, to_port, and cidr_ip. In other words, either you are revoking another group or you are revoking some ip-based rule. :type group_name: string :param group_name: The name of the security group you are removing the rule from. :type src_security_group_name: string :param src_security_group_name: The name of the security group you are revoking access to. :type src_security_group_owner_id: string :param src_security_group_owner_id: The ID of the owner of the security group you are revoking access to. :type ip_protocol: string :param ip_protocol: Either tcp | udp | icmp :type from_port: int :param from_port: The beginning port number you are disabling :type to_port: int :param to_port: The ending port number you are disabling :type to_port: string :param to_port: The CIDR block you are revoking access to. http://goo.gl/Yj5QC :type dry_run: bool :param dry_run: Set to True if the operation should not actually run. :rtype: bool :return: True if successful.
NOTE: This method uses the old-style request parameters that did not allow a port to be specified when authorizing a group.
[ "NOTE", ":", "This", "method", "uses", "the", "old", "-", "style", "request", "parameters", "that", "did", "not", "allow", "a", "port", "to", "be", "specified", "when", "authorizing", "a", "group", "." ]
def revoke_security_group_deprecated(self, group_name, src_security_group_name=None, src_security_group_owner_id=None, ip_protocol=None, from_port=None, to_port=None, cidr_ip=None, dry_run=False): """ NOTE: This method uses the old-style request parameters that did not allow a port to be specified when authorizing a group. Remove an existing rule from an existing security group. You need to pass in either src_security_group_name and src_security_group_owner_id OR ip_protocol, from_port, to_port, and cidr_ip. In other words, either you are revoking another group or you are revoking some ip-based rule. :type group_name: string :param group_name: The name of the security group you are removing the rule from. :type src_security_group_name: string :param src_security_group_name: The name of the security group you are revoking access to. :type src_security_group_owner_id: string :param src_security_group_owner_id: The ID of the owner of the security group you are revoking access to. :type ip_protocol: string :param ip_protocol: Either tcp | udp | icmp :type from_port: int :param from_port: The beginning port number you are disabling :type to_port: int :param to_port: The ending port number you are disabling :type to_port: string :param to_port: The CIDR block you are revoking access to. http://goo.gl/Yj5QC :type dry_run: bool :param dry_run: Set to True if the operation should not actually run. :rtype: bool :return: True if successful. """ params = {'GroupName': group_name} if src_security_group_name: params['SourceSecurityGroupName'] = src_security_group_name if src_security_group_owner_id: params['SourceSecurityGroupOwnerId'] = src_security_group_owner_id if ip_protocol: params['IpProtocol'] = ip_protocol if from_port: params['FromPort'] = from_port if to_port: params['ToPort'] = to_port if cidr_ip: params['CidrIp'] = cidr_ip if dry_run: params['DryRun'] = 'true' return self.get_status('RevokeSecurityGroupIngress', params)
[ "def", "revoke_security_group_deprecated", "(", "self", ",", "group_name", ",", "src_security_group_name", "=", "None", ",", "src_security_group_owner_id", "=", "None", ",", "ip_protocol", "=", "None", ",", "from_port", "=", "None", ",", "to_port", "=", "None", ",", "cidr_ip", "=", "None", ",", "dry_run", "=", "False", ")", ":", "params", "=", "{", "'GroupName'", ":", "group_name", "}", "if", "src_security_group_name", ":", "params", "[", "'SourceSecurityGroupName'", "]", "=", "src_security_group_name", "if", "src_security_group_owner_id", ":", "params", "[", "'SourceSecurityGroupOwnerId'", "]", "=", "src_security_group_owner_id", "if", "ip_protocol", ":", "params", "[", "'IpProtocol'", "]", "=", "ip_protocol", "if", "from_port", ":", "params", "[", "'FromPort'", "]", "=", "from_port", "if", "to_port", ":", "params", "[", "'ToPort'", "]", "=", "to_port", "if", "cidr_ip", ":", "params", "[", "'CidrIp'", "]", "=", "cidr_ip", "if", "dry_run", ":", "params", "[", "'DryRun'", "]", "=", "'true'", "return", "self", ".", "get_status", "(", "'RevokeSecurityGroupIngress'", ",", "params", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/ec2/connection.py#L3231-L3294
s9xie/hed
94fb22f10cbfec8d84fbc0642b224022014b6bd6
scripts/cpp_lint.py
python
ProcessFile
(filename, vlevel, extra_check_functions=[])
Does google-lint on a single file. Args: filename: The name of the file to parse. vlevel: The level of errors to report. Every error of confidence >= verbose_level will be reported. 0 is a good default. extra_check_functions: An array of additional check functions that will be run on each source line. Each function takes 4 arguments: filename, clean_lines, line, error
Does google-lint on a single file.
[ "Does", "google", "-", "lint", "on", "a", "single", "file", "." ]
def ProcessFile(filename, vlevel, extra_check_functions=[]): """Does google-lint on a single file. Args: filename: The name of the file to parse. vlevel: The level of errors to report. Every error of confidence >= verbose_level will be reported. 0 is a good default. extra_check_functions: An array of additional check functions that will be run on each source line. Each function takes 4 arguments: filename, clean_lines, line, error """ _SetVerboseLevel(vlevel) try: # Support the UNIX convention of using "-" for stdin. Note that # we are not opening the file with universal newline support # (which codecs doesn't support anyway), so the resulting lines do # contain trailing '\r' characters if we are reading a file that # has CRLF endings. # If after the split a trailing '\r' is present, it is removed # below. If it is not expected to be present (i.e. os.linesep != # '\r\n' as in Windows), a warning is issued below if this file # is processed. if filename == '-': lines = codecs.StreamReaderWriter(sys.stdin, codecs.getreader('utf8'), codecs.getwriter('utf8'), 'replace').read().split('\n') else: lines = codecs.open(filename, 'r', 'utf8', 'replace').read().split('\n') carriage_return_found = False # Remove trailing '\r'. for linenum in range(len(lines)): if lines[linenum].endswith('\r'): lines[linenum] = lines[linenum].rstrip('\r') carriage_return_found = True except IOError: sys.stderr.write( "Skipping input '%s': Can't open for reading\n" % filename) return # Note, if no dot is found, this will give the entire filename as the ext. file_extension = filename[filename.rfind('.') + 1:] # When reading from stdin, the extension is unknown, so no cpplint tests # should rely on the extension. if filename != '-' and file_extension not in _valid_extensions: sys.stderr.write('Ignoring %s; not a valid file name ' '(%s)\n' % (filename, ', '.join(_valid_extensions))) else: ProcessFileData(filename, file_extension, lines, Error, extra_check_functions) if carriage_return_found and os.linesep != '\r\n': # Use 0 for linenum since outputting only one error for potentially # several lines. Error(filename, 0, 'whitespace/newline', 1, 'One or more unexpected \\r (^M) found;' 'better to use only a \\n') sys.stderr.write('Done processing %s\n' % filename)
[ "def", "ProcessFile", "(", "filename", ",", "vlevel", ",", "extra_check_functions", "=", "[", "]", ")", ":", "_SetVerboseLevel", "(", "vlevel", ")", "try", ":", "# Support the UNIX convention of using \"-\" for stdin. Note that", "# we are not opening the file with universal newline support", "# (which codecs doesn't support anyway), so the resulting lines do", "# contain trailing '\\r' characters if we are reading a file that", "# has CRLF endings.", "# If after the split a trailing '\\r' is present, it is removed", "# below. If it is not expected to be present (i.e. os.linesep !=", "# '\\r\\n' as in Windows), a warning is issued below if this file", "# is processed.", "if", "filename", "==", "'-'", ":", "lines", "=", "codecs", ".", "StreamReaderWriter", "(", "sys", ".", "stdin", ",", "codecs", ".", "getreader", "(", "'utf8'", ")", ",", "codecs", ".", "getwriter", "(", "'utf8'", ")", ",", "'replace'", ")", ".", "read", "(", ")", ".", "split", "(", "'\\n'", ")", "else", ":", "lines", "=", "codecs", ".", "open", "(", "filename", ",", "'r'", ",", "'utf8'", ",", "'replace'", ")", ".", "read", "(", ")", ".", "split", "(", "'\\n'", ")", "carriage_return_found", "=", "False", "# Remove trailing '\\r'.", "for", "linenum", "in", "range", "(", "len", "(", "lines", ")", ")", ":", "if", "lines", "[", "linenum", "]", ".", "endswith", "(", "'\\r'", ")", ":", "lines", "[", "linenum", "]", "=", "lines", "[", "linenum", "]", ".", "rstrip", "(", "'\\r'", ")", "carriage_return_found", "=", "True", "except", "IOError", ":", "sys", ".", "stderr", ".", "write", "(", "\"Skipping input '%s': Can't open for reading\\n\"", "%", "filename", ")", "return", "# Note, if no dot is found, this will give the entire filename as the ext.", "file_extension", "=", "filename", "[", "filename", ".", "rfind", "(", "'.'", ")", "+", "1", ":", "]", "# When reading from stdin, the extension is unknown, so no cpplint tests", "# should rely on the extension.", "if", "filename", "!=", "'-'", "and", "file_extension", "not", "in", "_valid_extensions", ":", "sys", ".", "stderr", ".", "write", "(", "'Ignoring %s; not a valid file name '", "'(%s)\\n'", "%", "(", "filename", ",", "', '", ".", "join", "(", "_valid_extensions", ")", ")", ")", "else", ":", "ProcessFileData", "(", "filename", ",", "file_extension", ",", "lines", ",", "Error", ",", "extra_check_functions", ")", "if", "carriage_return_found", "and", "os", ".", "linesep", "!=", "'\\r\\n'", ":", "# Use 0 for linenum since outputting only one error for potentially", "# several lines.", "Error", "(", "filename", ",", "0", ",", "'whitespace/newline'", ",", "1", ",", "'One or more unexpected \\\\r (^M) found;'", "'better to use only a \\\\n'", ")", "sys", ".", "stderr", ".", "write", "(", "'Done processing %s\\n'", "%", "filename", ")" ]
https://github.com/s9xie/hed/blob/94fb22f10cbfec8d84fbc0642b224022014b6bd6/scripts/cpp_lint.py#L4689-L4754
yrnkrn/zapcc
c6a8aa30006d997eff0d60fd37b0e62b8aa0ea50
tools/clang/utils/check_cfc/check_cfc.py
python
flip_dash_g
(args)
Search for -g in args. If it exists then return args without. If not then add it.
Search for -g in args. If it exists then return args without. If not then add it.
[ "Search", "for", "-", "g", "in", "args", ".", "If", "it", "exists", "then", "return", "args", "without", ".", "If", "not", "then", "add", "it", "." ]
def flip_dash_g(args): """Search for -g in args. If it exists then return args without. If not then add it.""" if '-g' in args: # Return args without any -g return [x for x in args if x != '-g'] else: # No -g, add one return args + ['-g']
[ "def", "flip_dash_g", "(", "args", ")", ":", "if", "'-g'", "in", "args", ":", "# Return args without any -g", "return", "[", "x", "for", "x", "in", "args", "if", "x", "!=", "'-g'", "]", "else", ":", "# No -g, add one", "return", "args", "+", "[", "'-g'", "]" ]
https://github.com/yrnkrn/zapcc/blob/c6a8aa30006d997eff0d60fd37b0e62b8aa0ea50/tools/clang/utils/check_cfc/check_cfc.py#L108-L116
google/filament
d21f092645b8e1e312307cbf89f1484891347c63
third_party/libassimp/port/PyAssimp/scripts/transformations.py
python
quaternion_matrix
(quaternion)
return numpy.array(( (1.0-q[1, 1]-q[2, 2], q[0, 1]-q[2, 3], q[0, 2]+q[1, 3], 0.0), ( q[0, 1]+q[2, 3], 1.0-q[0, 0]-q[2, 2], q[1, 2]-q[0, 3], 0.0), ( q[0, 2]-q[1, 3], q[1, 2]+q[0, 3], 1.0-q[0, 0]-q[1, 1], 0.0), ( 0.0, 0.0, 0.0, 1.0) ), dtype=numpy.float64)
Return homogeneous rotation matrix from quaternion. >>> R = quaternion_matrix([0.06146124, 0, 0, 0.99810947]) >>> numpy.allclose(R, rotation_matrix(0.123, (1, 0, 0))) True
Return homogeneous rotation matrix from quaternion.
[ "Return", "homogeneous", "rotation", "matrix", "from", "quaternion", "." ]
def quaternion_matrix(quaternion): """Return homogeneous rotation matrix from quaternion. >>> R = quaternion_matrix([0.06146124, 0, 0, 0.99810947]) >>> numpy.allclose(R, rotation_matrix(0.123, (1, 0, 0))) True """ q = numpy.array(quaternion[:4], dtype=numpy.float64, copy=True) nq = numpy.dot(q, q) if nq < _EPS: return numpy.identity(4) q *= math.sqrt(2.0 / nq) q = numpy.outer(q, q) return numpy.array(( (1.0-q[1, 1]-q[2, 2], q[0, 1]-q[2, 3], q[0, 2]+q[1, 3], 0.0), ( q[0, 1]+q[2, 3], 1.0-q[0, 0]-q[2, 2], q[1, 2]-q[0, 3], 0.0), ( q[0, 2]-q[1, 3], q[1, 2]+q[0, 3], 1.0-q[0, 0]-q[1, 1], 0.0), ( 0.0, 0.0, 0.0, 1.0) ), dtype=numpy.float64)
[ "def", "quaternion_matrix", "(", "quaternion", ")", ":", "q", "=", "numpy", ".", "array", "(", "quaternion", "[", ":", "4", "]", ",", "dtype", "=", "numpy", ".", "float64", ",", "copy", "=", "True", ")", "nq", "=", "numpy", ".", "dot", "(", "q", ",", "q", ")", "if", "nq", "<", "_EPS", ":", "return", "numpy", ".", "identity", "(", "4", ")", "q", "*=", "math", ".", "sqrt", "(", "2.0", "/", "nq", ")", "q", "=", "numpy", ".", "outer", "(", "q", ",", "q", ")", "return", "numpy", ".", "array", "(", "(", "(", "1.0", "-", "q", "[", "1", ",", "1", "]", "-", "q", "[", "2", ",", "2", "]", ",", "q", "[", "0", ",", "1", "]", "-", "q", "[", "2", ",", "3", "]", ",", "q", "[", "0", ",", "2", "]", "+", "q", "[", "1", ",", "3", "]", ",", "0.0", ")", ",", "(", "q", "[", "0", ",", "1", "]", "+", "q", "[", "2", ",", "3", "]", ",", "1.0", "-", "q", "[", "0", ",", "0", "]", "-", "q", "[", "2", ",", "2", "]", ",", "q", "[", "1", ",", "2", "]", "-", "q", "[", "0", ",", "3", "]", ",", "0.0", ")", ",", "(", "q", "[", "0", ",", "2", "]", "-", "q", "[", "1", ",", "3", "]", ",", "q", "[", "1", ",", "2", "]", "+", "q", "[", "0", ",", "3", "]", ",", "1.0", "-", "q", "[", "0", ",", "0", "]", "-", "q", "[", "1", ",", "1", "]", ",", "0.0", ")", ",", "(", "0.0", ",", "0.0", ",", "0.0", ",", "1.0", ")", ")", ",", "dtype", "=", "numpy", ".", "float64", ")" ]
https://github.com/google/filament/blob/d21f092645b8e1e312307cbf89f1484891347c63/third_party/libassimp/port/PyAssimp/scripts/transformations.py#L1174-L1193
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/plat-mac/lib-scriptpackages/CodeWarrior/Standard_Suite.py
python
Standard_Suite_Events.count
(self, _object, _attributes={}, **_arguments)
count: return the number of elements of a particular class within an object Required argument: the object whose elements are to be counted Keyword argument each: the class of the elements to be counted. Keyword 'each' is optional in AppleScript Keyword argument _attributes: AppleEvent attribute dictionary Returns: the number of elements
count: return the number of elements of a particular class within an object Required argument: the object whose elements are to be counted Keyword argument each: the class of the elements to be counted. Keyword 'each' is optional in AppleScript Keyword argument _attributes: AppleEvent attribute dictionary Returns: the number of elements
[ "count", ":", "return", "the", "number", "of", "elements", "of", "a", "particular", "class", "within", "an", "object", "Required", "argument", ":", "the", "object", "whose", "elements", "are", "to", "be", "counted", "Keyword", "argument", "each", ":", "the", "class", "of", "the", "elements", "to", "be", "counted", ".", "Keyword", "each", "is", "optional", "in", "AppleScript", "Keyword", "argument", "_attributes", ":", "AppleEvent", "attribute", "dictionary", "Returns", ":", "the", "number", "of", "elements" ]
def count(self, _object, _attributes={}, **_arguments): """count: return the number of elements of a particular class within an object Required argument: the object whose elements are to be counted Keyword argument each: the class of the elements to be counted. Keyword 'each' is optional in AppleScript Keyword argument _attributes: AppleEvent attribute dictionary Returns: the number of elements """ _code = 'core' _subcode = 'cnte' aetools.keysubst(_arguments, self._argmap_count) _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", "count", "(", "self", ",", "_object", ",", "_attributes", "=", "{", "}", ",", "*", "*", "_arguments", ")", ":", "_code", "=", "'core'", "_subcode", "=", "'cnte'", "aetools", ".", "keysubst", "(", "_arguments", ",", "self", ".", "_argmap_count", ")", "_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/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/plat-mac/lib-scriptpackages/CodeWarrior/Standard_Suite.py#L48-L68
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/distributions/python/ops/autoregressive.py
python
Autoregressive.__init__
(self, distribution_fn, sample0=None, num_steps=None, validate_args=False, allow_nan_stats=True, name="Autoregressive")
Construct an `Autoregressive` distribution. Args: distribution_fn: Python `callable` which constructs a `tfp.distributions.Distribution`-like instance from a `Tensor` (e.g., `sample0`). The function must respect the "autoregressive property", i.e., there exists a permutation of event such that each coordinate is a diffeomorphic function of on preceding coordinates. sample0: Initial input to `distribution_fn`; used to build the distribution in `__init__` which in turn specifies this distribution's properties, e.g., `event_shape`, `batch_shape`, `dtype`. If unspecified, then `distribution_fn` should be default constructable. num_steps: Number of times `distribution_fn` is composed from samples, e.g., `num_steps=2` implies `distribution_fn(distribution_fn(sample0).sample(n)).sample()`. validate_args: Python `bool`. Whether to validate input with asserts. If `validate_args` is `False`, and the inputs are invalid, correct behavior is not guaranteed. allow_nan_stats: Python `bool`, default `True`. When `True`, statistics (e.g., mean, mode, variance) use the value "`NaN`" to indicate the result is undefined. When `False`, an exception is raised if one or more of the statistic's batch members are undefined. name: Python `str` name prefixed to Ops created by this class. Default value: "Autoregressive". Raises: ValueError: if `num_steps` and `distribution_fn(sample0).event_shape.num_elements()` are both `None`. ValueError: if `num_steps < 1`.
Construct an `Autoregressive` distribution.
[ "Construct", "an", "Autoregressive", "distribution", "." ]
def __init__(self, distribution_fn, sample0=None, num_steps=None, validate_args=False, allow_nan_stats=True, name="Autoregressive"): """Construct an `Autoregressive` distribution. Args: distribution_fn: Python `callable` which constructs a `tfp.distributions.Distribution`-like instance from a `Tensor` (e.g., `sample0`). The function must respect the "autoregressive property", i.e., there exists a permutation of event such that each coordinate is a diffeomorphic function of on preceding coordinates. sample0: Initial input to `distribution_fn`; used to build the distribution in `__init__` which in turn specifies this distribution's properties, e.g., `event_shape`, `batch_shape`, `dtype`. If unspecified, then `distribution_fn` should be default constructable. num_steps: Number of times `distribution_fn` is composed from samples, e.g., `num_steps=2` implies `distribution_fn(distribution_fn(sample0).sample(n)).sample()`. validate_args: Python `bool`. Whether to validate input with asserts. If `validate_args` is `False`, and the inputs are invalid, correct behavior is not guaranteed. allow_nan_stats: Python `bool`, default `True`. When `True`, statistics (e.g., mean, mode, variance) use the value "`NaN`" to indicate the result is undefined. When `False`, an exception is raised if one or more of the statistic's batch members are undefined. name: Python `str` name prefixed to Ops created by this class. Default value: "Autoregressive". Raises: ValueError: if `num_steps` and `distribution_fn(sample0).event_shape.num_elements()` are both `None`. ValueError: if `num_steps < 1`. """ parameters = dict(locals()) with ops.name_scope(name) as name: self._distribution_fn = distribution_fn self._sample0 = sample0 self._distribution0 = (distribution_fn() if sample0 is None else distribution_fn(sample0)) if num_steps is None: num_steps = self._distribution0.event_shape.num_elements() if num_steps is None: raise ValueError("distribution_fn must generate a distribution " "with fully known `event_shape`.") if num_steps < 1: raise ValueError("num_steps ({}) must be at least 1.".format(num_steps)) self._num_steps = num_steps super(Autoregressive, self).__init__( dtype=self._distribution0.dtype, reparameterization_type=self._distribution0.reparameterization_type, validate_args=validate_args, allow_nan_stats=allow_nan_stats, parameters=parameters, graph_parents=self._distribution0._graph_parents, # pylint: disable=protected-access name=name)
[ "def", "__init__", "(", "self", ",", "distribution_fn", ",", "sample0", "=", "None", ",", "num_steps", "=", "None", ",", "validate_args", "=", "False", ",", "allow_nan_stats", "=", "True", ",", "name", "=", "\"Autoregressive\"", ")", ":", "parameters", "=", "dict", "(", "locals", "(", ")", ")", "with", "ops", ".", "name_scope", "(", "name", ")", "as", "name", ":", "self", ".", "_distribution_fn", "=", "distribution_fn", "self", ".", "_sample0", "=", "sample0", "self", ".", "_distribution0", "=", "(", "distribution_fn", "(", ")", "if", "sample0", "is", "None", "else", "distribution_fn", "(", "sample0", ")", ")", "if", "num_steps", "is", "None", ":", "num_steps", "=", "self", ".", "_distribution0", ".", "event_shape", ".", "num_elements", "(", ")", "if", "num_steps", "is", "None", ":", "raise", "ValueError", "(", "\"distribution_fn must generate a distribution \"", "\"with fully known `event_shape`.\"", ")", "if", "num_steps", "<", "1", ":", "raise", "ValueError", "(", "\"num_steps ({}) must be at least 1.\"", ".", "format", "(", "num_steps", ")", ")", "self", ".", "_num_steps", "=", "num_steps", "super", "(", "Autoregressive", ",", "self", ")", ".", "__init__", "(", "dtype", "=", "self", ".", "_distribution0", ".", "dtype", ",", "reparameterization_type", "=", "self", ".", "_distribution0", ".", "reparameterization_type", ",", "validate_args", "=", "validate_args", ",", "allow_nan_stats", "=", "allow_nan_stats", ",", "parameters", "=", "parameters", ",", "graph_parents", "=", "self", ".", "_distribution0", ".", "_graph_parents", ",", "# pylint: disable=protected-access", "name", "=", "name", ")" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/distributions/python/ops/autoregressive.py#L120-L178
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_controls.py
python
ToolBarBase.Realize
(*args, **kwargs)
return _controls_.ToolBarBase_Realize(*args, **kwargs)
Realize(self) -> bool
Realize(self) -> bool
[ "Realize", "(", "self", ")", "-", ">", "bool" ]
def Realize(*args, **kwargs): """Realize(self) -> bool""" return _controls_.ToolBarBase_Realize(*args, **kwargs)
[ "def", "Realize", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "ToolBarBase_Realize", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_controls.py#L3787-L3789
wy1iu/LargeMargin_Softmax_Loss
c3e9f20e4f16e2b4daf7d358a614366b9b39a6ec
scripts/cpp_lint.py
python
CheckForFunctionLengths
(filename, clean_lines, linenum, function_state, error)
Reports for long function bodies. For an overview why this is done, see: http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Write_Short_Functions Uses a simplistic algorithm assuming other style guidelines (especially spacing) are followed. Only checks unindented functions, so class members are unchecked. Trivial bodies are unchecked, so constructors with huge initializer lists may be missed. Blank/comment lines are not counted so as to avoid encouraging the removal of vertical space and comments just to get through a lint check. NOLINT *on the last line of a function* disables this check. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. function_state: Current function name and lines in body so far. error: The function to call with any errors found.
Reports for long function bodies.
[ "Reports", "for", "long", "function", "bodies", "." ]
def CheckForFunctionLengths(filename, clean_lines, linenum, function_state, error): """Reports for long function bodies. For an overview why this is done, see: http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Write_Short_Functions Uses a simplistic algorithm assuming other style guidelines (especially spacing) are followed. Only checks unindented functions, so class members are unchecked. Trivial bodies are unchecked, so constructors with huge initializer lists may be missed. Blank/comment lines are not counted so as to avoid encouraging the removal of vertical space and comments just to get through a lint check. NOLINT *on the last line of a function* disables this check. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. function_state: Current function name and lines in body so far. error: The function to call with any errors found. """ lines = clean_lines.lines line = lines[linenum] raw = clean_lines.raw_lines raw_line = raw[linenum] joined_line = '' starting_func = False regexp = r'(\w(\w|::|\*|\&|\s)*)\(' # decls * & space::name( ... match_result = Match(regexp, line) if match_result: # If the name is all caps and underscores, figure it's a macro and # ignore it, unless it's TEST or TEST_F. function_name = match_result.group(1).split()[-1] if function_name == 'TEST' or function_name == 'TEST_F' or ( not Match(r'[A-Z_]+$', function_name)): starting_func = True if starting_func: body_found = False for start_linenum in xrange(linenum, clean_lines.NumLines()): start_line = lines[start_linenum] joined_line += ' ' + start_line.lstrip() if Search(r'(;|})', start_line): # Declarations and trivial functions body_found = True break # ... ignore elif Search(r'{', start_line): body_found = True function = Search(r'((\w|:)*)\(', line).group(1) if Match(r'TEST', function): # Handle TEST... macros parameter_regexp = Search(r'(\(.*\))', joined_line) if parameter_regexp: # Ignore bad syntax function += parameter_regexp.group(1) else: function += '()' function_state.Begin(function) break if not body_found: # No body for the function (or evidence of a non-function) was found. error(filename, linenum, 'readability/fn_size', 5, 'Lint failed to find start of function body.') elif Match(r'^\}\s*$', line): # function end function_state.Check(error, filename, linenum) function_state.End() elif not Match(r'^\s*$', line): function_state.Count()
[ "def", "CheckForFunctionLengths", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "function_state", ",", "error", ")", ":", "lines", "=", "clean_lines", ".", "lines", "line", "=", "lines", "[", "linenum", "]", "raw", "=", "clean_lines", ".", "raw_lines", "raw_line", "=", "raw", "[", "linenum", "]", "joined_line", "=", "''", "starting_func", "=", "False", "regexp", "=", "r'(\\w(\\w|::|\\*|\\&|\\s)*)\\('", "# decls * & space::name( ...", "match_result", "=", "Match", "(", "regexp", ",", "line", ")", "if", "match_result", ":", "# If the name is all caps and underscores, figure it's a macro and", "# ignore it, unless it's TEST or TEST_F.", "function_name", "=", "match_result", ".", "group", "(", "1", ")", ".", "split", "(", ")", "[", "-", "1", "]", "if", "function_name", "==", "'TEST'", "or", "function_name", "==", "'TEST_F'", "or", "(", "not", "Match", "(", "r'[A-Z_]+$'", ",", "function_name", ")", ")", ":", "starting_func", "=", "True", "if", "starting_func", ":", "body_found", "=", "False", "for", "start_linenum", "in", "xrange", "(", "linenum", ",", "clean_lines", ".", "NumLines", "(", ")", ")", ":", "start_line", "=", "lines", "[", "start_linenum", "]", "joined_line", "+=", "' '", "+", "start_line", ".", "lstrip", "(", ")", "if", "Search", "(", "r'(;|})'", ",", "start_line", ")", ":", "# Declarations and trivial functions", "body_found", "=", "True", "break", "# ... ignore", "elif", "Search", "(", "r'{'", ",", "start_line", ")", ":", "body_found", "=", "True", "function", "=", "Search", "(", "r'((\\w|:)*)\\('", ",", "line", ")", ".", "group", "(", "1", ")", "if", "Match", "(", "r'TEST'", ",", "function", ")", ":", "# Handle TEST... macros", "parameter_regexp", "=", "Search", "(", "r'(\\(.*\\))'", ",", "joined_line", ")", "if", "parameter_regexp", ":", "# Ignore bad syntax", "function", "+=", "parameter_regexp", ".", "group", "(", "1", ")", "else", ":", "function", "+=", "'()'", "function_state", ".", "Begin", "(", "function", ")", "break", "if", "not", "body_found", ":", "# No body for the function (or evidence of a non-function) was found.", "error", "(", "filename", ",", "linenum", ",", "'readability/fn_size'", ",", "5", ",", "'Lint failed to find start of function body.'", ")", "elif", "Match", "(", "r'^\\}\\s*$'", ",", "line", ")", ":", "# function end", "function_state", ".", "Check", "(", "error", ",", "filename", ",", "linenum", ")", "function_state", ".", "End", "(", ")", "elif", "not", "Match", "(", "r'^\\s*$'", ",", "line", ")", ":", "function_state", ".", "Count", "(", ")" ]
https://github.com/wy1iu/LargeMargin_Softmax_Loss/blob/c3e9f20e4f16e2b4daf7d358a614366b9b39a6ec/scripts/cpp_lint.py#L2384-L2451
sc0ty/subsync
be5390d00ff475b6543eb0140c7e65b34317d95b
assets/dictmk/scripts/wikt2dict/article.py
python
ArticleParser.add_features_to_word_pair
(self, pair)
return pair
Adding features to translation pairs
Adding features to translation pairs
[ "Adding", "features", "to", "translation", "pairs" ]
def add_features_to_word_pair(self, pair): """ Adding features to translation pairs """ # article of the word exists if pair[3] in self.titles: pair.append("has_article") return pair
[ "def", "add_features_to_word_pair", "(", "self", ",", "pair", ")", ":", "# article of the word exists", "if", "pair", "[", "3", "]", "in", "self", ".", "titles", ":", "pair", ".", "append", "(", "\"has_article\"", ")", "return", "pair" ]
https://github.com/sc0ty/subsync/blob/be5390d00ff475b6543eb0140c7e65b34317d95b/assets/dictmk/scripts/wikt2dict/article.py#L131-L137
smilehao/xlua-framework
a03801538be2b0e92d39332d445b22caca1ef61f
ConfigData/trunk/tools/protobuf-2.5.0/protobuf-2.5.0/python/build/lib/google/protobuf/descriptor.py
python
FileDescriptor.__init__
(self, name, package, options=None, serialized_pb=None)
Constructor.
Constructor.
[ "Constructor", "." ]
def __init__(self, name, package, options=None, serialized_pb=None): """Constructor.""" super(FileDescriptor, self).__init__(options, 'FileOptions') self.message_types_by_name = {} self.name = name self.package = package self.serialized_pb = serialized_pb if (api_implementation.Type() == 'cpp' and self.serialized_pb is not None): if api_implementation.Version() == 2: _message.BuildFile(self.serialized_pb) else: cpp_message.BuildFile(self.serialized_pb)
[ "def", "__init__", "(", "self", ",", "name", ",", "package", ",", "options", "=", "None", ",", "serialized_pb", "=", "None", ")", ":", "super", "(", "FileDescriptor", ",", "self", ")", ".", "__init__", "(", "options", ",", "'FileOptions'", ")", "self", ".", "message_types_by_name", "=", "{", "}", "self", ".", "name", "=", "name", "self", ".", "package", "=", "package", "self", ".", "serialized_pb", "=", "serialized_pb", "if", "(", "api_implementation", ".", "Type", "(", ")", "==", "'cpp'", "and", "self", ".", "serialized_pb", "is", "not", "None", ")", ":", "if", "api_implementation", ".", "Version", "(", ")", "==", "2", ":", "_message", ".", "BuildFile", "(", "self", ".", "serialized_pb", ")", "else", ":", "cpp_message", ".", "BuildFile", "(", "self", ".", "serialized_pb", ")" ]
https://github.com/smilehao/xlua-framework/blob/a03801538be2b0e92d39332d445b22caca1ef61f/ConfigData/trunk/tools/protobuf-2.5.0/protobuf-2.5.0/python/build/lib/google/protobuf/descriptor.py#L654-L667
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/Jinja2/py2/jinja2/visitor.py
python
NodeVisitor.get_visitor
(self, node)
return getattr(self, method, None)
Return the visitor function for this node or `None` if no visitor exists for this node. In that case the generic visit function is used instead.
Return the visitor function for this node or `None` if no visitor exists for this node. In that case the generic visit function is used instead.
[ "Return", "the", "visitor", "function", "for", "this", "node", "or", "None", "if", "no", "visitor", "exists", "for", "this", "node", ".", "In", "that", "case", "the", "generic", "visit", "function", "is", "used", "instead", "." ]
def get_visitor(self, node): """Return the visitor function for this node or `None` if no visitor exists for this node. In that case the generic visit function is used instead. """ method = "visit_" + node.__class__.__name__ return getattr(self, method, None)
[ "def", "get_visitor", "(", "self", ",", "node", ")", ":", "method", "=", "\"visit_\"", "+", "node", ".", "__class__", ".", "__name__", "return", "getattr", "(", "self", ",", "method", ",", "None", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/Jinja2/py2/jinja2/visitor.py#L20-L26
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/s3transfer/copies.py
python
CopyObjectTask._main
(self, client, copy_source, bucket, key, extra_args, callbacks, size)
:param client: The client to use when calling PutObject :param copy_source: The CopySource parameter to use :param bucket: The name of the bucket to copy to :param key: The name of the key to copy to :param extra_args: A dictionary of any extra arguments that may be used in the upload. :param callbacks: List of callbacks to call after copy :param size: The size of the transfer. This value is passed into the callbacks
:param client: The client to use when calling PutObject :param copy_source: The CopySource parameter to use :param bucket: The name of the bucket to copy to :param key: The name of the key to copy to :param extra_args: A dictionary of any extra arguments that may be used in the upload. :param callbacks: List of callbacks to call after copy :param size: The size of the transfer. This value is passed into the callbacks
[ ":", "param", "client", ":", "The", "client", "to", "use", "when", "calling", "PutObject", ":", "param", "copy_source", ":", "The", "CopySource", "parameter", "to", "use", ":", "param", "bucket", ":", "The", "name", "of", "the", "bucket", "to", "copy", "to", ":", "param", "key", ":", "The", "name", "of", "the", "key", "to", "copy", "to", ":", "param", "extra_args", ":", "A", "dictionary", "of", "any", "extra", "arguments", "that", "may", "be", "used", "in", "the", "upload", ".", ":", "param", "callbacks", ":", "List", "of", "callbacks", "to", "call", "after", "copy", ":", "param", "size", ":", "The", "size", "of", "the", "transfer", ".", "This", "value", "is", "passed", "into", "the", "callbacks" ]
def _main(self, client, copy_source, bucket, key, extra_args, callbacks, size): """ :param client: The client to use when calling PutObject :param copy_source: The CopySource parameter to use :param bucket: The name of the bucket to copy to :param key: The name of the key to copy to :param extra_args: A dictionary of any extra arguments that may be used in the upload. :param callbacks: List of callbacks to call after copy :param size: The size of the transfer. This value is passed into the callbacks """ client.copy_object( CopySource=copy_source, Bucket=bucket, Key=key, **extra_args) for callback in callbacks: callback(bytes_transferred=size)
[ "def", "_main", "(", "self", ",", "client", ",", "copy_source", ",", "bucket", ",", "key", ",", "extra_args", ",", "callbacks", ",", "size", ")", ":", "client", ".", "copy_object", "(", "CopySource", "=", "copy_source", ",", "Bucket", "=", "bucket", ",", "Key", "=", "key", ",", "*", "*", "extra_args", ")", "for", "callback", "in", "callbacks", ":", "callback", "(", "bytes_transferred", "=", "size", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/s3transfer/copies.py#L272-L289
Harick1/caffe-yolo
eea92bf3ddfe4d0ff6b0b3ba9b15c029a83ed9a3
scripts/cpp_lint.py
python
_SetCountingStyle
(level)
Sets the module's counting options.
Sets the module's counting options.
[ "Sets", "the", "module", "s", "counting", "options", "." ]
def _SetCountingStyle(level): """Sets the module's counting options.""" _cpplint_state.SetCountingStyle(level)
[ "def", "_SetCountingStyle", "(", "level", ")", ":", "_cpplint_state", ".", "SetCountingStyle", "(", "level", ")" ]
https://github.com/Harick1/caffe-yolo/blob/eea92bf3ddfe4d0ff6b0b3ba9b15c029a83ed9a3/scripts/cpp_lint.py#L787-L789
bumptop/BumpTop
466d23597a07ae738f4265262fa01087fc6e257c
trunk/win/Source/bin/jinja2/filters.py
python
do_sort
(value, case_sensitive=False)
return sorted(seq, key=sort_func)
Sort an iterable. If the iterable is made of strings the second parameter can be used to control the case sensitiveness of the comparison which is disabled by default. .. sourcecode:: jinja {% for item in iterable|sort %} ... {% endfor %}
Sort an iterable. If the iterable is made of strings the second parameter can be used to control the case sensitiveness of the comparison which is disabled by default.
[ "Sort", "an", "iterable", ".", "If", "the", "iterable", "is", "made", "of", "strings", "the", "second", "parameter", "can", "be", "used", "to", "control", "the", "case", "sensitiveness", "of", "the", "comparison", "which", "is", "disabled", "by", "default", "." ]
def do_sort(value, case_sensitive=False): """Sort an iterable. If the iterable is made of strings the second parameter can be used to control the case sensitiveness of the comparison which is disabled by default. .. sourcecode:: jinja {% for item in iterable|sort %} ... {% endfor %} """ if not case_sensitive: def sort_func(item): if isinstance(item, basestring): item = item.lower() return item else: sort_func = None return sorted(seq, key=sort_func)
[ "def", "do_sort", "(", "value", ",", "case_sensitive", "=", "False", ")", ":", "if", "not", "case_sensitive", ":", "def", "sort_func", "(", "item", ")", ":", "if", "isinstance", "(", "item", ",", "basestring", ")", ":", "item", "=", "item", ".", "lower", "(", ")", "return", "item", "else", ":", "sort_func", "=", "None", "return", "sorted", "(", "seq", ",", "key", "=", "sort_func", ")" ]
https://github.com/bumptop/BumpTop/blob/466d23597a07ae738f4265262fa01087fc6e257c/trunk/win/Source/bin/jinja2/filters.py#L172-L190
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/ops/sparse_ops.py
python
_add_many_sparse_to_tensors_map
(sp_input, container=None, shared_name=None, name=None)
return gen_sparse_ops._add_many_sparse_to_tensors_map( sp_input.indices, sp_input.values, sp_input.dense_shape, container=container, shared_name=shared_name, name=name)
Add a minibatch `SparseTensor` to a `SparseTensorsMap`, return `N` handles. The `SparseTensor` must have rank `R` greater than 1, and the first dimension is treated as the minibatch dimension. Elements of the `SparseTensor` must be sorted in increasing order of this first dimension. The serialized `SparseTensor` objects going into each row of the output `Tensor` will have rank `R-1`. The minibatch size `N` is extracted from `sparse_shape[0]`. Args: sp_input: The input rank `R` `SparseTensor`. container: The container for the underlying `SparseTensorsMap` (optional). shared_name: The shared name for the underlying `SparseTensorsMap` (optional, defaults to the name of the newly created op). name: A name prefix for the returned tensors (optional). Returns: A string matrix (2-D `Tensor`) with `N` rows and `1` column. Each row represents a unique handle to a `SparseTensor` stored by the `SparseTensorMap` underlying this op. Raises: TypeError: If `sp_input` is not a `SparseTensor`.
Add a minibatch `SparseTensor` to a `SparseTensorsMap`, return `N` handles.
[ "Add", "a", "minibatch", "SparseTensor", "to", "a", "SparseTensorsMap", "return", "N", "handles", "." ]
def _add_many_sparse_to_tensors_map(sp_input, container=None, shared_name=None, name=None): """Add a minibatch `SparseTensor` to a `SparseTensorsMap`, return `N` handles. The `SparseTensor` must have rank `R` greater than 1, and the first dimension is treated as the minibatch dimension. Elements of the `SparseTensor` must be sorted in increasing order of this first dimension. The serialized `SparseTensor` objects going into each row of the output `Tensor` will have rank `R-1`. The minibatch size `N` is extracted from `sparse_shape[0]`. Args: sp_input: The input rank `R` `SparseTensor`. container: The container for the underlying `SparseTensorsMap` (optional). shared_name: The shared name for the underlying `SparseTensorsMap` (optional, defaults to the name of the newly created op). name: A name prefix for the returned tensors (optional). Returns: A string matrix (2-D `Tensor`) with `N` rows and `1` column. Each row represents a unique handle to a `SparseTensor` stored by the `SparseTensorMap` underlying this op. Raises: TypeError: If `sp_input` is not a `SparseTensor`. """ sp_input = _convert_to_sparse_tensor(sp_input) return gen_sparse_ops._add_many_sparse_to_tensors_map( sp_input.indices, sp_input.values, sp_input.dense_shape, container=container, shared_name=shared_name, name=name)
[ "def", "_add_many_sparse_to_tensors_map", "(", "sp_input", ",", "container", "=", "None", ",", "shared_name", "=", "None", ",", "name", "=", "None", ")", ":", "sp_input", "=", "_convert_to_sparse_tensor", "(", "sp_input", ")", "return", "gen_sparse_ops", ".", "_add_many_sparse_to_tensors_map", "(", "sp_input", ".", "indices", ",", "sp_input", ".", "values", ",", "sp_input", ".", "dense_shape", ",", "container", "=", "container", ",", "shared_name", "=", "shared_name", ",", "name", "=", "name", ")" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/ops/sparse_ops.py#L1923-L1954
google/fhir
d77f57706c1a168529b0b87ca7ccb1c0113e83c2
py/google/fhir/json_format/wrappers/_primitive_wrappers.py
python
PrimitiveWrapper.__init__
(self, wrapped: message.Message, unused_context: Context)
Initializes a new PrimitiveWrapper with wrapped. Args: wrapped: The primitive message to wrap.
Initializes a new PrimitiveWrapper with wrapped.
[ "Initializes", "a", "new", "PrimitiveWrapper", "with", "wrapped", "." ]
def __init__(self, wrapped: message.Message, unused_context: Context) -> None: """Initializes a new PrimitiveWrapper with wrapped. Args: wrapped: The primitive message to wrap. """ self.wrapped = wrapped
[ "def", "__init__", "(", "self", ",", "wrapped", ":", "message", ".", "Message", ",", "unused_context", ":", "Context", ")", "->", "None", ":", "self", ".", "wrapped", "=", "wrapped" ]
https://github.com/google/fhir/blob/d77f57706c1a168529b0b87ca7ccb1c0113e83c2/py/google/fhir/json_format/wrappers/_primitive_wrappers.py#L202-L208
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_core.py
python
Window.SetRect
(*args, **kwargs)
return _core_.Window_SetRect(*args, **kwargs)
SetRect(self, Rect rect, int sizeFlags=SIZE_AUTO) Sets the position and size of the window in pixels using a wx.Rect.
SetRect(self, Rect rect, int sizeFlags=SIZE_AUTO)
[ "SetRect", "(", "self", "Rect", "rect", "int", "sizeFlags", "=", "SIZE_AUTO", ")" ]
def SetRect(*args, **kwargs): """ SetRect(self, Rect rect, int sizeFlags=SIZE_AUTO) Sets the position and size of the window in pixels using a wx.Rect. """ return _core_.Window_SetRect(*args, **kwargs)
[ "def", "SetRect", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "Window_SetRect", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L9357-L9363
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/opt/python/training/agn_optimizer.py
python
AGNOptimizer.__init__
(self, optimizer, num_worker, custom_getter, communication_period=10, use_locking=True, name='AGNOptimizer')
Construct a new AGN optimizer. Args: optimizer: input optimizer, can be sgd/momentum/adam etc. num_worker: The number of workers custom_getter: The AGNCustomGetter communication_period: An int point value to controls the frequency of the communication between every worker and the ps. use_locking: If True use locks for update operations. name: Optional name prefix for the operations created when applying gradients. Defaults to "AGNOptimizer".
Construct a new AGN optimizer.
[ "Construct", "a", "new", "AGN", "optimizer", "." ]
def __init__(self, optimizer, num_worker, custom_getter, communication_period=10, use_locking=True, name='AGNOptimizer'): """Construct a new AGN optimizer. Args: optimizer: input optimizer, can be sgd/momentum/adam etc. num_worker: The number of workers custom_getter: The AGNCustomGetter communication_period: An int point value to controls the frequency of the communication between every worker and the ps. use_locking: If True use locks for update operations. name: Optional name prefix for the operations created when applying gradients. Defaults to "AGNOptimizer". """ super(AGNOptimizer, self).__init__(use_locking, name) self._opt = optimizer self._num_worker = num_worker self._period = communication_period self._global_map = custom_getter._global_map self._grad_map = custom_getter._grad_map self._local_step = variable_scope.get_variable( initializer=0, trainable=False, collections=[ops.GraphKeys.LOCAL_VARIABLES], name='local_step') self._opt._prepare()
[ "def", "__init__", "(", "self", ",", "optimizer", ",", "num_worker", ",", "custom_getter", ",", "communication_period", "=", "10", ",", "use_locking", "=", "True", ",", "name", "=", "'AGNOptimizer'", ")", ":", "super", "(", "AGNOptimizer", ",", "self", ")", ".", "__init__", "(", "use_locking", ",", "name", ")", "self", ".", "_opt", "=", "optimizer", "self", ".", "_num_worker", "=", "num_worker", "self", ".", "_period", "=", "communication_period", "self", ".", "_global_map", "=", "custom_getter", ".", "_global_map", "self", ".", "_grad_map", "=", "custom_getter", ".", "_grad_map", "self", ".", "_local_step", "=", "variable_scope", ".", "get_variable", "(", "initializer", "=", "0", ",", "trainable", "=", "False", ",", "collections", "=", "[", "ops", ".", "GraphKeys", ".", "LOCAL_VARIABLES", "]", ",", "name", "=", "'local_step'", ")", "self", ".", "_opt", ".", "_prepare", "(", ")" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/opt/python/training/agn_optimizer.py#L102-L132
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/distutils/dist.py
python
Distribution.handle_display_options
(self, option_order)
return any_display_options
If there were any non-global "display-only" options (--help-commands or the metadata display options) on the command line, display the requested info and return true; else return false.
If there were any non-global "display-only" options (--help-commands or the metadata display options) on the command line, display the requested info and return true; else return false.
[ "If", "there", "were", "any", "non", "-", "global", "display", "-", "only", "options", "(", "--", "help", "-", "commands", "or", "the", "metadata", "display", "options", ")", "on", "the", "command", "line", "display", "the", "requested", "info", "and", "return", "true", ";", "else", "return", "false", "." ]
def handle_display_options(self, option_order): """If there were any non-global "display-only" options (--help-commands or the metadata display options) on the command line, display the requested info and return true; else return false. """ from distutils.core import gen_usage # User just wants a list of commands -- we'll print it out and stop # processing now (ie. if they ran "setup --help-commands foo bar", # we ignore "foo bar"). if self.help_commands: self.print_commands() print('') print(gen_usage(self.script_name)) return 1 # If user supplied any of the "display metadata" options, then # display that metadata in the order in which the user supplied the # metadata options. any_display_options = 0 is_display_option = {} for option in self.display_options: is_display_option[option[0]] = 1 for (opt, val) in option_order: if val and is_display_option.get(opt): opt = translate_longopt(opt) value = getattr(self.metadata, "get_"+opt)() if opt in ['keywords', 'platforms']: print(','.join(value)) elif opt in ('classifiers', 'provides', 'requires', 'obsoletes'): print('\n'.join(value)) else: print(value) any_display_options = 1 return any_display_options
[ "def", "handle_display_options", "(", "self", ",", "option_order", ")", ":", "from", "distutils", ".", "core", "import", "gen_usage", "# User just wants a list of commands -- we'll print it out and stop", "# processing now (ie. if they ran \"setup --help-commands foo bar\",", "# we ignore \"foo bar\").", "if", "self", ".", "help_commands", ":", "self", ".", "print_commands", "(", ")", "print", "(", "''", ")", "print", "(", "gen_usage", "(", "self", ".", "script_name", ")", ")", "return", "1", "# If user supplied any of the \"display metadata\" options, then", "# display that metadata in the order in which the user supplied the", "# metadata options.", "any_display_options", "=", "0", "is_display_option", "=", "{", "}", "for", "option", "in", "self", ".", "display_options", ":", "is_display_option", "[", "option", "[", "0", "]", "]", "=", "1", "for", "(", "opt", ",", "val", ")", "in", "option_order", ":", "if", "val", "and", "is_display_option", ".", "get", "(", "opt", ")", ":", "opt", "=", "translate_longopt", "(", "opt", ")", "value", "=", "getattr", "(", "self", ".", "metadata", ",", "\"get_\"", "+", "opt", ")", "(", ")", "if", "opt", "in", "[", "'keywords'", ",", "'platforms'", "]", ":", "print", "(", "','", ".", "join", "(", "value", ")", ")", "elif", "opt", "in", "(", "'classifiers'", ",", "'provides'", ",", "'requires'", ",", "'obsoletes'", ")", ":", "print", "(", "'\\n'", ".", "join", "(", "value", ")", ")", "else", ":", "print", "(", "value", ")", "any_display_options", "=", "1", "return", "any_display_options" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/distutils/dist.py#L671-L709
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/botocore/docs/waiter.py
python
document_wait_method
(section, waiter_name, event_emitter, service_model, service_waiter_model, include_signature=True)
Documents a the wait method of a waiter :param section: The section to write to :param waiter_name: The name of the waiter :param event_emitter: The event emitter to use to emit events :param service_model: The service model :param service_waiter_model: The waiter model associated to the service :param include_signature: Whether or not to include the signature. It is useful for generating docstrings.
Documents a the wait method of a waiter
[ "Documents", "a", "the", "wait", "method", "of", "a", "waiter" ]
def document_wait_method(section, waiter_name, event_emitter, service_model, service_waiter_model, include_signature=True): """Documents a the wait method of a waiter :param section: The section to write to :param waiter_name: The name of the waiter :param event_emitter: The event emitter to use to emit events :param service_model: The service model :param service_waiter_model: The waiter model associated to the service :param include_signature: Whether or not to include the signature. It is useful for generating docstrings. """ waiter_model = service_waiter_model.get_waiter(waiter_name) operation_model = service_model.operation_model( waiter_model.operation) waiter_config_members = OrderedDict() waiter_config_members['Delay'] = DocumentedShape( name='Delay', type_name='integer', documentation=( '<p>The amount of time in seconds to wait between ' 'attempts. Default: {0}</p>'.format(waiter_model.delay))) waiter_config_members['MaxAttempts'] = DocumentedShape( name='MaxAttempts', type_name='integer', documentation=( '<p>The maximum number of attempts to be made. ' 'Default: {0}</p>'.format(waiter_model.max_attempts))) botocore_waiter_params = [ DocumentedShape( name='WaiterConfig', type_name='structure', documentation=( '<p>A dictionary that provides parameters to control ' 'waiting behavior.</p>'), members=waiter_config_members) ] wait_description = ( 'Polls :py:meth:`{0}.Client.{1}` every {2} ' 'seconds until a successful state is reached. An error is ' 'returned after {3} failed checks.'.format( get_service_module_name(service_model), xform_name(waiter_model.operation), waiter_model.delay, waiter_model.max_attempts) ) document_model_driven_method( section, 'wait', operation_model, event_emitter=event_emitter, method_description=wait_description, example_prefix='waiter.wait', include_input=botocore_waiter_params, document_output=False, include_signature=include_signature )
[ "def", "document_wait_method", "(", "section", ",", "waiter_name", ",", "event_emitter", ",", "service_model", ",", "service_waiter_model", ",", "include_signature", "=", "True", ")", ":", "waiter_model", "=", "service_waiter_model", ".", "get_waiter", "(", "waiter_name", ")", "operation_model", "=", "service_model", ".", "operation_model", "(", "waiter_model", ".", "operation", ")", "waiter_config_members", "=", "OrderedDict", "(", ")", "waiter_config_members", "[", "'Delay'", "]", "=", "DocumentedShape", "(", "name", "=", "'Delay'", ",", "type_name", "=", "'integer'", ",", "documentation", "=", "(", "'<p>The amount of time in seconds to wait between '", "'attempts. Default: {0}</p>'", ".", "format", "(", "waiter_model", ".", "delay", ")", ")", ")", "waiter_config_members", "[", "'MaxAttempts'", "]", "=", "DocumentedShape", "(", "name", "=", "'MaxAttempts'", ",", "type_name", "=", "'integer'", ",", "documentation", "=", "(", "'<p>The maximum number of attempts to be made. '", "'Default: {0}</p>'", ".", "format", "(", "waiter_model", ".", "max_attempts", ")", ")", ")", "botocore_waiter_params", "=", "[", "DocumentedShape", "(", "name", "=", "'WaiterConfig'", ",", "type_name", "=", "'structure'", ",", "documentation", "=", "(", "'<p>A dictionary that provides parameters to control '", "'waiting behavior.</p>'", ")", ",", "members", "=", "waiter_config_members", ")", "]", "wait_description", "=", "(", "'Polls :py:meth:`{0}.Client.{1}` every {2} '", "'seconds until a successful state is reached. An error is '", "'returned after {3} failed checks.'", ".", "format", "(", "get_service_module_name", "(", "service_model", ")", ",", "xform_name", "(", "waiter_model", ".", "operation", ")", ",", "waiter_model", ".", "delay", ",", "waiter_model", ".", "max_attempts", ")", ")", "document_model_driven_method", "(", "section", ",", "'wait'", ",", "operation_model", ",", "event_emitter", "=", "event_emitter", ",", "method_description", "=", "wait_description", ",", "example_prefix", "=", "'waiter.wait'", ",", "include_input", "=", "botocore_waiter_params", ",", "document_output", "=", "False", ",", "include_signature", "=", "include_signature", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/botocore/docs/waiter.py#L65-L127
microsoft/CNTK
e9396480025b9ca457d26b6f33dd07c474c6aa04
bindings/python/cntk/ops/__init__.py
python
assign
(ref, input, name='')
return assign(ref_operand, operand, name)
Assign the value in input to ref and return the new value, ref need to be the same layout as input. Both ref and input can't have dynamic axis and broadcast isn't supported for the assign operator. During forward pass, ref will get the new value after the forward or backward pass finish, so that any part of the graph that depend on ref will get the old value. To get the new value, use the one returned by the assign node. The reason for that is to make ``assign`` have a deterministic behavior. If not computing gradients, the ref will be assigned the new value after the forward pass over the entire Function graph is complete; i.e. all uses of ref in the forward pass will use the original (pre-assignment) value of ref. If computing gradients (training mode), the assignment to ref will happen after completing both the forward and backward passes over the entire Function graph. The ref must be a Parameter or Constant. If the same ref is used in multiple assign operations, then the order in which the assignment happens is non-deterministic and the final value can be either of the assignments unless an order is established using a data dependence between the assignments. Example: >>> dest = C.constant(shape=(3,4)) >>> data = C.parameter(shape=(3,4), init=2) >>> C.assign(dest,data).eval() array([[ 2., 2., 2., 2.], [ 2., 2., 2., 2.], [ 2., 2., 2., 2.]], dtype=float32) >>> dest.asarray() array([[ 2., 2., 2., 2.], [ 2., 2., 2., 2.], [ 2., 2., 2., 2.]], dtype=float32) >>> dest = C.parameter(shape=(3,4), init=0) >>> a = C.assign(dest, data) >>> y = dest + data >>> result = C.combine([y, a]).eval() >>> result[y.output] array([[ 2., 2., 2., 2.], [ 2., 2., 2., 2.], [ 2., 2., 2., 2.]], dtype=float32) >>> dest.asarray() array([[ 2., 2., 2., 2.], [ 2., 2., 2., 2.], [ 2., 2., 2., 2.]], dtype=float32) >>> result = C.combine([y, a]).eval() >>> result[y.output] array([[ 4., 4., 4., 4.], [ 4., 4., 4., 4.], [ 4., 4., 4., 4.]], dtype=float32) >>> dest.asarray() array([[ 2., 2., 2., 2.], [ 2., 2., 2., 2.], [ 2., 2., 2., 2.]], dtype=float32) Args: ref: class: `~cntk.variables.Constant` or `~cntk.variables.Parameter`. input: class:`~cntk.ops.functions.Function` that outputs a tensor name (str, optional): the name of the Function instance in the network Returns: :class:`~cntk.ops.functions.Function`
Assign the value in input to ref and return the new value, ref need to be the same layout as input. Both ref and input can't have dynamic axis and broadcast isn't supported for the assign operator. During forward pass, ref will get the new value after the forward or backward pass finish, so that any part of the graph that depend on ref will get the old value. To get the new value, use the one returned by the assign node. The reason for that is to make ``assign`` have a deterministic behavior.
[ "Assign", "the", "value", "in", "input", "to", "ref", "and", "return", "the", "new", "value", "ref", "need", "to", "be", "the", "same", "layout", "as", "input", ".", "Both", "ref", "and", "input", "can", "t", "have", "dynamic", "axis", "and", "broadcast", "isn", "t", "supported", "for", "the", "assign", "operator", ".", "During", "forward", "pass", "ref", "will", "get", "the", "new", "value", "after", "the", "forward", "or", "backward", "pass", "finish", "so", "that", "any", "part", "of", "the", "graph", "that", "depend", "on", "ref", "will", "get", "the", "old", "value", ".", "To", "get", "the", "new", "value", "use", "the", "one", "returned", "by", "the", "assign", "node", ".", "The", "reason", "for", "that", "is", "to", "make", "assign", "have", "a", "deterministic", "behavior", "." ]
def assign(ref, input, name=''): ''' Assign the value in input to ref and return the new value, ref need to be the same layout as input. Both ref and input can't have dynamic axis and broadcast isn't supported for the assign operator. During forward pass, ref will get the new value after the forward or backward pass finish, so that any part of the graph that depend on ref will get the old value. To get the new value, use the one returned by the assign node. The reason for that is to make ``assign`` have a deterministic behavior. If not computing gradients, the ref will be assigned the new value after the forward pass over the entire Function graph is complete; i.e. all uses of ref in the forward pass will use the original (pre-assignment) value of ref. If computing gradients (training mode), the assignment to ref will happen after completing both the forward and backward passes over the entire Function graph. The ref must be a Parameter or Constant. If the same ref is used in multiple assign operations, then the order in which the assignment happens is non-deterministic and the final value can be either of the assignments unless an order is established using a data dependence between the assignments. Example: >>> dest = C.constant(shape=(3,4)) >>> data = C.parameter(shape=(3,4), init=2) >>> C.assign(dest,data).eval() array([[ 2., 2., 2., 2.], [ 2., 2., 2., 2.], [ 2., 2., 2., 2.]], dtype=float32) >>> dest.asarray() array([[ 2., 2., 2., 2.], [ 2., 2., 2., 2.], [ 2., 2., 2., 2.]], dtype=float32) >>> dest = C.parameter(shape=(3,4), init=0) >>> a = C.assign(dest, data) >>> y = dest + data >>> result = C.combine([y, a]).eval() >>> result[y.output] array([[ 2., 2., 2., 2.], [ 2., 2., 2., 2.], [ 2., 2., 2., 2.]], dtype=float32) >>> dest.asarray() array([[ 2., 2., 2., 2.], [ 2., 2., 2., 2.], [ 2., 2., 2., 2.]], dtype=float32) >>> result = C.combine([y, a]).eval() >>> result[y.output] array([[ 4., 4., 4., 4.], [ 4., 4., 4., 4.], [ 4., 4., 4., 4.]], dtype=float32) >>> dest.asarray() array([[ 2., 2., 2., 2.], [ 2., 2., 2., 2.], [ 2., 2., 2., 2.]], dtype=float32) Args: ref: class: `~cntk.variables.Constant` or `~cntk.variables.Parameter`. input: class:`~cntk.ops.functions.Function` that outputs a tensor name (str, optional): the name of the Function instance in the network Returns: :class:`~cntk.ops.functions.Function` ''' from cntk.cntk_py import assign dtype = get_data_type(input) operand = sanitize_input(input, dtype) ref_operand = sanitize_input(ref, dtype) return assign(ref_operand, operand, name)
[ "def", "assign", "(", "ref", ",", "input", ",", "name", "=", "''", ")", ":", "from", "cntk", ".", "cntk_py", "import", "assign", "dtype", "=", "get_data_type", "(", "input", ")", "operand", "=", "sanitize_input", "(", "input", ",", "dtype", ")", "ref_operand", "=", "sanitize_input", "(", "ref", ",", "dtype", ")", "return", "assign", "(", "ref_operand", ",", "operand", ",", "name", ")" ]
https://github.com/microsoft/CNTK/blob/e9396480025b9ca457d26b6f33dd07c474c6aa04/bindings/python/cntk/ops/__init__.py#L3846-L3911
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/devil/devil/android/sdk/shared_prefs.py
python
BooleanPref.set
(self, value)
Set from a value casted as a bool.
Set from a value casted as a bool.
[ "Set", "from", "a", "value", "casted", "as", "a", "bool", "." ]
def set(self, value): """Set from a value casted as a bool.""" super(BooleanPref, self).set('true' if value else 'false')
[ "def", "set", "(", "self", ",", "value", ")", ":", "super", "(", "BooleanPref", ",", "self", ")", ".", "set", "(", "'true'", "if", "value", "else", "'false'", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/devil/devil/android/sdk/shared_prefs.py#L73-L75
larroy/clearskies_core
3574ddf0edc8555454c7044126e786a6c29444dc
tools/gyp/pylib/gyp/generator/msvs.py
python
_PrepareListOfSources
(spec, generator_flags, gyp_file)
return (sources, excluded_sources)
Prepare list of sources and excluded sources. Besides the sources specified directly in the spec, adds the gyp file so that a change to it will cause a re-compile. Also adds appropriate sources for actions and copies. Assumes later stage will un-exclude files which have custom build steps attached. Arguments: spec: The target dictionary containing the properties of the target. gyp_file: The name of the gyp file. Returns: A pair of (list of sources, list of excluded sources). The sources will be relative to the gyp file.
Prepare list of sources and excluded sources.
[ "Prepare", "list", "of", "sources", "and", "excluded", "sources", "." ]
def _PrepareListOfSources(spec, generator_flags, gyp_file): """Prepare list of sources and excluded sources. Besides the sources specified directly in the spec, adds the gyp file so that a change to it will cause a re-compile. Also adds appropriate sources for actions and copies. Assumes later stage will un-exclude files which have custom build steps attached. Arguments: spec: The target dictionary containing the properties of the target. gyp_file: The name of the gyp file. Returns: A pair of (list of sources, list of excluded sources). The sources will be relative to the gyp file. """ sources = OrderedSet() _AddNormalizedSources(sources, spec.get('sources', [])) excluded_sources = OrderedSet() # Add in the gyp file. if not generator_flags.get('standalone'): sources.add(gyp_file) # Add in 'action' inputs and outputs. for a in spec.get('actions', []): inputs = a['inputs'] inputs = [_NormalizedSource(i) for i in inputs] # Add all inputs to sources and excluded sources. inputs = OrderedSet(inputs) sources.update(inputs) if not spec.get('msvs_external_builder'): excluded_sources.update(inputs) if int(a.get('process_outputs_as_sources', False)): _AddNormalizedSources(sources, a.get('outputs', [])) # Add in 'copies' inputs and outputs. for cpy in spec.get('copies', []): _AddNormalizedSources(sources, cpy.get('files', [])) return (sources, excluded_sources)
[ "def", "_PrepareListOfSources", "(", "spec", ",", "generator_flags", ",", "gyp_file", ")", ":", "sources", "=", "OrderedSet", "(", ")", "_AddNormalizedSources", "(", "sources", ",", "spec", ".", "get", "(", "'sources'", ",", "[", "]", ")", ")", "excluded_sources", "=", "OrderedSet", "(", ")", "# Add in the gyp file.", "if", "not", "generator_flags", ".", "get", "(", "'standalone'", ")", ":", "sources", ".", "add", "(", "gyp_file", ")", "# Add in 'action' inputs and outputs.", "for", "a", "in", "spec", ".", "get", "(", "'actions'", ",", "[", "]", ")", ":", "inputs", "=", "a", "[", "'inputs'", "]", "inputs", "=", "[", "_NormalizedSource", "(", "i", ")", "for", "i", "in", "inputs", "]", "# Add all inputs to sources and excluded sources.", "inputs", "=", "OrderedSet", "(", "inputs", ")", "sources", ".", "update", "(", "inputs", ")", "if", "not", "spec", ".", "get", "(", "'msvs_external_builder'", ")", ":", "excluded_sources", ".", "update", "(", "inputs", ")", "if", "int", "(", "a", ".", "get", "(", "'process_outputs_as_sources'", ",", "False", ")", ")", ":", "_AddNormalizedSources", "(", "sources", ",", "a", ".", "get", "(", "'outputs'", ",", "[", "]", ")", ")", "# Add in 'copies' inputs and outputs.", "for", "cpy", "in", "spec", ".", "get", "(", "'copies'", ",", "[", "]", ")", ":", "_AddNormalizedSources", "(", "sources", ",", "cpy", ".", "get", "(", "'files'", ",", "[", "]", ")", ")", "return", "(", "sources", ",", "excluded_sources", ")" ]
https://github.com/larroy/clearskies_core/blob/3574ddf0edc8555454c7044126e786a6c29444dc/tools/gyp/pylib/gyp/generator/msvs.py#L1401-L1437
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/ipython/py3/IPython/core/interactiveshell.py
python
InteractiveShell.find_cell_magic
(self, magic_name)
return self.magics_manager.magics['cell'].get(magic_name)
Find and return a cell magic by name. Returns None if the magic isn't found.
Find and return a cell magic by name.
[ "Find", "and", "return", "a", "cell", "magic", "by", "name", "." ]
def find_cell_magic(self, magic_name): """Find and return a cell magic by name. Returns None if the magic isn't found.""" return self.magics_manager.magics['cell'].get(magic_name)
[ "def", "find_cell_magic", "(", "self", ",", "magic_name", ")", ":", "return", "self", ".", "magics_manager", ".", "magics", "[", "'cell'", "]", ".", "get", "(", "magic_name", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py3/IPython/core/interactiveshell.py#L2428-L2432
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/numbers.py
python
Integral.numerator
(self)
return +self
Integers are their own numerators.
Integers are their own numerators.
[ "Integers", "are", "their", "own", "numerators", "." ]
def numerator(self): """Integers are their own numerators.""" return +self
[ "def", "numerator", "(", "self", ")", ":", "return", "+", "self" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/numbers.py#L380-L382
albertz/openlierox
d316c14a8eb57848ef56e9bfa7b23a56f694a51b
tools/DedicatedServerVideo/gdata/health/__init__.py
python
ProfileEntryFromString
(xml_string)
return atom.CreateClassFromXMLString(ProfileEntry, xml_string)
Converts an XML string into a ProfileEntry object. Args: xml_string: string The XML describing a Health profile feed entry. Returns: A ProfileEntry object corresponding to the given XML.
Converts an XML string into a ProfileEntry object.
[ "Converts", "an", "XML", "string", "into", "a", "ProfileEntry", "object", "." ]
def ProfileEntryFromString(xml_string): """Converts an XML string into a ProfileEntry object. Args: xml_string: string The XML describing a Health profile feed entry. Returns: A ProfileEntry object corresponding to the given XML. """ return atom.CreateClassFromXMLString(ProfileEntry, xml_string)
[ "def", "ProfileEntryFromString", "(", "xml_string", ")", ":", "return", "atom", ".", "CreateClassFromXMLString", "(", "ProfileEntry", ",", "xml_string", ")" ]
https://github.com/albertz/openlierox/blob/d316c14a8eb57848ef56e9bfa7b23a56f694a51b/tools/DedicatedServerVideo/gdata/health/__init__.py#L184-L193
cmu-db/noisepage
79276e68fe83322f1249e8a8be96bd63c583ae56
build-support/cpplint.py
python
NestingState.InTemplateArgumentList
(self, clean_lines, linenum, pos)
return False
Check if current position is inside template argument list. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. pos: position just after the suspected template argument. Returns: True if (linenum, pos) is inside template arguments.
Check if current position is inside template argument list.
[ "Check", "if", "current", "position", "is", "inside", "template", "argument", "list", "." ]
def InTemplateArgumentList(self, clean_lines, linenum, pos): """Check if current position is inside template argument list. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. pos: position just after the suspected template argument. Returns: True if (linenum, pos) is inside template arguments. """ while linenum < clean_lines.NumLines(): # Find the earliest character that might indicate a template argument line = clean_lines.elided[linenum] match = Match(r'^[^{};=\[\]\.<>]*(.)', line[pos:]) if not match: linenum += 1 pos = 0 continue token = match.group(1) pos += len(match.group(0)) # These things do not look like template argument list: # class Suspect { # class Suspect x; } if token in ('{', '}', ';'): return False # These things look like template argument list: # template <class Suspect> # template <class Suspect = default_value> # template <class Suspect[]> # template <class Suspect...> if token in ('>', '=', '[', ']', '.'): return True # Check if token is an unmatched '<'. # If not, move on to the next character. if token != '<': pos += 1 if pos >= len(line): linenum += 1 pos = 0 continue # We can't be sure if we just find a single '<', and need to # find the matching '>'. (_, end_line, end_pos) = CloseExpression(clean_lines, linenum, pos - 1) if end_pos < 0: # Not sure if template argument list or syntax error in file return False linenum = end_line pos = end_pos return False
[ "def", "InTemplateArgumentList", "(", "self", ",", "clean_lines", ",", "linenum", ",", "pos", ")", ":", "while", "linenum", "<", "clean_lines", ".", "NumLines", "(", ")", ":", "# Find the earliest character that might indicate a template argument", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "match", "=", "Match", "(", "r'^[^{};=\\[\\]\\.<>]*(.)'", ",", "line", "[", "pos", ":", "]", ")", "if", "not", "match", ":", "linenum", "+=", "1", "pos", "=", "0", "continue", "token", "=", "match", ".", "group", "(", "1", ")", "pos", "+=", "len", "(", "match", ".", "group", "(", "0", ")", ")", "# These things do not look like template argument list:", "# class Suspect {", "# class Suspect x; }", "if", "token", "in", "(", "'{'", ",", "'}'", ",", "';'", ")", ":", "return", "False", "# These things look like template argument list:", "# template <class Suspect>", "# template <class Suspect = default_value>", "# template <class Suspect[]>", "# template <class Suspect...>", "if", "token", "in", "(", "'>'", ",", "'='", ",", "'['", ",", "']'", ",", "'.'", ")", ":", "return", "True", "# Check if token is an unmatched '<'.", "# If not, move on to the next character.", "if", "token", "!=", "'<'", ":", "pos", "+=", "1", "if", "pos", ">=", "len", "(", "line", ")", ":", "linenum", "+=", "1", "pos", "=", "0", "continue", "# We can't be sure if we just find a single '<', and need to", "# find the matching '>'.", "(", "_", ",", "end_line", ",", "end_pos", ")", "=", "CloseExpression", "(", "clean_lines", ",", "linenum", ",", "pos", "-", "1", ")", "if", "end_pos", "<", "0", ":", "# Not sure if template argument list or syntax error in file", "return", "False", "linenum", "=", "end_line", "pos", "=", "end_pos", "return", "False" ]
https://github.com/cmu-db/noisepage/blob/79276e68fe83322f1249e8a8be96bd63c583ae56/build-support/cpplint.py#L2705-L2755
okex/V3-Open-API-SDK
c5abb0db7e2287718e0055e17e57672ce0ec7fd9
okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/html5lib/treebuilders/base.py
python
TreeBuilder.elementInActiveFormattingElements
(self, name)
return False
Check if an element exists between the end of the active formatting elements and the last marker. If it does, return it, else return false
Check if an element exists between the end of the active formatting elements and the last marker. If it does, return it, else return false
[ "Check", "if", "an", "element", "exists", "between", "the", "end", "of", "the", "active", "formatting", "elements", "and", "the", "last", "marker", ".", "If", "it", "does", "return", "it", "else", "return", "false" ]
def elementInActiveFormattingElements(self, name): """Check if an element exists between the end of the active formatting elements and the last marker. If it does, return it, else return false""" for item in self.activeFormattingElements[::-1]: # Check for Marker first because if it's a Marker it doesn't have a # name attribute. if item == Marker: break elif item.name == name: return item return False
[ "def", "elementInActiveFormattingElements", "(", "self", ",", "name", ")", ":", "for", "item", "in", "self", ".", "activeFormattingElements", "[", ":", ":", "-", "1", "]", ":", "# Check for Marker first because if it's a Marker it doesn't have a", "# name attribute.", "if", "item", "==", "Marker", ":", "break", "elif", "item", ".", "name", "==", "name", ":", "return", "item", "return", "False" ]
https://github.com/okex/V3-Open-API-SDK/blob/c5abb0db7e2287718e0055e17e57672ce0ec7fd9/okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/html5lib/treebuilders/base.py#L269-L281
calamares/calamares
9f6f82405b3074af7c99dc26487d2e46e4ece3e5
src/modules/services-openrc/main.py
python
OpenrcController.make_failure_description
(self, state, name, runlevel)
return description.format(arg=state, name=name, level=runlevel)
Returns a generic "could not <foo>" failure message, specialized for the action @p state and the specific service @p name in @p runlevel.
Returns a generic "could not <foo>" failure message, specialized for the action
[ "Returns", "a", "generic", "could", "not", "<foo", ">", "failure", "message", "specialized", "for", "the", "action" ]
def make_failure_description(self, state, name, runlevel): """ Returns a generic "could not <foo>" failure message, specialized for the action @p state and the specific service @p name in @p runlevel. """ if state == "add": description = _("Cannot add service {name!s} to run-level {level!s}.") elif state == "del": description = _("Cannot remove service {name!s} from run-level {level!s}.") else: description = _("Unknown service-action <code>{arg!s}</code> for service {name!s} in run-level {level!s}.") return description.format(arg=state, name=name, level=runlevel)
[ "def", "make_failure_description", "(", "self", ",", "state", ",", "name", ",", "runlevel", ")", ":", "if", "state", "==", "\"add\"", ":", "description", "=", "_", "(", "\"Cannot add service {name!s} to run-level {level!s}.\"", ")", "elif", "state", "==", "\"del\"", ":", "description", "=", "_", "(", "\"Cannot remove service {name!s} from run-level {level!s}.\"", ")", "else", ":", "description", "=", "_", "(", "\"Unknown service-action <code>{arg!s}</code> for service {name!s} in run-level {level!s}.\"", ")", "return", "description", ".", "format", "(", "arg", "=", "state", ",", "name", "=", "name", ",", "level", "=", "runlevel", ")" ]
https://github.com/calamares/calamares/blob/9f6f82405b3074af7c99dc26487d2e46e4ece3e5/src/modules/services-openrc/main.py#L51-L63
Polidea/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
SymbolExtractorAndRenamer/lldb/utils/vim-lldb/python-vim-lldb/vim_panes.py
python
PaneLayout.prepare
(self, panes=[])
Draw panes on screen. If empty list is provided, show all.
Draw panes on screen. If empty list is provided, show all.
[ "Draw", "panes", "on", "screen", ".", "If", "empty", "list", "is", "provided", "show", "all", "." ]
def prepare(self, panes=[]): """ Draw panes on screen. If empty list is provided, show all. """ # If we can't select a window contained in the layout, we are doing a # first draw first_draw = not self.selectWindow(True) did_first_draw = False # Prepare each registered pane for name in self.panes: if name in panes or len(panes) == 0: if first_draw: # First window in layout will be created with :vsp, and # closed later vim.command(":vsp") first_draw = False did_first_draw = True self.panes[name].prepare() if did_first_draw: # Close the split window vim.command(":q") self.selectWindow(False)
[ "def", "prepare", "(", "self", ",", "panes", "=", "[", "]", ")", ":", "# If we can't select a window contained in the layout, we are doing a", "# first draw", "first_draw", "=", "not", "self", ".", "selectWindow", "(", "True", ")", "did_first_draw", "=", "False", "# Prepare each registered pane", "for", "name", "in", "self", ".", "panes", ":", "if", "name", "in", "panes", "or", "len", "(", "panes", ")", "==", "0", ":", "if", "first_draw", ":", "# First window in layout will be created with :vsp, and", "# closed later", "vim", ".", "command", "(", "\":vsp\"", ")", "first_draw", "=", "False", "did_first_draw", "=", "True", "self", ".", "panes", "[", "name", "]", ".", "prepare", "(", ")", "if", "did_first_draw", ":", "# Close the split window", "vim", ".", "command", "(", "\":q\"", ")", "self", ".", "selectWindow", "(", "False", ")" ]
https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/utils/vim-lldb/python-vim-lldb/vim_panes.py#L155-L178
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_core.py
python
PyApp_GetMacExitMenuItemId
(*args)
return _core_.PyApp_GetMacExitMenuItemId(*args)
PyApp_GetMacExitMenuItemId() -> long
PyApp_GetMacExitMenuItemId() -> long
[ "PyApp_GetMacExitMenuItemId", "()", "-", ">", "long" ]
def PyApp_GetMacExitMenuItemId(*args): """PyApp_GetMacExitMenuItemId() -> long""" return _core_.PyApp_GetMacExitMenuItemId(*args)
[ "def", "PyApp_GetMacExitMenuItemId", "(", "*", "args", ")", ":", "return", "_core_", ".", "PyApp_GetMacExitMenuItemId", "(", "*", "args", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L8286-L8288
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/util/tf_inspect.py
python
isgenerator
(object)
return _inspect.isgenerator(tf_decorator.unwrap(object)[1])
TFDecorator-aware replacement for inspect.isgenerator.
TFDecorator-aware replacement for inspect.isgenerator.
[ "TFDecorator", "-", "aware", "replacement", "for", "inspect", ".", "isgenerator", "." ]
def isgenerator(object): # pylint: disable=redefined-builtin """TFDecorator-aware replacement for inspect.isgenerator.""" return _inspect.isgenerator(tf_decorator.unwrap(object)[1])
[ "def", "isgenerator", "(", "object", ")", ":", "# pylint: disable=redefined-builtin", "return", "_inspect", ".", "isgenerator", "(", "tf_decorator", ".", "unwrap", "(", "object", ")", "[", "1", "]", ")" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/util/tf_inspect.py#L380-L382
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py2/pandas/core/arrays/categorical.py
python
Categorical._repr_categories
(self)
return category_strs
return the base repr for the categories
return the base repr for the categories
[ "return", "the", "base", "repr", "for", "the", "categories" ]
def _repr_categories(self): """ return the base repr for the categories """ max_categories = (10 if get_option("display.max_categories") == 0 else get_option("display.max_categories")) from pandas.io.formats import format as fmt if len(self.categories) > max_categories: num = max_categories // 2 head = fmt.format_array(self.categories[:num], None) tail = fmt.format_array(self.categories[-num:], None) category_strs = head + ["..."] + tail else: category_strs = fmt.format_array(self.categories, None) # Strip all leading spaces, which format_array adds for columns... category_strs = [x.strip() for x in category_strs] return category_strs
[ "def", "_repr_categories", "(", "self", ")", ":", "max_categories", "=", "(", "10", "if", "get_option", "(", "\"display.max_categories\"", ")", "==", "0", "else", "get_option", "(", "\"display.max_categories\"", ")", ")", "from", "pandas", ".", "io", ".", "formats", "import", "format", "as", "fmt", "if", "len", "(", "self", ".", "categories", ")", ">", "max_categories", ":", "num", "=", "max_categories", "//", "2", "head", "=", "fmt", ".", "format_array", "(", "self", ".", "categories", "[", ":", "num", "]", ",", "None", ")", "tail", "=", "fmt", ".", "format_array", "(", "self", ".", "categories", "[", "-", "num", ":", "]", ",", "None", ")", "category_strs", "=", "head", "+", "[", "\"...\"", "]", "+", "tail", "else", ":", "category_strs", "=", "fmt", ".", "format_array", "(", "self", ".", "categories", ",", "None", ")", "# Strip all leading spaces, which format_array adds for columns...", "category_strs", "=", "[", "x", ".", "strip", "(", ")", "for", "x", "in", "category_strs", "]", "return", "category_strs" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/core/arrays/categorical.py#L1957-L1974
freeorion/freeorion
c266a40eccd3a99a17de8fe57c36ef6ba3771665
default/python/AI/ColonisationAI.py
python
OrbitalColonizationManager.create_new_plan
(self, target_id: int, source_id: int)
Create and keep track of a new colonization plan for a target planet. :param target_id: id of the target planet :param source_id: id of the planet which is supposed to build the base
Create and keep track of a new colonization plan for a target planet.
[ "Create", "and", "keep", "track", "of", "a", "new", "colonization", "plan", "for", "a", "target", "planet", "." ]
def create_new_plan(self, target_id: int, source_id: int): """ Create and keep track of a new colonization plan for a target planet. :param target_id: id of the target planet :param source_id: id of the planet which is supposed to build the base """ if target_id in self._colonization_plans: warning("Already have a colonization plan for this planet. Doing nothing.") return self._colonization_plans[target_id] = OrbitalColonizationPlan(target_id, source_id)
[ "def", "create_new_plan", "(", "self", ",", "target_id", ":", "int", ",", "source_id", ":", "int", ")", ":", "if", "target_id", "in", "self", ".", "_colonization_plans", ":", "warning", "(", "\"Already have a colonization plan for this planet. Doing nothing.\"", ")", "return", "self", ".", "_colonization_plans", "[", "target_id", "]", "=", "OrbitalColonizationPlan", "(", "target_id", ",", "source_id", ")" ]
https://github.com/freeorion/freeorion/blob/c266a40eccd3a99a17de8fe57c36ef6ba3771665/default/python/AI/ColonisationAI.py#L740-L750
SequoiaDB/SequoiaDB
2894ed7e5bd6fe57330afc900cf76d0ff0df9f64
driver/python/pysequoiadb/replicagroup.py
python
replicagroup.detach_node
(self, hostname, servicename, config=None)
Detach node in a given replica group. Parameters: Name Type Info: hostname str The host name for the node. servicename str The servicename for the node. config dict The configurations for the node. Exceptions: pysequoiadb.error.SDBBaseError
Detach node in a given replica group.
[ "Detach", "node", "in", "a", "given", "replica", "group", "." ]
def detach_node(self, hostname, servicename, config=None): """Detach node in a given replica group. Parameters: Name Type Info: hostname str The host name for the node. servicename str The servicename for the node. config dict The configurations for the node. Exceptions: pysequoiadb.error.SDBBaseError """ if not isinstance(hostname, str_type): raise SDBTypeError("host must be an instance of str_type") if not isinstance(servicename, str_type): raise SDBTypeError("service name must be an instance of str_type") if config is not None and not isinstance(config, dict): raise SDBTypeError("config must be an instance of dict") if config is None: config = {} bson_options = bson.BSON.encode(config) rc = sdb.gp_detach_node(self._group, hostname, servicename, bson_options) raise_if_error(rc, "Failed to detach node")
[ "def", "detach_node", "(", "self", ",", "hostname", ",", "servicename", ",", "config", "=", "None", ")", ":", "if", "not", "isinstance", "(", "hostname", ",", "str_type", ")", ":", "raise", "SDBTypeError", "(", "\"host must be an instance of str_type\"", ")", "if", "not", "isinstance", "(", "servicename", ",", "str_type", ")", ":", "raise", "SDBTypeError", "(", "\"service name must be an instance of str_type\"", ")", "if", "config", "is", "not", "None", "and", "not", "isinstance", "(", "config", ",", "dict", ")", ":", "raise", "SDBTypeError", "(", "\"config must be an instance of dict\"", ")", "if", "config", "is", "None", ":", "config", "=", "{", "}", "bson_options", "=", "bson", ".", "BSON", ".", "encode", "(", "config", ")", "rc", "=", "sdb", ".", "gp_detach_node", "(", "self", ".", "_group", ",", "hostname", ",", "servicename", ",", "bson_options", ")", "raise_if_error", "(", "rc", ",", "\"Failed to detach node\"", ")" ]
https://github.com/SequoiaDB/SequoiaDB/blob/2894ed7e5bd6fe57330afc900cf76d0ff0df9f64/driver/python/pysequoiadb/replicagroup.py#L351-L375
openweave/openweave-core
11ceb6b7efd39fe05de7f79229247a5774d56766
src/device-manager/python/openweave/WeaveBleBase.py
python
WeaveBleBase.CloseBle
(self, connObj)
return
Called by Weave to close the BLE connection.
Called by Weave to close the BLE connection.
[ "Called", "by", "Weave", "to", "close", "the", "BLE", "connection", "." ]
def CloseBle(self, connObj): """ Called by Weave to close the BLE connection.""" return
[ "def", "CloseBle", "(", "self", ",", "connObj", ")", ":", "return" ]
https://github.com/openweave/openweave-core/blob/11ceb6b7efd39fe05de7f79229247a5774d56766/src/device-manager/python/openweave/WeaveBleBase.py#L62-L64
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py2/sklearn/decomposition/dict_learning.py
python
sparse_encode
(X, dictionary, gram=None, cov=None, algorithm='lasso_lars', n_nonzero_coefs=None, alpha=None, copy_cov=True, init=None, max_iter=1000, n_jobs=1, check_input=True, verbose=0)
return code
Sparse coding Each row of the result is the solution to a sparse coding problem. The goal is to find a sparse array `code` such that:: X ~= code * dictionary Read more in the :ref:`User Guide <SparseCoder>`. Parameters ---------- X: array of shape (n_samples, n_features) Data matrix dictionary: array of shape (n_components, n_features) The dictionary matrix against which to solve the sparse coding of the data. Some of the algorithms assume normalized rows for meaningful output. gram: array, shape=(n_components, n_components) Precomputed Gram matrix, dictionary * dictionary' cov: array, shape=(n_components, n_samples) Precomputed covariance, dictionary' * X algorithm: {'lasso_lars', 'lasso_cd', 'lars', 'omp', 'threshold'} lars: uses the least angle regression method (linear_model.lars_path) lasso_lars: uses Lars to compute the Lasso solution lasso_cd: uses the coordinate descent method to compute the Lasso solution (linear_model.Lasso). lasso_lars will be faster if the estimated components are sparse. omp: uses orthogonal matching pursuit to estimate the sparse solution threshold: squashes to zero all coefficients less than alpha from the projection dictionary * X' n_nonzero_coefs: int, 0.1 * n_features by default Number of nonzero coefficients to target in each column of the solution. This is only used by `algorithm='lars'` and `algorithm='omp'` and is overridden by `alpha` in the `omp` case. alpha: float, 1. by default If `algorithm='lasso_lars'` or `algorithm='lasso_cd'`, `alpha` is the penalty applied to the L1 norm. If `algorithm='threshold'`, `alpha` is the absolute value of the threshold below which coefficients will be squashed to zero. If `algorithm='omp'`, `alpha` is the tolerance parameter: the value of the reconstruction error targeted. In this case, it overrides `n_nonzero_coefs`. init: array of shape (n_samples, n_components) Initialization value of the sparse codes. Only used if `algorithm='lasso_cd'`. max_iter: int, 1000 by default Maximum number of iterations to perform if `algorithm='lasso_cd'`. copy_cov: boolean, optional Whether to copy the precomputed covariance matrix; if False, it may be overwritten. n_jobs: int, optional Number of parallel jobs to run. check_input: boolean, optional If False, the input arrays X and dictionary will not be checked. verbose : int, optional Controls the verbosity; the higher, the more messages. Defaults to 0. Returns ------- code: array of shape (n_samples, n_components) The sparse codes See also -------- sklearn.linear_model.lars_path sklearn.linear_model.orthogonal_mp sklearn.linear_model.Lasso SparseCoder
Sparse coding
[ "Sparse", "coding" ]
def sparse_encode(X, dictionary, gram=None, cov=None, algorithm='lasso_lars', n_nonzero_coefs=None, alpha=None, copy_cov=True, init=None, max_iter=1000, n_jobs=1, check_input=True, verbose=0): """Sparse coding Each row of the result is the solution to a sparse coding problem. The goal is to find a sparse array `code` such that:: X ~= code * dictionary Read more in the :ref:`User Guide <SparseCoder>`. Parameters ---------- X: array of shape (n_samples, n_features) Data matrix dictionary: array of shape (n_components, n_features) The dictionary matrix against which to solve the sparse coding of the data. Some of the algorithms assume normalized rows for meaningful output. gram: array, shape=(n_components, n_components) Precomputed Gram matrix, dictionary * dictionary' cov: array, shape=(n_components, n_samples) Precomputed covariance, dictionary' * X algorithm: {'lasso_lars', 'lasso_cd', 'lars', 'omp', 'threshold'} lars: uses the least angle regression method (linear_model.lars_path) lasso_lars: uses Lars to compute the Lasso solution lasso_cd: uses the coordinate descent method to compute the Lasso solution (linear_model.Lasso). lasso_lars will be faster if the estimated components are sparse. omp: uses orthogonal matching pursuit to estimate the sparse solution threshold: squashes to zero all coefficients less than alpha from the projection dictionary * X' n_nonzero_coefs: int, 0.1 * n_features by default Number of nonzero coefficients to target in each column of the solution. This is only used by `algorithm='lars'` and `algorithm='omp'` and is overridden by `alpha` in the `omp` case. alpha: float, 1. by default If `algorithm='lasso_lars'` or `algorithm='lasso_cd'`, `alpha` is the penalty applied to the L1 norm. If `algorithm='threshold'`, `alpha` is the absolute value of the threshold below which coefficients will be squashed to zero. If `algorithm='omp'`, `alpha` is the tolerance parameter: the value of the reconstruction error targeted. In this case, it overrides `n_nonzero_coefs`. init: array of shape (n_samples, n_components) Initialization value of the sparse codes. Only used if `algorithm='lasso_cd'`. max_iter: int, 1000 by default Maximum number of iterations to perform if `algorithm='lasso_cd'`. copy_cov: boolean, optional Whether to copy the precomputed covariance matrix; if False, it may be overwritten. n_jobs: int, optional Number of parallel jobs to run. check_input: boolean, optional If False, the input arrays X and dictionary will not be checked. verbose : int, optional Controls the verbosity; the higher, the more messages. Defaults to 0. Returns ------- code: array of shape (n_samples, n_components) The sparse codes See also -------- sklearn.linear_model.lars_path sklearn.linear_model.orthogonal_mp sklearn.linear_model.Lasso SparseCoder """ if check_input: if algorithm == 'lasso_cd': dictionary = check_array(dictionary, order='C', dtype='float64') X = check_array(X, order='C', dtype='float64') else: dictionary = check_array(dictionary) X = check_array(X) n_samples, n_features = X.shape n_components = dictionary.shape[0] if gram is None and algorithm != 'threshold': gram = np.dot(dictionary, dictionary.T) if cov is None and algorithm != 'lasso_cd': copy_cov = False cov = np.dot(dictionary, X.T) if algorithm in ('lars', 'omp'): regularization = n_nonzero_coefs if regularization is None: regularization = min(max(n_features / 10, 1), n_components) else: regularization = alpha if regularization is None: regularization = 1. if n_jobs == 1 or algorithm == 'threshold': code = _sparse_encode(X, dictionary, gram, cov=cov, algorithm=algorithm, regularization=regularization, copy_cov=copy_cov, init=init, max_iter=max_iter, check_input=False, verbose=verbose) # This ensure that dimensionality of code is always 2, # consistant with the case n_jobs > 1 if code.ndim == 1: code = code[np.newaxis, :] return code # Enter parallel code block code = np.empty((n_samples, n_components)) slices = list(gen_even_slices(n_samples, _get_n_jobs(n_jobs))) code_views = Parallel(n_jobs=n_jobs, verbose=verbose)( delayed(_sparse_encode)( X[this_slice], dictionary, gram, cov[:, this_slice] if cov is not None else None, algorithm, regularization=regularization, copy_cov=copy_cov, init=init[this_slice] if init is not None else None, max_iter=max_iter, check_input=False) for this_slice in slices) for this_slice, this_view in zip(slices, code_views): code[this_slice] = this_view return code
[ "def", "sparse_encode", "(", "X", ",", "dictionary", ",", "gram", "=", "None", ",", "cov", "=", "None", ",", "algorithm", "=", "'lasso_lars'", ",", "n_nonzero_coefs", "=", "None", ",", "alpha", "=", "None", ",", "copy_cov", "=", "True", ",", "init", "=", "None", ",", "max_iter", "=", "1000", ",", "n_jobs", "=", "1", ",", "check_input", "=", "True", ",", "verbose", "=", "0", ")", ":", "if", "check_input", ":", "if", "algorithm", "==", "'lasso_cd'", ":", "dictionary", "=", "check_array", "(", "dictionary", ",", "order", "=", "'C'", ",", "dtype", "=", "'float64'", ")", "X", "=", "check_array", "(", "X", ",", "order", "=", "'C'", ",", "dtype", "=", "'float64'", ")", "else", ":", "dictionary", "=", "check_array", "(", "dictionary", ")", "X", "=", "check_array", "(", "X", ")", "n_samples", ",", "n_features", "=", "X", ".", "shape", "n_components", "=", "dictionary", ".", "shape", "[", "0", "]", "if", "gram", "is", "None", "and", "algorithm", "!=", "'threshold'", ":", "gram", "=", "np", ".", "dot", "(", "dictionary", ",", "dictionary", ".", "T", ")", "if", "cov", "is", "None", "and", "algorithm", "!=", "'lasso_cd'", ":", "copy_cov", "=", "False", "cov", "=", "np", ".", "dot", "(", "dictionary", ",", "X", ".", "T", ")", "if", "algorithm", "in", "(", "'lars'", ",", "'omp'", ")", ":", "regularization", "=", "n_nonzero_coefs", "if", "regularization", "is", "None", ":", "regularization", "=", "min", "(", "max", "(", "n_features", "/", "10", ",", "1", ")", ",", "n_components", ")", "else", ":", "regularization", "=", "alpha", "if", "regularization", "is", "None", ":", "regularization", "=", "1.", "if", "n_jobs", "==", "1", "or", "algorithm", "==", "'threshold'", ":", "code", "=", "_sparse_encode", "(", "X", ",", "dictionary", ",", "gram", ",", "cov", "=", "cov", ",", "algorithm", "=", "algorithm", ",", "regularization", "=", "regularization", ",", "copy_cov", "=", "copy_cov", ",", "init", "=", "init", ",", "max_iter", "=", "max_iter", ",", "check_input", "=", "False", ",", "verbose", "=", "verbose", ")", "# This ensure that dimensionality of code is always 2,", "# consistant with the case n_jobs > 1", "if", "code", ".", "ndim", "==", "1", ":", "code", "=", "code", "[", "np", ".", "newaxis", ",", ":", "]", "return", "code", "# Enter parallel code block", "code", "=", "np", ".", "empty", "(", "(", "n_samples", ",", "n_components", ")", ")", "slices", "=", "list", "(", "gen_even_slices", "(", "n_samples", ",", "_get_n_jobs", "(", "n_jobs", ")", ")", ")", "code_views", "=", "Parallel", "(", "n_jobs", "=", "n_jobs", ",", "verbose", "=", "verbose", ")", "(", "delayed", "(", "_sparse_encode", ")", "(", "X", "[", "this_slice", "]", ",", "dictionary", ",", "gram", ",", "cov", "[", ":", ",", "this_slice", "]", "if", "cov", "is", "not", "None", "else", "None", ",", "algorithm", ",", "regularization", "=", "regularization", ",", "copy_cov", "=", "copy_cov", ",", "init", "=", "init", "[", "this_slice", "]", "if", "init", "is", "not", "None", "else", "None", ",", "max_iter", "=", "max_iter", ",", "check_input", "=", "False", ")", "for", "this_slice", "in", "slices", ")", "for", "this_slice", ",", "this_view", "in", "zip", "(", "slices", ",", "code_views", ")", ":", "code", "[", "this_slice", "]", "=", "this_view", "return", "code" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/decomposition/dict_learning.py#L161-L303
chadmv/cvwrap
51367b050704817cf3e72d4be018c182b4dd8dcb
scripts/cvwrap/menu.py
python
get_wrap_node_from_selected
()
Get a wrap node from the selected geometry.
Get a wrap node from the selected geometry.
[ "Get", "a", "wrap", "node", "from", "the", "selected", "geometry", "." ]
def get_wrap_node_from_selected(): """Get a wrap node from the selected geometry.""" sel = cmds.ls(sl=True) or [] if not sel: raise RuntimeError('No cvWrap found on selected.') if cmds.nodeType(sel[0]) == 'cvWrap': return sel[0] history = cmds.listHistory(sel[0], pdo=0) or [] wrap_nodes = [node for node in history if cmds.nodeType(node) == 'cvWrap'] if not wrap_nodes: raise RuntimeError('No cvWrap node found on {0}.'.format(sel[0])) if len(wrap_nodes) == 1: return wrap_nodes[0] else: # Multiple wrap nodes are deforming the mesh. Let the user choose which one # to use. return QtGui.QInputDialog.getItem(None, 'Select cvWrap node', 'cvWrap node:', wrap_nodes)
[ "def", "get_wrap_node_from_selected", "(", ")", ":", "sel", "=", "cmds", ".", "ls", "(", "sl", "=", "True", ")", "or", "[", "]", "if", "not", "sel", ":", "raise", "RuntimeError", "(", "'No cvWrap found on selected.'", ")", "if", "cmds", ".", "nodeType", "(", "sel", "[", "0", "]", ")", "==", "'cvWrap'", ":", "return", "sel", "[", "0", "]", "history", "=", "cmds", ".", "listHistory", "(", "sel", "[", "0", "]", ",", "pdo", "=", "0", ")", "or", "[", "]", "wrap_nodes", "=", "[", "node", "for", "node", "in", "history", "if", "cmds", ".", "nodeType", "(", "node", ")", "==", "'cvWrap'", "]", "if", "not", "wrap_nodes", ":", "raise", "RuntimeError", "(", "'No cvWrap node found on {0}.'", ".", "format", "(", "sel", "[", "0", "]", ")", ")", "if", "len", "(", "wrap_nodes", ")", "==", "1", ":", "return", "wrap_nodes", "[", "0", "]", "else", ":", "# Multiple wrap nodes are deforming the mesh. Let the user choose which one", "# to use.", "return", "QtGui", ".", "QInputDialog", ".", "getItem", "(", "None", ",", "'Select cvWrap node'", ",", "'cvWrap node:'", ",", "wrap_nodes", ")" ]
https://github.com/chadmv/cvwrap/blob/51367b050704817cf3e72d4be018c182b4dd8dcb/scripts/cvwrap/menu.py#L210-L226
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/python/framework/ops.py
python
Operation.traceback_with_start_lines
(self)
return self._graph._convert_stack( # pylint: disable=protected-access self._traceback, include_func_start_lineno=True)
Same as traceback but includes start line of function definition. Returns: A list of 5-tuples (filename, lineno, name, code, func_start_lineno).
Same as traceback but includes start line of function definition.
[ "Same", "as", "traceback", "but", "includes", "start", "line", "of", "function", "definition", "." ]
def traceback_with_start_lines(self): """Same as traceback but includes start line of function definition. Returns: A list of 5-tuples (filename, lineno, name, code, func_start_lineno). """ return self._graph._convert_stack( # pylint: disable=protected-access self._traceback, include_func_start_lineno=True)
[ "def", "traceback_with_start_lines", "(", "self", ")", ":", "return", "self", ".", "_graph", ".", "_convert_stack", "(", "# pylint: disable=protected-access", "self", ".", "_traceback", ",", "include_func_start_lineno", "=", "True", ")" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/framework/ops.py#L1681-L1688
kamyu104/LeetCode-Solutions
77605708a927ea3b85aee5a479db733938c7c211
Python/advantage-shuffle.py
python
Solution.advantageCount
(self, A, B)
return [candidates[b].pop() if candidates[b] else others.pop() for b in B]
:type A: List[int] :type B: List[int] :rtype: List[int]
:type A: List[int] :type B: List[int] :rtype: List[int]
[ ":", "type", "A", ":", "List", "[", "int", "]", ":", "type", "B", ":", "List", "[", "int", "]", ":", "rtype", ":", "List", "[", "int", "]" ]
def advantageCount(self, A, B): """ :type A: List[int] :type B: List[int] :rtype: List[int] """ sortedA = sorted(A) sortedB = sorted(B) candidates = {b: [] for b in B} others = [] j = 0 for a in sortedA: if a > sortedB[j]: candidates[sortedB[j]].append(a) j += 1 else: others.append(a) return [candidates[b].pop() if candidates[b] else others.pop() for b in B]
[ "def", "advantageCount", "(", "self", ",", "A", ",", "B", ")", ":", "sortedA", "=", "sorted", "(", "A", ")", "sortedB", "=", "sorted", "(", "B", ")", "candidates", "=", "{", "b", ":", "[", "]", "for", "b", "in", "B", "}", "others", "=", "[", "]", "j", "=", "0", "for", "a", "in", "sortedA", ":", "if", "a", ">", "sortedB", "[", "j", "]", ":", "candidates", "[", "sortedB", "[", "j", "]", "]", ".", "append", "(", "a", ")", "j", "+=", "1", "else", ":", "others", ".", "append", "(", "a", ")", "return", "[", "candidates", "[", "b", "]", ".", "pop", "(", ")", "if", "candidates", "[", "b", "]", "else", "others", ".", "pop", "(", ")", "for", "b", "in", "B", "]" ]
https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/advantage-shuffle.py#L5-L24
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_misc.py
python
StandardPaths.GetDocumentsDir
(*args, **kwargs)
return _misc_.StandardPaths_GetDocumentsDir(*args, **kwargs)
GetDocumentsDir(self) -> String Return the Documents directory for the current user. C:/Documents and Settings/username/Documents under Windows, $HOME under Unix and ~/Documents under Mac
GetDocumentsDir(self) -> String
[ "GetDocumentsDir", "(", "self", ")", "-", ">", "String" ]
def GetDocumentsDir(*args, **kwargs): """ GetDocumentsDir(self) -> String Return the Documents directory for the current user. C:/Documents and Settings/username/Documents under Windows, $HOME under Unix and ~/Documents under Mac """ return _misc_.StandardPaths_GetDocumentsDir(*args, **kwargs)
[ "def", "GetDocumentsDir", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_misc_", ".", "StandardPaths_GetDocumentsDir", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_misc.py#L6412-L6421
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
tools/perf/metrics/histogram_util.py
python
GetHistogramCount
(histogram_type, histogram_name, tab)
Get the count of events for the given histograms.
Get the count of events for the given histograms.
[ "Get", "the", "count", "of", "events", "for", "the", "given", "histograms", "." ]
def GetHistogramCount(histogram_type, histogram_name, tab): """Get the count of events for the given histograms.""" histogram_json = GetHistogram(histogram_type, histogram_name, tab) histogram = json.loads(histogram_json) if 'count' in histogram: return histogram['count'] else: return 0
[ "def", "GetHistogramCount", "(", "histogram_type", ",", "histogram_name", ",", "tab", ")", ":", "histogram_json", "=", "GetHistogram", "(", "histogram_type", ",", "histogram_name", ",", "tab", ")", "histogram", "=", "json", ".", "loads", "(", "histogram_json", ")", "if", "'count'", "in", "histogram", ":", "return", "histogram", "[", "'count'", "]", "else", ":", "return", "0" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/perf/metrics/histogram_util.py#L76-L83
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/utils.py
python
bit_length
(intval)
Return the number of bits necessary to represent integer `intval`.
Return the number of bits necessary to represent integer `intval`.
[ "Return", "the", "number", "of", "bits", "necessary", "to", "represent", "integer", "intval", "." ]
def bit_length(intval): """ Return the number of bits necessary to represent integer `intval`. """ assert isinstance(intval, INT_TYPES) if intval >= 0: return len(bin(intval)) - 2 else: return len(bin(-intval - 1)) - 2
[ "def", "bit_length", "(", "intval", ")", ":", "assert", "isinstance", "(", "intval", ",", "INT_TYPES", ")", "if", "intval", ">=", "0", ":", "return", "len", "(", "bin", "(", "intval", ")", ")", "-", "2", "else", ":", "return", "len", "(", "bin", "(", "-", "intval", "-", "1", ")", ")", "-", "2" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/utils.py#L416-L424
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py2/scipy/io/matlab/mio5.py
python
MatFile5Reader.get_variables
(self, variable_names=None)
return mdict
get variables from stream as dictionary variable_names - optional list of variable names to get If variable_names is None, then get all variables in file
get variables from stream as dictionary
[ "get", "variables", "from", "stream", "as", "dictionary" ]
def get_variables(self, variable_names=None): ''' get variables from stream as dictionary variable_names - optional list of variable names to get If variable_names is None, then get all variables in file ''' if isinstance(variable_names, string_types): variable_names = [variable_names] elif variable_names is not None: variable_names = list(variable_names) self.mat_stream.seek(0) # Here we pass all the parameters in self to the reading objects self.initialize_read() mdict = self.read_file_header() mdict['__globals__'] = [] while not self.end_of_stream(): hdr, next_position = self.read_var_header() name = asstr(hdr.name) if name in mdict: warnings.warn('Duplicate variable name "%s" in stream' ' - replacing previous with new\n' 'Consider mio5.varmats_from_mat to split ' 'file into single variable files' % name, MatReadWarning, stacklevel=2) if name == '': # can only be a matlab 7 function workspace name = '__function_workspace__' # We want to keep this raw because mat_dtype processing # will break the format (uint8 as mxDOUBLE_CLASS) process = False else: process = True if variable_names is not None and name not in variable_names: self.mat_stream.seek(next_position) continue try: res = self.read_var_array(hdr, process) except MatReadError as err: warnings.warn( 'Unreadable variable "%s", because "%s"' % (name, err), Warning, stacklevel=2) res = "Read error: %s" % err self.mat_stream.seek(next_position) mdict[name] = res if hdr.is_global: mdict['__globals__'].append(name) if variable_names is not None: variable_names.remove(name) if len(variable_names) == 0: break return mdict
[ "def", "get_variables", "(", "self", ",", "variable_names", "=", "None", ")", ":", "if", "isinstance", "(", "variable_names", ",", "string_types", ")", ":", "variable_names", "=", "[", "variable_names", "]", "elif", "variable_names", "is", "not", "None", ":", "variable_names", "=", "list", "(", "variable_names", ")", "self", ".", "mat_stream", ".", "seek", "(", "0", ")", "# Here we pass all the parameters in self to the reading objects", "self", ".", "initialize_read", "(", ")", "mdict", "=", "self", ".", "read_file_header", "(", ")", "mdict", "[", "'__globals__'", "]", "=", "[", "]", "while", "not", "self", ".", "end_of_stream", "(", ")", ":", "hdr", ",", "next_position", "=", "self", ".", "read_var_header", "(", ")", "name", "=", "asstr", "(", "hdr", ".", "name", ")", "if", "name", "in", "mdict", ":", "warnings", ".", "warn", "(", "'Duplicate variable name \"%s\" in stream'", "' - replacing previous with new\\n'", "'Consider mio5.varmats_from_mat to split '", "'file into single variable files'", "%", "name", ",", "MatReadWarning", ",", "stacklevel", "=", "2", ")", "if", "name", "==", "''", ":", "# can only be a matlab 7 function workspace", "name", "=", "'__function_workspace__'", "# We want to keep this raw because mat_dtype processing", "# will break the format (uint8 as mxDOUBLE_CLASS)", "process", "=", "False", "else", ":", "process", "=", "True", "if", "variable_names", "is", "not", "None", "and", "name", "not", "in", "variable_names", ":", "self", ".", "mat_stream", ".", "seek", "(", "next_position", ")", "continue", "try", ":", "res", "=", "self", ".", "read_var_array", "(", "hdr", ",", "process", ")", "except", "MatReadError", "as", "err", ":", "warnings", ".", "warn", "(", "'Unreadable variable \"%s\", because \"%s\"'", "%", "(", "name", ",", "err", ")", ",", "Warning", ",", "stacklevel", "=", "2", ")", "res", "=", "\"Read error: %s\"", "%", "err", "self", ".", "mat_stream", ".", "seek", "(", "next_position", ")", "mdict", "[", "name", "]", "=", "res", "if", "hdr", ".", "is_global", ":", "mdict", "[", "'__globals__'", "]", ".", "append", "(", "name", ")", "if", "variable_names", "is", "not", "None", ":", "variable_names", ".", "remove", "(", "name", ")", "if", "len", "(", "variable_names", ")", "==", "0", ":", "break", "return", "mdict" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/io/matlab/mio5.py#L254-L307
JoseExposito/touchegg
1f3fda214358d071c05da4bf17c070c33d67b5eb
cmake/cpplint.py
python
ReplaceAll
(pattern, rep, s)
return _regexp_compile_cache[pattern].sub(rep, s)
Replaces instances of pattern in a string with a replacement. The compiled regex is kept in a cache shared by Match and Search. Args: pattern: regex pattern rep: replacement text s: search string Returns: string with replacements made (or original string if no replacements)
Replaces instances of pattern in a string with a replacement.
[ "Replaces", "instances", "of", "pattern", "in", "a", "string", "with", "a", "replacement", "." ]
def ReplaceAll(pattern, rep, s): """Replaces instances of pattern in a string with a replacement. The compiled regex is kept in a cache shared by Match and Search. Args: pattern: regex pattern rep: replacement text s: search string Returns: string with replacements made (or original string if no replacements) """ if pattern not in _regexp_compile_cache: _regexp_compile_cache[pattern] = sre_compile.compile(pattern) return _regexp_compile_cache[pattern].sub(rep, s)
[ "def", "ReplaceAll", "(", "pattern", ",", "rep", ",", "s", ")", ":", "if", "pattern", "not", "in", "_regexp_compile_cache", ":", "_regexp_compile_cache", "[", "pattern", "]", "=", "sre_compile", ".", "compile", "(", "pattern", ")", "return", "_regexp_compile_cache", "[", "pattern", "]", ".", "sub", "(", "rep", ",", "s", ")" ]
https://github.com/JoseExposito/touchegg/blob/1f3fda214358d071c05da4bf17c070c33d67b5eb/cmake/cpplint.py#L667-L682
BitMEX/api-connectors
37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812
auto-generated/python/swagger_client/models/announcement.py
python
Announcement.id
(self, id)
Sets the id of this Announcement. :param id: The id of this Announcement. # noqa: E501 :type: float
Sets the id of this Announcement.
[ "Sets", "the", "id", "of", "this", "Announcement", "." ]
def id(self, id): """Sets the id of this Announcement. :param id: The id of this Announcement. # noqa: E501 :type: float """ if id is None: raise ValueError("Invalid value for `id`, must not be `None`") # noqa: E501 self._id = id
[ "def", "id", "(", "self", ",", "id", ")", ":", "if", "id", "is", "None", ":", "raise", "ValueError", "(", "\"Invalid value for `id`, must not be `None`\"", ")", "# noqa: E501", "self", ".", "_id", "=", "id" ]
https://github.com/BitMEX/api-connectors/blob/37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812/auto-generated/python/swagger_client/models/announcement.py#L80-L90
google/zooshi
05390b98f79eed8ef26ec4ab2c3aea3790b1165c
scripts/build_assets.py
python
fbx_files_to_convert
()
return glob.glob(os.path.join(RAW_MESH_PATH, '*.fbx'))
FBX files to convert to fplmesh.
FBX files to convert to fplmesh.
[ "FBX", "files", "to", "convert", "to", "fplmesh", "." ]
def fbx_files_to_convert(): """FBX files to convert to fplmesh.""" return glob.glob(os.path.join(RAW_MESH_PATH, '*.fbx'))
[ "def", "fbx_files_to_convert", "(", ")", ":", "return", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "RAW_MESH_PATH", ",", "'*.fbx'", ")", ")" ]
https://github.com/google/zooshi/blob/05390b98f79eed8ef26ec4ab2c3aea3790b1165c/scripts/build_assets.py#L183-L185
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/stc.py
python
StyledTextEvent.GetLength
(*args, **kwargs)
return _stc.StyledTextEvent_GetLength(*args, **kwargs)
GetLength(self) -> int
GetLength(self) -> int
[ "GetLength", "(", "self", ")", "-", ">", "int" ]
def GetLength(*args, **kwargs): """GetLength(self) -> int""" return _stc.StyledTextEvent_GetLength(*args, **kwargs)
[ "def", "GetLength", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_stc", ".", "StyledTextEvent_GetLength", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/stc.py#L7142-L7144
vslavik/poedit
f7a9daa0a10037e090aa0a86f5ce0f24ececdf6a
deps/boost/tools/build/src/build/engine.py
python
Engine.set_target_variable
(self, targets, variable, value, append=0)
Sets a target variable. The 'variable' will be available to bjam when it decides where to generate targets, and will also be available to updating rule for that 'taret'.
Sets a target variable.
[ "Sets", "a", "target", "variable", "." ]
def set_target_variable (self, targets, variable, value, append=0): """ Sets a target variable. The 'variable' will be available to bjam when it decides where to generate targets, and will also be available to updating rule for that 'taret'. """ if isinstance (targets, str): targets = [targets] if isinstance(value, str): value = [value] assert is_iterable(targets) assert isinstance(variable, basestring) assert is_iterable(value) if targets: if append: bjam_interface.call("set-target-variable", targets, variable, value, "true") else: bjam_interface.call("set-target-variable", targets, variable, value)
[ "def", "set_target_variable", "(", "self", ",", "targets", ",", "variable", ",", "value", ",", "append", "=", "0", ")", ":", "if", "isinstance", "(", "targets", ",", "str", ")", ":", "targets", "=", "[", "targets", "]", "if", "isinstance", "(", "value", ",", "str", ")", ":", "value", "=", "[", "value", "]", "assert", "is_iterable", "(", "targets", ")", "assert", "isinstance", "(", "variable", ",", "basestring", ")", "assert", "is_iterable", "(", "value", ")", "if", "targets", ":", "if", "append", ":", "bjam_interface", ".", "call", "(", "\"set-target-variable\"", ",", "targets", ",", "variable", ",", "value", ",", "\"true\"", ")", "else", ":", "bjam_interface", ".", "call", "(", "\"set-target-variable\"", ",", "targets", ",", "variable", ",", "value", ")" ]
https://github.com/vslavik/poedit/blob/f7a9daa0a10037e090aa0a86f5ce0f24ececdf6a/deps/boost/tools/build/src/build/engine.py#L123-L143
albertz/openlierox
d316c14a8eb57848ef56e9bfa7b23a56f694a51b
tools/DedicatedServerVideo/gdata/docs/service.py
python
DocsService.Download
(self, entry_or_id_or_url, file_path, export_format=None, gid=None, extra_params=None)
Downloads a document from the Document List. Args: entry_or_id_or_url: a DocumentListEntry, or the resource id of an entry, or a url to download from (such as the content src). file_path: string The full path to save the file to. export_format: the format to convert to, if conversion is required. gid: grid id, for downloading a single grid of a spreadsheet extra_params: a map of any further parameters to control how the document is downloaded Raises: RequestError if the service does not respond with success
Downloads a document from the Document List.
[ "Downloads", "a", "document", "from", "the", "Document", "List", "." ]
def Download(self, entry_or_id_or_url, file_path, export_format=None, gid=None, extra_params=None): """Downloads a document from the Document List. Args: entry_or_id_or_url: a DocumentListEntry, or the resource id of an entry, or a url to download from (such as the content src). file_path: string The full path to save the file to. export_format: the format to convert to, if conversion is required. gid: grid id, for downloading a single grid of a spreadsheet extra_params: a map of any further parameters to control how the document is downloaded Raises: RequestError if the service does not respond with success """ if isinstance(entry_or_id_or_url, gdata.docs.DocumentListEntry): url = entry_or_id_or_url.content.src else: if self.__RESOURCE_ID_PATTERN.match(entry_or_id_or_url): url = self._MakeContentLinkFromId(entry_or_id_or_url) else: url = entry_or_id_or_url if export_format is not None: if url.find('/Export?') == -1: raise gdata.service.Error, ('This entry cannot be exported ' 'as a different format') url += '&exportFormat=%s' % export_format if gid is not None: if url.find('spreadsheets') == -1: raise gdata.service.Error, 'grid id param is not valid for this entry' url += '&gid=%s' % gid if extra_params: url += '&' + urllib.urlencode(extra_params) self._DownloadFile(url, file_path)
[ "def", "Download", "(", "self", ",", "entry_or_id_or_url", ",", "file_path", ",", "export_format", "=", "None", ",", "gid", "=", "None", ",", "extra_params", "=", "None", ")", ":", "if", "isinstance", "(", "entry_or_id_or_url", ",", "gdata", ".", "docs", ".", "DocumentListEntry", ")", ":", "url", "=", "entry_or_id_or_url", ".", "content", ".", "src", "else", ":", "if", "self", ".", "__RESOURCE_ID_PATTERN", ".", "match", "(", "entry_or_id_or_url", ")", ":", "url", "=", "self", ".", "_MakeContentLinkFromId", "(", "entry_or_id_or_url", ")", "else", ":", "url", "=", "entry_or_id_or_url", "if", "export_format", "is", "not", "None", ":", "if", "url", ".", "find", "(", "'/Export?'", ")", "==", "-", "1", ":", "raise", "gdata", ".", "service", ".", "Error", ",", "(", "'This entry cannot be exported '", "'as a different format'", ")", "url", "+=", "'&exportFormat=%s'", "%", "export_format", "if", "gid", "is", "not", "None", ":", "if", "url", ".", "find", "(", "'spreadsheets'", ")", "==", "-", "1", ":", "raise", "gdata", ".", "service", ".", "Error", ",", "'grid id param is not valid for this entry'", "url", "+=", "'&gid=%s'", "%", "gid", "if", "extra_params", ":", "url", "+=", "'&'", "+", "urllib", ".", "urlencode", "(", "extra_params", ")", "self", ".", "_DownloadFile", "(", "url", ",", "file_path", ")" ]
https://github.com/albertz/openlierox/blob/d316c14a8eb57848ef56e9bfa7b23a56f694a51b/tools/DedicatedServerVideo/gdata/docs/service.py#L301-L340
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_core.py
python
UpdateUIEvent.GetSetEnabled
(*args, **kwargs)
return _core_.UpdateUIEvent_GetSetEnabled(*args, **kwargs)
GetSetEnabled(self) -> bool Returns ``True`` if the application has called `Enable`. For wxWidgets internal use only.
GetSetEnabled(self) -> bool
[ "GetSetEnabled", "(", "self", ")", "-", ">", "bool" ]
def GetSetEnabled(*args, **kwargs): """ GetSetEnabled(self) -> bool Returns ``True`` if the application has called `Enable`. For wxWidgets internal use only. """ return _core_.UpdateUIEvent_GetSetEnabled(*args, **kwargs)
[ "def", "GetSetEnabled", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "UpdateUIEvent_GetSetEnabled", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L6799-L6806
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Editor/Python/windows/Lib/site-packages/pip/_vendor/distlib/_backport/tarfile.py
python
TarFile._getmember
(self, name, tarinfo=None, normalize=False)
Find an archive member by name from bottom to top. If tarinfo is given, it is used as the starting point.
Find an archive member by name from bottom to top. If tarinfo is given, it is used as the starting point.
[ "Find", "an", "archive", "member", "by", "name", "from", "bottom", "to", "top", ".", "If", "tarinfo", "is", "given", "it", "is", "used", "as", "the", "starting", "point", "." ]
def _getmember(self, name, tarinfo=None, normalize=False): """Find an archive member by name from bottom to top. If tarinfo is given, it is used as the starting point. """ # Ensure that all members have been loaded. members = self.getmembers() # Limit the member search list up to tarinfo. if tarinfo is not None: members = members[:members.index(tarinfo)] if normalize: name = os.path.normpath(name) for member in reversed(members): if normalize: member_name = os.path.normpath(member.name) else: member_name = member.name if name == member_name: return member
[ "def", "_getmember", "(", "self", ",", "name", ",", "tarinfo", "=", "None", ",", "normalize", "=", "False", ")", ":", "# Ensure that all members have been loaded.", "members", "=", "self", ".", "getmembers", "(", ")", "# Limit the member search list up to tarinfo.", "if", "tarinfo", "is", "not", "None", ":", "members", "=", "members", "[", ":", "members", ".", "index", "(", "tarinfo", ")", "]", "if", "normalize", ":", "name", "=", "os", ".", "path", ".", "normpath", "(", "name", ")", "for", "member", "in", "reversed", "(", "members", ")", ":", "if", "normalize", ":", "member_name", "=", "os", ".", "path", ".", "normpath", "(", "member", ".", "name", ")", "else", ":", "member_name", "=", "member", ".", "name", "if", "name", "==", "member_name", ":", "return", "member" ]
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/pip/_vendor/distlib/_backport/tarfile.py#L2463-L2484
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/aui/framemanager.py
python
AuiPaneInfo.CaptionVisible
(self, visible=True, left=False)
return self.SetFlag(self.optionCaption, visible)
Indicates that a pane caption should be visible. If `visible` is ``False``, no pane caption is drawn. :param bool `visible`: whether the caption should be visible or not; :param bool `left`: whether the caption should be drawn on the left (rotated by 90 degrees) or not.
Indicates that a pane caption should be visible. If `visible` is ``False``, no pane caption is drawn.
[ "Indicates", "that", "a", "pane", "caption", "should", "be", "visible", ".", "If", "visible", "is", "False", "no", "pane", "caption", "is", "drawn", "." ]
def CaptionVisible(self, visible=True, left=False): """ Indicates that a pane caption should be visible. If `visible` is ``False``, no pane caption is drawn. :param bool `visible`: whether the caption should be visible or not; :param bool `left`: whether the caption should be drawn on the left (rotated by 90 degrees) or not. """ if left: self.SetFlag(self.optionCaption, False) return self.SetFlag(self.optionCaptionLeft, visible) self.SetFlag(self.optionCaptionLeft, False) return self.SetFlag(self.optionCaption, visible)
[ "def", "CaptionVisible", "(", "self", ",", "visible", "=", "True", ",", "left", "=", "False", ")", ":", "if", "left", ":", "self", ".", "SetFlag", "(", "self", ".", "optionCaption", ",", "False", ")", "return", "self", ".", "SetFlag", "(", "self", ".", "optionCaptionLeft", ",", "visible", ")", "self", ".", "SetFlag", "(", "self", ".", "optionCaptionLeft", ",", "False", ")", "return", "self", ".", "SetFlag", "(", "self", ".", "optionCaption", ",", "visible", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/aui/framemanager.py#L1425-L1439
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_gdi.py
python
FontMapper.GetDefaultConfigPath
(*args, **kwargs)
return _gdi_.FontMapper_GetDefaultConfigPath(*args, **kwargs)
GetDefaultConfigPath() -> String
GetDefaultConfigPath() -> String
[ "GetDefaultConfigPath", "()", "-", ">", "String" ]
def GetDefaultConfigPath(*args, **kwargs): """GetDefaultConfigPath() -> String""" return _gdi_.FontMapper_GetDefaultConfigPath(*args, **kwargs)
[ "def", "GetDefaultConfigPath", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gdi_", ".", "FontMapper_GetDefaultConfigPath", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_gdi.py#L2053-L2055
junhyukoh/caffe-lstm
598d45456fa2a1b127a644f4aa38daa8fb9fc722
scripts/cpp_lint.py
python
GetLineWidth
(line)
Determines the width of the line in column positions. Args: line: A string, which may be a Unicode string. Returns: The width of the line in column positions, accounting for Unicode combining characters and wide characters.
Determines the width of the line in column positions.
[ "Determines", "the", "width", "of", "the", "line", "in", "column", "positions", "." ]
def GetLineWidth(line): """Determines the width of the line in column positions. Args: line: A string, which may be a Unicode string. Returns: The width of the line in column positions, accounting for Unicode combining characters and wide characters. """ if isinstance(line, unicode): width = 0 for uc in unicodedata.normalize('NFC', line): if unicodedata.east_asian_width(uc) in ('W', 'F'): width += 2 elif not unicodedata.combining(uc): width += 1 return width else: return len(line)
[ "def", "GetLineWidth", "(", "line", ")", ":", "if", "isinstance", "(", "line", ",", "unicode", ")", ":", "width", "=", "0", "for", "uc", "in", "unicodedata", ".", "normalize", "(", "'NFC'", ",", "line", ")", ":", "if", "unicodedata", ".", "east_asian_width", "(", "uc", ")", "in", "(", "'W'", ",", "'F'", ")", ":", "width", "+=", "2", "elif", "not", "unicodedata", ".", "combining", "(", "uc", ")", ":", "width", "+=", "1", "return", "width", "else", ":", "return", "len", "(", "line", ")" ]
https://github.com/junhyukoh/caffe-lstm/blob/598d45456fa2a1b127a644f4aa38daa8fb9fc722/scripts/cpp_lint.py#L3437-L3456
domino-team/openwrt-cc
8b181297c34d14d3ca521cc9f31430d561dbc688
package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/tools/gyp/pylib/gyp/generator/analyzer.py
python
CalculateVariables
(default_variables, params)
Calculate additional variables for use in the build (called by gyp).
Calculate additional variables for use in the build (called by gyp).
[ "Calculate", "additional", "variables", "for", "use", "in", "the", "build", "(", "called", "by", "gyp", ")", "." ]
def CalculateVariables(default_variables, params): """Calculate additional variables for use in the build (called by gyp).""" flavor = gyp.common.GetFlavor(params) if flavor == 'mac': default_variables.setdefault('OS', 'mac') elif flavor == 'win': default_variables.setdefault('OS', 'win') # Copy additional generator configuration data from VS, which is shared # by the Windows Ninja generator. import gyp.generator.msvs as msvs_generator generator_additional_non_configuration_keys = getattr(msvs_generator, 'generator_additional_non_configuration_keys', []) generator_additional_path_sections = getattr(msvs_generator, 'generator_additional_path_sections', []) gyp.msvs_emulation.CalculateCommonVariables(default_variables, params) else: operating_system = flavor if flavor == 'android': operating_system = 'linux' # Keep this legacy behavior for now. default_variables.setdefault('OS', operating_system)
[ "def", "CalculateVariables", "(", "default_variables", ",", "params", ")", ":", "flavor", "=", "gyp", ".", "common", ".", "GetFlavor", "(", "params", ")", "if", "flavor", "==", "'mac'", ":", "default_variables", ".", "setdefault", "(", "'OS'", ",", "'mac'", ")", "elif", "flavor", "==", "'win'", ":", "default_variables", ".", "setdefault", "(", "'OS'", ",", "'win'", ")", "# Copy additional generator configuration data from VS, which is shared", "# by the Windows Ninja generator.", "import", "gyp", ".", "generator", ".", "msvs", "as", "msvs_generator", "generator_additional_non_configuration_keys", "=", "getattr", "(", "msvs_generator", ",", "'generator_additional_non_configuration_keys'", ",", "[", "]", ")", "generator_additional_path_sections", "=", "getattr", "(", "msvs_generator", ",", "'generator_additional_path_sections'", ",", "[", "]", ")", "gyp", ".", "msvs_emulation", ".", "CalculateCommonVariables", "(", "default_variables", ",", "params", ")", "else", ":", "operating_system", "=", "flavor", "if", "flavor", "==", "'android'", ":", "operating_system", "=", "'linux'", "# Keep this legacy behavior for now.", "default_variables", ".", "setdefault", "(", "'OS'", ",", "operating_system", ")" ]
https://github.com/domino-team/openwrt-cc/blob/8b181297c34d14d3ca521cc9f31430d561dbc688/package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/tools/gyp/pylib/gyp/generator/analyzer.py#L518-L538
apache/mesos
97d9a4063332aae3825d78de71611657e05cf5e2
support/cpplint.py
python
CheckForMultilineCommentsAndStrings
(filename, clean_lines, linenum, error)
Logs an error if we see /* ... */ or "..." that extend past one line. /* ... */ comments are legit inside macros, for one line. Otherwise, we prefer // comments, so it's ok to warn about the other. Likewise, it's ok for strings to extend across multiple lines, as long as a line continuation character (backslash) terminates each line. Although not currently prohibited by the C++ style guide, it's ugly and unnecessary. We don't do well with either in this lint program, so we warn about both. 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.
Logs an error if we see /* ... */ or "..." that extend past one line.
[ "Logs", "an", "error", "if", "we", "see", "/", "*", "...", "*", "/", "or", "...", "that", "extend", "past", "one", "line", "." ]
def CheckForMultilineCommentsAndStrings(filename, clean_lines, linenum, error): """Logs an error if we see /* ... */ or "..." that extend past one line. /* ... */ comments are legit inside macros, for one line. Otherwise, we prefer // comments, so it's ok to warn about the other. Likewise, it's ok for strings to extend across multiple lines, as long as a line continuation character (backslash) terminates each line. Although not currently prohibited by the C++ style guide, it's ugly and unnecessary. We don't do well with either in this lint program, so we warn about both. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # Remove all \\ (escaped backslashes) from the line. They are OK, and the # second (escaped) slash may trigger later \" detection erroneously. line = line.replace('\\\\', '') if line.count('/*') > line.count('*/'): error(filename, linenum, 'readability/multiline_comment', 5, 'Complex multi-line /*...*/-style comment found. ' 'Lint may give bogus warnings. ' 'Consider replacing these with //-style comments, ' 'with #if 0...#endif, ' 'or with more clearly structured multi-line comments.') if (line.count('"') - line.count('\\"')) % 2: error(filename, linenum, 'readability/multiline_string', 5, 'Multi-line string ("...") found. This lint script doesn\'t ' 'do well with such strings, and may give bogus warnings. ' 'Use C++11 raw strings or concatenation instead.')
[ "def", "CheckForMultilineCommentsAndStrings", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "# Remove all \\\\ (escaped backslashes) from the line. They are OK, and the", "# second (escaped) slash may trigger later \\\" detection erroneously.", "line", "=", "line", ".", "replace", "(", "'\\\\\\\\'", ",", "''", ")", "if", "line", ".", "count", "(", "'/*'", ")", ">", "line", ".", "count", "(", "'*/'", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'readability/multiline_comment'", ",", "5", ",", "'Complex multi-line /*...*/-style comment found. '", "'Lint may give bogus warnings. '", "'Consider replacing these with //-style comments, '", "'with #if 0...#endif, '", "'or with more clearly structured multi-line comments.'", ")", "if", "(", "line", ".", "count", "(", "'\"'", ")", "-", "line", ".", "count", "(", "'\\\\\"'", ")", ")", "%", "2", ":", "error", "(", "filename", ",", "linenum", ",", "'readability/multiline_string'", ",", "5", ",", "'Multi-line string (\"...\") found. This lint script doesn\\'t '", "'do well with such strings, and may give bogus warnings. '", "'Use C++11 raw strings or concatenation instead.'", ")" ]
https://github.com/apache/mesos/blob/97d9a4063332aae3825d78de71611657e05cf5e2/support/cpplint.py#L2056-L2091