nwo
stringlengths
5
86
sha
stringlengths
40
40
path
stringlengths
4
189
language
stringclasses
1 value
identifier
stringlengths
1
94
parameters
stringlengths
2
4.03k
argument_list
stringclasses
1 value
return_statement
stringlengths
0
11.5k
docstring
stringlengths
1
33.2k
docstring_summary
stringlengths
0
5.15k
docstring_tokens
list
function
stringlengths
34
151k
function_tokens
list
url
stringlengths
90
278
raymondlu/super-animation-samples
04234269112ff0dc32447f27a761dbbb00b8ba17
samples/cocos2d-x-3.1/CocosLuaGame2/frameworks/cocos2d-x/tools/bindings-generator/clang/cindex.py
python
Cursor.objc_type_encoding
(self)
return self._objc_type_encoding
Return the Objective-C type encoding as a str.
Return the Objective-C type encoding as a str.
[ "Return", "the", "Objective", "-", "C", "type", "encoding", "as", "a", "str", "." ]
def objc_type_encoding(self): """Return the Objective-C type encoding as a str.""" if not hasattr(self, '_objc_type_encoding'): self._objc_type_encoding = \ conf.lib.clang_getDeclObjCTypeEncoding(self) return self._objc_type_encoding
[ "def", "objc_type_encoding", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_objc_type_encoding'", ")", ":", "self", ".", "_objc_type_encoding", "=", "conf", ".", "lib", ".", "clang_getDeclObjCTypeEncoding", "(", "self", ")", "return", "self", ".", "_objc_type_encoding" ]
https://github.com/raymondlu/super-animation-samples/blob/04234269112ff0dc32447f27a761dbbb00b8ba17/samples/cocos2d-x-3.1/CocosLuaGame2/frameworks/cocos2d-x/tools/bindings-generator/clang/cindex.py#L1383-L1389
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/fnmatch.py
python
filter
(names, pat)
return result
Construct a list from those elements of the iterable NAMES that match PAT.
Construct a list from those elements of the iterable NAMES that match PAT.
[ "Construct", "a", "list", "from", "those", "elements", "of", "the", "iterable", "NAMES", "that", "match", "PAT", "." ]
def filter(names, pat): """Construct a list from those elements of the iterable NAMES that match PAT.""" result = [] pat = os.path.normcase(pat) match = _compile_pattern(pat) if os.path is posixpath: # normcase on posix is NOP. Optimize it away from the loop. for name in names: if match(name): result.append(name) else: for name in names: if match(os.path.normcase(name)): result.append(name) return result
[ "def", "filter", "(", "names", ",", "pat", ")", ":", "result", "=", "[", "]", "pat", "=", "os", ".", "path", ".", "normcase", "(", "pat", ")", "match", "=", "_compile_pattern", "(", "pat", ")", "if", "os", ".", "path", "is", "posixpath", ":", "# normcase on posix is NOP. Optimize it away from the loop.", "for", "name", "in", "names", ":", "if", "match", "(", "name", ")", ":", "result", ".", "append", "(", "name", ")", "else", ":", "for", "name", "in", "names", ":", "if", "match", "(", "os", ".", "path", ".", "normcase", "(", "name", ")", ")", ":", "result", ".", "append", "(", "name", ")", "return", "result" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/fnmatch.py#L54-L68
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/_strptime.py
python
TimeRE.compile
(self, format)
return re_compile(self.pattern(format), IGNORECASE)
Return a compiled re object for the format string.
Return a compiled re object for the format string.
[ "Return", "a", "compiled", "re", "object", "for", "the", "format", "string", "." ]
def compile(self, format): """Return a compiled re object for the format string.""" return re_compile(self.pattern(format), IGNORECASE)
[ "def", "compile", "(", "self", ",", "format", ")", ":", "return", "re_compile", "(", "self", ".", "pattern", "(", "format", ")", ",", "IGNORECASE", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/_strptime.py#L261-L263
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/control-examples/klampt_catkin/src/klampt/scripts/controller.py
python
MultiController.__init__
(self,controllers=[])
Given a list of controllers, will execute all of them (in sequence) on each time step.
Given a list of controllers, will execute all of them (in sequence) on each time step.
[ "Given", "a", "list", "of", "controllers", "will", "execute", "all", "of", "them", "(", "in", "sequence", ")", "on", "each", "time", "step", "." ]
def __init__(self,controllers=[]): """Given a list of controllers, will execute all of them (in sequence) on each time step. """ self.controllers = controllers[:] self.register = {} self.outregister = {} self.inmap = [None for c in self.controllers] self.outmap = [None for c in self.controllers] self.myoutmap = None
[ "def", "__init__", "(", "self", ",", "controllers", "=", "[", "]", ")", ":", "self", ".", "controllers", "=", "controllers", "[", ":", "]", "self", ".", "register", "=", "{", "}", "self", ".", "outregister", "=", "{", "}", "self", ".", "inmap", "=", "[", "None", "for", "c", "in", "self", ".", "controllers", "]", "self", ".", "outmap", "=", "[", "None", "for", "c", "in", "self", ".", "controllers", "]", "self", ".", "myoutmap", "=", "None" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/control-examples/klampt_catkin/src/klampt/scripts/controller.py#L73-L82
arangodb/arangodb
0d658689c7d1b721b314fa3ca27d38303e1570c8
3rdParty/V8/gyp/msvs_emulation.py
python
MsvsSettings.IsEmbedManifest
(self, config)
return embed == 'true'
Returns whether manifest should be linked into binary.
Returns whether manifest should be linked into binary.
[ "Returns", "whether", "manifest", "should", "be", "linked", "into", "binary", "." ]
def IsEmbedManifest(self, config): """Returns whether manifest should be linked into binary.""" config = self._TargetConfig(config) embed = self._Setting(('VCManifestTool', 'EmbedManifest'), config, default='true') return embed == 'true'
[ "def", "IsEmbedManifest", "(", "self", ",", "config", ")", ":", "config", "=", "self", ".", "_TargetConfig", "(", "config", ")", "embed", "=", "self", ".", "_Setting", "(", "(", "'VCManifestTool'", ",", "'EmbedManifest'", ")", ",", "config", ",", "default", "=", "'true'", ")", "return", "embed", "==", "'true'" ]
https://github.com/arangodb/arangodb/blob/0d658689c7d1b721b314fa3ca27d38303e1570c8/3rdParty/V8/gyp/msvs_emulation.py#L691-L695
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
build/android/play_services/utils.py
python
IsRepoDirty
(repo_root)
return cmd_helper.Call(cmd, cwd=repo_root) == 1
Returns True if there are no staged or modified files, False otherwise.
Returns True if there are no staged or modified files, False otherwise.
[ "Returns", "True", "if", "there", "are", "no", "staged", "or", "modified", "files", "False", "otherwise", "." ]
def IsRepoDirty(repo_root): '''Returns True if there are no staged or modified files, False otherwise.''' # diff-index returns 1 if there are staged changes or modified files, # 0 otherwise cmd = ['git', 'diff-index', '--quiet', 'HEAD'] return cmd_helper.Call(cmd, cwd=repo_root) == 1
[ "def", "IsRepoDirty", "(", "repo_root", ")", ":", "# diff-index returns 1 if there are staged changes or modified files,", "# 0 otherwise", "cmd", "=", "[", "'git'", ",", "'diff-index'", ",", "'--quiet'", ",", "'HEAD'", "]", "return", "cmd_helper", ".", "Call", "(", "cmd", ",", "cwd", "=", "repo_root", ")", "==", "1" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/build/android/play_services/utils.py#L137-L143
microsoft/TSS.MSR
0f2516fca2cd9929c31d5450e39301c9bde43688
TSS.Py/src/TpmTypes.py
python
TPM2_Quote_REQUEST.fromBytes
(buffer)
return TpmBuffer(buffer).createObj(TPM2_Quote_REQUEST)
Returns new TPM2_Quote_REQUEST object constructed from its marshaled representation in the given byte buffer
Returns new TPM2_Quote_REQUEST object constructed from its marshaled representation in the given byte buffer
[ "Returns", "new", "TPM2_Quote_REQUEST", "object", "constructed", "from", "its", "marshaled", "representation", "in", "the", "given", "byte", "buffer" ]
def fromBytes(buffer): """ Returns new TPM2_Quote_REQUEST object constructed from its marshaled representation in the given byte buffer """ return TpmBuffer(buffer).createObj(TPM2_Quote_REQUEST)
[ "def", "fromBytes", "(", "buffer", ")", ":", "return", "TpmBuffer", "(", "buffer", ")", ".", "createObj", "(", "TPM2_Quote_REQUEST", ")" ]
https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L12688-L12692
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/pkg_resources/__init__.py
python
ResourceManager.resource_exists
(self, package_or_requirement, resource_name)
return get_provider(package_or_requirement).has_resource(resource_name)
Does the named resource exist?
Does the named resource exist?
[ "Does", "the", "named", "resource", "exist?" ]
def resource_exists(self, package_or_requirement, resource_name): """Does the named resource exist?""" return get_provider(package_or_requirement).has_resource(resource_name)
[ "def", "resource_exists", "(", "self", ",", "package_or_requirement", ",", "resource_name", ")", ":", "return", "get_provider", "(", "package_or_requirement", ")", ".", "has_resource", "(", "resource_name", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pkg_resources/__init__.py#L1133-L1135
MTG/gaia
0f7214dbdec6f9b651ca34211824841ffba0bc77
src/bindings/pygaia/utils.py
python
generateMergeFilelist
(basedir, relative = True, validFile = lambda x: x.endswith('.sig'), filename2gid = lambda x: splitext(basename(x))[0])
return result
Generate a dictionary of IDs to absolute filenames ready to be used for merging a DataSet. This will look for all the files inside basedir for which the validFile function is true. The IDs will be built by taking the basename of the file and removing its extension.
Generate a dictionary of IDs to absolute filenames ready to be used for merging a DataSet. This will look for all the files inside basedir for which the validFile function is true. The IDs will be built by taking the basename of the file and removing its extension.
[ "Generate", "a", "dictionary", "of", "IDs", "to", "absolute", "filenames", "ready", "to", "be", "used", "for", "merging", "a", "DataSet", ".", "This", "will", "look", "for", "all", "the", "files", "inside", "basedir", "for", "which", "the", "validFile", "function", "is", "true", ".", "The", "IDs", "will", "be", "built", "by", "taking", "the", "basename", "of", "the", "file", "and", "removing", "its", "extension", "." ]
def generateMergeFilelist(basedir, relative = True, validFile = lambda x: x.endswith('.sig'), filename2gid = lambda x: splitext(basename(x))[0]): """Generate a dictionary of IDs to absolute filenames ready to be used for merging a DataSet. This will look for all the files inside basedir for which the validFile function is true. The IDs will be built by taking the basename of the file and removing its extension.""" # get the list of all valid files inside this directory filenames = [] for root, dirs, files in os.walk(basedir, followlinks = True): filenames += [ join(root, filename) for filename in files if validFile(filename) ] if relative: l = len(basedir) + 1 # +1 for trailing '/' filenames = [ f[l:] for f in filenames ] else: filenames = [ abspath(f) for f in filenames ] # create a dictionary with their extracted IDs as keys result = dict((filename2gid(filename), filename) for filename in filenames) # make sure we don't have 2 files that didn't accidentally end up with the same ID #assert len(result) == len(filenames) if len(result) != len(filenames): print('\nERROR: there are some which end up being duplicates when taking their ID:') # need to find which are duplicates and print them from collections import defaultdict d = defaultdict(list) for filename in filenames: d[filename2gid(filename)] += [ filename ] for pid, filenames in d.items(): if len(filenames) > 1: print('\n%s:' % pid) for f in filenames: print(' -', f) assert False return result
[ "def", "generateMergeFilelist", "(", "basedir", ",", "relative", "=", "True", ",", "validFile", "=", "lambda", "x", ":", "x", ".", "endswith", "(", "'.sig'", ")", ",", "filename2gid", "=", "lambda", "x", ":", "splitext", "(", "basename", "(", "x", ")", ")", "[", "0", "]", ")", ":", "# get the list of all valid files inside this directory", "filenames", "=", "[", "]", "for", "root", ",", "dirs", ",", "files", "in", "os", ".", "walk", "(", "basedir", ",", "followlinks", "=", "True", ")", ":", "filenames", "+=", "[", "join", "(", "root", ",", "filename", ")", "for", "filename", "in", "files", "if", "validFile", "(", "filename", ")", "]", "if", "relative", ":", "l", "=", "len", "(", "basedir", ")", "+", "1", "# +1 for trailing '/'", "filenames", "=", "[", "f", "[", "l", ":", "]", "for", "f", "in", "filenames", "]", "else", ":", "filenames", "=", "[", "abspath", "(", "f", ")", "for", "f", "in", "filenames", "]", "# create a dictionary with their extracted IDs as keys", "result", "=", "dict", "(", "(", "filename2gid", "(", "filename", ")", ",", "filename", ")", "for", "filename", "in", "filenames", ")", "# make sure we don't have 2 files that didn't accidentally end up with the same ID", "#assert len(result) == len(filenames)", "if", "len", "(", "result", ")", "!=", "len", "(", "filenames", ")", ":", "print", "(", "'\\nERROR: there are some which end up being duplicates when taking their ID:'", ")", "# need to find which are duplicates and print them", "from", "collections", "import", "defaultdict", "d", "=", "defaultdict", "(", "list", ")", "for", "filename", "in", "filenames", ":", "d", "[", "filename2gid", "(", "filename", ")", "]", "+=", "[", "filename", "]", "for", "pid", ",", "filenames", "in", "d", ".", "items", "(", ")", ":", "if", "len", "(", "filenames", ")", ">", "1", ":", "print", "(", "'\\n%s:'", "%", "pid", ")", "for", "f", "in", "filenames", ":", "print", "(", "' -'", ",", "f", ")", "assert", "False", "return", "result" ]
https://github.com/MTG/gaia/blob/0f7214dbdec6f9b651ca34211824841ffba0bc77/src/bindings/pygaia/utils.py#L92-L132
opencv/opencv
76aff8478883858f0e46746044348ebb16dc3c67
doc/pattern_tools/svgfig.py
python
funcRtoC
(expr, var="t", globals=None, locals=None)
return output2
Converts a complex "z(t)" string to a function acceptable for Curve. expr required string in the form "z(t)" var default="t" name of the independent variable globals default=None dict of global variables used in the expression; you may want to use Python's builtin globals() locals default=None dict of local variables
Converts a complex "z(t)" string to a function acceptable for Curve.
[ "Converts", "a", "complex", "z", "(", "t", ")", "string", "to", "a", "function", "acceptable", "for", "Curve", "." ]
def funcRtoC(expr, var="t", globals=None, locals=None): """Converts a complex "z(t)" string to a function acceptable for Curve. expr required string in the form "z(t)" var default="t" name of the independent variable globals default=None dict of global variables used in the expression; you may want to use Python's builtin globals() locals default=None dict of local variables """ if locals is None: locals = {} # python 2.3's eval() won't accept None g = cmath.__dict__ if globals is not None: g.update(globals) output = eval("lambda %s: (%s)" % (var, expr), g, locals) split = lambda z: (z.real, z.imag) output2 = lambda t: split(output(t)) set_func_name(output2, "%s -> %s" % (var, expr)) return output2
[ "def", "funcRtoC", "(", "expr", ",", "var", "=", "\"t\"", ",", "globals", "=", "None", ",", "locals", "=", "None", ")", ":", "if", "locals", "is", "None", ":", "locals", "=", "{", "}", "# python 2.3's eval() won't accept None", "g", "=", "cmath", ".", "__dict__", "if", "globals", "is", "not", "None", ":", "g", ".", "update", "(", "globals", ")", "output", "=", "eval", "(", "\"lambda %s: (%s)\"", "%", "(", "var", ",", "expr", ")", ",", "g", ",", "locals", ")", "split", "=", "lambda", "z", ":", "(", "z", ".", "real", ",", "z", ".", "imag", ")", "output2", "=", "lambda", "t", ":", "split", "(", "output", "(", "t", ")", ")", "set_func_name", "(", "output2", ",", "\"%s -> %s\"", "%", "(", "var", ",", "expr", ")", ")", "return", "output2" ]
https://github.com/opencv/opencv/blob/76aff8478883858f0e46746044348ebb16dc3c67/doc/pattern_tools/svgfig.py#L1584-L1602
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/html.py
python
HtmlDCRenderer.__init__
(self, *args, **kwargs)
__init__(self) -> HtmlDCRenderer
__init__(self) -> HtmlDCRenderer
[ "__init__", "(", "self", ")", "-", ">", "HtmlDCRenderer" ]
def __init__(self, *args, **kwargs): """__init__(self) -> HtmlDCRenderer""" _html.HtmlDCRenderer_swiginit(self,_html.new_HtmlDCRenderer(*args, **kwargs))
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_html", ".", "HtmlDCRenderer_swiginit", "(", "self", ",", "_html", ".", "new_HtmlDCRenderer", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/html.py#L1224-L1226
appcelerator-archive/titanium_desktop
37dbaab5664e595115e2fcdc348ed125cd50b48d
site_scons/simplejson/__init__.py
python
loads
(s, encoding=None, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, **kw)
return cls(encoding=encoding, **kw).decode(s)
Deserialize ``s`` (a ``str`` or ``unicode`` instance containing a JSON document) to a Python object. If ``s`` is a ``str`` instance and is encoded with an ASCII based encoding other than utf-8 (e.g. latin-1) then an appropriate ``encoding`` name must be specified. Encodings that are not ASCII based (such as UCS-2) are not allowed and should be decoded to ``unicode`` first. ``object_hook`` is an optional function that will be called with the result of any object literal decode (a ``dict``). The return value of ``object_hook`` will be used instead of the ``dict``. This feature can be used to implement custom decoders (e.g. JSON-RPC class hinting). ``parse_float``, if specified, will be called with the string of every JSON float to be decoded. By default this is equivalent to float(num_str). This can be used to use another datatype or parser for JSON floats (e.g. decimal.Decimal). ``parse_int``, if specified, will be called with the string of every JSON int to be decoded. By default this is equivalent to int(num_str). This can be used to use another datatype or parser for JSON integers (e.g. float). ``parse_constant``, if specified, will be called with one of the following strings: -Infinity, Infinity, NaN, null, true, false. This can be used to raise an exception if invalid JSON numbers are encountered. To use a custom ``JSONDecoder`` subclass, specify it with the ``cls`` kwarg.
Deserialize ``s`` (a ``str`` or ``unicode`` instance containing a JSON document) to a Python object.
[ "Deserialize", "s", "(", "a", "str", "or", "unicode", "instance", "containing", "a", "JSON", "document", ")", "to", "a", "Python", "object", "." ]
def loads(s, encoding=None, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, **kw): """Deserialize ``s`` (a ``str`` or ``unicode`` instance containing a JSON document) to a Python object. If ``s`` is a ``str`` instance and is encoded with an ASCII based encoding other than utf-8 (e.g. latin-1) then an appropriate ``encoding`` name must be specified. Encodings that are not ASCII based (such as UCS-2) are not allowed and should be decoded to ``unicode`` first. ``object_hook`` is an optional function that will be called with the result of any object literal decode (a ``dict``). The return value of ``object_hook`` will be used instead of the ``dict``. This feature can be used to implement custom decoders (e.g. JSON-RPC class hinting). ``parse_float``, if specified, will be called with the string of every JSON float to be decoded. By default this is equivalent to float(num_str). This can be used to use another datatype or parser for JSON floats (e.g. decimal.Decimal). ``parse_int``, if specified, will be called with the string of every JSON int to be decoded. By default this is equivalent to int(num_str). This can be used to use another datatype or parser for JSON integers (e.g. float). ``parse_constant``, if specified, will be called with one of the following strings: -Infinity, Infinity, NaN, null, true, false. This can be used to raise an exception if invalid JSON numbers are encountered. To use a custom ``JSONDecoder`` subclass, specify it with the ``cls`` kwarg. """ if (cls is None and encoding is None and object_hook is None and parse_int is None and parse_float is None and parse_constant is None and not kw): return _default_decoder.decode(s) if cls is None: cls = JSONDecoder if object_hook is not None: kw['object_hook'] = object_hook if parse_float is not None: kw['parse_float'] = parse_float if parse_int is not None: kw['parse_int'] = parse_int if parse_constant is not None: kw['parse_constant'] = parse_constant return cls(encoding=encoding, **kw).decode(s)
[ "def", "loads", "(", "s", ",", "encoding", "=", "None", ",", "cls", "=", "None", ",", "object_hook", "=", "None", ",", "parse_float", "=", "None", ",", "parse_int", "=", "None", ",", "parse_constant", "=", "None", ",", "*", "*", "kw", ")", ":", "if", "(", "cls", "is", "None", "and", "encoding", "is", "None", "and", "object_hook", "is", "None", "and", "parse_int", "is", "None", "and", "parse_float", "is", "None", "and", "parse_constant", "is", "None", "and", "not", "kw", ")", ":", "return", "_default_decoder", ".", "decode", "(", "s", ")", "if", "cls", "is", "None", ":", "cls", "=", "JSONDecoder", "if", "object_hook", "is", "not", "None", ":", "kw", "[", "'object_hook'", "]", "=", "object_hook", "if", "parse_float", "is", "not", "None", ":", "kw", "[", "'parse_float'", "]", "=", "parse_float", "if", "parse_int", "is", "not", "None", ":", "kw", "[", "'parse_int'", "]", "=", "parse_int", "if", "parse_constant", "is", "not", "None", ":", "kw", "[", "'parse_constant'", "]", "=", "parse_constant", "return", "cls", "(", "encoding", "=", "encoding", ",", "*", "*", "kw", ")", ".", "decode", "(", "s", ")" ]
https://github.com/appcelerator-archive/titanium_desktop/blob/37dbaab5664e595115e2fcdc348ed125cd50b48d/site_scons/simplejson/__init__.py#L270-L318
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/catapult_base/catapult_base/refactor/annotated_symbol/import_statement.py
python
Import.name
(self)
The name used to reference this import's module.
The name used to reference this import's module.
[ "The", "name", "used", "to", "reference", "this", "import", "s", "module", "." ]
def name(self): """The name used to reference this import's module.""" raise NotImplementedError()
[ "def", "name", "(", "self", ")", ":", "raise", "NotImplementedError", "(", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/catapult_base/catapult_base/refactor/annotated_symbol/import_statement.py#L151-L153
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/decimal.py
python
Context.scaleb
(self, a, b)
return a.scaleb(b, context=self)
Returns the first operand after adding the second value its exp. >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2')) Decimal('0.0750') >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0')) Decimal('7.50') >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3')) Decimal('7.50E+3') >>> ExtendedContext.scaleb(1, 4) Decimal('1E+4') >>> ExtendedContext.scaleb(Decimal(1), 4) Decimal('1E+4') >>> ExtendedContext.scaleb(1, Decimal(4)) Decimal('1E+4')
Returns the first operand after adding the second value its exp.
[ "Returns", "the", "first", "operand", "after", "adding", "the", "second", "value", "its", "exp", "." ]
def scaleb (self, a, b): """Returns the first operand after adding the second value its exp. >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2')) Decimal('0.0750') >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0')) Decimal('7.50') >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3')) Decimal('7.50E+3') >>> ExtendedContext.scaleb(1, 4) Decimal('1E+4') >>> ExtendedContext.scaleb(Decimal(1), 4) Decimal('1E+4') >>> ExtendedContext.scaleb(1, Decimal(4)) Decimal('1E+4') """ a = _convert_other(a, raiseit=True) return a.scaleb(b, context=self)
[ "def", "scaleb", "(", "self", ",", "a", ",", "b", ")", ":", "a", "=", "_convert_other", "(", "a", ",", "raiseit", "=", "True", ")", "return", "a", ".", "scaleb", "(", "b", ",", "context", "=", "self", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/decimal.py#L5236-L5253
LunarG/VulkanTools
03314db74bcff6aa07f6d75b94ebc6d94eebfb43
scripts/common_codegen.py
python
GetFeatureProtect
(interface)
return protect
Get platform protection string
Get platform protection string
[ "Get", "platform", "protection", "string" ]
def GetFeatureProtect(interface): """Get platform protection string""" platform = interface.get('platform') protect = None if platform is not None: protect = platform_dict[platform] return protect
[ "def", "GetFeatureProtect", "(", "interface", ")", ":", "platform", "=", "interface", ".", "get", "(", "'platform'", ")", "protect", "=", "None", "if", "platform", "is", "not", "None", ":", "protect", "=", "platform_dict", "[", "platform", "]", "return", "protect" ]
https://github.com/LunarG/VulkanTools/blob/03314db74bcff6aa07f6d75b94ebc6d94eebfb43/scripts/common_codegen.py#L70-L76
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
tools/idl_parser/idl_parser.py
python
IDLParser.p_ExceptionMembers
(self, p)
ExceptionMembers : ExtendedAttributeList ExceptionMember ExceptionMembers |
ExceptionMembers : ExtendedAttributeList ExceptionMember ExceptionMembers |
[ "ExceptionMembers", ":", "ExtendedAttributeList", "ExceptionMember", "ExceptionMembers", "|" ]
def p_ExceptionMembers(self, p): """ExceptionMembers : ExtendedAttributeList ExceptionMember ExceptionMembers |""" if len(p) > 1: p[2].AddChildren(p[1]) p[0] = ListFromConcat(p[2], p[3])
[ "def", "p_ExceptionMembers", "(", "self", ",", "p", ")", ":", "if", "len", "(", "p", ")", ">", "1", ":", "p", "[", "2", "]", ".", "AddChildren", "(", "p", "[", "1", "]", ")", "p", "[", "0", "]", "=", "ListFromConcat", "(", "p", "[", "2", "]", ",", "p", "[", "3", "]", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/idl_parser/idl_parser.py#L366-L371
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/ebmlib/efilehist.py
python
EFileHistory.RemoveFileFromHistory
(self, index)
Remove a file from the history
Remove a file from the history
[ "Remove", "a", "file", "from", "the", "history" ]
def RemoveFileFromHistory(self, index): """Remove a file from the history""" assert self.MaxFiles > index, "Index out of range" self.History.pop(index) self._UpdateMenu()
[ "def", "RemoveFileFromHistory", "(", "self", ",", "index", ")", ":", "assert", "self", ".", "MaxFiles", ">", "index", ",", "\"Index out of range\"", "self", ".", "History", ".", "pop", "(", "index", ")", "self", ".", "_UpdateMenu", "(", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/ebmlib/efilehist.py#L109-L113
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/xml/sax/xmlreader.py
python
XMLReader.setProperty
(self, name, value)
Sets the value of a SAX2 property.
Sets the value of a SAX2 property.
[ "Sets", "the", "value", "of", "a", "SAX2", "property", "." ]
def setProperty(self, name, value): "Sets the value of a SAX2 property." raise SAXNotRecognizedException("Property '%s' not recognized" % name)
[ "def", "setProperty", "(", "self", ",", "name", ",", "value", ")", ":", "raise", "SAXNotRecognizedException", "(", "\"Property '%s' not recognized\"", "%", "name", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/xml/sax/xmlreader.py#L87-L89
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/calendar.py
python
CalendarDateAttr.SetMark
(*args, **kwargs)
return _calendar.CalendarDateAttr_SetMark(*args, **kwargs)
SetMark(CalendarDateAttr m)
SetMark(CalendarDateAttr m)
[ "SetMark", "(", "CalendarDateAttr", "m", ")" ]
def SetMark(*args, **kwargs): """SetMark(CalendarDateAttr m)""" return _calendar.CalendarDateAttr_SetMark(*args, **kwargs)
[ "def", "SetMark", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_calendar", ".", "CalendarDateAttr_SetMark", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/calendar.py#L171-L173
oracle/graaljs
36a56e8e993d45fc40939a3a4d9c0c24990720f1
graal-nodejs/tools/gyp/pylib/gyp/msvs_emulation.py
python
MsvsSettings._GetDefFileAsLdflags
(self, ldflags, gyp_to_build_path)
.def files get implicitly converted to a ModuleDefinitionFile for the linker in the VS generator. Emulate that behaviour here.
.def files get implicitly converted to a ModuleDefinitionFile for the linker in the VS generator. Emulate that behaviour here.
[ ".", "def", "files", "get", "implicitly", "converted", "to", "a", "ModuleDefinitionFile", "for", "the", "linker", "in", "the", "VS", "generator", ".", "Emulate", "that", "behaviour", "here", "." ]
def _GetDefFileAsLdflags(self, ldflags, gyp_to_build_path): """.def files get implicitly converted to a ModuleDefinitionFile for the linker in the VS generator. Emulate that behaviour here.""" def_file = self.GetDefFile(gyp_to_build_path) if def_file: ldflags.append('/DEF:"%s"' % def_file)
[ "def", "_GetDefFileAsLdflags", "(", "self", ",", "ldflags", ",", "gyp_to_build_path", ")", ":", "def_file", "=", "self", ".", "GetDefFile", "(", "gyp_to_build_path", ")", "if", "def_file", ":", "ldflags", ".", "append", "(", "'/DEF:\"%s\"'", "%", "def_file", ")" ]
https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/tools/gyp/pylib/gyp/msvs_emulation.py#L628-L633
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_controls.py
python
TextAttr.SetAlignment
(*args, **kwargs)
return _controls_.TextAttr_SetAlignment(*args, **kwargs)
SetAlignment(self, int alignment)
SetAlignment(self, int alignment)
[ "SetAlignment", "(", "self", "int", "alignment", ")" ]
def SetAlignment(*args, **kwargs): """SetAlignment(self, int alignment)""" return _controls_.TextAttr_SetAlignment(*args, **kwargs)
[ "def", "SetAlignment", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "TextAttr_SetAlignment", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_controls.py#L1519-L1521
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/email/_parseaddr.py
python
AddrlistClass.getdomainliteral
(self)
return '[%s]' % self.getdelimited('[', ']\r', False)
Parse an RFC 2822 domain-literal.
Parse an RFC 2822 domain-literal.
[ "Parse", "an", "RFC", "2822", "domain", "-", "literal", "." ]
def getdomainliteral(self): """Parse an RFC 2822 domain-literal.""" return '[%s]' % self.getdelimited('[', ']\r', False)
[ "def", "getdomainliteral", "(", "self", ")", ":", "return", "'[%s]'", "%", "self", ".", "getdelimited", "(", "'['", ",", "']\\r'", ",", "False", ")" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/email/_parseaddr.py#L405-L407
google/earthenterprise
0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9
earth_enterprise/src/server/wsgi/search/plugin/example_search_app.py
python
GeExampleSearchApp.__init__
(self)
Inits the status and response_headers for the HTTP response.
Inits the status and response_headers for the HTTP response.
[ "Inits", "the", "status", "and", "response_headers", "for", "the", "HTTP", "response", "." ]
def __init__(self): """Inits the status and response_headers for the HTTP response.""" self._status = "%s" self._example = example_search_handler.ExampleSearch()
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "_status", "=", "\"%s\"", "self", ".", "_example", "=", "example_search_handler", ".", "ExampleSearch", "(", ")" ]
https://github.com/google/earthenterprise/blob/0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9/earth_enterprise/src/server/wsgi/search/plugin/example_search_app.py#L30-L34
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/wsgiref/util.py
python
guess_scheme
(environ)
Return a guess for whether 'wsgi.url_scheme' should be 'http' or 'https'
Return a guess for whether 'wsgi.url_scheme' should be 'http' or 'https'
[ "Return", "a", "guess", "for", "whether", "wsgi", ".", "url_scheme", "should", "be", "http", "or", "https" ]
def guess_scheme(environ): """Return a guess for whether 'wsgi.url_scheme' should be 'http' or 'https' """ if environ.get("HTTPS") in ('yes','on','1'): return 'https' else: return 'http'
[ "def", "guess_scheme", "(", "environ", ")", ":", "if", "environ", ".", "get", "(", "\"HTTPS\"", ")", "in", "(", "'yes'", ",", "'on'", ",", "'1'", ")", ":", "return", "'https'", "else", ":", "return", "'http'" ]
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/wsgiref/util.py#L42-L48
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/ros_comm/roslaunch/src/roslaunch/remote.py
python
ROSRemoteRunner.add_process_listener
(self, l)
Listen to events about remote processes dying. Not threadsafe. Must be called before processes started. :param l: ProcessListener
Listen to events about remote processes dying. Not threadsafe. Must be called before processes started.
[ "Listen", "to", "events", "about", "remote", "processes", "dying", ".", "Not", "threadsafe", ".", "Must", "be", "called", "before", "processes", "started", "." ]
def add_process_listener(self, l): """ Listen to events about remote processes dying. Not threadsafe. Must be called before processes started. :param l: ProcessListener """ self.listeners.append(l)
[ "def", "add_process_listener", "(", "self", ",", "l", ")", ":", "self", ".", "listeners", ".", "append", "(", "l", ")" ]
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/ros_comm/roslaunch/src/roslaunch/remote.py#L76-L83
locusrobotics/robot_navigation
d0ebe153518a827622baf05f8a20508dc05dfe44
robot_nav_tools/rqt_dwb_plugin/src/rqt_dwb_plugin/trajectory_widget.py
python
expand_bounds
(bounds, extra=0.10)
Expand the negative bounds of the x axis by 10 percent so the area behind the robot is visible.
Expand the negative bounds of the x axis by 10 percent so the area behind the robot is visible.
[ "Expand", "the", "negative", "bounds", "of", "the", "x", "axis", "by", "10", "percent", "so", "the", "area", "behind", "the", "robot", "is", "visible", "." ]
def expand_bounds(bounds, extra=0.10): """Expand the negative bounds of the x axis by 10 percent so the area behind the robot is visible.""" bounds.x_min -= (bounds.x_max - bounds.x_min) * extra
[ "def", "expand_bounds", "(", "bounds", ",", "extra", "=", "0.10", ")", ":", "bounds", ".", "x_min", "-=", "(", "bounds", ".", "x_max", "-", "bounds", ".", "x_min", ")", "*", "extra" ]
https://github.com/locusrobotics/robot_navigation/blob/d0ebe153518a827622baf05f8a20508dc05dfe44/robot_nav_tools/rqt_dwb_plugin/src/rqt_dwb_plugin/trajectory_widget.py#L43-L45
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_gdi.py
python
Locale.Init1
(*args, **kwargs)
return _gdi_.Locale_Init1(*args, **kwargs)
Init1(self, String name, String shortName=EmptyString, String locale=EmptyString, bool bLoadDefault=True) -> bool
Init1(self, String name, String shortName=EmptyString, String locale=EmptyString, bool bLoadDefault=True) -> bool
[ "Init1", "(", "self", "String", "name", "String", "shortName", "=", "EmptyString", "String", "locale", "=", "EmptyString", "bool", "bLoadDefault", "=", "True", ")", "-", ">", "bool" ]
def Init1(*args, **kwargs): """ Init1(self, String name, String shortName=EmptyString, String locale=EmptyString, bool bLoadDefault=True) -> bool """ return _gdi_.Locale_Init1(*args, **kwargs)
[ "def", "Init1", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gdi_", ".", "Locale_Init1", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_gdi.py#L2982-L2987
trilinos/Trilinos
6168be6dd51e35e1cd681e9c4b24433e709df140
packages/seacas/libraries/ioss/src/visualization/catalyst/phactori/PhactoriDriver.py
python
GetViewMapCFromUserData
(datadescription)
return returnViewMapC
given a datadescription, get the json string view map from the user data\n and convert it into a python dict using the json library, and return\n that item. Also determine the separator character and input deck\n filename
given a datadescription, get the json string view map from the user data\n and convert it into a python dict using the json library, and return\n that item. Also determine the separator character and input deck\n filename
[ "given", "a", "datadescription", "get", "the", "json", "string", "view", "map", "from", "the", "user", "data", "\\", "n", "and", "convert", "it", "into", "a", "python", "dict", "using", "the", "json", "library", "and", "return", "\\", "n", "that", "item", ".", "Also", "determine", "the", "separator", "character", "and", "input", "deck", "\\", "n", "filename" ]
def GetViewMapCFromUserData(datadescription): "given a datadescription, get the json string view map from the user data\n and convert it into a python dict using the json library, and return\n that item. Also determine the separator character and input deck\n filename" #the following code forces a UserData item for internal testing #myDebugPrint3("GetViewMapCFromUserData entered\n") #newFd = vtk.vtkFieldData() #newStringArray = vtk.vtkStringArray() #xxViewMapCStr = '{ "camera blocks": { }, "representation blocks": { }, \ # "operation blocks": { }, "imageset blocks": {}, \ # "scatter plot blocks": { }, "plot over time blocks": { } }' #newStringArray.InsertNextValue(xxViewMapCStr) #x2str = '_' #x3str = 'cool_input_deck' #newStringArray.InsertNextValue(x2str) #newStringArray.InsertNextValue(x3str) #newFd.AddArray(newStringArray) #datadescription.SetUserData(newFd) global gBypassUserData sa = GetUserDataStringArrayAccountingForBypass(datadescription) testJsonString = sa[0] separatorCharacterString = sa[1] inputDeckFilename = sa[2] if PhactoriDbg(): myDebugPrint3("gGetJsonViewMapCFromUserData string:\n" + \ str(testJsonString) + "\n") if PhactoriDbg(): myDebugPrint3("separator string: " + separatorCharacterString + \ "\ninputDeckFilename: " + inputDeckFilename + "\n") #if PhactoriDbg(): #myDebugPrint3("num strings2: " + str(sa.GetNumberOfValues())) if PhactoriDbg(): myDebugPrint3("json.loads begin ---------------\n"); myDebugPrint3(testJsonString); myDebugPrint3("\njson.loads end ---------------\n"); if gBypassUserData == True: global gBypassUserDataJson returnViewMapC = gBypassUserDataJson #returnViewMapC = bccolli_controls.catalystSierraInputInJsonFormat else: returnViewMapC = json.loads(testJsonString) returnViewMapC = convertJsonUnicodeToStrings(returnViewMapC) SetDefaultImageBasename(inputDeckFilename) if PhactoriDbg(): myDebugPrint3("GetViewMapCFromUserData returning\n") return returnViewMapC
[ "def", "GetViewMapCFromUserData", "(", "datadescription", ")", ":", "#the following code forces a UserData item for internal testing", "#myDebugPrint3(\"GetViewMapCFromUserData entered\\n\")", "#newFd = vtk.vtkFieldData()", "#newStringArray = vtk.vtkStringArray()", "#xxViewMapCStr = '{ \"camera blocks\": { }, \"representation blocks\": { }, \\", "# \"operation blocks\": { }, \"imageset blocks\": {}, \\", "# \"scatter plot blocks\": { }, \"plot over time blocks\": { } }'", "#newStringArray.InsertNextValue(xxViewMapCStr)", "#x2str = '_'", "#x3str = 'cool_input_deck'", "#newStringArray.InsertNextValue(x2str)", "#newStringArray.InsertNextValue(x3str)", "#newFd.AddArray(newStringArray)", "#datadescription.SetUserData(newFd)", "global", "gBypassUserData", "sa", "=", "GetUserDataStringArrayAccountingForBypass", "(", "datadescription", ")", "testJsonString", "=", "sa", "[", "0", "]", "separatorCharacterString", "=", "sa", "[", "1", "]", "inputDeckFilename", "=", "sa", "[", "2", "]", "if", "PhactoriDbg", "(", ")", ":", "myDebugPrint3", "(", "\"gGetJsonViewMapCFromUserData string:\\n\"", "+", "str", "(", "testJsonString", ")", "+", "\"\\n\"", ")", "if", "PhactoriDbg", "(", ")", ":", "myDebugPrint3", "(", "\"separator string: \"", "+", "separatorCharacterString", "+", "\"\\ninputDeckFilename: \"", "+", "inputDeckFilename", "+", "\"\\n\"", ")", "#if PhactoriDbg():", "#myDebugPrint3(\"num strings2: \" + str(sa.GetNumberOfValues()))", "if", "PhactoriDbg", "(", ")", ":", "myDebugPrint3", "(", "\"json.loads begin ---------------\\n\"", ")", "myDebugPrint3", "(", "testJsonString", ")", "myDebugPrint3", "(", "\"\\njson.loads end ---------------\\n\"", ")", "if", "gBypassUserData", "==", "True", ":", "global", "gBypassUserDataJson", "returnViewMapC", "=", "gBypassUserDataJson", "#returnViewMapC = bccolli_controls.catalystSierraInputInJsonFormat", "else", ":", "returnViewMapC", "=", "json", ".", "loads", "(", "testJsonString", ")", "returnViewMapC", "=", "convertJsonUnicodeToStrings", "(", "returnViewMapC", ")", "SetDefaultImageBasename", "(", "inputDeckFilename", ")", "if", "PhactoriDbg", "(", ")", ":", "myDebugPrint3", "(", "\"GetViewMapCFromUserData returning\\n\"", ")", "return", "returnViewMapC" ]
https://github.com/trilinos/Trilinos/blob/6168be6dd51e35e1cd681e9c4b24433e709df140/packages/seacas/libraries/ioss/src/visualization/catalyst/phactori/PhactoriDriver.py#L24886-L24939
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/lib/recfunctions.py
python
repack_fields
(a, align=False, recurse=False)
return np.dtype((a.type, dt))
Re-pack the fields of a structured array or dtype in memory. The memory layout of structured datatypes allows fields at arbitrary byte offsets. This means the fields can be separated by padding bytes, their offsets can be non-monotonically increasing, and they can overlap. This method removes any overlaps and reorders the fields in memory so they have increasing byte offsets, and adds or removes padding bytes depending on the `align` option, which behaves like the `align` option to `np.dtype`. If `align=False`, this method produces a "packed" memory layout in which each field starts at the byte the previous field ended, and any padding bytes are removed. If `align=True`, this methods produces an "aligned" memory layout in which each field's offset is a multiple of its alignment, and the total itemsize is a multiple of the largest alignment, by adding padding bytes as needed. Parameters ---------- a : ndarray or dtype array or dtype for which to repack the fields. align : boolean If true, use an "aligned" memory layout, otherwise use a "packed" layout. recurse : boolean If True, also repack nested structures. Returns ------- repacked : ndarray or dtype Copy of `a` with fields repacked, or `a` itself if no repacking was needed. Examples -------- >>> from numpy.lib import recfunctions as rfn >>> def print_offsets(d): ... print("offsets:", [d.fields[name][1] for name in d.names]) ... print("itemsize:", d.itemsize) ... >>> dt = np.dtype('u1, <i8, <f8', align=True) >>> dt dtype({'names':['f0','f1','f2'], 'formats':['u1','<i8','<f8'], 'offsets':[0,8,16], 'itemsize':24}, align=True) >>> print_offsets(dt) offsets: [0, 8, 16] itemsize: 24 >>> packed_dt = rfn.repack_fields(dt) >>> packed_dt dtype([('f0', 'u1'), ('f1', '<i8'), ('f2', '<f8')]) >>> print_offsets(packed_dt) offsets: [0, 1, 9] itemsize: 17
Re-pack the fields of a structured array or dtype in memory.
[ "Re", "-", "pack", "the", "fields", "of", "a", "structured", "array", "or", "dtype", "in", "memory", "." ]
def repack_fields(a, align=False, recurse=False): """ Re-pack the fields of a structured array or dtype in memory. The memory layout of structured datatypes allows fields at arbitrary byte offsets. This means the fields can be separated by padding bytes, their offsets can be non-monotonically increasing, and they can overlap. This method removes any overlaps and reorders the fields in memory so they have increasing byte offsets, and adds or removes padding bytes depending on the `align` option, which behaves like the `align` option to `np.dtype`. If `align=False`, this method produces a "packed" memory layout in which each field starts at the byte the previous field ended, and any padding bytes are removed. If `align=True`, this methods produces an "aligned" memory layout in which each field's offset is a multiple of its alignment, and the total itemsize is a multiple of the largest alignment, by adding padding bytes as needed. Parameters ---------- a : ndarray or dtype array or dtype for which to repack the fields. align : boolean If true, use an "aligned" memory layout, otherwise use a "packed" layout. recurse : boolean If True, also repack nested structures. Returns ------- repacked : ndarray or dtype Copy of `a` with fields repacked, or `a` itself if no repacking was needed. Examples -------- >>> from numpy.lib import recfunctions as rfn >>> def print_offsets(d): ... print("offsets:", [d.fields[name][1] for name in d.names]) ... print("itemsize:", d.itemsize) ... >>> dt = np.dtype('u1, <i8, <f8', align=True) >>> dt dtype({'names':['f0','f1','f2'], 'formats':['u1','<i8','<f8'], 'offsets':[0,8,16], 'itemsize':24}, align=True) >>> print_offsets(dt) offsets: [0, 8, 16] itemsize: 24 >>> packed_dt = rfn.repack_fields(dt) >>> packed_dt dtype([('f0', 'u1'), ('f1', '<i8'), ('f2', '<f8')]) >>> print_offsets(packed_dt) offsets: [0, 1, 9] itemsize: 17 """ if not isinstance(a, np.dtype): dt = repack_fields(a.dtype, align=align, recurse=recurse) return a.astype(dt, copy=False) if a.names is None: return a fieldinfo = [] for name in a.names: tup = a.fields[name] if recurse: fmt = repack_fields(tup[0], align=align, recurse=True) else: fmt = tup[0] if len(tup) == 3: name = (tup[2], name) fieldinfo.append((name, fmt)) dt = np.dtype(fieldinfo, align=align) return np.dtype((a.type, dt))
[ "def", "repack_fields", "(", "a", ",", "align", "=", "False", ",", "recurse", "=", "False", ")", ":", "if", "not", "isinstance", "(", "a", ",", "np", ".", "dtype", ")", ":", "dt", "=", "repack_fields", "(", "a", ".", "dtype", ",", "align", "=", "align", ",", "recurse", "=", "recurse", ")", "return", "a", ".", "astype", "(", "dt", ",", "copy", "=", "False", ")", "if", "a", ".", "names", "is", "None", ":", "return", "a", "fieldinfo", "=", "[", "]", "for", "name", "in", "a", ".", "names", ":", "tup", "=", "a", ".", "fields", "[", "name", "]", "if", "recurse", ":", "fmt", "=", "repack_fields", "(", "tup", "[", "0", "]", ",", "align", "=", "align", ",", "recurse", "=", "True", ")", "else", ":", "fmt", "=", "tup", "[", "0", "]", "if", "len", "(", "tup", ")", "==", "3", ":", "name", "=", "(", "tup", "[", "2", "]", ",", "name", ")", "fieldinfo", ".", "append", "(", "(", "name", ",", "fmt", ")", ")", "dt", "=", "np", ".", "dtype", "(", "fieldinfo", ",", "align", "=", "align", ")", "return", "np", ".", "dtype", "(", "(", "a", ".", "type", ",", "dt", ")", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/lib/recfunctions.py#L793-L871
GoSSIP-SJTU/Armariris
ad5d868482956b2194a77b39c8d543c7c2318200
tools/clang/tools/scan-build-py/libscanbuild/runner.py
python
set_file_path_relative
(opts, continuation=filter_debug_flags)
return continuation(opts)
Set source file path to relative to the working directory. The only purpose of this function is to pass the SATestBuild.py tests.
Set source file path to relative to the working directory.
[ "Set", "source", "file", "path", "to", "relative", "to", "the", "working", "directory", "." ]
def set_file_path_relative(opts, continuation=filter_debug_flags): """ Set source file path to relative to the working directory. The only purpose of this function is to pass the SATestBuild.py tests. """ opts.update({'file': os.path.relpath(opts['file'], opts['directory'])}) return continuation(opts)
[ "def", "set_file_path_relative", "(", "opts", ",", "continuation", "=", "filter_debug_flags", ")", ":", "opts", ".", "update", "(", "{", "'file'", ":", "os", ".", "path", ".", "relpath", "(", "opts", "[", "'file'", "]", ",", "opts", "[", "'directory'", "]", ")", "}", ")", "return", "continuation", "(", "opts", ")" ]
https://github.com/GoSSIP-SJTU/Armariris/blob/ad5d868482956b2194a77b39c8d543c7c2318200/tools/clang/tools/scan-build-py/libscanbuild/runner.py#L209-L216
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/setuptools/py3/setuptools/extension.py
python
Extension._convert_pyx_sources_to_lang
(self)
Replace sources with .pyx extensions to sources with the target language extension. This mechanism allows language authors to supply pre-converted sources but to prefer the .pyx sources.
Replace sources with .pyx extensions to sources with the target language extension. This mechanism allows language authors to supply pre-converted sources but to prefer the .pyx sources.
[ "Replace", "sources", "with", ".", "pyx", "extensions", "to", "sources", "with", "the", "target", "language", "extension", ".", "This", "mechanism", "allows", "language", "authors", "to", "supply", "pre", "-", "converted", "sources", "but", "to", "prefer", "the", ".", "pyx", "sources", "." ]
def _convert_pyx_sources_to_lang(self): """ Replace sources with .pyx extensions to sources with the target language extension. This mechanism allows language authors to supply pre-converted sources but to prefer the .pyx sources. """ if _have_cython(): # the build has Cython, so allow it to compile the .pyx files return lang = self.language or '' target_ext = '.cpp' if lang.lower() == 'c++' else '.c' sub = functools.partial(re.sub, '.pyx$', target_ext) self.sources = list(map(sub, self.sources))
[ "def", "_convert_pyx_sources_to_lang", "(", "self", ")", ":", "if", "_have_cython", "(", ")", ":", "# the build has Cython, so allow it to compile the .pyx files", "return", "lang", "=", "self", ".", "language", "or", "''", "target_ext", "=", "'.cpp'", "if", "lang", ".", "lower", "(", ")", "==", "'c++'", "else", "'.c'", "sub", "=", "functools", ".", "partial", "(", "re", ".", "sub", ",", "'.pyx$'", ",", "target_ext", ")", "self", ".", "sources", "=", "list", "(", "map", "(", "sub", ",", "self", ".", "sources", ")", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py3/setuptools/extension.py#L39-L51
klzgrad/naiveproxy
ed2c513637c77b18721fe428d7ed395b4d284c83
src/tools/grit/grit/tool/interface.py
python
Tool.VerboseOut
(self, text)
Writes out 'text' if the verbose option is on.
Writes out 'text' if the verbose option is on.
[ "Writes", "out", "text", "if", "the", "verbose", "option", "is", "on", "." ]
def VerboseOut(self, text): '''Writes out 'text' if the verbose option is on.''' if self.o.verbose: self.o.output_stream.write(text)
[ "def", "VerboseOut", "(", "self", ",", "text", ")", ":", "if", "self", ".", "o", ".", "verbose", ":", "self", ".", "o", ".", "output_stream", ".", "write", "(", "text", ")" ]
https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/tools/grit/grit/tool/interface.py#L53-L56
apiaryio/snowcrash
b5b39faa85f88ee17459edf39fdc6fe4fc70d2e3
tools/gyp/pylib/gyp/xcodeproj_file.py
python
PBXProject.AddOrGetProjectReference
(self, other_pbxproject)
return [product_group, project_ref]
Add a reference to another project file (via PBXProject object) to this one. Returns [ProductGroup, ProjectRef]. ProductGroup is a PBXGroup object in this project file that contains a PBXReferenceProxy object for each product of each PBXNativeTarget in the other project file. ProjectRef is a PBXFileReference to the other project file. If this project file already references the other project file, the existing ProductGroup and ProjectRef are returned. The ProductGroup will still be updated if necessary.
Add a reference to another project file (via PBXProject object) to this one.
[ "Add", "a", "reference", "to", "another", "project", "file", "(", "via", "PBXProject", "object", ")", "to", "this", "one", "." ]
def AddOrGetProjectReference(self, other_pbxproject): """Add a reference to another project file (via PBXProject object) to this one. Returns [ProductGroup, ProjectRef]. ProductGroup is a PBXGroup object in this project file that contains a PBXReferenceProxy object for each product of each PBXNativeTarget in the other project file. ProjectRef is a PBXFileReference to the other project file. If this project file already references the other project file, the existing ProductGroup and ProjectRef are returned. The ProductGroup will still be updated if necessary. """ if not 'projectReferences' in self._properties: self._properties['projectReferences'] = [] product_group = None project_ref = None if not other_pbxproject in self._other_pbxprojects: # This project file isn't yet linked to the other one. Establish the # link. product_group = PBXGroup({'name': 'Products'}) # ProductGroup is strong. product_group.parent = self # There's nothing unique about this PBXGroup, and if left alone, it will # wind up with the same set of hashables as all other PBXGroup objects # owned by the projectReferences list. Add the hashables of the # remote PBXProject that it's related to. product_group._hashables.extend(other_pbxproject.Hashables()) # The other project reports its path as relative to the same directory # that this project's path is relative to. The other project's path # is not necessarily already relative to this project. Figure out the # pathname that this project needs to use to refer to the other one. this_path = posixpath.dirname(self.Path()) projectDirPath = self.GetProperty('projectDirPath') if projectDirPath: if posixpath.isabs(projectDirPath[0]): this_path = projectDirPath else: this_path = posixpath.join(this_path, projectDirPath) other_path = gyp.common.RelativePath(other_pbxproject.Path(), this_path) # ProjectRef is weak (it's owned by the mainGroup hierarchy). project_ref = PBXFileReference({ 'lastKnownFileType': 'wrapper.pb-project', 'path': other_path, 'sourceTree': 'SOURCE_ROOT', }) self.ProjectsGroup().AppendChild(project_ref) ref_dict = {'ProductGroup': product_group, 'ProjectRef': project_ref} self._other_pbxprojects[other_pbxproject] = ref_dict self.AppendProperty('projectReferences', ref_dict) # Xcode seems to sort this list case-insensitively self._properties['projectReferences'] = \ sorted(self._properties['projectReferences'], cmp=lambda x,y: cmp(x['ProjectRef'].Name().lower(), y['ProjectRef'].Name().lower())) else: # The link already exists. Pull out the relevnt data. project_ref_dict = self._other_pbxprojects[other_pbxproject] product_group = project_ref_dict['ProductGroup'] project_ref = project_ref_dict['ProjectRef'] self._SetUpProductReferences(other_pbxproject, product_group, project_ref) inherit_unique_symroot = self._AllSymrootsUnique(other_pbxproject, False) targets = other_pbxproject.GetProperty('targets') if all(self._AllSymrootsUnique(t, inherit_unique_symroot) for t in targets): dir_path = project_ref._properties['path'] product_group._hashables.extend(dir_path) return [product_group, project_ref]
[ "def", "AddOrGetProjectReference", "(", "self", ",", "other_pbxproject", ")", ":", "if", "not", "'projectReferences'", "in", "self", ".", "_properties", ":", "self", ".", "_properties", "[", "'projectReferences'", "]", "=", "[", "]", "product_group", "=", "None", "project_ref", "=", "None", "if", "not", "other_pbxproject", "in", "self", ".", "_other_pbxprojects", ":", "# This project file isn't yet linked to the other one. Establish the", "# link.", "product_group", "=", "PBXGroup", "(", "{", "'name'", ":", "'Products'", "}", ")", "# ProductGroup is strong.", "product_group", ".", "parent", "=", "self", "# There's nothing unique about this PBXGroup, and if left alone, it will", "# wind up with the same set of hashables as all other PBXGroup objects", "# owned by the projectReferences list. Add the hashables of the", "# remote PBXProject that it's related to.", "product_group", ".", "_hashables", ".", "extend", "(", "other_pbxproject", ".", "Hashables", "(", ")", ")", "# The other project reports its path as relative to the same directory", "# that this project's path is relative to. The other project's path", "# is not necessarily already relative to this project. Figure out the", "# pathname that this project needs to use to refer to the other one.", "this_path", "=", "posixpath", ".", "dirname", "(", "self", ".", "Path", "(", ")", ")", "projectDirPath", "=", "self", ".", "GetProperty", "(", "'projectDirPath'", ")", "if", "projectDirPath", ":", "if", "posixpath", ".", "isabs", "(", "projectDirPath", "[", "0", "]", ")", ":", "this_path", "=", "projectDirPath", "else", ":", "this_path", "=", "posixpath", ".", "join", "(", "this_path", ",", "projectDirPath", ")", "other_path", "=", "gyp", ".", "common", ".", "RelativePath", "(", "other_pbxproject", ".", "Path", "(", ")", ",", "this_path", ")", "# ProjectRef is weak (it's owned by the mainGroup hierarchy).", "project_ref", "=", "PBXFileReference", "(", "{", "'lastKnownFileType'", ":", "'wrapper.pb-project'", ",", "'path'", ":", "other_path", ",", "'sourceTree'", ":", "'SOURCE_ROOT'", ",", "}", ")", "self", ".", "ProjectsGroup", "(", ")", ".", "AppendChild", "(", "project_ref", ")", "ref_dict", "=", "{", "'ProductGroup'", ":", "product_group", ",", "'ProjectRef'", ":", "project_ref", "}", "self", ".", "_other_pbxprojects", "[", "other_pbxproject", "]", "=", "ref_dict", "self", ".", "AppendProperty", "(", "'projectReferences'", ",", "ref_dict", ")", "# Xcode seems to sort this list case-insensitively", "self", ".", "_properties", "[", "'projectReferences'", "]", "=", "sorted", "(", "self", ".", "_properties", "[", "'projectReferences'", "]", ",", "cmp", "=", "lambda", "x", ",", "y", ":", "cmp", "(", "x", "[", "'ProjectRef'", "]", ".", "Name", "(", ")", ".", "lower", "(", ")", ",", "y", "[", "'ProjectRef'", "]", ".", "Name", "(", ")", ".", "lower", "(", ")", ")", ")", "else", ":", "# The link already exists. Pull out the relevnt data.", "project_ref_dict", "=", "self", ".", "_other_pbxprojects", "[", "other_pbxproject", "]", "product_group", "=", "project_ref_dict", "[", "'ProductGroup'", "]", "project_ref", "=", "project_ref_dict", "[", "'ProjectRef'", "]", "self", ".", "_SetUpProductReferences", "(", "other_pbxproject", ",", "product_group", ",", "project_ref", ")", "inherit_unique_symroot", "=", "self", ".", "_AllSymrootsUnique", "(", "other_pbxproject", ",", "False", ")", "targets", "=", "other_pbxproject", ".", "GetProperty", "(", "'targets'", ")", "if", "all", "(", "self", ".", "_AllSymrootsUnique", "(", "t", ",", "inherit_unique_symroot", ")", "for", "t", "in", "targets", ")", ":", "dir_path", "=", "project_ref", ".", "_properties", "[", "'path'", "]", "product_group", ".", "_hashables", ".", "extend", "(", "dir_path", ")", "return", "[", "product_group", ",", "project_ref", "]" ]
https://github.com/apiaryio/snowcrash/blob/b5b39faa85f88ee17459edf39fdc6fe4fc70d2e3/tools/gyp/pylib/gyp/xcodeproj_file.py#L2674-L2752
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/ops/nn_grad.py
python
_BiasAddGradGrad
(op, received_grad)
return array_ops.tile(expanded_grad, tile_mults)
Gradient for the BiasAddGrad op. Args: op: BiasAddGrad op for which we are calculating gradients. received_grad: The gradients passed to the BiasAddGrad op. Returns: A single gradient Tensor for the input to BiasAddGrad (which is the gradient of the bias term in BiasAdd)
Gradient for the BiasAddGrad op.
[ "Gradient", "for", "the", "BiasAddGrad", "op", "." ]
def _BiasAddGradGrad(op, received_grad): """Gradient for the BiasAddGrad op. Args: op: BiasAddGrad op for which we are calculating gradients. received_grad: The gradients passed to the BiasAddGrad op. Returns: A single gradient Tensor for the input to BiasAddGrad (which is the gradient of the bias term in BiasAdd) """ try: data_format = op.get_attr("data_format") except ValueError: data_format = None shape = array_ops.shape(op.inputs[0]) bias_shape = array_ops.shape(received_grad) if data_format == b"NCHW": expanded_shape = array_ops.concat([ array_ops.ones_like(shape[:1]), bias_shape, array_ops.ones_like(shape[2:]) ], 0) tile_mults = array_ops.concat([shape[:1], [1], shape[2:]], 0) else: expanded_shape = array_ops.concat( [array_ops.ones_like(shape[:-1]), bias_shape], 0) tile_mults = array_ops.concat([shape[:-1], [1]], 0) expanded_grad = array_ops.reshape(received_grad, expanded_shape) return array_ops.tile(expanded_grad, tile_mults)
[ "def", "_BiasAddGradGrad", "(", "op", ",", "received_grad", ")", ":", "try", ":", "data_format", "=", "op", ".", "get_attr", "(", "\"data_format\"", ")", "except", "ValueError", ":", "data_format", "=", "None", "shape", "=", "array_ops", ".", "shape", "(", "op", ".", "inputs", "[", "0", "]", ")", "bias_shape", "=", "array_ops", ".", "shape", "(", "received_grad", ")", "if", "data_format", "==", "b\"NCHW\"", ":", "expanded_shape", "=", "array_ops", ".", "concat", "(", "[", "array_ops", ".", "ones_like", "(", "shape", "[", ":", "1", "]", ")", ",", "bias_shape", ",", "array_ops", ".", "ones_like", "(", "shape", "[", "2", ":", "]", ")", "]", ",", "0", ")", "tile_mults", "=", "array_ops", ".", "concat", "(", "[", "shape", "[", ":", "1", "]", ",", "[", "1", "]", ",", "shape", "[", "2", ":", "]", "]", ",", "0", ")", "else", ":", "expanded_shape", "=", "array_ops", ".", "concat", "(", "[", "array_ops", ".", "ones_like", "(", "shape", "[", ":", "-", "1", "]", ")", ",", "bias_shape", "]", ",", "0", ")", "tile_mults", "=", "array_ops", ".", "concat", "(", "[", "shape", "[", ":", "-", "1", "]", ",", "[", "1", "]", "]", ",", "0", ")", "expanded_grad", "=", "array_ops", ".", "reshape", "(", "received_grad", ",", "expanded_shape", ")", "return", "array_ops", ".", "tile", "(", "expanded_grad", ",", "tile_mults", ")" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/nn_grad.py#L348-L380
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py2/pandas/io/sql.py
python
read_sql_query
(sql, con, index_col=None, coerce_float=True, params=None, parse_dates=None, chunksize=None)
return pandas_sql.read_query( sql, index_col=index_col, params=params, coerce_float=coerce_float, parse_dates=parse_dates, chunksize=chunksize)
Read SQL query into a DataFrame. Returns a DataFrame corresponding to the result set of the query string. Optionally provide an `index_col` parameter to use one of the columns as the index, otherwise default integer index will be used. Parameters ---------- sql : string SQL query or SQLAlchemy Selectable (select or text object) SQL query to be executed. con : SQLAlchemy connectable(engine/connection), database string URI, or sqlite3 DBAPI2 connection Using SQLAlchemy makes it possible to use any DB supported by that library. If a DBAPI2 object, only sqlite3 is supported. index_col : string or list of strings, optional, default: None Column(s) to set as index(MultiIndex). coerce_float : boolean, default True Attempts to convert values of non-string, non-numeric objects (like decimal.Decimal) to floating point. Useful for SQL result sets. params : list, tuple or dict, optional, default: None List of parameters to pass to execute method. The syntax used to pass parameters is database driver dependent. Check your database driver documentation for which of the five syntax styles, described in PEP 249's paramstyle, is supported. Eg. for psycopg2, uses %(name)s so use params={'name' : 'value'} parse_dates : list or dict, default: None - List of column names to parse as dates. - Dict of ``{column_name: format string}`` where format string is strftime compatible in case of parsing string times, or is one of (D, s, ns, ms, us) in case of parsing integer timestamps. - Dict of ``{column_name: arg dict}``, where the arg dict corresponds to the keyword arguments of :func:`pandas.to_datetime` Especially useful with databases without native Datetime support, such as SQLite. chunksize : int, default None If specified, return an iterator where `chunksize` is the number of rows to include in each chunk. Returns ------- DataFrame See Also -------- read_sql_table : Read SQL database table into a DataFrame. read_sql Notes ----- Any datetime values with time zone information parsed via the `parse_dates` parameter will be converted to UTC.
Read SQL query into a DataFrame.
[ "Read", "SQL", "query", "into", "a", "DataFrame", "." ]
def read_sql_query(sql, con, index_col=None, coerce_float=True, params=None, parse_dates=None, chunksize=None): """Read SQL query into a DataFrame. Returns a DataFrame corresponding to the result set of the query string. Optionally provide an `index_col` parameter to use one of the columns as the index, otherwise default integer index will be used. Parameters ---------- sql : string SQL query or SQLAlchemy Selectable (select or text object) SQL query to be executed. con : SQLAlchemy connectable(engine/connection), database string URI, or sqlite3 DBAPI2 connection Using SQLAlchemy makes it possible to use any DB supported by that library. If a DBAPI2 object, only sqlite3 is supported. index_col : string or list of strings, optional, default: None Column(s) to set as index(MultiIndex). coerce_float : boolean, default True Attempts to convert values of non-string, non-numeric objects (like decimal.Decimal) to floating point. Useful for SQL result sets. params : list, tuple or dict, optional, default: None List of parameters to pass to execute method. The syntax used to pass parameters is database driver dependent. Check your database driver documentation for which of the five syntax styles, described in PEP 249's paramstyle, is supported. Eg. for psycopg2, uses %(name)s so use params={'name' : 'value'} parse_dates : list or dict, default: None - List of column names to parse as dates. - Dict of ``{column_name: format string}`` where format string is strftime compatible in case of parsing string times, or is one of (D, s, ns, ms, us) in case of parsing integer timestamps. - Dict of ``{column_name: arg dict}``, where the arg dict corresponds to the keyword arguments of :func:`pandas.to_datetime` Especially useful with databases without native Datetime support, such as SQLite. chunksize : int, default None If specified, return an iterator where `chunksize` is the number of rows to include in each chunk. Returns ------- DataFrame See Also -------- read_sql_table : Read SQL database table into a DataFrame. read_sql Notes ----- Any datetime values with time zone information parsed via the `parse_dates` parameter will be converted to UTC. """ pandas_sql = pandasSQL_builder(con) return pandas_sql.read_query( sql, index_col=index_col, params=params, coerce_float=coerce_float, parse_dates=parse_dates, chunksize=chunksize)
[ "def", "read_sql_query", "(", "sql", ",", "con", ",", "index_col", "=", "None", ",", "coerce_float", "=", "True", ",", "params", "=", "None", ",", "parse_dates", "=", "None", ",", "chunksize", "=", "None", ")", ":", "pandas_sql", "=", "pandasSQL_builder", "(", "con", ")", "return", "pandas_sql", ".", "read_query", "(", "sql", ",", "index_col", "=", "index_col", ",", "params", "=", "params", ",", "coerce_float", "=", "coerce_float", ",", "parse_dates", "=", "parse_dates", ",", "chunksize", "=", "chunksize", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/io/sql.py#L256-L314
devsisters/libquic
8954789a056d8e7d5fcb6452fd1572ca57eb5c4e
src/third_party/protobuf/python/google/protobuf/service.py
python
RpcController.Failed
(self)
Returns true if the call failed. After a call has finished, returns true if the call failed. The possible reasons for failure depend on the RPC implementation. Failed() must not be called before a call has finished. If Failed() returns true, the contents of the response message are undefined.
Returns true if the call failed.
[ "Returns", "true", "if", "the", "call", "failed", "." ]
def Failed(self): """Returns true if the call failed. After a call has finished, returns true if the call failed. The possible reasons for failure depend on the RPC implementation. Failed() must not be called before a call has finished. If Failed() returns true, the contents of the response message are undefined. """ raise NotImplementedError
[ "def", "Failed", "(", "self", ")", ":", "raise", "NotImplementedError" ]
https://github.com/devsisters/libquic/blob/8954789a056d8e7d5fcb6452fd1572ca57eb5c4e/src/third_party/protobuf/python/google/protobuf/service.py#L140-L148
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SaveVulcanGSS.py
python
SaveVulcanGSS.create_bank_header
(bank_id, vec_x)
return bank_header
create bank header of VDRIVE/GSAS convention as: BANK bank_id data_size data_size binning_type 'SLOG' tof_min tof_max deltaT/T :param bank_id: :param vec_x: :return:
create bank header of VDRIVE/GSAS convention as: BANK bank_id data_size data_size binning_type 'SLOG' tof_min tof_max deltaT/T :param bank_id: :param vec_x: :return:
[ "create", "bank", "header", "of", "VDRIVE", "/", "GSAS", "convention", "as", ":", "BANK", "bank_id", "data_size", "data_size", "binning_type", "SLOG", "tof_min", "tof_max", "deltaT", "/", "T", ":", "param", "bank_id", ":", ":", "param", "vec_x", ":", ":", "return", ":" ]
def create_bank_header(bank_id, vec_x): """ create bank header of VDRIVE/GSAS convention as: BANK bank_id data_size data_size binning_type 'SLOG' tof_min tof_max deltaT/T :param bank_id: :param vec_x: :return: """ tof_min = vec_x[0] tof_max = vec_x[-1] delta_tof = (vec_x[1] - tof_min) / tof_min # deltaT/T data_size = len(vec_x) bank_header = 'BANK {0} {1} {2} {3} {4} {5:.1f} {6:.7f} 0 FXYE' \ ''.format(bank_id, data_size, data_size, 'SLOG', tof_min, tof_max, delta_tof) bank_header = '{0:80s}'.format(bank_header) return bank_header
[ "def", "create_bank_header", "(", "bank_id", ",", "vec_x", ")", ":", "tof_min", "=", "vec_x", "[", "0", "]", "tof_max", "=", "vec_x", "[", "-", "1", "]", "delta_tof", "=", "(", "vec_x", "[", "1", "]", "-", "tof_min", ")", "/", "tof_min", "# deltaT/T", "data_size", "=", "len", "(", "vec_x", ")", "bank_header", "=", "'BANK {0} {1} {2} {3} {4} {5:.1f} {6:.7f} 0 FXYE'", "''", ".", "format", "(", "bank_id", ",", "data_size", ",", "data_size", ",", "'SLOG'", ",", "tof_min", ",", "tof_max", ",", "delta_tof", ")", "bank_header", "=", "'{0:80s}'", ".", "format", "(", "bank_header", ")", "return", "bank_header" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SaveVulcanGSS.py#L416-L434
dmlc/decord
96b750c7221322391969929e855b942d2fdcd06b
python/decord/_ffi/_ctypes/function.py
python
__init_handle_by_constructor__
(fconstructor, args)
return handle
Initialize handle by constructor
Initialize handle by constructor
[ "Initialize", "handle", "by", "constructor" ]
def __init_handle_by_constructor__(fconstructor, args): """Initialize handle by constructor""" temp_args = [] values, tcodes, num_args = _make_decord_args(args, temp_args) ret_val = DECORDValue() ret_tcode = ctypes.c_int() check_call(_LIB.DECORDFuncCall( fconstructor.handle, values, tcodes, ctypes.c_int(num_args), ctypes.byref(ret_val), ctypes.byref(ret_tcode))) _ = temp_args _ = args assert ret_tcode.value == TypeCode.NODE_HANDLE handle = ret_val.v_handle return handle
[ "def", "__init_handle_by_constructor__", "(", "fconstructor", ",", "args", ")", ":", "temp_args", "=", "[", "]", "values", ",", "tcodes", ",", "num_args", "=", "_make_decord_args", "(", "args", ",", "temp_args", ")", "ret_val", "=", "DECORDValue", "(", ")", "ret_tcode", "=", "ctypes", ".", "c_int", "(", ")", "check_call", "(", "_LIB", ".", "DECORDFuncCall", "(", "fconstructor", ".", "handle", ",", "values", ",", "tcodes", ",", "ctypes", ".", "c_int", "(", "num_args", ")", ",", "ctypes", ".", "byref", "(", "ret_val", ")", ",", "ctypes", ".", "byref", "(", "ret_tcode", ")", ")", ")", "_", "=", "temp_args", "_", "=", "args", "assert", "ret_tcode", ".", "value", "==", "TypeCode", ".", "NODE_HANDLE", "handle", "=", "ret_val", ".", "v_handle", "return", "handle" ]
https://github.com/dmlc/decord/blob/96b750c7221322391969929e855b942d2fdcd06b/python/decord/_ffi/_ctypes/function.py#L181-L194
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/lib2to3/pgen2/parse.py
python
Parser.push
(self, type, newdfa, newstate, context)
Push a nonterminal. (Internal)
Push a nonterminal. (Internal)
[ "Push", "a", "nonterminal", ".", "(", "Internal", ")" ]
def push(self, type, newdfa, newstate, context): """Push a nonterminal. (Internal)""" dfa, state, node = self.stack[-1] newnode = (type, None, context, []) self.stack[-1] = (dfa, newstate, node) self.stack.append((newdfa, 0, newnode))
[ "def", "push", "(", "self", ",", "type", ",", "newdfa", ",", "newstate", ",", "context", ")", ":", "dfa", ",", "state", ",", "node", "=", "self", ".", "stack", "[", "-", "1", "]", "newnode", "=", "(", "type", ",", "None", ",", "context", ",", "[", "]", ")", "self", ".", "stack", "[", "-", "1", "]", "=", "(", "dfa", ",", "newstate", ",", "node", ")", "self", ".", "stack", ".", "append", "(", "(", "newdfa", ",", "0", ",", "newnode", ")", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/lib2to3/pgen2/parse.py#L184-L189
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py2/pandas/core/dtypes/common.py
python
classes_and_not_datetimelike
(*klasses)
return lambda tipo: (issubclass(tipo, klasses) and not issubclass(tipo, (np.datetime64, np.timedelta64)))
evaluate if the tipo is a subclass of the klasses and not a datetimelike
evaluate if the tipo is a subclass of the klasses and not a datetimelike
[ "evaluate", "if", "the", "tipo", "is", "a", "subclass", "of", "the", "klasses", "and", "not", "a", "datetimelike" ]
def classes_and_not_datetimelike(*klasses): """ evaluate if the tipo is a subclass of the klasses and not a datetimelike """ return lambda tipo: (issubclass(tipo, klasses) and not issubclass(tipo, (np.datetime64, np.timedelta64)))
[ "def", "classes_and_not_datetimelike", "(", "*", "klasses", ")", ":", "return", "lambda", "tipo", ":", "(", "issubclass", "(", "tipo", ",", "klasses", ")", "and", "not", "issubclass", "(", "tipo", ",", "(", "np", ".", "datetime64", ",", "np", ".", "timedelta64", ")", ")", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/core/dtypes/common.py#L122-L128
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
scripts/Engineering/EnggUtils.py
python
get_ws_indices_for_bank
(workspace, bank)
return [i for i in range(workspace.getNumberHistograms()) if index_in_bank(i)]
DEPRECATED: not used in UI, only in deprecated function EnggVanadiumCorrections get_ws_indices_from_input_properties Finds the workspace indices of all the pixels/detectors/spectra corresponding to a bank. ws :: workspace with instrument definition bank :: bank number as it appears in the instrument definition. A <0 value implies all banks. @returns :: list of workspace indices for the bank
DEPRECATED: not used in UI, only in deprecated function EnggVanadiumCorrections
[ "DEPRECATED", ":", "not", "used", "in", "UI", "only", "in", "deprecated", "function", "EnggVanadiumCorrections" ]
def get_ws_indices_for_bank(workspace, bank): """ DEPRECATED: not used in UI, only in deprecated function EnggVanadiumCorrections get_ws_indices_from_input_properties Finds the workspace indices of all the pixels/detectors/spectra corresponding to a bank. ws :: workspace with instrument definition bank :: bank number as it appears in the instrument definition. A <0 value implies all banks. @returns :: list of workspace indices for the bank """ detector_ids = get_detector_ids_for_bank(bank) def index_in_bank(index): try: det = workspace.getDetector(index) return det.getID() in detector_ids except RuntimeError: return False return [i for i in range(workspace.getNumberHistograms()) if index_in_bank(i)]
[ "def", "get_ws_indices_for_bank", "(", "workspace", ",", "bank", ")", ":", "detector_ids", "=", "get_detector_ids_for_bank", "(", "bank", ")", "def", "index_in_bank", "(", "index", ")", ":", "try", ":", "det", "=", "workspace", ".", "getDetector", "(", "index", ")", "return", "det", ".", "getID", "(", ")", "in", "detector_ids", "except", "RuntimeError", ":", "return", "False", "return", "[", "i", "for", "i", "in", "range", "(", "workspace", ".", "getNumberHistograms", "(", ")", ")", "if", "index_in_bank", "(", "i", ")", "]" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/Engineering/EnggUtils.py#L685-L706
CaoWGG/TensorRT-CenterNet
f949252e37b51e60f873808f46d3683f15735e79
onnx-tensorrt/third_party/onnx/third_party/benchmark/tools/compare.py
python
check_inputs
(in1, in2, flags)
Perform checking on the user provided inputs and diagnose any abnormalities
Perform checking on the user provided inputs and diagnose any abnormalities
[ "Perform", "checking", "on", "the", "user", "provided", "inputs", "and", "diagnose", "any", "abnormalities" ]
def check_inputs(in1, in2, flags): """ Perform checking on the user provided inputs and diagnose any abnormalities """ in1_kind, in1_err = classify_input_file(in1) in2_kind, in2_err = classify_input_file(in2) output_file = find_benchmark_flag('--benchmark_out=', flags) output_type = find_benchmark_flag('--benchmark_out_format=', flags) if in1_kind == IT_Executable and in2_kind == IT_Executable and output_file: print(("WARNING: '--benchmark_out=%s' will be passed to both " "benchmarks causing it to be overwritten") % output_file) if in1_kind == IT_JSON and in2_kind == IT_JSON and len(flags) > 0: print("WARNING: passing optional flags has no effect since both " "inputs are JSON") if output_type is not None and output_type != 'json': print(("ERROR: passing '--benchmark_out_format=%s' to 'compare.py`" " is not supported.") % output_type) sys.exit(1)
[ "def", "check_inputs", "(", "in1", ",", "in2", ",", "flags", ")", ":", "in1_kind", ",", "in1_err", "=", "classify_input_file", "(", "in1", ")", "in2_kind", ",", "in2_err", "=", "classify_input_file", "(", "in2", ")", "output_file", "=", "find_benchmark_flag", "(", "'--benchmark_out='", ",", "flags", ")", "output_type", "=", "find_benchmark_flag", "(", "'--benchmark_out_format='", ",", "flags", ")", "if", "in1_kind", "==", "IT_Executable", "and", "in2_kind", "==", "IT_Executable", "and", "output_file", ":", "print", "(", "(", "\"WARNING: '--benchmark_out=%s' will be passed to both \"", "\"benchmarks causing it to be overwritten\"", ")", "%", "output_file", ")", "if", "in1_kind", "==", "IT_JSON", "and", "in2_kind", "==", "IT_JSON", "and", "len", "(", "flags", ")", ">", "0", ":", "print", "(", "\"WARNING: passing optional flags has no effect since both \"", "\"inputs are JSON\"", ")", "if", "output_type", "is", "not", "None", "and", "output_type", "!=", "'json'", ":", "print", "(", "(", "\"ERROR: passing '--benchmark_out_format=%s' to 'compare.py`\"", "\" is not supported.\"", ")", "%", "output_type", ")", "sys", ".", "exit", "(", "1", ")" ]
https://github.com/CaoWGG/TensorRT-CenterNet/blob/f949252e37b51e60f873808f46d3683f15735e79/onnx-tensorrt/third_party/onnx/third_party/benchmark/tools/compare.py#L15-L32
pyne/pyne
0c2714d7c0d1b5e20be6ae6527da2c660dd6b1b3
pyne/xs/data_source.py
python
OpenMCDataSource._load_reaction
(self, nuc, rx, temp=300.0)
return rxdata
Loads reaction data from ACE files indexed by OpenMC. Parameters ---------- nuc : int Nuclide id. rx : int Reaction id. temp : float, optional The nuclide temperature in [K].
Loads reaction data from ACE files indexed by OpenMC.
[ "Loads", "reaction", "data", "from", "ACE", "files", "indexed", "by", "OpenMC", "." ]
def _load_reaction(self, nuc, rx, temp=300.0): """Loads reaction data from ACE files indexed by OpenMC. Parameters ---------- nuc : int Nuclide id. rx : int Reaction id. temp : float, optional The nuclide temperature in [K]. """ rtn = self.pointwise(nuc, rx, temp=temp) if rtn is None: return E_points, rawdata = rtn E_g = self.src_group_struct if self.atom_dens.get(nuc, 0.0) > 1.0E19 and rx in self.self_shield_reactions: rxdata = self.self_shield(nuc, rx, temp, E_points, rawdata) else: rxdata = bins.pointwise_linear_collapse(E_g, E_points, rawdata) return rxdata
[ "def", "_load_reaction", "(", "self", ",", "nuc", ",", "rx", ",", "temp", "=", "300.0", ")", ":", "rtn", "=", "self", ".", "pointwise", "(", "nuc", ",", "rx", ",", "temp", "=", "temp", ")", "if", "rtn", "is", "None", ":", "return", "E_points", ",", "rawdata", "=", "rtn", "E_g", "=", "self", ".", "src_group_struct", "if", "self", ".", "atom_dens", ".", "get", "(", "nuc", ",", "0.0", ")", ">", "1.0E19", "and", "rx", "in", "self", ".", "self_shield_reactions", ":", "rxdata", "=", "self", ".", "self_shield", "(", "nuc", ",", "rx", ",", "temp", ",", "E_points", ",", "rawdata", ")", "else", ":", "rxdata", "=", "bins", ".", "pointwise_linear_collapse", "(", "E_g", ",", "E_points", ",", "rawdata", ")", "return", "rxdata" ]
https://github.com/pyne/pyne/blob/0c2714d7c0d1b5e20be6ae6527da2c660dd6b1b3/pyne/xs/data_source.py#L1010-L1031
ycm-core/ycmd
fc0fb7e5e15176cc5a2a30c80956335988c6b59a
ycmd/completers/language_server/language_server_completer.py
python
LanguageServerCompleter.GetProjectRootFiles
( self )
return []
Returns a list of files that indicate the root of the project. It should be easier to override just this method than the whole GetProjectDirectory.
Returns a list of files that indicate the root of the project. It should be easier to override just this method than the whole GetProjectDirectory.
[ "Returns", "a", "list", "of", "files", "that", "indicate", "the", "root", "of", "the", "project", ".", "It", "should", "be", "easier", "to", "override", "just", "this", "method", "than", "the", "whole", "GetProjectDirectory", "." ]
def GetProjectRootFiles( self ): """Returns a list of files that indicate the root of the project. It should be easier to override just this method than the whole GetProjectDirectory.""" return []
[ "def", "GetProjectRootFiles", "(", "self", ")", ":", "return", "[", "]" ]
https://github.com/ycm-core/ycmd/blob/fc0fb7e5e15176cc5a2a30c80956335988c6b59a/ycmd/completers/language_server/language_server_completer.py#L2133-L2137
crosslife/OpenBird
9e0198a1a2295f03fa1e8676e216e22c9c7d380b
cocos2d/tools/bindings-generator/clang/cindex.py
python
SourceLocation.offset
(self)
return self._get_instantiation()[3]
Get the file offset represented by this source location.
Get the file offset represented by this source location.
[ "Get", "the", "file", "offset", "represented", "by", "this", "source", "location", "." ]
def offset(self): """Get the file offset represented by this source location.""" return self._get_instantiation()[3]
[ "def", "offset", "(", "self", ")", ":", "return", "self", ".", "_get_instantiation", "(", ")", "[", "3", "]" ]
https://github.com/crosslife/OpenBird/blob/9e0198a1a2295f03fa1e8676e216e22c9c7d380b/cocos2d/tools/bindings-generator/clang/cindex.py#L213-L215
epiqc/ScaffCC
66a79944ee4cd116b27bc1a69137276885461db8
clang/utils/check_cfc/obj_diff.py
python
dump_debug
(objfile)
return [line for line in out.split(os.linesep) if keep_line(line)]
Dump all of the debug info from a file.
Dump all of the debug info from a file.
[ "Dump", "all", "of", "the", "debug", "info", "from", "a", "file", "." ]
def dump_debug(objfile): """Dump all of the debug info from a file.""" p = subprocess.Popen([disassembler, '-WliaprmfsoRt', objfile], stdout=subprocess.PIPE, stderr=subprocess.PIPE) (out, err) = p.communicate() if p.returncode or err: print("Dump debug failed: {}".format(objfile)) sys.exit(1) return [line for line in out.split(os.linesep) if keep_line(line)]
[ "def", "dump_debug", "(", "objfile", ")", ":", "p", "=", "subprocess", ".", "Popen", "(", "[", "disassembler", ",", "'-WliaprmfsoRt'", ",", "objfile", "]", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "PIPE", ")", "(", "out", ",", "err", ")", "=", "p", ".", "communicate", "(", ")", "if", "p", ".", "returncode", "or", "err", ":", "print", "(", "\"Dump debug failed: {}\"", ".", "format", "(", "objfile", ")", ")", "sys", ".", "exit", "(", "1", ")", "return", "[", "line", "for", "line", "in", "out", ".", "split", "(", "os", ".", "linesep", ")", "if", "keep_line", "(", "line", ")", "]" ]
https://github.com/epiqc/ScaffCC/blob/66a79944ee4cd116b27bc1a69137276885461db8/clang/utils/check_cfc/obj_diff.py#L30-L37
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
python/paddle/distributed/fleet/dataset/dataset.py
python
InMemoryDataset.get_shuffle_data_size
(self, fleet=None)
return local_data_size[0]
:api_attr: Static Graph Get shuffle data size, user can call this function to know the num of ins in all workers after local/global shuffle. Note: This function may cause bad performance to local shuffle, because it has barrier. It does not affect global shuffle. Args: fleet(Fleet): Fleet Object. Returns: The size of shuffle data. Examples: .. code-block:: python import paddle paddle.enable_static() dataset = paddle.distributed.InMemoryDataset() dataset = paddle.distributed.InMemoryDataset() slots = ["slot1", "slot2", "slot3", "slot4"] slots_vars = [] for slot in slots: var = paddle.static.data( name=slot, shape=[None, 1], dtype="int64", lod_level=1) slots_vars.append(var) dataset.init( batch_size=1, thread_num=2, input_type=1, pipe_command="cat", use_var=slots_vars) filelist = ["a.txt", "b.txt"] dataset.set_filelist(filelist) dataset.load_into_memory() dataset.global_shuffle() print dataset.get_shuffle_data_size()
:api_attr: Static Graph
[ ":", "api_attr", ":", "Static", "Graph" ]
def get_shuffle_data_size(self, fleet=None): """ :api_attr: Static Graph Get shuffle data size, user can call this function to know the num of ins in all workers after local/global shuffle. Note: This function may cause bad performance to local shuffle, because it has barrier. It does not affect global shuffle. Args: fleet(Fleet): Fleet Object. Returns: The size of shuffle data. Examples: .. code-block:: python import paddle paddle.enable_static() dataset = paddle.distributed.InMemoryDataset() dataset = paddle.distributed.InMemoryDataset() slots = ["slot1", "slot2", "slot3", "slot4"] slots_vars = [] for slot in slots: var = paddle.static.data( name=slot, shape=[None, 1], dtype="int64", lod_level=1) slots_vars.append(var) dataset.init( batch_size=1, thread_num=2, input_type=1, pipe_command="cat", use_var=slots_vars) filelist = ["a.txt", "b.txt"] dataset.set_filelist(filelist) dataset.load_into_memory() dataset.global_shuffle() print dataset.get_shuffle_data_size() """ import numpy as np local_data_size = self.dataset.get_shuffle_data_size() local_data_size = np.array([local_data_size]) if fleet is not None: global_data_size = local_data_size * 0 fleet._role_maker.all_reduce_worker(local_data_size, global_data_size) return global_data_size[0] return local_data_size[0]
[ "def", "get_shuffle_data_size", "(", "self", ",", "fleet", "=", "None", ")", ":", "import", "numpy", "as", "np", "local_data_size", "=", "self", ".", "dataset", ".", "get_shuffle_data_size", "(", ")", "local_data_size", "=", "np", ".", "array", "(", "[", "local_data_size", "]", ")", "if", "fleet", "is", "not", "None", ":", "global_data_size", "=", "local_data_size", "*", "0", "fleet", ".", "_role_maker", ".", "all_reduce_worker", "(", "local_data_size", ",", "global_data_size", ")", "return", "global_data_size", "[", "0", "]", "return", "local_data_size", "[", "0", "]" ]
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/distributed/fleet/dataset/dataset.py#L1121-L1173
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/devil/devil/android/device_utils.py
python
DeviceUtils.IsOnline
(self, timeout=None, retries=None)
Checks whether the device is online. Args: timeout: timeout in seconds retries: number of retries Returns: True if the device is online, False otherwise. Raises: CommandTimeoutError on timeout.
Checks whether the device is online.
[ "Checks", "whether", "the", "device", "is", "online", "." ]
def IsOnline(self, timeout=None, retries=None): """Checks whether the device is online. Args: timeout: timeout in seconds retries: number of retries Returns: True if the device is online, False otherwise. Raises: CommandTimeoutError on timeout. """ try: return self.adb.GetState() == 'device' except base_error.BaseError as exc: logging.info('Failed to get state: %s', exc) return False
[ "def", "IsOnline", "(", "self", ",", "timeout", "=", "None", ",", "retries", "=", "None", ")", ":", "try", ":", "return", "self", ".", "adb", ".", "GetState", "(", ")", "==", "'device'", "except", "base_error", ".", "BaseError", "as", "exc", ":", "logging", ".", "info", "(", "'Failed to get state: %s'", ",", "exc", ")", "return", "False" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/devil/devil/android/device_utils.py#L324-L341
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_windows.py
python
SashLayoutWindow.SetDefaultSize
(*args, **kwargs)
return _windows_.SashLayoutWindow_SetDefaultSize(*args, **kwargs)
SetDefaultSize(self, Size size)
SetDefaultSize(self, Size size)
[ "SetDefaultSize", "(", "self", "Size", "size", ")" ]
def SetDefaultSize(*args, **kwargs): """SetDefaultSize(self, Size size)""" return _windows_.SashLayoutWindow_SetDefaultSize(*args, **kwargs)
[ "def", "SetDefaultSize", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_windows_", ".", "SashLayoutWindow_SetDefaultSize", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_windows.py#L2067-L2069
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/compat/compat.py
python
forward_compatible
(year, month, day)
return _FORWARD_COMPATIBILITY_DATE_NUMBER > _date_to_date_number( year, month, day)
Return true if the forward compatibility window has expired. See [Version compatibility](https://tensorflow.org/guide/version_compat#backward_forward). Forward-compatibility refers to scenarios where the producer of a TensorFlow model (a GraphDef or SavedModel) is compiled against a version of the TensorFlow library newer than what the consumer was compiled against. The "producer" is typically a Python program that constructs and trains a model while the "consumer" is typically another program that loads and serves the model. TensorFlow has been supporting a 3 week forward-compatibility window for programs compiled from source at HEAD. For example, consider the case where a new operation `MyNewAwesomeAdd` is created with the intent of replacing the implementation of an existing Python wrapper - `tf.add`. The Python wrapper implementation should change from something like: ```python def add(inputs, name=None): return gen_math_ops.add(inputs, name) ``` to: ```python from tensorflow.python.compat import compat def add(inputs, name=None): if compat.forward_compatible(year, month, day): # Can use the awesome new implementation. return gen_math_ops.my_new_awesome_add(inputs, name) # To maintain forward compatibiltiy, use the old implementation. return gen_math_ops.add(inputs, name) ``` Where `year`, `month`, and `day` specify the date beyond which binaries that consume a model are expected to have been updated to include the new operations. This date is typically at least 3 weeks beyond the date the code that adds the new operation is committed. Args: year: A year (e.g., 2018). Must be an `int`. month: A month (1 <= month <= 12) in year. Must be an `int`. day: A day (1 <= day <= 31, or 30, or 29, or 28) in month. Must be an `int`. Returns: True if the caller can expect that serialized TensorFlow graphs produced can be consumed by programs that are compiled with the TensorFlow library source code after (year, month, day).
Return true if the forward compatibility window has expired.
[ "Return", "true", "if", "the", "forward", "compatibility", "window", "has", "expired", "." ]
def forward_compatible(year, month, day): """Return true if the forward compatibility window has expired. See [Version compatibility](https://tensorflow.org/guide/version_compat#backward_forward). Forward-compatibility refers to scenarios where the producer of a TensorFlow model (a GraphDef or SavedModel) is compiled against a version of the TensorFlow library newer than what the consumer was compiled against. The "producer" is typically a Python program that constructs and trains a model while the "consumer" is typically another program that loads and serves the model. TensorFlow has been supporting a 3 week forward-compatibility window for programs compiled from source at HEAD. For example, consider the case where a new operation `MyNewAwesomeAdd` is created with the intent of replacing the implementation of an existing Python wrapper - `tf.add`. The Python wrapper implementation should change from something like: ```python def add(inputs, name=None): return gen_math_ops.add(inputs, name) ``` to: ```python from tensorflow.python.compat import compat def add(inputs, name=None): if compat.forward_compatible(year, month, day): # Can use the awesome new implementation. return gen_math_ops.my_new_awesome_add(inputs, name) # To maintain forward compatibiltiy, use the old implementation. return gen_math_ops.add(inputs, name) ``` Where `year`, `month`, and `day` specify the date beyond which binaries that consume a model are expected to have been updated to include the new operations. This date is typically at least 3 weeks beyond the date the code that adds the new operation is committed. Args: year: A year (e.g., 2018). Must be an `int`. month: A month (1 <= month <= 12) in year. Must be an `int`. day: A day (1 <= day <= 31, or 30, or 29, or 28) in month. Must be an `int`. Returns: True if the caller can expect that serialized TensorFlow graphs produced can be consumed by programs that are compiled with the TensorFlow library source code after (year, month, day). """ return _FORWARD_COMPATIBILITY_DATE_NUMBER > _date_to_date_number( year, month, day)
[ "def", "forward_compatible", "(", "year", ",", "month", ",", "day", ")", ":", "return", "_FORWARD_COMPATIBILITY_DATE_NUMBER", ">", "_date_to_date_number", "(", "year", ",", "month", ",", "day", ")" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/compat/compat.py#L64-L120
miyosuda/TensorFlowAndroidMNIST
7b5a4603d2780a8a2834575706e9001977524007
jni-build/jni/include/tensorflow/python/training/coordinator.py
python
Coordinator.register_thread
(self, thread)
Register a thread to join. Args: thread: A Python thread to join.
Register a thread to join.
[ "Register", "a", "thread", "to", "join", "." ]
def register_thread(self, thread): """Register a thread to join. Args: thread: A Python thread to join. """ with self._lock: self._registered_threads.add(thread)
[ "def", "register_thread", "(", "self", ",", "thread", ")", ":", "with", "self", ".", "_lock", ":", "self", ".", "_registered_threads", ".", "add", "(", "thread", ")" ]
https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/python/training/coordinator.py#L313-L320
okex/V3-Open-API-SDK
c5abb0db7e2287718e0055e17e57672ce0ec7fd9
okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/distlib/metadata.py
python
LegacyMetadata.check
(self, strict=False)
return missing, warnings
Check if the metadata is compliant. If strict is True then raise if no Name or Version are provided
Check if the metadata is compliant. If strict is True then raise if no Name or Version are provided
[ "Check", "if", "the", "metadata", "is", "compliant", ".", "If", "strict", "is", "True", "then", "raise", "if", "no", "Name", "or", "Version", "are", "provided" ]
def check(self, strict=False): """Check if the metadata is compliant. If strict is True then raise if no Name or Version are provided""" self.set_metadata_version() # XXX should check the versions (if the file was loaded) missing, warnings = [], [] for attr in ('Name', 'Version'): # required by PEP 345 if attr not in self: missing.append(attr) if strict and missing != []: msg = 'missing required metadata: %s' % ', '.join(missing) raise MetadataMissingError(msg) for attr in ('Home-page', 'Author'): if attr not in self: missing.append(attr) # checking metadata 1.2 (XXX needs to check 1.1, 1.0) if self['Metadata-Version'] != '1.2': return missing, warnings scheme = get_scheme(self.scheme) def are_valid_constraints(value): for v in value: if not scheme.is_valid_matcher(v.split(';')[0]): return False return True for fields, controller in ((_PREDICATE_FIELDS, are_valid_constraints), (_VERSIONS_FIELDS, scheme.is_valid_constraint_list), (_VERSION_FIELDS, scheme.is_valid_version)): for field in fields: value = self.get(field, None) if value is not None and not controller(value): warnings.append("Wrong value for '%s': %s" % (field, value)) return missing, warnings
[ "def", "check", "(", "self", ",", "strict", "=", "False", ")", ":", "self", ".", "set_metadata_version", "(", ")", "# XXX should check the versions (if the file was loaded)", "missing", ",", "warnings", "=", "[", "]", ",", "[", "]", "for", "attr", "in", "(", "'Name'", ",", "'Version'", ")", ":", "# required by PEP 345", "if", "attr", "not", "in", "self", ":", "missing", ".", "append", "(", "attr", ")", "if", "strict", "and", "missing", "!=", "[", "]", ":", "msg", "=", "'missing required metadata: %s'", "%", "', '", ".", "join", "(", "missing", ")", "raise", "MetadataMissingError", "(", "msg", ")", "for", "attr", "in", "(", "'Home-page'", ",", "'Author'", ")", ":", "if", "attr", "not", "in", "self", ":", "missing", ".", "append", "(", "attr", ")", "# checking metadata 1.2 (XXX needs to check 1.1, 1.0)", "if", "self", "[", "'Metadata-Version'", "]", "!=", "'1.2'", ":", "return", "missing", ",", "warnings", "scheme", "=", "get_scheme", "(", "self", ".", "scheme", ")", "def", "are_valid_constraints", "(", "value", ")", ":", "for", "v", "in", "value", ":", "if", "not", "scheme", ".", "is_valid_matcher", "(", "v", ".", "split", "(", "';'", ")", "[", "0", "]", ")", ":", "return", "False", "return", "True", "for", "fields", ",", "controller", "in", "(", "(", "_PREDICATE_FIELDS", ",", "are_valid_constraints", ")", ",", "(", "_VERSIONS_FIELDS", ",", "scheme", ".", "is_valid_constraint_list", ")", ",", "(", "_VERSION_FIELDS", ",", "scheme", ".", "is_valid_version", ")", ")", ":", "for", "field", "in", "fields", ":", "value", "=", "self", ".", "get", "(", "field", ",", "None", ")", "if", "value", "is", "not", "None", "and", "not", "controller", "(", "value", ")", ":", "warnings", ".", "append", "(", "\"Wrong value for '%s': %s\"", "%", "(", "field", ",", "value", ")", ")", "return", "missing", ",", "warnings" ]
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/metadata.py#L519-L561
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pyparsing/py3/pyparsing/core.py
python
ParserElement.__ror__
(self, other)
return other | self
Implementation of ``|`` operator when left operand is not a :class:`ParserElement`
Implementation of ``|`` operator when left operand is not a :class:`ParserElement`
[ "Implementation", "of", "|", "operator", "when", "left", "operand", "is", "not", "a", ":", "class", ":", "ParserElement" ]
def __ror__(self, other): """ Implementation of ``|`` operator when left operand is not a :class:`ParserElement` """ if isinstance(other, str_type): other = self._literalStringClass(other) if not isinstance(other, ParserElement): raise TypeError( "Cannot combine element of type {} with ParserElement".format( type(other).__name__ ) ) return other | self
[ "def", "__ror__", "(", "self", ",", "other", ")", ":", "if", "isinstance", "(", "other", ",", "str_type", ")", ":", "other", "=", "self", ".", "_literalStringClass", "(", "other", ")", "if", "not", "isinstance", "(", "other", ",", "ParserElement", ")", ":", "raise", "TypeError", "(", "\"Cannot combine element of type {} with ParserElement\"", ".", "format", "(", "type", "(", "other", ")", ".", "__name__", ")", ")", "return", "other", "|", "self" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pyparsing/py3/pyparsing/core.py#L1536-L1548
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/socket.py
python
SocketIO.writable
(self)
return self._writing
True if the SocketIO is open for writing.
True if the SocketIO is open for writing.
[ "True", "if", "the", "SocketIO", "is", "open", "for", "writing", "." ]
def writable(self): """True if the SocketIO is open for writing. """ if self.closed: raise ValueError("I/O operation on closed socket.") return self._writing
[ "def", "writable", "(", "self", ")", ":", "if", "self", ".", "closed", ":", "raise", "ValueError", "(", "\"I/O operation on closed socket.\"", ")", "return", "self", ".", "_writing" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/socket.py#L736-L741
quantOS-org/DataCore
e2ef9bd2c22ee9e2845675b6435a14fa607f3551
mdlink/deps/windows/protobuf-2.5.0/python/google/protobuf/descriptor_pool.py
python
DescriptorPool.__init__
(self, descriptor_db=None)
Initializes a Pool of proto buffs. The descriptor_db argument to the constructor is provided to allow specialized file descriptor proto lookup code to be triggered on demand. An example would be an implementation which will read and compile a file specified in a call to FindFileByName() and not require the call to Add() at all. Results from this database will be cached internally here as well. Args: descriptor_db: A secondary source of file descriptors.
Initializes a Pool of proto buffs.
[ "Initializes", "a", "Pool", "of", "proto", "buffs", "." ]
def __init__(self, descriptor_db=None): """Initializes a Pool of proto buffs. The descriptor_db argument to the constructor is provided to allow specialized file descriptor proto lookup code to be triggered on demand. An example would be an implementation which will read and compile a file specified in a call to FindFileByName() and not require the call to Add() at all. Results from this database will be cached internally here as well. Args: descriptor_db: A secondary source of file descriptors. """ self._internal_db = descriptor_database.DescriptorDatabase() self._descriptor_db = descriptor_db self._descriptors = {} self._enum_descriptors = {} self._file_descriptors = {}
[ "def", "__init__", "(", "self", ",", "descriptor_db", "=", "None", ")", ":", "self", ".", "_internal_db", "=", "descriptor_database", ".", "DescriptorDatabase", "(", ")", "self", ".", "_descriptor_db", "=", "descriptor_db", "self", ".", "_descriptors", "=", "{", "}", "self", ".", "_enum_descriptors", "=", "{", "}", "self", ".", "_file_descriptors", "=", "{", "}" ]
https://github.com/quantOS-org/DataCore/blob/e2ef9bd2c22ee9e2845675b6435a14fa607f3551/mdlink/deps/windows/protobuf-2.5.0/python/google/protobuf/descriptor_pool.py#L64-L81
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/ipython/py3/IPython/utils/text.py
python
SList.fields
(self, *fields)
return res
Collect whitespace-separated fields from string list Allows quick awk-like usage of string lists. Example data (in var a, created by 'a = !ls -l'):: -rwxrwxrwx 1 ville None 18 Dec 14 2006 ChangeLog drwxrwxrwx+ 6 ville None 0 Oct 24 18:05 IPython * ``a.fields(0)`` is ``['-rwxrwxrwx', 'drwxrwxrwx+']`` * ``a.fields(1,0)`` is ``['1 -rwxrwxrwx', '6 drwxrwxrwx+']`` (note the joining by space). * ``a.fields(-1)`` is ``['ChangeLog', 'IPython']`` IndexErrors are ignored. Without args, fields() just split()'s the strings.
Collect whitespace-separated fields from string list
[ "Collect", "whitespace", "-", "separated", "fields", "from", "string", "list" ]
def fields(self, *fields): """ Collect whitespace-separated fields from string list Allows quick awk-like usage of string lists. Example data (in var a, created by 'a = !ls -l'):: -rwxrwxrwx 1 ville None 18 Dec 14 2006 ChangeLog drwxrwxrwx+ 6 ville None 0 Oct 24 18:05 IPython * ``a.fields(0)`` is ``['-rwxrwxrwx', 'drwxrwxrwx+']`` * ``a.fields(1,0)`` is ``['1 -rwxrwxrwx', '6 drwxrwxrwx+']`` (note the joining by space). * ``a.fields(-1)`` is ``['ChangeLog', 'IPython']`` IndexErrors are ignored. Without args, fields() just split()'s the strings. """ if len(fields) == 0: return [el.split() for el in self] res = SList() for el in [f.split() for f in self]: lineparts = [] for fd in fields: try: lineparts.append(el[fd]) except IndexError: pass if lineparts: res.append(" ".join(lineparts)) return res
[ "def", "fields", "(", "self", ",", "*", "fields", ")", ":", "if", "len", "(", "fields", ")", "==", "0", ":", "return", "[", "el", ".", "split", "(", ")", "for", "el", "in", "self", "]", "res", "=", "SList", "(", ")", "for", "el", "in", "[", "f", ".", "split", "(", ")", "for", "f", "in", "self", "]", ":", "lineparts", "=", "[", "]", "for", "fd", "in", "fields", ":", "try", ":", "lineparts", ".", "append", "(", "el", "[", "fd", "]", ")", "except", "IndexError", ":", "pass", "if", "lineparts", ":", "res", ".", "append", "(", "\" \"", ".", "join", "(", "lineparts", ")", ")", "return", "res" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py3/IPython/utils/text.py#L168-L202
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/computation/expr.py
python
_is_type
(t)
return lambda x: isinstance(x.value, t)
Factory for a type checking function of type ``t`` or tuple of types.
Factory for a type checking function of type ``t`` or tuple of types.
[ "Factory", "for", "a", "type", "checking", "function", "of", "type", "t", "or", "tuple", "of", "types", "." ]
def _is_type(t): """Factory for a type checking function of type ``t`` or tuple of types.""" return lambda x: isinstance(x.value, t)
[ "def", "_is_type", "(", "t", ")", ":", "return", "lambda", "x", ":", "isinstance", "(", "x", ".", "value", ",", "t", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/computation/expr.py#L148-L150
root-project/root
fcd3583bb14852bf2e8cd2415717cbaac0e75896
interpreter/llvm/src/utils/lint/common_lint.py
python
VerifyTabs
(filename, lines)
return lint
Checks to make sure the file has no tab characters. Args: filename: the file under consideration as string lines: contents of the file as string array Returns: A list of tuples with format [(line_number, msg), ...] with any violations found.
Checks to make sure the file has no tab characters.
[ "Checks", "to", "make", "sure", "the", "file", "has", "no", "tab", "characters", "." ]
def VerifyTabs(filename, lines): """Checks to make sure the file has no tab characters. Args: filename: the file under consideration as string lines: contents of the file as string array Returns: A list of tuples with format [(line_number, msg), ...] with any violations found. """ lint = [] tab_re = re.compile(r'\t') line_num = 1 for line in lines: if tab_re.match(line.rstrip('\n')): lint.append((filename, line_num, 'Tab found instead of whitespace')) line_num += 1 return lint
[ "def", "VerifyTabs", "(", "filename", ",", "lines", ")", ":", "lint", "=", "[", "]", "tab_re", "=", "re", ".", "compile", "(", "r'\\t'", ")", "line_num", "=", "1", "for", "line", "in", "lines", ":", "if", "tab_re", ".", "match", "(", "line", ".", "rstrip", "(", "'\\n'", ")", ")", ":", "lint", ".", "append", "(", "(", "filename", ",", "line_num", ",", "'Tab found instead of whitespace'", ")", ")", "line_num", "+=", "1", "return", "lint" ]
https://github.com/root-project/root/blob/fcd3583bb14852bf2e8cd2415717cbaac0e75896/interpreter/llvm/src/utils/lint/common_lint.py#L31-L49
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/SimpleXMLRPCServer.py
python
list_public_methods
(obj)
return [member for member in dir(obj) if not member.startswith('_') and hasattr(getattr(obj, member), '__call__')]
Returns a list of attribute strings, found in the specified object, which represent callable attributes
Returns a list of attribute strings, found in the specified object, which represent callable attributes
[ "Returns", "a", "list", "of", "attribute", "strings", "found", "in", "the", "specified", "object", "which", "represent", "callable", "attributes" ]
def list_public_methods(obj): """Returns a list of attribute strings, found in the specified object, which represent callable attributes""" return [member for member in dir(obj) if not member.startswith('_') and hasattr(getattr(obj, member), '__call__')]
[ "def", "list_public_methods", "(", "obj", ")", ":", "return", "[", "member", "for", "member", "in", "dir", "(", "obj", ")", "if", "not", "member", ".", "startswith", "(", "'_'", ")", "and", "hasattr", "(", "getattr", "(", "obj", ",", "member", ")", ",", "'__call__'", ")", "]" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/SimpleXMLRPCServer.py#L139-L145
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
lts/deps/v8/tools/lldb_commands.py
python
jco
(debugger, param, *args)
Print the code object at the given pc (default: current pc)
Print the code object at the given pc (default: current pc)
[ "Print", "the", "code", "object", "at", "the", "given", "pc", "(", "default", ":", "current", "pc", ")" ]
def jco(debugger, param, *args): """Print the code object at the given pc (default: current pc)""" if not param: param = str(current_frame(debugger).FindRegister("pc").value) ptr_arg_cmd(debugger, 'jco', param, "_v8_internal_Print_Code({})")
[ "def", "jco", "(", "debugger", ",", "param", ",", "*", "args", ")", ":", "if", "not", "param", ":", "param", "=", "str", "(", "current_frame", "(", "debugger", ")", ".", "FindRegister", "(", "\"pc\"", ")", ".", "value", ")", "ptr_arg_cmd", "(", "debugger", ",", "'jco'", ",", "param", ",", "\"_v8_internal_Print_Code({})\"", ")" ]
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/deps/v8/tools/lldb_commands.py#L46-L50
albertz/openlierox
d316c14a8eb57848ef56e9bfa7b23a56f694a51b
tools/DedicatedServerVideo/gdata/Crypto/Util/number.py
python
size
(N)
return bits
size(N:long) : int Returns the size of the number N in bits.
size(N:long) : int Returns the size of the number N in bits.
[ "size", "(", "N", ":", "long", ")", ":", "int", "Returns", "the", "size", "of", "the", "number", "N", "in", "bits", "." ]
def size (N): """size(N:long) : int Returns the size of the number N in bits. """ bits, power = 0,1L while N >= power: bits += 1 power = power << 1 return bits
[ "def", "size", "(", "N", ")", ":", "bits", ",", "power", "=", "0", ",", "1L", "while", "N", ">=", "power", ":", "bits", "+=", "1", "power", "=", "power", "<<", "1", "return", "bits" ]
https://github.com/albertz/openlierox/blob/d316c14a8eb57848ef56e9bfa7b23a56f694a51b/tools/DedicatedServerVideo/gdata/Crypto/Util/number.py#L34-L42
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/build/waf-1.7.13/waflib/TaskGen.py
python
task_gen.to_list
(self, val)
Ensure that a parameter is a list :type val: string or list of string :param val: input to return as a list :rtype: list
Ensure that a parameter is a list
[ "Ensure", "that", "a", "parameter", "is", "a", "list" ]
def to_list(self, val): """ Ensure that a parameter is a list :type val: string or list of string :param val: input to return as a list :rtype: list """ if isinstance(val, str): return val.split() else: return val
[ "def", "to_list", "(", "self", ",", "val", ")", ":", "if", "isinstance", "(", "val", ",", "str", ")", ":", "return", "val", ".", "split", "(", ")", "else", ":", "return", "val" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/build/waf-1.7.13/waflib/TaskGen.py#L131-L140
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/stringold.py
python
rfind
(s, *args)
return _apply(s.rfind, args)
rfind(s, sub [,start [,end]]) -> int Return the highest index in s where substring sub is found, such that sub is contained within s[start,end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on failure.
rfind(s, sub [,start [,end]]) -> int
[ "rfind", "(", "s", "sub", "[", "start", "[", "end", "]]", ")", "-", ">", "int" ]
def rfind(s, *args): """rfind(s, sub [,start [,end]]) -> int Return the highest index in s where substring sub is found, such that sub is contained within s[start,end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on failure. """ return _apply(s.rfind, args)
[ "def", "rfind", "(", "s", ",", "*", "args", ")", ":", "return", "_apply", "(", "s", ".", "rfind", ",", "args", ")" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/stringold.py#L178-L188
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/labelbook.py
python
ImageInfo.GetCaption
(self)
return self._strCaption
Returns the tab caption.
Returns the tab caption.
[ "Returns", "the", "tab", "caption", "." ]
def GetCaption(self): """ Returns the tab caption. """ return self._strCaption
[ "def", "GetCaption", "(", "self", ")", ":", "return", "self", ".", "_strCaption" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/labelbook.py#L375-L378
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/richtext.py
python
TextBoxAttr.GetRightBorder
(*args)
return _richtext.TextBoxAttr_GetRightBorder(*args)
GetRightBorder(self) -> TextAttrBorder GetRightBorder(self) -> TextAttrBorder
GetRightBorder(self) -> TextAttrBorder GetRightBorder(self) -> TextAttrBorder
[ "GetRightBorder", "(", "self", ")", "-", ">", "TextAttrBorder", "GetRightBorder", "(", "self", ")", "-", ">", "TextAttrBorder" ]
def GetRightBorder(*args): """ GetRightBorder(self) -> TextAttrBorder GetRightBorder(self) -> TextAttrBorder """ return _richtext.TextBoxAttr_GetRightBorder(*args)
[ "def", "GetRightBorder", "(", "*", "args", ")", ":", "return", "_richtext", ".", "TextBoxAttr_GetRightBorder", "(", "*", "args", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/richtext.py#L754-L759
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pytz/pytz/tzinfo.py
python
DstTzInfo.localize
(self, dt, is_dst=False)
return dates[[min, max][not is_dst](dates)]
Convert naive time to local time. This method should be used to construct localtimes, rather than passing a tzinfo argument to a datetime constructor. is_dst is used to determine the correct timezone in the ambigous period at the end of daylight saving time. >>> from pytz import timezone >>> fmt = '%Y-%m-%d %H:%M:%S %Z (%z)' >>> amdam = timezone('Europe/Amsterdam') >>> dt = datetime(2004, 10, 31, 2, 0, 0) >>> loc_dt1 = amdam.localize(dt, is_dst=True) >>> loc_dt2 = amdam.localize(dt, is_dst=False) >>> loc_dt1.strftime(fmt) '2004-10-31 02:00:00 CEST (+0200)' >>> loc_dt2.strftime(fmt) '2004-10-31 02:00:00 CET (+0100)' >>> str(loc_dt2 - loc_dt1) '1:00:00' Use is_dst=None to raise an AmbiguousTimeError for ambiguous times at the end of daylight saving time >>> try: ... loc_dt1 = amdam.localize(dt, is_dst=None) ... except AmbiguousTimeError: ... print('Ambiguous') Ambiguous is_dst defaults to False >>> amdam.localize(dt) == amdam.localize(dt, False) True is_dst is also used to determine the correct timezone in the wallclock times jumped over at the start of daylight saving time. >>> pacific = timezone('US/Pacific') >>> dt = datetime(2008, 3, 9, 2, 0, 0) >>> ploc_dt1 = pacific.localize(dt, is_dst=True) >>> ploc_dt2 = pacific.localize(dt, is_dst=False) >>> ploc_dt1.strftime(fmt) '2008-03-09 02:00:00 PDT (-0700)' >>> ploc_dt2.strftime(fmt) '2008-03-09 02:00:00 PST (-0800)' >>> str(ploc_dt2 - ploc_dt1) '1:00:00' Use is_dst=None to raise a NonExistentTimeError for these skipped times. >>> try: ... loc_dt1 = pacific.localize(dt, is_dst=None) ... except NonExistentTimeError: ... print('Non-existent') Non-existent
Convert naive time to local time.
[ "Convert", "naive", "time", "to", "local", "time", "." ]
def localize(self, dt, is_dst=False): '''Convert naive time to local time. This method should be used to construct localtimes, rather than passing a tzinfo argument to a datetime constructor. is_dst is used to determine the correct timezone in the ambigous period at the end of daylight saving time. >>> from pytz import timezone >>> fmt = '%Y-%m-%d %H:%M:%S %Z (%z)' >>> amdam = timezone('Europe/Amsterdam') >>> dt = datetime(2004, 10, 31, 2, 0, 0) >>> loc_dt1 = amdam.localize(dt, is_dst=True) >>> loc_dt2 = amdam.localize(dt, is_dst=False) >>> loc_dt1.strftime(fmt) '2004-10-31 02:00:00 CEST (+0200)' >>> loc_dt2.strftime(fmt) '2004-10-31 02:00:00 CET (+0100)' >>> str(loc_dt2 - loc_dt1) '1:00:00' Use is_dst=None to raise an AmbiguousTimeError for ambiguous times at the end of daylight saving time >>> try: ... loc_dt1 = amdam.localize(dt, is_dst=None) ... except AmbiguousTimeError: ... print('Ambiguous') Ambiguous is_dst defaults to False >>> amdam.localize(dt) == amdam.localize(dt, False) True is_dst is also used to determine the correct timezone in the wallclock times jumped over at the start of daylight saving time. >>> pacific = timezone('US/Pacific') >>> dt = datetime(2008, 3, 9, 2, 0, 0) >>> ploc_dt1 = pacific.localize(dt, is_dst=True) >>> ploc_dt2 = pacific.localize(dt, is_dst=False) >>> ploc_dt1.strftime(fmt) '2008-03-09 02:00:00 PDT (-0700)' >>> ploc_dt2.strftime(fmt) '2008-03-09 02:00:00 PST (-0800)' >>> str(ploc_dt2 - ploc_dt1) '1:00:00' Use is_dst=None to raise a NonExistentTimeError for these skipped times. >>> try: ... loc_dt1 = pacific.localize(dt, is_dst=None) ... except NonExistentTimeError: ... print('Non-existent') Non-existent ''' if dt.tzinfo is not None: raise ValueError('Not naive datetime (tzinfo is already set)') # Find the two best possibilities. possible_loc_dt = set() for delta in [timedelta(days=-1), timedelta(days=1)]: loc_dt = dt + delta idx = max(0, bisect_right( self._utc_transition_times, loc_dt) - 1) inf = self._transition_info[idx] tzinfo = self._tzinfos[inf] loc_dt = tzinfo.normalize(dt.replace(tzinfo=tzinfo)) if loc_dt.replace(tzinfo=None) == dt: possible_loc_dt.add(loc_dt) if len(possible_loc_dt) == 1: return possible_loc_dt.pop() # If there are no possibly correct timezones, we are attempting # to convert a time that never happened - the time period jumped # during the start-of-DST transition period. if len(possible_loc_dt) == 0: # If we refuse to guess, raise an exception. if is_dst is None: raise NonExistentTimeError(dt) # If we are forcing the pre-DST side of the DST transition, we # obtain the correct timezone by winding the clock forward a few # hours. elif is_dst: return self.localize( dt + timedelta(hours=6), is_dst=True) - timedelta(hours=6) # If we are forcing the post-DST side of the DST transition, we # obtain the correct timezone by winding the clock back. else: return self.localize( dt - timedelta(hours=6), is_dst=False) + timedelta(hours=6) # If we get this far, we have multiple possible timezones - this # is an ambiguous case occuring during the end-of-DST transition. # If told to be strict, raise an exception since we have an # ambiguous case if is_dst is None: raise AmbiguousTimeError(dt) # Filter out the possiblilities that don't match the requested # is_dst filtered_possible_loc_dt = [ p for p in possible_loc_dt if bool(p.tzinfo._dst) == is_dst ] # Hopefully we only have one possibility left. Return it. if len(filtered_possible_loc_dt) == 1: return filtered_possible_loc_dt[0] if len(filtered_possible_loc_dt) == 0: filtered_possible_loc_dt = list(possible_loc_dt) # If we get this far, we have in a wierd timezone transition # where the clocks have been wound back but is_dst is the same # in both (eg. Europe/Warsaw 1915 when they switched to CET). # At this point, we just have to guess unless we allow more # hints to be passed in (such as the UTC offset or abbreviation), # but that is just getting silly. # # Choose the earliest (by UTC) applicable timezone if is_dst=True # Choose the latest (by UTC) applicable timezone if is_dst=False # i.e., behave like end-of-DST transition dates = {} # utc -> local for local_dt in filtered_possible_loc_dt: utc_time = ( local_dt.replace(tzinfo=None) - local_dt.tzinfo._utcoffset) assert utc_time not in dates dates[utc_time] = local_dt return dates[[min, max][not is_dst](dates)]
[ "def", "localize", "(", "self", ",", "dt", ",", "is_dst", "=", "False", ")", ":", "if", "dt", ".", "tzinfo", "is", "not", "None", ":", "raise", "ValueError", "(", "'Not naive datetime (tzinfo is already set)'", ")", "# Find the two best possibilities.", "possible_loc_dt", "=", "set", "(", ")", "for", "delta", "in", "[", "timedelta", "(", "days", "=", "-", "1", ")", ",", "timedelta", "(", "days", "=", "1", ")", "]", ":", "loc_dt", "=", "dt", "+", "delta", "idx", "=", "max", "(", "0", ",", "bisect_right", "(", "self", ".", "_utc_transition_times", ",", "loc_dt", ")", "-", "1", ")", "inf", "=", "self", ".", "_transition_info", "[", "idx", "]", "tzinfo", "=", "self", ".", "_tzinfos", "[", "inf", "]", "loc_dt", "=", "tzinfo", ".", "normalize", "(", "dt", ".", "replace", "(", "tzinfo", "=", "tzinfo", ")", ")", "if", "loc_dt", ".", "replace", "(", "tzinfo", "=", "None", ")", "==", "dt", ":", "possible_loc_dt", ".", "add", "(", "loc_dt", ")", "if", "len", "(", "possible_loc_dt", ")", "==", "1", ":", "return", "possible_loc_dt", ".", "pop", "(", ")", "# If there are no possibly correct timezones, we are attempting", "# to convert a time that never happened - the time period jumped", "# during the start-of-DST transition period.", "if", "len", "(", "possible_loc_dt", ")", "==", "0", ":", "# If we refuse to guess, raise an exception.", "if", "is_dst", "is", "None", ":", "raise", "NonExistentTimeError", "(", "dt", ")", "# If we are forcing the pre-DST side of the DST transition, we", "# obtain the correct timezone by winding the clock forward a few", "# hours.", "elif", "is_dst", ":", "return", "self", ".", "localize", "(", "dt", "+", "timedelta", "(", "hours", "=", "6", ")", ",", "is_dst", "=", "True", ")", "-", "timedelta", "(", "hours", "=", "6", ")", "# If we are forcing the post-DST side of the DST transition, we", "# obtain the correct timezone by winding the clock back.", "else", ":", "return", "self", ".", "localize", "(", "dt", "-", "timedelta", "(", "hours", "=", "6", ")", ",", "is_dst", "=", "False", ")", "+", "timedelta", "(", "hours", "=", "6", ")", "# If we get this far, we have multiple possible timezones - this", "# is an ambiguous case occuring during the end-of-DST transition.", "# If told to be strict, raise an exception since we have an", "# ambiguous case", "if", "is_dst", "is", "None", ":", "raise", "AmbiguousTimeError", "(", "dt", ")", "# Filter out the possiblilities that don't match the requested", "# is_dst", "filtered_possible_loc_dt", "=", "[", "p", "for", "p", "in", "possible_loc_dt", "if", "bool", "(", "p", ".", "tzinfo", ".", "_dst", ")", "==", "is_dst", "]", "# Hopefully we only have one possibility left. Return it.", "if", "len", "(", "filtered_possible_loc_dt", ")", "==", "1", ":", "return", "filtered_possible_loc_dt", "[", "0", "]", "if", "len", "(", "filtered_possible_loc_dt", ")", "==", "0", ":", "filtered_possible_loc_dt", "=", "list", "(", "possible_loc_dt", ")", "# If we get this far, we have in a wierd timezone transition", "# where the clocks have been wound back but is_dst is the same", "# in both (eg. Europe/Warsaw 1915 when they switched to CET).", "# At this point, we just have to guess unless we allow more", "# hints to be passed in (such as the UTC offset or abbreviation),", "# but that is just getting silly.", "#", "# Choose the earliest (by UTC) applicable timezone if is_dst=True", "# Choose the latest (by UTC) applicable timezone if is_dst=False", "# i.e., behave like end-of-DST transition", "dates", "=", "{", "}", "# utc -> local", "for", "local_dt", "in", "filtered_possible_loc_dt", ":", "utc_time", "=", "(", "local_dt", ".", "replace", "(", "tzinfo", "=", "None", ")", "-", "local_dt", ".", "tzinfo", ".", "_utcoffset", ")", "assert", "utc_time", "not", "in", "dates", "dates", "[", "utc_time", "]", "=", "local_dt", "return", "dates", "[", "[", "min", ",", "max", "]", "[", "not", "is_dst", "]", "(", "dates", ")", "]" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pytz/pytz/tzinfo.py#L258-L394
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/grid.py
python
GridCellBoolEditor_UseStringValues
(*args, **kwargs)
return _grid.GridCellBoolEditor_UseStringValues(*args, **kwargs)
GridCellBoolEditor_UseStringValues(String valueTrue=OneString, String valueFalse=EmptyString)
GridCellBoolEditor_UseStringValues(String valueTrue=OneString, String valueFalse=EmptyString)
[ "GridCellBoolEditor_UseStringValues", "(", "String", "valueTrue", "=", "OneString", "String", "valueFalse", "=", "EmptyString", ")" ]
def GridCellBoolEditor_UseStringValues(*args, **kwargs): """GridCellBoolEditor_UseStringValues(String valueTrue=OneString, String valueFalse=EmptyString)""" return _grid.GridCellBoolEditor_UseStringValues(*args, **kwargs)
[ "def", "GridCellBoolEditor_UseStringValues", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_grid", ".", "GridCellBoolEditor_UseStringValues", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/grid.py#L473-L475
Komnomnomnom/swigibpy
cfd307fdbfaffabc69a2dc037538d7e34a8b8daf
swigibpy.py
python
ComboLegList.__nonzero__
(self)
return _swigibpy.ComboLegList___nonzero__(self)
__nonzero__(ComboLegList self) -> bool
__nonzero__(ComboLegList self) -> bool
[ "__nonzero__", "(", "ComboLegList", "self", ")", "-", ">", "bool" ]
def __nonzero__(self): """__nonzero__(ComboLegList self) -> bool""" return _swigibpy.ComboLegList___nonzero__(self)
[ "def", "__nonzero__", "(", "self", ")", ":", "return", "_swigibpy", ".", "ComboLegList___nonzero__", "(", "self", ")" ]
https://github.com/Komnomnomnom/swigibpy/blob/cfd307fdbfaffabc69a2dc037538d7e34a8b8daf/swigibpy.py#L251-L253
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/queue.py
python
Queue.get_nowait
(self)
return self.get(block=False)
Remove and return an item from the queue without blocking. Only get an item if one is immediately available. Otherwise raise the Empty exception.
Remove and return an item from the queue without blocking.
[ "Remove", "and", "return", "an", "item", "from", "the", "queue", "without", "blocking", "." ]
def get_nowait(self): '''Remove and return an item from the queue without blocking. Only get an item if one is immediately available. Otherwise raise the Empty exception. ''' return self.get(block=False)
[ "def", "get_nowait", "(", "self", ")", ":", "return", "self", ".", "get", "(", "block", "=", "False", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/queue.py#L192-L198
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py3/pandas/io/formats/info.py
python
DataFrameTableBuilderVerbose.headers
(self)
return [" # ", "Column", "Dtype"]
Headers names of the columns in verbose table.
Headers names of the columns in verbose table.
[ "Headers", "names", "of", "the", "columns", "in", "verbose", "table", "." ]
def headers(self) -> Sequence[str]: """Headers names of the columns in verbose table.""" if self.with_counts: return [" # ", "Column", "Non-Null Count", "Dtype"] return [" # ", "Column", "Dtype"]
[ "def", "headers", "(", "self", ")", "->", "Sequence", "[", "str", "]", ":", "if", "self", ".", "with_counts", ":", "return", "[", "\" # \"", ",", "\"Column\"", ",", "\"Non-Null Count\"", ",", "\"Dtype\"", "]", "return", "[", "\" # \"", ",", "\"Column\"", ",", "\"Dtype\"", "]" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/io/formats/info.py#L650-L654
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py3/sklearn/impute/_knn.py
python
KNNImputer._calc_impute
(self, dist_pot_donors, n_neighbors, fit_X_col, mask_fit_X_col)
return np.ma.average(donors, axis=1, weights=weight_matrix).data
Helper function to impute a single column. Parameters ---------- dist_pot_donors : ndarray of shape (n_receivers, n_potential_donors) Distance matrix between the receivers and potential donors from training set. There must be at least one non-nan distance between a receiver and a potential donor. n_neighbors : int Number of neighbors to consider. fit_X_col : ndarray of shape (n_potential_donors,) Column of potential donors from training set. mask_fit_X_col : ndarray of shape (n_potential_donors,) Missing mask for fit_X_col. Returns ------- imputed_values: ndarray of shape (n_receivers,) Imputed values for receiver.
Helper function to impute a single column.
[ "Helper", "function", "to", "impute", "a", "single", "column", "." ]
def _calc_impute(self, dist_pot_donors, n_neighbors, fit_X_col, mask_fit_X_col): """Helper function to impute a single column. Parameters ---------- dist_pot_donors : ndarray of shape (n_receivers, n_potential_donors) Distance matrix between the receivers and potential donors from training set. There must be at least one non-nan distance between a receiver and a potential donor. n_neighbors : int Number of neighbors to consider. fit_X_col : ndarray of shape (n_potential_donors,) Column of potential donors from training set. mask_fit_X_col : ndarray of shape (n_potential_donors,) Missing mask for fit_X_col. Returns ------- imputed_values: ndarray of shape (n_receivers,) Imputed values for receiver. """ # Get donors donors_idx = np.argpartition(dist_pot_donors, n_neighbors - 1, axis=1)[:, :n_neighbors] # Get weight matrix from from distance matrix donors_dist = dist_pot_donors[ np.arange(donors_idx.shape[0])[:, None], donors_idx] weight_matrix = _get_weights(donors_dist, self.weights) # fill nans with zeros if weight_matrix is not None: weight_matrix[np.isnan(weight_matrix)] = 0.0 # Retrieve donor values and calculate kNN average donors = fit_X_col.take(donors_idx) donors_mask = mask_fit_X_col.take(donors_idx) donors = np.ma.array(donors, mask=donors_mask) return np.ma.average(donors, axis=1, weights=weight_matrix).data
[ "def", "_calc_impute", "(", "self", ",", "dist_pot_donors", ",", "n_neighbors", ",", "fit_X_col", ",", "mask_fit_X_col", ")", ":", "# Get donors", "donors_idx", "=", "np", ".", "argpartition", "(", "dist_pot_donors", ",", "n_neighbors", "-", "1", ",", "axis", "=", "1", ")", "[", ":", ",", ":", "n_neighbors", "]", "# Get weight matrix from from distance matrix", "donors_dist", "=", "dist_pot_donors", "[", "np", ".", "arange", "(", "donors_idx", ".", "shape", "[", "0", "]", ")", "[", ":", ",", "None", "]", ",", "donors_idx", "]", "weight_matrix", "=", "_get_weights", "(", "donors_dist", ",", "self", ".", "weights", ")", "# fill nans with zeros", "if", "weight_matrix", "is", "not", "None", ":", "weight_matrix", "[", "np", ".", "isnan", "(", "weight_matrix", ")", "]", "=", "0.0", "# Retrieve donor values and calculate kNN average", "donors", "=", "fit_X_col", ".", "take", "(", "donors_idx", ")", "donors_mask", "=", "mask_fit_X_col", ".", "take", "(", "donors_idx", ")", "donors", "=", "np", ".", "ma", ".", "array", "(", "donors", ",", "mask", "=", "donors_mask", ")", "return", "np", ".", "ma", ".", "average", "(", "donors", ",", "axis", "=", "1", ",", "weights", "=", "weight_matrix", ")", ".", "data" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/impute/_knn.py#L110-L154
SoarGroup/Soar
a1c5e249499137a27da60533c72969eef3b8ab6b
scons/scons-local-4.1.0/SCons/Action.py
python
_object_contents
(obj)
Return the signature contents of any Python object. We have to handle the case where object contains a code object since it can be pickled directly.
Return the signature contents of any Python object.
[ "Return", "the", "signature", "contents", "of", "any", "Python", "object", "." ]
def _object_contents(obj): """Return the signature contents of any Python object. We have to handle the case where object contains a code object since it can be pickled directly. """ try: # Test if obj is a method. return _function_contents(obj.__func__) except AttributeError: try: # Test if obj is a callable object. return _function_contents(obj.__call__.__func__) except AttributeError: try: # Test if obj is a code object. return _code_contents(obj) except AttributeError: try: # Test if obj is a function object. return _function_contents(obj) except AttributeError as ae: # Should be a pickle-able Python object. try: return _object_instance_content(obj) # pickling an Action instance or object doesn't yield a stable # content as instance property may be dumped in different orders # return pickle.dumps(obj, ACTION_SIGNATURE_PICKLE_PROTOCOL) except (pickle.PicklingError, TypeError, AttributeError) as ex: # This is weird, but it seems that nested classes # are unpickable. The Python docs say it should # always be a PicklingError, but some Python # versions seem to return TypeError. Just do # the best we can. return bytearray(repr(obj), 'utf-8')
[ "def", "_object_contents", "(", "obj", ")", ":", "try", ":", "# Test if obj is a method.", "return", "_function_contents", "(", "obj", ".", "__func__", ")", "except", "AttributeError", ":", "try", ":", "# Test if obj is a callable object.", "return", "_function_contents", "(", "obj", ".", "__call__", ".", "__func__", ")", "except", "AttributeError", ":", "try", ":", "# Test if obj is a code object.", "return", "_code_contents", "(", "obj", ")", "except", "AttributeError", ":", "try", ":", "# Test if obj is a function object.", "return", "_function_contents", "(", "obj", ")", "except", "AttributeError", "as", "ae", ":", "# Should be a pickle-able Python object.", "try", ":", "return", "_object_instance_content", "(", "obj", ")", "# pickling an Action instance or object doesn't yield a stable", "# content as instance property may be dumped in different orders", "# return pickle.dumps(obj, ACTION_SIGNATURE_PICKLE_PROTOCOL)", "except", "(", "pickle", ".", "PicklingError", ",", "TypeError", ",", "AttributeError", ")", "as", "ex", ":", "# This is weird, but it seems that nested classes", "# are unpickable. The Python docs say it should", "# always be a PicklingError, but some Python", "# versions seem to return TypeError. Just do", "# the best we can.", "return", "bytearray", "(", "repr", "(", "obj", ")", ",", "'utf-8'", ")" ]
https://github.com/SoarGroup/Soar/blob/a1c5e249499137a27da60533c72969eef3b8ab6b/scons/scons-local-4.1.0/SCons/Action.py#L173-L211
ideawu/ssdb
f229ba277c7f7d0ca5a441c0c6fb3d1209af68e4
deps/cpy/antlr3/tree.py
python
TreeAdaptor.errorNode
(self, input, start, stop, exc)
Return a tree node representing an error. This node records the tokens consumed during error recovery. The start token indicates the input symbol at which the error was detected. The stop token indicates the last symbol consumed during recovery. You must specify the input stream so that the erroneous text can be packaged up in the error node. The exception could be useful to some applications; default implementation stores ptr to it in the CommonErrorNode. This only makes sense during token parsing, not tree parsing. Tree parsing should happen only when parsing and tree construction succeed.
Return a tree node representing an error. This node records the tokens consumed during error recovery. The start token indicates the input symbol at which the error was detected. The stop token indicates the last symbol consumed during recovery.
[ "Return", "a", "tree", "node", "representing", "an", "error", ".", "This", "node", "records", "the", "tokens", "consumed", "during", "error", "recovery", ".", "The", "start", "token", "indicates", "the", "input", "symbol", "at", "which", "the", "error", "was", "detected", ".", "The", "stop", "token", "indicates", "the", "last", "symbol", "consumed", "during", "recovery", "." ]
def errorNode(self, input, start, stop, exc): """ Return a tree node representing an error. This node records the tokens consumed during error recovery. The start token indicates the input symbol at which the error was detected. The stop token indicates the last symbol consumed during recovery. You must specify the input stream so that the erroneous text can be packaged up in the error node. The exception could be useful to some applications; default implementation stores ptr to it in the CommonErrorNode. This only makes sense during token parsing, not tree parsing. Tree parsing should happen only when parsing and tree construction succeed. """ raise NotImplementedError
[ "def", "errorNode", "(", "self", ",", "input", ",", "start", ",", "stop", ",", "exc", ")", ":", "raise", "NotImplementedError" ]
https://github.com/ideawu/ssdb/blob/f229ba277c7f7d0ca5a441c0c6fb3d1209af68e4/deps/cpy/antlr3/tree.py#L300-L317
apiaryio/snowcrash
b5b39faa85f88ee17459edf39fdc6fe4fc70d2e3
tools/gyp/pylib/gyp/msvs_emulation.py
python
MsvsSettings._ConfigAttrib
(self, path, config, default=None, prefix='', append=None, map=None)
return self._GetAndMunge( self.msvs_configuration_attributes[config], path, default, prefix, append, map)
_GetAndMunge for msvs_configuration_attributes.
_GetAndMunge for msvs_configuration_attributes.
[ "_GetAndMunge", "for", "msvs_configuration_attributes", "." ]
def _ConfigAttrib(self, path, config, default=None, prefix='', append=None, map=None): """_GetAndMunge for msvs_configuration_attributes.""" return self._GetAndMunge( self.msvs_configuration_attributes[config], path, default, prefix, append, map)
[ "def", "_ConfigAttrib", "(", "self", ",", "path", ",", "config", ",", "default", "=", "None", ",", "prefix", "=", "''", ",", "append", "=", "None", ",", "map", "=", "None", ")", ":", "return", "self", ".", "_GetAndMunge", "(", "self", ".", "msvs_configuration_attributes", "[", "config", "]", ",", "path", ",", "default", ",", "prefix", ",", "append", ",", "map", ")" ]
https://github.com/apiaryio/snowcrash/blob/b5b39faa85f88ee17459edf39fdc6fe4fc70d2e3/tools/gyp/pylib/gyp/msvs_emulation.py#L325-L330
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/contrib/cudnn_rnn/python/ops/cudnn_rnn_ops.py
python
_get_num_params
(rnn_mode, num_layers, direction)
return num_params
Return num params for given Cudnn config.
Return num params for given Cudnn config.
[ "Return", "num", "params", "for", "given", "Cudnn", "config", "." ]
def _get_num_params(rnn_mode, num_layers, direction): """Return num params for given Cudnn config.""" if rnn_mode == CUDNN_LSTM: num_params_per_layer = CUDNN_LSTM_PARAMS_PER_LAYER elif rnn_mode == CUDNN_GRU: num_params_per_layer = CUDNN_GRU_PARAMS_PER_LAYER elif rnn_mode == CUDNN_RNN_RELU: num_params_per_layer = CUDNN_RNN_RELU_PARAMS_PER_LAYER elif rnn_mode == CUDNN_RNN_TANH: num_params_per_layer = CUDNN_RNN_TANH_PARAMS_PER_LAYER else: raise ValueError("Invalid \'rnn_mode\': %s", rnn_mode) num_params = num_layers * num_params_per_layer if direction != CUDNN_RNN_UNIDIRECTION: num_params *= 2 return num_params
[ "def", "_get_num_params", "(", "rnn_mode", ",", "num_layers", ",", "direction", ")", ":", "if", "rnn_mode", "==", "CUDNN_LSTM", ":", "num_params_per_layer", "=", "CUDNN_LSTM_PARAMS_PER_LAYER", "elif", "rnn_mode", "==", "CUDNN_GRU", ":", "num_params_per_layer", "=", "CUDNN_GRU_PARAMS_PER_LAYER", "elif", "rnn_mode", "==", "CUDNN_RNN_RELU", ":", "num_params_per_layer", "=", "CUDNN_RNN_RELU_PARAMS_PER_LAYER", "elif", "rnn_mode", "==", "CUDNN_RNN_TANH", ":", "num_params_per_layer", "=", "CUDNN_RNN_TANH_PARAMS_PER_LAYER", "else", ":", "raise", "ValueError", "(", "\"Invalid \\'rnn_mode\\': %s\"", ",", "rnn_mode", ")", "num_params", "=", "num_layers", "*", "num_params_per_layer", "if", "direction", "!=", "CUDNN_RNN_UNIDIRECTION", ":", "num_params", "*=", "2", "return", "num_params" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/cudnn_rnn/python/ops/cudnn_rnn_ops.py#L749-L764
giuspen/cherrytree
84712f206478fcf9acf30174009ad28c648c6344
pygtk2/modules/imports.py
python
KeepnoteHandler.get_cherrytree_xml
(self)
return self.dom.toxml()
Returns a CherryTree string Containing the KeepNote Nodes
Returns a CherryTree string Containing the KeepNote Nodes
[ "Returns", "a", "CherryTree", "string", "Containing", "the", "KeepNote", "Nodes" ]
def get_cherrytree_xml(self): """Returns a CherryTree string Containing the KeepNote Nodes""" self.dom = xml.dom.minidom.Document() self.nodes_list = [self.dom.createElement(cons.APP_NAME)] self.dom.appendChild(self.nodes_list[0]) self.curr_attributes = {} self.start_parsing() return self.dom.toxml()
[ "def", "get_cherrytree_xml", "(", "self", ")", ":", "self", ".", "dom", "=", "xml", ".", "dom", ".", "minidom", ".", "Document", "(", ")", "self", ".", "nodes_list", "=", "[", "self", ".", "dom", ".", "createElement", "(", "cons", ".", "APP_NAME", ")", "]", "self", ".", "dom", ".", "appendChild", "(", "self", ".", "nodes_list", "[", "0", "]", ")", "self", ".", "curr_attributes", "=", "{", "}", "self", ".", "start_parsing", "(", ")", "return", "self", ".", "dom", ".", "toxml", "(", ")" ]
https://github.com/giuspen/cherrytree/blob/84712f206478fcf9acf30174009ad28c648c6344/pygtk2/modules/imports.py#L489-L496
netket/netket
0d534e54ecbf25b677ea72af6b85947979420652
netket/jax/utils.py
python
is_complex_dtype
(typ)
return jnp.issubdtype(typ, jnp.complexfloating)
Returns True if typ is a complex dtype
Returns True if typ is a complex dtype
[ "Returns", "True", "if", "typ", "is", "a", "complex", "dtype" ]
def is_complex_dtype(typ): """ Returns True if typ is a complex dtype """ return jnp.issubdtype(typ, jnp.complexfloating)
[ "def", "is_complex_dtype", "(", "typ", ")", ":", "return", "jnp", ".", "issubdtype", "(", "typ", ",", "jnp", ".", "complexfloating", ")" ]
https://github.com/netket/netket/blob/0d534e54ecbf25b677ea72af6b85947979420652/netket/jax/utils.py#L104-L108
Samsung/veles
95ed733c2e49bc011ad98ccf2416ecec23fbf352
veles/__init__.py
python
VelesModule.__loc__
(self)
return result
Calculates of lines of code relies on "cloc" utility.
Calculates of lines of code relies on "cloc" utility.
[ "Calculates", "of", "lines", "of", "code", "relies", "on", "cloc", "utility", "." ]
def __loc__(self): """Calculates of lines of code relies on "cloc" utility. """ if self.__loc is not None: return self.__loc from subprocess import Popen, PIPE result = {} def calc(cond): cmd = ("cd %s && echo $(find %s ! -path '*debian*' " "! -path '*docs*' ! -path '*.pybuild*' " "-exec cloc --quiet --csv {} \; | " "sed -n '1p;0~3p' | tail -n +2 | cut -d ',' -f 5 | " "tr '\n' '+' | head -c -1) | bc") % \ (self.__root__, cond) print(cmd) discovery = Popen(cmd, shell=True, stdout=PIPE) num, _ = discovery.communicate() return int(num) result["core"] = \ calc("-name '*.py' ! -path '*cpplint*' ! -path './deploy/*' " "! -path './web/*' ! -path './veles/external/*' " "! -name create-emitter-tests.py ! -path " "'./veles/tests/*' ! -path './veles/znicz/tests/*'") result["tests"] = calc("'./veles/tests' './veles/znicz/tests' " "-name '*.py'") result["c/c++"] = calc( "\( -name '*.cc' -o -name '*.h' -o -name '*.c' \) ! -path " "'*google*' ! -path '*web*' ! -path '*zlib*' !" " -path '*libarchive*' ! -path '*jsoncpp*' ! -path '*boost*'") result["js"] = calc("-name '*.js' ! -path '*node_modules*' " "! -path '*dist*' ! -path '*libs*' " "! -path '*jquery*' " "! -path '*viz.js*' ! -path '*emscripten*'") result["sass"] = calc("-name '*.scss' ! -path '*node_modules*' " "! -path '*dist*' ! -path '*libs*' " "! -path '*viz.js*' ! -path '*emscripten*'") result["html"] = calc("-name '*.html' ! -path '*node_modules*' " "! -path '*dist*' ! -path '*libs*' " "! -path '*viz.js*' ! -path '*emscripten*'") result["opencl/cuda"] = calc( "\( -name '*.cl' -o -name '*.cu' \) ! -path './web/*'") result["java"] = calc("'./mastodon/lib/src/main' -name '*.java'") result["tests"] += calc("'./mastodon/lib/src/test' -name '*.java'") result["all"] = sum(result.values()) self.__loc = result return result
[ "def", "__loc__", "(", "self", ")", ":", "if", "self", ".", "__loc", "is", "not", "None", ":", "return", "self", ".", "__loc", "from", "subprocess", "import", "Popen", ",", "PIPE", "result", "=", "{", "}", "def", "calc", "(", "cond", ")", ":", "cmd", "=", "(", "\"cd %s && echo $(find %s ! -path '*debian*' \"", "\"! -path '*docs*' ! -path '*.pybuild*' \"", "\"-exec cloc --quiet --csv {} \\; | \"", "\"sed -n '1p;0~3p' | tail -n +2 | cut -d ',' -f 5 | \"", "\"tr '\\n' '+' | head -c -1) | bc\"", ")", "%", "(", "self", ".", "__root__", ",", "cond", ")", "print", "(", "cmd", ")", "discovery", "=", "Popen", "(", "cmd", ",", "shell", "=", "True", ",", "stdout", "=", "PIPE", ")", "num", ",", "_", "=", "discovery", ".", "communicate", "(", ")", "return", "int", "(", "num", ")", "result", "[", "\"core\"", "]", "=", "calc", "(", "\"-name '*.py' ! -path '*cpplint*' ! -path './deploy/*' \"", "\"! -path './web/*' ! -path './veles/external/*' \"", "\"! -name create-emitter-tests.py ! -path \"", "\"'./veles/tests/*' ! -path './veles/znicz/tests/*'\"", ")", "result", "[", "\"tests\"", "]", "=", "calc", "(", "\"'./veles/tests' './veles/znicz/tests' \"", "\"-name '*.py'\"", ")", "result", "[", "\"c/c++\"", "]", "=", "calc", "(", "\"\\( -name '*.cc' -o -name '*.h' -o -name '*.c' \\) ! -path \"", "\"'*google*' ! -path '*web*' ! -path '*zlib*' !\"", "\" -path '*libarchive*' ! -path '*jsoncpp*' ! -path '*boost*'\"", ")", "result", "[", "\"js\"", "]", "=", "calc", "(", "\"-name '*.js' ! -path '*node_modules*' \"", "\"! -path '*dist*' ! -path '*libs*' \"", "\"! -path '*jquery*' \"", "\"! -path '*viz.js*' ! -path '*emscripten*'\"", ")", "result", "[", "\"sass\"", "]", "=", "calc", "(", "\"-name '*.scss' ! -path '*node_modules*' \"", "\"! -path '*dist*' ! -path '*libs*' \"", "\"! -path '*viz.js*' ! -path '*emscripten*'\"", ")", "result", "[", "\"html\"", "]", "=", "calc", "(", "\"-name '*.html' ! -path '*node_modules*' \"", "\"! -path '*dist*' ! -path '*libs*' \"", "\"! -path '*viz.js*' ! -path '*emscripten*'\"", ")", "result", "[", "\"opencl/cuda\"", "]", "=", "calc", "(", "\"\\( -name '*.cl' -o -name '*.cu' \\) ! -path './web/*'\"", ")", "result", "[", "\"java\"", "]", "=", "calc", "(", "\"'./mastodon/lib/src/main' -name '*.java'\"", ")", "result", "[", "\"tests\"", "]", "+=", "calc", "(", "\"'./mastodon/lib/src/test' -name '*.java'\"", ")", "result", "[", "\"all\"", "]", "=", "sum", "(", "result", ".", "values", "(", ")", ")", "self", ".", "__loc", "=", "result", "return", "result" ]
https://github.com/Samsung/veles/blob/95ed733c2e49bc011ad98ccf2416ecec23fbf352/veles/__init__.py#L242-L291
vnpy/vnpy
f50f2535ed39dd33272e0985ed40c7078e4c19f6
vnpy/trader/gateway.py
python
LocalOrderManager.new_local_orderid
(self)
return local_orderid
Generate a new local orderid.
Generate a new local orderid.
[ "Generate", "a", "new", "local", "orderid", "." ]
def new_local_orderid(self) -> str: """ Generate a new local orderid. """ self.order_count += 1 local_orderid = self.order_prefix + str(self.order_count).rjust(8, "0") return local_orderid
[ "def", "new_local_orderid", "(", "self", ")", "->", "str", ":", "self", ".", "order_count", "+=", "1", "local_orderid", "=", "self", ".", "order_prefix", "+", "str", "(", "self", ".", "order_count", ")", ".", "rjust", "(", "8", ",", "\"0\"", ")", "return", "local_orderid" ]
https://github.com/vnpy/vnpy/blob/f50f2535ed39dd33272e0985ed40c7078e4c19f6/vnpy/trader/gateway.py#L309-L315
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/io/stata.py
python
StataReader.__enter__
(self)
return self
enter context manager
enter context manager
[ "enter", "context", "manager" ]
def __enter__(self): """ enter context manager """ return self
[ "def", "__enter__", "(", "self", ")", ":", "return", "self" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/io/stata.py#L1059-L1061
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_misc.py
python
TimeSpan.__ge__
(*args, **kwargs)
return _misc_.TimeSpan___ge__(*args, **kwargs)
__ge__(self, TimeSpan other) -> bool
__ge__(self, TimeSpan other) -> bool
[ "__ge__", "(", "self", "TimeSpan", "other", ")", "-", ">", "bool" ]
def __ge__(*args, **kwargs): """__ge__(self, TimeSpan other) -> bool""" return _misc_.TimeSpan___ge__(*args, **kwargs)
[ "def", "__ge__", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_misc_", ".", "TimeSpan___ge__", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_misc.py#L4478-L4480
OpenChemistry/tomviz
0a903679318f191cb7dd3eb5ff5bc3a7d3320d9a
tomviz/python/BinTiltSeriesByTwo.py
python
transform
(dataset)
Downsample tilt images by a factor of 2
Downsample tilt images by a factor of 2
[ "Downsample", "tilt", "images", "by", "a", "factor", "of", "2" ]
def transform(dataset): """Downsample tilt images by a factor of 2""" from tomviz import utils import scipy.ndimage import numpy as np import warnings array = dataset.active_scalars zoom = (0.5, 0.5, 1) result_shape = utils.zoom_shape(array, zoom) result = np.empty(result_shape, array.dtype, order='F') # Downsample the dataset x2 using order 1 spline (linear) warnings.filterwarnings('ignore', '.*output shape of zoom.*') scipy.ndimage.interpolation.zoom(array, zoom, output=result, order=1, mode='constant', cval=0.0, prefilter=False) # Set the result as the new scalars. dataset.active_scalars = result
[ "def", "transform", "(", "dataset", ")", ":", "from", "tomviz", "import", "utils", "import", "scipy", ".", "ndimage", "import", "numpy", "as", "np", "import", "warnings", "array", "=", "dataset", ".", "active_scalars", "zoom", "=", "(", "0.5", ",", "0.5", ",", "1", ")", "result_shape", "=", "utils", ".", "zoom_shape", "(", "array", ",", "zoom", ")", "result", "=", "np", ".", "empty", "(", "result_shape", ",", "array", ".", "dtype", ",", "order", "=", "'F'", ")", "# Downsample the dataset x2 using order 1 spline (linear)", "warnings", ".", "filterwarnings", "(", "'ignore'", ",", "'.*output shape of zoom.*'", ")", "scipy", ".", "ndimage", ".", "interpolation", ".", "zoom", "(", "array", ",", "zoom", ",", "output", "=", "result", ",", "order", "=", "1", ",", "mode", "=", "'constant'", ",", "cval", "=", "0.0", ",", "prefilter", "=", "False", ")", "# Set the result as the new scalars.", "dataset", ".", "active_scalars", "=", "result" ]
https://github.com/OpenChemistry/tomviz/blob/0a903679318f191cb7dd3eb5ff5bc3a7d3320d9a/tomviz/python/BinTiltSeriesByTwo.py#L1-L23
apache/qpid-proton
6bcdfebb55ea3554bc29b1901422532db331a591
python/proton/_handlers.py
python
MessagingHandler.on_connection_closing
(self, event: Event)
Called when the peer initiates the closing of the connection. :param event: The underlying event object. Use this to obtain further information on the event.
Called when the peer initiates the closing of the connection.
[ "Called", "when", "the", "peer", "initiates", "the", "closing", "of", "the", "connection", "." ]
def on_connection_closing(self, event: Event) -> None: """ Called when the peer initiates the closing of the connection. :param event: The underlying event object. Use this to obtain further information on the event. """ pass
[ "def", "on_connection_closing", "(", "self", ",", "event", ":", "Event", ")", "->", "None", ":", "pass" ]
https://github.com/apache/qpid-proton/blob/6bcdfebb55ea3554bc29b1901422532db331a591/python/proton/_handlers.py#L789-L796
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/base64.py
python
b16encode
(s)
return binascii.hexlify(s).upper()
Encode a string using Base16. s is the string to encode. The encoded string is returned.
Encode a string using Base16.
[ "Encode", "a", "string", "using", "Base16", "." ]
def b16encode(s): """Encode a string using Base16. s is the string to encode. The encoded string is returned. """ return binascii.hexlify(s).upper()
[ "def", "b16encode", "(", "s", ")", ":", "return", "binascii", ".", "hexlify", "(", "s", ")", ".", "upper", "(", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/base64.py#L251-L256
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/propgrid.py
python
PropertyGridManager.InsertPage
(*args, **kwargs)
return _propgrid.PropertyGridManager_InsertPage(*args, **kwargs)
InsertPage(self, int index, String label, Bitmap bmp=wxNullBitmap, PropertyGridPage pageObj=None) -> PropertyGridPage
InsertPage(self, int index, String label, Bitmap bmp=wxNullBitmap, PropertyGridPage pageObj=None) -> PropertyGridPage
[ "InsertPage", "(", "self", "int", "index", "String", "label", "Bitmap", "bmp", "=", "wxNullBitmap", "PropertyGridPage", "pageObj", "=", "None", ")", "-", ">", "PropertyGridPage" ]
def InsertPage(*args, **kwargs): """InsertPage(self, int index, String label, Bitmap bmp=wxNullBitmap, PropertyGridPage pageObj=None) -> PropertyGridPage""" return _propgrid.PropertyGridManager_InsertPage(*args, **kwargs)
[ "def", "InsertPage", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_propgrid", ".", "PropertyGridManager_InsertPage", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/propgrid.py#L3524-L3526
hughperkins/tf-coriander
970d3df6c11400ad68405f22b0c42a52374e94ca
tensorflow/models/embedding/word2vec.py
python
Word2Vec.optimize
(self, loss)
Build the graph to optimize the loss function.
Build the graph to optimize the loss function.
[ "Build", "the", "graph", "to", "optimize", "the", "loss", "function", "." ]
def optimize(self, loss): """Build the graph to optimize the loss function.""" # Optimizer nodes. # Linear learning rate decay. opts = self._options words_to_train = float(opts.words_per_epoch * opts.epochs_to_train) lr = opts.learning_rate * tf.maximum( 0.0001, 1.0 - tf.cast(self._words, tf.float32) / words_to_train) self._lr = lr optimizer = tf.train.GradientDescentOptimizer(lr) train = optimizer.minimize(loss, global_step=self.global_step, gate_gradients=optimizer.GATE_NONE) self._train = train
[ "def", "optimize", "(", "self", ",", "loss", ")", ":", "# Optimizer nodes.", "# Linear learning rate decay.", "opts", "=", "self", ".", "_options", "words_to_train", "=", "float", "(", "opts", ".", "words_per_epoch", "*", "opts", ".", "epochs_to_train", ")", "lr", "=", "opts", ".", "learning_rate", "*", "tf", ".", "maximum", "(", "0.0001", ",", "1.0", "-", "tf", ".", "cast", "(", "self", ".", "_words", ",", "tf", ".", "float32", ")", "/", "words_to_train", ")", "self", ".", "_lr", "=", "lr", "optimizer", "=", "tf", ".", "train", ".", "GradientDescentOptimizer", "(", "lr", ")", "train", "=", "optimizer", ".", "minimize", "(", "loss", ",", "global_step", "=", "self", ".", "global_step", ",", "gate_gradients", "=", "optimizer", ".", "GATE_NONE", ")", "self", ".", "_train", "=", "train" ]
https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/models/embedding/word2vec.py#L274-L288
nasa/meshNetwork
ff4bd66e0ca6bd424fd8897a97252bb3925d8b3c
python/mesh/generic/nodeConfig.py
python
NodeConfig.calculateHash
(self)
return configHash.digest()
Calculates SHA1 hash of the current configuration data.
Calculates SHA1 hash of the current configuration data.
[ "Calculates", "SHA1", "hash", "of", "the", "current", "configuration", "data", "." ]
def calculateHash(self): '''Calculates SHA1 hash of the current configuration data.''' if (self.loadSuccess == False): # Don't calculate hash if configuration not loaded return b'' configHash = hashlib.sha1() # Get all attribute names and sort allAttrsDict = self.__dict__ allAttrNames = list(allAttrsDict.keys()) sortedAttrNames = sorted(allAttrNames) ### Create hash (from global parameters only) # Node configuration parameters nodeParams = ['maxNumNodes', 'gcsPresent', 'gcsNodeId', 'nodeUpdateTimeout', 'FCCommWriteInterval', 'FCCommDevice', 'FCBaudrate', 'cmdInterval', 'logInterval', 'commType', 'parseMsgMax', 'rxBufferSize', 'meshBaudrate', 'uartNumBytesToRead', 'numMeshNetworks', 'meshDevices', 'radios', 'msgParsers'] for param in nodeParams: self.hashElem(configHash, allAttrsDict[param]) # Interface configuration parameters intParams = sorted(list(self.interface.keys())) for param in intParams: self.hashElem(configHash, self.interface[param]) # Comm configuration parameters commParams = sorted(list(self.commConfig.keys())) if ('transmitSlot' in commParams): # remove unique config parameters commParams.remove('transmitSlot') for param in commParams: self.hashElem(configHash, self.commConfig[param]) # Platform specific params self.hashPlatformConfig(configHash) return configHash.digest()
[ "def", "calculateHash", "(", "self", ")", ":", "if", "(", "self", ".", "loadSuccess", "==", "False", ")", ":", "# Don't calculate hash if configuration not loaded", "return", "b''", "configHash", "=", "hashlib", ".", "sha1", "(", ")", "# Get all attribute names and sort", "allAttrsDict", "=", "self", ".", "__dict__", "allAttrNames", "=", "list", "(", "allAttrsDict", ".", "keys", "(", ")", ")", "sortedAttrNames", "=", "sorted", "(", "allAttrNames", ")", "### Create hash (from global parameters only)", "# Node configuration parameters", "nodeParams", "=", "[", "'maxNumNodes'", ",", "'gcsPresent'", ",", "'gcsNodeId'", ",", "'nodeUpdateTimeout'", ",", "'FCCommWriteInterval'", ",", "'FCCommDevice'", ",", "'FCBaudrate'", ",", "'cmdInterval'", ",", "'logInterval'", ",", "'commType'", ",", "'parseMsgMax'", ",", "'rxBufferSize'", ",", "'meshBaudrate'", ",", "'uartNumBytesToRead'", ",", "'numMeshNetworks'", ",", "'meshDevices'", ",", "'radios'", ",", "'msgParsers'", "]", "for", "param", "in", "nodeParams", ":", "self", ".", "hashElem", "(", "configHash", ",", "allAttrsDict", "[", "param", "]", ")", "# Interface configuration parameters ", "intParams", "=", "sorted", "(", "list", "(", "self", ".", "interface", ".", "keys", "(", ")", ")", ")", "for", "param", "in", "intParams", ":", "self", ".", "hashElem", "(", "configHash", ",", "self", ".", "interface", "[", "param", "]", ")", "# Comm configuration parameters", "commParams", "=", "sorted", "(", "list", "(", "self", ".", "commConfig", ".", "keys", "(", ")", ")", ")", "if", "(", "'transmitSlot'", "in", "commParams", ")", ":", "# remove unique config parameters", "commParams", ".", "remove", "(", "'transmitSlot'", ")", "for", "param", "in", "commParams", ":", "self", ".", "hashElem", "(", "configHash", ",", "self", ".", "commConfig", "[", "param", "]", ")", "# Platform specific params", "self", ".", "hashPlatformConfig", "(", "configHash", ")", "return", "configHash", ".", "digest", "(", ")" ]
https://github.com/nasa/meshNetwork/blob/ff4bd66e0ca6bd424fd8897a97252bb3925d8b3c/python/mesh/generic/nodeConfig.py#L206-L240
eclipse/sumo
7132a9b8b6eea734bdec38479026b4d8c4336d03
tools/traci/_vehicle.py
python
VehicleDomain.setChargingStationStop
(self, vehID, stopID, duration=tc.INVALID_DOUBLE_VALUE, until=tc.INVALID_DOUBLE_VALUE, flags=tc.STOP_DEFAULT)
setChargingStationStop(string, string, double, double, integer) -> None Adds or modifies a stop at a chargingStation with the given parameters. The duration and the until attribute are in seconds.
setChargingStationStop(string, string, double, double, integer) -> None
[ "setChargingStationStop", "(", "string", "string", "double", "double", "integer", ")", "-", ">", "None" ]
def setChargingStationStop(self, vehID, stopID, duration=tc.INVALID_DOUBLE_VALUE, until=tc.INVALID_DOUBLE_VALUE, flags=tc.STOP_DEFAULT): """setChargingStationStop(string, string, double, double, integer) -> None Adds or modifies a stop at a chargingStation with the given parameters. The duration and the until attribute are in seconds. """ self.setStop(vehID, stopID, duration=duration, until=until, flags=flags | tc.STOP_CHARGING_STATION)
[ "def", "setChargingStationStop", "(", "self", ",", "vehID", ",", "stopID", ",", "duration", "=", "tc", ".", "INVALID_DOUBLE_VALUE", ",", "until", "=", "tc", ".", "INVALID_DOUBLE_VALUE", ",", "flags", "=", "tc", ".", "STOP_DEFAULT", ")", ":", "self", ".", "setStop", "(", "vehID", ",", "stopID", ",", "duration", "=", "duration", ",", "until", "=", "until", ",", "flags", "=", "flags", "|", "tc", ".", "STOP_CHARGING_STATION", ")" ]
https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/traci/_vehicle.py#L1081-L1088
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/threading.py
python
_Event.set
(self)
Set the internal flag to true. All threads waiting for the flag to become true are awakened. Threads that call wait() once the flag is true will not block at all.
Set the internal flag to true.
[ "Set", "the", "internal", "flag", "to", "true", "." ]
def set(self): """Set the internal flag to true. All threads waiting for the flag to become true are awakened. Threads that call wait() once the flag is true will not block at all. """ self.__cond.acquire() try: self.__flag = True self.__cond.notify_all() finally: self.__cond.release()
[ "def", "set", "(", "self", ")", ":", "self", ".", "__cond", ".", "acquire", "(", ")", "try", ":", "self", ".", "__flag", "=", "True", "self", ".", "__cond", ".", "notify_all", "(", ")", "finally", ":", "self", ".", "__cond", ".", "release", "(", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/threading.py#L573-L585
epam/Indigo
30e40b4b1eb9bae0207435a26cfcb81ddcc42be1
api/python/indigo/__init__.py
python
IndigoObject.countDataSGroups
(self)
return self.dispatcher._checkResult( Indigo._lib.indigoCountDataSGroups(self.id) )
Molecule method returns the number of data s-groups Returns: int: number of s-groups
Molecule method returns the number of data s-groups
[ "Molecule", "method", "returns", "the", "number", "of", "data", "s", "-", "groups" ]
def countDataSGroups(self): """Molecule method returns the number of data s-groups Returns: int: number of s-groups """ self.dispatcher._setSessionId() return self.dispatcher._checkResult( Indigo._lib.indigoCountDataSGroups(self.id) )
[ "def", "countDataSGroups", "(", "self", ")", ":", "self", ".", "dispatcher", ".", "_setSessionId", "(", ")", "return", "self", ".", "dispatcher", ".", "_checkResult", "(", "Indigo", ".", "_lib", ".", "indigoCountDataSGroups", "(", "self", ".", "id", ")", ")" ]
https://github.com/epam/Indigo/blob/30e40b4b1eb9bae0207435a26cfcb81ddcc42be1/api/python/indigo/__init__.py#L1316-L1325
cms-sw/cmssw
fd9de012d503d3405420bcbeec0ec879baa57cf2
PhysicsTools/PythonAnalysis/python/rootplot/utilities.py
python
Hist.min
(self, threshold=None)
Return the y-value of the bottom tip of the lowest errorbar.
Return the y-value of the bottom tip of the lowest errorbar.
[ "Return", "the", "y", "-", "value", "of", "the", "bottom", "tip", "of", "the", "lowest", "errorbar", "." ]
def min(self, threshold=None): """Return the y-value of the bottom tip of the lowest errorbar.""" vals = [(yval - yerr) for yval, yerr in zip(self.y, self.yerr[0]) if (yval - yerr) > threshold] if vals: return min(vals) else: return threshold
[ "def", "min", "(", "self", ",", "threshold", "=", "None", ")", ":", "vals", "=", "[", "(", "yval", "-", "yerr", ")", "for", "yval", ",", "yerr", "in", "zip", "(", "self", ".", "y", ",", "self", ".", "yerr", "[", "0", "]", ")", "if", "(", "yval", "-", "yerr", ")", ">", "threshold", "]", "if", "vals", ":", "return", "min", "(", "vals", ")", "else", ":", "return", "threshold" ]
https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/PhysicsTools/PythonAnalysis/python/rootplot/utilities.py#L198-L205
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/html.py
python
HtmlHelpController.KeywordSearch
(*args, **kwargs)
return _html.HtmlHelpController_KeywordSearch(*args, **kwargs)
KeywordSearch(self, String keyword) -> bool
KeywordSearch(self, String keyword) -> bool
[ "KeywordSearch", "(", "self", "String", "keyword", ")", "-", ">", "bool" ]
def KeywordSearch(*args, **kwargs): """KeywordSearch(self, String keyword) -> bool""" return _html.HtmlHelpController_KeywordSearch(*args, **kwargs)
[ "def", "KeywordSearch", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_html", ".", "HtmlHelpController_KeywordSearch", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/html.py#L1986-L1988
zachriggle/ida-splode
a4aee3be415b318a0e051a523ebd0a8d6d5e0026
py/idasplode/database.py
python
DatabaseNames
()
return ValidDBs
Generates a list of database names which are valid for the file currently loaded in IDA
Generates a list of database names which are valid for the file currently loaded in IDA
[ "Generates", "a", "list", "of", "database", "names", "which", "are", "valid", "for", "the", "file", "currently", "loaded", "in", "IDA" ]
def DatabaseNames(): """ Generates a list of database names which are valid for the file currently loaded in IDA """ InputMD5 = ida.GetInputFileMD5() Databases = c.database_names() ValidDBs = [] for Database in Databases: try: if c[Database].modules.find_one({'MD5':InputMD5}): ValidDBs.append(str(Database)) except: pass return ValidDBs
[ "def", "DatabaseNames", "(", ")", ":", "InputMD5", "=", "ida", ".", "GetInputFileMD5", "(", ")", "Databases", "=", "c", ".", "database_names", "(", ")", "ValidDBs", "=", "[", "]", "for", "Database", "in", "Databases", ":", "try", ":", "if", "c", "[", "Database", "]", ".", "modules", ".", "find_one", "(", "{", "'MD5'", ":", "InputMD5", "}", ")", ":", "ValidDBs", ".", "append", "(", "str", "(", "Database", ")", ")", "except", ":", "pass", "return", "ValidDBs" ]
https://github.com/zachriggle/ida-splode/blob/a4aee3be415b318a0e051a523ebd0a8d6d5e0026/py/idasplode/database.py#L43-L59
moflow/moflow
2dfb27c799c90c6caf1477508eca3eec616ef7d2
bap/libtracewrap/libtrace/protobuf/python/google/protobuf/internal/containers.py
python
RepeatedScalarFieldContainer.__getslice__
(self, start, stop)
return self._values[start:stop]
Retrieves the subset of items from between the specified indices.
Retrieves the subset of items from between the specified indices.
[ "Retrieves", "the", "subset", "of", "items", "from", "between", "the", "specified", "indices", "." ]
def __getslice__(self, start, stop): """Retrieves the subset of items from between the specified indices.""" return self._values[start:stop]
[ "def", "__getslice__", "(", "self", ",", "start", ",", "stop", ")", ":", "return", "self", ".", "_values", "[", "start", ":", "stop", "]" ]
https://github.com/moflow/moflow/blob/2dfb27c799c90c6caf1477508eca3eec616ef7d2/bap/libtracewrap/libtrace/protobuf/python/google/protobuf/internal/containers.py#L153-L155
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
tools/grit/grit/node/structure.py
python
StructureNode.GetDataPackPair
(self, lang, encoding)
return id, self.gatherer.GetData(lang, encoding)
Returns a (id, string|None) pair that represents the resource id and raw bytes of the data (or None if no resource is generated). This is used to generate the data pack data file.
Returns a (id, string|None) pair that represents the resource id and raw bytes of the data (or None if no resource is generated). This is used to generate the data pack data file.
[ "Returns", "a", "(", "id", "string|None", ")", "pair", "that", "represents", "the", "resource", "id", "and", "raw", "bytes", "of", "the", "data", "(", "or", "None", "if", "no", "resource", "is", "generated", ")", ".", "This", "is", "used", "to", "generate", "the", "data", "pack", "data", "file", "." ]
def GetDataPackPair(self, lang, encoding): """Returns a (id, string|None) pair that represents the resource id and raw bytes of the data (or None if no resource is generated). This is used to generate the data pack data file. """ from grit.format import rc_header id_map = rc_header.GetIds(self.GetRoot()) id = id_map[self.GetTextualIds()[0]] if self.ExpandVariables(): text = self.gatherer.GetText() return id, util.Encode(self._Substitute(text), encoding) return id, self.gatherer.GetData(lang, encoding)
[ "def", "GetDataPackPair", "(", "self", ",", "lang", ",", "encoding", ")", ":", "from", "grit", ".", "format", "import", "rc_header", "id_map", "=", "rc_header", ".", "GetIds", "(", "self", ".", "GetRoot", "(", ")", ")", "id", "=", "id_map", "[", "self", ".", "GetTextualIds", "(", ")", "[", "0", "]", "]", "if", "self", ".", "ExpandVariables", "(", ")", ":", "text", "=", "self", ".", "gatherer", ".", "GetText", "(", ")", "return", "id", ",", "util", ".", "Encode", "(", "self", ".", "_Substitute", "(", "text", ")", ",", "encoding", ")", "return", "id", ",", "self", ".", "gatherer", ".", "GetData", "(", "lang", ",", "encoding", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/grit/grit/node/structure.py#L198-L209
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/SocketServer.py
python
BaseServer.handle_error
(self, request, client_address)
Handle an error gracefully. May be overridden. The default is to print a traceback and continue.
Handle an error gracefully. May be overridden.
[ "Handle", "an", "error", "gracefully", ".", "May", "be", "overridden", "." ]
def handle_error(self, request, client_address): """Handle an error gracefully. May be overridden. The default is to print a traceback and continue. """ print '-'*40 print 'Exception happened during processing of request from', print client_address import traceback traceback.print_exc() # XXX But this goes to stderr! print '-'*40
[ "def", "handle_error", "(", "self", ",", "request", ",", "client_address", ")", ":", "print", "'-'", "*", "40", "print", "'Exception happened during processing of request from'", ",", "print", "client_address", "import", "traceback", "traceback", ".", "print_exc", "(", ")", "# XXX But this goes to stderr!", "print", "'-'", "*", "40" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/SocketServer.py#L344-L355
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/lib-tk/Tkinter.py
python
Misc.__winfo_parseitem
(self, t)
return t[:1] + tuple(map(self.__winfo_getint, t[1:]))
Internal function.
Internal function.
[ "Internal", "function", "." ]
def __winfo_parseitem(self, t): """Internal function.""" return t[:1] + tuple(map(self.__winfo_getint, t[1:]))
[ "def", "__winfo_parseitem", "(", "self", ",", "t", ")", ":", "return", "t", "[", ":", "1", "]", "+", "tuple", "(", "map", "(", "self", ".", "__winfo_getint", ",", "t", "[", "1", ":", "]", ")", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/lib-tk/Tkinter.py#L985-L987
weichengkuo/DeepBox
c4f8c065b6a51cf296540cc453a44f0519aaacc9
caffe-fast-rcnn/scripts/cpp_lint.py
python
_SetFilters
(filters)
Sets the module's error-message filters. These filters are applied when deciding whether to emit a given error message. Args: filters: A string of comma-separated filters (eg "whitespace/indent"). Each filter should start with + or -; else we die.
Sets the module's error-message filters.
[ "Sets", "the", "module", "s", "error", "-", "message", "filters", "." ]
def _SetFilters(filters): """Sets the module's error-message filters. These filters are applied when deciding whether to emit a given error message. Args: filters: A string of comma-separated filters (eg "whitespace/indent"). Each filter should start with + or -; else we die. """ _cpplint_state.SetFilters(filters)
[ "def", "_SetFilters", "(", "filters", ")", ":", "_cpplint_state", ".", "SetFilters", "(", "filters", ")" ]
https://github.com/weichengkuo/DeepBox/blob/c4f8c065b6a51cf296540cc453a44f0519aaacc9/caffe-fast-rcnn/scripts/cpp_lint.py#L797-L807
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/prompt-toolkit/py2/prompt_toolkit/key_binding/bindings/named_commands.py
python
redraw_current_line
(event)
Refresh the current line. (Readline defines this command, but prompt-toolkit doesn't have it.)
Refresh the current line. (Readline defines this command, but prompt-toolkit doesn't have it.)
[ "Refresh", "the", "current", "line", ".", "(", "Readline", "defines", "this", "command", "but", "prompt", "-", "toolkit", "doesn", "t", "have", "it", ".", ")" ]
def redraw_current_line(event): """ Refresh the current line. (Readline defines this command, but prompt-toolkit doesn't have it.) """ pass
[ "def", "redraw_current_line", "(", "event", ")", ":", "pass" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/prompt-toolkit/py2/prompt_toolkit/key_binding/bindings/named_commands.py#L116-L121
moflow/moflow
2dfb27c799c90c6caf1477508eca3eec616ef7d2
bap/libtracewrap/libtrace/protobuf/python/google/protobuf/internal/cpp_message.py
python
CompositeProperty
(cdescriptor, message_type)
return property(Getter)
Returns a Python property the given composite field.
Returns a Python property the given composite field.
[ "Returns", "a", "Python", "property", "the", "given", "composite", "field", "." ]
def CompositeProperty(cdescriptor, message_type): """Returns a Python property the given composite field.""" def Getter(self): sub_message = self._composite_fields.get(cdescriptor.name, None) if sub_message is None: cmessage = self._cmsg.NewSubMessage(cdescriptor) sub_message = message_type._concrete_class(__cmessage=cmessage) self._composite_fields[cdescriptor.name] = sub_message return sub_message return property(Getter)
[ "def", "CompositeProperty", "(", "cdescriptor", ",", "message_type", ")", ":", "def", "Getter", "(", "self", ")", ":", "sub_message", "=", "self", ".", "_composite_fields", ".", "get", "(", "cdescriptor", ".", "name", ",", "None", ")", "if", "sub_message", "is", "None", ":", "cmessage", "=", "self", ".", "_cmsg", ".", "NewSubMessage", "(", "cdescriptor", ")", "sub_message", "=", "message_type", ".", "_concrete_class", "(", "__cmessage", "=", "cmessage", ")", "self", ".", "_composite_fields", "[", "cdescriptor", ".", "name", "]", "=", "sub_message", "return", "sub_message", "return", "property", "(", "Getter", ")" ]
https://github.com/moflow/moflow/blob/2dfb27c799c90c6caf1477508eca3eec616ef7d2/bap/libtracewrap/libtrace/protobuf/python/google/protobuf/internal/cpp_message.py#L90-L101