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
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/saved_model/load_v1_in_v2.py
python
_EagerSavedModelLoader.restore_variables
(self, wrapped, restore_from_saver)
Restores variables from the checkpoint.
Restores variables from the checkpoint.
[ "Restores", "variables", "from", "the", "checkpoint", "." ]
def restore_variables(self, wrapped, restore_from_saver): """Restores variables from the checkpoint.""" if restore_from_saver is not None: initializer, _ = restore_from_saver( constant_op.constant(self._variables_path)) if not ops.executing_eagerly_outside_functions(): # Add the initialization operation to the "saved_model_initializers" # collection in case we don't have any lifted variables to attach it to. ops.add_to_collection("saved_model_initializers", initializer) one_unlifted = False for variable in wrapped.graph.get_collection_ref( ops.GraphKeys.GLOBAL_VARIABLES): if variable.graph is wrapped.graph: one_unlifted = True # pylint: disable=protected-access variable._initializer_op = initializer # pylint: enable=protected-access if one_unlifted: logging.warning( "Some variables could not be lifted out of a loaded function. " "Please run " "`sess.run(tf.get_collection(\"saved_model_initializers\"))`to " "restore these variables.")
[ "def", "restore_variables", "(", "self", ",", "wrapped", ",", "restore_from_saver", ")", ":", "if", "restore_from_saver", "is", "not", "None", ":", "initializer", ",", "_", "=", "restore_from_saver", "(", "constant_op", ".", "constant", "(", "self", ".", "_variables_path", ")", ")", "if", "not", "ops", ".", "executing_eagerly_outside_functions", "(", ")", ":", "# Add the initialization operation to the \"saved_model_initializers\"", "# collection in case we don't have any lifted variables to attach it to.", "ops", ".", "add_to_collection", "(", "\"saved_model_initializers\"", ",", "initializer", ")", "one_unlifted", "=", "False", "for", "variable", "in", "wrapped", ".", "graph", ".", "get_collection_ref", "(", "ops", ".", "GraphKeys", ".", "GLOBAL_VARIABLES", ")", ":", "if", "variable", ".", "graph", "is", "wrapped", ".", "graph", ":", "one_unlifted", "=", "True", "# pylint: disable=protected-access", "variable", ".", "_initializer_op", "=", "initializer", "# pylint: enable=protected-access", "if", "one_unlifted", ":", "logging", ".", "warning", "(", "\"Some variables could not be lifted out of a loaded function. \"", "\"Please run \"", "\"`sess.run(tf.get_collection(\\\"saved_model_initializers\\\"))`to \"", "\"restore these variables.\"", ")" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/saved_model/load_v1_in_v2.py#L110-L133
psi4/psi4
be533f7f426b6ccc263904e55122899b16663395
psi4/driver/qcdb/libmintsmolecule.py
python
LibmintsMolecule.input_units_to_au
(self)
return self.PYinput_units_to_au
Gets the geometry unit conversion.
Gets the geometry unit conversion.
[ "Gets", "the", "geometry", "unit", "conversion", "." ]
def input_units_to_au(self): """Gets the geometry unit conversion.""" return self.PYinput_units_to_au
[ "def", "input_units_to_au", "(", "self", ")", ":", "return", "self", ".", "PYinput_units_to_au" ]
https://github.com/psi4/psi4/blob/be533f7f426b6ccc263904e55122899b16663395/psi4/driver/qcdb/libmintsmolecule.py#L330-L332
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/propgrid.py
python
PGProperty.SetWasModified
(*args, **kwargs)
return _propgrid.PGProperty_SetWasModified(*args, **kwargs)
SetWasModified(self, bool set=True)
SetWasModified(self, bool set=True)
[ "SetWasModified", "(", "self", "bool", "set", "=", "True", ")" ]
def SetWasModified(*args, **kwargs): """SetWasModified(self, bool set=True)""" return _propgrid.PGProperty_SetWasModified(*args, **kwargs)
[ "def", "SetWasModified", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_propgrid", ".", "PGProperty_SetWasModified", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/propgrid.py#L783-L785
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/third_party/lib_aarch64/python2.7/dist-packages/rospkg/manifest.py
python
_check_platform
(n, filename)
return [Platform(*v) for v in vals]
Validator for manifest platform. :raise: :exc:`InvalidManifest` If validation fails
Validator for manifest platform. :raise: :exc:`InvalidManifest` If validation fails
[ "Validator", "for", "manifest", "platform", ".", ":", "raise", ":", ":", "exc", ":", "InvalidManifest", "If", "validation", "fails" ]
def _check_platform(n, filename): """ Validator for manifest platform. :raise: :exc:`InvalidManifest` If validation fails """ platforms = _get_nodes_by_name(n, 'platform') try: vals = [(p.attributes['os'].value, p.attributes['version'].value, p.getAttribute('notes')) for p in platforms] except KeyError as e: raise InvalidManifest("<platform> tag is missing required '%s' attribute"%str(e)) return [Platform(*v) for v in vals]
[ "def", "_check_platform", "(", "n", ",", "filename", ")", ":", "platforms", "=", "_get_nodes_by_name", "(", "n", ",", "'platform'", ")", "try", ":", "vals", "=", "[", "(", "p", ".", "attributes", "[", "'os'", "]", ".", "value", ",", "p", ".", "attributes", "[", "'version'", "]", ".", "value", ",", "p", ".", "getAttribute", "(", "'notes'", ")", ")", "for", "p", "in", "platforms", "]", "except", "KeyError", "as", "e", ":", "raise", "InvalidManifest", "(", "\"<platform> tag is missing required '%s' attribute\"", "%", "str", "(", "e", ")", ")", "return", "[", "Platform", "(", "*", "v", ")", "for", "v", "in", "vals", "]" ]
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_aarch64/python2.7/dist-packages/rospkg/manifest.py#L100-L110
twtygqyy/caffe-augmentation
c76600d247e5132fa5bd89d87bb5df458341fa84
tools/extra/resize_and_crop_images.py
python
OpenCVResizeCrop.resize_and_crop_image
(self, input_file, output_file, output_side_length = 256)
Takes an image name, resize it and crop the center square
Takes an image name, resize it and crop the center square
[ "Takes", "an", "image", "name", "resize", "it", "and", "crop", "the", "center", "square" ]
def resize_and_crop_image(self, input_file, output_file, output_side_length = 256): '''Takes an image name, resize it and crop the center square ''' img = cv2.imread(input_file) height, width, depth = img.shape new_height = output_side_length new_width = output_side_length if height > width: new_height = output_side_length * height / width else: new_width = output_side_length * width / height resized_img = cv2.resize(img, (new_width, new_height)) height_offset = (new_height - output_side_length) / 2 width_offset = (new_width - output_side_length) / 2 cropped_img = resized_img[height_offset:height_offset + output_side_length, width_offset:width_offset + output_side_length] cv2.imwrite(output_file, cropped_img)
[ "def", "resize_and_crop_image", "(", "self", ",", "input_file", ",", "output_file", ",", "output_side_length", "=", "256", ")", ":", "img", "=", "cv2", ".", "imread", "(", "input_file", ")", "height", ",", "width", ",", "depth", "=", "img", ".", "shape", "new_height", "=", "output_side_length", "new_width", "=", "output_side_length", "if", "height", ">", "width", ":", "new_height", "=", "output_side_length", "*", "height", "/", "width", "else", ":", "new_width", "=", "output_side_length", "*", "width", "/", "height", "resized_img", "=", "cv2", ".", "resize", "(", "img", ",", "(", "new_width", ",", "new_height", ")", ")", "height_offset", "=", "(", "new_height", "-", "output_side_length", ")", "/", "2", "width_offset", "=", "(", "new_width", "-", "output_side_length", ")", "/", "2", "cropped_img", "=", "resized_img", "[", "height_offset", ":", "height_offset", "+", "output_side_length", ",", "width_offset", ":", "width_offset", "+", "output_side_length", "]", "cv2", ".", "imwrite", "(", "output_file", ",", "cropped_img", ")" ]
https://github.com/twtygqyy/caffe-augmentation/blob/c76600d247e5132fa5bd89d87bb5df458341fa84/tools/extra/resize_and_crop_images.py#L20-L36
luliyucoordinate/Leetcode
96afcdc54807d1d184e881a075d1dbf3371e31fb
src/0279-Perfect-Squares/0279.py
python
Solution.numSquares
(self, n)
return 3
:type n: int :rtype: int
:type n: int :rtype: int
[ ":", "type", "n", ":", "int", ":", "rtype", ":", "int" ]
def numSquares(self, n): """ :type n: int :rtype: int """ while n % 4 == 0: n /= 4 if n % 8 == 7: return 4 a = 0 while a**2 <= n: b = int((n - a**2)**0.5) if a**2 + b**2 == n: return (not not a) + (not not b) a += 1 return 3
[ "def", "numSquares", "(", "self", ",", "n", ")", ":", "while", "n", "%", "4", "==", "0", ":", "n", "/=", "4", "if", "n", "%", "8", "==", "7", ":", "return", "4", "a", "=", "0", "while", "a", "**", "2", "<=", "n", ":", "b", "=", "int", "(", "(", "n", "-", "a", "**", "2", ")", "**", "0.5", ")", "if", "a", "**", "2", "+", "b", "**", "2", "==", "n", ":", "return", "(", "not", "not", "a", ")", "+", "(", "not", "not", "b", ")", "a", "+=", "1", "return", "3" ]
https://github.com/luliyucoordinate/Leetcode/blob/96afcdc54807d1d184e881a075d1dbf3371e31fb/src/0279-Perfect-Squares/0279.py#L2-L21
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/lib/scimath.py
python
arccos
(x)
return nx.arccos(x)
Compute the inverse cosine of x. Return the "principal value" (for a description of this, see `numpy.arccos`) of the inverse cosine of `x`. For real `x` such that `abs(x) <= 1`, this is a real number in the closed interval :math:`[0, \\pi]`. Otherwise, the complex principle value is returned. Parameters ---------- x : array_like or scalar The value(s) whose arccos is (are) required. Returns ------- out : ndarray or scalar The inverse cosine(s) of the `x` value(s). If `x` was a scalar, so is `out`, otherwise an array object is returned. See Also -------- numpy.arccos Notes ----- For an arccos() that returns ``NAN`` when real `x` is not in the interval ``[-1,1]``, use `numpy.arccos`. Examples -------- >>> np.set_printoptions(precision=4) >>> np.emath.arccos(1) # a scalar is returned 0.0 >>> np.emath.arccos([1,2]) array([0.-0.j , 0.-1.317j])
Compute the inverse cosine of x.
[ "Compute", "the", "inverse", "cosine", "of", "x", "." ]
def arccos(x): """ Compute the inverse cosine of x. Return the "principal value" (for a description of this, see `numpy.arccos`) of the inverse cosine of `x`. For real `x` such that `abs(x) <= 1`, this is a real number in the closed interval :math:`[0, \\pi]`. Otherwise, the complex principle value is returned. Parameters ---------- x : array_like or scalar The value(s) whose arccos is (are) required. Returns ------- out : ndarray or scalar The inverse cosine(s) of the `x` value(s). If `x` was a scalar, so is `out`, otherwise an array object is returned. See Also -------- numpy.arccos Notes ----- For an arccos() that returns ``NAN`` when real `x` is not in the interval ``[-1,1]``, use `numpy.arccos`. Examples -------- >>> np.set_printoptions(precision=4) >>> np.emath.arccos(1) # a scalar is returned 0.0 >>> np.emath.arccos([1,2]) array([0.-0.j , 0.-1.317j]) """ x = _fix_real_abs_gt_1(x) return nx.arccos(x)
[ "def", "arccos", "(", "x", ")", ":", "x", "=", "_fix_real_abs_gt_1", "(", "x", ")", "return", "nx", ".", "arccos", "(", "x", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/lib/scimath.py#L465-L506
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqtinterfaces/mantidqtinterfaces/drill/view/DrillExportDialog.py
python
DrillExportDialog.getAlgorithmCheckStates
(self)
return {a:w.isChecked() for a,w in self._widgets.items()}
Get the check state of algorithms. Returns: dict(str:bool): for each algorithm name, a bool to set its check state
Get the check state of algorithms.
[ "Get", "the", "check", "state", "of", "algorithms", "." ]
def getAlgorithmCheckStates(self): """ Get the check state of algorithms. Returns: dict(str:bool): for each algorithm name, a bool to set its check state """ return {a:w.isChecked() for a,w in self._widgets.items()}
[ "def", "getAlgorithmCheckStates", "(", "self", ")", ":", "return", "{", "a", ":", "w", ".", "isChecked", "(", ")", "for", "a", ",", "w", "in", "self", ".", "_widgets", ".", "items", "(", ")", "}" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/drill/view/DrillExportDialog.py#L100-L108
mandiant/flare-wmi
b0a5a094ff9ca7d7a1c4fc711dc00c74dec4b6b1
python-cim/cim/objects.py
python
ClassDefinition.keys
(self)
return ret
get names of Key properties for instances :rtype: str
get names of Key properties for instances
[ "get", "names", "of", "Key", "properties", "for", "instances" ]
def keys(self): """ get names of Key properties for instances :rtype: str """ ret = [] for propname, prop in self.properties.items(): for k, v in prop.qualifiers.items(): # TODO: don't hardcode BUILTIN_QUALIFIERS.PROP_KEY symbol name if k == "PROP_QUALIFIER_KEY" and v is True: ret.append(propname) return ret
[ "def", "keys", "(", "self", ")", ":", "ret", "=", "[", "]", "for", "propname", ",", "prop", "in", "self", ".", "properties", ".", "items", "(", ")", ":", "for", "k", ",", "v", "in", "prop", ".", "qualifiers", ".", "items", "(", ")", ":", "# TODO: don't hardcode BUILTIN_QUALIFIERS.PROP_KEY symbol name", "if", "k", "==", "\"PROP_QUALIFIER_KEY\"", "and", "v", "is", "True", ":", "ret", ".", "append", "(", "propname", ")", "return", "ret" ]
https://github.com/mandiant/flare-wmi/blob/b0a5a094ff9ca7d7a1c4fc711dc00c74dec4b6b1/python-cim/cim/objects.py#L615-L627
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/robotparser.py
python
RobotFileParser.parse
(self, lines)
parse the input lines from a robots.txt file. We allow that a user-agent: line is not preceded by one or more blank lines.
parse the input lines from a robots.txt file. We allow that a user-agent: line is not preceded by one or more blank lines.
[ "parse", "the", "input", "lines", "from", "a", "robots", ".", "txt", "file", ".", "We", "allow", "that", "a", "user", "-", "agent", ":", "line", "is", "not", "preceded", "by", "one", "or", "more", "blank", "lines", "." ]
def parse(self, lines): """parse the input lines from a robots.txt file. We allow that a user-agent: line is not preceded by one or more blank lines.""" # states: # 0: start state # 1: saw user-agent line # 2: saw an allow or disallow line state = 0 linenumber = 0 entry = Entry() for line in lines: linenumber += 1 if not line: if state == 1: entry = Entry() state = 0 elif state == 2: self._add_entry(entry) entry = Entry() state = 0 # remove optional comment and strip line i = line.find('#') if i >= 0: line = line[:i] line = line.strip() if not line: continue line = line.split(':', 1) if len(line) == 2: line[0] = line[0].strip().lower() line[1] = urllib.unquote(line[1].strip()) if line[0] == "user-agent": if state == 2: self._add_entry(entry) entry = Entry() entry.useragents.append(line[1]) state = 1 elif line[0] == "disallow": if state != 0: entry.rulelines.append(RuleLine(line[1], False)) state = 2 elif line[0] == "allow": if state != 0: entry.rulelines.append(RuleLine(line[1], True)) state = 2 if state == 2: self._add_entry(entry)
[ "def", "parse", "(", "self", ",", "lines", ")", ":", "# states:", "# 0: start state", "# 1: saw user-agent line", "# 2: saw an allow or disallow line", "state", "=", "0", "linenumber", "=", "0", "entry", "=", "Entry", "(", ")", "for", "line", "in", "lines", ":", "linenumber", "+=", "1", "if", "not", "line", ":", "if", "state", "==", "1", ":", "entry", "=", "Entry", "(", ")", "state", "=", "0", "elif", "state", "==", "2", ":", "self", ".", "_add_entry", "(", "entry", ")", "entry", "=", "Entry", "(", ")", "state", "=", "0", "# remove optional comment and strip line", "i", "=", "line", ".", "find", "(", "'#'", ")", "if", "i", ">=", "0", ":", "line", "=", "line", "[", ":", "i", "]", "line", "=", "line", ".", "strip", "(", ")", "if", "not", "line", ":", "continue", "line", "=", "line", ".", "split", "(", "':'", ",", "1", ")", "if", "len", "(", "line", ")", "==", "2", ":", "line", "[", "0", "]", "=", "line", "[", "0", "]", ".", "strip", "(", ")", ".", "lower", "(", ")", "line", "[", "1", "]", "=", "urllib", ".", "unquote", "(", "line", "[", "1", "]", ".", "strip", "(", ")", ")", "if", "line", "[", "0", "]", "==", "\"user-agent\"", ":", "if", "state", "==", "2", ":", "self", ".", "_add_entry", "(", "entry", ")", "entry", "=", "Entry", "(", ")", "entry", ".", "useragents", ".", "append", "(", "line", "[", "1", "]", ")", "state", "=", "1", "elif", "line", "[", "0", "]", "==", "\"disallow\"", ":", "if", "state", "!=", "0", ":", "entry", ".", "rulelines", ".", "append", "(", "RuleLine", "(", "line", "[", "1", "]", ",", "False", ")", ")", "state", "=", "2", "elif", "line", "[", "0", "]", "==", "\"allow\"", ":", "if", "state", "!=", "0", ":", "entry", ".", "rulelines", ".", "append", "(", "RuleLine", "(", "line", "[", "1", "]", ",", "True", ")", ")", "state", "=", "2", "if", "state", "==", "2", ":", "self", ".", "_add_entry", "(", "entry", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/robotparser.py#L77-L125
wesnoth/wesnoth
6ccac5a5e8ff75303c9190c0da60580925cb32c0
data/tools/wesnoth/wmltools3.py
python
namespace_directory
(name)
Go from namespace to directory.
Go from namespace to directory.
[ "Go", "from", "namespace", "to", "directory", "." ]
def namespace_directory(name): "Go from namespace to directory." if name == "core": return "data/core/" else: return "data/campaigns/" + name + "/"
[ "def", "namespace_directory", "(", "name", ")", ":", "if", "name", "==", "\"core\"", ":", "return", "\"data/core/\"", "else", ":", "return", "\"data/campaigns/\"", "+", "name", "+", "\"/\"" ]
https://github.com/wesnoth/wesnoth/blob/6ccac5a5e8ff75303c9190c0da60580925cb32c0/data/tools/wesnoth/wmltools3.py#L1079-L1084
lballabio/quantlib-old
136336947ed4fea9ecc1da6edad188700e821739
gensrc/gensrc/addins/addin.py
python
Addin.objectIdSuffix
(self)
return self.objectIdSuffix_
Return the text which is appended to variable names in autogenerated source code after object IDs are converted to the corresponding objects.
Return the text which is appended to variable names in autogenerated source code after object IDs are converted to the corresponding objects.
[ "Return", "the", "text", "which", "is", "appended", "to", "variable", "names", "in", "autogenerated", "source", "code", "after", "object", "IDs", "are", "converted", "to", "the", "corresponding", "objects", "." ]
def objectIdSuffix(self): """Return the text which is appended to variable names in autogenerated source code after object IDs are converted to the corresponding objects.""" return self.objectIdSuffix_
[ "def", "objectIdSuffix", "(", "self", ")", ":", "return", "self", ".", "objectIdSuffix_" ]
https://github.com/lballabio/quantlib-old/blob/136336947ed4fea9ecc1da6edad188700e821739/gensrc/gensrc/addins/addin.py#L50-L54
cms-sw/cmssw
fd9de012d503d3405420bcbeec0ec879baa57cf2
Validation/RecoTrack/python/plotting/plotting.py
python
PlotGroup.draw
(self, legendLabels, prefix=None, separate=False, saveFormat=".pdf", ratio=True, directory="")
return self._save(canvas, saveFormat, prefix=prefix, directory=directory)
Draw the histograms using values for a given algorithm. Arguments: legendLabels -- List of strings for legend labels (corresponding to the tdirectories in create()) prefix -- Optional string for file name prefix (default None) separate -- Save the plots of a group to separate files instead of a file per group (default False) saveFormat -- String specifying the plot format (default '.pdf') ratio -- Add ratio to the plot (default True) directory -- Directory where to save the file (default "")
Draw the histograms using values for a given algorithm.
[ "Draw", "the", "histograms", "using", "values", "for", "a", "given", "algorithm", "." ]
def draw(self, legendLabels, prefix=None, separate=False, saveFormat=".pdf", ratio=True, directory=""): """Draw the histograms using values for a given algorithm. Arguments: legendLabels -- List of strings for legend labels (corresponding to the tdirectories in create()) prefix -- Optional string for file name prefix (default None) separate -- Save the plots of a group to separate files instead of a file per group (default False) saveFormat -- String specifying the plot format (default '.pdf') ratio -- Add ratio to the plot (default True) directory -- Directory where to save the file (default "") """ if self._overrideLegendLabels is not None: legendLabels = self._overrideLegendLabels # Do not draw the group if it would be empty onlyEmptyPlots = True for plot in self._plots: if not plot.isEmpty(): onlyEmptyPlots = False break if onlyEmptyPlots: return [] if separate: return self._drawSeparate(legendLabels, prefix, saveFormat, ratio, directory) cwidth = 500*self._ncols nrows = int((len(self._plots)+self._ncols-1)/self._ncols) # this should work also for odd n cheight = 500 * nrows if ratio: cheight = int(cheight*self._ratioFactor) canvas = _createCanvas(self._name, cwidth, cheight) canvas.Divide(self._ncols, nrows) if ratio: for i, plot in enumerate(self._plots): pad = canvas.cd(i+1) self._modifyPadForRatio(pad) # Draw plots to canvas for i, plot in enumerate(self._plots): pad = canvas.cd(i+1) if not plot.isEmpty(): plot.draw(pad, ratio, self._ratioFactor, nrows) # Setup legend canvas.cd() if len(self._plots) <= 4: lx1 = 0.2 lx2 = 0.9 ly1 = 0.48 ly2 = 0.53 else: lx1 = 0.1 lx2 = 0.9 ly1 = 0.64 ly2 = 0.67 if self._legendDx is not None: lx1 += self._legendDx lx2 += self._legendDx if self._legendDy is not None: ly1 += self._legendDy ly2 += self._legendDy if self._legendDw is not None: lx2 += self._legendDw if self._legendDh is not None: ly1 -= self._legendDh plot = max(self._plots, key=lambda p: p.getNumberOfHistograms()) denomUnc = sum([p.drawRatioUncertainty() for p in self._plots]) > 0 legend = self._createLegend(plot, legendLabels, lx1, ly1, lx2, ly2, denomUncertainty=(ratio and denomUnc)) return self._save(canvas, saveFormat, prefix=prefix, directory=directory)
[ "def", "draw", "(", "self", ",", "legendLabels", ",", "prefix", "=", "None", ",", "separate", "=", "False", ",", "saveFormat", "=", "\".pdf\"", ",", "ratio", "=", "True", ",", "directory", "=", "\"\"", ")", ":", "if", "self", ".", "_overrideLegendLabels", "is", "not", "None", ":", "legendLabels", "=", "self", ".", "_overrideLegendLabels", "# Do not draw the group if it would be empty", "onlyEmptyPlots", "=", "True", "for", "plot", "in", "self", ".", "_plots", ":", "if", "not", "plot", ".", "isEmpty", "(", ")", ":", "onlyEmptyPlots", "=", "False", "break", "if", "onlyEmptyPlots", ":", "return", "[", "]", "if", "separate", ":", "return", "self", ".", "_drawSeparate", "(", "legendLabels", ",", "prefix", ",", "saveFormat", ",", "ratio", ",", "directory", ")", "cwidth", "=", "500", "*", "self", ".", "_ncols", "nrows", "=", "int", "(", "(", "len", "(", "self", ".", "_plots", ")", "+", "self", ".", "_ncols", "-", "1", ")", "/", "self", ".", "_ncols", ")", "# this should work also for odd n", "cheight", "=", "500", "*", "nrows", "if", "ratio", ":", "cheight", "=", "int", "(", "cheight", "*", "self", ".", "_ratioFactor", ")", "canvas", "=", "_createCanvas", "(", "self", ".", "_name", ",", "cwidth", ",", "cheight", ")", "canvas", ".", "Divide", "(", "self", ".", "_ncols", ",", "nrows", ")", "if", "ratio", ":", "for", "i", ",", "plot", "in", "enumerate", "(", "self", ".", "_plots", ")", ":", "pad", "=", "canvas", ".", "cd", "(", "i", "+", "1", ")", "self", ".", "_modifyPadForRatio", "(", "pad", ")", "# Draw plots to canvas", "for", "i", ",", "plot", "in", "enumerate", "(", "self", ".", "_plots", ")", ":", "pad", "=", "canvas", ".", "cd", "(", "i", "+", "1", ")", "if", "not", "plot", ".", "isEmpty", "(", ")", ":", "plot", ".", "draw", "(", "pad", ",", "ratio", ",", "self", ".", "_ratioFactor", ",", "nrows", ")", "# Setup legend", "canvas", ".", "cd", "(", ")", "if", "len", "(", "self", ".", "_plots", ")", "<=", "4", ":", "lx1", "=", "0.2", "lx2", "=", "0.9", "ly1", "=", "0.48", "ly2", "=", "0.53", "else", ":", "lx1", "=", "0.1", "lx2", "=", "0.9", "ly1", "=", "0.64", "ly2", "=", "0.67", "if", "self", ".", "_legendDx", "is", "not", "None", ":", "lx1", "+=", "self", ".", "_legendDx", "lx2", "+=", "self", ".", "_legendDx", "if", "self", ".", "_legendDy", "is", "not", "None", ":", "ly1", "+=", "self", ".", "_legendDy", "ly2", "+=", "self", ".", "_legendDy", "if", "self", ".", "_legendDw", "is", "not", "None", ":", "lx2", "+=", "self", ".", "_legendDw", "if", "self", ".", "_legendDh", "is", "not", "None", ":", "ly1", "-=", "self", ".", "_legendDh", "plot", "=", "max", "(", "self", ".", "_plots", ",", "key", "=", "lambda", "p", ":", "p", ".", "getNumberOfHistograms", "(", ")", ")", "denomUnc", "=", "sum", "(", "[", "p", ".", "drawRatioUncertainty", "(", ")", "for", "p", "in", "self", ".", "_plots", "]", ")", ">", "0", "legend", "=", "self", ".", "_createLegend", "(", "plot", ",", "legendLabels", ",", "lx1", ",", "ly1", ",", "lx2", ",", "ly2", ",", "denomUncertainty", "=", "(", "ratio", "and", "denomUnc", ")", ")", "return", "self", ".", "_save", "(", "canvas", ",", "saveFormat", ",", "prefix", "=", "prefix", ",", "directory", "=", "directory", ")" ]
https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/Validation/RecoTrack/python/plotting/plotting.py#L2337-L2412
fatih/subvim
241b6d170597857105da219c9b7d36059e9f11fb
vim/base/YouCompleteMe/third_party/jedi/jedi/parser/fast.py
python
FastParser._scan_user_scope
(self, sub_module)
return None
Scan with self.user_position.
Scan with self.user_position.
[ "Scan", "with", "self", ".", "user_position", "." ]
def _scan_user_scope(self, sub_module): """ Scan with self.user_position. """ for scope in sub_module.statements + sub_module.subscopes: if isinstance(scope, pr.Scope): if scope.start_pos <= self.user_position <= scope.end_pos: return self._scan_user_scope(scope) or scope return None
[ "def", "_scan_user_scope", "(", "self", ",", "sub_module", ")", ":", "for", "scope", "in", "sub_module", ".", "statements", "+", "sub_module", ".", "subscopes", ":", "if", "isinstance", "(", "scope", ",", "pr", ".", "Scope", ")", ":", "if", "scope", ".", "start_pos", "<=", "self", ".", "user_position", "<=", "scope", ".", "end_pos", ":", "return", "self", ".", "_scan_user_scope", "(", "scope", ")", "or", "scope", "return", "None" ]
https://github.com/fatih/subvim/blob/241b6d170597857105da219c9b7d36059e9f11fb/vim/base/YouCompleteMe/third_party/jedi/jedi/parser/fast.py#L237-L243
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/dataview.py
python
DataViewCtrl.IsExpanded
(*args, **kwargs)
return _dataview.DataViewCtrl_IsExpanded(*args, **kwargs)
IsExpanded(self, DataViewItem item) -> bool
IsExpanded(self, DataViewItem item) -> bool
[ "IsExpanded", "(", "self", "DataViewItem", "item", ")", "-", ">", "bool" ]
def IsExpanded(*args, **kwargs): """IsExpanded(self, DataViewItem item) -> bool""" return _dataview.DataViewCtrl_IsExpanded(*args, **kwargs)
[ "def", "IsExpanded", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_dataview", ".", "DataViewCtrl_IsExpanded", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/dataview.py#L1808-L1810
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/cookielib.py
python
split_header_words
(header_values)
return result
r"""Parse header values into a list of lists containing key,value pairs. The function knows how to deal with ",", ";" and "=" as well as quoted values after "=". A list of space separated tokens are parsed as if they were separated by ";". If the header_values passed as argument contains multiple values, then they are treated as if they were a single value separated by comma ",". This means that this function is useful for parsing header fields that follow this syntax (BNF as from the HTTP/1.1 specification, but we relax the requirement for tokens). headers = #header header = (token | parameter) *( [";"] (token | parameter)) token = 1*<any CHAR except CTLs or separators> separators = "(" | ")" | "<" | ">" | "@" | "," | ";" | ":" | "\" | <"> | "/" | "[" | "]" | "?" | "=" | "{" | "}" | SP | HT quoted-string = ( <"> *(qdtext | quoted-pair ) <"> ) qdtext = <any TEXT except <">> quoted-pair = "\" CHAR parameter = attribute "=" value attribute = token value = token | quoted-string Each header is represented by a list of key/value pairs. The value for a simple token (not part of a parameter) is None. Syntactically incorrect headers will not necessarily be parsed as you would want. This is easier to describe with some examples: >>> split_header_words(['foo="bar"; port="80,81"; discard, bar=baz']) [[('foo', 'bar'), ('port', '80,81'), ('discard', None)], [('bar', 'baz')]] >>> split_header_words(['text/html; charset="iso-8859-1"']) [[('text/html', None), ('charset', 'iso-8859-1')]] >>> split_header_words([r'Basic realm="\"foo\bar\""']) [[('Basic', None), ('realm', '"foobar"')]]
r"""Parse header values into a list of lists containing key,value pairs.
[ "r", "Parse", "header", "values", "into", "a", "list", "of", "lists", "containing", "key", "value", "pairs", "." ]
def split_header_words(header_values): r"""Parse header values into a list of lists containing key,value pairs. The function knows how to deal with ",", ";" and "=" as well as quoted values after "=". A list of space separated tokens are parsed as if they were separated by ";". If the header_values passed as argument contains multiple values, then they are treated as if they were a single value separated by comma ",". This means that this function is useful for parsing header fields that follow this syntax (BNF as from the HTTP/1.1 specification, but we relax the requirement for tokens). headers = #header header = (token | parameter) *( [";"] (token | parameter)) token = 1*<any CHAR except CTLs or separators> separators = "(" | ")" | "<" | ">" | "@" | "," | ";" | ":" | "\" | <"> | "/" | "[" | "]" | "?" | "=" | "{" | "}" | SP | HT quoted-string = ( <"> *(qdtext | quoted-pair ) <"> ) qdtext = <any TEXT except <">> quoted-pair = "\" CHAR parameter = attribute "=" value attribute = token value = token | quoted-string Each header is represented by a list of key/value pairs. The value for a simple token (not part of a parameter) is None. Syntactically incorrect headers will not necessarily be parsed as you would want. This is easier to describe with some examples: >>> split_header_words(['foo="bar"; port="80,81"; discard, bar=baz']) [[('foo', 'bar'), ('port', '80,81'), ('discard', None)], [('bar', 'baz')]] >>> split_header_words(['text/html; charset="iso-8859-1"']) [[('text/html', None), ('charset', 'iso-8859-1')]] >>> split_header_words([r'Basic realm="\"foo\bar\""']) [[('Basic', None), ('realm', '"foobar"')]] """ assert not isinstance(header_values, basestring) result = [] for text in header_values: orig_text = text pairs = [] while text: m = HEADER_TOKEN_RE.search(text) if m: text = unmatched(m) name = m.group(1) m = HEADER_QUOTED_VALUE_RE.search(text) if m: # quoted value text = unmatched(m) value = m.group(1) value = HEADER_ESCAPE_RE.sub(r"\1", value) else: m = HEADER_VALUE_RE.search(text) if m: # unquoted value text = unmatched(m) value = m.group(1) value = value.rstrip() else: # no value, a lone token value = None pairs.append((name, value)) elif text.lstrip().startswith(","): # concatenated headers, as per RFC 2616 section 4.2 text = text.lstrip()[1:] if pairs: result.append(pairs) pairs = [] else: # skip junk non_junk, nr_junk_chars = re.subn("^[=\s;]*", "", text) assert nr_junk_chars > 0, ( "split_header_words bug: '%s', '%s', %s" % (orig_text, text, pairs)) text = non_junk if pairs: result.append(pairs) return result
[ "def", "split_header_words", "(", "header_values", ")", ":", "assert", "not", "isinstance", "(", "header_values", ",", "basestring", ")", "result", "=", "[", "]", "for", "text", "in", "header_values", ":", "orig_text", "=", "text", "pairs", "=", "[", "]", "while", "text", ":", "m", "=", "HEADER_TOKEN_RE", ".", "search", "(", "text", ")", "if", "m", ":", "text", "=", "unmatched", "(", "m", ")", "name", "=", "m", ".", "group", "(", "1", ")", "m", "=", "HEADER_QUOTED_VALUE_RE", ".", "search", "(", "text", ")", "if", "m", ":", "# quoted value", "text", "=", "unmatched", "(", "m", ")", "value", "=", "m", ".", "group", "(", "1", ")", "value", "=", "HEADER_ESCAPE_RE", ".", "sub", "(", "r\"\\1\"", ",", "value", ")", "else", ":", "m", "=", "HEADER_VALUE_RE", ".", "search", "(", "text", ")", "if", "m", ":", "# unquoted value", "text", "=", "unmatched", "(", "m", ")", "value", "=", "m", ".", "group", "(", "1", ")", "value", "=", "value", ".", "rstrip", "(", ")", "else", ":", "# no value, a lone token", "value", "=", "None", "pairs", ".", "append", "(", "(", "name", ",", "value", ")", ")", "elif", "text", ".", "lstrip", "(", ")", ".", "startswith", "(", "\",\"", ")", ":", "# concatenated headers, as per RFC 2616 section 4.2", "text", "=", "text", ".", "lstrip", "(", ")", "[", "1", ":", "]", "if", "pairs", ":", "result", ".", "append", "(", "pairs", ")", "pairs", "=", "[", "]", "else", ":", "# skip junk", "non_junk", ",", "nr_junk_chars", "=", "re", ".", "subn", "(", "\"^[=\\s;]*\"", ",", "\"\"", ",", "text", ")", "assert", "nr_junk_chars", ">", "0", ",", "(", "\"split_header_words bug: '%s', '%s', %s\"", "%", "(", "orig_text", ",", "text", ",", "pairs", ")", ")", "text", "=", "non_junk", "if", "pairs", ":", "result", ".", "append", "(", "pairs", ")", "return", "result" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/cookielib.py#L326-L409
eventql/eventql
7ca0dbb2e683b525620ea30dc40540a22d5eb227
deps/3rdparty/spidermonkey/mozjs/build/pymake/pymake/parser.py
python
itermakefilechars
(d, offset, tokenlist, it, ignorecomments=False)
Iterate over data in makefile syntax. Comments are found at unescaped # characters, and escaped newlines are converted to single-space continuations.
Iterate over data in makefile syntax. Comments are found at unescaped # characters, and escaped newlines are converted to single-space continuations.
[ "Iterate", "over", "data", "in", "makefile", "syntax", ".", "Comments", "are", "found", "at", "unescaped", "#", "characters", "and", "escaped", "newlines", "are", "converted", "to", "single", "-", "space", "continuations", "." ]
def itermakefilechars(d, offset, tokenlist, it, ignorecomments=False): """ Iterate over data in makefile syntax. Comments are found at unescaped # characters, and escaped newlines are converted to single-space continuations. """ assert offset >= d.lstart and offset <= d.lend, "offset %i should be between %i and %i" % (offset, d.lstart, d.lend) if offset == d.lend: return s = d.s for m in it: mstart, mend = m.span(0) token = s[mstart:mend] starttext = _makecontinuations.sub(_replacemakecontinuations, s[offset:mstart]) if token[-1] == '#' and not ignorecomments: l = mend - mstart # multiple backslashes before a hash are unescaped, halving their total number if l % 2: # found a comment yield starttext + token[:(l - 1) / 2], None, None, None return else: yield starttext + token[-l / 2:], None, None, mend elif token in tokenlist or (token[0] == '$' and '$' in tokenlist): yield starttext, token, mstart, mend else: yield starttext + token, None, None, mend offset = mend yield _makecontinuations.sub(_replacemakecontinuations, s[offset:d.lend]), None, None, None
[ "def", "itermakefilechars", "(", "d", ",", "offset", ",", "tokenlist", ",", "it", ",", "ignorecomments", "=", "False", ")", ":", "assert", "offset", ">=", "d", ".", "lstart", "and", "offset", "<=", "d", ".", "lend", ",", "\"offset %i should be between %i and %i\"", "%", "(", "offset", ",", "d", ".", "lstart", ",", "d", ".", "lend", ")", "if", "offset", "==", "d", ".", "lend", ":", "return", "s", "=", "d", ".", "s", "for", "m", "in", "it", ":", "mstart", ",", "mend", "=", "m", ".", "span", "(", "0", ")", "token", "=", "s", "[", "mstart", ":", "mend", "]", "starttext", "=", "_makecontinuations", ".", "sub", "(", "_replacemakecontinuations", ",", "s", "[", "offset", ":", "mstart", "]", ")", "if", "token", "[", "-", "1", "]", "==", "'#'", "and", "not", "ignorecomments", ":", "l", "=", "mend", "-", "mstart", "# multiple backslashes before a hash are unescaped, halving their total number", "if", "l", "%", "2", ":", "# found a comment", "yield", "starttext", "+", "token", "[", ":", "(", "l", "-", "1", ")", "/", "2", "]", ",", "None", ",", "None", ",", "None", "return", "else", ":", "yield", "starttext", "+", "token", "[", "-", "l", "/", "2", ":", "]", ",", "None", ",", "None", ",", "mend", "elif", "token", "in", "tokenlist", "or", "(", "token", "[", "0", "]", "==", "'$'", "and", "'$'", "in", "tokenlist", ")", ":", "yield", "starttext", ",", "token", ",", "mstart", ",", "mend", "else", ":", "yield", "starttext", "+", "token", ",", "None", ",", "None", ",", "mend", "offset", "=", "mend", "yield", "_makecontinuations", ".", "sub", "(", "_replacemakecontinuations", ",", "s", "[", "offset", ":", "d", ".", "lend", "]", ")", ",", "None", ",", "None", ",", "None" ]
https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/build/pymake/pymake/parser.py#L146-L179
oracle/graaljs
36a56e8e993d45fc40939a3a4d9c0c24990720f1
graal-nodejs/deps/v8/third_party/jinja2/filters.py
python
do_format
(value, *args, **kwargs)
return soft_unicode(value) % (kwargs or args)
Apply python string formatting on an object: .. sourcecode:: jinja {{ "%s - %s"|format("Hello?", "Foo!") }} -> Hello? - Foo!
Apply python string formatting on an object:
[ "Apply", "python", "string", "formatting", "on", "an", "object", ":" ]
def do_format(value, *args, **kwargs): """ Apply python string formatting on an object: .. sourcecode:: jinja {{ "%s - %s"|format("Hello?", "Foo!") }} -> Hello? - Foo! """ if args and kwargs: raise FilterArgumentError('can\'t handle positional and keyword ' 'arguments at the same time') return soft_unicode(value) % (kwargs or args)
[ "def", "do_format", "(", "value", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "args", "and", "kwargs", ":", "raise", "FilterArgumentError", "(", "'can\\'t handle positional and keyword '", "'arguments at the same time'", ")", "return", "soft_unicode", "(", "value", ")", "%", "(", "kwargs", "or", "args", ")" ]
https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/deps/v8/third_party/jinja2/filters.py#L673-L685
jeog/TOSDataBridge
6a5a08ca5cf3883db1f12e9bc89ef374d098df5a
python/tosdb/_common.py
python
_TOSDB_DataBlock.remove_items
()
Remove items (ex. 'IBM', 'SPY') from the block. NOTE: if this call removes all items from the block the remaining topics will be pre-cached and appear not to exist, until a valid item is re-added. remove_items(self, *items) *items :: *str :: any numer of item strings in the block throws TOSDB_Error
Remove items (ex. 'IBM', 'SPY') from the block.
[ "Remove", "items", "(", "ex", ".", "IBM", "SPY", ")", "from", "the", "block", "." ]
def remove_items(): """ Remove items (ex. 'IBM', 'SPY') from the block. NOTE: if this call removes all items from the block the remaining topics will be pre-cached and appear not to exist, until a valid item is re-added. remove_items(self, *items) *items :: *str :: any numer of item strings in the block throws TOSDB_Error """ pass
[ "def", "remove_items", "(", ")", ":", "pass" ]
https://github.com/jeog/TOSDataBridge/blob/6a5a08ca5cf3883db1f12e9bc89ef374d098df5a/python/tosdb/_common.py#L211-L223
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/metrics_impl.py
python
false_positives_at_thresholds
(labels, predictions, thresholds, weights=None, metrics_collections=None, updates_collections=None, name=None)
Computes false positives at provided threshold values. If `weights` is `None`, weights default to 1. Use weights of 0 to mask values. Args: labels: A `Tensor` whose shape matches `predictions`. Will be cast to `bool`. predictions: A floating point `Tensor` of arbitrary shape and whose values are in the range `[0, 1]`. thresholds: A python list or tuple of float thresholds in `[0, 1]`. weights: Optional `Tensor` whose rank is either 0, or the same rank as `labels`, and must be broadcastable to `labels` (i.e., all dimensions must be either `1`, or the same as the corresponding `labels` dimension). metrics_collections: An optional list of collections that `false_positives` should be added to. updates_collections: An optional list of collections that `update_op` should be added to. name: An optional variable_scope name. Returns: false_positives: A float `Tensor` of shape `[len(thresholds)]`. update_op: An operation that updates the `false_positives` variable and returns its current value. Raises: ValueError: If `predictions` and `labels` have mismatched shapes, or if `weights` is not `None` and its shape doesn't match `predictions`, or if either `metrics_collections` or `updates_collections` are not a list or tuple. RuntimeError: If eager execution is enabled.
Computes false positives at provided threshold values.
[ "Computes", "false", "positives", "at", "provided", "threshold", "values", "." ]
def false_positives_at_thresholds(labels, predictions, thresholds, weights=None, metrics_collections=None, updates_collections=None, name=None): """Computes false positives at provided threshold values. If `weights` is `None`, weights default to 1. Use weights of 0 to mask values. Args: labels: A `Tensor` whose shape matches `predictions`. Will be cast to `bool`. predictions: A floating point `Tensor` of arbitrary shape and whose values are in the range `[0, 1]`. thresholds: A python list or tuple of float thresholds in `[0, 1]`. weights: Optional `Tensor` whose rank is either 0, or the same rank as `labels`, and must be broadcastable to `labels` (i.e., all dimensions must be either `1`, or the same as the corresponding `labels` dimension). metrics_collections: An optional list of collections that `false_positives` should be added to. updates_collections: An optional list of collections that `update_op` should be added to. name: An optional variable_scope name. Returns: false_positives: A float `Tensor` of shape `[len(thresholds)]`. update_op: An operation that updates the `false_positives` variable and returns its current value. Raises: ValueError: If `predictions` and `labels` have mismatched shapes, or if `weights` is not `None` and its shape doesn't match `predictions`, or if either `metrics_collections` or `updates_collections` are not a list or tuple. RuntimeError: If eager execution is enabled. """ if context.executing_eagerly(): raise RuntimeError('tf.metrics.false_positives_at_thresholds is not ' 'supported when eager execution is enabled.') with variable_scope.variable_scope(name, 'false_positives', (predictions, labels, weights)): values, update_ops = _confusion_matrix_at_thresholds( labels, predictions, thresholds, weights=weights, includes=('fp',)) fp_value = _aggregate_variable(values['fp'], metrics_collections) if updates_collections: ops.add_to_collections(updates_collections, update_ops['fp']) return fp_value, update_ops['fp']
[ "def", "false_positives_at_thresholds", "(", "labels", ",", "predictions", ",", "thresholds", ",", "weights", "=", "None", ",", "metrics_collections", "=", "None", ",", "updates_collections", "=", "None", ",", "name", "=", "None", ")", ":", "if", "context", ".", "executing_eagerly", "(", ")", ":", "raise", "RuntimeError", "(", "'tf.metrics.false_positives_at_thresholds is not '", "'supported when eager execution is enabled.'", ")", "with", "variable_scope", ".", "variable_scope", "(", "name", ",", "'false_positives'", ",", "(", "predictions", ",", "labels", ",", "weights", ")", ")", ":", "values", ",", "update_ops", "=", "_confusion_matrix_at_thresholds", "(", "labels", ",", "predictions", ",", "thresholds", ",", "weights", "=", "weights", ",", "includes", "=", "(", "'fp'", ",", ")", ")", "fp_value", "=", "_aggregate_variable", "(", "values", "[", "'fp'", "]", ",", "metrics_collections", ")", "if", "updates_collections", ":", "ops", ".", "add_to_collections", "(", "updates_collections", ",", "update_ops", "[", "'fp'", "]", ")", "return", "fp_value", ",", "update_ops", "[", "'fp'", "]" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/metrics_impl.py#L1674-L1726
ricardoquesada/Spidermonkey
4a75ea2543408bd1b2c515aa95901523eeef7858
config/configobj.py
python
ConfigObj._handle_repeat
(self, section, configspec)
Dynamically assign configspec for repeated section.
Dynamically assign configspec for repeated section.
[ "Dynamically", "assign", "configspec", "for", "repeated", "section", "." ]
def _handle_repeat(self, section, configspec): """Dynamically assign configspec for repeated section.""" try: section_keys = configspec.sections scalar_keys = configspec.scalars except AttributeError: section_keys = [entry for entry in configspec if isinstance(configspec[entry], dict)] scalar_keys = [entry for entry in configspec if not isinstance(configspec[entry], dict)] if '__many__' in section_keys and len(section_keys) > 1: # FIXME: can we supply any useful information here ? raise RepeatSectionError scalars = {} sections = {} for entry in scalar_keys: val = configspec[entry] scalars[entry] = val for entry in section_keys: val = configspec[entry] if entry == '__many__': scalars[entry] = val continue sections[entry] = val # section.configspec = scalars for entry in sections: if not section.has_key(entry): section[entry] = {} self._handle_repeat(section[entry], sections[entry])
[ "def", "_handle_repeat", "(", "self", ",", "section", ",", "configspec", ")", ":", "try", ":", "section_keys", "=", "configspec", ".", "sections", "scalar_keys", "=", "configspec", ".", "scalars", "except", "AttributeError", ":", "section_keys", "=", "[", "entry", "for", "entry", "in", "configspec", "if", "isinstance", "(", "configspec", "[", "entry", "]", ",", "dict", ")", "]", "scalar_keys", "=", "[", "entry", "for", "entry", "in", "configspec", "if", "not", "isinstance", "(", "configspec", "[", "entry", "]", ",", "dict", ")", "]", "if", "'__many__'", "in", "section_keys", "and", "len", "(", "section_keys", ")", ">", "1", ":", "# FIXME: can we supply any useful information here ?", "raise", "RepeatSectionError", "scalars", "=", "{", "}", "sections", "=", "{", "}", "for", "entry", "in", "scalar_keys", ":", "val", "=", "configspec", "[", "entry", "]", "scalars", "[", "entry", "]", "=", "val", "for", "entry", "in", "section_keys", ":", "val", "=", "configspec", "[", "entry", "]", "if", "entry", "==", "'__many__'", ":", "scalars", "[", "entry", "]", "=", "val", "continue", "sections", "[", "entry", "]", "=", "val", "#", "section", ".", "configspec", "=", "scalars", "for", "entry", "in", "sections", ":", "if", "not", "section", ".", "has_key", "(", "entry", ")", ":", "section", "[", "entry", "]", "=", "{", "}", "self", ".", "_handle_repeat", "(", "section", "[", "entry", "]", ",", "sections", "[", "entry", "]", ")" ]
https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/config/configobj.py#L1826-L1855
smartdevicelink/sdl_core
68f082169e0a40fccd9eb0db3c83911c28870f07
tools/InterfaceGenerator/generator/generators/SmartFactoryBase.py
python
CodeGenerator._indent_code
(self, code, indent_level)
return u"".join( [u"{0}{1}\n".format( self._indent_template * indent_level, x) if x != u"" else u"\n" for x in code_lines])
Indent given source code. Indents given source code right by given indentation level. Keyword arguments: code -- given source code. indent_level -- desired indentation level. Returns: String with processed code.
Indent given source code.
[ "Indent", "given", "source", "code", "." ]
def _indent_code(self, code, indent_level): """Indent given source code. Indents given source code right by given indentation level. Keyword arguments: code -- given source code. indent_level -- desired indentation level. Returns: String with processed code. """ code_lines = code.split("\n") return u"".join( [u"{0}{1}\n".format( self._indent_template * indent_level, x) if x != u"" else u"\n" for x in code_lines])
[ "def", "_indent_code", "(", "self", ",", "code", ",", "indent_level", ")", ":", "code_lines", "=", "code", ".", "split", "(", "\"\\n\"", ")", "return", "u\"\"", ".", "join", "(", "[", "u\"{0}{1}\\n\"", ".", "format", "(", "self", ".", "_indent_template", "*", "indent_level", ",", "x", ")", "if", "x", "!=", "u\"\"", "else", "u\"\\n\"", "for", "x", "in", "code_lines", "]", ")" ]
https://github.com/smartdevicelink/sdl_core/blob/68f082169e0a40fccd9eb0db3c83911c28870f07/tools/InterfaceGenerator/generator/generators/SmartFactoryBase.py#L1482-L1500
ceph/ceph
959663007321a369c83218414a29bd9dbc8bda3a
qa/tasks/barbican.py
python
assign_ports
(ctx, config, initial_port)
return role_endpoints
Assign port numbers starting from @initial_port
Assign port numbers starting from
[ "Assign", "port", "numbers", "starting", "from" ]
def assign_ports(ctx, config, initial_port): """ Assign port numbers starting from @initial_port """ port = initial_port role_endpoints = {} for remote, roles_for_host in ctx.cluster.remotes.items(): for role in roles_for_host: if role in config: role_endpoints[role] = (remote.name.split('@')[1], port) port += 1 return role_endpoints
[ "def", "assign_ports", "(", "ctx", ",", "config", ",", "initial_port", ")", ":", "port", "=", "initial_port", "role_endpoints", "=", "{", "}", "for", "remote", ",", "roles_for_host", "in", "ctx", ".", "cluster", ".", "remotes", ".", "items", "(", ")", ":", "for", "role", "in", "roles_for_host", ":", "if", "role", "in", "config", ":", "role_endpoints", "[", "role", "]", "=", "(", "remote", ".", "name", ".", "split", "(", "'@'", ")", "[", "1", "]", ",", "port", ")", "port", "+=", "1", "return", "role_endpoints" ]
https://github.com/ceph/ceph/blob/959663007321a369c83218414a29bd9dbc8bda3a/qa/tasks/barbican.py#L108-L120
deepmind/reverb
ef3c8f0be1b720a741d2dee335e15e44668c291a
reverb/server.py
python
Table.stack
(cls, name: str, max_size: int, extensions: Sequence[TableExtensionBase] = (), signature: Optional[reverb_types.SpecNest] = None)
return cls( name=name, sampler=item_selectors.Lifo(), remover=item_selectors.Lifo(), max_size=max_size, max_times_sampled=1, rate_limiter=rate_limiters.Stack(max_size), extensions=extensions, signature=signature)
Constructs a Table which acts like a stack. Args: name: Name of the priority table (aka stack). max_size: Maximum number of items in the priority table (aka stack). extensions: See documentation in the constructor. signature: See documentation in the constructor. Returns: Table which behaves like a stack of size `max_size`.
Constructs a Table which acts like a stack.
[ "Constructs", "a", "Table", "which", "acts", "like", "a", "stack", "." ]
def stack(cls, name: str, max_size: int, extensions: Sequence[TableExtensionBase] = (), signature: Optional[reverb_types.SpecNest] = None): """Constructs a Table which acts like a stack. Args: name: Name of the priority table (aka stack). max_size: Maximum number of items in the priority table (aka stack). extensions: See documentation in the constructor. signature: See documentation in the constructor. Returns: Table which behaves like a stack of size `max_size`. """ return cls( name=name, sampler=item_selectors.Lifo(), remover=item_selectors.Lifo(), max_size=max_size, max_times_sampled=1, rate_limiter=rate_limiters.Stack(max_size), extensions=extensions, signature=signature)
[ "def", "stack", "(", "cls", ",", "name", ":", "str", ",", "max_size", ":", "int", ",", "extensions", ":", "Sequence", "[", "TableExtensionBase", "]", "=", "(", ")", ",", "signature", ":", "Optional", "[", "reverb_types", ".", "SpecNest", "]", "=", "None", ")", ":", "return", "cls", "(", "name", "=", "name", ",", "sampler", "=", "item_selectors", ".", "Lifo", "(", ")", ",", "remover", "=", "item_selectors", ".", "Lifo", "(", ")", ",", "max_size", "=", "max_size", ",", "max_times_sampled", "=", "1", ",", "rate_limiter", "=", "rate_limiters", ".", "Stack", "(", "max_size", ")", ",", "extensions", "=", "extensions", ",", "signature", "=", "signature", ")" ]
https://github.com/deepmind/reverb/blob/ef3c8f0be1b720a741d2dee335e15e44668c291a/reverb/server.py#L192-L216
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
current/deps/v8/third_party/jinja2/utils.py
python
environmentfunction
(f)
return f
This decorator can be used to mark a function or method as environment callable. This decorator works exactly like the :func:`contextfunction` decorator just that the first argument is the active :class:`Environment` and not context.
This decorator can be used to mark a function or method as environment callable. This decorator works exactly like the :func:`contextfunction` decorator just that the first argument is the active :class:`Environment` and not context.
[ "This", "decorator", "can", "be", "used", "to", "mark", "a", "function", "or", "method", "as", "environment", "callable", ".", "This", "decorator", "works", "exactly", "like", "the", ":", "func", ":", "contextfunction", "decorator", "just", "that", "the", "first", "argument", "is", "the", "active", ":", "class", ":", "Environment", "and", "not", "context", "." ]
def environmentfunction(f): """This decorator can be used to mark a function or method as environment callable. This decorator works exactly like the :func:`contextfunction` decorator just that the first argument is the active :class:`Environment` and not context. """ f.environmentfunction = True return f
[ "def", "environmentfunction", "(", "f", ")", ":", "f", ".", "environmentfunction", "=", "True", "return", "f" ]
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/current/deps/v8/third_party/jinja2/utils.py#L73-L80
Smorodov/Multitarget-tracker
bee300e8bfd660c86cbeb6892c65a5b7195c9381
thirdparty/pybind11/tools/clang/cindex.py
python
CursorKind.is_expression
(self)
return conf.lib.clang_isExpression(self)
Test if this is an expression kind.
Test if this is an expression kind.
[ "Test", "if", "this", "is", "an", "expression", "kind", "." ]
def is_expression(self): """Test if this is an expression kind.""" return conf.lib.clang_isExpression(self)
[ "def", "is_expression", "(", "self", ")", ":", "return", "conf", ".", "lib", ".", "clang_isExpression", "(", "self", ")" ]
https://github.com/Smorodov/Multitarget-tracker/blob/bee300e8bfd660c86cbeb6892c65a5b7195c9381/thirdparty/pybind11/tools/clang/cindex.py#L584-L586
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/thumbnailctrl.py
python
ScrolledThumbnail.SetCaption
(self, caption="")
Sets the current caption string. :param `caption`: the current caption string.
Sets the current caption string.
[ "Sets", "the", "current", "caption", "string", "." ]
def SetCaption(self, caption=""): """ Sets the current caption string. :param `caption`: the current caption string. """ self._caption = caption if self._labelcontrol: maxWidth = self._labelcontrol.GetSize().GetWidth()/8 if len(caption) > maxWidth: caption = "..." + caption[len(caption) + 3 - maxWidth] self._labelcontrol.SetLabel(caption) eventOut = ThumbnailEvent(wxEVT_THUMBNAILS_CAPTION_CHANGED, self.GetId()) self.GetEventHandler().ProcessEvent(eventOut)
[ "def", "SetCaption", "(", "self", ",", "caption", "=", "\"\"", ")", ":", "self", ".", "_caption", "=", "caption", "if", "self", ".", "_labelcontrol", ":", "maxWidth", "=", "self", ".", "_labelcontrol", ".", "GetSize", "(", ")", ".", "GetWidth", "(", ")", "/", "8", "if", "len", "(", "caption", ")", ">", "maxWidth", ":", "caption", "=", "\"...\"", "+", "caption", "[", "len", "(", "caption", ")", "+", "3", "-", "maxWidth", "]", "self", ".", "_labelcontrol", ".", "SetLabel", "(", "caption", ")", "eventOut", "=", "ThumbnailEvent", "(", "wxEVT_THUMBNAILS_CAPTION_CHANGED", ",", "self", ".", "GetId", "(", ")", ")", "self", ".", "GetEventHandler", "(", ")", ".", "ProcessEvent", "(", "eventOut", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/thumbnailctrl.py#L1731-L1748
hughperkins/tf-coriander
970d3df6c11400ad68405f22b0c42a52374e94ca
tensorflow/contrib/learn/python/learn/monitors.py
python
CaptureVariable.values
(self)
return self._var_values
Returns the values captured so far. Returns: `dict` mapping `int` step numbers to that values of the variable at the respective step.
Returns the values captured so far.
[ "Returns", "the", "values", "captured", "so", "far", "." ]
def values(self): """Returns the values captured so far. Returns: `dict` mapping `int` step numbers to that values of the variable at the respective step. """ return self._var_values
[ "def", "values", "(", "self", ")", ":", "return", "self", ".", "_var_values" ]
https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/contrib/learn/python/learn/monitors.py#L770-L777
CoolProp/CoolProp
381c8535e5dec3eec27ad430ebbfff8bc9dfc008
dev/scripts/viscosity_builder.py
python
viscosity_linear
(fluid, T, rho, e_k, sigma)
return viscosity_dilute(fluid, T, e_k, sigma) * B_eta * rho / molemass * 1000
Implements the method of Vogel 1998 (Propane) for the linear part
Implements the method of Vogel 1998 (Propane) for the linear part
[ "Implements", "the", "method", "of", "Vogel", "1998", "(", "Propane", ")", "for", "the", "linear", "part" ]
def viscosity_linear(fluid, T, rho, e_k, sigma): """ Implements the method of Vogel 1998 (Propane) for the linear part """ N_A = 6.02214129e23 molemass = Props(fluid, 'molemass') Tstar = T / e_k b = [-19.572881, 219.73999, -1015.3226, 2471.01251, -3375.1717, 2491.6597, -787.26086, 14.085455, -0.34664158] s = sum([b[i] * pow(Tstar, -0.25 * i) for i in range(7)]) B_eta_star = s + b[7] * pow(Tstar, -2.5) + b[8] * pow(Tstar, -5.5) # //[no units] B_eta = N_A * pow(sigma / 1e9, 3) * B_eta_star # [m3/mol] return viscosity_dilute(fluid, T, e_k, sigma) * B_eta * rho / molemass * 1000
[ "def", "viscosity_linear", "(", "fluid", ",", "T", ",", "rho", ",", "e_k", ",", "sigma", ")", ":", "N_A", "=", "6.02214129e23", "molemass", "=", "Props", "(", "fluid", ",", "'molemass'", ")", "Tstar", "=", "T", "/", "e_k", "b", "=", "[", "-", "19.572881", ",", "219.73999", ",", "-", "1015.3226", ",", "2471.01251", ",", "-", "3375.1717", ",", "2491.6597", ",", "-", "787.26086", ",", "14.085455", ",", "-", "0.34664158", "]", "s", "=", "sum", "(", "[", "b", "[", "i", "]", "*", "pow", "(", "Tstar", ",", "-", "0.25", "*", "i", ")", "for", "i", "in", "range", "(", "7", ")", "]", ")", "B_eta_star", "=", "s", "+", "b", "[", "7", "]", "*", "pow", "(", "Tstar", ",", "-", "2.5", ")", "+", "b", "[", "8", "]", "*", "pow", "(", "Tstar", ",", "-", "5.5", ")", "# //[no units]", "B_eta", "=", "N_A", "*", "pow", "(", "sigma", "/", "1e9", ",", "3", ")", "*", "B_eta_star", "# [m3/mol]", "return", "viscosity_dilute", "(", "fluid", ",", "T", ",", "e_k", ",", "sigma", ")", "*", "B_eta", "*", "rho", "/", "molemass", "*", "1000" ]
https://github.com/CoolProp/CoolProp/blob/381c8535e5dec3eec27ad430ebbfff8bc9dfc008/dev/scripts/viscosity_builder.py#L43-L55
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_core.py
python
Window.Layout
(*args, **kwargs)
return _core_.Window_Layout(*args, **kwargs)
Layout(self) -> bool Invokes the constraint-based layout algorithm or the sizer-based algorithm for this window. See SetAutoLayout: when auto layout is on, this function gets called automatically by the default EVT_SIZE handler when the window is resized.
Layout(self) -> bool
[ "Layout", "(", "self", ")", "-", ">", "bool" ]
def Layout(*args, **kwargs): """ Layout(self) -> bool Invokes the constraint-based layout algorithm or the sizer-based algorithm for this window. See SetAutoLayout: when auto layout is on, this function gets called automatically by the default EVT_SIZE handler when the window is resized. """ return _core_.Window_Layout(*args, **kwargs)
[ "def", "Layout", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "Window_Layout", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L11491-L11500
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/requests/sessions.py
python
SessionRedirectMixin.rebuild_auth
(self, prepared_request, response)
When being redirected we may want to strip authentication from the request to avoid leaking credentials. This method intelligently removes and reapplies authentication where possible to avoid credential loss.
When being redirected we may want to strip authentication from the request to avoid leaking credentials. This method intelligently removes and reapplies authentication where possible to avoid credential loss.
[ "When", "being", "redirected", "we", "may", "want", "to", "strip", "authentication", "from", "the", "request", "to", "avoid", "leaking", "credentials", ".", "This", "method", "intelligently", "removes", "and", "reapplies", "authentication", "where", "possible", "to", "avoid", "credential", "loss", "." ]
def rebuild_auth(self, prepared_request, response): """When being redirected we may want to strip authentication from the request to avoid leaking credentials. This method intelligently removes and reapplies authentication where possible to avoid credential loss. """ headers = prepared_request.headers url = prepared_request.url if 'Authorization' in headers and self.should_strip_auth(response.request.url, url): # If we get redirected to a new host, we should strip out any # authentication headers. del headers['Authorization'] # .netrc might have more auth for us on our new host. new_auth = get_netrc_auth(url) if self.trust_env else None if new_auth is not None: prepared_request.prepare_auth(new_auth)
[ "def", "rebuild_auth", "(", "self", ",", "prepared_request", ",", "response", ")", ":", "headers", "=", "prepared_request", ".", "headers", "url", "=", "prepared_request", ".", "url", "if", "'Authorization'", "in", "headers", "and", "self", ".", "should_strip_auth", "(", "response", ".", "request", ".", "url", ",", "url", ")", ":", "# If we get redirected to a new host, we should strip out any", "# authentication headers.", "del", "headers", "[", "'Authorization'", "]", "# .netrc might have more auth for us on our new host.", "new_auth", "=", "get_netrc_auth", "(", "url", ")", "if", "self", ".", "trust_env", "else", "None", "if", "new_auth", "is", "not", "None", ":", "prepared_request", ".", "prepare_auth", "(", "new_auth", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/requests/sessions.py#L254-L270
kevinlin311tw/Caffe-DeepBinaryCode
9eaa7662be47d49f475ecbeea2bd51be105270d2
scripts/cpp_lint.py
python
_IncludeState.CanonicalizeAlphabeticalOrder
(self, header_path)
return header_path.replace('-inl.h', '.h').replace('-', '_').lower()
Returns a path canonicalized for alphabetical comparison. - replaces "-" with "_" so they both cmp the same. - removes '-inl' since we don't require them to be after the main header. - lowercase everything, just in case. Args: header_path: Path to be canonicalized. Returns: Canonicalized path.
Returns a path canonicalized for alphabetical comparison.
[ "Returns", "a", "path", "canonicalized", "for", "alphabetical", "comparison", "." ]
def CanonicalizeAlphabeticalOrder(self, header_path): """Returns a path canonicalized for alphabetical comparison. - replaces "-" with "_" so they both cmp the same. - removes '-inl' since we don't require them to be after the main header. - lowercase everything, just in case. Args: header_path: Path to be canonicalized. Returns: Canonicalized path. """ return header_path.replace('-inl.h', '.h').replace('-', '_').lower()
[ "def", "CanonicalizeAlphabeticalOrder", "(", "self", ",", "header_path", ")", ":", "return", "header_path", ".", "replace", "(", "'-inl.h'", ",", "'.h'", ")", ".", "replace", "(", "'-'", ",", "'_'", ")", ".", "lower", "(", ")" ]
https://github.com/kevinlin311tw/Caffe-DeepBinaryCode/blob/9eaa7662be47d49f475ecbeea2bd51be105270d2/scripts/cpp_lint.py#L597-L610
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/tarfile.py
python
TarFile._getmember
(self, name, tarinfo=None, normalize=False)
Find an archive member by name from bottom to top. If tarinfo is given, it is used as the starting point.
Find an archive member by name from bottom to top. If tarinfo is given, it is used as the starting point.
[ "Find", "an", "archive", "member", "by", "name", "from", "bottom", "to", "top", ".", "If", "tarinfo", "is", "given", "it", "is", "used", "as", "the", "starting", "point", "." ]
def _getmember(self, name, tarinfo=None, normalize=False): """Find an archive member by name from bottom to top. If tarinfo is given, it is used as the starting point. """ # Ensure that all members have been loaded. members = self.getmembers() # Limit the member search list up to tarinfo. if tarinfo is not None: members = members[:members.index(tarinfo)] if normalize: name = os.path.normpath(name) for member in reversed(members): if normalize: member_name = os.path.normpath(member.name) else: member_name = member.name if name == member_name: return member
[ "def", "_getmember", "(", "self", ",", "name", ",", "tarinfo", "=", "None", ",", "normalize", "=", "False", ")", ":", "# Ensure that all members have been loaded.", "members", "=", "self", ".", "getmembers", "(", ")", "# Limit the member search list up to tarinfo.", "if", "tarinfo", "is", "not", "None", ":", "members", "=", "members", "[", ":", "members", ".", "index", "(", "tarinfo", ")", "]", "if", "normalize", ":", "name", "=", "os", ".", "path", ".", "normpath", "(", "name", ")", "for", "member", "in", "reversed", "(", "members", ")", ":", "if", "normalize", ":", "member_name", "=", "os", ".", "path", ".", "normpath", "(", "member", ".", "name", ")", "else", ":", "member_name", "=", "member", ".", "name", "if", "name", "==", "member_name", ":", "return", "member" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/tarfile.py#L2369-L2390
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/python/client/timeline.py
python
_TensorTracker.name
(self)
return self._name
Name of this tensor.
Name of this tensor.
[ "Name", "of", "this", "tensor", "." ]
def name(self): """Name of this tensor.""" return self._name
[ "def", "name", "(", "self", ")", ":", "return", "self", ".", "_name" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/client/timeline.py#L295-L297
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/propgrid.py
python
ArrayStringProperty.OnButtonClick
(*args, **kwargs)
return _propgrid.ArrayStringProperty_OnButtonClick(*args, **kwargs)
OnButtonClick(self, PropertyGrid propgrid, Window primary, wxChar cbt) -> bool
OnButtonClick(self, PropertyGrid propgrid, Window primary, wxChar cbt) -> bool
[ "OnButtonClick", "(", "self", "PropertyGrid", "propgrid", "Window", "primary", "wxChar", "cbt", ")", "-", ">", "bool" ]
def OnButtonClick(*args, **kwargs): """OnButtonClick(self, PropertyGrid propgrid, Window primary, wxChar cbt) -> bool""" return _propgrid.ArrayStringProperty_OnButtonClick(*args, **kwargs)
[ "def", "OnButtonClick", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_propgrid", ".", "ArrayStringProperty_OnButtonClick", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/propgrid.py#L3143-L3145
apache/incubator-mxnet
f03fb23f1d103fec9541b5ae59ee06b1734a51d9
docs/tutorial_utils/vision/cnn_visualization/gradcam.py
python
get_image_grad
(net, image, class_id=None)
return _get_grad(net, image, class_id, image_grad=True)
Get the gradients of the image. Parameters: ---------- net: Block Network to use for visualization. image: NDArray Preprocessed image to use for visualization. class_id: int Category ID this image belongs to. If not provided, network's prediction will be used.
Get the gradients of the image.
[ "Get", "the", "gradients", "of", "the", "image", "." ]
def get_image_grad(net, image, class_id=None): """Get the gradients of the image. Parameters: ---------- net: Block Network to use for visualization. image: NDArray Preprocessed image to use for visualization. class_id: int Category ID this image belongs to. If not provided, network's prediction will be used.""" return _get_grad(net, image, class_id, image_grad=True)
[ "def", "get_image_grad", "(", "net", ",", "image", ",", "class_id", "=", "None", ")", ":", "return", "_get_grad", "(", "net", ",", "image", ",", "class_id", ",", "image_grad", "=", "True", ")" ]
https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/docs/tutorial_utils/vision/cnn_visualization/gradcam.py#L184-L196
miyosuda/TensorFlowAndroidMNIST
7b5a4603d2780a8a2834575706e9001977524007
jni-build/jni/include/tensorflow/contrib/distributions/python/ops/beta.py
python
Beta.b
(self)
return self._b
Shape parameter.
Shape parameter.
[ "Shape", "parameter", "." ]
def b(self): """Shape parameter.""" return self._b
[ "def", "b", "(", "self", ")", ":", "return", "self", ".", "_b" ]
https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/contrib/distributions/python/ops/beta.py#L159-L161
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_controls.py
python
ListItem.GetColumn
(*args, **kwargs)
return _controls_.ListItem_GetColumn(*args, **kwargs)
GetColumn(self) -> int
GetColumn(self) -> int
[ "GetColumn", "(", "self", ")", "-", ">", "int" ]
def GetColumn(*args, **kwargs): """GetColumn(self) -> int""" return _controls_.ListItem_GetColumn(*args, **kwargs)
[ "def", "GetColumn", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "ListItem_GetColumn", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_controls.py#L4220-L4222
bulletphysics/bullet3
f0f2a952e146f016096db6f85cf0c44ed75b0b9a
examples/pybullet/gym/pybullet_envs/minitaur/robots/safety/motor_action_validator.py
python
MotorActionValidator.__init__
( self, motor_id: typing.Any, position_bound: data_types.Bound, position_gain_bound: data_types.Bound, velocity_bound: data_types.Bound, velocity_gain_bound: data_types.Bound, torque_bound: data_types.Bound, timestamp_delta_bound: data_types.Bound, delta_position_bound: data_types.Bound, average_abs_delta_position_bound: data_types.Bound, state_buffer_size: int = _DEQUE_SIZE, )
Initializes the class. Args: motor_id: Unique ID for the motor. position_bound: The lower/upper bound of the motor angle. position_gain_bound: The lower/upper bound of the motor position gain for PD control. velocity_bound: The lower/upper bound of the motor speed. velocity_gain_bound: The lower/upper bound of the motor velocity gain for PD control. torque_bound: The lower/upper bound of the measured motor torque. timestamp_delta_bound: The range of timestamp difference between two consecutively received motor states. delta_position_bound: The bound between the current motor position and the command position, in position control mode. average_abs_delta_position_bound: The bound for average motor position and command poisition difference. state_buffer_size: The buffer size used to calculate the average.
Initializes the class.
[ "Initializes", "the", "class", "." ]
def __init__( self, motor_id: typing.Any, position_bound: data_types.Bound, position_gain_bound: data_types.Bound, velocity_bound: data_types.Bound, velocity_gain_bound: data_types.Bound, torque_bound: data_types.Bound, timestamp_delta_bound: data_types.Bound, delta_position_bound: data_types.Bound, average_abs_delta_position_bound: data_types.Bound, state_buffer_size: int = _DEQUE_SIZE, ): """Initializes the class. Args: motor_id: Unique ID for the motor. position_bound: The lower/upper bound of the motor angle. position_gain_bound: The lower/upper bound of the motor position gain for PD control. velocity_bound: The lower/upper bound of the motor speed. velocity_gain_bound: The lower/upper bound of the motor velocity gain for PD control. torque_bound: The lower/upper bound of the measured motor torque. timestamp_delta_bound: The range of timestamp difference between two consecutively received motor states. delta_position_bound: The bound between the current motor position and the command position, in position control mode. average_abs_delta_position_bound: The bound for average motor position and command poisition difference. state_buffer_size: The buffer size used to calculate the average. """ assert state_buffer_size > 1 self._last_motor_state = None self._motor_id = motor_id self._position_bound = position_bound self._position_gain_bound = position_gain_bound self._velocity_bound = velocity_bound self._velocity_gain_bound = velocity_gain_bound self._torque_bound = torque_bound self._timestamp_delta_bound = timestamp_delta_bound self._delta_position_bound = delta_position_bound self._average_abs_delta_position_bound = average_abs_delta_position_bound self._abs_delta_position_filter = moving_window_filter.MovingWindowFilter( state_buffer_size)
[ "def", "__init__", "(", "self", ",", "motor_id", ":", "typing", ".", "Any", ",", "position_bound", ":", "data_types", ".", "Bound", ",", "position_gain_bound", ":", "data_types", ".", "Bound", ",", "velocity_bound", ":", "data_types", ".", "Bound", ",", "velocity_gain_bound", ":", "data_types", ".", "Bound", ",", "torque_bound", ":", "data_types", ".", "Bound", ",", "timestamp_delta_bound", ":", "data_types", ".", "Bound", ",", "delta_position_bound", ":", "data_types", ".", "Bound", ",", "average_abs_delta_position_bound", ":", "data_types", ".", "Bound", ",", "state_buffer_size", ":", "int", "=", "_DEQUE_SIZE", ",", ")", ":", "assert", "state_buffer_size", ">", "1", "self", ".", "_last_motor_state", "=", "None", "self", ".", "_motor_id", "=", "motor_id", "self", ".", "_position_bound", "=", "position_bound", "self", ".", "_position_gain_bound", "=", "position_gain_bound", "self", ".", "_velocity_bound", "=", "velocity_bound", "self", ".", "_velocity_gain_bound", "=", "velocity_gain_bound", "self", ".", "_torque_bound", "=", "torque_bound", "self", ".", "_timestamp_delta_bound", "=", "timestamp_delta_bound", "self", ".", "_delta_position_bound", "=", "delta_position_bound", "self", ".", "_average_abs_delta_position_bound", "=", "average_abs_delta_position_bound", "self", ".", "_abs_delta_position_filter", "=", "moving_window_filter", ".", "MovingWindowFilter", "(", "state_buffer_size", ")" ]
https://github.com/bulletphysics/bullet3/blob/f0f2a952e146f016096db6f85cf0c44ed75b0b9a/examples/pybullet/gym/pybullet_envs/minitaur/robots/safety/motor_action_validator.py#L22-L67
glotzerlab/hoomd-blue
f7f97abfa3fcc2522fa8d458d65d0aeca7ba781a
hoomd/hpmc/update.py
python
BoxMC.counter
(self)
Trial move counters. The counter object has the following attributes: * ``volume``: `tuple` [`int`, `int`] - Number of accepted and rejected volume and length moves. * ``shear``: `tuple` [`int`, `int`] - Number of accepted and rejected shear moves. * ``aspect``: `tuple` [`int`, `int`] - Number of accepted and rejected aspect moves. Note: The counts are reset to 0 at the start of each call to `hoomd.Simulation.run`. Before the first call to `Simulation.run`, `counter` is `None`.
Trial move counters.
[ "Trial", "move", "counters", "." ]
def counter(self): """Trial move counters. The counter object has the following attributes: * ``volume``: `tuple` [`int`, `int`] - Number of accepted and rejected volume and length moves. * ``shear``: `tuple` [`int`, `int`] - Number of accepted and rejected shear moves. * ``aspect``: `tuple` [`int`, `int`] - Number of accepted and rejected aspect moves. Note: The counts are reset to 0 at the start of each call to `hoomd.Simulation.run`. Before the first call to `Simulation.run`, `counter` is `None`. """ if not self._attached: return None else: return self._cpp_obj.getCounters(1)
[ "def", "counter", "(", "self", ")", ":", "if", "not", "self", ".", "_attached", ":", "return", "None", "else", ":", "return", "self", ".", "_cpp_obj", ".", "getCounters", "(", "1", ")" ]
https://github.com/glotzerlab/hoomd-blue/blob/f7f97abfa3fcc2522fa8d458d65d0aeca7ba781a/hoomd/hpmc/update.py#L134-L154
mongodb/mongo
d8ff665343ad29cf286ee2cf4a1960d29371937b
buildscripts/resmokelib/core/programs.py
python
genny_program
(logger, job_num, test_id=None, executable=None, process_kwargs=None, **kwargs)
return generic_program(logger, args, job_num, test_id=test_id, process_kwargs=process_kwargs, **kwargs)
Return a Process instance that starts a genny executable with arguments constructed from 'kwargs'.
Return a Process instance that starts a genny executable with arguments constructed from 'kwargs'.
[ "Return", "a", "Process", "instance", "that", "starts", "a", "genny", "executable", "with", "arguments", "constructed", "from", "kwargs", "." ]
def genny_program(logger, job_num, test_id=None, executable=None, process_kwargs=None, **kwargs): """Return a Process instance that starts a genny executable with arguments constructed from 'kwargs'.""" executable = utils.default_if_none(executable, config.DEFAULT_GENNY_EXECUTABLE) args = [executable] return generic_program(logger, args, job_num, test_id=test_id, process_kwargs=process_kwargs, **kwargs)
[ "def", "genny_program", "(", "logger", ",", "job_num", ",", "test_id", "=", "None", ",", "executable", "=", "None", ",", "process_kwargs", "=", "None", ",", "*", "*", "kwargs", ")", ":", "executable", "=", "utils", ".", "default_if_none", "(", "executable", ",", "config", ".", "DEFAULT_GENNY_EXECUTABLE", ")", "args", "=", "[", "executable", "]", "return", "generic_program", "(", "logger", ",", "args", ",", "job_num", ",", "test_id", "=", "test_id", ",", "process_kwargs", "=", "process_kwargs", ",", "*", "*", "kwargs", ")" ]
https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/resmokelib/core/programs.py#L350-L355
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/datetime.py
python
time._tzstr
(self)
return _format_offset(off)
Return formatted timezone offset (+xx:xx) or an empty string.
Return formatted timezone offset (+xx:xx) or an empty string.
[ "Return", "formatted", "timezone", "offset", "(", "+", "xx", ":", "xx", ")", "or", "an", "empty", "string", "." ]
def _tzstr(self): """Return formatted timezone offset (+xx:xx) or an empty string.""" off = self.utcoffset() return _format_offset(off)
[ "def", "_tzstr", "(", "self", ")", ":", "off", "=", "self", ".", "utcoffset", "(", ")", "return", "_format_offset", "(", "off", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/datetime.py#L1341-L1344
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py2/scipy/interpolate/fitpack2.py
python
BivariateSpline._from_tck
(cls, tck)
return self
Construct a spline object from given tck and degree
Construct a spline object from given tck and degree
[ "Construct", "a", "spline", "object", "from", "given", "tck", "and", "degree" ]
def _from_tck(cls, tck): """Construct a spline object from given tck and degree""" self = cls.__new__(cls) if len(tck) != 5: raise ValueError("tck should be a 5 element tuple of tx," " ty, c, kx, ky") self.tck = tck[:3] self.degrees = tck[3:] return self
[ "def", "_from_tck", "(", "cls", ",", "tck", ")", ":", "self", "=", "cls", ".", "__new__", "(", "cls", ")", "if", "len", "(", "tck", ")", "!=", "5", ":", "raise", "ValueError", "(", "\"tck should be a 5 element tuple of tx,\"", "\" ty, c, kx, ky\"", ")", "self", ".", "tck", "=", "tck", "[", ":", "3", "]", "self", ".", "degrees", "=", "tck", "[", "3", ":", "]", "return", "self" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/interpolate/fitpack2.py#L945-L953
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
deps/src/libxml2-2.9.1/python/libxml2.py
python
uCSIsBuhid
(code)
return ret
Check whether the character is part of Buhid UCS Block
Check whether the character is part of Buhid UCS Block
[ "Check", "whether", "the", "character", "is", "part", "of", "Buhid", "UCS", "Block" ]
def uCSIsBuhid(code): """Check whether the character is part of Buhid UCS Block """ ret = libxml2mod.xmlUCSIsBuhid(code) return ret
[ "def", "uCSIsBuhid", "(", "code", ")", ":", "ret", "=", "libxml2mod", ".", "xmlUCSIsBuhid", "(", "code", ")", "return", "ret" ]
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/deps/src/libxml2-2.9.1/python/libxml2.py#L2174-L2177
hughperkins/tf-coriander
970d3df6c11400ad68405f22b0c42a52374e94ca
tensorflow/python/debug/debug_data.py
python
has_inf_or_nan
(datum, tensor)
A predicate for whether a tensor consists of any bad numerical values. This predicate is common enough to merit definition in this module. Bad numerical values include nans and infs. The signature of this function follows the requiremnet of DebugDumpDir's find() method. Args: datum: (DebugTensorDatum) Datum metadata. tensor: (numpy.ndarray or None) Value of the tensor. None represents an uninitialized tensor. Returns: (bool) True if and only if tensor consists of any nan or inf values.
A predicate for whether a tensor consists of any bad numerical values.
[ "A", "predicate", "for", "whether", "a", "tensor", "consists", "of", "any", "bad", "numerical", "values", "." ]
def has_inf_or_nan(datum, tensor): """A predicate for whether a tensor consists of any bad numerical values. This predicate is common enough to merit definition in this module. Bad numerical values include nans and infs. The signature of this function follows the requiremnet of DebugDumpDir's find() method. Args: datum: (DebugTensorDatum) Datum metadata. tensor: (numpy.ndarray or None) Value of the tensor. None represents an uninitialized tensor. Returns: (bool) True if and only if tensor consists of any nan or inf values. """ _ = datum # Datum metadata is unused in this predicte. if tensor is None: # Uninitialized tensor doesn't have bad numerical values. return False else: return np.any(np.isnan(tensor)) or np.any(np.isinf(tensor))
[ "def", "has_inf_or_nan", "(", "datum", ",", "tensor", ")", ":", "_", "=", "datum", "# Datum metadata is unused in this predicte.", "if", "tensor", "is", "None", ":", "# Uninitialized tensor doesn't have bad numerical values.", "return", "False", "else", ":", "return", "np", ".", "any", "(", "np", ".", "isnan", "(", "tensor", ")", ")", "or", "np", ".", "any", "(", "np", ".", "isinf", "(", "tensor", ")", ")" ]
https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/debug/debug_data.py#L184-L206
hughperkins/tf-coriander
970d3df6c11400ad68405f22b0c42a52374e94ca
tensorflow/python/ops/random_ops.py
python
random_uniform
(shape, minval=0, maxval=None, dtype=dtypes.float32, seed=None, name=None)
Outputs random values from a uniform distribution. The generated values follow a uniform distribution in the range `[minval, maxval)`. The lower bound `minval` is included in the range, while the upper bound `maxval` is excluded. For floats, the default range is `[0, 1)`. For ints, at least `maxval` must be specified explicitly. In the integer case, the random integers are slightly biased unless `maxval - minval` is an exact power of two. The bias is small for values of `maxval - minval` significantly smaller than the range of the output (either `2**32` or `2**64`). Args: shape: A 1-D integer Tensor or Python array. The shape of the output tensor. minval: A 0-D Tensor or Python value of type `dtype`. The lower bound on the range of random values to generate. Defaults to 0. maxval: A 0-D Tensor or Python value of type `dtype`. The upper bound on the range of random values to generate. Defaults to 1 if `dtype` is floating point. dtype: The type of the output: `float32`, `float64`, `int32`, or `int64`. seed: A Python integer. Used to create a random seed for the distribution. See [`set_random_seed`](../../api_docs/python/constant_op.md#set_random_seed) for behavior. name: A name for the operation (optional). Returns: A tensor of the specified shape filled with random uniform values. Raises: ValueError: If `dtype` is integral and `maxval` is not specified.
Outputs random values from a uniform distribution.
[ "Outputs", "random", "values", "from", "a", "uniform", "distribution", "." ]
def random_uniform(shape, minval=0, maxval=None, dtype=dtypes.float32, seed=None, name=None): """Outputs random values from a uniform distribution. The generated values follow a uniform distribution in the range `[minval, maxval)`. The lower bound `minval` is included in the range, while the upper bound `maxval` is excluded. For floats, the default range is `[0, 1)`. For ints, at least `maxval` must be specified explicitly. In the integer case, the random integers are slightly biased unless `maxval - minval` is an exact power of two. The bias is small for values of `maxval - minval` significantly smaller than the range of the output (either `2**32` or `2**64`). Args: shape: A 1-D integer Tensor or Python array. The shape of the output tensor. minval: A 0-D Tensor or Python value of type `dtype`. The lower bound on the range of random values to generate. Defaults to 0. maxval: A 0-D Tensor or Python value of type `dtype`. The upper bound on the range of random values to generate. Defaults to 1 if `dtype` is floating point. dtype: The type of the output: `float32`, `float64`, `int32`, or `int64`. seed: A Python integer. Used to create a random seed for the distribution. See [`set_random_seed`](../../api_docs/python/constant_op.md#set_random_seed) for behavior. name: A name for the operation (optional). Returns: A tensor of the specified shape filled with random uniform values. Raises: ValueError: If `dtype` is integral and `maxval` is not specified. """ dtype = dtypes.as_dtype(dtype) if maxval is None: if dtype.is_integer: raise ValueError("Must specify maxval for integer dtype %r" % dtype) maxval = 1 with ops.name_scope(name, "random_uniform", [shape, minval, maxval]) as name: shape = _ShapeTensor(shape) minval = ops.convert_to_tensor(minval, dtype=dtype, name="min") maxval = ops.convert_to_tensor(maxval, dtype=dtype, name="max") seed1, seed2 = random_seed.get_seed(seed) if dtype.is_integer: return gen_random_ops._random_uniform_int(shape, minval, maxval, seed=seed1, seed2=seed2, name=name) else: rnd = gen_random_ops._random_uniform(shape, dtype, seed=seed1, seed2=seed2) return math_ops.add(rnd * (maxval - minval), minval, name=name)
[ "def", "random_uniform", "(", "shape", ",", "minval", "=", "0", ",", "maxval", "=", "None", ",", "dtype", "=", "dtypes", ".", "float32", ",", "seed", "=", "None", ",", "name", "=", "None", ")", ":", "dtype", "=", "dtypes", ".", "as_dtype", "(", "dtype", ")", "if", "maxval", "is", "None", ":", "if", "dtype", ".", "is_integer", ":", "raise", "ValueError", "(", "\"Must specify maxval for integer dtype %r\"", "%", "dtype", ")", "maxval", "=", "1", "with", "ops", ".", "name_scope", "(", "name", ",", "\"random_uniform\"", ",", "[", "shape", ",", "minval", ",", "maxval", "]", ")", "as", "name", ":", "shape", "=", "_ShapeTensor", "(", "shape", ")", "minval", "=", "ops", ".", "convert_to_tensor", "(", "minval", ",", "dtype", "=", "dtype", ",", "name", "=", "\"min\"", ")", "maxval", "=", "ops", ".", "convert_to_tensor", "(", "maxval", ",", "dtype", "=", "dtype", ",", "name", "=", "\"max\"", ")", "seed1", ",", "seed2", "=", "random_seed", ".", "get_seed", "(", "seed", ")", "if", "dtype", ".", "is_integer", ":", "return", "gen_random_ops", ".", "_random_uniform_int", "(", "shape", ",", "minval", ",", "maxval", ",", "seed", "=", "seed1", ",", "seed2", "=", "seed2", ",", "name", "=", "name", ")", "else", ":", "rnd", "=", "gen_random_ops", ".", "_random_uniform", "(", "shape", ",", "dtype", ",", "seed", "=", "seed1", ",", "seed2", "=", "seed2", ")", "return", "math_ops", ".", "add", "(", "rnd", "*", "(", "maxval", "-", "minval", ")", ",", "minval", ",", "name", "=", "name", ")" ]
https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/ops/random_ops.py#L185-L247
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/ros/roslib/src/roslib/packages.py
python
_update_rospack_cache
(env=None)
return _read_rospack_cache(cache, ros_root, ros_package_path)
Internal routine to update global package directory cache @return: True if cache is valid @rtype: bool
Internal routine to update global package directory cache
[ "Internal", "routine", "to", "update", "global", "package", "directory", "cache" ]
def _update_rospack_cache(env=None): """ Internal routine to update global package directory cache @return: True if cache is valid @rtype: bool """ if env is None: env = os.environ cache = _pkg_dir_cache if cache: return True ros_root = env[ROS_ROOT] ros_package_path = env.get(ROS_PACKAGE_PATH, '') return _read_rospack_cache(cache, ros_root, ros_package_path)
[ "def", "_update_rospack_cache", "(", "env", "=", "None", ")", ":", "if", "env", "is", "None", ":", "env", "=", "os", ".", "environ", "cache", "=", "_pkg_dir_cache", "if", "cache", ":", "return", "True", "ros_root", "=", "env", "[", "ROS_ROOT", "]", "ros_package_path", "=", "env", ".", "get", "(", "ROS_PACKAGE_PATH", ",", "''", ")", "return", "_read_rospack_cache", "(", "cache", ",", "ros_root", ",", "ros_package_path", ")" ]
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/ros/roslib/src/roslib/packages.py#L274-L288
andr3wmac/Torque6
db6cd08f18f4917e0c6557b2766fb40d8e2bee39
lib/freetype/android/freetype-2.4.12/src/tools/docmaker/tohtml.py
python
HtmlFormatter.make_html_words
( self, words )
return line
convert a series of simple words into some HTML text
convert a series of simple words into some HTML text
[ "convert", "a", "series", "of", "simple", "words", "into", "some", "HTML", "text" ]
def make_html_words( self, words ): """ convert a series of simple words into some HTML text """ line = "" if words: line = html_quote( words[0] ) for w in words[1:]: line = line + " " + html_quote( w ) return line
[ "def", "make_html_words", "(", "self", ",", "words", ")", ":", "line", "=", "\"\"", "if", "words", ":", "line", "=", "html_quote", "(", "words", "[", "0", "]", ")", "for", "w", "in", "words", "[", "1", ":", "]", ":", "line", "=", "line", "+", "\" \"", "+", "html_quote", "(", "w", ")", "return", "line" ]
https://github.com/andr3wmac/Torque6/blob/db6cd08f18f4917e0c6557b2766fb40d8e2bee39/lib/freetype/android/freetype-2.4.12/src/tools/docmaker/tohtml.py#L245-L253
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/third_party/lib_x86_64/python2.7/dist-packages/geodesy/utm.py
python
UTMPoint.is2D
(self)
return self.altitude != self.altitude
:returns: True if altitude is not defined.
:returns: True if altitude is not defined.
[ ":", "returns", ":", "True", "if", "altitude", "is", "not", "defined", "." ]
def is2D(self): """:returns: True if altitude is not defined.""" return self.altitude != self.altitude
[ "def", "is2D", "(", "self", ")", ":", "return", "self", ".", "altitude", "!=", "self", ".", "altitude" ]
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/geodesy/utm.py#L98-L100
TGAC/KAT
e8870331de2b4bb0a1b3b91c6afb8fb9d59e9216
scripts/kat/spectra.py
python
Spectra.analyse
(self, min_elements=1, verbose=False)
Analyse the histogram for peaks :param verbose: Prints additional information about progress to stdout
Analyse the histogram for peaks :param verbose: Prints additional information about progress to stdout
[ "Analyse", "the", "histogram", "for", "peaks", ":", "param", "verbose", ":", "Prints", "additional", "information", "about", "progress", "to", "stdout" ]
def analyse(self, min_elements=1, verbose=False): """ Analyse the histogram for peaks :param verbose: Prints additional information about progress to stdout """ if verbose: print() print("Creating initial peaks ... ", end="", flush=True) self._createInitialPeaks() if self.peaks: if verbose: print("done.", len(self.peaks), "peaks initially created") print() self.printPeaks() print() print("Locally optimising each peak ... ", end="") for p_i, p in enumerate(self.peaks): try: p.optimise(self.histogram) except Exception as inst: print("Problem locally optimising peak", p_i+1, file=sys.stderr) print(inst, file=sys.stderr) # Just carry on from here... maybe the problem will fix itself...? # For debugging if False: plt.plot(self.histogram, color='black') for p_i, p in enumerate(self.peaks): plt.plot(p.Ty) plt.xlim(0, 70) plt.ylim(0, 200000000) plt.show() # Remove any peaks that contain little to no content self.peaks = list(filter(lambda p: p.elements() >= min_elements, self.peaks)) if verbose: print("done.") print() self.printPeaks() print() print("Fitting cumulative distribution to histogram by adjusting peaks ... ", end="", flush=True) try: self.optimise(fmin=self.fmin if type(self) == KmerSpectra else 0) # Remove any peaks that contain little to no content self.peaks = list(filter(lambda p: p.elements() >= min_elements, self.peaks)) if verbose: print("done.") print() self.printPeaks() except Exception as inst: print( "WARNING: problem optimising peaks. It is likely that the spectra is too complex to analyse properly. Output for this spectra may not be valid.", file=sys.stderr) print(inst, file=sys.stderr) pass elif verbose: print("done. No peaks created")
[ "def", "analyse", "(", "self", ",", "min_elements", "=", "1", ",", "verbose", "=", "False", ")", ":", "if", "verbose", ":", "print", "(", ")", "print", "(", "\"Creating initial peaks ... \"", ",", "end", "=", "\"\"", ",", "flush", "=", "True", ")", "self", ".", "_createInitialPeaks", "(", ")", "if", "self", ".", "peaks", ":", "if", "verbose", ":", "print", "(", "\"done.\"", ",", "len", "(", "self", ".", "peaks", ")", ",", "\"peaks initially created\"", ")", "print", "(", ")", "self", ".", "printPeaks", "(", ")", "print", "(", ")", "print", "(", "\"Locally optimising each peak ... \"", ",", "end", "=", "\"\"", ")", "for", "p_i", ",", "p", "in", "enumerate", "(", "self", ".", "peaks", ")", ":", "try", ":", "p", ".", "optimise", "(", "self", ".", "histogram", ")", "except", "Exception", "as", "inst", ":", "print", "(", "\"Problem locally optimising peak\"", ",", "p_i", "+", "1", ",", "file", "=", "sys", ".", "stderr", ")", "print", "(", "inst", ",", "file", "=", "sys", ".", "stderr", ")", "# Just carry on from here... maybe the problem will fix itself...?", "# For debugging", "if", "False", ":", "plt", ".", "plot", "(", "self", ".", "histogram", ",", "color", "=", "'black'", ")", "for", "p_i", ",", "p", "in", "enumerate", "(", "self", ".", "peaks", ")", ":", "plt", ".", "plot", "(", "p", ".", "Ty", ")", "plt", ".", "xlim", "(", "0", ",", "70", ")", "plt", ".", "ylim", "(", "0", ",", "200000000", ")", "plt", ".", "show", "(", ")", "# Remove any peaks that contain little to no content", "self", ".", "peaks", "=", "list", "(", "filter", "(", "lambda", "p", ":", "p", ".", "elements", "(", ")", ">=", "min_elements", ",", "self", ".", "peaks", ")", ")", "if", "verbose", ":", "print", "(", "\"done.\"", ")", "print", "(", ")", "self", ".", "printPeaks", "(", ")", "print", "(", ")", "print", "(", "\"Fitting cumulative distribution to histogram by adjusting peaks ... \"", ",", "end", "=", "\"\"", ",", "flush", "=", "True", ")", "try", ":", "self", ".", "optimise", "(", "fmin", "=", "self", ".", "fmin", "if", "type", "(", "self", ")", "==", "KmerSpectra", "else", "0", ")", "# Remove any peaks that contain little to no content", "self", ".", "peaks", "=", "list", "(", "filter", "(", "lambda", "p", ":", "p", ".", "elements", "(", ")", ">=", "min_elements", ",", "self", ".", "peaks", ")", ")", "if", "verbose", ":", "print", "(", "\"done.\"", ")", "print", "(", ")", "self", ".", "printPeaks", "(", ")", "except", "Exception", "as", "inst", ":", "print", "(", "\"WARNING: problem optimising peaks. It is likely that the spectra is too complex to analyse properly. Output for this spectra may not be valid.\"", ",", "file", "=", "sys", ".", "stderr", ")", "print", "(", "inst", ",", "file", "=", "sys", ".", "stderr", ")", "pass", "elif", "verbose", ":", "print", "(", "\"done. No peaks created\"", ")" ]
https://github.com/TGAC/KAT/blob/e8870331de2b4bb0a1b3b91c6afb8fb9d59e9216/scripts/kat/spectra.py#L140-L201
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/wsgiref/handlers.py
python
BaseHandler.write
(self, data)
write()' callable as specified by PEP 333
write()' callable as specified by PEP 333
[ "write", "()", "callable", "as", "specified", "by", "PEP", "333" ]
def write(self, data): """'write()' callable as specified by PEP 333""" assert type(data) is StringType,"write() argument must be string" if not self.status: raise AssertionError("write() before start_response()") elif not self.headers_sent: # Before the first output, send the stored headers self.bytes_sent = len(data) # make sure we know content-length self.send_headers() else: self.bytes_sent += len(data) # XXX check Content-Length and truncate if too many bytes written? self._write(data) self._flush()
[ "def", "write", "(", "self", ",", "data", ")", ":", "assert", "type", "(", "data", ")", "is", "StringType", ",", "\"write() argument must be string\"", "if", "not", "self", ".", "status", ":", "raise", "AssertionError", "(", "\"write() before start_response()\"", ")", "elif", "not", "self", ".", "headers_sent", ":", "# Before the first output, send the stored headers", "self", ".", "bytes_sent", "=", "len", "(", "data", ")", "# make sure we know content-length", "self", ".", "send_headers", "(", ")", "else", ":", "self", ".", "bytes_sent", "+=", "len", "(", "data", ")", "# XXX check Content-Length and truncate if too many bytes written?", "self", ".", "_write", "(", "data", ")", "self", ".", "_flush", "(", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/wsgiref/handlers.py#L201-L218
s5z/zsim
fb4d6e0475a25cffd23f0687ede2d43d96b4a99f
misc/cpplint.py
python
ResetNolintSuppressions
()
Resets the set of NOLINT suppressions to empty.
Resets the set of NOLINT suppressions to empty.
[ "Resets", "the", "set", "of", "NOLINT", "suppressions", "to", "empty", "." ]
def ResetNolintSuppressions(): "Resets the set of NOLINT suppressions to empty." _error_suppressions.clear()
[ "def", "ResetNolintSuppressions", "(", ")", ":", "_error_suppressions", ".", "clear", "(", ")" ]
https://github.com/s5z/zsim/blob/fb4d6e0475a25cffd23f0687ede2d43d96b4a99f/misc/cpplint.py#L390-L392
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/html.py
python
HtmlTag.HasParam
(*args, **kwargs)
return _html.HtmlTag_HasParam(*args, **kwargs)
HasParam(self, String par) -> bool
HasParam(self, String par) -> bool
[ "HasParam", "(", "self", "String", "par", ")", "-", ">", "bool" ]
def HasParam(*args, **kwargs): """HasParam(self, String par) -> bool""" return _html.HtmlTag_HasParam(*args, **kwargs)
[ "def", "HasParam", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_html", ".", "HtmlTag_HasParam", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/html.py#L145-L147
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/idlelib/outwin.py
python
OutputWindow.write
(self, s, tags=(), mark="insert")
return len(s)
Write text to text widget. The text is inserted at the given index with the provided tags. The text widget is then scrolled to make it visible and updated to display it, giving the effect of seeing each line as it is added. Args: s: Text to insert into text widget. tags: Tuple of tag strings to apply on the insert. mark: Index for the insert. Return: Length of text inserted.
Write text to text widget.
[ "Write", "text", "to", "text", "widget", "." ]
def write(self, s, tags=(), mark="insert"): """Write text to text widget. The text is inserted at the given index with the provided tags. The text widget is then scrolled to make it visible and updated to display it, giving the effect of seeing each line as it is added. Args: s: Text to insert into text widget. tags: Tuple of tag strings to apply on the insert. mark: Index for the insert. Return: Length of text inserted. """ if isinstance(s, bytes): s = s.decode(iomenu.encoding, "replace") self.text.insert(mark, s, tags) self.text.see(mark) self.text.update() return len(s)
[ "def", "write", "(", "self", ",", "s", ",", "tags", "=", "(", ")", ",", "mark", "=", "\"insert\"", ")", ":", "if", "isinstance", "(", "s", ",", "bytes", ")", ":", "s", "=", "s", ".", "decode", "(", "iomenu", ".", "encoding", ",", "\"replace\"", ")", "self", ".", "text", ".", "insert", "(", "mark", ",", "s", ",", "tags", ")", "self", ".", "text", ".", "see", "(", "mark", ")", "self", ".", "text", ".", "update", "(", ")", "return", "len", "(", "s", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/idlelib/outwin.py#L97-L118
gimli-org/gimli
17aa2160de9b15ababd9ef99e89b1bc3277bbb23
pygimli/physics/SIP/sipspectrum.py
python
SIPSpectrum.unifyData
(self, onlydown=False)
Unify data (only one value per frequency) by mean or selection.
Unify data (only one value per frequency) by mean or selection.
[ "Unify", "data", "(", "only", "one", "value", "per", "frequency", ")", "by", "mean", "or", "selection", "." ]
def unifyData(self, onlydown=False): """Unify data (only one value per frequency) by mean or selection.""" if self.f is None: return fu = np.unique(self.f) if len(fu) < len(self.f) or onlydown: if onlydown: nonzero = np.nonzero(np.diff(self.f) > 0)[0] if len(nonzero) > 0: wende = min(nonzero) if wende > 0: self.f = self.f[wende::-1] self.amp = self.amp[wende::-1] self.phi = self.phi[wende::-1] else: amp = np.zeros(fu.shape) phi = np.zeros(fu.shape) for i in range(len(fu)): ind = np.nonzero(self.f == fu[i])[0] amp[i] = np.mean(self.amp[ind]) phi[i] = np.mean(self.phi[ind]) self.f = fu self.amp = amp self.phi = phi
[ "def", "unifyData", "(", "self", ",", "onlydown", "=", "False", ")", ":", "if", "self", ".", "f", "is", "None", ":", "return", "fu", "=", "np", ".", "unique", "(", "self", ".", "f", ")", "if", "len", "(", "fu", ")", "<", "len", "(", "self", ".", "f", ")", "or", "onlydown", ":", "if", "onlydown", ":", "nonzero", "=", "np", ".", "nonzero", "(", "np", ".", "diff", "(", "self", ".", "f", ")", ">", "0", ")", "[", "0", "]", "if", "len", "(", "nonzero", ")", ">", "0", ":", "wende", "=", "min", "(", "nonzero", ")", "if", "wende", ">", "0", ":", "self", ".", "f", "=", "self", ".", "f", "[", "wende", ":", ":", "-", "1", "]", "self", ".", "amp", "=", "self", ".", "amp", "[", "wende", ":", ":", "-", "1", "]", "self", ".", "phi", "=", "self", ".", "phi", "[", "wende", ":", ":", "-", "1", "]", "else", ":", "amp", "=", "np", ".", "zeros", "(", "fu", ".", "shape", ")", "phi", "=", "np", ".", "zeros", "(", "fu", ".", "shape", ")", "for", "i", "in", "range", "(", "len", "(", "fu", ")", ")", ":", "ind", "=", "np", ".", "nonzero", "(", "self", ".", "f", "==", "fu", "[", "i", "]", ")", "[", "0", "]", "amp", "[", "i", "]", "=", "np", ".", "mean", "(", "self", ".", "amp", "[", "ind", "]", ")", "phi", "[", "i", "]", "=", "np", ".", "mean", "(", "self", ".", "phi", "[", "ind", "]", ")", "self", ".", "f", "=", "fu", "self", ".", "amp", "=", "amp", "self", ".", "phi", "=", "phi" ]
https://github.com/gimli-org/gimli/blob/17aa2160de9b15ababd9ef99e89b1bc3277bbb23/pygimli/physics/SIP/sipspectrum.py#L337-L361
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
gpu/command_buffer/build_gles2_cmd_buffer.py
python
PUTnHandler.WriteGLES2ImplementationUnitTest
(self, func, file)
Writes the GLES2 Implemention unit test.
Writes the GLES2 Implemention unit test.
[ "Writes", "the", "GLES2", "Implemention", "unit", "test", "." ]
def WriteGLES2ImplementationUnitTest(self, func, file): """Writes the GLES2 Implemention unit test.""" code = """ TEST_F(GLES2ImplementationTest, %(name)s) { %(type)s data[%(count_param)d][%(count)d] = {{0}}; struct Cmds { cmds::%(name)sImmediate cmd; %(type)s data[%(count_param)d][%(count)d]; }; Cmds expected; for (int ii = 0; ii < %(count_param)d; ++ii) { for (int jj = 0; jj < %(count)d; ++jj) { data[ii][jj] = static_cast<%(type)s>(ii * %(count)d + jj); } } expected.cmd.Init(%(cmd_args)s, &data[0][0]); gl_->%(name)s(%(args)s, &data[0][0]); EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected))); } """ cmd_arg_strings = [] for count, arg in enumerate(func.GetCmdArgs()[0:-2]): cmd_arg_strings.append(arg.GetValidClientSideCmdArg(func, count, 0)) gl_arg_strings = [] count_param = 0 for count, arg in enumerate(func.GetOriginalArgs()[0:-1]): gl_arg_strings.append(arg.GetValidClientSideArg(func, count, 0)) if arg.name == "count": count_param = int(arg.GetValidClientSideArg(func, count, 0)) file.Write(code % { 'name': func.name, 'type': func.GetInfo('data_type'), 'count': func.GetInfo('count'), 'args': ", ".join(gl_arg_strings), 'cmd_args': ", ".join(cmd_arg_strings), 'count_param': count_param, })
[ "def", "WriteGLES2ImplementationUnitTest", "(", "self", ",", "func", ",", "file", ")", ":", "code", "=", "\"\"\"\nTEST_F(GLES2ImplementationTest, %(name)s) {\n %(type)s data[%(count_param)d][%(count)d] = {{0}};\n struct Cmds {\n cmds::%(name)sImmediate cmd;\n %(type)s data[%(count_param)d][%(count)d];\n };\n\n Cmds expected;\n for (int ii = 0; ii < %(count_param)d; ++ii) {\n for (int jj = 0; jj < %(count)d; ++jj) {\n data[ii][jj] = static_cast<%(type)s>(ii * %(count)d + jj);\n }\n }\n expected.cmd.Init(%(cmd_args)s, &data[0][0]);\n gl_->%(name)s(%(args)s, &data[0][0]);\n EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));\n}\n\"\"\"", "cmd_arg_strings", "=", "[", "]", "for", "count", ",", "arg", "in", "enumerate", "(", "func", ".", "GetCmdArgs", "(", ")", "[", "0", ":", "-", "2", "]", ")", ":", "cmd_arg_strings", ".", "append", "(", "arg", ".", "GetValidClientSideCmdArg", "(", "func", ",", "count", ",", "0", ")", ")", "gl_arg_strings", "=", "[", "]", "count_param", "=", "0", "for", "count", ",", "arg", "in", "enumerate", "(", "func", ".", "GetOriginalArgs", "(", ")", "[", "0", ":", "-", "1", "]", ")", ":", "gl_arg_strings", ".", "append", "(", "arg", ".", "GetValidClientSideArg", "(", "func", ",", "count", ",", "0", ")", ")", "if", "arg", ".", "name", "==", "\"count\"", ":", "count_param", "=", "int", "(", "arg", ".", "GetValidClientSideArg", "(", "func", ",", "count", ",", "0", ")", ")", "file", ".", "Write", "(", "code", "%", "{", "'name'", ":", "func", ".", "name", ",", "'type'", ":", "func", ".", "GetInfo", "(", "'data_type'", ")", ",", "'count'", ":", "func", ".", "GetInfo", "(", "'count'", ")", ",", "'args'", ":", "\", \"", ".", "join", "(", "gl_arg_strings", ")", ",", "'cmd_args'", ":", "\", \"", ".", "join", "(", "cmd_arg_strings", ")", ",", "'count_param'", ":", "count_param", ",", "}", ")" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/gpu/command_buffer/build_gles2_cmd_buffer.py#L5088-L5125
ptrkrysik/gr-gsm
2de47e28ce1fb9a518337bfc0add36c8e3cff5eb
python/qa_gsm_bcch_ccch_sdcch4_demapper.py
python
qa_bcch_ccch_sdcch4_demapper.test_uplink
(self)
BCCH_CCCH_SDCCH4 demapper uplink test
BCCH_CCCH_SDCCH4 demapper uplink test
[ "BCCH_CCCH_SDCCH4", "demapper", "uplink", "test" ]
def test_uplink (self): """ BCCH_CCCH_SDCCH4 demapper uplink test """ src = grgsm.burst_source(test_data.frames, test_data.timeslots, test_data.bursts) src.set_arfcn(0x2240); #uplink flag is 40 demapper = grgsm.gsm_bcch_ccch_sdcch4_demapper(timeslot_nr=0) dst = grgsm.burst_sink() self.tb.msg_connect(src, "out", demapper, "bursts") self.tb.msg_connect(demapper, "bursts", dst, "in") self.tb.run () b = test_data.bursts self.assertEqual(b, list(dst.get_burst_data())) self.assertEqual([ 7, 7, 7, 7, #SDCCH 3 3, 3, #RACCH 135, 135, 135, 135, #SACCH 2 135, 135, 135, 135, #SACCH 3 3, 3, 3, 3, #RACCH 3, 3, 3, 3, #RACCH 3, 3, 3, 3, #RACCH 3, 3, 3, 3, #RACCH 3, 3, 3, 3, #RACCH 3, 3, 3, #RACCH 7, 7, 7, 7, #SDCCH 0 7, 7, 7, 7, #SDCCH 1 3, 3, #RACCH 7, 7, 7, 7, #SDCCH 2 7, 7, 7, 7, #SDCCH 3 3, 3, #RACCH 135, 135, 135, 135, #SACCH 0 135, 135, 135, 135, #SACCH 1 3, 3, 3, 3, #RACCH 3, 3, 3, 3, #RACCH 3, 3, 3, 3, #RACCH 3, 3, 3, 3, #RACCH 3, 3, 3, 3, #RACCH 3, 3, 3, #RACCH 7, 7, 7, 7, #SDCCH 0 7, 7, 7, 7, #SDCCH 1 3, 3, #RACCH 7, 7, 7, 7, #SDCCH 2 7, 7, 7, 7, #SDCCH 3 3, 3, #RACCH ], list(dst.get_sub_types())) self.assertEqual([ 3, 3, 3, 3, #SDCCH 3 0, 0, #RACCH 2, 2, 2, 2, #SACCH 2 3, 3, 3, 3, #SACCH 3 0, 0, 0, 0, #RACCH 0, 0, 0, 0, #RACCH 0, 0, 0, 0, #RACCH 0, 0, 0, 0, #RACCH 0, 0, 0, 0, #RACCH 0, 0, 0, #RACCH 0, 0, 0, 0, #SDCCH 0 1, 1, 1, 1, #SDCCH 1 0, 0, #RACCH 2, 2, 2, 2, #SDCCH 2 3, 3, 3, 3, #SDCCH 3 0, 0, #RACCH 0, 0, 0, 0, #SACCH 0 1, 1, 1, 1, #SACCH 1 0, 0, 0, 0, #RACCH 0, 0, 0, 0, #RACCH 0, 0, 0, 0, #RACCH 0, 0, 0, 0, #RACCH 0, 0, 0, 0, #RACCH 0, 0, 0, #RACCH 0, 0, 0, 0, #SDCCH 0 1, 1, 1, 1, #SDCCH 1 0, 0, #RACCH 2, 2, 2, 2, #SDCCH 2 3, 3, 3, 3, #SDCCH 3 0, 0, #RACCH ], list(dst.get_sub_slots()))
[ "def", "test_uplink", "(", "self", ")", ":", "src", "=", "grgsm", ".", "burst_source", "(", "test_data", ".", "frames", ",", "test_data", ".", "timeslots", ",", "test_data", ".", "bursts", ")", "src", ".", "set_arfcn", "(", "0x2240", ")", "#uplink flag is 40", "demapper", "=", "grgsm", ".", "gsm_bcch_ccch_sdcch4_demapper", "(", "timeslot_nr", "=", "0", ")", "dst", "=", "grgsm", ".", "burst_sink", "(", ")", "self", ".", "tb", ".", "msg_connect", "(", "src", ",", "\"out\"", ",", "demapper", ",", "\"bursts\"", ")", "self", ".", "tb", ".", "msg_connect", "(", "demapper", ",", "\"bursts\"", ",", "dst", ",", "\"in\"", ")", "self", ".", "tb", ".", "run", "(", ")", "b", "=", "test_data", ".", "bursts", "self", ".", "assertEqual", "(", "b", ",", "list", "(", "dst", ".", "get_burst_data", "(", ")", ")", ")", "self", ".", "assertEqual", "(", "[", "7", ",", "7", ",", "7", ",", "7", ",", "#SDCCH 3", "3", ",", "3", ",", "#RACCH", "135", ",", "135", ",", "135", ",", "135", ",", "#SACCH 2", "135", ",", "135", ",", "135", ",", "135", ",", "#SACCH 3", "3", ",", "3", ",", "3", ",", "3", ",", "#RACCH", "3", ",", "3", ",", "3", ",", "3", ",", "#RACCH", "3", ",", "3", ",", "3", ",", "3", ",", "#RACCH", "3", ",", "3", ",", "3", ",", "3", ",", "#RACCH", "3", ",", "3", ",", "3", ",", "3", ",", "#RACCH", "3", ",", "3", ",", "3", ",", "#RACCH", "7", ",", "7", ",", "7", ",", "7", ",", "#SDCCH 0", "7", ",", "7", ",", "7", ",", "7", ",", "#SDCCH 1", "3", ",", "3", ",", "#RACCH", "7", ",", "7", ",", "7", ",", "7", ",", "#SDCCH 2", "7", ",", "7", ",", "7", ",", "7", ",", "#SDCCH 3", "3", ",", "3", ",", "#RACCH", "135", ",", "135", ",", "135", ",", "135", ",", "#SACCH 0", "135", ",", "135", ",", "135", ",", "135", ",", "#SACCH 1", "3", ",", "3", ",", "3", ",", "3", ",", "#RACCH", "3", ",", "3", ",", "3", ",", "3", ",", "#RACCH", "3", ",", "3", ",", "3", ",", "3", ",", "#RACCH", "3", ",", "3", ",", "3", ",", "3", ",", "#RACCH", "3", ",", "3", ",", "3", ",", "3", ",", "#RACCH", "3", ",", "3", ",", "3", ",", "#RACCH", "7", ",", "7", ",", "7", ",", "7", ",", "#SDCCH 0", "7", ",", "7", ",", "7", ",", "7", ",", "#SDCCH 1", "3", ",", "3", ",", "#RACCH", "7", ",", "7", ",", "7", ",", "7", ",", "#SDCCH 2", "7", ",", "7", ",", "7", ",", "7", ",", "#SDCCH 3", "3", ",", "3", ",", "#RACCH", "]", ",", "list", "(", "dst", ".", "get_sub_types", "(", ")", ")", ")", "self", ".", "assertEqual", "(", "[", "3", ",", "3", ",", "3", ",", "3", ",", "#SDCCH 3", "0", ",", "0", ",", "#RACCH", "2", ",", "2", ",", "2", ",", "2", ",", "#SACCH 2", "3", ",", "3", ",", "3", ",", "3", ",", "#SACCH 3", "0", ",", "0", ",", "0", ",", "0", ",", "#RACCH", "0", ",", "0", ",", "0", ",", "0", ",", "#RACCH", "0", ",", "0", ",", "0", ",", "0", ",", "#RACCH", "0", ",", "0", ",", "0", ",", "0", ",", "#RACCH", "0", ",", "0", ",", "0", ",", "0", ",", "#RACCH", "0", ",", "0", ",", "0", ",", "#RACCH", "0", ",", "0", ",", "0", ",", "0", ",", "#SDCCH 0", "1", ",", "1", ",", "1", ",", "1", ",", "#SDCCH 1", "0", ",", "0", ",", "#RACCH", "2", ",", "2", ",", "2", ",", "2", ",", "#SDCCH 2", "3", ",", "3", ",", "3", ",", "3", ",", "#SDCCH 3", "0", ",", "0", ",", "#RACCH", "0", ",", "0", ",", "0", ",", "0", ",", "#SACCH 0", "1", ",", "1", ",", "1", ",", "1", ",", "#SACCH 1", "0", ",", "0", ",", "0", ",", "0", ",", "#RACCH", "0", ",", "0", ",", "0", ",", "0", ",", "#RACCH", "0", ",", "0", ",", "0", ",", "0", ",", "#RACCH", "0", ",", "0", ",", "0", ",", "0", ",", "#RACCH", "0", ",", "0", ",", "0", ",", "0", ",", "#RACCH", "0", ",", "0", ",", "0", ",", "#RACCH", "0", ",", "0", ",", "0", ",", "0", ",", "#SDCCH 0", "1", ",", "1", ",", "1", ",", "1", ",", "#SDCCH 1", "0", ",", "0", ",", "#RACCH", "2", ",", "2", ",", "2", ",", "2", ",", "#SDCCH 2", "3", ",", "3", ",", "3", ",", "3", ",", "#SDCCH 3", "0", ",", "0", ",", "#RACCH", "]", ",", "list", "(", "dst", ".", "get_sub_slots", "(", ")", ")", ")" ]
https://github.com/ptrkrysik/gr-gsm/blob/2de47e28ce1fb9a518337bfc0add36c8e3cff5eb/python/qa_gsm_bcch_ccch_sdcch4_demapper.py#L126-L206
xhzdeng/crpn
a5aef0f80dbe486103123f740c634fb01e6cc9a1
caffe-fast-rcnn/scripts/cpp_lint.py
python
_CppLintState.SetFilters
(self, filters)
Sets the error-message filters. These filters are applied when deciding whether to emit a given error message. Args: filters: A string of comma-separated filters (eg "+whitespace/indent"). Each filter should start with + or -; else we die. Raises: ValueError: The comma-separated filters did not all start with '+' or '-'. E.g. "-,+whitespace,-whitespace/indent,whitespace/badfilter"
Sets the error-message filters.
[ "Sets", "the", "error", "-", "message", "filters", "." ]
def SetFilters(self, filters): """Sets the error-message filters. These filters are applied when deciding whether to emit a given error message. Args: filters: A string of comma-separated filters (eg "+whitespace/indent"). Each filter should start with + or -; else we die. Raises: ValueError: The comma-separated filters did not all start with '+' or '-'. E.g. "-,+whitespace,-whitespace/indent,whitespace/badfilter" """ # Default filters always have less priority than the flag ones. self.filters = _DEFAULT_FILTERS[:] for filt in filters.split(','): clean_filt = filt.strip() if clean_filt: self.filters.append(clean_filt) for filt in self.filters: if not (filt.startswith('+') or filt.startswith('-')): raise ValueError('Every filter in --filters must start with + or -' ' (%s does not)' % filt)
[ "def", "SetFilters", "(", "self", ",", "filters", ")", ":", "# Default filters always have less priority than the flag ones.", "self", ".", "filters", "=", "_DEFAULT_FILTERS", "[", ":", "]", "for", "filt", "in", "filters", ".", "split", "(", "','", ")", ":", "clean_filt", "=", "filt", ".", "strip", "(", ")", "if", "clean_filt", ":", "self", ".", "filters", ".", "append", "(", "clean_filt", ")", "for", "filt", "in", "self", ".", "filters", ":", "if", "not", "(", "filt", ".", "startswith", "(", "'+'", ")", "or", "filt", ".", "startswith", "(", "'-'", ")", ")", ":", "raise", "ValueError", "(", "'Every filter in --filters must start with + or -'", "' (%s does not)'", "%", "filt", ")" ]
https://github.com/xhzdeng/crpn/blob/a5aef0f80dbe486103123f740c634fb01e6cc9a1/caffe-fast-rcnn/scripts/cpp_lint.py#L721-L744
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/prompt-toolkit/py2/prompt_toolkit/buffer.py
python
Buffer._set_cursor_position
(self, value)
return value != original_position
Set cursor position. Return whether it changed.
Set cursor position. Return whether it changed.
[ "Set", "cursor", "position", ".", "Return", "whether", "it", "changed", "." ]
def _set_cursor_position(self, value): """ Set cursor position. Return whether it changed. """ original_position = self.__cursor_position self.__cursor_position = max(0, value) return value != original_position
[ "def", "_set_cursor_position", "(", "self", ",", "value", ")", ":", "original_position", "=", "self", ".", "__cursor_position", "self", ".", "__cursor_position", "=", "max", "(", "0", ",", "value", ")", "return", "value", "!=", "original_position" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/prompt-toolkit/py2/prompt_toolkit/buffer.py#L353-L358
microsoft/EdgeML
ef9f8a77f096acbdeb941014791f8eda1c1bc35b
tf/edgeml_tf/graph/rnn.py
python
EMI_UGRNN.addBaseAssignOps
(self, graph, initVarList, **kwargs)
Adds Tensorflow assignment operations to all of the model tensors. These operations can then be used to initialize these tensors from numpy matrices by running these operators initVarList: A list of numpy matrices that will be used for initialization by the assignment operation. For EMI_UGRNN, this should be list of numpy matrices corresponding to [kernel, bias]
Adds Tensorflow assignment operations to all of the model tensors. These operations can then be used to initialize these tensors from numpy matrices by running these operators
[ "Adds", "Tensorflow", "assignment", "operations", "to", "all", "of", "the", "model", "tensors", ".", "These", "operations", "can", "then", "be", "used", "to", "initialize", "these", "tensors", "from", "numpy", "matrices", "by", "running", "these", "operators" ]
def addBaseAssignOps(self, graph, initVarList, **kwargs): ''' Adds Tensorflow assignment operations to all of the model tensors. These operations can then be used to initialize these tensors from numpy matrices by running these operators initVarList: A list of numpy matrices that will be used for initialization by the assignment operation. For EMI_UGRNN, this should be list of numpy matrices corresponding to [kernel, bias] ''' assert initVarList is not None assert len(initVarList) == 2 k_ = graph.get_tensor_by_name('rnn/ugrnn_cell/kernel:0') b_ = graph.get_tensor_by_name('rnn/ugrnn_cell/bias:0') kernel, bias = initVarList[-2], initVarList[-1] k_op = tf.assign(k_, kernel) b_op = tf.assign(b_, bias) self.assignOps.extend([k_op, b_op])
[ "def", "addBaseAssignOps", "(", "self", ",", "graph", ",", "initVarList", ",", "*", "*", "kwargs", ")", ":", "assert", "initVarList", "is", "not", "None", "assert", "len", "(", "initVarList", ")", "==", "2", "k_", "=", "graph", ".", "get_tensor_by_name", "(", "'rnn/ugrnn_cell/kernel:0'", ")", "b_", "=", "graph", ".", "get_tensor_by_name", "(", "'rnn/ugrnn_cell/bias:0'", ")", "kernel", ",", "bias", "=", "initVarList", "[", "-", "2", "]", ",", "initVarList", "[", "-", "1", "]", "k_op", "=", "tf", ".", "assign", "(", "k_", ",", "kernel", ")", "b_op", "=", "tf", ".", "assign", "(", "b_", ",", "bias", ")", "self", ".", "assignOps", ".", "extend", "(", "[", "k_op", ",", "b_op", "]", ")" ]
https://github.com/microsoft/EdgeML/blob/ef9f8a77f096acbdeb941014791f8eda1c1bc35b/tf/edgeml_tf/graph/rnn.py#L1896-L1913
MythTV/mythtv
d282a209cb8be85d036f85a62a8ec971b67d45f4
mythtv/bindings/python/MythTV/mythproto.py
python
FileOps.forgetRecording
(self, program)
FileOps.forgetRecording(program) -> None
FileOps.forgetRecording(program) -> None
[ "FileOps", ".", "forgetRecording", "(", "program", ")", "-", ">", "None" ]
def forgetRecording(self, program): """FileOps.forgetRecording(program) -> None""" self.backendCommand(BACKEND_SEP.join(['FORGET_RECORDING', program.toString()]))
[ "def", "forgetRecording", "(", "self", ",", "program", ")", ":", "self", ".", "backendCommand", "(", "BACKEND_SEP", ".", "join", "(", "[", "'FORGET_RECORDING'", ",", "program", ".", "toString", "(", ")", "]", ")", ")" ]
https://github.com/MythTV/mythtv/blob/d282a209cb8be85d036f85a62a8ec971b67d45f4/mythtv/bindings/python/MythTV/mythproto.py#L666-L669
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/ttk.py
python
Notebook.identify
(self, x, y)
return self.tk.call(self._w, "identify", x, y)
Returns the name of the tab element at position x, y, or the empty string if none.
Returns the name of the tab element at position x, y, or the empty string if none.
[ "Returns", "the", "name", "of", "the", "tab", "element", "at", "position", "x", "y", "or", "the", "empty", "string", "if", "none", "." ]
def identify(self, x, y): """Returns the name of the tab element at position x, y, or the empty string if none.""" 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/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/ttk.py#L857-L860
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py3/pandas/core/dtypes/common.py
python
is_timedelta64_dtype
(arr_or_dtype)
return _is_dtype_type(arr_or_dtype, classes(np.timedelta64))
Check whether an array-like or dtype is of the timedelta64 dtype. Parameters ---------- arr_or_dtype : array-like The array-like or dtype to check. Returns ------- boolean Whether or not the array-like or dtype is of the timedelta64 dtype. Examples -------- >>> is_timedelta64_dtype(object) False >>> is_timedelta64_dtype(np.timedelta64) True >>> is_timedelta64_dtype([1, 2, 3]) False >>> is_timedelta64_dtype(pd.Series([], dtype="timedelta64[ns]")) True >>> is_timedelta64_dtype('0 days') False
Check whether an array-like or dtype is of the timedelta64 dtype.
[ "Check", "whether", "an", "array", "-", "like", "or", "dtype", "is", "of", "the", "timedelta64", "dtype", "." ]
def is_timedelta64_dtype(arr_or_dtype) -> bool: """ Check whether an array-like or dtype is of the timedelta64 dtype. Parameters ---------- arr_or_dtype : array-like The array-like or dtype to check. Returns ------- boolean Whether or not the array-like or dtype is of the timedelta64 dtype. Examples -------- >>> is_timedelta64_dtype(object) False >>> is_timedelta64_dtype(np.timedelta64) True >>> is_timedelta64_dtype([1, 2, 3]) False >>> is_timedelta64_dtype(pd.Series([], dtype="timedelta64[ns]")) True >>> is_timedelta64_dtype('0 days') False """ if isinstance(arr_or_dtype, np.dtype): # GH#33400 fastpath for dtype object return arr_or_dtype.kind == "m" return _is_dtype_type(arr_or_dtype, classes(np.timedelta64))
[ "def", "is_timedelta64_dtype", "(", "arr_or_dtype", ")", "->", "bool", ":", "if", "isinstance", "(", "arr_or_dtype", ",", "np", ".", "dtype", ")", ":", "# GH#33400 fastpath for dtype object", "return", "arr_or_dtype", ".", "kind", "==", "\"m\"", "return", "_is_dtype_type", "(", "arr_or_dtype", ",", "classes", "(", "np", ".", "timedelta64", ")", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/dtypes/common.py#L388-L419
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_misc.py
python
AboutDialogInfo.SetLicense
(*args, **kwargs)
return _misc_.AboutDialogInfo_SetLicense(*args, **kwargs)
SetLicense(self, String licence) This is the same as `SetLicence`.
SetLicense(self, String licence)
[ "SetLicense", "(", "self", "String", "licence", ")" ]
def SetLicense(*args, **kwargs): """ SetLicense(self, String licence) This is the same as `SetLicence`. """ return _misc_.AboutDialogInfo_SetLicense(*args, **kwargs)
[ "def", "SetLicense", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_misc_", ".", "AboutDialogInfo_SetLicense", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_misc.py#L6700-L6706
TGAC/KAT
e8870331de2b4bb0a1b3b91c6afb8fb9d59e9216
deps/boost/tools/build/src/tools/common.py
python
check_init_parameters
(toolset, requirement, *args)
return ['/'.join(condition)]
The rule for checking toolset parameters. Trailing parameters should all be parameter name/value pairs. The rule will check that each parameter either has a value in each invocation or has no value in each invocation. Also, the rule will check that the combination of all parameter values is unique in all invocations. Each parameter name corresponds to a subfeature. This rule will declare a subfeature the first time a non-empty parameter value is passed and will extend it with all the values. The return value from this rule is a condition to be used for flags settings.
The rule for checking toolset parameters. Trailing parameters should all be parameter name/value pairs. The rule will check that each parameter either has a value in each invocation or has no value in each invocation. Also, the rule will check that the combination of all parameter values is unique in all invocations.
[ "The", "rule", "for", "checking", "toolset", "parameters", ".", "Trailing", "parameters", "should", "all", "be", "parameter", "name", "/", "value", "pairs", ".", "The", "rule", "will", "check", "that", "each", "parameter", "either", "has", "a", "value", "in", "each", "invocation", "or", "has", "no", "value", "in", "each", "invocation", ".", "Also", "the", "rule", "will", "check", "that", "the", "combination", "of", "all", "parameter", "values", "is", "unique", "in", "all", "invocations", "." ]
def check_init_parameters(toolset, requirement, *args): """ The rule for checking toolset parameters. Trailing parameters should all be parameter name/value pairs. The rule will check that each parameter either has a value in each invocation or has no value in each invocation. Also, the rule will check that the combination of all parameter values is unique in all invocations. Each parameter name corresponds to a subfeature. This rule will declare a subfeature the first time a non-empty parameter value is passed and will extend it with all the values. The return value from this rule is a condition to be used for flags settings. """ assert isinstance(toolset, basestring) assert is_iterable_typed(requirement, basestring) or requirement is None from b2.build import toolset as b2_toolset if requirement is None: requirement = [] sig = toolset condition = replace_grist(toolset, '<toolset>') subcondition = [] for arg in args: assert(isinstance(arg, tuple)) assert(len(arg) == 2) name = arg[0] value = arg[1] assert(isinstance(name, str)) assert(isinstance(value, str) or value is None) str_toolset_name = str((toolset, name)) # FIXME: is this the correct translation? ### if $(value)-is-not-empty if value is not None: condition = condition + '-' + value if str_toolset_name in __had_unspecified_value: raise BaseException("'%s' initialization: parameter '%s' inconsistent\n" \ "no value was specified in earlier initialization\n" \ "an explicit value is specified now" % (toolset, name)) # The logic below is for intel compiler. It calls this rule # with 'intel-linux' and 'intel-win' as toolset, so we need to # get the base part of toolset name. # We can't pass 'intel' as toolset, because it that case it will # be impossible to register versionles intel-linux and # intel-win of specific version. t = toolset m = __re__before_first_dash.match(toolset) if m: t = m.group(1) if str_toolset_name not in __had_value: if str((t, name)) not in __declared_subfeature: feature.subfeature('toolset', t, name, [], ['propagated']) __declared_subfeature[str((t, name))] = True __had_value[str_toolset_name] = True feature.extend_subfeature('toolset', t, name, [value]) subcondition += ['<toolset-' + t + ':' + name + '>' + value ] else: if str_toolset_name in __had_value: raise BaseException ("'%s' initialization: parameter '%s' inconsistent\n" \ "an explicit value was specified in an earlier initialization\n" \ "no value is specified now" % (toolset, name)) __had_unspecified_value[str_toolset_name] = True if value == None: value = '' sig = sig + value + '-' # if a requirement is specified, the signature should be unique # with that requirement if requirement: sig += '-' + '-'.join(requirement) if sig in __all_signatures: message = "duplicate initialization of '%s' with the following parameters: " % toolset for arg in args: name = arg[0] value = arg[1] if value == None: value = '<unspecified>' message += "'%s' = '%s'\n" % (name, value) raise BaseException(message) __all_signatures[sig] = True # FIXME __init_loc[sig] = "User location unknown" #[ errors.nearest-user-location ] ; # If we have a requirement, this version should only be applied under that # condition. To accomplish this we add a toolset requirement that imposes # the toolset subcondition, which encodes the version. if requirement: r = ['<toolset>' + toolset] + requirement r = ','.join(r) b2_toolset.add_requirements([r + ':' + c for c in subcondition]) # We add the requirements, if any, to the condition to scope the toolset # variables and options to this specific version. condition = [condition] if requirement: condition += requirement if __show_configuration: print "notice:", condition return ['/'.join(condition)]
[ "def", "check_init_parameters", "(", "toolset", ",", "requirement", ",", "*", "args", ")", ":", "assert", "isinstance", "(", "toolset", ",", "basestring", ")", "assert", "is_iterable_typed", "(", "requirement", ",", "basestring", ")", "or", "requirement", "is", "None", "from", "b2", ".", "build", "import", "toolset", "as", "b2_toolset", "if", "requirement", "is", "None", ":", "requirement", "=", "[", "]", "sig", "=", "toolset", "condition", "=", "replace_grist", "(", "toolset", ",", "'<toolset>'", ")", "subcondition", "=", "[", "]", "for", "arg", "in", "args", ":", "assert", "(", "isinstance", "(", "arg", ",", "tuple", ")", ")", "assert", "(", "len", "(", "arg", ")", "==", "2", ")", "name", "=", "arg", "[", "0", "]", "value", "=", "arg", "[", "1", "]", "assert", "(", "isinstance", "(", "name", ",", "str", ")", ")", "assert", "(", "isinstance", "(", "value", ",", "str", ")", "or", "value", "is", "None", ")", "str_toolset_name", "=", "str", "(", "(", "toolset", ",", "name", ")", ")", "# FIXME: is this the correct translation?", "### if $(value)-is-not-empty", "if", "value", "is", "not", "None", ":", "condition", "=", "condition", "+", "'-'", "+", "value", "if", "str_toolset_name", "in", "__had_unspecified_value", ":", "raise", "BaseException", "(", "\"'%s' initialization: parameter '%s' inconsistent\\n\"", "\"no value was specified in earlier initialization\\n\"", "\"an explicit value is specified now\"", "%", "(", "toolset", ",", "name", ")", ")", "# The logic below is for intel compiler. It calls this rule", "# with 'intel-linux' and 'intel-win' as toolset, so we need to", "# get the base part of toolset name.", "# We can't pass 'intel' as toolset, because it that case it will", "# be impossible to register versionles intel-linux and", "# intel-win of specific version.", "t", "=", "toolset", "m", "=", "__re__before_first_dash", ".", "match", "(", "toolset", ")", "if", "m", ":", "t", "=", "m", ".", "group", "(", "1", ")", "if", "str_toolset_name", "not", "in", "__had_value", ":", "if", "str", "(", "(", "t", ",", "name", ")", ")", "not", "in", "__declared_subfeature", ":", "feature", ".", "subfeature", "(", "'toolset'", ",", "t", ",", "name", ",", "[", "]", ",", "[", "'propagated'", "]", ")", "__declared_subfeature", "[", "str", "(", "(", "t", ",", "name", ")", ")", "]", "=", "True", "__had_value", "[", "str_toolset_name", "]", "=", "True", "feature", ".", "extend_subfeature", "(", "'toolset'", ",", "t", ",", "name", ",", "[", "value", "]", ")", "subcondition", "+=", "[", "'<toolset-'", "+", "t", "+", "':'", "+", "name", "+", "'>'", "+", "value", "]", "else", ":", "if", "str_toolset_name", "in", "__had_value", ":", "raise", "BaseException", "(", "\"'%s' initialization: parameter '%s' inconsistent\\n\"", "\"an explicit value was specified in an earlier initialization\\n\"", "\"no value is specified now\"", "%", "(", "toolset", ",", "name", ")", ")", "__had_unspecified_value", "[", "str_toolset_name", "]", "=", "True", "if", "value", "==", "None", ":", "value", "=", "''", "sig", "=", "sig", "+", "value", "+", "'-'", "# if a requirement is specified, the signature should be unique", "# with that requirement", "if", "requirement", ":", "sig", "+=", "'-'", "+", "'-'", ".", "join", "(", "requirement", ")", "if", "sig", "in", "__all_signatures", ":", "message", "=", "\"duplicate initialization of '%s' with the following parameters: \"", "%", "toolset", "for", "arg", "in", "args", ":", "name", "=", "arg", "[", "0", "]", "value", "=", "arg", "[", "1", "]", "if", "value", "==", "None", ":", "value", "=", "'<unspecified>'", "message", "+=", "\"'%s' = '%s'\\n\"", "%", "(", "name", ",", "value", ")", "raise", "BaseException", "(", "message", ")", "__all_signatures", "[", "sig", "]", "=", "True", "# FIXME", "__init_loc", "[", "sig", "]", "=", "\"User location unknown\"", "#[ errors.nearest-user-location ] ;", "# If we have a requirement, this version should only be applied under that", "# condition. To accomplish this we add a toolset requirement that imposes", "# the toolset subcondition, which encodes the version.", "if", "requirement", ":", "r", "=", "[", "'<toolset>'", "+", "toolset", "]", "+", "requirement", "r", "=", "','", ".", "join", "(", "r", ")", "b2_toolset", ".", "add_requirements", "(", "[", "r", "+", "':'", "+", "c", "for", "c", "in", "subcondition", "]", ")", "# We add the requirements, if any, to the condition to scope the toolset", "# variables and options to this specific version.", "condition", "=", "[", "condition", "]", "if", "requirement", ":", "condition", "+=", "requirement", "if", "__show_configuration", ":", "print", "\"notice:\"", ",", "condition", "return", "[", "'/'", ".", "join", "(", "condition", ")", "]" ]
https://github.com/TGAC/KAT/blob/e8870331de2b4bb0a1b3b91c6afb8fb9d59e9216/deps/boost/tools/build/src/tools/common.py#L171-L282
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/ma/core.py
python
_arraymethod.getdoc
(self)
Return the doc of the function (from the doc of the method).
Return the doc of the function (from the doc of the method).
[ "Return", "the", "doc", "of", "the", "function", "(", "from", "the", "doc", "of", "the", "method", ")", "." ]
def getdoc(self): "Return the doc of the function (from the doc of the method)." methdoc = getattr(ndarray, self.__name__, None) or \ getattr(np, self.__name__, None) if methdoc is not None: return methdoc.__doc__
[ "def", "getdoc", "(", "self", ")", ":", "methdoc", "=", "getattr", "(", "ndarray", ",", "self", ".", "__name__", ",", "None", ")", "or", "getattr", "(", "np", ",", "self", ".", "__name__", ",", "None", ")", "if", "methdoc", "is", "not", "None", ":", "return", "methdoc", ".", "__doc__" ]
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/ma/core.py#L2434-L2439
fifengine/fifengine
4b62c42e85bec19893cef8e63e6855927cff2c47
engine/python/fife/extensions/pychan/widgets/common.py
python
gui2str
(text)
This function returns an 8-bit representation of the unicode string. This is useful for passing strings to SWIG functions.
This function returns an 8-bit representation of the unicode string. This is useful for passing strings to SWIG functions.
[ "This", "function", "returns", "an", "8", "-", "bit", "representation", "of", "the", "unicode", "string", ".", "This", "is", "useful", "for", "passing", "strings", "to", "SWIG", "functions", "." ]
def gui2str(text): """ This function returns an 8-bit representation of the unicode string. This is useful for passing strings to SWIG functions. """ try: return text.__str__() except: # String contains non-ascii characters return text.encode("utf-8")
[ "def", "gui2str", "(", "text", ")", ":", "try", ":", "return", "text", ".", "__str__", "(", ")", "except", ":", "# String contains non-ascii characters", "return", "text", ".", "encode", "(", "\"utf-8\"", ")" ]
https://github.com/fifengine/fifengine/blob/4b62c42e85bec19893cef8e63e6855927cff2c47/engine/python/fife/extensions/pychan/widgets/common.py#L66-L76
hpi-xnor/BMXNet
ed0b201da6667887222b8e4b5f997c4f6b61943d
amalgamation/python/mxnet_predict.py
python
_find_lib_path
()
return lib_path
Find mxnet library.
Find mxnet library.
[ "Find", "mxnet", "library", "." ]
def _find_lib_path(): """Find mxnet library.""" curr_path = os.path.dirname(os.path.abspath(os.path.expanduser(__file__))) api_path = os.path.join(curr_path, '../../lib/') dll_path = [curr_path, api_path] dll_path = [os.path.join(p, 'libmxnet.so') for p in dll_path] + \ [os.path.join(p, 'libmxnet_predict.so') for p in dll_path] lib_path = [p for p in dll_path if os.path.exists(p) and os.path.isfile(p)] if len(lib_path) == 0: raise RuntimeError('Cannot find the files.\n' + 'List of candidates:\n' + str('\n'.join(dll_path))) return lib_path
[ "def", "_find_lib_path", "(", ")", ":", "curr_path", "=", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "expanduser", "(", "__file__", ")", ")", ")", "api_path", "=", "os", ".", "path", ".", "join", "(", "curr_path", ",", "'../../lib/'", ")", "dll_path", "=", "[", "curr_path", ",", "api_path", "]", "dll_path", "=", "[", "os", ".", "path", ".", "join", "(", "p", ",", "'libmxnet.so'", ")", "for", "p", "in", "dll_path", "]", "+", "[", "os", ".", "path", ".", "join", "(", "p", ",", "'libmxnet_predict.so'", ")", "for", "p", "in", "dll_path", "]", "lib_path", "=", "[", "p", "for", "p", "in", "dll_path", "if", "os", ".", "path", ".", "exists", "(", "p", ")", "and", "os", ".", "path", ".", "isfile", "(", "p", ")", "]", "if", "len", "(", "lib_path", ")", "==", "0", ":", "raise", "RuntimeError", "(", "'Cannot find the files.\\n'", "+", "'List of candidates:\\n'", "+", "str", "(", "'\\n'", ".", "join", "(", "dll_path", ")", ")", ")", "return", "lib_path" ]
https://github.com/hpi-xnor/BMXNet/blob/ed0b201da6667887222b8e4b5f997c4f6b61943d/amalgamation/python/mxnet_predict.py#L46-L57
garbear/kodi-steamlink
3f8e5970b01607cdb3c2688fbaa78e08f2d9c561
tools/EventClients/lib/python/xbmcclient.py
python
PacketHELO.__init__
(self, devicename=None, icon_type=ICON_NONE, icon_file=None)
Keyword arguments: devicename -- the string that identifies the client icon_type -- one of ICON_NONE, ICON_JPEG, ICON_PNG, ICON_GIF icon_file -- location of icon file with respect to current working directory if icon_type is not ICON_NONE
Keyword arguments: devicename -- the string that identifies the client icon_type -- one of ICON_NONE, ICON_JPEG, ICON_PNG, ICON_GIF icon_file -- location of icon file with respect to current working directory if icon_type is not ICON_NONE
[ "Keyword", "arguments", ":", "devicename", "--", "the", "string", "that", "identifies", "the", "client", "icon_type", "--", "one", "of", "ICON_NONE", "ICON_JPEG", "ICON_PNG", "ICON_GIF", "icon_file", "--", "location", "of", "icon", "file", "with", "respect", "to", "current", "working", "directory", "if", "icon_type", "is", "not", "ICON_NONE" ]
def __init__(self, devicename=None, icon_type=ICON_NONE, icon_file=None): """ Keyword arguments: devicename -- the string that identifies the client icon_type -- one of ICON_NONE, ICON_JPEG, ICON_PNG, ICON_GIF icon_file -- location of icon file with respect to current working directory if icon_type is not ICON_NONE """ Packet.__init__(self) self.packettype = PT_HELO self.icontype = icon_type self.set_payload ( format_string(devicename)[0:128] ) self.append_payload( chr (icon_type) ) self.append_payload( format_uint16 (0) ) # port no self.append_payload( format_uint32 (0) ) # reserved1 self.append_payload( format_uint32 (0) ) # reserved2 if icon_type != ICON_NONE and icon_file: with open(icon_file, 'rb') as f: self.append_payload(f.read())
[ "def", "__init__", "(", "self", ",", "devicename", "=", "None", ",", "icon_type", "=", "ICON_NONE", ",", "icon_file", "=", "None", ")", ":", "Packet", ".", "__init__", "(", "self", ")", "self", ".", "packettype", "=", "PT_HELO", "self", ".", "icontype", "=", "icon_type", "self", ".", "set_payload", "(", "format_string", "(", "devicename", ")", "[", "0", ":", "128", "]", ")", "self", ".", "append_payload", "(", "chr", "(", "icon_type", ")", ")", "self", ".", "append_payload", "(", "format_uint16", "(", "0", ")", ")", "# port no", "self", ".", "append_payload", "(", "format_uint32", "(", "0", ")", ")", "# reserved1", "self", ".", "append_payload", "(", "format_uint32", "(", "0", ")", ")", "# reserved2", "if", "icon_type", "!=", "ICON_NONE", "and", "icon_file", ":", "with", "open", "(", "icon_file", ",", "'rb'", ")", "as", "f", ":", "self", ".", "append_payload", "(", "f", ".", "read", "(", ")", ")" ]
https://github.com/garbear/kodi-steamlink/blob/3f8e5970b01607cdb3c2688fbaa78e08f2d9c561/tools/EventClients/lib/python/xbmcclient.py#L268-L286
OSGeo/gdal
3748fc4ba4fba727492774b2b908a2130c864a83
swig/python/osgeo/ogr.py
python
Feature.SetNativeData
(self, *args)
return _ogr.Feature_SetNativeData(self, *args)
r""" SetNativeData(Feature self, char const * nativeData) void OGR_F_SetNativeData(OGRFeatureH hFeat, const char *pszNativeData) Sets the native data for the feature. The native data is the representation in a "natural" form that comes from the driver that created this feature, or that is aimed at an output driver. The native data may be in different format, which is indicated by OGR_F_GetNativeMediaType(). This function is the same as the C++ method OGRFeature::SetNativeData(). Parameters: ----------- hFeat: handle to the feature. pszNativeData: a string with the native data, or NULL if there is none. GDAL 2.1 See: https://trac.osgeo.org/gdal/wiki/rfc60_improved_roundtripping_in_ogr
r""" SetNativeData(Feature self, char const * nativeData) void OGR_F_SetNativeData(OGRFeatureH hFeat, const char *pszNativeData)
[ "r", "SetNativeData", "(", "Feature", "self", "char", "const", "*", "nativeData", ")", "void", "OGR_F_SetNativeData", "(", "OGRFeatureH", "hFeat", "const", "char", "*", "pszNativeData", ")" ]
def SetNativeData(self, *args): r""" SetNativeData(Feature self, char const * nativeData) void OGR_F_SetNativeData(OGRFeatureH hFeat, const char *pszNativeData) Sets the native data for the feature. The native data is the representation in a "natural" form that comes from the driver that created this feature, or that is aimed at an output driver. The native data may be in different format, which is indicated by OGR_F_GetNativeMediaType(). This function is the same as the C++ method OGRFeature::SetNativeData(). Parameters: ----------- hFeat: handle to the feature. pszNativeData: a string with the native data, or NULL if there is none. GDAL 2.1 See: https://trac.osgeo.org/gdal/wiki/rfc60_improved_roundtripping_in_ogr """ return _ogr.Feature_SetNativeData(self, *args)
[ "def", "SetNativeData", "(", "self", ",", "*", "args", ")", ":", "return", "_ogr", ".", "Feature_SetNativeData", "(", "self", ",", "*", "args", ")" ]
https://github.com/OSGeo/gdal/blob/3748fc4ba4fba727492774b2b908a2130c864a83/swig/python/osgeo/ogr.py#L4118-L4148
microsoft/TSS.MSR
0f2516fca2cd9929c31d5450e39301c9bde43688
TSS.Py/src/Tpm.py
python
Tpm.GetTestResult
(self)
return self.processResponse(respBuf, GetTestResultResponse)
This command returns manufacturer-specific information regarding the results of a self-test and an indication of the test status. Returns: outData - Test result data contains manufacturer-specific information testResult - TBD
This command returns manufacturer-specific information regarding the results of a self-test and an indication of the test status.
[ "This", "command", "returns", "manufacturer", "-", "specific", "information", "regarding", "the", "results", "of", "a", "self", "-", "test", "and", "an", "indication", "of", "the", "test", "status", "." ]
def GetTestResult(self): """ This command returns manufacturer-specific information regarding the results of a self-test and an indication of the test status. Returns: outData - Test result data contains manufacturer-specific information testResult - TBD """ req = TPM2_GetTestResult_REQUEST() respBuf = self.dispatchCommand(TPM_CC.GetTestResult, req) return self.processResponse(respBuf, GetTestResultResponse)
[ "def", "GetTestResult", "(", "self", ")", ":", "req", "=", "TPM2_GetTestResult_REQUEST", "(", ")", "respBuf", "=", "self", ".", "dispatchCommand", "(", "TPM_CC", ".", "GetTestResult", ",", "req", ")", "return", "self", ".", "processResponse", "(", "respBuf", ",", "GetTestResultResponse", ")" ]
https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/Tpm.py#L75-L86
SequoiaDB/SequoiaDB
2894ed7e5bd6fe57330afc900cf76d0ff0df9f64
driver/python/bson/objectid.py
python
ObjectId.__getstate__
(self)
return self.__id
return value of object for pickling. needed explicitly because __slots__() defined.
return value of object for pickling. needed explicitly because __slots__() defined.
[ "return", "value", "of", "object", "for", "pickling", ".", "needed", "explicitly", "because", "__slots__", "()", "defined", "." ]
def __getstate__(self): """return value of object for pickling. needed explicitly because __slots__() defined. """ return self.__id
[ "def", "__getstate__", "(", "self", ")", ":", "return", "self", ".", "__id" ]
https://github.com/SequoiaDB/SequoiaDB/blob/2894ed7e5bd6fe57330afc900cf76d0ff0df9f64/driver/python/bson/objectid.py#L229-L233
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/lib2to3/fixes/fix_urllib.py
python
FixUrllib.transform_dot
(self, node, results)
Transform for calls to module members in code.
Transform for calls to module members in code.
[ "Transform", "for", "calls", "to", "module", "members", "in", "code", "." ]
def transform_dot(self, node, results): """Transform for calls to module members in code.""" module_dot = results.get("bare_with_attr") member = results.get("member") new_name = None if isinstance(member, list): member = member[0] for change in MAPPING[module_dot.value]: if member.value in change[1]: new_name = change[0] break if new_name: module_dot.replace(Name(new_name, prefix=module_dot.prefix)) else: self.cannot_convert(node, "This is an invalid module element")
[ "def", "transform_dot", "(", "self", ",", "node", ",", "results", ")", ":", "module_dot", "=", "results", ".", "get", "(", "\"bare_with_attr\"", ")", "member", "=", "results", ".", "get", "(", "\"member\"", ")", "new_name", "=", "None", "if", "isinstance", "(", "member", ",", "list", ")", ":", "member", "=", "member", "[", "0", "]", "for", "change", "in", "MAPPING", "[", "module_dot", ".", "value", "]", ":", "if", "member", ".", "value", "in", "change", "[", "1", "]", ":", "new_name", "=", "change", "[", "0", "]", "break", "if", "new_name", ":", "module_dot", ".", "replace", "(", "Name", "(", "new_name", ",", "prefix", "=", "module_dot", ".", "prefix", ")", ")", "else", ":", "self", ".", "cannot_convert", "(", "node", ",", "\"This is an invalid module element\"", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/lib2to3/fixes/fix_urllib.py#L168-L183
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/dis.py
python
dis
(x=None)
Disassemble classes, methods, functions, or code. With no argument, disassemble the last traceback.
Disassemble classes, methods, functions, or code.
[ "Disassemble", "classes", "methods", "functions", "or", "code", "." ]
def dis(x=None): """Disassemble classes, methods, functions, or code. With no argument, disassemble the last traceback. """ if x is None: distb() return if type(x) is types.InstanceType: x = x.__class__ if hasattr(x, 'im_func'): x = x.im_func if hasattr(x, 'func_code'): x = x.func_code if hasattr(x, '__dict__'): items = x.__dict__.items() items.sort() for name, x1 in items: if type(x1) in (types.MethodType, types.FunctionType, types.CodeType, types.ClassType): print "Disassembly of %s:" % name try: dis(x1) except TypeError, msg: print "Sorry:", msg print elif hasattr(x, 'co_code'): disassemble(x) elif isinstance(x, str): disassemble_string(x) else: raise TypeError, \ "don't know how to disassemble %s objects" % \ type(x).__name__
[ "def", "dis", "(", "x", "=", "None", ")", ":", "if", "x", "is", "None", ":", "distb", "(", ")", "return", "if", "type", "(", "x", ")", "is", "types", ".", "InstanceType", ":", "x", "=", "x", ".", "__class__", "if", "hasattr", "(", "x", ",", "'im_func'", ")", ":", "x", "=", "x", ".", "im_func", "if", "hasattr", "(", "x", ",", "'func_code'", ")", ":", "x", "=", "x", ".", "func_code", "if", "hasattr", "(", "x", ",", "'__dict__'", ")", ":", "items", "=", "x", ".", "__dict__", ".", "items", "(", ")", "items", ".", "sort", "(", ")", "for", "name", ",", "x1", "in", "items", ":", "if", "type", "(", "x1", ")", "in", "(", "types", ".", "MethodType", ",", "types", ".", "FunctionType", ",", "types", ".", "CodeType", ",", "types", ".", "ClassType", ")", ":", "print", "\"Disassembly of %s:\"", "%", "name", "try", ":", "dis", "(", "x1", ")", "except", "TypeError", ",", "msg", ":", "print", "\"Sorry:\"", ",", "msg", "print", "elif", "hasattr", "(", "x", ",", "'co_code'", ")", ":", "disassemble", "(", "x", ")", "elif", "isinstance", "(", "x", ",", "str", ")", ":", "disassemble_string", "(", "x", ")", "else", ":", "raise", "TypeError", ",", "\"don't know how to disassemble %s objects\"", "%", "type", "(", "x", ")", ".", "__name__" ]
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/dis.py#L12-L48
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
scripts/SANS/SANSUserFileParser.py
python
BackCommandParser._parse
(self, arguments)
Parse the arguments and store the results @param arguments: the string containing the arguments @raise RuntimeError: If the argument cannot be parsed correctly
Parse the arguments and store the results
[ "Parse", "the", "arguments", "and", "store", "the", "results" ]
def _parse(self, arguments): ''' Parse the arguments and store the results @param arguments: the string containing the arguments @raise RuntimeError: If the argument cannot be parsed correctly ''' to_parse = self._prepare_argument(arguments) if not self.can_attempt_to_parse(arguments): raise RuntimeError("BackCommandParser: Cannot parse provided arguments." "They are not compatible") index = 0 for element in to_parse: key = self._evaluation_chain[index] evaluation_method = self._get_method(key) evaluation_method(element) index += 1
[ "def", "_parse", "(", "self", ",", "arguments", ")", ":", "to_parse", "=", "self", ".", "_prepare_argument", "(", "arguments", ")", "if", "not", "self", ".", "can_attempt_to_parse", "(", "arguments", ")", ":", "raise", "RuntimeError", "(", "\"BackCommandParser: Cannot parse provided arguments.\"", "\"They are not compatible\"", ")", "index", "=", "0", "for", "element", "in", "to_parse", ":", "key", "=", "self", ".", "_evaluation_chain", "[", "index", "]", "evaluation_method", "=", "self", ".", "_get_method", "(", "key", ")", "evaluation_method", "(", "element", ")", "index", "+=", "1" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/SANS/SANSUserFileParser.py#L216-L233
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/python/ops/control_flow_ops.py
python
_GetLoopConstantEnter
(value)
return op if _IsLoopConstantEnter(op) else None
Return the enter op if we can infer `value` to be a loop invariant.
Return the enter op if we can infer `value` to be a loop invariant.
[ "Return", "the", "enter", "op", "if", "we", "can", "infer", "value", "to", "be", "a", "loop", "invariant", "." ]
def _GetLoopConstantEnter(value): """Return the enter op if we can infer `value` to be a loop invariant.""" id_ops = {"Switch", "RefSwitch", "Identity", "RefIdentity"} op = value.op while op.type in id_ops: op = op.inputs[0].op return op if _IsLoopConstantEnter(op) else None
[ "def", "_GetLoopConstantEnter", "(", "value", ")", ":", "id_ops", "=", "{", "\"Switch\"", ",", "\"RefSwitch\"", ",", "\"Identity\"", ",", "\"RefIdentity\"", "}", "op", "=", "value", ".", "op", "while", "op", ".", "type", "in", "id_ops", ":", "op", "=", "op", ".", "inputs", "[", "0", "]", ".", "op", "return", "op", "if", "_IsLoopConstantEnter", "(", "op", ")", "else", "None" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/ops/control_flow_ops.py#L469-L475
libfive/libfive
ab5e354cf6fd992f80aaa9432c52683219515c8a
libfive/bind/python/libfive/stdlib/transforms.py
python
twirl_y
(shape, amount, radius, center=(0, 0, 0))
return Shape(stdlib.twirl_y( args[0].ptr, args[1].ptr, args[2].ptr, tvec3(*[a.ptr for a in args[3]])))
Twirls the shape in the y axis about the (optional) center point
Twirls the shape in the y axis about the (optional) center point
[ "Twirls", "the", "shape", "in", "the", "y", "axis", "about", "the", "(", "optional", ")", "center", "point" ]
def twirl_y(shape, amount, radius, center=(0, 0, 0)): """ Twirls the shape in the y axis about the (optional) center point """ args = [Shape.wrap(shape), Shape.wrap(amount), Shape.wrap(radius), list([Shape.wrap(i) for i in center])] return Shape(stdlib.twirl_y( args[0].ptr, args[1].ptr, args[2].ptr, tvec3(*[a.ptr for a in args[3]])))
[ "def", "twirl_y", "(", "shape", ",", "amount", ",", "radius", ",", "center", "=", "(", "0", ",", "0", ",", "0", ")", ")", ":", "args", "=", "[", "Shape", ".", "wrap", "(", "shape", ")", ",", "Shape", ".", "wrap", "(", "amount", ")", ",", "Shape", ".", "wrap", "(", "radius", ")", ",", "list", "(", "[", "Shape", ".", "wrap", "(", "i", ")", "for", "i", "in", "center", "]", ")", "]", "return", "Shape", "(", "stdlib", ".", "twirl_y", "(", "args", "[", "0", "]", ".", "ptr", ",", "args", "[", "1", "]", ".", "ptr", ",", "args", "[", "2", "]", ".", "ptr", ",", "tvec3", "(", "*", "[", "a", ".", "ptr", "for", "a", "in", "args", "[", "3", "]", "]", ")", ")", ")" ]
https://github.com/libfive/libfive/blob/ab5e354cf6fd992f80aaa9432c52683219515c8a/libfive/bind/python/libfive/stdlib/transforms.py#L459-L467
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/py/buffer.py
python
Buffer.addEditor
(self, editor)
Add an editor.
Add an editor.
[ "Add", "an", "editor", "." ]
def addEditor(self, editor): """Add an editor.""" self.editor = editor self.editors[editor.id] = editor
[ "def", "addEditor", "(", "self", ",", "editor", ")", ":", "self", ".", "editor", "=", "editor", "self", ".", "editors", "[", "editor", ".", "id", "]", "=", "editor" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/py/buffer.py#L42-L45
magazino/move_base_flex
a8ca484e354a0196b5e9fbda5f0eae311d9b72d3
git-clang-format.py
python
interpret_args
(args, dash_dash, default_commit)
return commits, files
Interpret `args` as "[commits] [--] [files]" and return (commits, files). It is assumed that "--" and everything that follows has been removed from args and placed in `dash_dash`. If "--" is present (i.e., `dash_dash` is non-empty), the arguments to its left (if present) are taken as commits. Otherwise, the arguments are checked from left to right if they are commits or files. If commits are not given, a list with `default_commit` is used.
Interpret `args` as "[commits] [--] [files]" and return (commits, files).
[ "Interpret", "args", "as", "[", "commits", "]", "[", "--", "]", "[", "files", "]", "and", "return", "(", "commits", "files", ")", "." ]
def interpret_args(args, dash_dash, default_commit): """Interpret `args` as "[commits] [--] [files]" and return (commits, files). It is assumed that "--" and everything that follows has been removed from args and placed in `dash_dash`. If "--" is present (i.e., `dash_dash` is non-empty), the arguments to its left (if present) are taken as commits. Otherwise, the arguments are checked from left to right if they are commits or files. If commits are not given, a list with `default_commit` is used.""" if dash_dash: if len(args) == 0: commits = [default_commit] else: commits = args for commit in commits: object_type = get_object_type(commit) if object_type not in ('commit', 'tag'): if object_type is None: die("'%s' is not a commit" % commit) else: die("'%s' is a %s, but a commit was expected" % (commit, object_type)) files = dash_dash[1:] elif args: commits = [] while args: if not disambiguate_revision(args[0]): break commits.append(args.pop(0)) if not commits: commits = [default_commit] files = args else: commits = [default_commit] files = [] return commits, files
[ "def", "interpret_args", "(", "args", ",", "dash_dash", ",", "default_commit", ")", ":", "if", "dash_dash", ":", "if", "len", "(", "args", ")", "==", "0", ":", "commits", "=", "[", "default_commit", "]", "else", ":", "commits", "=", "args", "for", "commit", "in", "commits", ":", "object_type", "=", "get_object_type", "(", "commit", ")", "if", "object_type", "not", "in", "(", "'commit'", ",", "'tag'", ")", ":", "if", "object_type", "is", "None", ":", "die", "(", "\"'%s' is not a commit\"", "%", "commit", ")", "else", ":", "die", "(", "\"'%s' is a %s, but a commit was expected\"", "%", "(", "commit", ",", "object_type", ")", ")", "files", "=", "dash_dash", "[", "1", ":", "]", "elif", "args", ":", "commits", "=", "[", "]", "while", "args", ":", "if", "not", "disambiguate_revision", "(", "args", "[", "0", "]", ")", ":", "break", "commits", ".", "append", "(", "args", ".", "pop", "(", "0", ")", ")", "if", "not", "commits", ":", "commits", "=", "[", "default_commit", "]", "files", "=", "args", "else", ":", "commits", "=", "[", "default_commit", "]", "files", "=", "[", "]", "return", "commits", ",", "files" ]
https://github.com/magazino/move_base_flex/blob/a8ca484e354a0196b5e9fbda5f0eae311d9b72d3/git-clang-format.py#L202-L237
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/ipython/py3/IPython/core/profiledir.py
python
ProfileDir.find_profile_dir
(cls, profile_dir, config=None)
return cls(location=profile_dir, config=config)
Find/create a profile dir and return its ProfileDir. This will create the profile directory if it doesn't exist. Parameters ---------- profile_dir : unicode or str The path of the profile directory.
Find/create a profile dir and return its ProfileDir.
[ "Find", "/", "create", "a", "profile", "dir", "and", "return", "its", "ProfileDir", "." ]
def find_profile_dir(cls, profile_dir, config=None): """Find/create a profile dir and return its ProfileDir. This will create the profile directory if it doesn't exist. Parameters ---------- profile_dir : unicode or str The path of the profile directory. """ profile_dir = expand_path(profile_dir) if not os.path.isdir(profile_dir): raise ProfileDirError('Profile directory not found: %s' % profile_dir) return cls(location=profile_dir, config=config)
[ "def", "find_profile_dir", "(", "cls", ",", "profile_dir", ",", "config", "=", "None", ")", ":", "profile_dir", "=", "expand_path", "(", "profile_dir", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "profile_dir", ")", ":", "raise", "ProfileDirError", "(", "'Profile directory not found: %s'", "%", "profile_dir", ")", "return", "cls", "(", "location", "=", "profile_dir", ",", "config", "=", "config", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py3/IPython/core/profiledir.py#L208-L221
thalium/icebox
99d147d5b9269222225443ce171b4fd46d8985d4
third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py
python
parserCtxt.parseCDSect
(self)
Parse escaped pure raw content. [18] CDSect ::= CDStart CData CDEnd [19] CDStart ::= '<![CDATA[' [20] Data ::= (Char* - (Char* ']]>' Char*)) [21] CDEnd ::= ']]>'
Parse escaped pure raw content. [18] CDSect ::= CDStart CData CDEnd [19] CDStart ::= '<![CDATA[' [20] Data ::= (Char* - (Char* ']]>' Char*)) [21] CDEnd ::= ']]>'
[ "Parse", "escaped", "pure", "raw", "content", ".", "[", "18", "]", "CDSect", "::", "=", "CDStart", "CData", "CDEnd", "[", "19", "]", "CDStart", "::", "=", "<!", "[", "CDATA", "[", "[", "20", "]", "Data", "::", "=", "(", "Char", "*", "-", "(", "Char", "*", "]]", ">", "Char", "*", "))", "[", "21", "]", "CDEnd", "::", "=", "]]", ">" ]
def parseCDSect(self): """Parse escaped pure raw content. [18] CDSect ::= CDStart CData CDEnd [19] CDStart ::= '<![CDATA[' [20] Data ::= (Char* - (Char* ']]>' Char*)) [21] CDEnd ::= ']]>' """ libxml2mod.xmlParseCDSect(self._o)
[ "def", "parseCDSect", "(", "self", ")", ":", "libxml2mod", ".", "xmlParseCDSect", "(", "self", ".", "_o", ")" ]
https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py#L5205-L5209
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Runtime/VART/vart/rnn-runner/apps/imdb_sentiment_detection/utils/hdf5_format.py
python
load_weights_from_hdf5_group
(f, layers)
Implements topological (order-based) weight loading. Arguments: f: A pointer to a HDF5 group. layers: a list of target layers. Raises: ValueError: in case of mismatch between provided layers and weights file.
Implements topological (order-based) weight loading.
[ "Implements", "topological", "(", "order", "-", "based", ")", "weight", "loading", "." ]
def load_weights_from_hdf5_group(f, layers): """Implements topological (order-based) weight loading. Arguments: f: A pointer to a HDF5 group. layers: a list of target layers. Raises: ValueError: in case of mismatch between provided layers and weights file. """ if 'keras_version' in f.attrs: original_keras_version = f.attrs['keras_version'] else: original_keras_version = '1' if 'backend' in f.attrs: original_backend = f.attrs['backend'] else: original_backend = None filtered_layers = [] for layer in layers: weights = _legacy_weights(layer) if weights: filtered_layers.append(layer) layer_names = load_attributes_from_hdf5_group(f, 'layer_names') filtered_layer_names = [] for name in layer_names: g = f[name] weight_names = load_attributes_from_hdf5_group(g, 'weight_names') if weight_names: filtered_layer_names.append(name) layer_names = filtered_layer_names if len(layer_names) != len(filtered_layers): raise ValueError('You are trying to load a weight file ' 'containing ' + str(len(layer_names)) + ' layers into a model with ' + str(len(filtered_layers)) + ' layers.') # We batch weight value assignments in a single backend call # which provides a speedup in TensorFlow. weight_value_tuples = [] for k, name in enumerate(layer_names): g = f[name] weight_names = load_attributes_from_hdf5_group(g, 'weight_names') weight_values = [np.asarray(g[weight_name]) for weight_name in weight_names] layer = filtered_layers[k] symbolic_weights = _legacy_weights(layer) weight_values = preprocess_weights_for_loading( layer, weight_values, original_keras_version, original_backend) if len(weight_values) != len(symbolic_weights): raise ValueError('Layer #' + str(k) + ' (named "' + layer.name + '" in the current model) was found to ' 'correspond to layer ' + name + ' in the save file. ' 'However the new layer ' + layer.name + ' expects ' + str(len(symbolic_weights)) + ' weights, but the saved weights have ' + str(len(weight_values)) + ' elements.') weight_value_tuples += zip(symbolic_weights, weight_values) K.batch_set_value(weight_value_tuples)
[ "def", "load_weights_from_hdf5_group", "(", "f", ",", "layers", ")", ":", "if", "'keras_version'", "in", "f", ".", "attrs", ":", "original_keras_version", "=", "f", ".", "attrs", "[", "'keras_version'", "]", "else", ":", "original_keras_version", "=", "'1'", "if", "'backend'", "in", "f", ".", "attrs", ":", "original_backend", "=", "f", ".", "attrs", "[", "'backend'", "]", "else", ":", "original_backend", "=", "None", "filtered_layers", "=", "[", "]", "for", "layer", "in", "layers", ":", "weights", "=", "_legacy_weights", "(", "layer", ")", "if", "weights", ":", "filtered_layers", ".", "append", "(", "layer", ")", "layer_names", "=", "load_attributes_from_hdf5_group", "(", "f", ",", "'layer_names'", ")", "filtered_layer_names", "=", "[", "]", "for", "name", "in", "layer_names", ":", "g", "=", "f", "[", "name", "]", "weight_names", "=", "load_attributes_from_hdf5_group", "(", "g", ",", "'weight_names'", ")", "if", "weight_names", ":", "filtered_layer_names", ".", "append", "(", "name", ")", "layer_names", "=", "filtered_layer_names", "if", "len", "(", "layer_names", ")", "!=", "len", "(", "filtered_layers", ")", ":", "raise", "ValueError", "(", "'You are trying to load a weight file '", "'containing '", "+", "str", "(", "len", "(", "layer_names", ")", ")", "+", "' layers into a model with '", "+", "str", "(", "len", "(", "filtered_layers", ")", ")", "+", "' layers.'", ")", "# We batch weight value assignments in a single backend call", "# which provides a speedup in TensorFlow.", "weight_value_tuples", "=", "[", "]", "for", "k", ",", "name", "in", "enumerate", "(", "layer_names", ")", ":", "g", "=", "f", "[", "name", "]", "weight_names", "=", "load_attributes_from_hdf5_group", "(", "g", ",", "'weight_names'", ")", "weight_values", "=", "[", "np", ".", "asarray", "(", "g", "[", "weight_name", "]", ")", "for", "weight_name", "in", "weight_names", "]", "layer", "=", "filtered_layers", "[", "k", "]", "symbolic_weights", "=", "_legacy_weights", "(", "layer", ")", "weight_values", "=", "preprocess_weights_for_loading", "(", "layer", ",", "weight_values", ",", "original_keras_version", ",", "original_backend", ")", "if", "len", "(", "weight_values", ")", "!=", "len", "(", "symbolic_weights", ")", ":", "raise", "ValueError", "(", "'Layer #'", "+", "str", "(", "k", ")", "+", "' (named \"'", "+", "layer", ".", "name", "+", "'\" in the current model) was found to '", "'correspond to layer '", "+", "name", "+", "' in the save file. '", "'However the new layer '", "+", "layer", ".", "name", "+", "' expects '", "+", "str", "(", "len", "(", "symbolic_weights", ")", ")", "+", "' weights, but the saved weights have '", "+", "str", "(", "len", "(", "weight_values", ")", ")", "+", "' elements.'", ")", "weight_value_tuples", "+=", "zip", "(", "symbolic_weights", ",", "weight_values", ")", "K", ".", "batch_set_value", "(", "weight_value_tuples", ")" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Runtime/VART/vart/rnn-runner/apps/imdb_sentiment_detection/utils/hdf5_format.py#L653-L713
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/ultimatelistctrl.py
python
UltimateListMainWindow.HideWindows
(self)
Hides the windows associated to the items. Used internally.
Hides the windows associated to the items. Used internally.
[ "Hides", "the", "windows", "associated", "to", "the", "items", ".", "Used", "internally", "." ]
def HideWindows(self): """ Hides the windows associated to the items. Used internally. """ for child in self._itemWithWindow: wnd = child.GetWindow() if wnd: wnd.Hide()
[ "def", "HideWindows", "(", "self", ")", ":", "for", "child", "in", "self", ".", "_itemWithWindow", ":", "wnd", "=", "child", ".", "GetWindow", "(", ")", "if", "wnd", ":", "wnd", ".", "Hide", "(", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/ultimatelistctrl.py#L7047-L7053
ivansafrin/Polycode
37a40fefe194ec7f6e9d1257f3bb3517b0a168bc
Bindings/Scripts/create_lua_library/CppHeaderParser3.py
python
is_namespace
(nameStack)
return False
Determines if a namespace is being specified
Determines if a namespace is being specified
[ "Determines", "if", "a", "namespace", "is", "being", "specified" ]
def is_namespace(nameStack): """Determines if a namespace is being specified""" if len(nameStack) == 0: return False if nameStack[0] == "namespace": return True return False
[ "def", "is_namespace", "(", "nameStack", ")", ":", "if", "len", "(", "nameStack", ")", "==", "0", ":", "return", "False", "if", "nameStack", "[", "0", "]", "==", "\"namespace\"", ":", "return", "True", "return", "False" ]
https://github.com/ivansafrin/Polycode/blob/37a40fefe194ec7f6e9d1257f3bb3517b0a168bc/Bindings/Scripts/create_lua_library/CppHeaderParser3.py#L201-L207
wyrover/book-code
7f4883d9030d553bc6bcfa3da685e34789839900
3rdparty/protobuf/python/google/protobuf/internal/python_message.py
python
_AddEqualsMethod
(message_descriptor, cls)
Helper for _AddMessageMethods().
Helper for _AddMessageMethods().
[ "Helper", "for", "_AddMessageMethods", "()", "." ]
def _AddEqualsMethod(message_descriptor, cls): """Helper for _AddMessageMethods().""" def __eq__(self, other): if (not isinstance(other, message_mod.Message) or other.DESCRIPTOR != self.DESCRIPTOR): return False if self is other: return True if self.DESCRIPTOR.full_name == _AnyFullTypeName: any_a = _InternalUnpackAny(self) any_b = _InternalUnpackAny(other) if any_a and any_b: return any_a == any_b if not self.ListFields() == other.ListFields(): return False # Sort unknown fields because their order shouldn't affect equality test. unknown_fields = list(self._unknown_fields) unknown_fields.sort() other_unknown_fields = list(other._unknown_fields) other_unknown_fields.sort() return unknown_fields == other_unknown_fields cls.__eq__ = __eq__
[ "def", "_AddEqualsMethod", "(", "message_descriptor", ",", "cls", ")", ":", "def", "__eq__", "(", "self", ",", "other", ")", ":", "if", "(", "not", "isinstance", "(", "other", ",", "message_mod", ".", "Message", ")", "or", "other", ".", "DESCRIPTOR", "!=", "self", ".", "DESCRIPTOR", ")", ":", "return", "False", "if", "self", "is", "other", ":", "return", "True", "if", "self", ".", "DESCRIPTOR", ".", "full_name", "==", "_AnyFullTypeName", ":", "any_a", "=", "_InternalUnpackAny", "(", "self", ")", "any_b", "=", "_InternalUnpackAny", "(", "other", ")", "if", "any_a", "and", "any_b", ":", "return", "any_a", "==", "any_b", "if", "not", "self", ".", "ListFields", "(", ")", "==", "other", ".", "ListFields", "(", ")", ":", "return", "False", "# Sort unknown fields because their order shouldn't affect equality test.", "unknown_fields", "=", "list", "(", "self", ".", "_unknown_fields", ")", "unknown_fields", ".", "sort", "(", ")", "other_unknown_fields", "=", "list", "(", "other", ".", "_unknown_fields", ")", "other_unknown_fields", ".", "sort", "(", ")", "return", "unknown_fields", "==", "other_unknown_fields", "cls", ".", "__eq__", "=", "__eq__" ]
https://github.com/wyrover/book-code/blob/7f4883d9030d553bc6bcfa3da685e34789839900/3rdparty/protobuf/python/google/protobuf/internal/python_message.py#L951-L978
microsoft/TSS.MSR
0f2516fca2cd9929c31d5450e39301c9bde43688
TSS.Py/src/TpmTypes.py
python
TPM2_PolicyGetDigest_REQUEST.__init__
(self, policySession = TPM_HANDLE())
This command returns the current policyDigest of the session. This command allows the TPM to be used to perform the actions required to pre-compute the authPolicy for an object. Attributes: policySession (TPM_HANDLE): Handle for the policy session Auth Index: None
This command returns the current policyDigest of the session. This command allows the TPM to be used to perform the actions required to pre-compute the authPolicy for an object.
[ "This", "command", "returns", "the", "current", "policyDigest", "of", "the", "session", ".", "This", "command", "allows", "the", "TPM", "to", "be", "used", "to", "perform", "the", "actions", "required", "to", "pre", "-", "compute", "the", "authPolicy", "for", "an", "object", "." ]
def __init__(self, policySession = TPM_HANDLE()): """ This command returns the current policyDigest of the session. This command allows the TPM to be used to perform the actions required to pre-compute the authPolicy for an object. Attributes: policySession (TPM_HANDLE): Handle for the policy session Auth Index: None """ self.policySession = policySession
[ "def", "__init__", "(", "self", ",", "policySession", "=", "TPM_HANDLE", "(", ")", ")", ":", "self", ".", "policySession", "=", "policySession" ]
https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L15029-L15038
smartdevicelink/sdl_core
68f082169e0a40fccd9eb0db3c83911c28870f07
tools/InterfaceGenerator/MsgVersionGenerate.py
python
store_data_to_file
(path_to_storage, data_for_storage)
Stores data with major and minor version to file generated_msg_version.h
Stores data with major and minor version to file generated_msg_version.h
[ "Stores", "data", "with", "major", "and", "minor", "version", "to", "file", "generated_msg_version", ".", "h" ]
def store_data_to_file(path_to_storage, data_for_storage): """Stores data with major and minor version to file generated_msg_version.h """ path_to_storage = path_to_storage + "/generated_msg_version.h" fh = open(path_to_storage, 'w') fh.write(data_for_storage) fh.close()
[ "def", "store_data_to_file", "(", "path_to_storage", ",", "data_for_storage", ")", ":", "path_to_storage", "=", "path_to_storage", "+", "\"/generated_msg_version.h\"", "fh", "=", "open", "(", "path_to_storage", ",", "'w'", ")", "fh", ".", "write", "(", "data_for_storage", ")", "fh", ".", "close", "(", ")" ]
https://github.com/smartdevicelink/sdl_core/blob/68f082169e0a40fccd9eb0db3c83911c28870f07/tools/InterfaceGenerator/MsgVersionGenerate.py#L43-L50
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/distutils/dist.py
python
DistributionMetadata.write_pkg_file
(self, file)
Write the PKG-INFO format data to a file object.
Write the PKG-INFO format data to a file object.
[ "Write", "the", "PKG", "-", "INFO", "format", "data", "to", "a", "file", "object", "." ]
def write_pkg_file(self, file): """Write the PKG-INFO format data to a file object. """ version = '1.0' if (self.provides or self.requires or self.obsoletes or self.classifiers or self.download_url): version = '1.1' file.write('Metadata-Version: %s\n' % version) file.write('Name: %s\n' % self.get_name()) file.write('Version: %s\n' % self.get_version()) file.write('Summary: %s\n' % self.get_description()) file.write('Home-page: %s\n' % self.get_url()) file.write('Author: %s\n' % self.get_contact()) file.write('Author-email: %s\n' % self.get_contact_email()) file.write('License: %s\n' % self.get_license()) if self.download_url: file.write('Download-URL: %s\n' % self.download_url) long_desc = rfc822_escape(self.get_long_description()) file.write('Description: %s\n' % long_desc) keywords = ','.join(self.get_keywords()) if keywords: file.write('Keywords: %s\n' % keywords) self._write_list(file, 'Platform', self.get_platforms()) self._write_list(file, 'Classifier', self.get_classifiers()) # PEP 314 self._write_list(file, 'Requires', self.get_requires()) self._write_list(file, 'Provides', self.get_provides()) self._write_list(file, 'Obsoletes', self.get_obsoletes())
[ "def", "write_pkg_file", "(", "self", ",", "file", ")", ":", "version", "=", "'1.0'", "if", "(", "self", ".", "provides", "or", "self", ".", "requires", "or", "self", ".", "obsoletes", "or", "self", ".", "classifiers", "or", "self", ".", "download_url", ")", ":", "version", "=", "'1.1'", "file", ".", "write", "(", "'Metadata-Version: %s\\n'", "%", "version", ")", "file", ".", "write", "(", "'Name: %s\\n'", "%", "self", ".", "get_name", "(", ")", ")", "file", ".", "write", "(", "'Version: %s\\n'", "%", "self", ".", "get_version", "(", ")", ")", "file", ".", "write", "(", "'Summary: %s\\n'", "%", "self", ".", "get_description", "(", ")", ")", "file", ".", "write", "(", "'Home-page: %s\\n'", "%", "self", ".", "get_url", "(", ")", ")", "file", ".", "write", "(", "'Author: %s\\n'", "%", "self", ".", "get_contact", "(", ")", ")", "file", ".", "write", "(", "'Author-email: %s\\n'", "%", "self", ".", "get_contact_email", "(", ")", ")", "file", ".", "write", "(", "'License: %s\\n'", "%", "self", ".", "get_license", "(", ")", ")", "if", "self", ".", "download_url", ":", "file", ".", "write", "(", "'Download-URL: %s\\n'", "%", "self", ".", "download_url", ")", "long_desc", "=", "rfc822_escape", "(", "self", ".", "get_long_description", "(", ")", ")", "file", ".", "write", "(", "'Description: %s\\n'", "%", "long_desc", ")", "keywords", "=", "','", ".", "join", "(", "self", ".", "get_keywords", "(", ")", ")", "if", "keywords", ":", "file", ".", "write", "(", "'Keywords: %s\\n'", "%", "keywords", ")", "self", ".", "_write_list", "(", "file", ",", "'Platform'", ",", "self", ".", "get_platforms", "(", ")", ")", "self", ".", "_write_list", "(", "file", ",", "'Classifier'", ",", "self", ".", "get_classifiers", "(", ")", ")", "# PEP 314", "self", ".", "_write_list", "(", "file", ",", "'Requires'", ",", "self", ".", "get_requires", "(", ")", ")", "self", ".", "_write_list", "(", "file", ",", "'Provides'", ",", "self", ".", "get_provides", "(", ")", ")", "self", ".", "_write_list", "(", "file", ",", "'Obsoletes'", ",", "self", ".", "get_obsoletes", "(", ")", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/distutils/dist.py#L1119-L1151
psi4/psi4
be533f7f426b6ccc263904e55122899b16663395
psi4/driver/qcdb/molpro2.py
python
psi4_list
()
return procedures['energy'].keys()
Return an array of Psi4 methods with energies.
Return an array of Psi4 methods with energies.
[ "Return", "an", "array", "of", "Psi4", "methods", "with", "energies", "." ]
def psi4_list(): """Return an array of Psi4 methods with energies. """ return procedures['energy'].keys()
[ "def", "psi4_list", "(", ")", ":", "return", "procedures", "[", "'energy'", "]", ".", "keys", "(", ")" ]
https://github.com/psi4/psi4/blob/be533f7f426b6ccc263904e55122899b16663395/psi4/driver/qcdb/molpro2.py#L577-L581
kamyu104/LeetCode-Solutions
77605708a927ea3b85aee5a479db733938c7c211
Python/fibonacci-number.py
python
Solution.fib
(self, N)
return matrix_mult([[1, 0]], matrix_expo(T, N))[0][1]
:type N: int :rtype: int
:type N: int :rtype: int
[ ":", "type", "N", ":", "int", ":", "rtype", ":", "int" ]
def fib(self, N): """ :type N: int :rtype: int """ def matrix_expo(A, K): result = [[int(i==j) for j in xrange(len(A))] \ for i in xrange(len(A))] while K: if K % 2: result = matrix_mult(result, A) A = matrix_mult(A, A) K /= 2 return result def matrix_mult(A, B): ZB = zip(*B) return [[sum(a*b for a, b in itertools.izip(row, col)) \ for col in ZB] for row in A] T = [[1, 1], [1, 0]] return matrix_mult([[1, 0]], matrix_expo(T, N))[0][1]
[ "def", "fib", "(", "self", ",", "N", ")", ":", "def", "matrix_expo", "(", "A", ",", "K", ")", ":", "result", "=", "[", "[", "int", "(", "i", "==", "j", ")", "for", "j", "in", "xrange", "(", "len", "(", "A", ")", ")", "]", "for", "i", "in", "xrange", "(", "len", "(", "A", ")", ")", "]", "while", "K", ":", "if", "K", "%", "2", ":", "result", "=", "matrix_mult", "(", "result", ",", "A", ")", "A", "=", "matrix_mult", "(", "A", ",", "A", ")", "K", "/=", "2", "return", "result", "def", "matrix_mult", "(", "A", ",", "B", ")", ":", "ZB", "=", "zip", "(", "*", "B", ")", "return", "[", "[", "sum", "(", "a", "*", "b", "for", "a", ",", "b", "in", "itertools", ".", "izip", "(", "row", ",", "col", ")", ")", "for", "col", "in", "ZB", "]", "for", "row", "in", "A", "]", "T", "=", "[", "[", "1", ",", "1", "]", ",", "[", "1", ",", "0", "]", "]", "return", "matrix_mult", "(", "[", "[", "1", ",", "0", "]", "]", ",", "matrix_expo", "(", "T", ",", "N", ")", ")", "[", "0", "]", "[", "1", "]" ]
https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/fibonacci-number.py#L8-L30
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/ebmlib/fileutil.py
python
GetPathName
(path)
return os.path.split(path)[0]
Gets the path minus filename @param path: full path to get base of
Gets the path minus filename @param path: full path to get base of
[ "Gets", "the", "path", "minus", "filename", "@param", "path", ":", "full", "path", "to", "get", "base", "of" ]
def GetPathName(path): """Gets the path minus filename @param path: full path to get base of """ return os.path.split(path)[0]
[ "def", "GetPathName", "(", "path", ")", ":", "return", "os", ".", "path", ".", "split", "(", "path", ")", "[", "0", "]" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/ebmlib/fileutil.py#L186-L191
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/ops/composite/multitype_ops/negative_impl.py
python
_neg_scalar
(x)
return F.scalar_usub(x)
Returns the negative value of scalar x. Outputs: Number, negative value of x.
Returns the negative value of scalar x.
[ "Returns", "the", "negative", "value", "of", "scalar", "x", "." ]
def _neg_scalar(x): """ Returns the negative value of scalar x. Outputs: Number, negative value of x. """ return F.scalar_usub(x)
[ "def", "_neg_scalar", "(", "x", ")", ":", "return", "F", ".", "scalar_usub", "(", "x", ")" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/composite/multitype_ops/negative_impl.py#L30-L37
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/aui.py
python
AuiPaneInfo.HasMinimizeButton
(*args, **kwargs)
return _aui.AuiPaneInfo_HasMinimizeButton(*args, **kwargs)
HasMinimizeButton(self) -> bool
HasMinimizeButton(self) -> bool
[ "HasMinimizeButton", "(", "self", ")", "-", ">", "bool" ]
def HasMinimizeButton(*args, **kwargs): """HasMinimizeButton(self) -> bool""" return _aui.AuiPaneInfo_HasMinimizeButton(*args, **kwargs)
[ "def", "HasMinimizeButton", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_aui", ".", "AuiPaneInfo_HasMinimizeButton", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/aui.py#L321-L323
okex/V3-Open-API-SDK
c5abb0db7e2287718e0055e17e57672ce0ec7fd9
okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/urllib3/request.py
python
RequestMethods.request
(self, method, url, fields=None, headers=None, **urlopen_kw)
Make a request using :meth:`urlopen` with the appropriate encoding of ``fields`` based on the ``method`` used. This is a convenience method that requires the least amount of manual effort. It can be used in most situations, while still having the option to drop down to more specific methods when necessary, such as :meth:`request_encode_url`, :meth:`request_encode_body`, or even the lowest level :meth:`urlopen`.
Make a request using :meth:`urlopen` with the appropriate encoding of ``fields`` based on the ``method`` used.
[ "Make", "a", "request", "using", ":", "meth", ":", "urlopen", "with", "the", "appropriate", "encoding", "of", "fields", "based", "on", "the", "method", "used", "." ]
def request(self, method, url, fields=None, headers=None, **urlopen_kw): """ Make a request using :meth:`urlopen` with the appropriate encoding of ``fields`` based on the ``method`` used. This is a convenience method that requires the least amount of manual effort. It can be used in most situations, while still having the option to drop down to more specific methods when necessary, such as :meth:`request_encode_url`, :meth:`request_encode_body`, or even the lowest level :meth:`urlopen`. """ method = method.upper() urlopen_kw['request_url'] = url if method in self._encode_url_methods: return self.request_encode_url(method, url, fields=fields, headers=headers, **urlopen_kw) else: return self.request_encode_body(method, url, fields=fields, headers=headers, **urlopen_kw)
[ "def", "request", "(", "self", ",", "method", ",", "url", ",", "fields", "=", "None", ",", "headers", "=", "None", ",", "*", "*", "urlopen_kw", ")", ":", "method", "=", "method", ".", "upper", "(", ")", "urlopen_kw", "[", "'request_url'", "]", "=", "url", "if", "method", "in", "self", ".", "_encode_url_methods", ":", "return", "self", ".", "request_encode_url", "(", "method", ",", "url", ",", "fields", "=", "fields", ",", "headers", "=", "headers", ",", "*", "*", "urlopen_kw", ")", "else", ":", "return", "self", ".", "request_encode_body", "(", "method", ",", "url", ",", "fields", "=", "fields", ",", "headers", "=", "headers", ",", "*", "*", "urlopen_kw", ")" ]
https://github.com/okex/V3-Open-API-SDK/blob/c5abb0db7e2287718e0055e17e57672ce0ec7fd9/okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/urllib3/request.py#L50-L72
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_core.py
python
Event.GetEventCategory
(*args, **kwargs)
return _core_.Event_GetEventCategory(*args, **kwargs)
GetEventCategory(self) -> int
GetEventCategory(self) -> int
[ "GetEventCategory", "(", "self", ")", "-", ">", "int" ]
def GetEventCategory(*args, **kwargs): """GetEventCategory(self) -> int""" return _core_.Event_GetEventCategory(*args, **kwargs)
[ "def", "GetEventCategory", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "Event_GetEventCategory", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L5034-L5036
SpenceKonde/megaTinyCore
1c4a70b18a149fe6bcb551dfa6db11ca50b8997b
megaavr/tools/libs/serial/urlhandler/protocol_alt.py
python
serial_class_for_url
(url)
return (''.join([parts.netloc, parts.path]), cls)
extract host and port from an URL string
extract host and port from an URL string
[ "extract", "host", "and", "port", "from", "an", "URL", "string" ]
def serial_class_for_url(url): """extract host and port from an URL string""" parts = urlparse.urlsplit(url) if parts.scheme != 'alt': raise serial.SerialException( 'expected a string in the form "alt://port[?option[=value][&option[=value]]]": ' 'not starting with alt:// ({!r})'.format(parts.scheme)) class_name = 'Serial' try: for option, values in urlparse.parse_qs(parts.query, True).items(): if option == 'class': class_name = values[0] else: raise ValueError('unknown option: {!r}'.format(option)) except ValueError as e: raise serial.SerialException( 'expected a string in the form ' '"alt://port[?option[=value][&option[=value]]]": {!r}'.format(e)) if not hasattr(serial, class_name): raise ValueError('unknown class: {!r}'.format(class_name)) cls = getattr(serial, class_name) if not issubclass(cls, serial.Serial): raise ValueError('class {!r} is not an instance of Serial'.format(class_name)) return (''.join([parts.netloc, parts.path]), cls)
[ "def", "serial_class_for_url", "(", "url", ")", ":", "parts", "=", "urlparse", ".", "urlsplit", "(", "url", ")", "if", "parts", ".", "scheme", "!=", "'alt'", ":", "raise", "serial", ".", "SerialException", "(", "'expected a string in the form \"alt://port[?option[=value][&option[=value]]]\": '", "'not starting with alt:// ({!r})'", ".", "format", "(", "parts", ".", "scheme", ")", ")", "class_name", "=", "'Serial'", "try", ":", "for", "option", ",", "values", "in", "urlparse", ".", "parse_qs", "(", "parts", ".", "query", ",", "True", ")", ".", "items", "(", ")", ":", "if", "option", "==", "'class'", ":", "class_name", "=", "values", "[", "0", "]", "else", ":", "raise", "ValueError", "(", "'unknown option: {!r}'", ".", "format", "(", "option", ")", ")", "except", "ValueError", "as", "e", ":", "raise", "serial", ".", "SerialException", "(", "'expected a string in the form '", "'\"alt://port[?option[=value][&option[=value]]]\": {!r}'", ".", "format", "(", "e", ")", ")", "if", "not", "hasattr", "(", "serial", ",", "class_name", ")", ":", "raise", "ValueError", "(", "'unknown class: {!r}'", ".", "format", "(", "class_name", ")", ")", "cls", "=", "getattr", "(", "serial", ",", "class_name", ")", "if", "not", "issubclass", "(", "cls", ",", "serial", ".", "Serial", ")", ":", "raise", "ValueError", "(", "'class {!r} is not an instance of Serial'", ".", "format", "(", "class_name", ")", ")", "return", "(", "''", ".", "join", "(", "[", "parts", ".", "netloc", ",", "parts", ".", "path", "]", ")", ",", "cls", ")" ]
https://github.com/SpenceKonde/megaTinyCore/blob/1c4a70b18a149fe6bcb551dfa6db11ca50b8997b/megaavr/tools/libs/serial/urlhandler/protocol_alt.py#L27-L50
hpi-xnor/BMXNet-v2
af2b1859eafc5c721b1397cef02f946aaf2ce20d
python/mxnet/ndarray/ndarray.py
python
NDArray._fresh_grad
(self)
return out.value
Whether this array's corresponding gradient array (registered via `autograd.mark_variables`) has been updated by `autograd.backward` since last reset. `_fresh_grad` need to be manually set to False after consuming gradient (usually after updating this array).
Whether this array's corresponding gradient array (registered via `autograd.mark_variables`) has been updated by `autograd.backward` since last reset.
[ "Whether", "this", "array", "s", "corresponding", "gradient", "array", "(", "registered", "via", "autograd", ".", "mark_variables", ")", "has", "been", "updated", "by", "autograd", ".", "backward", "since", "last", "reset", "." ]
def _fresh_grad(self): """Whether this array's corresponding gradient array (registered via `autograd.mark_variables`) has been updated by `autograd.backward` since last reset. `_fresh_grad` need to be manually set to False after consuming gradient (usually after updating this array). """ out = ctypes.c_int() check_call(_LIB.MXNDArrayGetGradState(self.handle, ctypes.byref(out))) return out.value
[ "def", "_fresh_grad", "(", "self", ")", ":", "out", "=", "ctypes", ".", "c_int", "(", ")", "check_call", "(", "_LIB", ".", "MXNDArrayGetGradState", "(", "self", ".", "handle", ",", "ctypes", ".", "byref", "(", "out", ")", ")", ")", "return", "out", ".", "value" ]
https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/python/mxnet/ndarray/ndarray.py#L1982-L1993
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/RNN/rnn_quantizer/pytorch_binding/pytorch_nndct/parse/parser.py
python
TorchParser._convert_blob_tensor_type
(graph)
r"""convert torch tensor info to nndct tensor info
r"""convert torch tensor info to nndct tensor info
[ "r", "convert", "torch", "tensor", "info", "to", "nndct", "tensor", "info" ]
def _convert_blob_tensor_type(graph): r"""convert torch tensor info to nndct tensor info""" for blob_tensor in graph.tensors: # tensor_util.convert_blob_tensor_format(blob_tensor, # tensor_util.FrameworkType.TORCH, # tensor_util.FrameworkType.NNDCT) blob_tensor.dtype = convert_dtype(blob_tensor.dtype)
[ "def", "_convert_blob_tensor_type", "(", "graph", ")", ":", "for", "blob_tensor", "in", "graph", ".", "tensors", ":", "# tensor_util.convert_blob_tensor_format(blob_tensor,", "# tensor_util.FrameworkType.TORCH,", "# tensor_util.FrameworkType.NNDCT)", "blob_tensor", ".", "dtype", "=", "convert_dtype", "(", "blob_tensor", ".", "dtype", ")" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/RNN/rnn_quantizer/pytorch_binding/pytorch_nndct/parse/parser.py#L145-L151
MegEngine/MegEngine
ce9ad07a27ec909fb8db4dd67943d24ba98fb93a
imperative/python/megengine/core/tensor/array_method.py
python
ArrayMethodMixin.sum
(self, axis=None, keepdims: bool = False)
return _reduce("sum")(self, axis, keepdims)
r"""Returns the sum of each row of the input tensor in the given dimension ``axis``. If ``axis`` is a list of axises, reduce over all of them. If ``keepdims`` is ``True``, the shape of output tensor is the same as the input tensor, except in the dimension(s) ``axis`` where it is of size 1. Otherwise, ``axis`` is squeezed (see :func:`~.squeeze`). Args: axis: the dimension or dimensions to reduce. keepdims: whether the output tensor has ndim retained or not. Returns: output tensor. Examples: .. testcode:: from megengine import tensor a = tensor([False, True, True, False]) b = tensor([1.0, 2.0, 3.0, 4.0]) print(a.sum().numpy()) print(b.sum().numpy()) Outputs: .. testoutput:: 2 10.0
r"""Returns the sum of each row of the input tensor in the given dimension ``axis``.
[ "r", "Returns", "the", "sum", "of", "each", "row", "of", "the", "input", "tensor", "in", "the", "given", "dimension", "axis", "." ]
def sum(self, axis=None, keepdims: bool = False): r"""Returns the sum of each row of the input tensor in the given dimension ``axis``. If ``axis`` is a list of axises, reduce over all of them. If ``keepdims`` is ``True``, the shape of output tensor is the same as the input tensor, except in the dimension(s) ``axis`` where it is of size 1. Otherwise, ``axis`` is squeezed (see :func:`~.squeeze`). Args: axis: the dimension or dimensions to reduce. keepdims: whether the output tensor has ndim retained or not. Returns: output tensor. Examples: .. testcode:: from megengine import tensor a = tensor([False, True, True, False]) b = tensor([1.0, 2.0, 3.0, 4.0]) print(a.sum().numpy()) print(b.sum().numpy()) Outputs: .. testoutput:: 2 10.0 """ return _reduce("sum")(self, axis, keepdims)
[ "def", "sum", "(", "self", ",", "axis", "=", "None", ",", "keepdims", ":", "bool", "=", "False", ")", ":", "return", "_reduce", "(", "\"sum\"", ")", "(", "self", ",", "axis", ",", "keepdims", ")" ]
https://github.com/MegEngine/MegEngine/blob/ce9ad07a27ec909fb8db4dd67943d24ba98fb93a/imperative/python/megengine/core/tensor/array_method.py#L490-L521
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/keras/backend.py
python
depthwise_conv2d
(x, depthwise_kernel, strides=(1, 1), padding='valid', data_format=None, dilation_rate=(1, 1))
return x
2D convolution with separable filters. Args: x: input tensor depthwise_kernel: convolution kernel for the depthwise convolution. strides: strides tuple (length 2). padding: string, `"same"` or `"valid"`. data_format: string, `"channels_last"` or `"channels_first"`. dilation_rate: tuple of integers, dilation rates for the separable convolution. Returns: Output tensor. Raises: ValueError: if `data_format` is neither `channels_last` or `channels_first`.
2D convolution with separable filters.
[ "2D", "convolution", "with", "separable", "filters", "." ]
def depthwise_conv2d(x, depthwise_kernel, strides=(1, 1), padding='valid', data_format=None, dilation_rate=(1, 1)): """2D convolution with separable filters. Args: x: input tensor depthwise_kernel: convolution kernel for the depthwise convolution. strides: strides tuple (length 2). padding: string, `"same"` or `"valid"`. data_format: string, `"channels_last"` or `"channels_first"`. dilation_rate: tuple of integers, dilation rates for the separable convolution. Returns: Output tensor. Raises: ValueError: if `data_format` is neither `channels_last` or `channels_first`. """ if data_format is None: data_format = image_data_format() if data_format not in {'channels_first', 'channels_last'}: raise ValueError('Unknown data_format: ' + str(data_format)) x, tf_data_format = _preprocess_conv2d_input(x, data_format) padding = _preprocess_padding(padding) if tf_data_format == 'NHWC': strides = (1,) + strides + (1,) else: strides = (1, 1) + strides x = nn.depthwise_conv2d( x, depthwise_kernel, strides=strides, padding=padding, rate=dilation_rate, data_format=tf_data_format) if data_format == 'channels_first' and tf_data_format == 'NHWC': x = array_ops.transpose(x, (0, 3, 1, 2)) # NHWC -> NCHW return x
[ "def", "depthwise_conv2d", "(", "x", ",", "depthwise_kernel", ",", "strides", "=", "(", "1", ",", "1", ")", ",", "padding", "=", "'valid'", ",", "data_format", "=", "None", ",", "dilation_rate", "=", "(", "1", ",", "1", ")", ")", ":", "if", "data_format", "is", "None", ":", "data_format", "=", "image_data_format", "(", ")", "if", "data_format", "not", "in", "{", "'channels_first'", ",", "'channels_last'", "}", ":", "raise", "ValueError", "(", "'Unknown data_format: '", "+", "str", "(", "data_format", ")", ")", "x", ",", "tf_data_format", "=", "_preprocess_conv2d_input", "(", "x", ",", "data_format", ")", "padding", "=", "_preprocess_padding", "(", "padding", ")", "if", "tf_data_format", "==", "'NHWC'", ":", "strides", "=", "(", "1", ",", ")", "+", "strides", "+", "(", "1", ",", ")", "else", ":", "strides", "=", "(", "1", ",", "1", ")", "+", "strides", "x", "=", "nn", ".", "depthwise_conv2d", "(", "x", ",", "depthwise_kernel", ",", "strides", "=", "strides", ",", "padding", "=", "padding", ",", "rate", "=", "dilation_rate", ",", "data_format", "=", "tf_data_format", ")", "if", "data_format", "==", "'channels_first'", "and", "tf_data_format", "==", "'NHWC'", ":", "x", "=", "array_ops", ".", "transpose", "(", "x", ",", "(", "0", ",", "3", ",", "1", ",", "2", ")", ")", "# NHWC -> NCHW", "return", "x" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/keras/backend.py#L5552-L5597