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
y123456yz/reading-and-annotate-mongodb-3.6
93280293672ca7586dc24af18132aa61e4ed7fcf
mongo/buildscripts/pylinters.py
python
_get_build_dir
()
return os.path.join(git.get_base_dir(), "build")
Get the location of the scons' build directory in case we need to download clang-format.
Get the location of the scons' build directory in case we need to download clang-format.
[ "Get", "the", "location", "of", "the", "scons", "build", "directory", "in", "case", "we", "need", "to", "download", "clang", "-", "format", "." ]
def _get_build_dir(): # type: () -> str """Get the location of the scons' build directory in case we need to download clang-format.""" return os.path.join(git.get_base_dir(), "build")
[ "def", "_get_build_dir", "(", ")", ":", "# type: () -> str", "return", "os", ".", "path", ".", "join", "(", "git", ".", "get_base_dir", "(", ")", ",", "\"build\"", ")" ]
https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/buildscripts/pylinters.py#L65-L68
ptrkrysik/gr-gsm
2de47e28ce1fb9a518337bfc0add36c8e3cff5eb
python/qa_tch_h_decoder.py
python
qa_tch_h_decoder.test_facch_th
(self)
FACCH/TH test
FACCH/TH test
[ "FACCH", "/", "TH", "test" ]
def test_facch_th (self): """ FACCH/TH test """ b = self.b self.assertEqual(self.facch_test( frames= [259207, 259209, 259211, 259213, 259211, 259213, 259215, 259217], timeslots = [ 6, 6, 6, 6, 6, 6, 6, 6], bursts = [ b[14], b[15], b[16], b[17], b[16], b[17], b[18], b[19]]), ['02 04 01 06 00 00 00 00 00 03 f4 8b 06 00 00 00 03 60 09 03 0f 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b'])
[ "def", "test_facch_th", "(", "self", ")", ":", "b", "=", "self", ".", "b", "self", ".", "assertEqual", "(", "self", ".", "facch_test", "(", "frames", "=", "[", "259207", ",", "259209", ",", "259211", ",", "259213", ",", "259211", ",", "259213", ",", "259215", ",", "259217", "]", ",", "timeslots", "=", "[", "6", ",", "6", ",", "6", ",", "6", ",", "6", ",", "6", ",", "6", ",", "6", "]", ",", "bursts", "=", "[", "b", "[", "14", "]", ",", "b", "[", "15", "]", ",", "b", "[", "16", "]", ",", "b", "[", "17", "]", ",", "b", "[", "16", "]", ",", "b", "[", "17", "]", ",", "b", "[", "18", "]", ",", "b", "[", "19", "]", "]", ")", ",", "[", "'02 04 01 06 00 00 00 00 00 03 f4 8b 06 00 00 00 03 60 09 03 0f 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b 2b'", "]", ")" ]
https://github.com/ptrkrysik/gr-gsm/blob/2de47e28ce1fb9a518337bfc0add36c8e3cff5eb/python/qa_tch_h_decoder.py#L167-L176
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/traceback.py
python
format_tb
(tb, limit = None)
return format_list(extract_tb(tb, limit))
A shorthand for 'format_list(extract_tb(tb, limit))'.
A shorthand for 'format_list(extract_tb(tb, limit))'.
[ "A", "shorthand", "for", "format_list", "(", "extract_tb", "(", "tb", "limit", "))", "." ]
def format_tb(tb, limit = None): """A shorthand for 'format_list(extract_tb(tb, limit))'.""" return format_list(extract_tb(tb, limit))
[ "def", "format_tb", "(", "tb", ",", "limit", "=", "None", ")", ":", "return", "format_list", "(", "extract_tb", "(", "tb", ",", "limit", ")", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/traceback.py#L74-L76
PixarAnimationStudios/USD
faed18ce62c8736b02413635b584a2f637156bad
pxr/usdImaging/usdviewq/appController.py
python
AppController._HUDInfoChanged
(self)
Called when a HUD setting that requires info refresh has changed.
Called when a HUD setting that requires info refresh has changed.
[ "Called", "when", "a", "HUD", "setting", "that", "requires", "info", "refresh", "has", "changed", "." ]
def _HUDInfoChanged(self): """Called when a HUD setting that requires info refresh has changed.""" if self._isHUDVisible(): self._updateHUDPrimStats() self._updateHUDGeomCounts()
[ "def", "_HUDInfoChanged", "(", "self", ")", ":", "if", "self", ".", "_isHUDVisible", "(", ")", ":", "self", ".", "_updateHUDPrimStats", "(", ")", "self", ".", "_updateHUDGeomCounts", "(", ")" ]
https://github.com/PixarAnimationStudios/USD/blob/faed18ce62c8736b02413635b584a2f637156bad/pxr/usdImaging/usdviewq/appController.py#L5014-L5018
wyrover/book-code
7f4883d9030d553bc6bcfa3da685e34789839900
3rdparty/protobuf/python/google/protobuf/internal/_parameterized.py
python
Parameters
(*testcases)
return _ParameterDecorator(_ARGUMENT_REPR, testcases)
A decorator for creating parameterized tests. See the module docstring for a usage example. Args: *testcases: Parameters for the decorated method, either a single iterable, or a list of tuples/dicts/objects (for tests with only one argument). Returns: A test generator to be handled by TestGeneratorMetaclass.
A decorator for creating parameterized tests.
[ "A", "decorator", "for", "creating", "parameterized", "tests", "." ]
def Parameters(*testcases): """A decorator for creating parameterized tests. See the module docstring for a usage example. Args: *testcases: Parameters for the decorated method, either a single iterable, or a list of tuples/dicts/objects (for tests with only one argument). Returns: A test generator to be handled by TestGeneratorMetaclass. """ return _ParameterDecorator(_ARGUMENT_REPR, testcases)
[ "def", "Parameters", "(", "*", "testcases", ")", ":", "return", "_ParameterDecorator", "(", "_ARGUMENT_REPR", ",", "testcases", ")" ]
https://github.com/wyrover/book-code/blob/7f4883d9030d553bc6bcfa3da685e34789839900/3rdparty/protobuf/python/google/protobuf/internal/_parameterized.py#L309-L321
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/fnmatch.py
python
fnmatchcase
(name, pat)
return match(name) is not None
Test whether FILENAME matches PATTERN, including case. This is a version of fnmatch() which doesn't case-normalize its arguments.
Test whether FILENAME matches PATTERN, including case.
[ "Test", "whether", "FILENAME", "matches", "PATTERN", "including", "case", "." ]
def fnmatchcase(name, pat): """Test whether FILENAME matches PATTERN, including case. This is a version of fnmatch() which doesn't case-normalize its arguments. """ match = _compile_pattern(pat) return match(name) is not None
[ "def", "fnmatchcase", "(", "name", ",", "pat", ")", ":", "match", "=", "_compile_pattern", "(", "pat", ")", "return", "match", "(", "name", ")", "is", "not", "None" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/fnmatch.py#L70-L77
esa/pagmo
80281d549c8f1b470e1489a5d37c8f06b2e429c0
PyGMO/util/_analysis.py
python
analysis._scale_sample
(self)
Scales the sample in x and f after sampling, so all values are [0,1]. If constraints have been computed, it also scales c to [-k,1-k] for k in [0,1].
Scales the sample in x and f after sampling, so all values are [0,1]. If constraints have been computed, it also scales c to [-k,1-k] for k in [0,1].
[ "Scales", "the", "sample", "in", "x", "and", "f", "after", "sampling", "so", "all", "values", "are", "[", "0", "1", "]", ".", "If", "constraints", "have", "been", "computed", "it", "also", "scales", "c", "to", "[", "-", "k", "1", "-", "k", "]", "for", "k", "in", "[", "0", "1", "]", "." ]
def _scale_sample(self): """ Scales the sample in x and f after sampling, so all values are [0,1]. If constraints have been computed, it also scales c to [-k,1-k] for k in [0,1]. """ for i in range(self.npoints): for j in range(self.dim): self.points[i][j] -= self.lb[j] self.points[i][j] /= (self.ub[j] - self.lb[j]) for j in range(self.f_dim): self.f[i][j] -= self.f_offset[j] self.f[i][j] /= self.f_span[j] for j in range(self.c_dim): self.c[i][j] /= self.c_span[j]
[ "def", "_scale_sample", "(", "self", ")", ":", "for", "i", "in", "range", "(", "self", ".", "npoints", ")", ":", "for", "j", "in", "range", "(", "self", ".", "dim", ")", ":", "self", ".", "points", "[", "i", "]", "[", "j", "]", "-=", "self", ".", "lb", "[", "j", "]", "self", ".", "points", "[", "i", "]", "[", "j", "]", "/=", "(", "self", ".", "ub", "[", "j", "]", "-", "self", ".", "lb", "[", "j", "]", ")", "for", "j", "in", "range", "(", "self", ".", "f_dim", ")", ":", "self", ".", "f", "[", "i", "]", "[", "j", "]", "-=", "self", ".", "f_offset", "[", "j", "]", "self", ".", "f", "[", "i", "]", "[", "j", "]", "/=", "self", ".", "f_span", "[", "j", "]", "for", "j", "in", "range", "(", "self", ".", "c_dim", ")", ":", "self", ".", "c", "[", "i", "]", "[", "j", "]", "/=", "self", ".", "c_span", "[", "j", "]" ]
https://github.com/esa/pagmo/blob/80281d549c8f1b470e1489a5d37c8f06b2e429c0/PyGMO/util/_analysis.py#L247-L260
idaholab/moose
9eeebc65e098b4c30f8205fb41591fd5b61eb6ff
python/peacock/PeacockMainWindow.py
python
PeacockMainWindow._setTitle
(self)
Sets the title of the window.
Sets the title of the window.
[ "Sets", "the", "title", "of", "the", "window", "." ]
def _setTitle(self): """ Sets the title of the window. """ title = "Peacock" if self.exe_path: title += " : executable - %s" % os.path.abspath(self.exe_path) if self.input_file_path: title += " : input file - %s" % os.path.abspath(self.input_file_path) self.setWindowTitle(title)
[ "def", "_setTitle", "(", "self", ")", ":", "title", "=", "\"Peacock\"", "if", "self", ".", "exe_path", ":", "title", "+=", "\" : executable - %s\"", "%", "os", ".", "path", ".", "abspath", "(", "self", ".", "exe_path", ")", "if", "self", ".", "input_file_path", ":", "title", "+=", "\" : input file - %s\"", "%", "os", ".", "path", ".", "abspath", "(", "self", ".", "input_file_path", ")", "self", ".", "setWindowTitle", "(", "title", ")" ]
https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/peacock/PeacockMainWindow.py#L121-L130
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/tkinter/__init__.py
python
Misc._displayof
(self, displayof)
return ()
Internal function.
Internal function.
[ "Internal", "function", "." ]
def _displayof(self, displayof): """Internal function.""" if displayof: return ('-displayof', displayof) if displayof is None: return ('-displayof', self._w) return ()
[ "def", "_displayof", "(", "self", ",", "displayof", ")", ":", "if", "displayof", ":", "return", "(", "'-displayof'", ",", "displayof", ")", "if", "displayof", "is", "None", ":", "return", "(", "'-displayof'", ",", "self", ".", "_w", ")", "return", "(", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/tkinter/__init__.py#L1299-L1305
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/tkinter/ttk.py
python
LabeledScale.__init__
(self, master=None, variable=None, from_=0, to=10, **kw)
Construct a horizontal LabeledScale with parent master, a variable to be associated with the Ttk Scale widget and its range. If variable is not specified, a tkinter.IntVar is created. WIDGET-SPECIFIC OPTIONS compound: 'top' or 'bottom' Specifies how to display the label relative to the scale. Defaults to 'top'.
Construct a horizontal LabeledScale with parent master, a variable to be associated with the Ttk Scale widget and its range. If variable is not specified, a tkinter.IntVar is created.
[ "Construct", "a", "horizontal", "LabeledScale", "with", "parent", "master", "a", "variable", "to", "be", "associated", "with", "the", "Ttk", "Scale", "widget", "and", "its", "range", ".", "If", "variable", "is", "not", "specified", "a", "tkinter", ".", "IntVar", "is", "created", "." ]
def __init__(self, master=None, variable=None, from_=0, to=10, **kw): """Construct a horizontal LabeledScale with parent master, a variable to be associated with the Ttk Scale widget and its range. If variable is not specified, a tkinter.IntVar is created. WIDGET-SPECIFIC OPTIONS compound: 'top' or 'bottom' Specifies how to display the label relative to the scale. Defaults to 'top'. """ self._label_top = kw.pop('compound', 'top') == 'top' Frame.__init__(self, master, **kw) self._variable = variable or tkinter.IntVar(master) self._variable.set(from_) self._last_valid = from_ self.label = Label(self) self.scale = Scale(self, variable=self._variable, from_=from_, to=to) self.scale.bind('<<RangeChanged>>', self._adjust) # position scale and label according to the compound option scale_side = 'bottom' if self._label_top else 'top' label_side = 'top' if scale_side == 'bottom' else 'bottom' self.scale.pack(side=scale_side, fill='x') tmp = Label(self).pack(side=label_side) # place holder self.label.place(anchor='n' if label_side == 'top' else 's') # update the label as scale or variable changes self.__tracecb = self._variable.trace_variable('w', self._adjust) self.bind('<Configure>', self._adjust) self.bind('<Map>', self._adjust)
[ "def", "__init__", "(", "self", ",", "master", "=", "None", ",", "variable", "=", "None", ",", "from_", "=", "0", ",", "to", "=", "10", ",", "*", "*", "kw", ")", ":", "self", ".", "_label_top", "=", "kw", ".", "pop", "(", "'compound'", ",", "'top'", ")", "==", "'top'", "Frame", ".", "__init__", "(", "self", ",", "master", ",", "*", "*", "kw", ")", "self", ".", "_variable", "=", "variable", "or", "tkinter", ".", "IntVar", "(", "master", ")", "self", ".", "_variable", ".", "set", "(", "from_", ")", "self", ".", "_last_valid", "=", "from_", "self", ".", "label", "=", "Label", "(", "self", ")", "self", ".", "scale", "=", "Scale", "(", "self", ",", "variable", "=", "self", ".", "_variable", ",", "from_", "=", "from_", ",", "to", "=", "to", ")", "self", ".", "scale", ".", "bind", "(", "'<<RangeChanged>>'", ",", "self", ".", "_adjust", ")", "# position scale and label according to the compound option", "scale_side", "=", "'bottom'", "if", "self", ".", "_label_top", "else", "'top'", "label_side", "=", "'top'", "if", "scale_side", "==", "'bottom'", "else", "'bottom'", "self", ".", "scale", ".", "pack", "(", "side", "=", "scale_side", ",", "fill", "=", "'x'", ")", "tmp", "=", "Label", "(", "self", ")", ".", "pack", "(", "side", "=", "label_side", ")", "# place holder", "self", ".", "label", ".", "place", "(", "anchor", "=", "'n'", "if", "label_side", "==", "'top'", "else", "'s'", ")", "# update the label as scale or variable changes", "self", ".", "__tracecb", "=", "self", ".", "_variable", ".", "trace_variable", "(", "'w'", ",", "self", ".", "_adjust", ")", "self", ".", "bind", "(", "'<Configure>'", ",", "self", ".", "_adjust", ")", "self", ".", "bind", "(", "'<Map>'", ",", "self", ".", "_adjust", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/tkinter/ttk.py#L1534-L1566
trilinos/Trilinos
6168be6dd51e35e1cd681e9c4b24433e709df140
packages/seacas/scripts/exodus2.in.py
python
exodus.put_node_set
(self, id, nodeSetNodes)
exo.put_node_set(node_set_id, ns_nodes) -> store a node set by its id and the list of node *INDICES* in the node set (see exo.get_node_id_map() for explanation of node *INDEX* versus node *ID*) input value(s): <int> node_set_id node set *ID* (not *INDEX*) <list<int>> ns_nodes
exo.put_node_set(node_set_id, ns_nodes)
[ "exo", ".", "put_node_set", "(", "node_set_id", "ns_nodes", ")" ]
def put_node_set(self, id, nodeSetNodes): """ exo.put_node_set(node_set_id, ns_nodes) -> store a node set by its id and the list of node *INDICES* in the node set (see exo.get_node_id_map() for explanation of node *INDEX* versus node *ID*) input value(s): <int> node_set_id node set *ID* (not *INDEX*) <list<int>> ns_nodes """ self.__ex_put_node_set(id, nodeSetNodes)
[ "def", "put_node_set", "(", "self", ",", "id", ",", "nodeSetNodes", ")", ":", "self", ".", "__ex_put_node_set", "(", "id", ",", "nodeSetNodes", ")" ]
https://github.com/trilinos/Trilinos/blob/6168be6dd51e35e1cd681e9c4b24433e709df140/packages/seacas/scripts/exodus2.in.py#L2089-L2101
ku-nlp/jumanpp
008e73b9cf876ce50ba5e751ac7108e68796cb1f
script/git-clang-format.py
python
filter_by_extension
(dictionary, allowed_extensions)
Delete every key in `dictionary` that doesn't have an allowed extension. `allowed_extensions` must be a collection of lowercase file extensions, excluding the period.
Delete every key in `dictionary` that doesn't have an allowed extension.
[ "Delete", "every", "key", "in", "dictionary", "that", "doesn", "t", "have", "an", "allowed", "extension", "." ]
def filter_by_extension(dictionary, allowed_extensions): """Delete every key in `dictionary` that doesn't have an allowed extension. `allowed_extensions` must be a collection of lowercase file extensions, excluding the period.""" allowed_extensions = frozenset(allowed_extensions) for filename in list(dictionary.keys()): base_ext = filename.rsplit('.', 1) if len(base_ext) == 1 and '' in allowed_extensions: continue if len(base_ext) == 1 or base_ext[1].lower() not in allowed_extensions: del dictionary[filename]
[ "def", "filter_by_extension", "(", "dictionary", ",", "allowed_extensions", ")", ":", "allowed_extensions", "=", "frozenset", "(", "allowed_extensions", ")", "for", "filename", "in", "list", "(", "dictionary", ".", "keys", "(", ")", ")", ":", "base_ext", "=", "filename", ".", "rsplit", "(", "'.'", ",", "1", ")", "if", "len", "(", "base_ext", ")", "==", "1", "and", "''", "in", "allowed_extensions", ":", "continue", "if", "len", "(", "base_ext", ")", "==", "1", "or", "base_ext", "[", "1", "]", ".", "lower", "(", ")", "not", "in", "allowed_extensions", ":", "del", "dictionary", "[", "filename", "]" ]
https://github.com/ku-nlp/jumanpp/blob/008e73b9cf876ce50ba5e751ac7108e68796cb1f/script/git-clang-format.py#L319-L330
cinder/Cinder
e83f5bb9c01a63eec20168d02953a0879e5100f7
docs/libs/pystache/loader.py
python
Loader.load_object
(self, obj)
return self.read(path)
Find and return the template associated to the given object. Arguments: obj: an instance of a user-defined class. search_dirs: the list of directories in which to search.
Find and return the template associated to the given object.
[ "Find", "and", "return", "the", "template", "associated", "to", "the", "given", "object", "." ]
def load_object(self, obj): """ Find and return the template associated to the given object. Arguments: obj: an instance of a user-defined class. search_dirs: the list of directories in which to search. """ locator = self._make_locator() path = locator.find_object(obj, self.search_dirs) return self.read(path)
[ "def", "load_object", "(", "self", ",", "obj", ")", ":", "locator", "=", "self", ".", "_make_locator", "(", ")", "path", "=", "locator", ".", "find_object", "(", "obj", ",", "self", ".", "search_dirs", ")", "return", "self", ".", "read", "(", "path", ")" ]
https://github.com/cinder/Cinder/blob/e83f5bb9c01a63eec20168d02953a0879e5100f7/docs/libs/pystache/loader.py#L155-L170
qt/qt
0a2f2382541424726168804be2c90b91381608c6
src/3rdparty/webkit/Source/ThirdParty/gyp/pylib/gyp/xcodeproj_file.py
python
XCConfigurationList.AppendBuildSetting
(self, key, value)
Appends value to the build setting for key, which is treated as a list, in all child XCBuildConfiguration objects.
Appends value to the build setting for key, which is treated as a list, in all child XCBuildConfiguration objects.
[ "Appends", "value", "to", "the", "build", "setting", "for", "key", "which", "is", "treated", "as", "a", "list", "in", "all", "child", "XCBuildConfiguration", "objects", "." ]
def AppendBuildSetting(self, key, value): """Appends value to the build setting for key, which is treated as a list, in all child XCBuildConfiguration objects. """ for configuration in self._properties['buildConfigurations']: configuration.AppendBuildSetting(key, value)
[ "def", "AppendBuildSetting", "(", "self", ",", "key", ",", "value", ")", ":", "for", "configuration", "in", "self", ".", "_properties", "[", "'buildConfigurations'", "]", ":", "configuration", ".", "AppendBuildSetting", "(", "key", ",", "value", ")" ]
https://github.com/qt/qt/blob/0a2f2382541424726168804be2c90b91381608c6/src/3rdparty/webkit/Source/ThirdParty/gyp/pylib/gyp/xcodeproj_file.py#L1634-L1640
ROCmSoftwarePlatform/hipCaffe
4ec5d482515cce532348553b6db6d00d015675d5
python/caffe/coord_map.py
python
crop_params
(fn)
return (axis, offset)
Extract the crop layer parameters with defaults.
Extract the crop layer parameters with defaults.
[ "Extract", "the", "crop", "layer", "parameters", "with", "defaults", "." ]
def crop_params(fn): """ Extract the crop layer parameters with defaults. """ params = fn.params.get('crop_param', fn.params) axis = params.get('axis', 2) # default to spatial crop for N, C, H, W offset = np.array(params.get('offset', 0), ndmin=1) return (axis, offset)
[ "def", "crop_params", "(", "fn", ")", ":", "params", "=", "fn", ".", "params", ".", "get", "(", "'crop_param'", ",", "fn", ".", "params", ")", "axis", "=", "params", ".", "get", "(", "'axis'", ",", "2", ")", "# default to spatial crop for N, C, H, W", "offset", "=", "np", ".", "array", "(", "params", ".", "get", "(", "'offset'", ",", "0", ")", ",", "ndmin", "=", "1", ")", "return", "(", "axis", ",", "offset", ")" ]
https://github.com/ROCmSoftwarePlatform/hipCaffe/blob/4ec5d482515cce532348553b6db6d00d015675d5/python/caffe/coord_map.py#L40-L47
greenheartgames/greenworks
3ea4ab490b56676de3f0a237c74bcfdb17323e60
deps/cpplint/cpplint.py
python
FilesBelongToSameModule
(filename_cc, filename_h)
return files_belong_to_same_module, common_path
Check if these two filenames belong to the same module. The concept of a 'module' here is a as follows: foo.h, foo-inl.h, foo.cc, foo_test.cc and foo_unittest.cc belong to the same 'module' if they are in the same directory. some/path/public/xyzzy and some/path/internal/xyzzy are also considered to belong to the same module here. If the filename_cc contains a longer path than the filename_h, for example, '/absolute/path/to/base/sysinfo.cc', and this file would include 'base/sysinfo.h', this function also produces the prefix needed to open the header. This is used by the caller of this function to more robustly open the header file. We don't have access to the real include paths in this context, so we need this guesswork here. Known bugs: tools/base/bar.cc and base/bar.h belong to the same module according to this implementation. Because of this, this function gives some false positives. This should be sufficiently rare in practice. Args: filename_cc: is the path for the .cc file filename_h: is the path for the header path Returns: Tuple with a bool and a string: bool: True if filename_cc and filename_h belong to the same module. string: the additional prefix needed to open the header file.
Check if these two filenames belong to the same module.
[ "Check", "if", "these", "two", "filenames", "belong", "to", "the", "same", "module", "." ]
def FilesBelongToSameModule(filename_cc, filename_h): """Check if these two filenames belong to the same module. The concept of a 'module' here is a as follows: foo.h, foo-inl.h, foo.cc, foo_test.cc and foo_unittest.cc belong to the same 'module' if they are in the same directory. some/path/public/xyzzy and some/path/internal/xyzzy are also considered to belong to the same module here. If the filename_cc contains a longer path than the filename_h, for example, '/absolute/path/to/base/sysinfo.cc', and this file would include 'base/sysinfo.h', this function also produces the prefix needed to open the header. This is used by the caller of this function to more robustly open the header file. We don't have access to the real include paths in this context, so we need this guesswork here. Known bugs: tools/base/bar.cc and base/bar.h belong to the same module according to this implementation. Because of this, this function gives some false positives. This should be sufficiently rare in practice. Args: filename_cc: is the path for the .cc file filename_h: is the path for the header path Returns: Tuple with a bool and a string: bool: True if filename_cc and filename_h belong to the same module. string: the additional prefix needed to open the header file. """ fileinfo = FileInfo(filename_cc) if not fileinfo.IsSource(): return (False, '') filename_cc = filename_cc[:-len(fileinfo.Extension())] matched_test_suffix = Search(_TEST_FILE_SUFFIX, fileinfo.BaseName()) if matched_test_suffix: filename_cc = filename_cc[:-len(matched_test_suffix.group(1))] filename_cc = filename_cc.replace('/public/', '/') filename_cc = filename_cc.replace('/internal/', '/') if not filename_h.endswith('.h'): return (False, '') filename_h = filename_h[:-len('.h')] if filename_h.endswith('-inl'): filename_h = filename_h[:-len('-inl')] filename_h = filename_h.replace('/public/', '/') filename_h = filename_h.replace('/internal/', '/') files_belong_to_same_module = filename_cc.endswith(filename_h) common_path = '' if files_belong_to_same_module: common_path = filename_cc[:-len(filename_h)] return files_belong_to_same_module, common_path
[ "def", "FilesBelongToSameModule", "(", "filename_cc", ",", "filename_h", ")", ":", "fileinfo", "=", "FileInfo", "(", "filename_cc", ")", "if", "not", "fileinfo", ".", "IsSource", "(", ")", ":", "return", "(", "False", ",", "''", ")", "filename_cc", "=", "filename_cc", "[", ":", "-", "len", "(", "fileinfo", ".", "Extension", "(", ")", ")", "]", "matched_test_suffix", "=", "Search", "(", "_TEST_FILE_SUFFIX", ",", "fileinfo", ".", "BaseName", "(", ")", ")", "if", "matched_test_suffix", ":", "filename_cc", "=", "filename_cc", "[", ":", "-", "len", "(", "matched_test_suffix", ".", "group", "(", "1", ")", ")", "]", "filename_cc", "=", "filename_cc", ".", "replace", "(", "'/public/'", ",", "'/'", ")", "filename_cc", "=", "filename_cc", ".", "replace", "(", "'/internal/'", ",", "'/'", ")", "if", "not", "filename_h", ".", "endswith", "(", "'.h'", ")", ":", "return", "(", "False", ",", "''", ")", "filename_h", "=", "filename_h", "[", ":", "-", "len", "(", "'.h'", ")", "]", "if", "filename_h", ".", "endswith", "(", "'-inl'", ")", ":", "filename_h", "=", "filename_h", "[", ":", "-", "len", "(", "'-inl'", ")", "]", "filename_h", "=", "filename_h", ".", "replace", "(", "'/public/'", ",", "'/'", ")", "filename_h", "=", "filename_h", ".", "replace", "(", "'/internal/'", ",", "'/'", ")", "files_belong_to_same_module", "=", "filename_cc", ".", "endswith", "(", "filename_h", ")", "common_path", "=", "''", "if", "files_belong_to_same_module", ":", "common_path", "=", "filename_cc", "[", ":", "-", "len", "(", "filename_h", ")", "]", "return", "files_belong_to_same_module", ",", "common_path" ]
https://github.com/greenheartgames/greenworks/blob/3ea4ab490b56676de3f0a237c74bcfdb17323e60/deps/cpplint/cpplint.py#L5341-L5393
indutny/candor
48e7260618f5091c80a3416828e2808cad3ea22e
tools/gyp/pylib/gyp/generator/msvs.py
python
_EscapeCommandLineArgumentForMSBuild
(s)
return s
Escapes a Windows command-line argument for use by MSBuild.
Escapes a Windows command-line argument for use by MSBuild.
[ "Escapes", "a", "Windows", "command", "-", "line", "argument", "for", "use", "by", "MSBuild", "." ]
def _EscapeCommandLineArgumentForMSBuild(s): """Escapes a Windows command-line argument for use by MSBuild.""" def _Replace(match): return (len(match.group(1))/2*4)*'\\' + '\\"' # Escape all quotes so that they are interpreted literally. s = quote_replacer_regex2.sub(_Replace, s) return s
[ "def", "_EscapeCommandLineArgumentForMSBuild", "(", "s", ")", ":", "def", "_Replace", "(", "match", ")", ":", "return", "(", "len", "(", "match", ".", "group", "(", "1", ")", ")", "/", "2", "*", "4", ")", "*", "'\\\\'", "+", "'\\\\\"'", "# Escape all quotes so that they are interpreted literally.", "s", "=", "quote_replacer_regex2", ".", "sub", "(", "_Replace", ",", "s", ")", "return", "s" ]
https://github.com/indutny/candor/blob/48e7260618f5091c80a3416828e2808cad3ea22e/tools/gyp/pylib/gyp/generator/msvs.py#L718-L726
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/framework/ops.py
python
value_text
(tensor, is_repr=False)
return text
Either the NumPy value or a custom TensorFlow formatting of `tensor`. Custom formatting is used for custom device tensors, e.g. parallel tensors with multiple components on different devices. Args: tensor: The tensor to format. is_repr: Controls the style/verbosity of formatting. Returns: The formatted tensor.
Either the NumPy value or a custom TensorFlow formatting of `tensor`.
[ "Either", "the", "NumPy", "value", "or", "a", "custom", "TensorFlow", "formatting", "of", "tensor", "." ]
def value_text(tensor, is_repr=False): """Either the NumPy value or a custom TensorFlow formatting of `tensor`. Custom formatting is used for custom device tensors, e.g. parallel tensors with multiple components on different devices. Args: tensor: The tensor to format. is_repr: Controls the style/verbosity of formatting. Returns: The formatted tensor. """ # pylint: disable=protected-access # friend access if tensor._prefer_custom_summarizer(): text = tensor._summarize_value() # pylint: enable=protected-access if is_repr: text = "value=" + text else: text = numpy_text(tensor, is_repr=is_repr) if is_repr: text = "numpy=" + text return text
[ "def", "value_text", "(", "tensor", ",", "is_repr", "=", "False", ")", ":", "# pylint: disable=protected-access # friend access", "if", "tensor", ".", "_prefer_custom_summarizer", "(", ")", ":", "text", "=", "tensor", ".", "_summarize_value", "(", ")", "# pylint: enable=protected-access", "if", "is_repr", ":", "text", "=", "\"value=\"", "+", "text", "else", ":", "text", "=", "numpy_text", "(", "tensor", ",", "is_repr", "=", "is_repr", ")", "if", "is_repr", ":", "text", "=", "\"numpy=\"", "+", "text", "return", "text" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/framework/ops.py#L236-L259
scylladb/seastar
0cdd2329beb1cc4c0af8828598c26114397ffa9c
scripts/perftune.py
python
DiskPerfTuner.__write_cache_config
(self)
return "write back" if self.args.set_write_back else "write through"
:return: None - if write cache mode configuration is not requested or the corresponding write cache configuration value string
:return: None - if write cache mode configuration is not requested or the corresponding write cache configuration value string
[ ":", "return", ":", "None", "-", "if", "write", "cache", "mode", "configuration", "is", "not", "requested", "or", "the", "corresponding", "write", "cache", "configuration", "value", "string" ]
def __write_cache_config(self): """ :return: None - if write cache mode configuration is not requested or the corresponding write cache configuration value string """ if self.args.set_write_back is None: return None return "write back" if self.args.set_write_back else "write through"
[ "def", "__write_cache_config", "(", "self", ")", ":", "if", "self", ".", "args", ".", "set_write_back", "is", "None", ":", "return", "None", "return", "\"write back\"", "if", "self", ".", "args", ".", "set_write_back", "else", "\"write through\"" ]
https://github.com/scylladb/seastar/blob/0cdd2329beb1cc4c0af8828598c26114397ffa9c/scripts/perftune.py#L1020-L1028
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_misc.py
python
PlatformInformation.IsOk
(*args, **kwargs)
return _misc_.PlatformInformation_IsOk(*args, **kwargs)
IsOk(self) -> bool
IsOk(self) -> bool
[ "IsOk", "(", "self", ")", "-", ">", "bool" ]
def IsOk(*args, **kwargs): """IsOk(self) -> bool""" return _misc_.PlatformInformation_IsOk(*args, **kwargs)
[ "def", "IsOk", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_misc_", ".", "PlatformInformation_IsOk", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_misc.py#L1182-L1184
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/email/mime/application.py
python
MIMEApplication.__init__
(self, _data, _subtype='octet-stream', _encoder=encoders.encode_base64, *, policy=None, **_params)
Create an application/* type MIME document. _data is a string containing the raw application data. _subtype is the MIME content type subtype, defaulting to 'octet-stream'. _encoder is a function which will perform the actual encoding for transport of the application data, defaulting to base64 encoding. Any additional keyword arguments are passed to the base class constructor, which turns them into parameters on the Content-Type header.
Create an application/* type MIME document.
[ "Create", "an", "application", "/", "*", "type", "MIME", "document", "." ]
def __init__(self, _data, _subtype='octet-stream', _encoder=encoders.encode_base64, *, policy=None, **_params): """Create an application/* type MIME document. _data is a string containing the raw application data. _subtype is the MIME content type subtype, defaulting to 'octet-stream'. _encoder is a function which will perform the actual encoding for transport of the application data, defaulting to base64 encoding. Any additional keyword arguments are passed to the base class constructor, which turns them into parameters on the Content-Type header. """ if _subtype is None: raise TypeError('Invalid application MIME subtype') MIMENonMultipart.__init__(self, 'application', _subtype, policy=policy, **_params) self.set_payload(_data) _encoder(self)
[ "def", "__init__", "(", "self", ",", "_data", ",", "_subtype", "=", "'octet-stream'", ",", "_encoder", "=", "encoders", ".", "encode_base64", ",", "*", ",", "policy", "=", "None", ",", "*", "*", "_params", ")", ":", "if", "_subtype", "is", "None", ":", "raise", "TypeError", "(", "'Invalid application MIME subtype'", ")", "MIMENonMultipart", ".", "__init__", "(", "self", ",", "'application'", ",", "_subtype", ",", "policy", "=", "policy", ",", "*", "*", "_params", ")", "self", ".", "set_payload", "(", "_data", ")", "_encoder", "(", "self", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/email/mime/application.py#L16-L37
llvm/llvm-project
ffa6262cb4e2a335d26416fad39a581b4f98c5f4
clang/bindings/python/clang/cindex.py
python
Type.get_declaration
(self)
return conf.lib.clang_getTypeDeclaration(self)
Return the cursor for the declaration of the given type.
Return the cursor for the declaration of the given type.
[ "Return", "the", "cursor", "for", "the", "declaration", "of", "the", "given", "type", "." ]
def get_declaration(self): """ Return the cursor for the declaration of the given type. """ return conf.lib.clang_getTypeDeclaration(self)
[ "def", "get_declaration", "(", "self", ")", ":", "return", "conf", ".", "lib", ".", "clang_getTypeDeclaration", "(", "self", ")" ]
https://github.com/llvm/llvm-project/blob/ffa6262cb4e2a335d26416fad39a581b4f98c5f4/clang/bindings/python/clang/cindex.py#L2343-L2347
freeorion/freeorion
c266a40eccd3a99a17de8fe57c36ef6ba3771665
default/python/AI/AIstate.py
python
AIstate.__split_new_fleets
(self)
Split any new fleets. This function is supposed to be called once at the beginning of the turn. Splitting the auto generated fleets at game start or those created by recently built ships allows the AI to assign correct roles to all ships.
Split any new fleets.
[ "Split", "any", "new", "fleets", "." ]
def __split_new_fleets(self): """Split any new fleets. This function is supposed to be called once at the beginning of the turn. Splitting the auto generated fleets at game start or those created by recently built ships allows the AI to assign correct roles to all ships. """ # TODO: check length of fleets for losses or do in AIstate.__cleanRoles universe = fo.getUniverse() known_fleets = self.get_fleet_roles_map() self.newlySplitFleets.clear() fleets_to_split = [fleet_id for fleet_id in FleetUtilsAI.get_empire_fleet_ids() if fleet_id not in known_fleets] if fleets_to_split: debug("Trying to split %d new fleets" % len(fleets_to_split)) for fleet_id in fleets_to_split: fleet = universe.getFleet(fleet_id) if not fleet: warning("Trying to split fleet %d but seemingly does not exist" % fleet_id) continue fleet_len = len(fleet.shipIDs) if fleet_len == 1: continue new_fleets = FleetUtilsAI.split_fleet(fleet_id) debug("Split fleet %d with %d ships into %d new fleets:" % (fleet_id, fleet_len, len(new_fleets)))
[ "def", "__split_new_fleets", "(", "self", ")", ":", "# TODO: check length of fleets for losses or do in AIstate.__cleanRoles", "universe", "=", "fo", ".", "getUniverse", "(", ")", "known_fleets", "=", "self", ".", "get_fleet_roles_map", "(", ")", "self", ".", "newlySplitFleets", ".", "clear", "(", ")", "fleets_to_split", "=", "[", "fleet_id", "for", "fleet_id", "in", "FleetUtilsAI", ".", "get_empire_fleet_ids", "(", ")", "if", "fleet_id", "not", "in", "known_fleets", "]", "if", "fleets_to_split", ":", "debug", "(", "\"Trying to split %d new fleets\"", "%", "len", "(", "fleets_to_split", ")", ")", "for", "fleet_id", "in", "fleets_to_split", ":", "fleet", "=", "universe", ".", "getFleet", "(", "fleet_id", ")", "if", "not", "fleet", ":", "warning", "(", "\"Trying to split fleet %d but seemingly does not exist\"", "%", "fleet_id", ")", "continue", "fleet_len", "=", "len", "(", "fleet", ".", "shipIDs", ")", "if", "fleet_len", "==", "1", ":", "continue", "new_fleets", "=", "FleetUtilsAI", ".", "split_fleet", "(", "fleet_id", ")", "debug", "(", "\"Split fleet %d with %d ships into %d new fleets:\"", "%", "(", "fleet_id", ",", "fleet_len", ",", "len", "(", "new_fleets", ")", ")", ")" ]
https://github.com/freeorion/freeorion/blob/c266a40eccd3a99a17de8fe57c36ef6ba3771665/default/python/AI/AIstate.py#L991-L1015
hszhao/PSPNet
cf7e5a99ba37e46118026e96be5821a9bc63bde0
scripts/cpp_lint.py
python
ReverseCloseExpression
(clean_lines, linenum, pos)
return (line, 0, -1)
If input points to ) or } or ] or >, finds the position that opens it. If lines[linenum][pos] points to a ')' or '}' or ']' or '>', finds the linenum/pos that correspond to the opening of the expression. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. pos: A position on the line. Returns: A tuple (line, linenum, pos) pointer *at* the opening brace, or (line, 0, -1) if we never find the matching opening brace. Note we ignore strings and comments when matching; and the line we return is the 'cleansed' line at linenum.
If input points to ) or } or ] or >, finds the position that opens it.
[ "If", "input", "points", "to", ")", "or", "}", "or", "]", "or", ">", "finds", "the", "position", "that", "opens", "it", "." ]
def ReverseCloseExpression(clean_lines, linenum, pos): """If input points to ) or } or ] or >, finds the position that opens it. If lines[linenum][pos] points to a ')' or '}' or ']' or '>', finds the linenum/pos that correspond to the opening of the expression. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. pos: A position on the line. Returns: A tuple (line, linenum, pos) pointer *at* the opening brace, or (line, 0, -1) if we never find the matching opening brace. Note we ignore strings and comments when matching; and the line we return is the 'cleansed' line at linenum. """ line = clean_lines.elided[linenum] endchar = line[pos] if endchar not in ')}]>': return (line, 0, -1) if endchar == ')': startchar = '(' if endchar == ']': startchar = '[' if endchar == '}': startchar = '{' if endchar == '>': startchar = '<' # Check last line (start_pos, num_open) = FindStartOfExpressionInLine( line, pos, 0, startchar, endchar) if start_pos > -1: return (line, linenum, start_pos) # Continue scanning backward while linenum > 0: linenum -= 1 line = clean_lines.elided[linenum] (start_pos, num_open) = FindStartOfExpressionInLine( line, len(line) - 1, num_open, startchar, endchar) if start_pos > -1: return (line, linenum, start_pos) # Did not find startchar before beginning of file, give up return (line, 0, -1)
[ "def", "ReverseCloseExpression", "(", "clean_lines", ",", "linenum", ",", "pos", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "endchar", "=", "line", "[", "pos", "]", "if", "endchar", "not", "in", "')}]>'", ":", "return", "(", "line", ",", "0", ",", "-", "1", ")", "if", "endchar", "==", "')'", ":", "startchar", "=", "'('", "if", "endchar", "==", "']'", ":", "startchar", "=", "'['", "if", "endchar", "==", "'}'", ":", "startchar", "=", "'{'", "if", "endchar", "==", "'>'", ":", "startchar", "=", "'<'", "# Check last line", "(", "start_pos", ",", "num_open", ")", "=", "FindStartOfExpressionInLine", "(", "line", ",", "pos", ",", "0", ",", "startchar", ",", "endchar", ")", "if", "start_pos", ">", "-", "1", ":", "return", "(", "line", ",", "linenum", ",", "start_pos", ")", "# Continue scanning backward", "while", "linenum", ">", "0", ":", "linenum", "-=", "1", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "(", "start_pos", ",", "num_open", ")", "=", "FindStartOfExpressionInLine", "(", "line", ",", "len", "(", "line", ")", "-", "1", ",", "num_open", ",", "startchar", ",", "endchar", ")", "if", "start_pos", ">", "-", "1", ":", "return", "(", "line", ",", "linenum", ",", "start_pos", ")", "# Did not find startchar before beginning of file, give up", "return", "(", "line", ",", "0", ",", "-", "1", ")" ]
https://github.com/hszhao/PSPNet/blob/cf7e5a99ba37e46118026e96be5821a9bc63bde0/scripts/cpp_lint.py#L1327-L1369
mysql/mysql-workbench
2f35f9034f015cbcd22139a60e1baa2e3e8e795c
plugins/wb.sqlide/sqlide_schematree_ext.py
python
CodeGenerator.build_cascaded_delete
(self)
To delete a row from a table all references to that row from other tables must be deleted first, otherwise the FK constraint won't let it be done. So this function will build the DELETE statements needed to do that, by deleting references to the given row all the way up to the wanted table.
To delete a row from a table all references to that row from other tables must be deleted first, otherwise the FK constraint won't let it be done. So this function will build the DELETE statements needed to do that, by deleting references to the given row all the way up to the wanted table.
[ "To", "delete", "a", "row", "from", "a", "table", "all", "references", "to", "that", "row", "from", "other", "tables", "must", "be", "deleted", "first", "otherwise", "the", "FK", "constraint", "won", "t", "let", "it", "be", "done", ".", "So", "this", "function", "will", "build", "the", "DELETE", "statements", "needed", "to", "do", "that", "by", "deleting", "references", "to", "the", "given", "row", "all", "the", "way", "up", "to", "the", "wanted", "table", "." ]
def build_cascaded_delete(self): """ To delete a row from a table all references to that row from other tables must be deleted first, otherwise the FK constraint won't let it be done. So this function will build the DELETE statements needed to do that, by deleting references to the given row all the way up to the wanted table. """ editor = self.editor object = self.selection[0] info = dependencyInfoForSchemaInEditor(editor, object.schemaName) if not info: return info.scan_tables() the_table = info.table_with_name(object.schemaName, object.name) if not the_table: mforms.Utilities.show_error("Cascading DELETE", "Could not find reverse engineered %s" % object.name, "OK", "", "") return if not the_table.primaryKey: mforms.Utilities.show_error("Cascading DELETE", "Unable to create a DELETE statement for %s because the table has no primary key." % object.name, "OK", "", "") return # expression to match the row to be deleted pk = [] for c in the_table.primaryKey.columns: pk.append("%s.%s = @%s_to_delete" % (the_table.name, c.referencedColumn.name, c.referencedColumn.name)) pk = " AND ".join(pk) def create_delete(table, info, deletes, reference_chain, visited): if table in visited: return visited.add(table) def add_to_list(list, item): if item not in list: return list + [item] return list for fk in info.get_foreign_keys_to_table(table): create_delete(fk.owner, info, deletes, reference_chain + [fk], visited) query = "DELETE FROM %s\n" % table.name query += " USING %s\n" % ", ".join(add_to_list([fk.owner.name for fk in reference_chain], the_table.name)) if reference_chain: query += " WHERE %s\n" % "\n AND ".join([format_fk_join(fk) for fk in reference_chain]) query += " AND %s;" % pk else: query += " WHERE %s;" % pk deletes.append(query) deletes = [] create_delete(the_table, info, deletes, [], set()) varsetup = [] for c in the_table.primaryKey.columns: varsetup.append("SET @%s_to_delete = <{row_id}>;" % c.referencedColumn.name) query = """ -- All objects that reference that row (directly or indirectly) will be deleted when this snippet is executed. -- To preview the rows to be deleted, use Select Row Dependencies START TRANSACTION; -- Provide the values of the primary key of the row to delete. %s %s COMMIT; """ % ("\n".join(varsetup), "\n".join(deletes)) self.send(query) if not self.to_editor: mforms.App.get().set_status_text("DELETE statement for %s was copied to clipboard" % the_table.name)
[ "def", "build_cascaded_delete", "(", "self", ")", ":", "editor", "=", "self", ".", "editor", "object", "=", "self", ".", "selection", "[", "0", "]", "info", "=", "dependencyInfoForSchemaInEditor", "(", "editor", ",", "object", ".", "schemaName", ")", "if", "not", "info", ":", "return", "info", ".", "scan_tables", "(", ")", "the_table", "=", "info", ".", "table_with_name", "(", "object", ".", "schemaName", ",", "object", ".", "name", ")", "if", "not", "the_table", ":", "mforms", ".", "Utilities", ".", "show_error", "(", "\"Cascading DELETE\"", ",", "\"Could not find reverse engineered %s\"", "%", "object", ".", "name", ",", "\"OK\"", ",", "\"\"", ",", "\"\"", ")", "return", "if", "not", "the_table", ".", "primaryKey", ":", "mforms", ".", "Utilities", ".", "show_error", "(", "\"Cascading DELETE\"", ",", "\"Unable to create a DELETE statement for %s because the table has no primary key.\"", "%", "object", ".", "name", ",", "\"OK\"", ",", "\"\"", ",", "\"\"", ")", "return", "# expression to match the row to be deleted", "pk", "=", "[", "]", "for", "c", "in", "the_table", ".", "primaryKey", ".", "columns", ":", "pk", ".", "append", "(", "\"%s.%s = @%s_to_delete\"", "%", "(", "the_table", ".", "name", ",", "c", ".", "referencedColumn", ".", "name", ",", "c", ".", "referencedColumn", ".", "name", ")", ")", "pk", "=", "\" AND \"", ".", "join", "(", "pk", ")", "def", "create_delete", "(", "table", ",", "info", ",", "deletes", ",", "reference_chain", ",", "visited", ")", ":", "if", "table", "in", "visited", ":", "return", "visited", ".", "add", "(", "table", ")", "def", "add_to_list", "(", "list", ",", "item", ")", ":", "if", "item", "not", "in", "list", ":", "return", "list", "+", "[", "item", "]", "return", "list", "for", "fk", "in", "info", ".", "get_foreign_keys_to_table", "(", "table", ")", ":", "create_delete", "(", "fk", ".", "owner", ",", "info", ",", "deletes", ",", "reference_chain", "+", "[", "fk", "]", ",", "visited", ")", "query", "=", "\"DELETE FROM %s\\n\"", "%", "table", ".", "name", "query", "+=", "\" USING %s\\n\"", "%", "\", \"", ".", "join", "(", "add_to_list", "(", "[", "fk", ".", "owner", ".", "name", "for", "fk", "in", "reference_chain", "]", ",", "the_table", ".", "name", ")", ")", "if", "reference_chain", ":", "query", "+=", "\" WHERE %s\\n\"", "%", "\"\\n AND \"", ".", "join", "(", "[", "format_fk_join", "(", "fk", ")", "for", "fk", "in", "reference_chain", "]", ")", "query", "+=", "\" AND %s;\"", "%", "pk", "else", ":", "query", "+=", "\" WHERE %s;\"", "%", "pk", "deletes", ".", "append", "(", "query", ")", "deletes", "=", "[", "]", "create_delete", "(", "the_table", ",", "info", ",", "deletes", ",", "[", "]", ",", "set", "(", ")", ")", "varsetup", "=", "[", "]", "for", "c", "in", "the_table", ".", "primaryKey", ".", "columns", ":", "varsetup", ".", "append", "(", "\"SET @%s_to_delete = <{row_id}>;\"", "%", "c", ".", "referencedColumn", ".", "name", ")", "query", "=", "\"\"\"\n-- All objects that reference that row (directly or indirectly) will be deleted when this snippet is executed.\n-- To preview the rows to be deleted, use Select Row Dependencies\nSTART TRANSACTION;\n-- Provide the values of the primary key of the row to delete.\n%s\n\n%s\nCOMMIT;\n\"\"\"", "%", "(", "\"\\n\"", ".", "join", "(", "varsetup", ")", ",", "\"\\n\"", ".", "join", "(", "deletes", ")", ")", "self", ".", "send", "(", "query", ")", "if", "not", "self", ".", "to_editor", ":", "mforms", ".", "App", ".", "get", "(", ")", ".", "set_status_text", "(", "\"DELETE statement for %s was copied to clipboard\"", "%", "the_table", ".", "name", ")" ]
https://github.com/mysql/mysql-workbench/blob/2f35f9034f015cbcd22139a60e1baa2e3e8e795c/plugins/wb.sqlide/sqlide_schematree_ext.py#L983-L1056
y123456yz/reading-and-annotate-mongodb-3.6
93280293672ca7586dc24af18132aa61e4ed7fcf
mongo/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/SConf.py
python
SConfBase._shutdown
(self)
Private method. Reset to non-piped spawn
Private method. Reset to non-piped spawn
[ "Private", "method", ".", "Reset", "to", "non", "-", "piped", "spawn" ]
def _shutdown(self): """Private method. Reset to non-piped spawn""" global sconf_global, _ac_config_hs if not self.active: raise SCons.Errors.UserError("Finish may be called only once!") if self.logstream is not None and not dryrun: self.logstream.write("\n") self.logstream.close() self.logstream = None # remove the SConfSourceBuilder from the environment blds = self.env['BUILDERS'] del blds['SConfSourceBuilder'] self.env.Replace( BUILDERS=blds ) self.active = 0 sconf_global = None if not self.config_h is None: _ac_config_hs[self.config_h] = self.config_h_text self.env.fs = self.lastEnvFs
[ "def", "_shutdown", "(", "self", ")", ":", "global", "sconf_global", ",", "_ac_config_hs", "if", "not", "self", ".", "active", ":", "raise", "SCons", ".", "Errors", ".", "UserError", "(", "\"Finish may be called only once!\"", ")", "if", "self", ".", "logstream", "is", "not", "None", "and", "not", "dryrun", ":", "self", ".", "logstream", ".", "write", "(", "\"\\n\"", ")", "self", ".", "logstream", ".", "close", "(", ")", "self", ".", "logstream", "=", "None", "# remove the SConfSourceBuilder from the environment", "blds", "=", "self", ".", "env", "[", "'BUILDERS'", "]", "del", "blds", "[", "'SConfSourceBuilder'", "]", "self", ".", "env", ".", "Replace", "(", "BUILDERS", "=", "blds", ")", "self", ".", "active", "=", "0", "sconf_global", "=", "None", "if", "not", "self", ".", "config_h", "is", "None", ":", "_ac_config_hs", "[", "self", ".", "config_h", "]", "=", "self", ".", "config_h_text", "self", ".", "env", ".", "fs", "=", "self", ".", "lastEnvFs" ]
https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/SConf.py#L731-L749
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/distutils/command/sdist.py
python
sdist.write_manifest
(self)
Write the file list in 'self.filelist' (presumably as filled in by 'add_defaults()' and 'read_template()') to the manifest file named by 'self.manifest'.
Write the file list in 'self.filelist' (presumably as filled in by 'add_defaults()' and 'read_template()') to the manifest file named by 'self.manifest'.
[ "Write", "the", "file", "list", "in", "self", ".", "filelist", "(", "presumably", "as", "filled", "in", "by", "add_defaults", "()", "and", "read_template", "()", ")", "to", "the", "manifest", "file", "named", "by", "self", ".", "manifest", "." ]
def write_manifest(self): """Write the file list in 'self.filelist' (presumably as filled in by 'add_defaults()' and 'read_template()') to the manifest file named by 'self.manifest'. """ if self._manifest_is_not_generated(): log.info("not writing to manually maintained " "manifest file '%s'" % self.manifest) return content = self.filelist.files[:] content.insert(0, '# file GENERATED by distutils, do NOT edit') self.execute(file_util.write_file, (self.manifest, content), "writing manifest file '%s'" % self.manifest)
[ "def", "write_manifest", "(", "self", ")", ":", "if", "self", ".", "_manifest_is_not_generated", "(", ")", ":", "log", ".", "info", "(", "\"not writing to manually maintained \"", "\"manifest file '%s'\"", "%", "self", ".", "manifest", ")", "return", "content", "=", "self", ".", "filelist", ".", "files", "[", ":", "]", "content", ".", "insert", "(", "0", ",", "'# file GENERATED by distutils, do NOT edit'", ")", "self", ".", "execute", "(", "file_util", ".", "write_file", ",", "(", "self", ".", "manifest", ",", "content", ")", ",", "\"writing manifest file '%s'\"", "%", "self", ".", "manifest", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/distutils/command/sdist.py#L377-L390
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/functools.py
python
_le_from_gt
(self, other, NotImplemented=NotImplemented)
return not op_result
Return a <= b. Computed by @total_ordering from (not a > b).
Return a <= b. Computed by
[ "Return", "a", "<", "=", "b", ".", "Computed", "by" ]
def _le_from_gt(self, other, NotImplemented=NotImplemented): 'Return a <= b. Computed by @total_ordering from (not a > b).' op_result = type(self).__gt__(self, other) if op_result is NotImplemented: return op_result return not op_result
[ "def", "_le_from_gt", "(", "self", ",", "other", ",", "NotImplemented", "=", "NotImplemented", ")", ":", "op_result", "=", "type", "(", "self", ")", ".", "__gt__", "(", "self", ",", "other", ")", "if", "op_result", "is", "NotImplemented", ":", "return", "op_result", "return", "not", "op_result" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/functools.py#L145-L150
mapequation/infomap
5f56b94fe0f956483f61a03ef07e94d8def2205e
interfaces/python/infomap.py
python
Infomap.num_leaf_modules
(self)
return num_leaf_modules
Get the number of leaf modules in the tree Returns ------- int The number of leaf modules
Get the number of leaf modules in the tree
[ "Get", "the", "number", "of", "leaf", "modules", "in", "the", "tree" ]
def num_leaf_modules(self): """Get the number of leaf modules in the tree Returns ------- int The number of leaf modules """ num_leaf_modules = 0 for _ in self.leaf_modules: num_leaf_modules += 1 return num_leaf_modules
[ "def", "num_leaf_modules", "(", "self", ")", ":", "num_leaf_modules", "=", "0", "for", "_", "in", "self", ".", "leaf_modules", ":", "num_leaf_modules", "+=", "1", "return", "num_leaf_modules" ]
https://github.com/mapequation/infomap/blob/5f56b94fe0f956483f61a03ef07e94d8def2205e/interfaces/python/infomap.py#L2073-L2084
adobe/chromium
cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7
tools/json_schema_compiler/schema_bundle_generator.py
python
SchemaBundleGenerator.GenerateHeader
(self, file_base, body_code)
return c
Generates a code.Code object for a header file Parameters: - |file_base| - the base of the filename, e.g. 'foo' (for 'foo.h') - |body_code| - the code to put in between the multiple inclusion guards
Generates a code.Code object for a header file
[ "Generates", "a", "code", ".", "Code", "object", "for", "a", "header", "file" ]
def GenerateHeader(self, file_base, body_code): """Generates a code.Code object for a header file Parameters: - |file_base| - the base of the filename, e.g. 'foo' (for 'foo.h') - |body_code| - the code to put in between the multiple inclusion guards""" c = code.Code() c.Append(cpp_util.CHROMIUM_LICENSE) c.Append() c.Append(cpp_util.GENERATED_BUNDLE_FILE_MESSAGE % SOURCE_BASE_PATH) ifndef_name = cpp_util.GenerateIfndefName(SOURCE_BASE_PATH, file_base) c.Append() c.Append('#ifndef %s' % ifndef_name) c.Append('#define %s' % ifndef_name) c.Append('#pragma once') c.Append() c.Concat(body_code) c.Append() c.Append('#endif // %s' % ifndef_name) c.Append() return c
[ "def", "GenerateHeader", "(", "self", ",", "file_base", ",", "body_code", ")", ":", "c", "=", "code", ".", "Code", "(", ")", "c", ".", "Append", "(", "cpp_util", ".", "CHROMIUM_LICENSE", ")", "c", ".", "Append", "(", ")", "c", ".", "Append", "(", "cpp_util", ".", "GENERATED_BUNDLE_FILE_MESSAGE", "%", "SOURCE_BASE_PATH", ")", "ifndef_name", "=", "cpp_util", ".", "GenerateIfndefName", "(", "SOURCE_BASE_PATH", ",", "file_base", ")", "c", ".", "Append", "(", ")", "c", ".", "Append", "(", "'#ifndef %s'", "%", "ifndef_name", ")", "c", ".", "Append", "(", "'#define %s'", "%", "ifndef_name", ")", "c", ".", "Append", "(", "'#pragma once'", ")", "c", ".", "Append", "(", ")", "c", ".", "Concat", "(", "body_code", ")", "c", ".", "Append", "(", ")", "c", ".", "Append", "(", "'#endif // %s'", "%", "ifndef_name", ")", "c", ".", "Append", "(", ")", "return", "c" ]
https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/tools/json_schema_compiler/schema_bundle_generator.py#L24-L44
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/nntplib.py
python
NNTP.xhdr
(self, hdr, str, file=None)
return resp, lines
Process an XHDR command (optional server extension). Arguments: - hdr: the header type (e.g. 'subject') - str: an article nr, a message id, or a range nr1-nr2 Returns: - resp: server response if successful - list: list of (nr, value) strings
Process an XHDR command (optional server extension). Arguments: - hdr: the header type (e.g. 'subject') - str: an article nr, a message id, or a range nr1-nr2 Returns: - resp: server response if successful - list: list of (nr, value) strings
[ "Process", "an", "XHDR", "command", "(", "optional", "server", "extension", ")", ".", "Arguments", ":", "-", "hdr", ":", "the", "header", "type", "(", "e", ".", "g", ".", "subject", ")", "-", "str", ":", "an", "article", "nr", "a", "message", "id", "or", "a", "range", "nr1", "-", "nr2", "Returns", ":", "-", "resp", ":", "server", "response", "if", "successful", "-", "list", ":", "list", "of", "(", "nr", "value", ")", "strings" ]
def xhdr(self, hdr, str, file=None): """Process an XHDR command (optional server extension). Arguments: - hdr: the header type (e.g. 'subject') - str: an article nr, a message id, or a range nr1-nr2 Returns: - resp: server response if successful - list: list of (nr, value) strings""" pat = re.compile('^([0-9]+) ?(.*)\n?') resp, lines = self.longcmd('XHDR ' + hdr + ' ' + str, file) for i in range(len(lines)): line = lines[i] m = pat.match(line) if m: lines[i] = m.group(1, 2) return resp, lines
[ "def", "xhdr", "(", "self", ",", "hdr", ",", "str", ",", "file", "=", "None", ")", ":", "pat", "=", "re", ".", "compile", "(", "'^([0-9]+) ?(.*)\\n?'", ")", "resp", ",", "lines", "=", "self", ".", "longcmd", "(", "'XHDR '", "+", "hdr", "+", "' '", "+", "str", ",", "file", ")", "for", "i", "in", "range", "(", "len", "(", "lines", ")", ")", ":", "line", "=", "lines", "[", "i", "]", "m", "=", "pat", ".", "match", "(", "line", ")", "if", "m", ":", "lines", "[", "i", "]", "=", "m", ".", "group", "(", "1", ",", "2", ")", "return", "resp", ",", "lines" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/nntplib.py#L452-L467
gem5/gem5
141cc37c2d4b93959d4c249b8f7e6a8b2ef75338
src/python/m5/ext/pyfdt/pyfdt.py
python
FdtPropertyBytes.json_represent
(self, depth=0)
return result
Ouput JSON
Ouput JSON
[ "Ouput", "JSON" ]
def json_represent(self, depth=0): """Ouput JSON""" result = '%s: ["bytes", "' % json.dumps(self.name) result += '", "'.join(["%02x" % byte for byte in self.bytes]) result += '"]' return result
[ "def", "json_represent", "(", "self", ",", "depth", "=", "0", ")", ":", "result", "=", "'%s: [\"bytes\", \"'", "%", "json", ".", "dumps", "(", "self", ".", "name", ")", "result", "+=", "'\", \"'", ".", "join", "(", "[", "\"%02x\"", "%", "byte", "for", "byte", "in", "self", ".", "bytes", "]", ")", "result", "+=", "'\"]'", "return", "result" ]
https://github.com/gem5/gem5/blob/141cc37c2d4b93959d4c249b8f7e6a8b2ef75338/src/python/m5/ext/pyfdt/pyfdt.py#L364-L370
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_core.py
python
NavigationKeyEvent.SetFromTab
(*args, **kwargs)
return _core_.NavigationKeyEvent_SetFromTab(*args, **kwargs)
SetFromTab(self, bool bIs) Set to true under MSW if the event was generated using the tab key. This is required for proper navogation over radio buttons.
SetFromTab(self, bool bIs)
[ "SetFromTab", "(", "self", "bool", "bIs", ")" ]
def SetFromTab(*args, **kwargs): """ SetFromTab(self, bool bIs) Set to true under MSW if the event was generated using the tab key. This is required for proper navogation over radio buttons. """ return _core_.NavigationKeyEvent_SetFromTab(*args, **kwargs)
[ "def", "SetFromTab", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "NavigationKeyEvent_SetFromTab", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L7275-L7282
htcondor/htcondor
4829724575176d1d6c936e4693dfd78a728569b0
src/condor_contrib/condor_pigeon/src/condor_pigeon_client/skype_linux_tools/Skype4Py/skype.py
python
ISkypeEvents.ConnectionStatus
(self, Status)
This event is caused by a connection status change. @param Status: New connection status. @type Status: L{Connection status<enums.conUnknown>}
This event is caused by a connection status change.
[ "This", "event", "is", "caused", "by", "a", "connection", "status", "change", "." ]
def ConnectionStatus(self, Status): '''This event is caused by a connection status change. @param Status: New connection status. @type Status: L{Connection status<enums.conUnknown>} '''
[ "def", "ConnectionStatus", "(", "self", ",", "Status", ")", ":" ]
https://github.com/htcondor/htcondor/blob/4829724575176d1d6c936e4693dfd78a728569b0/src/condor_contrib/condor_pigeon/src/condor_pigeon_client/skype_linux_tools/Skype4Py/skype.py#L1496-L1501
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
tools/code_coverage/croc.py
python
Coverage.__init__
(self)
Constructor.
Constructor.
[ "Constructor", "." ]
def __init__(self): """Constructor.""" self.files = {} # Map filename --> CoverageFile self.root_dirs = [] # (root, altname) self.rules = [] # (regexp, dict of RHS attrs) self.tree = CoveredDir('') self.print_stats = [] # Dicts of args to PrintStat() # Functions which need to be replaced for unit testing self.add_files_walk = os.walk # Walk function for AddFiles() self.scan_file = croc_scan.ScanFile
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "files", "=", "{", "}", "# Map filename --> CoverageFile", "self", ".", "root_dirs", "=", "[", "]", "# (root, altname)", "self", ".", "rules", "=", "[", "]", "# (regexp, dict of RHS attrs)", "self", ".", "tree", "=", "CoveredDir", "(", "''", ")", "self", ".", "print_stats", "=", "[", "]", "# Dicts of args to PrintStat()", "# Functions which need to be replaced for unit testing", "self", ".", "add_files_walk", "=", "os", ".", "walk", "# Walk function for AddFiles()", "self", ".", "scan_file", "=", "croc_scan", ".", "ScanFile" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/code_coverage/croc.py#L168-L178
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/build/waf-1.7.13/waflib/Build.py
python
BuildContext.get_all_task_gen
(self)
return lst
Utility method, returns a list of all task generators - if you need something more complicated, implement your own
Utility method, returns a list of all task generators - if you need something more complicated, implement your own
[ "Utility", "method", "returns", "a", "list", "of", "all", "task", "generators", "-", "if", "you", "need", "something", "more", "complicated", "implement", "your", "own" ]
def get_all_task_gen(self): """ Utility method, returns a list of all task generators - if you need something more complicated, implement your own """ lst = [] for g in self.groups: lst.extend(t for t in g if isinstance(t, TaskGen.task_gen)) return lst
[ "def", "get_all_task_gen", "(", "self", ")", ":", "lst", "=", "[", "]", "for", "g", "in", "self", ".", "groups", ":", "lst", ".", "extend", "(", "t", "for", "t", "in", "g", "if", "isinstance", "(", "t", ",", "TaskGen", ".", "task_gen", ")", ")", "return", "lst" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/build/waf-1.7.13/waflib/Build.py#L740-L747
ideawu/ssdb-rocks
a3cbb322cafb2f493252829c608e2239df98c9ac
deps/rocksdb-master/linters/cpp_linter/cpplint.py
python
CheckIncludeLine
(filename, clean_lines, linenum, include_state, error)
Check rules that are applicable to #include lines. Strings on #include lines are NOT removed from elided line, to make certain tasks easier. However, to prevent false positives, checks applicable to #include lines in CheckLanguage must be put here. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. include_state: An _IncludeState instance in which the headers are inserted. error: The function to call with any errors found.
Check rules that are applicable to #include lines.
[ "Check", "rules", "that", "are", "applicable", "to", "#include", "lines", "." ]
def CheckIncludeLine(filename, clean_lines, linenum, include_state, error): """Check rules that are applicable to #include lines. Strings on #include lines are NOT removed from elided line, to make certain tasks easier. However, to prevent false positives, checks applicable to #include lines in CheckLanguage must be put here. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. include_state: An _IncludeState instance in which the headers are inserted. error: The function to call with any errors found. """ fileinfo = FileInfo(filename) line = clean_lines.lines[linenum] # "include" should use the new style "foo/bar.h" instead of just "bar.h" if _RE_PATTERN_INCLUDE_NEW_STYLE.search(line): error(filename, linenum, 'build/include', 4, 'Include the directory when naming .h files') # we shouldn't include a file more than once. actually, there are a # handful of instances where doing so is okay, but in general it's # not. match = _RE_PATTERN_INCLUDE.search(line) if match: include = match.group(2) is_system = (match.group(1) == '<') if include in include_state: error(filename, linenum, 'build/include', 4, '"%s" already included at %s:%s' % (include, filename, include_state[include])) else: include_state[include] = linenum # We want to ensure that headers appear in the right order: # 1) for foo.cc, foo.h (preferred location) # 2) c system files # 3) cpp system files # 4) for foo.cc, foo.h (deprecated location) # 5) other google headers # # We classify each include statement as one of those 5 types # using a number of techniques. The include_state object keeps # track of the highest type seen, and complains if we see a # lower type after that. error_message = include_state.CheckNextIncludeOrder( _ClassifyInclude(fileinfo, include, is_system)) if error_message: error(filename, linenum, 'build/include_order', 4, '%s. Should be: %s.h, c system, c++ system, other.' % (error_message, fileinfo.BaseName())) canonical_include = include_state.CanonicalizeAlphabeticalOrder(include) if not include_state.IsInAlphabeticalOrder( clean_lines, linenum, canonical_include): error(filename, linenum, 'build/include_alpha', 4, 'Include "%s" not in alphabetical order' % include) include_state.SetLastHeader(canonical_include) # Look for any of the stream classes that are part of standard C++. match = _RE_PATTERN_INCLUDE.match(line) if match: include = match.group(2) if Match(r'(f|ind|io|i|o|parse|pf|stdio|str|)?stream$', include): # Many unit tests use cout, so we exempt them. if not _IsTestFilename(filename): error(filename, linenum, 'readability/streams', 3, 'Streams are highly discouraged.')
[ "def", "CheckIncludeLine", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "include_state", ",", "error", ")", ":", "fileinfo", "=", "FileInfo", "(", "filename", ")", "line", "=", "clean_lines", ".", "lines", "[", "linenum", "]", "# \"include\" should use the new style \"foo/bar.h\" instead of just \"bar.h\"", "if", "_RE_PATTERN_INCLUDE_NEW_STYLE", ".", "search", "(", "line", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'build/include'", ",", "4", ",", "'Include the directory when naming .h files'", ")", "# we shouldn't include a file more than once. actually, there are a", "# handful of instances where doing so is okay, but in general it's", "# not.", "match", "=", "_RE_PATTERN_INCLUDE", ".", "search", "(", "line", ")", "if", "match", ":", "include", "=", "match", ".", "group", "(", "2", ")", "is_system", "=", "(", "match", ".", "group", "(", "1", ")", "==", "'<'", ")", "if", "include", "in", "include_state", ":", "error", "(", "filename", ",", "linenum", ",", "'build/include'", ",", "4", ",", "'\"%s\" already included at %s:%s'", "%", "(", "include", ",", "filename", ",", "include_state", "[", "include", "]", ")", ")", "else", ":", "include_state", "[", "include", "]", "=", "linenum", "# We want to ensure that headers appear in the right order:", "# 1) for foo.cc, foo.h (preferred location)", "# 2) c system files", "# 3) cpp system files", "# 4) for foo.cc, foo.h (deprecated location)", "# 5) other google headers", "#", "# We classify each include statement as one of those 5 types", "# using a number of techniques. The include_state object keeps", "# track of the highest type seen, and complains if we see a", "# lower type after that.", "error_message", "=", "include_state", ".", "CheckNextIncludeOrder", "(", "_ClassifyInclude", "(", "fileinfo", ",", "include", ",", "is_system", ")", ")", "if", "error_message", ":", "error", "(", "filename", ",", "linenum", ",", "'build/include_order'", ",", "4", ",", "'%s. Should be: %s.h, c system, c++ system, other.'", "%", "(", "error_message", ",", "fileinfo", ".", "BaseName", "(", ")", ")", ")", "canonical_include", "=", "include_state", ".", "CanonicalizeAlphabeticalOrder", "(", "include", ")", "if", "not", "include_state", ".", "IsInAlphabeticalOrder", "(", "clean_lines", ",", "linenum", ",", "canonical_include", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'build/include_alpha'", ",", "4", ",", "'Include \"%s\" not in alphabetical order'", "%", "include", ")", "include_state", ".", "SetLastHeader", "(", "canonical_include", ")", "# Look for any of the stream classes that are part of standard C++.", "match", "=", "_RE_PATTERN_INCLUDE", ".", "match", "(", "line", ")", "if", "match", ":", "include", "=", "match", ".", "group", "(", "2", ")", "if", "Match", "(", "r'(f|ind|io|i|o|parse|pf|stdio|str|)?stream$'", ",", "include", ")", ":", "# Many unit tests use cout, so we exempt them.", "if", "not", "_IsTestFilename", "(", "filename", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'readability/streams'", ",", "3", ",", "'Streams are highly discouraged.'", ")" ]
https://github.com/ideawu/ssdb-rocks/blob/a3cbb322cafb2f493252829c608e2239df98c9ac/deps/rocksdb-master/linters/cpp_linter/cpplint.py#L3582-L3651
intel/caffe
3f494b442ee3f9d17a07b09ecbd5fa2bbda00836
examples/pycaffe/layers/pascal_multilabel_datalayers.py
python
load_pascal_annotation
(index, pascal_root)
return {'boxes': boxes, 'gt_classes': gt_classes, 'gt_overlaps': overlaps, 'flipped': False, 'index': index}
This code is borrowed from Ross Girshick's FAST-RCNN code (https://github.com/rbgirshick/fast-rcnn). It parses the PASCAL .xml metadata files. See publication for further details: (http://arxiv.org/abs/1504.08083). Thanks Ross!
This code is borrowed from Ross Girshick's FAST-RCNN code (https://github.com/rbgirshick/fast-rcnn). It parses the PASCAL .xml metadata files. See publication for further details: (http://arxiv.org/abs/1504.08083).
[ "This", "code", "is", "borrowed", "from", "Ross", "Girshick", "s", "FAST", "-", "RCNN", "code", "(", "https", ":", "//", "github", ".", "com", "/", "rbgirshick", "/", "fast", "-", "rcnn", ")", ".", "It", "parses", "the", "PASCAL", ".", "xml", "metadata", "files", ".", "See", "publication", "for", "further", "details", ":", "(", "http", ":", "//", "arxiv", ".", "org", "/", "abs", "/", "1504", ".", "08083", ")", "." ]
def load_pascal_annotation(index, pascal_root): """ This code is borrowed from Ross Girshick's FAST-RCNN code (https://github.com/rbgirshick/fast-rcnn). It parses the PASCAL .xml metadata files. See publication for further details: (http://arxiv.org/abs/1504.08083). Thanks Ross! """ classes = ('__background__', # always index 0 'aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat', 'chair', 'cow', 'diningtable', 'dog', 'horse', 'motorbike', 'person', 'pottedplant', 'sheep', 'sofa', 'train', 'tvmonitor') class_to_ind = dict(zip(classes, xrange(21))) filename = osp.join(pascal_root, 'Annotations', index + '.xml') # print 'Loading: {}'.format(filename) def get_data_from_tag(node, tag): return node.getElementsByTagName(tag)[0].childNodes[0].data with open(filename) as f: data = minidom.parseString(f.read()) objs = data.getElementsByTagName('object') num_objs = len(objs) boxes = np.zeros((num_objs, 4), dtype=np.uint16) gt_classes = np.zeros((num_objs), dtype=np.int32) overlaps = np.zeros((num_objs, 21), dtype=np.float32) # Load object bounding boxes into a data frame. for ix, obj in enumerate(objs): # Make pixel indexes 0-based x1 = float(get_data_from_tag(obj, 'xmin')) - 1 y1 = float(get_data_from_tag(obj, 'ymin')) - 1 x2 = float(get_data_from_tag(obj, 'xmax')) - 1 y2 = float(get_data_from_tag(obj, 'ymax')) - 1 cls = class_to_ind[ str(get_data_from_tag(obj, "name")).lower().strip()] boxes[ix, :] = [x1, y1, x2, y2] gt_classes[ix] = cls overlaps[ix, cls] = 1.0 overlaps = scipy.sparse.csr_matrix(overlaps) return {'boxes': boxes, 'gt_classes': gt_classes, 'gt_overlaps': overlaps, 'flipped': False, 'index': index}
[ "def", "load_pascal_annotation", "(", "index", ",", "pascal_root", ")", ":", "classes", "=", "(", "'__background__'", ",", "# always index 0", "'aeroplane'", ",", "'bicycle'", ",", "'bird'", ",", "'boat'", ",", "'bottle'", ",", "'bus'", ",", "'car'", ",", "'cat'", ",", "'chair'", ",", "'cow'", ",", "'diningtable'", ",", "'dog'", ",", "'horse'", ",", "'motorbike'", ",", "'person'", ",", "'pottedplant'", ",", "'sheep'", ",", "'sofa'", ",", "'train'", ",", "'tvmonitor'", ")", "class_to_ind", "=", "dict", "(", "zip", "(", "classes", ",", "xrange", "(", "21", ")", ")", ")", "filename", "=", "osp", ".", "join", "(", "pascal_root", ",", "'Annotations'", ",", "index", "+", "'.xml'", ")", "# print 'Loading: {}'.format(filename)", "def", "get_data_from_tag", "(", "node", ",", "tag", ")", ":", "return", "node", ".", "getElementsByTagName", "(", "tag", ")", "[", "0", "]", ".", "childNodes", "[", "0", "]", ".", "data", "with", "open", "(", "filename", ")", "as", "f", ":", "data", "=", "minidom", ".", "parseString", "(", "f", ".", "read", "(", ")", ")", "objs", "=", "data", ".", "getElementsByTagName", "(", "'object'", ")", "num_objs", "=", "len", "(", "objs", ")", "boxes", "=", "np", ".", "zeros", "(", "(", "num_objs", ",", "4", ")", ",", "dtype", "=", "np", ".", "uint16", ")", "gt_classes", "=", "np", ".", "zeros", "(", "(", "num_objs", ")", ",", "dtype", "=", "np", ".", "int32", ")", "overlaps", "=", "np", ".", "zeros", "(", "(", "num_objs", ",", "21", ")", ",", "dtype", "=", "np", ".", "float32", ")", "# Load object bounding boxes into a data frame.", "for", "ix", ",", "obj", "in", "enumerate", "(", "objs", ")", ":", "# Make pixel indexes 0-based", "x1", "=", "float", "(", "get_data_from_tag", "(", "obj", ",", "'xmin'", ")", ")", "-", "1", "y1", "=", "float", "(", "get_data_from_tag", "(", "obj", ",", "'ymin'", ")", ")", "-", "1", "x2", "=", "float", "(", "get_data_from_tag", "(", "obj", ",", "'xmax'", ")", ")", "-", "1", "y2", "=", "float", "(", "get_data_from_tag", "(", "obj", ",", "'ymax'", ")", ")", "-", "1", "cls", "=", "class_to_ind", "[", "str", "(", "get_data_from_tag", "(", "obj", ",", "\"name\"", ")", ")", ".", "lower", "(", ")", ".", "strip", "(", ")", "]", "boxes", "[", "ix", ",", ":", "]", "=", "[", "x1", ",", "y1", ",", "x2", ",", "y2", "]", "gt_classes", "[", "ix", "]", "=", "cls", "overlaps", "[", "ix", ",", "cls", "]", "=", "1.0", "overlaps", "=", "scipy", ".", "sparse", ".", "csr_matrix", "(", "overlaps", ")", "return", "{", "'boxes'", ":", "boxes", ",", "'gt_classes'", ":", "gt_classes", ",", "'gt_overlaps'", ":", "overlaps", ",", "'flipped'", ":", "False", ",", "'index'", ":", "index", "}" ]
https://github.com/intel/caffe/blob/3f494b442ee3f9d17a07b09ecbd5fa2bbda00836/examples/pycaffe/layers/pascal_multilabel_datalayers.py#L176-L229
hughperkins/tf-coriander
970d3df6c11400ad68405f22b0c42a52374e94ca
tensorflow/python/lib/io/tf_record.py
python
TFRecordWriter.close
(self)
Close the file.
Close the file.
[ "Close", "the", "file", "." ]
def close(self): """Close the file.""" self._writer.Close()
[ "def", "close", "(", "self", ")", ":", "self", ".", "_writer", ".", "Close", "(", ")" ]
https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/lib/io/tf_record.py#L122-L124
cms-sw/cmssw
fd9de012d503d3405420bcbeec0ec879baa57cf2
CondCore/Utilities/scripts/uploadConditions.py
python
HTTP.query
(self, url, data = None, files = None, keepCookies = True)
Queries a URL, optionally with some data (dictionary). If no data is specified, a GET request will be used. If some data is specified, a POST request will be used. If files is specified, it must be a dictionary like data but the values are filenames. By default, cookies are kept in-between requests. A HTTPError exception is raised if the response's HTTP code is not 200.
Queries a URL, optionally with some data (dictionary).
[ "Queries", "a", "URL", "optionally", "with", "some", "data", "(", "dictionary", ")", "." ]
def query(self, url, data = None, files = None, keepCookies = True): '''Queries a URL, optionally with some data (dictionary). If no data is specified, a GET request will be used. If some data is specified, a POST request will be used. If files is specified, it must be a dictionary like data but the values are filenames. By default, cookies are kept in-between requests. A HTTPError exception is raised if the response's HTTP code is not 200. ''' if not keepCookies: self.discardCookies() url = self.baseUrl + url # make sure the logs are safe ... at least somewhat :) data4log = copy.copy(data) if data4log: if 'password' in data4log.keys(): data4log['password'] = '*' retries = [0] + list(self.retries) while True: logging.debug('Querying %s with data %s and files %s (retries left: %s, current sleep: %s)...', url, data4log, files, len(retries), retries[0]) time.sleep(retries.pop(0)) try: self.curl.setopt(self.curl.URL, url) self.curl.setopt(self.curl.HTTPGET, 1) # from now on we use the token we got from the login self.curl.setopt(pycurl.USERPWD, '%s:""' % ( str(self.token), ) ) self.curl.setopt(pycurl.HTTPHEADER, ['Accept: application/json']) if data is not None or files is not None: # If there is data or files to send, use a POST request finalData = {} if data is not None: finalData.update(data) if files is not None: for (key, fileName) in files.items(): finalData[key] = (self.curl.FORM_FILE, fileName) self.curl.setopt( self.curl.HTTPPOST, list(finalData.items()) ) self.curl.setopt(pycurl.VERBOSE, 0) response = io.BytesIO() self.curl.setopt(self.curl.WRITEFUNCTION, response.write) self.curl.perform() code = self.curl.getinfo(self.curl.RESPONSE_CODE) if code in self.retryCodes and len(retries) > 0: logging.debug('Retrying since we got the %s error code...', code) continue if code != 200: raise HTTPError(code, response.getvalue()) return response.getvalue() except pycurl.error as e: if len(retries) == 0: raise e logging.debug('Retrying since we got the %s pycurl exception...', str(e))
[ "def", "query", "(", "self", ",", "url", ",", "data", "=", "None", ",", "files", "=", "None", ",", "keepCookies", "=", "True", ")", ":", "if", "not", "keepCookies", ":", "self", ".", "discardCookies", "(", ")", "url", "=", "self", ".", "baseUrl", "+", "url", "# make sure the logs are safe ... at least somewhat :)", "data4log", "=", "copy", ".", "copy", "(", "data", ")", "if", "data4log", ":", "if", "'password'", "in", "data4log", ".", "keys", "(", ")", ":", "data4log", "[", "'password'", "]", "=", "'*'", "retries", "=", "[", "0", "]", "+", "list", "(", "self", ".", "retries", ")", "while", "True", ":", "logging", ".", "debug", "(", "'Querying %s with data %s and files %s (retries left: %s, current sleep: %s)...'", ",", "url", ",", "data4log", ",", "files", ",", "len", "(", "retries", ")", ",", "retries", "[", "0", "]", ")", "time", ".", "sleep", "(", "retries", ".", "pop", "(", "0", ")", ")", "try", ":", "self", ".", "curl", ".", "setopt", "(", "self", ".", "curl", ".", "URL", ",", "url", ")", "self", ".", "curl", ".", "setopt", "(", "self", ".", "curl", ".", "HTTPGET", ",", "1", ")", "# from now on we use the token we got from the login", "self", ".", "curl", ".", "setopt", "(", "pycurl", ".", "USERPWD", ",", "'%s:\"\"'", "%", "(", "str", "(", "self", ".", "token", ")", ",", ")", ")", "self", ".", "curl", ".", "setopt", "(", "pycurl", ".", "HTTPHEADER", ",", "[", "'Accept: application/json'", "]", ")", "if", "data", "is", "not", "None", "or", "files", "is", "not", "None", ":", "# If there is data or files to send, use a POST request", "finalData", "=", "{", "}", "if", "data", "is", "not", "None", ":", "finalData", ".", "update", "(", "data", ")", "if", "files", "is", "not", "None", ":", "for", "(", "key", ",", "fileName", ")", "in", "files", ".", "items", "(", ")", ":", "finalData", "[", "key", "]", "=", "(", "self", ".", "curl", ".", "FORM_FILE", ",", "fileName", ")", "self", ".", "curl", ".", "setopt", "(", "self", ".", "curl", ".", "HTTPPOST", ",", "list", "(", "finalData", ".", "items", "(", ")", ")", ")", "self", ".", "curl", ".", "setopt", "(", "pycurl", ".", "VERBOSE", ",", "0", ")", "response", "=", "io", ".", "BytesIO", "(", ")", "self", ".", "curl", ".", "setopt", "(", "self", ".", "curl", ".", "WRITEFUNCTION", ",", "response", ".", "write", ")", "self", ".", "curl", ".", "perform", "(", ")", "code", "=", "self", ".", "curl", ".", "getinfo", "(", "self", ".", "curl", ".", "RESPONSE_CODE", ")", "if", "code", "in", "self", ".", "retryCodes", "and", "len", "(", "retries", ")", ">", "0", ":", "logging", ".", "debug", "(", "'Retrying since we got the %s error code...'", ",", "code", ")", "continue", "if", "code", "!=", "200", ":", "raise", "HTTPError", "(", "code", ",", "response", ".", "getvalue", "(", ")", ")", "return", "response", ".", "getvalue", "(", ")", "except", "pycurl", ".", "error", "as", "e", ":", "if", "len", "(", "retries", ")", "==", "0", ":", "raise", "e", "logging", ".", "debug", "(", "'Retrying since we got the %s pycurl exception...'", ",", "str", "(", "e", ")", ")" ]
https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/CondCore/Utilities/scripts/uploadConditions.py#L351-L424
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/keras/distribute/distribute_coordinator_utils.py
python
_WorkerContext.has_barrier
(self)
return self._worker_barrier is not None
Whether the barrier is set or not.
Whether the barrier is set or not.
[ "Whether", "the", "barrier", "is", "set", "or", "not", "." ]
def has_barrier(self): """Whether the barrier is set or not.""" return self._worker_barrier is not None
[ "def", "has_barrier", "(", "self", ")", ":", "return", "self", ".", "_worker_barrier", "is", "not", "None" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/keras/distribute/distribute_coordinator_utils.py#L232-L234
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/ops/operations/_quant_ops.py
python
BatchNormFold2.__init__
(self, freeze_bn=0)
Initialize conv2d fold layer
Initialize conv2d fold layer
[ "Initialize", "conv2d", "fold", "layer" ]
def __init__(self, freeze_bn=0): """Initialize conv2d fold layer""" self.freeze_bn = validator.check_value_type('freeze_bn', freeze_bn, (int,), self.name) self.init_prim_io_names(inputs=['x', 'beta', 'gamma', 'batch_std', 'batch_mean', 'running_std', 'running_mean', 'global_step'], outputs=['y'])
[ "def", "__init__", "(", "self", ",", "freeze_bn", "=", "0", ")", ":", "self", ".", "freeze_bn", "=", "validator", ".", "check_value_type", "(", "'freeze_bn'", ",", "freeze_bn", ",", "(", "int", ",", ")", ",", "self", ".", "name", ")", "self", ".", "init_prim_io_names", "(", "inputs", "=", "[", "'x'", ",", "'beta'", ",", "'gamma'", ",", "'batch_std'", ",", "'batch_mean'", ",", "'running_std'", ",", "'running_mean'", ",", "'global_step'", "]", ",", "outputs", "=", "[", "'y'", "]", ")" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/operations/_quant_ops.py#L1264-L1269
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/pathlib.py
python
Path.is_mount
(self)
return ino == parent_ino
Check if this path is a POSIX mount point
Check if this path is a POSIX mount point
[ "Check", "if", "this", "path", "is", "a", "POSIX", "mount", "point" ]
def is_mount(self): """ Check if this path is a POSIX mount point """ # Need to exist and be a dir if not self.exists() or not self.is_dir(): return False try: parent_dev = self.parent.stat().st_dev except OSError: return False dev = self.stat().st_dev if dev != parent_dev: return True ino = self.stat().st_ino parent_ino = self.parent.stat().st_ino return ino == parent_ino
[ "def", "is_mount", "(", "self", ")", ":", "# Need to exist and be a dir", "if", "not", "self", ".", "exists", "(", ")", "or", "not", "self", ".", "is_dir", "(", ")", ":", "return", "False", "try", ":", "parent_dev", "=", "self", ".", "parent", ".", "stat", "(", ")", ".", "st_dev", "except", "OSError", ":", "return", "False", "dev", "=", "self", ".", "stat", "(", ")", ".", "st_dev", "if", "dev", "!=", "parent_dev", ":", "return", "True", "ino", "=", "self", ".", "stat", "(", ")", ".", "st_ino", "parent_ino", "=", "self", ".", "parent", ".", "stat", "(", ")", ".", "st_ino", "return", "ino", "==", "parent_ino" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/pathlib.py#L1467-L1485
l4ka/pistachio
8be66aa9b85a774ad1b71dbd3a79c5c745a96273
contrib/cml2/cmlcompile.py
python
intern_symbol
(input, name=None, oktypes=None, record=0)
return ref
Attempt to read and intern a symbol.
Attempt to read and intern a symbol.
[ "Attempt", "to", "read", "and", "intern", "a", "symbol", "." ]
def intern_symbol(input, name=None, oktypes=None, record=0): "Attempt to read and intern a symbol." if name is None: tok = input.lex_token() if tok.type == "word": name = tok.attr else: input.push_token(tok) return None # If symbol is a constant just pass it through. if name == "y": return cml.y elif name == "m": return cml.m elif name == "n": return cml.n # If we have not seen the symbol before, create an entry for it. if not rulebase.dictionary.has_key(name): ref = rulebase.dictionary[name] = cml.ConfigSymbol(name, None, None, None, input.infile, input.lineno) compstate.explicit_ancestors[ref] = [] else: ref = rulebase.dictionary[name] if ref.type and oktypes is not None and ref.type not in oktypes: input.complain('incompatible previous declaration of %s as %s (see "%s", %d)' % (name, ref.type, ref.file, ref.lineno)) if record: if record: ref.file = input.infile ref.lineno = input.lineno else: input.complain('duplicate symbol %s (see "%s", line %d)' % (name, ref.file, ref.lineno)) return ref
[ "def", "intern_symbol", "(", "input", ",", "name", "=", "None", ",", "oktypes", "=", "None", ",", "record", "=", "0", ")", ":", "if", "name", "is", "None", ":", "tok", "=", "input", ".", "lex_token", "(", ")", "if", "tok", ".", "type", "==", "\"word\"", ":", "name", "=", "tok", ".", "attr", "else", ":", "input", ".", "push_token", "(", "tok", ")", "return", "None", "# If symbol is a constant just pass it through.", "if", "name", "==", "\"y\"", ":", "return", "cml", ".", "y", "elif", "name", "==", "\"m\"", ":", "return", "cml", ".", "m", "elif", "name", "==", "\"n\"", ":", "return", "cml", ".", "n", "# If we have not seen the symbol before, create an entry for it.", "if", "not", "rulebase", ".", "dictionary", ".", "has_key", "(", "name", ")", ":", "ref", "=", "rulebase", ".", "dictionary", "[", "name", "]", "=", "cml", ".", "ConfigSymbol", "(", "name", ",", "None", ",", "None", ",", "None", ",", "input", ".", "infile", ",", "input", ".", "lineno", ")", "compstate", ".", "explicit_ancestors", "[", "ref", "]", "=", "[", "]", "else", ":", "ref", "=", "rulebase", ".", "dictionary", "[", "name", "]", "if", "ref", ".", "type", "and", "oktypes", "is", "not", "None", "and", "ref", ".", "type", "not", "in", "oktypes", ":", "input", ".", "complain", "(", "'incompatible previous declaration of %s as %s (see \"%s\", %d)'", "%", "(", "name", ",", "ref", ".", "type", ",", "ref", ".", "file", ",", "ref", ".", "lineno", ")", ")", "if", "record", ":", "if", "record", ":", "ref", ".", "file", "=", "input", ".", "infile", "ref", ".", "lineno", "=", "input", ".", "lineno", "else", ":", "input", ".", "complain", "(", "'duplicate symbol %s (see \"%s\", line %d)'", "%", "(", "name", ",", "ref", ".", "file", ",", "ref", ".", "lineno", ")", ")", "return", "ref" ]
https://github.com/l4ka/pistachio/blob/8be66aa9b85a774ad1b71dbd3a79c5c745a96273/contrib/cml2/cmlcompile.py#L371-L405
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/jira/client.py
python
JIRA.search_allowed_users_for_issue
(self, user, issueKey=None, projectKey=None, startAt=0, maxResults=50)
return self._fetch_pages(User, None, 'user/viewissue/search', startAt, maxResults, params)
Get a list of user Resources that match a username string and have browse permission for the issue or project. :param user: a string to match usernames against. :param issueKey: find users with browse permission for this issue. :param projectKey: find users with browse permission for this project. :param startAt: index of the first user to return. :param maxResults: maximum number of users to return. If maxResults evaluates as False, it will try to get all items in batches.
Get a list of user Resources that match a username string and have browse permission for the issue or project.
[ "Get", "a", "list", "of", "user", "Resources", "that", "match", "a", "username", "string", "and", "have", "browse", "permission", "for", "the", "issue", "or", "project", "." ]
def search_allowed_users_for_issue(self, user, issueKey=None, projectKey=None, startAt=0, maxResults=50): """Get a list of user Resources that match a username string and have browse permission for the issue or project. :param user: a string to match usernames against. :param issueKey: find users with browse permission for this issue. :param projectKey: find users with browse permission for this project. :param startAt: index of the first user to return. :param maxResults: maximum number of users to return. If maxResults evaluates as False, it will try to get all items in batches. """ params = { 'username': user} if issueKey is not None: params['issueKey'] = issueKey if projectKey is not None: params['projectKey'] = projectKey return self._fetch_pages(User, None, 'user/viewissue/search', startAt, maxResults, params)
[ "def", "search_allowed_users_for_issue", "(", "self", ",", "user", ",", "issueKey", "=", "None", ",", "projectKey", "=", "None", ",", "startAt", "=", "0", ",", "maxResults", "=", "50", ")", ":", "params", "=", "{", "'username'", ":", "user", "}", "if", "issueKey", "is", "not", "None", ":", "params", "[", "'issueKey'", "]", "=", "issueKey", "if", "projectKey", "is", "not", "None", ":", "params", "[", "'projectKey'", "]", "=", "projectKey", "return", "self", ".", "_fetch_pages", "(", "User", ",", "None", ",", "'user/viewissue/search'", ",", "startAt", ",", "maxResults", ",", "params", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/jira/client.py#L2299-L2315
bryanyzhu/Hidden-Two-Stream
f7f684adbdacb6df6b1cf196c3a476cd23484a0f
scripts/cpp_lint.py
python
_OutputFormat
()
return _cpplint_state.output_format
Gets the module's output format.
Gets the module's output format.
[ "Gets", "the", "module", "s", "output", "format", "." ]
def _OutputFormat(): """Gets the module's output format.""" return _cpplint_state.output_format
[ "def", "_OutputFormat", "(", ")", ":", "return", "_cpplint_state", ".", "output_format" ]
https://github.com/bryanyzhu/Hidden-Two-Stream/blob/f7f684adbdacb6df6b1cf196c3a476cd23484a0f/scripts/cpp_lint.py#L767-L769
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/asyncio/windows_events.py
python
IocpProactor._unregister
(self, ov)
Unregister an overlapped object. Call this method when its future has been cancelled. The event can already be signalled (pending in the proactor event queue). It is also safe if the event is never signalled (because it was cancelled).
Unregister an overlapped object.
[ "Unregister", "an", "overlapped", "object", "." ]
def _unregister(self, ov): """Unregister an overlapped object. Call this method when its future has been cancelled. The event can already be signalled (pending in the proactor event queue). It is also safe if the event is never signalled (because it was cancelled). """ self._check_closed() self._unregistered.append(ov)
[ "def", "_unregister", "(", "self", ",", "ov", ")", ":", "self", ".", "_check_closed", "(", ")", "self", ".", "_unregistered", ".", "append", "(", "ov", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/asyncio/windows_events.py#L687-L695
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_gdi.py
python
Font.GetFaceName
(*args, **kwargs)
return _gdi_.Font_GetFaceName(*args, **kwargs)
GetFaceName(self) -> String Returns the typeface name associated with the font, or the empty string if there is no typeface information.
GetFaceName(self) -> String
[ "GetFaceName", "(", "self", ")", "-", ">", "String" ]
def GetFaceName(*args, **kwargs): """ GetFaceName(self) -> String Returns the typeface name associated with the font, or the empty string if there is no typeface information. """ return _gdi_.Font_GetFaceName(*args, **kwargs)
[ "def", "GetFaceName", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gdi_", ".", "Font_GetFaceName", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_gdi.py#L2238-L2245
hpi-xnor/BMXNet
ed0b201da6667887222b8e4b5f997c4f6b61943d
python/mxnet/ndarray/ndarray.py
python
imdecode
(str_img, clip_rect=(0, 0, 0, 0), out=None, index=0, channels=3, mean=None)
DEPRECATED, use mx.img instead Parameters ---------- str_img : str Binary image data clip_rect : iterable of 4 int Clip decoded image to rectangle (x0, y0, x1, y1). out : NDArray Output buffer. Can be 3 dimensional (c, h, w) or 4 dimensional (n, c, h, w). index : int Output decoded image to i-th slice of 4 dimensional buffer. channels : int Number of channels to output. Decode to grey scale when channels = 1. mean : NDArray Subtract mean from decode image before outputing.
DEPRECATED, use mx.img instead
[ "DEPRECATED", "use", "mx", ".", "img", "instead" ]
def imdecode(str_img, clip_rect=(0, 0, 0, 0), out=None, index=0, channels=3, mean=None): """DEPRECATED, use mx.img instead Parameters ---------- str_img : str Binary image data clip_rect : iterable of 4 int Clip decoded image to rectangle (x0, y0, x1, y1). out : NDArray Output buffer. Can be 3 dimensional (c, h, w) or 4 dimensional (n, c, h, w). index : int Output decoded image to i-th slice of 4 dimensional buffer. channels : int Number of channels to output. Decode to grey scale when channels = 1. mean : NDArray Subtract mean from decode image before outputing. """ # pylint: disable= no-member, protected-access, too-many-arguments if mean is None: mean = NDArray(_new_empty_handle()) if out is None: return _internal._imdecode(mean, index, clip_rect[0], clip_rect[1], clip_rect[2], clip_rect[3], channels, len(str_img), str_img=str_img) else: return _internal._imdecode(mean, index, clip_rect[0], clip_rect[1], clip_rect[2], clip_rect[3], channels, len(str_img), str_img=str_img, out=out)
[ "def", "imdecode", "(", "str_img", ",", "clip_rect", "=", "(", "0", ",", "0", ",", "0", ",", "0", ")", ",", "out", "=", "None", ",", "index", "=", "0", ",", "channels", "=", "3", ",", "mean", "=", "None", ")", ":", "# pylint: disable= no-member, protected-access, too-many-arguments", "if", "mean", "is", "None", ":", "mean", "=", "NDArray", "(", "_new_empty_handle", "(", ")", ")", "if", "out", "is", "None", ":", "return", "_internal", ".", "_imdecode", "(", "mean", ",", "index", ",", "clip_rect", "[", "0", "]", ",", "clip_rect", "[", "1", "]", ",", "clip_rect", "[", "2", "]", ",", "clip_rect", "[", "3", "]", ",", "channels", ",", "len", "(", "str_img", ")", ",", "str_img", "=", "str_img", ")", "else", ":", "return", "_internal", ".", "_imdecode", "(", "mean", ",", "index", ",", "clip_rect", "[", "0", "]", ",", "clip_rect", "[", "1", "]", ",", "clip_rect", "[", "2", "]", ",", "clip_rect", "[", "3", "]", ",", "channels", ",", "len", "(", "str_img", ")", ",", "str_img", "=", "str_img", ",", "out", "=", "out", ")" ]
https://github.com/hpi-xnor/BMXNet/blob/ed0b201da6667887222b8e4b5f997c4f6b61943d/python/mxnet/ndarray/ndarray.py#L3312-L3351
apiaryio/snowcrash
b5b39faa85f88ee17459edf39fdc6fe4fc70d2e3
tools/gyp/pylib/gyp/common.py
python
EncodePOSIXShellList
(list)
return ' '.join(encoded_arguments)
Encodes |list| suitably for consumption by POSIX shells. Returns EncodePOSIXShellArgument for each item in list, and joins them together using the space character as an argument separator.
Encodes |list| suitably for consumption by POSIX shells.
[ "Encodes", "|list|", "suitably", "for", "consumption", "by", "POSIX", "shells", "." ]
def EncodePOSIXShellList(list): """Encodes |list| suitably for consumption by POSIX shells. Returns EncodePOSIXShellArgument for each item in list, and joins them together using the space character as an argument separator. """ encoded_arguments = [] for argument in list: encoded_arguments.append(EncodePOSIXShellArgument(argument)) return ' '.join(encoded_arguments)
[ "def", "EncodePOSIXShellList", "(", "list", ")", ":", "encoded_arguments", "=", "[", "]", "for", "argument", "in", "list", ":", "encoded_arguments", ".", "append", "(", "EncodePOSIXShellArgument", "(", "argument", ")", ")", "return", "' '", ".", "join", "(", "encoded_arguments", ")" ]
https://github.com/apiaryio/snowcrash/blob/b5b39faa85f88ee17459edf39fdc6fe4fc70d2e3/tools/gyp/pylib/gyp/common.py#L283-L293
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/stc.py
python
StyledTextCtrl.StyleSetChangeable
(*args, **kwargs)
return _stc.StyledTextCtrl_StyleSetChangeable(*args, **kwargs)
StyleSetChangeable(self, int style, bool changeable) Set a style to be changeable or not (read only). Experimental feature, currently buggy.
StyleSetChangeable(self, int style, bool changeable)
[ "StyleSetChangeable", "(", "self", "int", "style", "bool", "changeable", ")" ]
def StyleSetChangeable(*args, **kwargs): """ StyleSetChangeable(self, int style, bool changeable) Set a style to be changeable or not (read only). Experimental feature, currently buggy. """ return _stc.StyledTextCtrl_StyleSetChangeable(*args, **kwargs)
[ "def", "StyleSetChangeable", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_stc", ".", "StyledTextCtrl_StyleSetChangeable", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/stc.py#L3019-L3026
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/nn/layer/conv.py
python
Conv2d.__init__
(self, in_channels, out_channels, kernel_size, stride=1, pad_mode='same', padding=0, dilation=1, group=1, has_bias=False, weight_init='normal', bias_init='zeros', data_format='NCHW')
Initialize Conv2d.
Initialize Conv2d.
[ "Initialize", "Conv2d", "." ]
def __init__(self, in_channels, out_channels, kernel_size, stride=1, pad_mode='same', padding=0, dilation=1, group=1, has_bias=False, weight_init='normal', bias_init='zeros', data_format='NCHW'): """Initialize Conv2d.""" kernel_size = twice(kernel_size) stride = twice(stride) self._dilation = dilation dilation = twice(dilation) super(Conv2d, self).__init__( in_channels, out_channels, kernel_size, stride, pad_mode, padding, dilation, group, has_bias, weight_init, bias_init, data_format) self.conv2d = P.Conv2D(out_channel=self.out_channels, kernel_size=self.kernel_size, mode=1, pad_mode=self.pad_mode, pad=self.padding, stride=self.stride, dilation=self.dilation, group=self.group, data_format=self.format) self.bias_add = P.BiasAdd(data_format=self.format)
[ "def", "__init__", "(", "self", ",", "in_channels", ",", "out_channels", ",", "kernel_size", ",", "stride", "=", "1", ",", "pad_mode", "=", "'same'", ",", "padding", "=", "0", ",", "dilation", "=", "1", ",", "group", "=", "1", ",", "has_bias", "=", "False", ",", "weight_init", "=", "'normal'", ",", "bias_init", "=", "'zeros'", ",", "data_format", "=", "'NCHW'", ")", ":", "kernel_size", "=", "twice", "(", "kernel_size", ")", "stride", "=", "twice", "(", "stride", ")", "self", ".", "_dilation", "=", "dilation", "dilation", "=", "twice", "(", "dilation", ")", "super", "(", "Conv2d", ",", "self", ")", ".", "__init__", "(", "in_channels", ",", "out_channels", ",", "kernel_size", ",", "stride", ",", "pad_mode", ",", "padding", ",", "dilation", ",", "group", ",", "has_bias", ",", "weight_init", ",", "bias_init", ",", "data_format", ")", "self", ".", "conv2d", "=", "P", ".", "Conv2D", "(", "out_channel", "=", "self", ".", "out_channels", ",", "kernel_size", "=", "self", ".", "kernel_size", ",", "mode", "=", "1", ",", "pad_mode", "=", "self", ".", "pad_mode", ",", "pad", "=", "self", ".", "padding", ",", "stride", "=", "self", ".", "stride", ",", "dilation", "=", "self", ".", "dilation", ",", "group", "=", "self", ".", "group", ",", "data_format", "=", "self", ".", "format", ")", "self", ".", "bias_add", "=", "P", ".", "BiasAdd", "(", "data_format", "=", "self", ".", "format", ")" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/nn/layer/conv.py#L223-L263
kamyu104/LeetCode-Solutions
77605708a927ea3b85aee5a479db733938c7c211
Python/minimum-number-of-operations-to-reinitialize-a-permutation.py
python
Solution2.reinitializePermutation
(self, n)
return result
:type n: int :rtype: int
:type n: int :rtype: int
[ ":", "type", "n", ":", "int", ":", "rtype", ":", "int" ]
def reinitializePermutation(self, n): """ :type n: int :rtype: int """ if n == 2: return 1 result, i = 0, 1 while not result or i != 1: i = (i*2)%(n-1) result += 1 return result
[ "def", "reinitializePermutation", "(", "self", ",", "n", ")", ":", "if", "n", "==", "2", ":", "return", "1", "result", ",", "i", "=", "0", ",", "1", "while", "not", "result", "or", "i", "!=", "1", ":", "i", "=", "(", "i", "*", "2", ")", "%", "(", "n", "-", "1", ")", "result", "+=", "1", "return", "result" ]
https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/minimum-number-of-operations-to-reinitialize-a-permutation.py#L34-L45
LiquidPlayer/LiquidCore
9405979363f2353ac9a71ad8ab59685dd7f919c9
deps/boost_1_66_0/tools/build/src/util/set.py
python
intersection
(set1, set2)
return result
Removes from set1 any items which don't appear in set2 and returns the result.
Removes from set1 any items which don't appear in set2 and returns the result.
[ "Removes", "from", "set1", "any", "items", "which", "don", "t", "appear", "in", "set2", "and", "returns", "the", "result", "." ]
def intersection (set1, set2): """ Removes from set1 any items which don't appear in set2 and returns the result. """ assert is_iterable(set1) assert is_iterable(set2) result = [] for v in set1: if v in set2: result.append (v) return result
[ "def", "intersection", "(", "set1", ",", "set2", ")", ":", "assert", "is_iterable", "(", "set1", ")", "assert", "is_iterable", "(", "set2", ")", "result", "=", "[", "]", "for", "v", "in", "set1", ":", "if", "v", "in", "set2", ":", "result", ".", "append", "(", "v", ")", "return", "result" ]
https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/boost_1_66_0/tools/build/src/util/set.py#L20-L29
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/apitools/apitools/base/py/app2.py
python
CommandLoop.onecmd
(self, line)
return False
Process a single command. Runs a single command, and stores the return code in self._last_return_code. Always returns False unless the command was EOF. Args: line: (str) Command line to process. Returns: A bool signaling whether or not the command loop should terminate.
Process a single command.
[ "Process", "a", "single", "command", "." ]
def onecmd(self, line): """Process a single command. Runs a single command, and stores the return code in self._last_return_code. Always returns False unless the command was EOF. Args: line: (str) Command line to process. Returns: A bool signaling whether or not the command loop should terminate. """ try: self._last_return_code = cmd.Cmd.onecmd(self, line) except CommandLoop.TerminateSignal: return True except BaseException as e: name = line.split(' ')[0] print('Error running %s:' % name) print(e) self._last_return_code = 1 return False
[ "def", "onecmd", "(", "self", ",", "line", ")", ":", "try", ":", "self", ".", "_last_return_code", "=", "cmd", ".", "Cmd", ".", "onecmd", "(", "self", ",", "line", ")", "except", "CommandLoop", ".", "TerminateSignal", ":", "return", "True", "except", "BaseException", "as", "e", ":", "name", "=", "line", ".", "split", "(", "' '", ")", "[", "0", "]", "print", "(", "'Error running %s:'", "%", "name", ")", "print", "(", "e", ")", "self", ".", "_last_return_code", "=", "1", "return", "False" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/apitools/apitools/base/py/app2.py#L262-L284
google/mysql-protobuf
467cda676afaa49e762c5c9164a43f6ad31a1fbf
protobuf/python/mox.py
python
IsA.equals
(self, rhs)
Check to see if the RHS is an instance of class_name. Args: # rhs: the right hand side of the test rhs: object Returns: bool
Check to see if the RHS is an instance of class_name.
[ "Check", "to", "see", "if", "the", "RHS", "is", "an", "instance", "of", "class_name", "." ]
def equals(self, rhs): """Check to see if the RHS is an instance of class_name. Args: # rhs: the right hand side of the test rhs: object Returns: bool """ try: return isinstance(rhs, self._class_name) except TypeError: # Check raw types if there was a type error. This is helpful for # things like cStringIO.StringIO. return type(rhs) == type(self._class_name)
[ "def", "equals", "(", "self", ",", "rhs", ")", ":", "try", ":", "return", "isinstance", "(", "rhs", ",", "self", ".", "_class_name", ")", "except", "TypeError", ":", "# Check raw types if there was a type error. This is helpful for", "# things like cStringIO.StringIO.", "return", "type", "(", "rhs", ")", "==", "type", "(", "self", ".", "_class_name", ")" ]
https://github.com/google/mysql-protobuf/blob/467cda676afaa49e762c5c9164a43f6ad31a1fbf/protobuf/python/mox.py#L807-L823
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemFramework/v1/ResourceManager/lib/Crypto/Util/number.py
python
getStrongPrime
(N, e=0, false_positive_prob=1e-6, randfunc=None)
return X
r""" Return a random strong *N*-bit prime number. In this context, *p* is a strong prime if *p-1* and *p+1* have at least one large prime factor. Args: N (integer): the exact length of the strong prime. It must be a multiple of 128 and > 512. e (integer): if provided, the returned prime (minus 1) will be coprime to *e* and thus suitable for RSA where *e* is the public exponent. false_positive_prob (float): The statistical probability for the result not to be actually a prime. It defaults to 10\ :sup:`-6`. Note that the real probability of a false-positive is far less. This is just the mathematically provable limit. randfunc (callable): A function that takes a parameter *N* and that returns a random byte string of such length. If omitted, :func:`Crypto.Random.get_random_bytes` is used. Return: The new strong prime. .. deprecated:: 3.0 This function is for internal use only and may be renamed or removed in the future.
r""" Return a random strong *N*-bit prime number. In this context, *p* is a strong prime if *p-1* and *p+1* have at least one large prime factor.
[ "r", "Return", "a", "random", "strong", "*", "N", "*", "-", "bit", "prime", "number", ".", "In", "this", "context", "*", "p", "*", "is", "a", "strong", "prime", "if", "*", "p", "-", "1", "*", "and", "*", "p", "+", "1", "*", "have", "at", "least", "one", "large", "prime", "factor", "." ]
def getStrongPrime(N, e=0, false_positive_prob=1e-6, randfunc=None): r""" Return a random strong *N*-bit prime number. In this context, *p* is a strong prime if *p-1* and *p+1* have at least one large prime factor. Args: N (integer): the exact length of the strong prime. It must be a multiple of 128 and > 512. e (integer): if provided, the returned prime (minus 1) will be coprime to *e* and thus suitable for RSA where *e* is the public exponent. false_positive_prob (float): The statistical probability for the result not to be actually a prime. It defaults to 10\ :sup:`-6`. Note that the real probability of a false-positive is far less. This is just the mathematically provable limit. randfunc (callable): A function that takes a parameter *N* and that returns a random byte string of such length. If omitted, :func:`Crypto.Random.get_random_bytes` is used. Return: The new strong prime. .. deprecated:: 3.0 This function is for internal use only and may be renamed or removed in the future. """ # This function was implemented following the # instructions found in the paper: # "FAST GENERATION OF RANDOM, STRONG RSA PRIMES" # by Robert D. Silverman # RSA Laboratories # May 17, 1997 # which by the time of writing could be freely downloaded here: # http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.17.2713&rep=rep1&type=pdf if randfunc is None: randfunc = Random.get_random_bytes # Use the accelerator if available if _fastmath is not None: return _fastmath.getStrongPrime(long(N), long(e), false_positive_prob, randfunc) if (N < 512) or ((N % 128) != 0): raise ValueError ("bits must be multiple of 128 and > 512") rabin_miller_rounds = int(math.ceil(-math.log(false_positive_prob)/math.log(4))) # calculate range for X # lower_bound = sqrt(2) * 2^{511 + 128*x} # upper_bound = 2^{512 + 128*x} - 1 x = (N - 512) >> 7; # We need to approximate the sqrt(2) in the lower_bound by an integer # expression because floating point math overflows with these numbers lower_bound = (14142135623730950489 * (2 ** (511 + 128*x))) // 10000000000000000000 upper_bound = (1 << (512 + 128*x)) - 1 # Randomly choose X in calculated range X = getRandomRange (lower_bound, upper_bound, randfunc) # generate p1 and p2 p = [0, 0] for i in (0, 1): # randomly choose 101-bit y y = getRandomNBitInteger (101, randfunc) # initialize the field for sieving field = [0] * 5 * len (sieve_base) # sieve the field for prime in sieve_base: offset = y % prime for j in iter_range((prime - offset) % prime, len (field), prime): field[j] = 1 # look for suitable p[i] starting at y result = 0 for j in range(len(field)): composite = field[j] # look for next canidate if composite: continue tmp = y + j result = _rabinMillerTest (tmp, rabin_miller_rounds) if result > 0: p[i] = tmp break if result == 0: raise RuntimeError ("Couln't find prime in field. " "Developer: Increase field_size") # Calculate R # R = (p2^{-1} mod p1) * p2 - (p1^{-1} mod p2) * p1 tmp1 = inverse (p[1], p[0]) * p[1] # (p2^-1 mod p1)*p2 tmp2 = inverse (p[0], p[1]) * p[0] # (p1^-1 mod p2)*p1 R = tmp1 - tmp2 # (p2^-1 mod p1)*p2 - (p1^-1 mod p2)*p1 # search for final prime number starting by Y0 # Y0 = X + (R - X mod p1p2) increment = p[0] * p[1] X = X + (R - (X % increment)) while 1: is_possible_prime = 1 # first check candidate against sieve_base for prime in sieve_base: if (X % prime) == 0: is_possible_prime = 0 break # if e is given make sure that e and X-1 are coprime # this is not necessarily a strong prime criterion but useful when # creating them for RSA where the p-1 and q-1 should be coprime to # the public exponent e if e and is_possible_prime: if e & 1: if GCD(e, X-1) != 1: is_possible_prime = 0 else: if GCD(e, (X-1) // 2) != 1: is_possible_prime = 0 # do some Rabin-Miller-Tests if is_possible_prime: result = _rabinMillerTest (X, rabin_miller_rounds) if result > 0: break X += increment # abort when X has more bits than requested # TODO: maybe we shouldn't abort but rather start over. if X >= 1 << N: raise RuntimeError ("Couln't find prime in field. " "Developer: Increase field_size") return X
[ "def", "getStrongPrime", "(", "N", ",", "e", "=", "0", ",", "false_positive_prob", "=", "1e-6", ",", "randfunc", "=", "None", ")", ":", "# This function was implemented following the", "# instructions found in the paper:", "# \"FAST GENERATION OF RANDOM, STRONG RSA PRIMES\"", "# by Robert D. Silverman", "# RSA Laboratories", "# May 17, 1997", "# which by the time of writing could be freely downloaded here:", "# http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.17.2713&rep=rep1&type=pdf", "if", "randfunc", "is", "None", ":", "randfunc", "=", "Random", ".", "get_random_bytes", "# Use the accelerator if available", "if", "_fastmath", "is", "not", "None", ":", "return", "_fastmath", ".", "getStrongPrime", "(", "long", "(", "N", ")", ",", "long", "(", "e", ")", ",", "false_positive_prob", ",", "randfunc", ")", "if", "(", "N", "<", "512", ")", "or", "(", "(", "N", "%", "128", ")", "!=", "0", ")", ":", "raise", "ValueError", "(", "\"bits must be multiple of 128 and > 512\"", ")", "rabin_miller_rounds", "=", "int", "(", "math", ".", "ceil", "(", "-", "math", ".", "log", "(", "false_positive_prob", ")", "/", "math", ".", "log", "(", "4", ")", ")", ")", "# calculate range for X", "# lower_bound = sqrt(2) * 2^{511 + 128*x}", "# upper_bound = 2^{512 + 128*x} - 1", "x", "=", "(", "N", "-", "512", ")", ">>", "7", "# We need to approximate the sqrt(2) in the lower_bound by an integer", "# expression because floating point math overflows with these numbers", "lower_bound", "=", "(", "14142135623730950489", "*", "(", "2", "**", "(", "511", "+", "128", "*", "x", ")", ")", ")", "//", "10000000000000000000", "upper_bound", "=", "(", "1", "<<", "(", "512", "+", "128", "*", "x", ")", ")", "-", "1", "# Randomly choose X in calculated range", "X", "=", "getRandomRange", "(", "lower_bound", ",", "upper_bound", ",", "randfunc", ")", "# generate p1 and p2", "p", "=", "[", "0", ",", "0", "]", "for", "i", "in", "(", "0", ",", "1", ")", ":", "# randomly choose 101-bit y", "y", "=", "getRandomNBitInteger", "(", "101", ",", "randfunc", ")", "# initialize the field for sieving", "field", "=", "[", "0", "]", "*", "5", "*", "len", "(", "sieve_base", ")", "# sieve the field", "for", "prime", "in", "sieve_base", ":", "offset", "=", "y", "%", "prime", "for", "j", "in", "iter_range", "(", "(", "prime", "-", "offset", ")", "%", "prime", ",", "len", "(", "field", ")", ",", "prime", ")", ":", "field", "[", "j", "]", "=", "1", "# look for suitable p[i] starting at y", "result", "=", "0", "for", "j", "in", "range", "(", "len", "(", "field", ")", ")", ":", "composite", "=", "field", "[", "j", "]", "# look for next canidate", "if", "composite", ":", "continue", "tmp", "=", "y", "+", "j", "result", "=", "_rabinMillerTest", "(", "tmp", ",", "rabin_miller_rounds", ")", "if", "result", ">", "0", ":", "p", "[", "i", "]", "=", "tmp", "break", "if", "result", "==", "0", ":", "raise", "RuntimeError", "(", "\"Couln't find prime in field. \"", "\"Developer: Increase field_size\"", ")", "# Calculate R", "# R = (p2^{-1} mod p1) * p2 - (p1^{-1} mod p2) * p1", "tmp1", "=", "inverse", "(", "p", "[", "1", "]", ",", "p", "[", "0", "]", ")", "*", "p", "[", "1", "]", "# (p2^-1 mod p1)*p2", "tmp2", "=", "inverse", "(", "p", "[", "0", "]", ",", "p", "[", "1", "]", ")", "*", "p", "[", "0", "]", "# (p1^-1 mod p2)*p1", "R", "=", "tmp1", "-", "tmp2", "# (p2^-1 mod p1)*p2 - (p1^-1 mod p2)*p1", "# search for final prime number starting by Y0", "# Y0 = X + (R - X mod p1p2)", "increment", "=", "p", "[", "0", "]", "*", "p", "[", "1", "]", "X", "=", "X", "+", "(", "R", "-", "(", "X", "%", "increment", ")", ")", "while", "1", ":", "is_possible_prime", "=", "1", "# first check candidate against sieve_base", "for", "prime", "in", "sieve_base", ":", "if", "(", "X", "%", "prime", ")", "==", "0", ":", "is_possible_prime", "=", "0", "break", "# if e is given make sure that e and X-1 are coprime", "# this is not necessarily a strong prime criterion but useful when", "# creating them for RSA where the p-1 and q-1 should be coprime to", "# the public exponent e", "if", "e", "and", "is_possible_prime", ":", "if", "e", "&", "1", ":", "if", "GCD", "(", "e", ",", "X", "-", "1", ")", "!=", "1", ":", "is_possible_prime", "=", "0", "else", ":", "if", "GCD", "(", "e", ",", "(", "X", "-", "1", ")", "//", "2", ")", "!=", "1", ":", "is_possible_prime", "=", "0", "# do some Rabin-Miller-Tests", "if", "is_possible_prime", ":", "result", "=", "_rabinMillerTest", "(", "X", ",", "rabin_miller_rounds", ")", "if", "result", ">", "0", ":", "break", "X", "+=", "increment", "# abort when X has more bits than requested", "# TODO: maybe we shouldn't abort but rather start over.", "if", "X", ">=", "1", "<<", "N", ":", "raise", "RuntimeError", "(", "\"Couln't find prime in field. \"", "\"Developer: Increase field_size\"", ")", "return", "X" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/ResourceManager/lib/Crypto/Util/number.py#L200-L331
AstarLight/Lets_OCR
b2af7120a34d785434c96e820b6eb1aa69269d20
detector/ctpn/infer.py
python
get_text_lines
(text_proposals, im_size, scores=0)
return text_recs
text_proposals:boxes
text_proposals:boxes
[ "text_proposals", ":", "boxes" ]
def get_text_lines(text_proposals, im_size, scores=0): """ text_proposals:boxes """ #tp_groups = neighbour_connector(text_proposals, im_size) # 首先还是建图,获取到文本行由哪几个小框构成 #print(tp_groups) text_lines = np.zeros((len(text_proposals), 8), np.float32) for index, tp_indices in enumerate(text_proposals): text_line_boxes = np.array(tp_indices) # 每个文本行的全部小框 #print(text_line_boxes) #print(type(text_line_boxes)) #print(text_line_boxes.shape) X = (text_line_boxes[:, 0] + text_line_boxes[:, 2]) / 2 # 求每一个小框的中心x,y坐标 Y = (text_line_boxes[:, 1] + text_line_boxes[:, 3]) / 2 #print(X) #print(Y) z1 = np.polyfit(X, Y, 1) # 多项式拟合,根据之前求的中心店拟合一条直线(最小二乘) x0 = np.min(text_line_boxes[:, 0]) # 文本行x坐标最小值 x1 = np.max(text_line_boxes[:, 2]) # 文本行x坐标最大值 offset = (text_line_boxes[0, 2] - text_line_boxes[0, 0]) * 0.5 # 小框宽度的一半 # 以全部小框的左上角这个点去拟合一条直线,然后计算一下文本行x坐标的极左极右对应的y坐标 lt_y, rt_y = fit_y(text_line_boxes[:, 0], text_line_boxes[:, 1], x0 + offset, x1 - offset) # 以全部小框的左下角这个点去拟合一条直线,然后计算一下文本行x坐标的极左极右对应的y坐标 lb_y, rb_y = fit_y(text_line_boxes[:, 0], text_line_boxes[:, 3], x0 + offset, x1 - offset) #score = scores[list(tp_indices)].sum() / float(len(tp_indices)) # 求全部小框得分的均值作为文本行的均值 text_lines[index, 0] = x0 text_lines[index, 1] = min(lt_y, rt_y) # 文本行上端 线段 的y坐标的小值 text_lines[index, 2] = x1 text_lines[index, 3] = max(lb_y, rb_y) # 文本行下端 线段 的y坐标的大值 text_lines[index, 4] = scores # 文本行得分 text_lines[index, 5] = z1[0] # 根据中心点拟合的直线的k,b text_lines[index, 6] = z1[1] height = np.mean((text_line_boxes[:, 3] - text_line_boxes[:, 1])) # 小框平均高度 text_lines[index, 7] = height + 2.5 text_recs = np.zeros((len(text_lines), 9), np.float32) index = 0 for line in text_lines: b1 = line[6] - line[7] / 2 # 根据高度和文本行中心线,求取文本行上下两条线的b值 b2 = line[6] + line[7] / 2 x1 = line[0] y1 = line[5] * line[0] + b1 # 左上 x2 = line[2] y2 = line[5] * line[2] + b1 # 右上 x3 = line[0] y3 = line[5] * line[0] + b2 # 左下 x4 = line[2] y4 = line[5] * line[2] + b2 # 右下 disX = x2 - x1 disY = y2 - y1 width = np.sqrt(disX * disX + disY * disY) # 文本行宽度 fTmp0 = y3 - y1 # 文本行高度 fTmp1 = fTmp0 * disY / width x = np.fabs(fTmp1 * disX / width) # 做补偿 y = np.fabs(fTmp1 * disY / width) if line[5] < 0: x1 -= x y1 += y x4 += x y4 -= y else: x2 += x y2 += y x3 -= x y3 -= y # clock-wise order text_recs[index, 0] = x1 text_recs[index, 1] = y1 text_recs[index, 2] = x2 text_recs[index, 3] = y2 text_recs[index, 4] = x4 text_recs[index, 5] = y4 text_recs[index, 6] = x3 text_recs[index, 7] = y3 text_recs[index, 8] = line[4] index = index + 1 text_recs = clip_boxes(text_recs, im_size) return text_recs
[ "def", "get_text_lines", "(", "text_proposals", ",", "im_size", ",", "scores", "=", "0", ")", ":", "#tp_groups = neighbour_connector(text_proposals, im_size) # 首先还是建图,获取到文本行由哪几个小框构成", "#print(tp_groups)", "text_lines", "=", "np", ".", "zeros", "(", "(", "len", "(", "text_proposals", ")", ",", "8", ")", ",", "np", ".", "float32", ")", "for", "index", ",", "tp_indices", "in", "enumerate", "(", "text_proposals", ")", ":", "text_line_boxes", "=", "np", ".", "array", "(", "tp_indices", ")", "# 每个文本行的全部小框", "#print(text_line_boxes)", "#print(type(text_line_boxes))", "#print(text_line_boxes.shape)", "X", "=", "(", "text_line_boxes", "[", ":", ",", "0", "]", "+", "text_line_boxes", "[", ":", ",", "2", "]", ")", "/", "2", "# 求每一个小框的中心x,y坐标", "Y", "=", "(", "text_line_boxes", "[", ":", ",", "1", "]", "+", "text_line_boxes", "[", ":", ",", "3", "]", ")", "/", "2", "#print(X)", "#print(Y)", "z1", "=", "np", ".", "polyfit", "(", "X", ",", "Y", ",", "1", ")", "# 多项式拟合,根据之前求的中心店拟合一条直线(最小二乘)", "x0", "=", "np", ".", "min", "(", "text_line_boxes", "[", ":", ",", "0", "]", ")", "# 文本行x坐标最小值", "x1", "=", "np", ".", "max", "(", "text_line_boxes", "[", ":", ",", "2", "]", ")", "# 文本行x坐标最大值", "offset", "=", "(", "text_line_boxes", "[", "0", ",", "2", "]", "-", "text_line_boxes", "[", "0", ",", "0", "]", ")", "*", "0.5", "# 小框宽度的一半", "# 以全部小框的左上角这个点去拟合一条直线,然后计算一下文本行x坐标的极左极右对应的y坐标", "lt_y", ",", "rt_y", "=", "fit_y", "(", "text_line_boxes", "[", ":", ",", "0", "]", ",", "text_line_boxes", "[", ":", ",", "1", "]", ",", "x0", "+", "offset", ",", "x1", "-", "offset", ")", "# 以全部小框的左下角这个点去拟合一条直线,然后计算一下文本行x坐标的极左极右对应的y坐标", "lb_y", ",", "rb_y", "=", "fit_y", "(", "text_line_boxes", "[", ":", ",", "0", "]", ",", "text_line_boxes", "[", ":", ",", "3", "]", ",", "x0", "+", "offset", ",", "x1", "-", "offset", ")", "#score = scores[list(tp_indices)].sum() / float(len(tp_indices)) # 求全部小框得分的均值作为文本行的均值", "text_lines", "[", "index", ",", "0", "]", "=", "x0", "text_lines", "[", "index", ",", "1", "]", "=", "min", "(", "lt_y", ",", "rt_y", ")", "# 文本行上端 线段 的y坐标的小值", "text_lines", "[", "index", ",", "2", "]", "=", "x1", "text_lines", "[", "index", ",", "3", "]", "=", "max", "(", "lb_y", ",", "rb_y", ")", "# 文本行下端 线段 的y坐标的大值", "text_lines", "[", "index", ",", "4", "]", "=", "scores", "# 文本行得分", "text_lines", "[", "index", ",", "5", "]", "=", "z1", "[", "0", "]", "# 根据中心点拟合的直线的k,b", "text_lines", "[", "index", ",", "6", "]", "=", "z1", "[", "1", "]", "height", "=", "np", ".", "mean", "(", "(", "text_line_boxes", "[", ":", ",", "3", "]", "-", "text_line_boxes", "[", ":", ",", "1", "]", ")", ")", "# 小框平均高度", "text_lines", "[", "index", ",", "7", "]", "=", "height", "+", "2.5", "text_recs", "=", "np", ".", "zeros", "(", "(", "len", "(", "text_lines", ")", ",", "9", ")", ",", "np", ".", "float32", ")", "index", "=", "0", "for", "line", "in", "text_lines", ":", "b1", "=", "line", "[", "6", "]", "-", "line", "[", "7", "]", "/", "2", "# 根据高度和文本行中心线,求取文本行上下两条线的b值", "b2", "=", "line", "[", "6", "]", "+", "line", "[", "7", "]", "/", "2", "x1", "=", "line", "[", "0", "]", "y1", "=", "line", "[", "5", "]", "*", "line", "[", "0", "]", "+", "b1", "# 左上", "x2", "=", "line", "[", "2", "]", "y2", "=", "line", "[", "5", "]", "*", "line", "[", "2", "]", "+", "b1", "# 右上", "x3", "=", "line", "[", "0", "]", "y3", "=", "line", "[", "5", "]", "*", "line", "[", "0", "]", "+", "b2", "# 左下", "x4", "=", "line", "[", "2", "]", "y4", "=", "line", "[", "5", "]", "*", "line", "[", "2", "]", "+", "b2", "# 右下", "disX", "=", "x2", "-", "x1", "disY", "=", "y2", "-", "y1", "width", "=", "np", ".", "sqrt", "(", "disX", "*", "disX", "+", "disY", "*", "disY", ")", "# 文本行宽度", "fTmp0", "=", "y3", "-", "y1", "# 文本行高度", "fTmp1", "=", "fTmp0", "*", "disY", "/", "width", "x", "=", "np", ".", "fabs", "(", "fTmp1", "*", "disX", "/", "width", ")", "# 做补偿", "y", "=", "np", ".", "fabs", "(", "fTmp1", "*", "disY", "/", "width", ")", "if", "line", "[", "5", "]", "<", "0", ":", "x1", "-=", "x", "y1", "+=", "y", "x4", "+=", "x", "y4", "-=", "y", "else", ":", "x2", "+=", "x", "y2", "+=", "y", "x3", "-=", "x", "y3", "-=", "y", "# clock-wise order", "text_recs", "[", "index", ",", "0", "]", "=", "x1", "text_recs", "[", "index", ",", "1", "]", "=", "y1", "text_recs", "[", "index", ",", "2", "]", "=", "x2", "text_recs", "[", "index", ",", "3", "]", "=", "y2", "text_recs", "[", "index", ",", "4", "]", "=", "x4", "text_recs", "[", "index", ",", "5", "]", "=", "y4", "text_recs", "[", "index", ",", "6", "]", "=", "x3", "text_recs", "[", "index", ",", "7", "]", "=", "y3", "text_recs", "[", "index", ",", "8", "]", "=", "line", "[", "4", "]", "index", "=", "index", "+", "1", "text_recs", "=", "clip_boxes", "(", "text_recs", ",", "im_size", ")", "return", "text_recs" ]
https://github.com/AstarLight/Lets_OCR/blob/b2af7120a34d785434c96e820b6eb1aa69269d20/detector/ctpn/infer.py#L50-L138
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/propgrid.py
python
PropertyGrid.DoHidePropertyError
(*args, **kwargs)
return _propgrid.PropertyGrid_DoHidePropertyError(*args, **kwargs)
DoHidePropertyError(self, PGProperty property)
DoHidePropertyError(self, PGProperty property)
[ "DoHidePropertyError", "(", "self", "PGProperty", "property", ")" ]
def DoHidePropertyError(*args, **kwargs): """DoHidePropertyError(self, PGProperty property)""" return _propgrid.PropertyGrid_DoHidePropertyError(*args, **kwargs)
[ "def", "DoHidePropertyError", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_propgrid", ".", "PropertyGrid_DoHidePropertyError", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/propgrid.py#L2436-L2438
takemaru/graphillion
51879f92bb96b53ef8f914ef37a05252ce383617
graphillion/graphset.py
python
GraphSet.complement
(self)
return GraphSet(ss)
Returns a new GraphSet with complement graphs of `self`. The `self` is not changed. Examples: >>> GraphSet.set_universe([(1, 2), (1, 4)]) >>> graph1 = [(1, 2)] >>> graph2 = [(1, 2), (1, 4)] >>> gs = GraphSet([graph1, graph2]) >>> gs.complement() GraphSet([[], [(1, 4)]]) Returns: A new GraphSet object.
Returns a new GraphSet with complement graphs of `self`.
[ "Returns", "a", "new", "GraphSet", "with", "complement", "graphs", "of", "self", "." ]
def complement(self): """Returns a new GraphSet with complement graphs of `self`. The `self` is not changed. Examples: >>> GraphSet.set_universe([(1, 2), (1, 4)]) >>> graph1 = [(1, 2)] >>> graph2 = [(1, 2), (1, 4)] >>> gs = GraphSet([graph1, graph2]) >>> gs.complement() GraphSet([[], [(1, 4)]]) Returns: A new GraphSet object. """ ss = self._ss.copy() ss.flip() return GraphSet(ss)
[ "def", "complement", "(", "self", ")", ":", "ss", "=", "self", ".", "_ss", ".", "copy", "(", ")", "ss", ".", "flip", "(", ")", "return", "GraphSet", "(", "ss", ")" ]
https://github.com/takemaru/graphillion/blob/51879f92bb96b53ef8f914ef37a05252ce383617/graphillion/graphset.py#L1144-L1162
verilog-to-routing/vtr-verilog-to-routing
d9719cf7374821156c3cee31d66991cb85578562
vtr_flow/scripts/python_libs/vtr/log_parse.py
python
determine_lut_size
(architecture_file)
return lut_size
Determines the maximum LUT size (K) in an architecture file. Assumes LUTs are represented as BLIF '.names'
Determines the maximum LUT size (K) in an architecture file.
[ "Determines", "the", "maximum", "LUT", "size", "(", "K", ")", "in", "an", "architecture", "file", "." ]
def determine_lut_size(architecture_file): """ Determines the maximum LUT size (K) in an architecture file. Assumes LUTs are represented as BLIF '.names' """ arch_xml = ET.parse(architecture_file).getroot() lut_size = 0 saw_blif_names = False for elem in arch_xml.findall(".//pb_type"): # Xpath recrusive search for 'pb_type' blif_model = elem.get("blif_model") if blif_model and blif_model == ".names": saw_blif_names = True input_port = elem.find("input") input_width = int(input_port.get("num_pins")) assert input_width > 0 # Keep the maximum lut size found (i.e. fracturable architectures) lut_size = max(lut_size, input_width) if saw_blif_names and lut_size == 0: raise InspectError("Could not identify valid LUT size (K)", filename=architecture_file) return lut_size
[ "def", "determine_lut_size", "(", "architecture_file", ")", ":", "arch_xml", "=", "ET", ".", "parse", "(", "architecture_file", ")", ".", "getroot", "(", ")", "lut_size", "=", "0", "saw_blif_names", "=", "False", "for", "elem", "in", "arch_xml", ".", "findall", "(", "\".//pb_type\"", ")", ":", "# Xpath recrusive search for 'pb_type'", "blif_model", "=", "elem", ".", "get", "(", "\"blif_model\"", ")", "if", "blif_model", "and", "blif_model", "==", "\".names\"", ":", "saw_blif_names", "=", "True", "input_port", "=", "elem", ".", "find", "(", "\"input\"", ")", "input_width", "=", "int", "(", "input_port", ".", "get", "(", "\"num_pins\"", ")", ")", "assert", "input_width", ">", "0", "# Keep the maximum lut size found (i.e. fracturable architectures)", "lut_size", "=", "max", "(", "lut_size", ",", "input_width", ")", "if", "saw_blif_names", "and", "lut_size", "==", "0", ":", "raise", "InspectError", "(", "\"Could not identify valid LUT size (K)\"", ",", "filename", "=", "architecture_file", ")", "return", "lut_size" ]
https://github.com/verilog-to-routing/vtr-verilog-to-routing/blob/d9719cf7374821156c3cee31d66991cb85578562/vtr_flow/scripts/python_libs/vtr/log_parse.py#L470-L495
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/pickletools.py
python
read_floatnl
(f)
return float(s)
r""" >>> import StringIO >>> read_floatnl(StringIO.StringIO("-1.25\n6")) -1.25
r""" >>> import StringIO >>> read_floatnl(StringIO.StringIO("-1.25\n6")) -1.25
[ "r", ">>>", "import", "StringIO", ">>>", "read_floatnl", "(", "StringIO", ".", "StringIO", "(", "-", "1", ".", "25", "\\", "n6", "))", "-", "1", ".", "25" ]
def read_floatnl(f): r""" >>> import StringIO >>> read_floatnl(StringIO.StringIO("-1.25\n6")) -1.25 """ s = read_stringnl(f, decode=False, stripquotes=False) return float(s)
[ "def", "read_floatnl", "(", "f", ")", ":", "s", "=", "read_stringnl", "(", "f", ",", "decode", "=", "False", ",", "stripquotes", "=", "False", ")", "return", "float", "(", "s", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/pickletools.py#L562-L569
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/lib/io/file_io.py
python
copy_v2
(src, dst, overwrite=False)
Copies data from `src` to `dst`. Args: src: string, name of the file whose contents need to be copied dst: string, name of the file to which to copy to overwrite: boolean, if false it's an error for `dst` to be occupied by an existing file. Raises: errors.OpError: If the operation fails.
Copies data from `src` to `dst`.
[ "Copies", "data", "from", "src", "to", "dst", "." ]
def copy_v2(src, dst, overwrite=False): """Copies data from `src` to `dst`. Args: src: string, name of the file whose contents need to be copied dst: string, name of the file to which to copy to overwrite: boolean, if false it's an error for `dst` to be occupied by an existing file. Raises: errors.OpError: If the operation fails. """ pywrap_tensorflow.CopyFile( compat.as_bytes(src), compat.as_bytes(dst), overwrite)
[ "def", "copy_v2", "(", "src", ",", "dst", ",", "overwrite", "=", "False", ")", ":", "pywrap_tensorflow", ".", "CopyFile", "(", "compat", ".", "as_bytes", "(", "src", ")", ",", "compat", ".", "as_bytes", "(", "dst", ")", ",", "overwrite", ")" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/lib/io/file_io.py#L473-L486
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/fractions.py
python
Fraction.__abs__
(a)
return Fraction(abs(a._numerator), a._denominator)
abs(a)
abs(a)
[ "abs", "(", "a", ")" ]
def __abs__(a): """abs(a)""" return Fraction(abs(a._numerator), a._denominator)
[ "def", "__abs__", "(", "a", ")", ":", "return", "Fraction", "(", "abs", "(", "a", ".", "_numerator", ")", ",", "a", ".", "_denominator", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/fractions.py#L497-L499
dgobbi/vtk-dicom
9078df24cfeceead466a785d675b7a4afa034bba
Utilities/chartables.py
python
readdict
(fname)
return d
Read a text file that contains a mapping table. The table is assumed to have two or more columns, with '#' for comments.
Read a text file that contains a mapping table. The table is assumed to have two or more columns, with '#' for comments.
[ "Read", "a", "text", "file", "that", "contains", "a", "mapping", "table", ".", "The", "table", "is", "assumed", "to", "have", "two", "or", "more", "columns", "with", "#", "for", "comments", "." ]
def readdict(fname): """Read a text file that contains a mapping table. The table is assumed to have two or more columns, with '#' for comments. """ d = {} f = open(fname, 'r') for l in f.readlines(): l = l.strip() if l and l[0] != '#': columns = l.split() if len(columns) > 1: d[int(columns[0],base=0)] = int(columns[1],base=0) f.close() return d
[ "def", "readdict", "(", "fname", ")", ":", "d", "=", "{", "}", "f", "=", "open", "(", "fname", ",", "'r'", ")", "for", "l", "in", "f", ".", "readlines", "(", ")", ":", "l", "=", "l", ".", "strip", "(", ")", "if", "l", "and", "l", "[", "0", "]", "!=", "'#'", ":", "columns", "=", "l", ".", "split", "(", ")", "if", "len", "(", "columns", ")", ">", "1", ":", "d", "[", "int", "(", "columns", "[", "0", "]", ",", "base", "=", "0", ")", "]", "=", "int", "(", "columns", "[", "1", "]", ",", "base", "=", "0", ")", "f", ".", "close", "(", ")", "return", "d" ]
https://github.com/dgobbi/vtk-dicom/blob/9078df24cfeceead466a785d675b7a4afa034bba/Utilities/chartables.py#L105-L119
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py3/scipy/optimize/_tstutils.py
python
aps05_f
(x)
return np.sin(x) - 1.0 / 2
r"""Simple Trigonometric function
r"""Simple Trigonometric function
[ "r", "Simple", "Trigonometric", "function" ]
def aps05_f(x): r"""Simple Trigonometric function""" return np.sin(x) - 1.0 / 2
[ "def", "aps05_f", "(", "x", ")", ":", "return", "np", ".", "sin", "(", "x", ")", "-", "1.0", "/", "2" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/optimize/_tstutils.py#L216-L218
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
python/paddle/fluid/framework.py
python
Block._to_readable_code
(self, skip_op_callstack=True)
return block_str
Get readable debug string of Block. .. note:: If you want to get the debug string in protobuf format, please use :code:`to_string` method. Args: skip_op_callstack(bool): whether to skip parsing Operator's attribute op_callstack, default value is True Returns: string: The formatted Block string. Examples: .. code-block:: python import paddle.fluid as fluid cur_program = fluid.Program() cur_block = cur_program.current_block() new_var = cur_block.create_var(name="X", shape=[-1, 23, 48], dtype='float32') new_op = cur_block.append_op(type="abs", inputs={"X": [new_var]}, outputs={"Out": [new_var]}) print(cur_block._to_readable_code())
Get readable debug string of Block.
[ "Get", "readable", "debug", "string", "of", "Block", "." ]
def _to_readable_code(self, skip_op_callstack=True): """ Get readable debug string of Block. .. note:: If you want to get the debug string in protobuf format, please use :code:`to_string` method. Args: skip_op_callstack(bool): whether to skip parsing Operator's attribute op_callstack, default value is True Returns: string: The formatted Block string. Examples: .. code-block:: python import paddle.fluid as fluid cur_program = fluid.Program() cur_block = cur_program.current_block() new_var = cur_block.create_var(name="X", shape=[-1, 23, 48], dtype='float32') new_op = cur_block.append_op(type="abs", inputs={"X": [new_var]}, outputs={"Out": [new_var]}) print(cur_block._to_readable_code()) """ assert isinstance( skip_op_callstack, bool ), "skip_op_callstack parameter's type is error, expect bool, received {}".format( type(skip_op_callstack)) block_str = "{ // block " block_str += "{}\n".format(self.idx) for var in list(self.vars.values()): block_str += " {}\n".format(var._to_readable_code()) block_str += "\n" for op in self.ops: block_str += " {}\n".format( op._to_readable_code(skip_op_callstack)) block_str += "}" return block_str
[ "def", "_to_readable_code", "(", "self", ",", "skip_op_callstack", "=", "True", ")", ":", "assert", "isinstance", "(", "skip_op_callstack", ",", "bool", ")", ",", "\"skip_op_callstack parameter's type is error, expect bool, received {}\"", ".", "format", "(", "type", "(", "skip_op_callstack", ")", ")", "block_str", "=", "\"{ // block \"", "block_str", "+=", "\"{}\\n\"", ".", "format", "(", "self", ".", "idx", ")", "for", "var", "in", "list", "(", "self", ".", "vars", ".", "values", "(", ")", ")", ":", "block_str", "+=", "\" {}\\n\"", ".", "format", "(", "var", ".", "_to_readable_code", "(", ")", ")", "block_str", "+=", "\"\\n\"", "for", "op", "in", "self", ".", "ops", ":", "block_str", "+=", "\" {}\\n\"", ".", "format", "(", "op", ".", "_to_readable_code", "(", "skip_op_callstack", ")", ")", "block_str", "+=", "\"}\"", "return", "block_str" ]
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/fluid/framework.py#L3113-L3156
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/imaplib.py
python
IMAP4._CRAM_MD5_AUTH
(self, challenge)
return self.user + " " + hmac.HMAC(self.password, challenge).hexdigest()
Authobject to use with CRAM-MD5 authentication.
Authobject to use with CRAM-MD5 authentication.
[ "Authobject", "to", "use", "with", "CRAM", "-", "MD5", "authentication", "." ]
def _CRAM_MD5_AUTH(self, challenge): """ Authobject to use with CRAM-MD5 authentication. """ import hmac return self.user + " " + hmac.HMAC(self.password, challenge).hexdigest()
[ "def", "_CRAM_MD5_AUTH", "(", "self", ",", "challenge", ")", ":", "import", "hmac", "return", "self", ".", "user", "+", "\" \"", "+", "hmac", ".", "HMAC", "(", "self", ".", "password", ",", "challenge", ")", ".", "hexdigest", "(", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/imaplib.py#L537-L540
perilouswithadollarsign/cstrike15_src
f82112a2388b841d72cb62ca48ab1846dfcc11c8
thirdparty/protobuf-2.5.0/python/google/protobuf/internal/python_message.py
python
_AddSlots
(message_descriptor, dictionary)
Adds a __slots__ entry to dictionary, containing the names of all valid attributes for this message type. Args: message_descriptor: A Descriptor instance describing this message type. dictionary: Class dictionary to which we'll add a '__slots__' entry.
Adds a __slots__ entry to dictionary, containing the names of all valid attributes for this message type.
[ "Adds", "a", "__slots__", "entry", "to", "dictionary", "containing", "the", "names", "of", "all", "valid", "attributes", "for", "this", "message", "type", "." ]
def _AddSlots(message_descriptor, dictionary): """Adds a __slots__ entry to dictionary, containing the names of all valid attributes for this message type. Args: message_descriptor: A Descriptor instance describing this message type. dictionary: Class dictionary to which we'll add a '__slots__' entry. """ dictionary['__slots__'] = ['_cached_byte_size', '_cached_byte_size_dirty', '_fields', '_unknown_fields', '_is_present_in_parent', '_listener', '_listener_for_children', '__weakref__']
[ "def", "_AddSlots", "(", "message_descriptor", ",", "dictionary", ")", ":", "dictionary", "[", "'__slots__'", "]", "=", "[", "'_cached_byte_size'", ",", "'_cached_byte_size_dirty'", ",", "'_fields'", ",", "'_unknown_fields'", ",", "'_is_present_in_parent'", ",", "'_listener'", ",", "'_listener_for_children'", ",", "'__weakref__'", "]" ]
https://github.com/perilouswithadollarsign/cstrike15_src/blob/f82112a2388b841d72cb62ca48ab1846dfcc11c8/thirdparty/protobuf-2.5.0/python/google/protobuf/internal/python_message.py#L164-L179
microsoft/ivy
9f3c7ecc0b2383129fdd0953e10890d98d09a82d
ivy/tactics_api.py
python
arg_initial_node
()
return _ivy_ag.states[0]
Add an initial node to the abstract reachability graph (arg) and return it.
Add an initial node to the abstract reachability graph (arg) and return it.
[ "Add", "an", "initial", "node", "to", "the", "abstract", "reachability", "graph", "(", "arg", ")", "and", "return", "it", "." ]
def arg_initial_node(): """ Add an initial node to the abstract reachability graph (arg) and return it. """ # right now, the initial state is already added as the first # state, so just return it return _ivy_ag.states[0]
[ "def", "arg_initial_node", "(", ")", ":", "# right now, the initial state is already added as the first", "# state, so just return it", "return", "_ivy_ag", ".", "states", "[", "0", "]" ]
https://github.com/microsoft/ivy/blob/9f3c7ecc0b2383129fdd0953e10890d98d09a82d/ivy/tactics_api.py#L92-L99
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqt/mantidqt/widgets/samplelogs/model.py
python
SampleLogsModel.getItemModel
(self, searched_key='')
return model
Return a QModel made from the current workspace. This should be set onto a QTableView. The searched_key allows for filtering log entries.
Return a QModel made from the current workspace. This should be set onto a QTableView. The searched_key allows for filtering log entries.
[ "Return", "a", "QModel", "made", "from", "the", "current", "workspace", ".", "This", "should", "be", "set", "onto", "a", "QTableView", ".", "The", "searched_key", "allows", "for", "filtering", "log", "entries", "." ]
def getItemModel(self, searched_key=''): """Return a QModel made from the current workspace. This should be set onto a QTableView. The searched_key allows for filtering log entries. """ def create_table_item(column, itemname, invalid_value_count, log_size, callable, *args): item = QStandardItem() item.setEditable(False) #format if there is invalid data entries if invalid_value_count == -1: item.setData(DEEP_RED, Qt.BackgroundRole) item.setToolTip("All of the values in the log are marked invalid, none of them are filtered.") elif invalid_value_count > 0: saturation = 10 + (170 * (invalid_value_count/(log_size+invalid_value_count))) item.setData(QColor.fromHsv(0, saturation, 255), Qt.BackgroundRole) aux_verb = "is" if invalid_value_count == 1 else "are" item.setToolTip(f"{invalid_value_count}/{log_size+invalid_value_count} of the values in the log" f" {aux_verb} marked invalid, and {aux_verb} filtered.") try: item.setText(callable(*args)) except Exception as exc: logger.warning("Error setting column {} for log {}: {}".format(column, itemname, str(exc))) return item model = QStandardItemModel() model.setHorizontalHeaderLabels(["Name", "Type", "Value", "Units"]) model.setColumnCount(4) logs_to_highlight = self.get_logs_with_invalid_data() logs_to_hide = self.get_hidden_logs() for key in self.get_log_names(): if key in logs_to_hide: continue if searched_key.casefold() not in key.casefold(): continue invalid_value_count = 0 if key in logs_to_highlight.keys(): invalid_value_count = logs_to_highlight[key] log = self.run.getLogData(key) size = log.size() if hasattr(log, 'size') else 0 name = create_table_item("Name", key, invalid_value_count, size, lambda: log.name) log_type = create_table_item("Type", key, invalid_value_count, size, get_type, log) value = create_table_item("Value", key, invalid_value_count, size, lambda log: get_value(log), log) unit = create_table_item("Units", key, invalid_value_count, size, lambda: log.units) model.appendRow((name, log_type, value, unit)) model.sort(0) return model
[ "def", "getItemModel", "(", "self", ",", "searched_key", "=", "''", ")", ":", "def", "create_table_item", "(", "column", ",", "itemname", ",", "invalid_value_count", ",", "log_size", ",", "callable", ",", "*", "args", ")", ":", "item", "=", "QStandardItem", "(", ")", "item", ".", "setEditable", "(", "False", ")", "#format if there is invalid data entries", "if", "invalid_value_count", "==", "-", "1", ":", "item", ".", "setData", "(", "DEEP_RED", ",", "Qt", ".", "BackgroundRole", ")", "item", ".", "setToolTip", "(", "\"All of the values in the log are marked invalid, none of them are filtered.\"", ")", "elif", "invalid_value_count", ">", "0", ":", "saturation", "=", "10", "+", "(", "170", "*", "(", "invalid_value_count", "/", "(", "log_size", "+", "invalid_value_count", ")", ")", ")", "item", ".", "setData", "(", "QColor", ".", "fromHsv", "(", "0", ",", "saturation", ",", "255", ")", ",", "Qt", ".", "BackgroundRole", ")", "aux_verb", "=", "\"is\"", "if", "invalid_value_count", "==", "1", "else", "\"are\"", "item", ".", "setToolTip", "(", "f\"{invalid_value_count}/{log_size+invalid_value_count} of the values in the log\"", "f\" {aux_verb} marked invalid, and {aux_verb} filtered.\"", ")", "try", ":", "item", ".", "setText", "(", "callable", "(", "*", "args", ")", ")", "except", "Exception", "as", "exc", ":", "logger", ".", "warning", "(", "\"Error setting column {} for log {}: {}\"", ".", "format", "(", "column", ",", "itemname", ",", "str", "(", "exc", ")", ")", ")", "return", "item", "model", "=", "QStandardItemModel", "(", ")", "model", ".", "setHorizontalHeaderLabels", "(", "[", "\"Name\"", ",", "\"Type\"", ",", "\"Value\"", ",", "\"Units\"", "]", ")", "model", ".", "setColumnCount", "(", "4", ")", "logs_to_highlight", "=", "self", ".", "get_logs_with_invalid_data", "(", ")", "logs_to_hide", "=", "self", ".", "get_hidden_logs", "(", ")", "for", "key", "in", "self", ".", "get_log_names", "(", ")", ":", "if", "key", "in", "logs_to_hide", ":", "continue", "if", "searched_key", ".", "casefold", "(", ")", "not", "in", "key", ".", "casefold", "(", ")", ":", "continue", "invalid_value_count", "=", "0", "if", "key", "in", "logs_to_highlight", ".", "keys", "(", ")", ":", "invalid_value_count", "=", "logs_to_highlight", "[", "key", "]", "log", "=", "self", ".", "run", ".", "getLogData", "(", "key", ")", "size", "=", "log", ".", "size", "(", ")", "if", "hasattr", "(", "log", ",", "'size'", ")", "else", "0", "name", "=", "create_table_item", "(", "\"Name\"", ",", "key", ",", "invalid_value_count", ",", "size", ",", "lambda", ":", "log", ".", "name", ")", "log_type", "=", "create_table_item", "(", "\"Type\"", ",", "key", ",", "invalid_value_count", ",", "size", ",", "get_type", ",", "log", ")", "value", "=", "create_table_item", "(", "\"Value\"", ",", "key", ",", "invalid_value_count", ",", "size", ",", "lambda", "log", ":", "get_value", "(", "log", ")", ",", "log", ")", "unit", "=", "create_table_item", "(", "\"Units\"", ",", "key", ",", "invalid_value_count", ",", "size", ",", "lambda", ":", "log", ".", "units", ")", "model", ".", "appendRow", "(", "(", "name", ",", "log_type", ",", "value", ",", "unit", ")", ")", "model", ".", "sort", "(", "0", ")", "return", "model" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqt/mantidqt/widgets/samplelogs/model.py#L187-L234
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/ticker.py
python
Ticker.ShouldInheritColours
(self)
return False
Don't get colours from our parent...
Don't get colours from our parent...
[ "Don", "t", "get", "colours", "from", "our", "parent", "..." ]
def ShouldInheritColours(self): """Don't get colours from our parent...""" return False
[ "def", "ShouldInheritColours", "(", "self", ")", ":", "return", "False" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/ticker.py#L196-L198
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/layers/utils.py
python
object_list_uid
(object_list)
return ', '.join([str(abs(id(x))) for x in object_list])
Creates a single string from object ids.
Creates a single string from object ids.
[ "Creates", "a", "single", "string", "from", "object", "ids", "." ]
def object_list_uid(object_list): """Creates a single string from object ids.""" object_list = nest.flatten(object_list) return ', '.join([str(abs(id(x))) for x in object_list])
[ "def", "object_list_uid", "(", "object_list", ")", ":", "object_list", "=", "nest", ".", "flatten", "(", "object_list", ")", "return", "', '", ".", "join", "(", "[", "str", "(", "abs", "(", "id", "(", "x", ")", ")", ")", "for", "x", "in", "object_list", "]", ")" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/layers/utils.py#L231-L234
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/contrib/learn/python/learn/dataframe/queues/feeding_queue_runner.py
python
FeedingQueueRunner._run
(self, sess, enqueue_op, feed_fn, coord=None)
Execute the enqueue op in a loop, close the queue in case of error. Args: sess: A `Session`. enqueue_op: The `Operation` to run. feed_fn: the feed function to pass to `sess.run`. coord: Optional `Coordinator` object for reporting errors and checking for stop conditions.
Execute the enqueue op in a loop, close the queue in case of error.
[ "Execute", "the", "enqueue", "op", "in", "a", "loop", "close", "the", "queue", "in", "case", "of", "error", "." ]
def _run(self, sess, enqueue_op, feed_fn, coord=None): """Execute the enqueue op in a loop, close the queue in case of error. Args: sess: A `Session`. enqueue_op: The `Operation` to run. feed_fn: the feed function to pass to `sess.run`. coord: Optional `Coordinator` object for reporting errors and checking for stop conditions. """ # TODO(jamieas): Reduce code duplication with `QueueRunner`. decremented = False try: while True: if coord and coord.should_stop(): break try: feed_dict = None if feed_fn is None else feed_fn() sess.run(enqueue_op, feed_dict=feed_dict) except errors.OutOfRangeError: # This exception indicates that a queue was closed. with self._lock: self._runs -= 1 decremented = True if self._runs == 0: try: sess.run(self._close_op) except Exception as e: # Intentionally ignore errors from close_op. logging.vlog(1, "Ignored exception: %s", str(e)) return except Exception as e: # This catches all other exceptions. if coord: coord.request_stop(e) else: logging.error("Exception in QueueRunner: %s", str(e)) with self._lock: self._exceptions_raised.append(e) raise finally: # Make sure we account for all terminations: normal or errors. if not decremented: with self._lock: self._runs -= 1
[ "def", "_run", "(", "self", ",", "sess", ",", "enqueue_op", ",", "feed_fn", ",", "coord", "=", "None", ")", ":", "# TODO(jamieas): Reduce code duplication with `QueueRunner`.", "decremented", "=", "False", "try", ":", "while", "True", ":", "if", "coord", "and", "coord", ".", "should_stop", "(", ")", ":", "break", "try", ":", "feed_dict", "=", "None", "if", "feed_fn", "is", "None", "else", "feed_fn", "(", ")", "sess", ".", "run", "(", "enqueue_op", ",", "feed_dict", "=", "feed_dict", ")", "except", "errors", ".", "OutOfRangeError", ":", "# This exception indicates that a queue was closed.", "with", "self", ".", "_lock", ":", "self", ".", "_runs", "-=", "1", "decremented", "=", "True", "if", "self", ".", "_runs", "==", "0", ":", "try", ":", "sess", ".", "run", "(", "self", ".", "_close_op", ")", "except", "Exception", "as", "e", ":", "# Intentionally ignore errors from close_op.", "logging", ".", "vlog", "(", "1", ",", "\"Ignored exception: %s\"", ",", "str", "(", "e", ")", ")", "return", "except", "Exception", "as", "e", ":", "# This catches all other exceptions.", "if", "coord", ":", "coord", ".", "request_stop", "(", "e", ")", "else", ":", "logging", ".", "error", "(", "\"Exception in QueueRunner: %s\"", ",", "str", "(", "e", ")", ")", "with", "self", ".", "_lock", ":", "self", ".", "_exceptions_raised", ".", "append", "(", "e", ")", "raise", "finally", ":", "# Make sure we account for all terminations: normal or errors.", "if", "not", "decremented", ":", "with", "self", ".", "_lock", ":", "self", ".", "_runs", "-=", "1" ]
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/contrib/learn/python/learn/dataframe/queues/feeding_queue_runner.py#L64-L109
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/xml/etree/ElementTree.py
python
Element.keys
(self)
return self.attrib.keys()
Get list of attribute names. Names are returned in an arbitrary order, just like an ordinary Python dict. Equivalent to attrib.keys()
Get list of attribute names.
[ "Get", "list", "of", "attribute", "names", "." ]
def keys(self): """Get list of attribute names. Names are returned in an arbitrary order, just like an ordinary Python dict. Equivalent to attrib.keys() """ return self.attrib.keys()
[ "def", "keys", "(", "self", ")", ":", "return", "self", ".", "attrib", ".", "keys", "(", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/xml/etree/ElementTree.py#L371-L378
oracle/graaljs
36a56e8e993d45fc40939a3a4d9c0c24990720f1
graal-js/mx.graal-js/mx_graal_js.py
python
testv8
(args, nonZeroIsFatal=True)
run the testV8 conformance suite
run the testV8 conformance suite
[ "run", "the", "testV8", "conformance", "suite" ]
def testv8(args, nonZeroIsFatal=True): """run the testV8 conformance suite""" _location = join(_suite.dir, 'lib', 'testv8') _stack_size = '3m' if mx.get_arch() in ('aarch64', 'sparcv9') else '1m' _run_test_suite( location=_location, library_names=['TESTV8'], custom_args=args, default_vm_args=[], max_heap='8g', stack_size=_stack_size, main_class='com.oracle.truffle.js.test.external.testv8.TestV8', nonZeroIsFatal=nonZeroIsFatal, cwd=_suite.dir )
[ "def", "testv8", "(", "args", ",", "nonZeroIsFatal", "=", "True", ")", ":", "_location", "=", "join", "(", "_suite", ".", "dir", ",", "'lib'", ",", "'testv8'", ")", "_stack_size", "=", "'3m'", "if", "mx", ".", "get_arch", "(", ")", "in", "(", "'aarch64'", ",", "'sparcv9'", ")", "else", "'1m'", "_run_test_suite", "(", "location", "=", "_location", ",", "library_names", "=", "[", "'TESTV8'", "]", ",", "custom_args", "=", "args", ",", "default_vm_args", "=", "[", "]", ",", "max_heap", "=", "'8g'", ",", "stack_size", "=", "_stack_size", ",", "main_class", "=", "'com.oracle.truffle.js.test.external.testv8.TestV8'", ",", "nonZeroIsFatal", "=", "nonZeroIsFatal", ",", "cwd", "=", "_suite", ".", "dir", ")" ]
https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-js/mx.graal-js/mx_graal_js.py#L259-L273
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/turtle.py
python
TNavigator.ycor
(self)
return self._position[1]
Return the turtle's y coordinate --- No arguments. Example (for a Turtle instance named turtle): >>> reset() >>> turtle.left(60) >>> turtle.forward(100) >>> print turtle.ycor() 86.6025403784
Return the turtle's y coordinate --- No arguments.
[ "Return", "the", "turtle", "s", "y", "coordinate", "---", "No", "arguments", "." ]
def ycor(self): """ Return the turtle's y coordinate --- No arguments. Example (for a Turtle instance named turtle): >>> reset() >>> turtle.left(60) >>> turtle.forward(100) >>> print turtle.ycor() 86.6025403784 """ return self._position[1]
[ "def", "ycor", "(", "self", ")", ":", "return", "self", ".", "_position", "[", "1", "]" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/turtle.py#L1729-L1741
LiquidPlayer/LiquidCore
9405979363f2353ac9a71ad8ab59685dd7f919c9
deps/node-10.15.3/tools/gyp/pylib/gyp/generator/ninja.py
python
NinjaWriter.GetToolchainEnv
(self, additional_settings=None)
return env
Returns the variables toolchain would set for build steps.
Returns the variables toolchain would set for build steps.
[ "Returns", "the", "variables", "toolchain", "would", "set", "for", "build", "steps", "." ]
def GetToolchainEnv(self, additional_settings=None): """Returns the variables toolchain would set for build steps.""" env = self.GetSortedXcodeEnv(additional_settings=additional_settings) if self.flavor == 'win': env = self.GetMsvsToolchainEnv( additional_settings=additional_settings) return env
[ "def", "GetToolchainEnv", "(", "self", ",", "additional_settings", "=", "None", ")", ":", "env", "=", "self", ".", "GetSortedXcodeEnv", "(", "additional_settings", "=", "additional_settings", ")", "if", "self", ".", "flavor", "==", "'win'", ":", "env", "=", "self", ".", "GetMsvsToolchainEnv", "(", "additional_settings", "=", "additional_settings", ")", "return", "env" ]
https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/tools/gyp/pylib/gyp/generator/ninja.py#L1391-L1397
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_core.py
python
IdleEvent.RequestMore
(*args, **kwargs)
return _core_.IdleEvent_RequestMore(*args, **kwargs)
RequestMore(self, bool needMore=True) Tells wxWidgets that more processing is required. This function can be called by an EVT_IDLE handler for a window to indicate that the application should forward the EVT_IDLE event once more to the application windows. If no window calls this function during its EVT_IDLE handler, then the application will remain in a passive event loop until a new event is posted to the application by the windowing system.
RequestMore(self, bool needMore=True)
[ "RequestMore", "(", "self", "bool", "needMore", "=", "True", ")" ]
def RequestMore(*args, **kwargs): """ RequestMore(self, bool needMore=True) Tells wxWidgets that more processing is required. This function can be called by an EVT_IDLE handler for a window to indicate that the application should forward the EVT_IDLE event once more to the application windows. If no window calls this function during its EVT_IDLE handler, then the application will remain in a passive event loop until a new event is posted to the application by the windowing system. """ return _core_.IdleEvent_RequestMore(*args, **kwargs)
[ "def", "RequestMore", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "IdleEvent_RequestMore", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L7456-L7468
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/third_party/lib_x86_64/python2.7/dist-packages/catkin_pkg/cmake.py
python
configure_file
(template_file, environment)
Evaluate a .in template file used in CMake with configure_file(). :param template_file: path to the template, ``str`` :param environment: dictionary of placeholders to substitute, ``dict`` :returns: string with evaluates template :raises: KeyError for placeholders in the template which are not in the environment
Evaluate a .in template file used in CMake with configure_file().
[ "Evaluate", "a", ".", "in", "template", "file", "used", "in", "CMake", "with", "configure_file", "()", "." ]
def configure_file(template_file, environment): ''' Evaluate a .in template file used in CMake with configure_file(). :param template_file: path to the template, ``str`` :param environment: dictionary of placeholders to substitute, ``dict`` :returns: string with evaluates template :raises: KeyError for placeholders in the template which are not in the environment ''' with open(template_file, 'r') as f: template = f.read() return configure_string(template, environment)
[ "def", "configure_file", "(", "template_file", ",", "environment", ")", ":", "with", "open", "(", "template_file", ",", "'r'", ")", "as", "f", ":", "template", "=", "f", ".", "read", "(", ")", "return", "configure_string", "(", "template", ",", "environment", ")" ]
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/catkin_pkg/cmake.py#L50-L63
wujian16/Cornell-MOE
df299d1be882d2af9796d7a68b3f9505cac7a53e
moe/optimal_learning/python/cpp_wrappers/knowledge_gradient_mcmc.py
python
KnowledgeGradientMCMC.compute_grad_knowledge_gradient_mcmc
(self, force_monte_carlo=False)
return grad_knowledge_gradient_mcmc
r"""Compute the gradient of knowledge gradient at ``points_to_sample`` wrt ``points_to_sample``, with ``points_being_sampled`` concurrent samples. .. Note:: These comments were copied from :meth:`moe.optimal_learning.python.interfaces.expected_improvement_interface.ExpectedImprovementInterface.compute_grad_expected_improvement` ``points_to_sample`` is the "q" and ``points_being_sampled`` is the "p" in q,p-EI. In general, the expressions for gradients of EI are complex and difficult to evaluate; hence we use Monte-Carlo simulation to approximate it. When faster (e.g., analytic) techniques are available, we will prefer them. The MC computation of grad EI is similar to the computation of EI (decsribed in compute_expected_improvement). We differentiate ``y = \mu + Lw`` wrt ``points_to_sample``; only terms from the gradient of ``\mu`` and ``L`` contribute. In EI, we computed: ``improvement_per_step = max(max(best_so_far - y), 0.0)`` and noted that only the smallest component of ``y`` may contribute (if it is > 0.0). Call this index ``winner``. Thus in computing grad EI, we only add gradient terms that are attributable to the ``winner``-th component of ``y``. :param force_monte_carlo: whether to force monte carlo evaluation (vs using fast/accurate analytic eval when possible) :type force_monte_carlo: boolean :return: gradient of EI, ``\pderiv{EI(Xq \cup Xp)}{Xq_{i,d}}`` where ``Xq`` is ``points_to_sample`` and ``Xp`` is ``points_being_sampled`` (grad EI from sampling ``points_to_sample`` with ``points_being_sampled`` concurrent experiments wrt each dimension of the points in ``points_to_sample``) :rtype: array of float64 with shape (num_to_sample, dim)
r"""Compute the gradient of knowledge gradient at ``points_to_sample`` wrt ``points_to_sample``, with ``points_being_sampled`` concurrent samples.
[ "r", "Compute", "the", "gradient", "of", "knowledge", "gradient", "at", "points_to_sample", "wrt", "points_to_sample", "with", "points_being_sampled", "concurrent", "samples", "." ]
def compute_grad_knowledge_gradient_mcmc(self, force_monte_carlo=False): r"""Compute the gradient of knowledge gradient at ``points_to_sample`` wrt ``points_to_sample``, with ``points_being_sampled`` concurrent samples. .. Note:: These comments were copied from :meth:`moe.optimal_learning.python.interfaces.expected_improvement_interface.ExpectedImprovementInterface.compute_grad_expected_improvement` ``points_to_sample`` is the "q" and ``points_being_sampled`` is the "p" in q,p-EI. In general, the expressions for gradients of EI are complex and difficult to evaluate; hence we use Monte-Carlo simulation to approximate it. When faster (e.g., analytic) techniques are available, we will prefer them. The MC computation of grad EI is similar to the computation of EI (decsribed in compute_expected_improvement). We differentiate ``y = \mu + Lw`` wrt ``points_to_sample``; only terms from the gradient of ``\mu`` and ``L`` contribute. In EI, we computed: ``improvement_per_step = max(max(best_so_far - y), 0.0)`` and noted that only the smallest component of ``y`` may contribute (if it is > 0.0). Call this index ``winner``. Thus in computing grad EI, we only add gradient terms that are attributable to the ``winner``-th component of ``y``. :param force_monte_carlo: whether to force monte carlo evaluation (vs using fast/accurate analytic eval when possible) :type force_monte_carlo: boolean :return: gradient of EI, ``\pderiv{EI(Xq \cup Xp)}{Xq_{i,d}}`` where ``Xq`` is ``points_to_sample`` and ``Xp`` is ``points_being_sampled`` (grad EI from sampling ``points_to_sample`` with ``points_being_sampled`` concurrent experiments wrt each dimension of the points in ``points_to_sample``) :rtype: array of float64 with shape (num_to_sample, dim) """ grad_knowledge_gradient_mcmc = C_GP.compute_grad_knowledge_gradient_mcmc( self._gaussian_process_mcmc._gaussian_process_mcmc, self._num_fidelity, self._inner_optimizer.optimizer_parameters, cpp_utils.cppify(self._inner_optimizer.domain.domain_bounds), cpp_utils.cppify(self._discrete_pts_list), cpp_utils.cppify(self._points_to_sample), cpp_utils.cppify(self._points_being_sampled), self.discrete, self.num_to_sample, self.num_being_sampled, self._num_mc_iterations, cpp_utils.cppify(self._best_so_far_list), self._randomness, ) return grad_knowledge_gradient_mcmc
[ "def", "compute_grad_knowledge_gradient_mcmc", "(", "self", ",", "force_monte_carlo", "=", "False", ")", ":", "grad_knowledge_gradient_mcmc", "=", "C_GP", ".", "compute_grad_knowledge_gradient_mcmc", "(", "self", ".", "_gaussian_process_mcmc", ".", "_gaussian_process_mcmc", ",", "self", ".", "_num_fidelity", ",", "self", ".", "_inner_optimizer", ".", "optimizer_parameters", ",", "cpp_utils", ".", "cppify", "(", "self", ".", "_inner_optimizer", ".", "domain", ".", "domain_bounds", ")", ",", "cpp_utils", ".", "cppify", "(", "self", ".", "_discrete_pts_list", ")", ",", "cpp_utils", ".", "cppify", "(", "self", ".", "_points_to_sample", ")", ",", "cpp_utils", ".", "cppify", "(", "self", ".", "_points_being_sampled", ")", ",", "self", ".", "discrete", ",", "self", ".", "num_to_sample", ",", "self", ".", "num_being_sampled", ",", "self", ".", "_num_mc_iterations", ",", "cpp_utils", ".", "cppify", "(", "self", ".", "_best_so_far_list", ")", ",", "self", ".", "_randomness", ",", ")", "return", "grad_knowledge_gradient_mcmc" ]
https://github.com/wujian16/Cornell-MOE/blob/df299d1be882d2af9796d7a68b3f9505cac7a53e/moe/optimal_learning/python/cpp_wrappers/knowledge_gradient_mcmc.py#L575-L617
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/distributions/python/ops/mvn_linear_operator.py
python
MultivariateNormalLinearOperator.scale
(self)
return self.bijector.scale
The `scale` `LinearOperator` in `Y = scale @ X + loc`.
The `scale` `LinearOperator` in `Y = scale
[ "The", "scale", "LinearOperator", "in", "Y", "=", "scale" ]
def scale(self): """The `scale` `LinearOperator` in `Y = scale @ X + loc`.""" return self.bijector.scale
[ "def", "scale", "(", "self", ")", ":", "return", "self", ".", "bijector", ".", "scale" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/distributions/python/ops/mvn_linear_operator.py#L214-L216
google/nucleus
68d3947fafba1337f294c0668a6e1c7f3f1273e3
nucleus/util/variant_utils.py
python
has_calls
(variant)
return bool(variant.calls)
Does variant have any genotype calls? Args: variant: nucleus.genomics.v1.Variant. Returns: True if variant has one or more VariantCalls.
Does variant have any genotype calls?
[ "Does", "variant", "have", "any", "genotype", "calls?" ]
def has_calls(variant): """Does variant have any genotype calls? Args: variant: nucleus.genomics.v1.Variant. Returns: True if variant has one or more VariantCalls. """ return bool(variant.calls)
[ "def", "has_calls", "(", "variant", ")", ":", "return", "bool", "(", "variant", ".", "calls", ")" ]
https://github.com/google/nucleus/blob/68d3947fafba1337f294c0668a6e1c7f3f1273e3/nucleus/util/variant_utils.py#L608-L617
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/SimpleXMLRPCServer.py
python
SimpleXMLRPCDispatcher.register_multicall_functions
(self)
Registers the XML-RPC multicall method in the system namespace. see http://www.xmlrpc.com/discuss/msgReader$1208
Registers the XML-RPC multicall method in the system namespace.
[ "Registers", "the", "XML", "-", "RPC", "multicall", "method", "in", "the", "system", "namespace", "." ]
def register_multicall_functions(self): """Registers the XML-RPC multicall method in the system namespace. see http://www.xmlrpc.com/discuss/msgReader$1208""" self.funcs.update({'system.multicall' : self.system_multicall})
[ "def", "register_multicall_functions", "(", "self", ")", ":", "self", ".", "funcs", ".", "update", "(", "{", "'system.multicall'", ":", "self", ".", "system_multicall", "}", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/SimpleXMLRPCServer.py#L233-L239
Kitware/ParaView
f760af9124ff4634b23ebbeab95a4f56e0261955
ThirdParty/cinema/paraview/tpl/cinema_python/database/store.py
python
Store.add_field
(self, name, properties, parent_layer, parents_values)
A field is a component of the final color for a layer. Examples include: depth, normal, color, scalar values.
A field is a component of the final color for a layer. Examples include: depth, normal, color, scalar values.
[ "A", "field", "is", "a", "component", "of", "the", "final", "color", "for", "a", "layer", ".", "Examples", "include", ":", "depth", "normal", "color", "scalar", "values", "." ]
def add_field(self, name, properties, parent_layer, parents_values): """ A field is a component of the final color for a layer. Examples include: depth, normal, color, scalar values. """ properties['type'] = 'hidden' properties['role'] = 'field' self.add_parameter(name, properties) self.assign_parameter_dependence(name, parent_layer, parents_values)
[ "def", "add_field", "(", "self", ",", "name", ",", "properties", ",", "parent_layer", ",", "parents_values", ")", ":", "properties", "[", "'type'", "]", "=", "'hidden'", "properties", "[", "'role'", "]", "=", "'field'", "self", ".", "add_parameter", "(", "name", ",", "properties", ")", "self", ".", "assign_parameter_dependence", "(", "name", ",", "parent_layer", ",", "parents_values", ")" ]
https://github.com/Kitware/ParaView/blob/f760af9124ff4634b23ebbeab95a4f56e0261955/ThirdParty/cinema/paraview/tpl/cinema_python/database/store.py#L513-L521
kamyu104/LeetCode-Solutions
77605708a927ea3b85aee5a479db733938c7c211
Python/best-team-with-no-conflicts.py
python
Solution4.bestTeamScore
(self, scores, ages)
return max(dp.itervalues())
:type scores: List[int] :type ages: List[int] :rtype: int
:type scores: List[int] :type ages: List[int] :rtype: int
[ ":", "type", "scores", ":", "List", "[", "int", "]", ":", "type", "ages", ":", "List", "[", "int", "]", ":", "rtype", ":", "int" ]
def bestTeamScore(self, scores, ages): """ :type scores: List[int] :type ages: List[int] :rtype: int """ players = sorted(zip(ages, scores)) sorted_scores = sorted(set(scores)) dp = collections.defaultdict(int) result = 0 for age, score in players: dp[score] = max(dp[s] for s in sorted_scores if s <= score) + score return max(dp.itervalues())
[ "def", "bestTeamScore", "(", "self", ",", "scores", ",", "ages", ")", ":", "players", "=", "sorted", "(", "zip", "(", "ages", ",", "scores", ")", ")", "sorted_scores", "=", "sorted", "(", "set", "(", "scores", ")", ")", "dp", "=", "collections", ".", "defaultdict", "(", "int", ")", "result", "=", "0", "for", "age", ",", "score", "in", "players", ":", "dp", "[", "score", "]", "=", "max", "(", "dp", "[", "s", "]", "for", "s", "in", "sorted_scores", "if", "s", "<=", "score", ")", "+", "score", "return", "max", "(", "dp", ".", "itervalues", "(", ")", ")" ]
https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/best-team-with-no-conflicts.py#L151-L163
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
torch/distributed/rpc/backend_registry.py
python
backend_registered
(backend_name)
return backend_name in BackendType.__members__.keys()
Checks if backend_name is registered as an RPC backend. Args: backend_name (str): string to identify the RPC backend. Returns: True if the backend has been registered with ``register_backend``, else False.
Checks if backend_name is registered as an RPC backend.
[ "Checks", "if", "backend_name", "is", "registered", "as", "an", "RPC", "backend", "." ]
def backend_registered(backend_name): """ Checks if backend_name is registered as an RPC backend. Args: backend_name (str): string to identify the RPC backend. Returns: True if the backend has been registered with ``register_backend``, else False. """ return backend_name in BackendType.__members__.keys()
[ "def", "backend_registered", "(", "backend_name", ")", ":", "return", "backend_name", "in", "BackendType", ".", "__members__", ".", "keys", "(", ")" ]
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/distributed/rpc/backend_registry.py#L37-L47
taskflow/taskflow
f423a100a70b275f6e7331bc96537a3fe172e8d7
3rd-party/tbb/python/tbb/pool.py
python
Pool.join
(self)
Wait for the worker processes to exit. One must call close() or terminate() before using join().
Wait for the worker processes to exit. One must call close() or terminate() before using join().
[ "Wait", "for", "the", "worker", "processes", "to", "exit", ".", "One", "must", "call", "close", "()", "or", "terminate", "()", "before", "using", "join", "()", "." ]
def join(self): """Wait for the worker processes to exit. One must call close() or terminate() before using join().""" self._tasks.wait()
[ "def", "join", "(", "self", ")", ":", "self", ".", "_tasks", ".", "wait", "(", ")" ]
https://github.com/taskflow/taskflow/blob/f423a100a70b275f6e7331bc96537a3fe172e8d7/3rd-party/tbb/python/tbb/pool.py#L220-L223
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_core.py
python
PyApp.GetTraits
(*args, **kwargs)
return _core_.PyApp_GetTraits(*args, **kwargs)
GetTraits(self) -> wxAppTraits Return (and create if necessary) the app traits object to which we delegate for everything which either should be configurable by the user (then he can change the default behaviour simply by overriding CreateTraits() and returning his own traits object) or which is GUI/console dependent as then wx.AppTraits allows us to abstract the differences behind the common facade. :todo: Add support for overriding CreateAppTraits in wxPython.
GetTraits(self) -> wxAppTraits
[ "GetTraits", "(", "self", ")", "-", ">", "wxAppTraits" ]
def GetTraits(*args, **kwargs): """ GetTraits(self) -> wxAppTraits Return (and create if necessary) the app traits object to which we delegate for everything which either should be configurable by the user (then he can change the default behaviour simply by overriding CreateTraits() and returning his own traits object) or which is GUI/console dependent as then wx.AppTraits allows us to abstract the differences behind the common facade. :todo: Add support for overriding CreateAppTraits in wxPython. """ return _core_.PyApp_GetTraits(*args, **kwargs)
[ "def", "GetTraits", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "PyApp_GetTraits", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L7804-L7817
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/keras/losses.py
python
_ragged_tensor_msle
(y_true, y_pred)
return _ragged_tensor_apply_loss(mean_squared_logarithmic_error, y_true, y_pred)
Implements support for handling RaggedTensors.
Implements support for handling RaggedTensors.
[ "Implements", "support", "for", "handling", "RaggedTensors", "." ]
def _ragged_tensor_msle(y_true, y_pred): """Implements support for handling RaggedTensors.""" return _ragged_tensor_apply_loss(mean_squared_logarithmic_error, y_true, y_pred)
[ "def", "_ragged_tensor_msle", "(", "y_true", ",", "y_pred", ")", ":", "return", "_ragged_tensor_apply_loss", "(", "mean_squared_logarithmic_error", ",", "y_true", ",", "y_pred", ")" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/keras/losses.py#L1439-L1442
generalized-intelligence/GAAS
29ab17d3e8a4ba18edef3a57c36d8db6329fac73
algorithms/src/LocalizationAndMapping/registration_localization/fast_gicp/thirdparty/Sophus/py/sophus/quaternion.py
python
Quaternion.__mul__
(self, right)
return Quaternion(self[3] * right[3] - self.vec.dot(right.vec), self[3] * right.vec + right[3] * self.vec + self.vec.cross(right.vec))
quaternion multiplication
quaternion multiplication
[ "quaternion", "multiplication" ]
def __mul__(self, right): """ quaternion multiplication """ return Quaternion(self[3] * right[3] - self.vec.dot(right.vec), self[3] * right.vec + right[3] * self.vec + self.vec.cross(right.vec))
[ "def", "__mul__", "(", "self", ",", "right", ")", ":", "return", "Quaternion", "(", "self", "[", "3", "]", "*", "right", "[", "3", "]", "-", "self", ".", "vec", ".", "dot", "(", "right", ".", "vec", ")", ",", "self", "[", "3", "]", "*", "right", ".", "vec", "+", "right", "[", "3", "]", "*", "self", ".", "vec", "+", "self", ".", "vec", ".", "cross", "(", "right", ".", "vec", ")", ")" ]
https://github.com/generalized-intelligence/GAAS/blob/29ab17d3e8a4ba18edef3a57c36d8db6329fac73/algorithms/src/LocalizationAndMapping/registration_localization/fast_gicp/thirdparty/Sophus/py/sophus/quaternion.py#L19-L23
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/ops/functional_ops.py
python
scan
(fn, elems, initializer=None, parallel_iterations=10, back_prop=True, swap_memory=False, infer_shape=True, name=None)
scan on the list of tensors unpacked from `elems` on dimension 0. The simplest version of `scan` repeatedly applies the callable `fn` to a sequence of elements from first to last. The elements are made of the tensors unpacked from `elems` on dimension 0. The callable fn takes two tensors as arguments. The first argument is the accumulated value computed from the preceding invocation of fn. If `initializer` is None, `elems` must contain at least one element, and its first element is used as the initializer. Suppose that `elems` is unpacked into `values`, a list of tensors. The shape of the result tensor is `[len(values)] + fn(initializer, values[0]).shape`. This method also allows multi-arity `elems` and accumulator. If `elems` is a (possibly nested) list or tuple of tensors, then each of these tensors must have a matching first (unpack) dimension. The second argument of `fn` must match the structure of `elems`. If no `initializer` is provided, the output structure and dtypes of `fn` are assumed to be the same as its input; and in this case, the first argument of `fn` must match the structure of `elems`. If an `initializer` is provided, then the output of `fn` must have the same structure as `initializer`; and the first argument of `fn` must match this structure. For example, if `elems` is `(t1, [t2, t3])` and `initializer` is `[i1, i2]` then an appropriate signature for `fn` in `python2` is: `fn = lambda (acc_p1, acc_p2), (t1 [t2, t3]):` and `fn` must return a list, `[acc_n1, acc_n2]`. An alternative correct signature for `fn`, and the one that works in `python3`, is: `fn = lambda a, t:`, where `a` and `t` correspond to the input tuples. Args: fn: The callable to be performed. It accepts two arguments. The first will have the same structure as `initializer` if one is provided, otherwise it will have the same structure as `elems`. The second will have the same (possibly nested) structure as `elems`. Its output must have the same structure as `initializer` if one is provided, otherwise it must have the same structure as `elems`. elems: A tensor or (possibly nested) sequence of tensors, each of which will be unpacked along their first dimension. The nested sequence of the resulting slices will be the first argument to `fn`. initializer: (optional) A tensor or (possibly nested) sequence of tensors, initial value for the accumulator, and the expected output type of `fn`. parallel_iterations: (optional) The number of iterations allowed to run in parallel. back_prop: (optional) True enables support for back propagation. swap_memory: (optional) True enables GPU-CPU memory swapping. infer_shape: (optional) False disables tests for consistent output shapes. name: (optional) Name prefix for the returned tensors. Returns: A tensor or (possibly nested) sequence of tensors. Each tensor packs the results of applying `fn` to tensors unpacked from `elems` along the first dimension, and the previous accumulator value(s), from first to last. Raises: TypeError: if `fn` is not callable or the structure of the output of `fn` and `initializer` do not match. ValueError: if the lengths of the output of `fn` and `initializer` do not match. Examples: ```python elems = np.array([1, 2, 3, 4, 5, 6]) sum = scan(lambda a, x: a + x, elems) # sum == [1, 3, 6, 10, 15, 21] ``` ```python elems = np.array([1, 2, 3, 4, 5, 6]) initializer = np.array(0) sum_one = scan( lambda a, x: x[0] - x[1] + a, (elems + 1, elems), initializer) # sum_one == [1, 2, 3, 4, 5, 6] ``` ```python elems = np.array([1, 0, 0, 0, 0, 0]) initializer = (np.array(0), np.array(1)) fibonaccis = scan(lambda a, _: (a[1], a[0] + a[1]), elems, initializer) # fibonaccis == ([1, 1, 2, 3, 5, 8], [1, 2, 3, 5, 8, 13]) ```
scan on the list of tensors unpacked from `elems` on dimension 0.
[ "scan", "on", "the", "list", "of", "tensors", "unpacked", "from", "elems", "on", "dimension", "0", "." ]
def scan(fn, elems, initializer=None, parallel_iterations=10, back_prop=True, swap_memory=False, infer_shape=True, name=None): """scan on the list of tensors unpacked from `elems` on dimension 0. The simplest version of `scan` repeatedly applies the callable `fn` to a sequence of elements from first to last. The elements are made of the tensors unpacked from `elems` on dimension 0. The callable fn takes two tensors as arguments. The first argument is the accumulated value computed from the preceding invocation of fn. If `initializer` is None, `elems` must contain at least one element, and its first element is used as the initializer. Suppose that `elems` is unpacked into `values`, a list of tensors. The shape of the result tensor is `[len(values)] + fn(initializer, values[0]).shape`. This method also allows multi-arity `elems` and accumulator. If `elems` is a (possibly nested) list or tuple of tensors, then each of these tensors must have a matching first (unpack) dimension. The second argument of `fn` must match the structure of `elems`. If no `initializer` is provided, the output structure and dtypes of `fn` are assumed to be the same as its input; and in this case, the first argument of `fn` must match the structure of `elems`. If an `initializer` is provided, then the output of `fn` must have the same structure as `initializer`; and the first argument of `fn` must match this structure. For example, if `elems` is `(t1, [t2, t3])` and `initializer` is `[i1, i2]` then an appropriate signature for `fn` in `python2` is: `fn = lambda (acc_p1, acc_p2), (t1 [t2, t3]):` and `fn` must return a list, `[acc_n1, acc_n2]`. An alternative correct signature for `fn`, and the one that works in `python3`, is: `fn = lambda a, t:`, where `a` and `t` correspond to the input tuples. Args: fn: The callable to be performed. It accepts two arguments. The first will have the same structure as `initializer` if one is provided, otherwise it will have the same structure as `elems`. The second will have the same (possibly nested) structure as `elems`. Its output must have the same structure as `initializer` if one is provided, otherwise it must have the same structure as `elems`. elems: A tensor or (possibly nested) sequence of tensors, each of which will be unpacked along their first dimension. The nested sequence of the resulting slices will be the first argument to `fn`. initializer: (optional) A tensor or (possibly nested) sequence of tensors, initial value for the accumulator, and the expected output type of `fn`. parallel_iterations: (optional) The number of iterations allowed to run in parallel. back_prop: (optional) True enables support for back propagation. swap_memory: (optional) True enables GPU-CPU memory swapping. infer_shape: (optional) False disables tests for consistent output shapes. name: (optional) Name prefix for the returned tensors. Returns: A tensor or (possibly nested) sequence of tensors. Each tensor packs the results of applying `fn` to tensors unpacked from `elems` along the first dimension, and the previous accumulator value(s), from first to last. Raises: TypeError: if `fn` is not callable or the structure of the output of `fn` and `initializer` do not match. ValueError: if the lengths of the output of `fn` and `initializer` do not match. Examples: ```python elems = np.array([1, 2, 3, 4, 5, 6]) sum = scan(lambda a, x: a + x, elems) # sum == [1, 3, 6, 10, 15, 21] ``` ```python elems = np.array([1, 2, 3, 4, 5, 6]) initializer = np.array(0) sum_one = scan( lambda a, x: x[0] - x[1] + a, (elems + 1, elems), initializer) # sum_one == [1, 2, 3, 4, 5, 6] ``` ```python elems = np.array([1, 0, 0, 0, 0, 0]) initializer = (np.array(0), np.array(1)) fibonaccis = scan(lambda a, _: (a[1], a[0] + a[1]), elems, initializer) # fibonaccis == ([1, 1, 2, 3, 5, 8], [1, 2, 3, 5, 8, 13]) ``` """ if not callable(fn): raise TypeError("fn must be callable.") input_is_sequence = nest.is_sequence(elems) input_flatten = lambda x: nest.flatten(x) if input_is_sequence else [x] def input_pack(x): return nest.pack_sequence_as(elems, x) if input_is_sequence else x[0] if initializer is None: output_is_sequence = input_is_sequence output_flatten = input_flatten output_pack = input_pack else: output_is_sequence = nest.is_sequence(initializer) output_flatten = lambda x: nest.flatten(x) if output_is_sequence else [x] def output_pack(x): return (nest.pack_sequence_as(initializer, x) if output_is_sequence else x[0]) elems_flat = input_flatten(elems) with ops.name_scope(name, "scan", elems_flat): # Any get_variable calls in fn will cache the first call locally # and not issue repeated network I/O requests for each iteration. varscope = vs.get_variable_scope() varscope_caching_device_was_none = False if varscope.caching_device is None: # TODO(ebrevdo): Change to using colocate_with here and in other methods. varscope.set_caching_device(lambda op: op.device) varscope_caching_device_was_none = True # Convert elems to tensor array. elems_flat = [ ops.convert_to_tensor(elem, name="elem") for elem in elems_flat] n = array_ops.shape(elems_flat[0])[0] # TensorArrays are always flat elems_ta = [ tensor_array_ops.TensorArray(dtype=elem.dtype, size=n, dynamic_size=False, infer_shape=True) for elem in elems_flat] # Unpack elements elems_ta = [ elem_ta.unstack(elem) for elem_ta, elem in zip(elems_ta, elems_flat)] if initializer is None: a_flat = [elem.read(0) for elem in elems_ta] i = constant_op.constant(1) else: initializer_flat = output_flatten(initializer) a_flat = [ops.convert_to_tensor(init) for init in initializer_flat] i = constant_op.constant(0) # Create a tensor array to store the intermediate values. accs_ta = [ tensor_array_ops.TensorArray( dtype=init.dtype, size=n, element_shape=init.shape if infer_shape else None, dynamic_size=False, infer_shape=infer_shape) for init in a_flat] if initializer is None: accs_ta = [acc_ta.write(0, a) for (acc_ta, a) in zip(accs_ta, a_flat)] def compute(i, a_flat, tas): """The loop body of scan. Args: i: the loop counter. a_flat: the accumulator value(s), flattened. tas: the output accumulator TensorArray(s), flattened. Returns: [i + 1, a_flat, tas]: the updated counter + new accumulator values + updated TensorArrays Raises: TypeError: if initializer and fn() output structure do not match ValueType: if initializer and fn() output lengths do not match """ packed_elems = input_pack([elem_ta.read(i) for elem_ta in elems_ta]) packed_a = output_pack(a_flat) a_out = fn(packed_a, packed_elems) nest.assert_same_structure( elems if initializer is None else initializer, a_out) flat_a_out = output_flatten(a_out) tas = [ta.write(i, value) for (ta, value) in zip(tas, flat_a_out)] return (i + 1, flat_a_out, tas) _, _, r_a = control_flow_ops.while_loop( lambda i, _1, _2: i < n, compute, (i, a_flat, accs_ta), parallel_iterations=parallel_iterations, back_prop=back_prop, swap_memory=swap_memory) results_flat = [r.stack() for r in r_a] n_static = elems_flat[0].get_shape().with_rank_at_least(1)[0] for elem in elems_flat[1:]: n_static.merge_with(elem.get_shape().with_rank_at_least(1)[0]) for r in results_flat: r.set_shape(tensor_shape.TensorShape(n_static).concatenate( r.get_shape()[1:])) if varscope_caching_device_was_none: varscope.set_caching_device(None) return output_pack(results_flat)
[ "def", "scan", "(", "fn", ",", "elems", ",", "initializer", "=", "None", ",", "parallel_iterations", "=", "10", ",", "back_prop", "=", "True", ",", "swap_memory", "=", "False", ",", "infer_shape", "=", "True", ",", "name", "=", "None", ")", ":", "if", "not", "callable", "(", "fn", ")", ":", "raise", "TypeError", "(", "\"fn must be callable.\"", ")", "input_is_sequence", "=", "nest", ".", "is_sequence", "(", "elems", ")", "input_flatten", "=", "lambda", "x", ":", "nest", ".", "flatten", "(", "x", ")", "if", "input_is_sequence", "else", "[", "x", "]", "def", "input_pack", "(", "x", ")", ":", "return", "nest", ".", "pack_sequence_as", "(", "elems", ",", "x", ")", "if", "input_is_sequence", "else", "x", "[", "0", "]", "if", "initializer", "is", "None", ":", "output_is_sequence", "=", "input_is_sequence", "output_flatten", "=", "input_flatten", "output_pack", "=", "input_pack", "else", ":", "output_is_sequence", "=", "nest", ".", "is_sequence", "(", "initializer", ")", "output_flatten", "=", "lambda", "x", ":", "nest", ".", "flatten", "(", "x", ")", "if", "output_is_sequence", "else", "[", "x", "]", "def", "output_pack", "(", "x", ")", ":", "return", "(", "nest", ".", "pack_sequence_as", "(", "initializer", ",", "x", ")", "if", "output_is_sequence", "else", "x", "[", "0", "]", ")", "elems_flat", "=", "input_flatten", "(", "elems", ")", "with", "ops", ".", "name_scope", "(", "name", ",", "\"scan\"", ",", "elems_flat", ")", ":", "# Any get_variable calls in fn will cache the first call locally", "# and not issue repeated network I/O requests for each iteration.", "varscope", "=", "vs", ".", "get_variable_scope", "(", ")", "varscope_caching_device_was_none", "=", "False", "if", "varscope", ".", "caching_device", "is", "None", ":", "# TODO(ebrevdo): Change to using colocate_with here and in other methods.", "varscope", ".", "set_caching_device", "(", "lambda", "op", ":", "op", ".", "device", ")", "varscope_caching_device_was_none", "=", "True", "# Convert elems to tensor array.", "elems_flat", "=", "[", "ops", ".", "convert_to_tensor", "(", "elem", ",", "name", "=", "\"elem\"", ")", "for", "elem", "in", "elems_flat", "]", "n", "=", "array_ops", ".", "shape", "(", "elems_flat", "[", "0", "]", ")", "[", "0", "]", "# TensorArrays are always flat", "elems_ta", "=", "[", "tensor_array_ops", ".", "TensorArray", "(", "dtype", "=", "elem", ".", "dtype", ",", "size", "=", "n", ",", "dynamic_size", "=", "False", ",", "infer_shape", "=", "True", ")", "for", "elem", "in", "elems_flat", "]", "# Unpack elements", "elems_ta", "=", "[", "elem_ta", ".", "unstack", "(", "elem", ")", "for", "elem_ta", ",", "elem", "in", "zip", "(", "elems_ta", ",", "elems_flat", ")", "]", "if", "initializer", "is", "None", ":", "a_flat", "=", "[", "elem", ".", "read", "(", "0", ")", "for", "elem", "in", "elems_ta", "]", "i", "=", "constant_op", ".", "constant", "(", "1", ")", "else", ":", "initializer_flat", "=", "output_flatten", "(", "initializer", ")", "a_flat", "=", "[", "ops", ".", "convert_to_tensor", "(", "init", ")", "for", "init", "in", "initializer_flat", "]", "i", "=", "constant_op", ".", "constant", "(", "0", ")", "# Create a tensor array to store the intermediate values.", "accs_ta", "=", "[", "tensor_array_ops", ".", "TensorArray", "(", "dtype", "=", "init", ".", "dtype", ",", "size", "=", "n", ",", "element_shape", "=", "init", ".", "shape", "if", "infer_shape", "else", "None", ",", "dynamic_size", "=", "False", ",", "infer_shape", "=", "infer_shape", ")", "for", "init", "in", "a_flat", "]", "if", "initializer", "is", "None", ":", "accs_ta", "=", "[", "acc_ta", ".", "write", "(", "0", ",", "a", ")", "for", "(", "acc_ta", ",", "a", ")", "in", "zip", "(", "accs_ta", ",", "a_flat", ")", "]", "def", "compute", "(", "i", ",", "a_flat", ",", "tas", ")", ":", "\"\"\"The loop body of scan.\n\n Args:\n i: the loop counter.\n a_flat: the accumulator value(s), flattened.\n tas: the output accumulator TensorArray(s), flattened.\n\n Returns:\n [i + 1, a_flat, tas]: the updated counter + new accumulator values +\n updated TensorArrays\n\n Raises:\n TypeError: if initializer and fn() output structure do not match\n ValueType: if initializer and fn() output lengths do not match\n \"\"\"", "packed_elems", "=", "input_pack", "(", "[", "elem_ta", ".", "read", "(", "i", ")", "for", "elem_ta", "in", "elems_ta", "]", ")", "packed_a", "=", "output_pack", "(", "a_flat", ")", "a_out", "=", "fn", "(", "packed_a", ",", "packed_elems", ")", "nest", ".", "assert_same_structure", "(", "elems", "if", "initializer", "is", "None", "else", "initializer", ",", "a_out", ")", "flat_a_out", "=", "output_flatten", "(", "a_out", ")", "tas", "=", "[", "ta", ".", "write", "(", "i", ",", "value", ")", "for", "(", "ta", ",", "value", ")", "in", "zip", "(", "tas", ",", "flat_a_out", ")", "]", "return", "(", "i", "+", "1", ",", "flat_a_out", ",", "tas", ")", "_", ",", "_", ",", "r_a", "=", "control_flow_ops", ".", "while_loop", "(", "lambda", "i", ",", "_1", ",", "_2", ":", "i", "<", "n", ",", "compute", ",", "(", "i", ",", "a_flat", ",", "accs_ta", ")", ",", "parallel_iterations", "=", "parallel_iterations", ",", "back_prop", "=", "back_prop", ",", "swap_memory", "=", "swap_memory", ")", "results_flat", "=", "[", "r", ".", "stack", "(", ")", "for", "r", "in", "r_a", "]", "n_static", "=", "elems_flat", "[", "0", "]", ".", "get_shape", "(", ")", ".", "with_rank_at_least", "(", "1", ")", "[", "0", "]", "for", "elem", "in", "elems_flat", "[", "1", ":", "]", ":", "n_static", ".", "merge_with", "(", "elem", ".", "get_shape", "(", ")", ".", "with_rank_at_least", "(", "1", ")", "[", "0", "]", ")", "for", "r", "in", "results_flat", ":", "r", ".", "set_shape", "(", "tensor_shape", ".", "TensorShape", "(", "n_static", ")", ".", "concatenate", "(", "r", ".", "get_shape", "(", ")", "[", "1", ":", "]", ")", ")", "if", "varscope_caching_device_was_none", ":", "varscope", ".", "set_caching_device", "(", "None", ")", "return", "output_pack", "(", "results_flat", ")" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/ops/functional_ops.py#L405-L600
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/hmac.py
python
HMAC.copy
(self)
return other
Return a separate copy of this hashing object. An update to this copy won't affect the original object.
Return a separate copy of this hashing object.
[ "Return", "a", "separate", "copy", "of", "this", "hashing", "object", "." ]
def copy(self): """Return a separate copy of this hashing object. An update to this copy won't affect the original object. """ other = self.__class__(_secret_backdoor_key) other.digest_cons = self.digest_cons other.digest_size = self.digest_size other.inner = self.inner.copy() other.outer = self.outer.copy() return other
[ "def", "copy", "(", "self", ")", ":", "other", "=", "self", ".", "__class__", "(", "_secret_backdoor_key", ")", "other", ".", "digest_cons", "=", "self", ".", "digest_cons", "other", ".", "digest_size", "=", "self", ".", "digest_size", "other", ".", "inner", "=", "self", ".", "inner", ".", "copy", "(", ")", "other", ".", "outer", "=", "self", ".", "outer", ".", "copy", "(", ")", "return", "other" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/hmac.py#L85-L95
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib-tk/Tkinter.py
python
PanedWindow.identify
(self, x, y)
return self.tk.call(self._w, 'identify', x, y)
Identify the panedwindow component at point x, y If the point is over a sash or a sash handle, the result is a two element list containing the index of the sash or handle, and a word indicating whether it is over a sash or a handle, such as {0 sash} or {2 handle}. If the point is over any other part of the panedwindow, the result is an empty list.
Identify the panedwindow component at point x, y
[ "Identify", "the", "panedwindow", "component", "at", "point", "x", "y" ]
def identify(self, x, y): """Identify the panedwindow component at point x, y If the point is over a sash or a sash handle, the result is a two element list containing the index of the sash or handle, and a word indicating whether it is over a sash or a handle, such as {0 sash} or {2 handle}. If the point is over any other part of the panedwindow, the result is an empty list. """ return self.tk.call(self._w, 'identify', x, y)
[ "def", "identify", "(", "self", ",", "x", ",", "y", ")", ":", "return", "self", ".", "tk", ".", "call", "(", "self", ".", "_w", ",", "'identify'", ",", "x", ",", "y", ")" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib-tk/Tkinter.py#L3587-L3597
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_misc.py
python
LogStderr.__init__
(self, *args, **kwargs)
__init__(self) -> LogStderr
__init__(self) -> LogStderr
[ "__init__", "(", "self", ")", "-", ">", "LogStderr" ]
def __init__(self, *args, **kwargs): """__init__(self) -> LogStderr""" _misc_.LogStderr_swiginit(self,_misc_.new_LogStderr(*args, **kwargs))
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_misc_", ".", "LogStderr_swiginit", "(", "self", ",", "_misc_", ".", "new_LogStderr", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_misc.py#L1740-L1742
stack-of-tasks/pinocchio
593d4d43fded997bb9aa2421f4e55294dbd233c4
bindings/python/pinocchio/visualize/gepetto_visualizer.py
python
GepettoVisualizer.displayCollisions
(self,visibility)
Set whether to display collision objects or not
Set whether to display collision objects or not
[ "Set", "whether", "to", "display", "collision", "objects", "or", "not" ]
def displayCollisions(self,visibility): """Set whether to display collision objects or not""" gui = self.viewer.gui self.display_collisions = visibility if self.collision_model is None: return if visibility: visibility_mode = "ON" else: visibility_mode = "OFF" for collision in self.collision_model.geometryObjects: nodeName = self.getViewerNodeName(collision,pin.GeometryType.COLLISION) gui.setVisibility(nodeName,visibility_mode)
[ "def", "displayCollisions", "(", "self", ",", "visibility", ")", ":", "gui", "=", "self", ".", "viewer", ".", "gui", "self", ".", "display_collisions", "=", "visibility", "if", "self", ".", "collision_model", "is", "None", ":", "return", "if", "visibility", ":", "visibility_mode", "=", "\"ON\"", "else", ":", "visibility_mode", "=", "\"OFF\"", "for", "collision", "in", "self", ".", "collision_model", ".", "geometryObjects", ":", "nodeName", "=", "self", ".", "getViewerNodeName", "(", "collision", ",", "pin", ".", "GeometryType", ".", "COLLISION", ")", "gui", ".", "setVisibility", "(", "nodeName", ",", "visibility_mode", ")" ]
https://github.com/stack-of-tasks/pinocchio/blob/593d4d43fded997bb9aa2421f4e55294dbd233c4/bindings/python/pinocchio/visualize/gepetto_visualizer.py#L192-L205
hpi-xnor/BMXNet
ed0b201da6667887222b8e4b5f997c4f6b61943d
python/mxnet/symbol/symbol.py
python
Symbol.__mul__
(self, other)
x.__mul__(y) <=> x*y Scalar input is supported. Broadcasting is not supported. Use `broadcast_mul` instead.
x.__mul__(y) <=> x*y
[ "x", ".", "__mul__", "(", "y", ")", "<", "=", ">", "x", "*", "y" ]
def __mul__(self, other): """x.__mul__(y) <=> x*y Scalar input is supported. Broadcasting is not supported. Use `broadcast_mul` instead. """ if isinstance(other, Symbol): return _internal._Mul(self, other) if isinstance(other, Number): return _internal._MulScalar(self, scalar=other) else: raise TypeError('type %s not supported' % str(type(other)))
[ "def", "__mul__", "(", "self", ",", "other", ")", ":", "if", "isinstance", "(", "other", ",", "Symbol", ")", ":", "return", "_internal", ".", "_Mul", "(", "self", ",", "other", ")", "if", "isinstance", "(", "other", ",", "Number", ")", ":", "return", "_internal", ".", "_MulScalar", "(", "self", ",", "scalar", "=", "other", ")", "else", ":", "raise", "TypeError", "(", "'type %s not supported'", "%", "str", "(", "type", "(", "other", ")", ")", ")" ]
https://github.com/hpi-xnor/BMXNet/blob/ed0b201da6667887222b8e4b5f997c4f6b61943d/python/mxnet/symbol/symbol.py#L142-L152
klzgrad/naiveproxy
ed2c513637c77b18721fe428d7ed395b4d284c83
src/build/android/gyp/dist_aar.py
python
_MergeRTxt
(r_paths, include_globs)
return ''.join(sorted(all_lines))
Merging the given R.txt files and returns them as a string.
Merging the given R.txt files and returns them as a string.
[ "Merging", "the", "given", "R", ".", "txt", "files", "and", "returns", "them", "as", "a", "string", "." ]
def _MergeRTxt(r_paths, include_globs): """Merging the given R.txt files and returns them as a string.""" all_lines = set() for r_path in r_paths: if include_globs and not build_utils.MatchesGlob(r_path, include_globs): continue with open(r_path) as f: all_lines.update(f.readlines()) return ''.join(sorted(all_lines))
[ "def", "_MergeRTxt", "(", "r_paths", ",", "include_globs", ")", ":", "all_lines", "=", "set", "(", ")", "for", "r_path", "in", "r_paths", ":", "if", "include_globs", "and", "not", "build_utils", ".", "MatchesGlob", "(", "r_path", ",", "include_globs", ")", ":", "continue", "with", "open", "(", "r_path", ")", "as", "f", ":", "all_lines", ".", "update", "(", "f", ".", "readlines", "(", ")", ")", "return", "''", ".", "join", "(", "sorted", "(", "all_lines", ")", ")" ]
https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/build/android/gyp/dist_aar.py#L24-L32
MythTV/mythtv
d282a209cb8be85d036f85a62a8ec971b67d45f4
mythtv/bindings/python/MythTV/system.py
python
Grabber.search
(self, phrase, subtitle=None, tolerance=None, func=None)
obj.search(phrase, subtitle=None, tolerance=None) -> result generator Returns a generator of results matching the given search phrase. A secondary phrase can be given through the 'subtitle' parameter, and an optional levenshtein tolerance value can be given for filtering results.
obj.search(phrase, subtitle=None, tolerance=None) -> result generator
[ "obj", ".", "search", "(", "phrase", "subtitle", "=", "None", "tolerance", "=", "None", ")", "-", ">", "result", "generator" ]
def search(self, phrase, subtitle=None, tolerance=None, func=None): """ obj.search(phrase, subtitle=None, tolerance=None) -> result generator Returns a generator of results matching the given search phrase. A secondary phrase can be given through the 'subtitle' parameter, and an optional levenshtein tolerance value can be given for filtering results. """ if not func: if subtitle is not None: func = lambda p,s,r: levenshtein(r.subtitle, s) else: func = lambda p,s,r: levenshtein('%s : %s' % \ (r.title,r.subtitle), p) \ if r.subtitle is not None else \ levenshtein(r.title, p) if tolerance is None: tolerance = int(self.db.settings.NULL.\ get('MetadataLookupTolerance', 5)) if subtitle is not None: res = self.command('-N', '"%s" "%s"' % (phrase, subtitle)) else: res = self.command('-M', '"%s"' % phrase) for r in res: r.levenshtein = func(phrase, subtitle, r) if r.levenshtein > tolerance: continue yield r
[ "def", "search", "(", "self", ",", "phrase", ",", "subtitle", "=", "None", ",", "tolerance", "=", "None", ",", "func", "=", "None", ")", ":", "if", "not", "func", ":", "if", "subtitle", "is", "not", "None", ":", "func", "=", "lambda", "p", ",", "s", ",", "r", ":", "levenshtein", "(", "r", ".", "subtitle", ",", "s", ")", "else", ":", "func", "=", "lambda", "p", ",", "s", ",", "r", ":", "levenshtein", "(", "'%s : %s'", "%", "(", "r", ".", "title", ",", "r", ".", "subtitle", ")", ",", "p", ")", "if", "r", ".", "subtitle", "is", "not", "None", "else", "levenshtein", "(", "r", ".", "title", ",", "p", ")", "if", "tolerance", "is", "None", ":", "tolerance", "=", "int", "(", "self", ".", "db", ".", "settings", ".", "NULL", ".", "get", "(", "'MetadataLookupTolerance'", ",", "5", ")", ")", "if", "subtitle", "is", "not", "None", ":", "res", "=", "self", ".", "command", "(", "'-N'", ",", "'\"%s\" \"%s\"'", "%", "(", "phrase", ",", "subtitle", ")", ")", "else", ":", "res", "=", "self", ".", "command", "(", "'-M'", ",", "'\"%s\"'", "%", "phrase", ")", "for", "r", "in", "res", ":", "r", ".", "levenshtein", "=", "func", "(", "phrase", ",", "subtitle", ",", "r", ")", "if", "r", ".", "levenshtein", ">", "tolerance", ":", "continue", "yield", "r" ]
https://github.com/MythTV/mythtv/blob/d282a209cb8be85d036f85a62a8ec971b67d45f4/mythtv/bindings/python/MythTV/system.py#L353-L383
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/linalg/linalg.py
python
lstsq
(a, b, rcond="warn")
return wrap(x), wrap(resids), rank, s
r""" Return the least-squares solution to a linear matrix equation. Solves the equation :math:`a x = b` by computing a vector `x` that minimizes the squared Euclidean 2-norm :math:`\| b - a x \|^2_2`. The equation may be under-, well-, or over-determined (i.e., the number of linearly independent rows of `a` can be less than, equal to, or greater than its number of linearly independent columns). If `a` is square and of full rank, then `x` (but for round-off error) is the "exact" solution of the equation. Parameters ---------- a : (M, N) array_like "Coefficient" matrix. b : {(M,), (M, K)} array_like Ordinate or "dependent variable" values. If `b` is two-dimensional, the least-squares solution is calculated for each of the `K` columns of `b`. rcond : float, optional Cut-off ratio for small singular values of `a`. For the purposes of rank determination, singular values are treated as zero if they are smaller than `rcond` times the largest singular value of `a`. .. versionchanged:: 1.14.0 If not set, a FutureWarning is given. The previous default of ``-1`` will use the machine precision as `rcond` parameter, the new default will use the machine precision times `max(M, N)`. To silence the warning and use the new default, use ``rcond=None``, to keep using the old behavior, use ``rcond=-1``. Returns ------- x : {(N,), (N, K)} ndarray Least-squares solution. If `b` is two-dimensional, the solutions are in the `K` columns of `x`. residuals : {(1,), (K,), (0,)} ndarray Sums of residuals; squared Euclidean 2-norm for each column in ``b - a*x``. If the rank of `a` is < N or M <= N, this is an empty array. If `b` is 1-dimensional, this is a (1,) shape array. Otherwise the shape is (K,). rank : int Rank of matrix `a`. s : (min(M, N),) ndarray Singular values of `a`. Raises ------ LinAlgError If computation does not converge. Notes ----- If `b` is a matrix, then all array results are returned as matrices. Examples -------- Fit a line, ``y = mx + c``, through some noisy data-points: >>> x = np.array([0, 1, 2, 3]) >>> y = np.array([-1, 0.2, 0.9, 2.1]) By examining the coefficients, we see that the line should have a gradient of roughly 1 and cut the y-axis at, more or less, -1. We can rewrite the line equation as ``y = Ap``, where ``A = [[x 1]]`` and ``p = [[m], [c]]``. Now use `lstsq` to solve for `p`: >>> A = np.vstack([x, np.ones(len(x))]).T >>> A array([[ 0., 1.], [ 1., 1.], [ 2., 1.], [ 3., 1.]]) >>> m, c = np.linalg.lstsq(A, y, rcond=None)[0] >>> m, c (1.0 -0.95) # may vary Plot the data along with the fitted line: >>> import matplotlib.pyplot as plt >>> _ = plt.plot(x, y, 'o', label='Original data', markersize=10) >>> _ = plt.plot(x, m*x + c, 'r', label='Fitted line') >>> _ = plt.legend() >>> plt.show()
r""" Return the least-squares solution to a linear matrix equation.
[ "r", "Return", "the", "least", "-", "squares", "solution", "to", "a", "linear", "matrix", "equation", "." ]
def lstsq(a, b, rcond="warn"): r""" Return the least-squares solution to a linear matrix equation. Solves the equation :math:`a x = b` by computing a vector `x` that minimizes the squared Euclidean 2-norm :math:`\| b - a x \|^2_2`. The equation may be under-, well-, or over-determined (i.e., the number of linearly independent rows of `a` can be less than, equal to, or greater than its number of linearly independent columns). If `a` is square and of full rank, then `x` (but for round-off error) is the "exact" solution of the equation. Parameters ---------- a : (M, N) array_like "Coefficient" matrix. b : {(M,), (M, K)} array_like Ordinate or "dependent variable" values. If `b` is two-dimensional, the least-squares solution is calculated for each of the `K` columns of `b`. rcond : float, optional Cut-off ratio for small singular values of `a`. For the purposes of rank determination, singular values are treated as zero if they are smaller than `rcond` times the largest singular value of `a`. .. versionchanged:: 1.14.0 If not set, a FutureWarning is given. The previous default of ``-1`` will use the machine precision as `rcond` parameter, the new default will use the machine precision times `max(M, N)`. To silence the warning and use the new default, use ``rcond=None``, to keep using the old behavior, use ``rcond=-1``. Returns ------- x : {(N,), (N, K)} ndarray Least-squares solution. If `b` is two-dimensional, the solutions are in the `K` columns of `x`. residuals : {(1,), (K,), (0,)} ndarray Sums of residuals; squared Euclidean 2-norm for each column in ``b - a*x``. If the rank of `a` is < N or M <= N, this is an empty array. If `b` is 1-dimensional, this is a (1,) shape array. Otherwise the shape is (K,). rank : int Rank of matrix `a`. s : (min(M, N),) ndarray Singular values of `a`. Raises ------ LinAlgError If computation does not converge. Notes ----- If `b` is a matrix, then all array results are returned as matrices. Examples -------- Fit a line, ``y = mx + c``, through some noisy data-points: >>> x = np.array([0, 1, 2, 3]) >>> y = np.array([-1, 0.2, 0.9, 2.1]) By examining the coefficients, we see that the line should have a gradient of roughly 1 and cut the y-axis at, more or less, -1. We can rewrite the line equation as ``y = Ap``, where ``A = [[x 1]]`` and ``p = [[m], [c]]``. Now use `lstsq` to solve for `p`: >>> A = np.vstack([x, np.ones(len(x))]).T >>> A array([[ 0., 1.], [ 1., 1.], [ 2., 1.], [ 3., 1.]]) >>> m, c = np.linalg.lstsq(A, y, rcond=None)[0] >>> m, c (1.0 -0.95) # may vary Plot the data along with the fitted line: >>> import matplotlib.pyplot as plt >>> _ = plt.plot(x, y, 'o', label='Original data', markersize=10) >>> _ = plt.plot(x, m*x + c, 'r', label='Fitted line') >>> _ = plt.legend() >>> plt.show() """ a, _ = _makearray(a) b, wrap = _makearray(b) is_1d = b.ndim == 1 if is_1d: b = b[:, newaxis] _assert_2d(a, b) m, n = a.shape[-2:] m2, n_rhs = b.shape[-2:] if m != m2: raise LinAlgError('Incompatible dimensions') t, result_t = _commonType(a, b) # FIXME: real_t is unused real_t = _linalgRealType(t) result_real_t = _realType(result_t) # Determine default rcond value if rcond == "warn": # 2017-08-19, 1.14.0 warnings.warn("`rcond` parameter will change to the default of " "machine precision times ``max(M, N)`` where M and N " "are the input matrix dimensions.\n" "To use the future default and silence this warning " "we advise to pass `rcond=None`, to keep using the old, " "explicitly pass `rcond=-1`.", FutureWarning, stacklevel=3) rcond = -1 if rcond is None: rcond = finfo(t).eps * max(n, m) if m <= n: gufunc = _umath_linalg.lstsq_m else: gufunc = _umath_linalg.lstsq_n signature = 'DDd->Ddid' if isComplexType(t) else 'ddd->ddid' extobj = get_linalg_error_extobj(_raise_linalgerror_lstsq) if n_rhs == 0: # lapack can't handle n_rhs = 0 - so allocate the array one larger in that axis b = zeros(b.shape[:-2] + (m, n_rhs + 1), dtype=b.dtype) x, resids, rank, s = gufunc(a, b, rcond, signature=signature, extobj=extobj) if m == 0: x[...] = 0 if n_rhs == 0: # remove the item we added x = x[..., :n_rhs] resids = resids[..., :n_rhs] # remove the axis we added if is_1d: x = x.squeeze(axis=-1) # we probably should squeeze resids too, but we can't # without breaking compatibility. # as documented if rank != n or m <= n: resids = array([], result_real_t) # coerce output arrays s = s.astype(result_real_t, copy=False) resids = resids.astype(result_real_t, copy=False) x = x.astype(result_t, copy=True) # Copying lets the memory in r_parts be freed return wrap(x), wrap(resids), rank, s
[ "def", "lstsq", "(", "a", ",", "b", ",", "rcond", "=", "\"warn\"", ")", ":", "a", ",", "_", "=", "_makearray", "(", "a", ")", "b", ",", "wrap", "=", "_makearray", "(", "b", ")", "is_1d", "=", "b", ".", "ndim", "==", "1", "if", "is_1d", ":", "b", "=", "b", "[", ":", ",", "newaxis", "]", "_assert_2d", "(", "a", ",", "b", ")", "m", ",", "n", "=", "a", ".", "shape", "[", "-", "2", ":", "]", "m2", ",", "n_rhs", "=", "b", ".", "shape", "[", "-", "2", ":", "]", "if", "m", "!=", "m2", ":", "raise", "LinAlgError", "(", "'Incompatible dimensions'", ")", "t", ",", "result_t", "=", "_commonType", "(", "a", ",", "b", ")", "# FIXME: real_t is unused", "real_t", "=", "_linalgRealType", "(", "t", ")", "result_real_t", "=", "_realType", "(", "result_t", ")", "# Determine default rcond value", "if", "rcond", "==", "\"warn\"", ":", "# 2017-08-19, 1.14.0", "warnings", ".", "warn", "(", "\"`rcond` parameter will change to the default of \"", "\"machine precision times ``max(M, N)`` where M and N \"", "\"are the input matrix dimensions.\\n\"", "\"To use the future default and silence this warning \"", "\"we advise to pass `rcond=None`, to keep using the old, \"", "\"explicitly pass `rcond=-1`.\"", ",", "FutureWarning", ",", "stacklevel", "=", "3", ")", "rcond", "=", "-", "1", "if", "rcond", "is", "None", ":", "rcond", "=", "finfo", "(", "t", ")", ".", "eps", "*", "max", "(", "n", ",", "m", ")", "if", "m", "<=", "n", ":", "gufunc", "=", "_umath_linalg", ".", "lstsq_m", "else", ":", "gufunc", "=", "_umath_linalg", ".", "lstsq_n", "signature", "=", "'DDd->Ddid'", "if", "isComplexType", "(", "t", ")", "else", "'ddd->ddid'", "extobj", "=", "get_linalg_error_extobj", "(", "_raise_linalgerror_lstsq", ")", "if", "n_rhs", "==", "0", ":", "# lapack can't handle n_rhs = 0 - so allocate the array one larger in that axis", "b", "=", "zeros", "(", "b", ".", "shape", "[", ":", "-", "2", "]", "+", "(", "m", ",", "n_rhs", "+", "1", ")", ",", "dtype", "=", "b", ".", "dtype", ")", "x", ",", "resids", ",", "rank", ",", "s", "=", "gufunc", "(", "a", ",", "b", ",", "rcond", ",", "signature", "=", "signature", ",", "extobj", "=", "extobj", ")", "if", "m", "==", "0", ":", "x", "[", "...", "]", "=", "0", "if", "n_rhs", "==", "0", ":", "# remove the item we added", "x", "=", "x", "[", "...", ",", ":", "n_rhs", "]", "resids", "=", "resids", "[", "...", ",", ":", "n_rhs", "]", "# remove the axis we added", "if", "is_1d", ":", "x", "=", "x", ".", "squeeze", "(", "axis", "=", "-", "1", ")", "# we probably should squeeze resids too, but we can't", "# without breaking compatibility.", "# as documented", "if", "rank", "!=", "n", "or", "m", "<=", "n", ":", "resids", "=", "array", "(", "[", "]", ",", "result_real_t", ")", "# coerce output arrays", "s", "=", "s", ".", "astype", "(", "result_real_t", ",", "copy", "=", "False", ")", "resids", "=", "resids", ".", "astype", "(", "result_real_t", ",", "copy", "=", "False", ")", "x", "=", "x", ".", "astype", "(", "result_t", ",", "copy", "=", "True", ")", "# Copying lets the memory in r_parts be freed", "return", "wrap", "(", "x", ")", ",", "wrap", "(", "resids", ")", ",", "rank", ",", "s" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/linalg/linalg.py#L2128-L2281