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
AcademySoftwareFoundation/OpenShadingLanguage
b816c21b1901beba3dec53cc229d381f80882171
doc/build_install/windows/build_osl.py
python
CopyFiles
(context, src, dest)
Copy files like shutil.copy, but src may be a glob pattern.
Copy files like shutil.copy, but src may be a glob pattern.
[ "Copy", "files", "like", "shutil", ".", "copy", "but", "src", "may", "be", "a", "glob", "pattern", "." ]
def CopyFiles(context, src, dest): """Copy files like shutil.copy, but src may be a glob pattern.""" filesToCopy = glob.glob(src) if not filesToCopy: raise RuntimeError("File(s) to copy {src} not found".format(src=src)) instDestDir = os.path.join(context.instDir, dest) for f in filesToCopy: PrintCommandOutput( "Copying {file} to {destDir}\n".format(file=f, destDir=instDestDir) ) shutil.copy(f, instDestDir)
[ "def", "CopyFiles", "(", "context", ",", "src", ",", "dest", ")", ":", "filesToCopy", "=", "glob", ".", "glob", "(", "src", ")", "if", "not", "filesToCopy", ":", "raise", "RuntimeError", "(", "\"File(s) to copy {src} not found\"", ".", "format", "(", "src", ...
https://github.com/AcademySoftwareFoundation/OpenShadingLanguage/blob/b816c21b1901beba3dec53cc229d381f80882171/doc/build_install/windows/build_osl.py#L336-L347
deepmind/open_spiel
4ca53bea32bb2875c7385d215424048ae92f78c8
open_spiel/python/algorithms/exploitability_descent.py
python
Solver.step
(self, session, learning_rate)
return nash_conv
Takes a single exploitability descent step.
Takes a single exploitability descent step.
[ "Takes", "a", "single", "exploitability", "descent", "step", "." ]
def step(self, session, learning_rate): """Takes a single exploitability descent step.""" _, nash_conv = session.run([self._optimizer_step, self._nash_conv], feed_dict={self._learning_rate: learning_rate}) return nash_conv
[ "def", "step", "(", "self", ",", "session", ",", "learning_rate", ")", ":", "_", ",", "nash_conv", "=", "session", ".", "run", "(", "[", "self", ".", "_optimizer_step", ",", "self", ".", "_nash_conv", "]", ",", "feed_dict", "=", "{", "self", ".", "_l...
https://github.com/deepmind/open_spiel/blob/4ca53bea32bb2875c7385d215424048ae92f78c8/open_spiel/python/algorithms/exploitability_descent.py#L154-L158
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/setuptools/_vendor/pyparsing.py
python
ParseResults.asDict
( self )
return dict((k,toItem(v)) for k,v in item_fn())
Returns the named parse results as a nested dictionary. Example:: integer = Word(nums) date_str = integer("year") + '/' + integer("month") + '/' + integer("day") result = date_str.parseString('12/31/1999') print(type(result), repr(result)) # -> <class 'pyparsing.ParseResults'> (['12', '/', '31', '/', '1999'], {'day': [('1999', 4)], 'year': [('12', 0)], 'month': [('31', 2)]}) result_dict = result.asDict() print(type(result_dict), repr(result_dict)) # -> <class 'dict'> {'day': '1999', 'year': '12', 'month': '31'} # even though a ParseResults supports dict-like access, sometime you just need to have a dict import json print(json.dumps(result)) # -> Exception: TypeError: ... is not JSON serializable print(json.dumps(result.asDict())) # -> {"month": "31", "day": "1999", "year": "12"}
Returns the named parse results as a nested dictionary.
[ "Returns", "the", "named", "parse", "results", "as", "a", "nested", "dictionary", "." ]
def asDict( self ): """ Returns the named parse results as a nested dictionary. Example:: integer = Word(nums) date_str = integer("year") + '/' + integer("month") + '/' + integer("day") result = date_str.parseString('12/31/1999') print(type(result), repr(result)) # -> <class 'pyparsing.ParseResults'> (['12', '/', '31', '/', '1999'], {'day': [('1999', 4)], 'year': [('12', 0)], 'month': [('31', 2)]}) result_dict = result.asDict() print(type(result_dict), repr(result_dict)) # -> <class 'dict'> {'day': '1999', 'year': '12', 'month': '31'} # even though a ParseResults supports dict-like access, sometime you just need to have a dict import json print(json.dumps(result)) # -> Exception: TypeError: ... is not JSON serializable print(json.dumps(result.asDict())) # -> {"month": "31", "day": "1999", "year": "12"} """ if PY_3: item_fn = self.items else: item_fn = self.iteritems def toItem(obj): if isinstance(obj, ParseResults): if obj.haskeys(): return obj.asDict() else: return [toItem(v) for v in obj] else: return obj return dict((k,toItem(v)) for k,v in item_fn())
[ "def", "asDict", "(", "self", ")", ":", "if", "PY_3", ":", "item_fn", "=", "self", ".", "items", "else", ":", "item_fn", "=", "self", ".", "iteritems", "def", "toItem", "(", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "ParseResults", ")", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/setuptools/_vendor/pyparsing.py#L720-L753
apple/swift-lldb
d74be846ef3e62de946df343e8c234bde93a8912
scripts/Python/static-binding/lldb.py
python
SBProcess.Kill
(self)
return _lldb.SBProcess_Kill(self)
Kill(SBProcess self) -> SBError
Kill(SBProcess self) -> SBError
[ "Kill", "(", "SBProcess", "self", ")", "-", ">", "SBError" ]
def Kill(self): """Kill(SBProcess self) -> SBError""" return _lldb.SBProcess_Kill(self)
[ "def", "Kill", "(", "self", ")", ":", "return", "_lldb", ".", "SBProcess_Kill", "(", "self", ")" ]
https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L8523-L8525
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/protobuf/py2/google/protobuf/json_format.py
python
_ConvertFloat
(value, field)
Convert an floating point number.
Convert an floating point number.
[ "Convert", "an", "floating", "point", "number", "." ]
def _ConvertFloat(value, field): """Convert an floating point number.""" if isinstance(value, float): if math.isnan(value): raise ParseError('Couldn\'t parse NaN, use quoted "NaN" instead.') if math.isinf(value): if value > 0: raise ParseError('Couldn\'t parse Infinity or value too large, ' 'use quoted "Infinity" instead.') else: raise ParseError('Couldn\'t parse -Infinity or value too small, ' 'use quoted "-Infinity" instead.') if field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_FLOAT: # pylint: disable=protected-access if value > type_checkers._FLOAT_MAX: raise ParseError('Float value too large') # pylint: disable=protected-access if value < type_checkers._FLOAT_MIN: raise ParseError('Float value too small') if value == 'nan': raise ParseError('Couldn\'t parse float "nan", use "NaN" instead.') try: # Assume Python compatible syntax. return float(value) except ValueError: # Check alternative spellings. if value == _NEG_INFINITY: return float('-inf') elif value == _INFINITY: return float('inf') elif value == _NAN: return float('nan') else: raise ParseError('Couldn\'t parse float: {0}.'.format(value))
[ "def", "_ConvertFloat", "(", "value", ",", "field", ")", ":", "if", "isinstance", "(", "value", ",", "float", ")", ":", "if", "math", ".", "isnan", "(", "value", ")", ":", "raise", "ParseError", "(", "'Couldn\\'t parse NaN, use quoted \"NaN\" instead.'", ")", ...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/protobuf/py2/google/protobuf/json_format.py#L789-L822
gnuradio/gnuradio
09c3c4fa4bfb1a02caac74cb5334dfe065391e3b
gr-digital/python/digital/qa_header_payload_demux.py
python
qa_header_payload_demux.test_003_t
(self)
Like test 1, but twice, plus one fail
Like test 1, but twice, plus one fail
[ "Like", "test", "1", "but", "twice", "plus", "one", "fail" ]
def test_003_t(self): """ Like test 1, but twice, plus one fail """ # Tx Data n_zeros = 5 header = [1, 2, 3] header_fail = [-1, -2, -4] # Contents don't really matter payload1 = list(range(5, 20)) payload2 = [42, ] sampling_rate = 2 data_signal = [0, ] * n_zeros + header + payload1 trigger_signal = [0, ] * len(data_signal) * 2 trigger_signal[n_zeros] = 1 trigger_signal[len(data_signal)] = 1 trigger_signal[len(data_signal) + len(header_fail) + n_zeros] = 1 print("Triggers at: {0} {1} {2}".format( n_zeros, len(data_signal), len(data_signal) + len(header_fail) + n_zeros)) tx_signal = data_signal + \ header_fail + [0, ] * n_zeros + \ header + payload2 + [0, ] * 1000 # Timing tag: This is preserved and updated: timing_tag = make_tag('rx_time', (0, 0), 0) # Rx freq tags: rx_freq_tag1 = make_tag('rx_freq', 1.0, 0) rx_freq_tag2 = make_tag('rx_freq', 1.5, 29) rx_freq_tag3 = make_tag('rx_freq', 2.0, 30) # Flow graph data_src = blocks.vector_source_f( tx_signal, False, tags=(timing_tag, rx_freq_tag1, rx_freq_tag2, rx_freq_tag3) ) trigger_src = blocks.vector_source_b(trigger_signal, False) hpd = digital.header_payload_demux( header_len=len(header), items_per_symbol=1, guard_interval=0, length_tag_key="frame_len", trigger_tag_key="detect", output_symbols=False, itemsize=gr.sizeof_float, timing_tag_key='rx_time', samp_rate=sampling_rate, special_tags=('rx_freq',), ) # extra system port defined for you self.assertEqual(pmt.length(hpd.message_ports_in()), 2) header_sink = blocks.vector_sink_f() payload_sink = blocks.vector_sink_f() self.tb.connect(data_src, (hpd, 0)) self.tb.connect(trigger_src, (hpd, 1)) self.tb.connect((hpd, 0), header_sink) self.tb.connect((hpd, 1), payload_sink) self.tb.start() time.sleep(.2) # Need this, otherwise, the next message is ignored hpd.to_basic_block()._post( pmt.intern('header_data'), pmt.from_long(len(payload1)) ) while len(payload_sink.data()) < len(payload1): time.sleep(.2) hpd.to_basic_block()._post( pmt.intern('header_data'), pmt.PMT_F ) # This next command is a bit of a showstopper, but there's no condition to check upon # to see if the previous msg handling is finished time.sleep(.7) hpd.to_basic_block()._post( pmt.intern('header_data'), pmt.from_long(len(payload2)) ) while len(payload_sink.data()) < len(payload1) + len(payload2): time.sleep(.2) self.tb.stop() self.tb.wait() # Signal description: # 0: 5 zeros # 5: header 1 # 8: payload 1 (length: 15) # 23: header 2 (fail) # 26: 5 zeros # 31: header 3 # 34: payload 2 (length 1) # 35: 1000 zeros self.assertEqual( header_sink.data(), list( header + header_fail + header)) self.assertEqual(payload_sink.data(), payload1 + payload2) tags_payload = [gr.tag_to_python(x) for x in payload_sink.tags()] tags_payload = sorted([(x.offset, x.key, x.value) for x in tags_payload]) tags_expected_payload = [ (0, 'frame_len', len(payload1)), (len(payload1), 'frame_len', len(payload2)), ] tags_header = [gr.tag_to_python(x) for x in header_sink.tags()] tags_header = sorted([(x.offset, x.key, x.value) for x in tags_header]) tags_expected_header = [ (0, 'rx_freq', 1.0), # Hard coded time value :( Is n_zeros/sampling_rate (0, 'rx_time', (2, 0.5)), (len(header), 'rx_freq', 1.0), # Hard coded time value :(. See above. (len(header), 'rx_time', (11, .5)), (2 * len(header), 'rx_freq', 2.0), # Hard coded time value :(. See above. (2 * len(header), 'rx_time', (15, .5)), ] self.assertEqual(tags_header, tags_expected_header) self.assertEqual(tags_payload, tags_expected_payload)
[ "def", "test_003_t", "(", "self", ")", ":", "# Tx Data", "n_zeros", "=", "5", "header", "=", "[", "1", ",", "2", ",", "3", "]", "header_fail", "=", "[", "-", "1", ",", "-", "2", ",", "-", "4", "]", "# Contents don't really matter", "payload1", "=", ...
https://github.com/gnuradio/gnuradio/blob/09c3c4fa4bfb1a02caac74cb5334dfe065391e3b/gr-digital/python/digital/qa_header_payload_demux.py#L454-L566
kamyu104/LeetCode-Solutions
77605708a927ea3b85aee5a479db733938c7c211
Python/binary-watch.py
python
Solution.readBinaryWatch
(self, num)
return ['%d:%02d' % (h, m) for h in xrange(12) for m in xrange(60) if bit_count(h) + bit_count(m) == num]
:type num: int :rtype: List[str]
:type num: int :rtype: List[str]
[ ":", "type", "num", ":", "int", ":", "rtype", ":", "List", "[", "str", "]" ]
def readBinaryWatch(self, num): """ :type num: int :rtype: List[str] """ def bit_count(bits): count = 0 while bits: bits &= bits-1 count += 1 return count return ['%d:%02d' % (h, m) for h in xrange(12) for m in xrange(60) if bit_count(h) + bit_count(m) == num]
[ "def", "readBinaryWatch", "(", "self", ",", "num", ")", ":", "def", "bit_count", "(", "bits", ")", ":", "count", "=", "0", "while", "bits", ":", "bits", "&=", "bits", "-", "1", "count", "+=", "1", "return", "count", "return", "[", "'%d:%02d'", "%", ...
https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/binary-watch.py#L6-L19
vtraag/louvain-igraph
124ea1be49ee74eec2eaca8006599d7fc5560db6
src/louvain/VertexPartition.py
python
RBConfigurationVertexPartition.__init__
(self, graph, initial_membership=None, weights=None, resolution_parameter=1.0)
Parameters ---------- graph : :class:`ig.Graph` Graph to define the partition on. initial_membership : list of int Initial membership for the partition. If :obj:`None` then defaults to a singleton partition. weights : list of double, or edge attribute Weights of edges. Can be either an iterable or an edge attribute. resolution_parameter : double Resolution parameter.
Parameters ---------- graph : :class:`ig.Graph` Graph to define the partition on.
[ "Parameters", "----------", "graph", ":", ":", "class", ":", "ig", ".", "Graph", "Graph", "to", "define", "the", "partition", "on", "." ]
def __init__(self, graph, initial_membership=None, weights=None, resolution_parameter=1.0): """ Parameters ---------- graph : :class:`ig.Graph` Graph to define the partition on. initial_membership : list of int Initial membership for the partition. If :obj:`None` then defaults to a singleton partition. weights : list of double, or edge attribute Weights of edges. Can be either an iterable or an edge attribute. resolution_parameter : double Resolution parameter. """ if initial_membership is not None: initial_membership = list(initial_membership) super(RBConfigurationVertexPartition, self).__init__(graph, initial_membership) pygraph_t = _get_py_capsule(graph) if weights is not None: if isinstance(weights, str): weights = graph.es[weights] else: # Make sure it is a list weights = list(weights) self._partition = _c_louvain._new_RBConfigurationVertexPartition(pygraph_t, initial_membership, weights, resolution_parameter) self._update_internal_membership()
[ "def", "__init__", "(", "self", ",", "graph", ",", "initial_membership", "=", "None", ",", "weights", "=", "None", ",", "resolution_parameter", "=", "1.0", ")", ":", "if", "initial_membership", "is", "not", "None", ":", "initial_membership", "=", "list", "("...
https://github.com/vtraag/louvain-igraph/blob/124ea1be49ee74eec2eaca8006599d7fc5560db6/src/louvain/VertexPartition.py#L738-L771
Tencent/CMONGO
c40380caa14e05509f46993aa8b8da966b09b0b5
src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Tool/ar.py
python
generate
(env)
Add Builders and construction variables for ar to an Environment.
Add Builders and construction variables for ar to an Environment.
[ "Add", "Builders", "and", "construction", "variables", "for", "ar", "to", "an", "Environment", "." ]
def generate(env): """Add Builders and construction variables for ar to an Environment.""" SCons.Tool.createStaticLibBuilder(env) env['AR'] = 'ar' env['ARFLAGS'] = SCons.Util.CLVar('rc') env['ARCOM'] = '$AR $ARFLAGS $TARGET $SOURCES' env['LIBPREFIX'] = 'lib' env['LIBSUFFIX'] = '.a' if env.Detect('ranlib'): env['RANLIB'] = 'ranlib' env['RANLIBFLAGS'] = SCons.Util.CLVar('') env['RANLIBCOM'] = '$RANLIB $RANLIBFLAGS $TARGET'
[ "def", "generate", "(", "env", ")", ":", "SCons", ".", "Tool", ".", "createStaticLibBuilder", "(", "env", ")", "env", "[", "'AR'", "]", "=", "'ar'", "env", "[", "'ARFLAGS'", "]", "=", "SCons", ".", "Util", ".", "CLVar", "(", "'rc'", ")", "env", "["...
https://github.com/Tencent/CMONGO/blob/c40380caa14e05509f46993aa8b8da966b09b0b5/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Tool/ar.py#L41-L54
Manu343726/siplasplas
9fae7559f87087cf8ef34f04bd1e774b84b2ea9c
reference/cindex.py
python
Cursor.kind
(self)
return CursorKind.from_id(self._kind_id)
Return the kind of this cursor.
Return the kind of this cursor.
[ "Return", "the", "kind", "of", "this", "cursor", "." ]
def kind(self): """Return the kind of this cursor.""" return CursorKind.from_id(self._kind_id)
[ "def", "kind", "(", "self", ")", ":", "return", "CursorKind", ".", "from_id", "(", "self", ".", "_kind_id", ")" ]
https://github.com/Manu343726/siplasplas/blob/9fae7559f87087cf8ef34f04bd1e774b84b2ea9c/reference/cindex.py#L1249-L1251
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
python/paddle/nn/functional/common.py
python
class_center_sample
(label, num_classes, num_samples, group=None)
return remapped_label, sampled_class_center
Class center sample method is proposed from the paper PartialFC that only sample a subset of the class centers. The process of sampling subset class centers is straightforward: 1. First select the positive class centers; 2. Then randomly sample negative class centers. Specifically, given a label tensor, shape [batch_size], select all the positive class centers and randomly sample negative class centers, then remap the input label tensor using the sampled class centers. For more information, Partial FC: Training 10 Million Identities on a Single Machine arxiv: https://arxiv.org/abs/2010.05222 .. hint:: If the number of the positive class centers is greater than the input num_samples, it keeps all the positive class centers and the shape of sampled_class_center will be [num_positive_class_centers]. The API supports CPU, single GPU and multi GPU. Args: label (Tensor): 1-D tensor with shape [N], each label in [0, num_classes) num_classes (int): A positive integer to specify the number of classes at local rank. Note that num_classes of each GPU can be different. num_samples (int): A positive integer to specify the number of class center to sample. group (Group, optional): The abstract representation of group. See paddle.distributed.collective.Group. Default is ``None``. Returns: Tuple of two ``Tensor`` : (remapped_label, sampled_class_center), remapped label using sampled class center, sampled class center from [0, num_classes). Examples: .. code-block:: python :name: code-example1 # CPU or single GPU import paddle num_classes = 20 batch_size = 10 num_samples = 6 label = paddle.randint(low=0, high=num_classes, shape=[batch_size], dtype='int64') remapped_label, sampled_class_index = paddle.nn.functional.class_center_sample(label, num_classes, num_samples) print(label) print(remapped_label) print(sampled_class_index) # the output is #Tensor(shape=[10], dtype=int64, place=CPUPlace, stop_gradient=True, # [11, 5 , 1 , 3 , 12, 2 , 15, 19, 18, 19]) #Tensor(shape=[10], dtype=int64, place=CPUPlace, stop_gradient=True, # [4, 3, 0, 2, 5, 1, 6, 8, 7, 8]) #Tensor(shape=[9], dtype=int64, place=CPUPlace, stop_gradient=True, # [1 , 2 , 3 , 5 , 11, 12, 15, 18, 19]) .. code-block:: python :name: code-example2 # required: distributed # Multi GPU, test_class_center_sample.py import paddle import paddle.distributed as dist strategy = dist.fleet.DistributedStrategy() dist.fleet.init(is_collective=True, strategy=strategy) batch_size = 10 num_samples = 6 rank_id = dist.get_rank() # num_classes of each GPU can be different, e.g num_classes_list = [10, 8] num_classes_list = [10, 10] num_classes = paddle.sum(paddle.to_tensor(num_classes_list)) label = paddle.randint(low=0, high=num_classes.item(), shape=[batch_size], dtype='int64') label_list = [] dist.all_gather(label_list, label) label = paddle.concat(label_list, axis=0) remapped_label, sampled_class_index = paddle.nn.functional.class_center_sample(label, num_classes_list[rank_id], num_samples) print(label) print(remapped_label) print(sampled_class_index) #python -m paddle.distributed.launch --gpus=0,1 test_class_center_sample.py # rank 0 output: #Tensor(shape=[20], dtype=int64, place=CUDAPlace(0), stop_gradient=True, # [10, 17, 15, 11, 9 , 12, 18, 18, 17, 18, 19, 2 , 8 , 13, 11, 13, 9 , 10, 0 , 4 ]) #Tensor(shape=[20], dtype=int64, place=CUDAPlace(0), stop_gradient=True, # [6 , 11, 10, 7 , 4 , 8 , 12, 12, 11, 12, 13, 1 , 3 , 9 , 7 , 9 , 4 , 6 , 0 , 2 ]) #Tensor(shape=[6], dtype=int64, place=CUDAPlace(0), stop_gradient=True, # [0, 2, 4, 8, 9, 3]) # rank 1 output: #Tensor(shape=[20], dtype=int64, place=CUDAPlace(1), stop_gradient=True, # [10, 17, 15, 11, 9 , 12, 18, 18, 17, 18, 19, 2 , 8 , 13, 11, 13, 9 , 10, 0 , 4 ]) #Tensor(shape=[20], dtype=int64, place=CUDAPlace(1), stop_gradient=True, # [6 , 11, 10, 7 , 4 , 8 , 12, 12, 11, 12, 13, 1 , 3 , 9 , 7 , 9 , 4 , 6 , 0 , 2 ]) #Tensor(shape=[7], dtype=int64, place=CUDAPlace(1), stop_gradient=True, # [0, 1, 2, 3, 5, 7, 8])
Class center sample method is proposed from the paper PartialFC that only sample a subset of the class centers. The process of sampling subset class centers is straightforward:
[ "Class", "center", "sample", "method", "is", "proposed", "from", "the", "paper", "PartialFC", "that", "only", "sample", "a", "subset", "of", "the", "class", "centers", ".", "The", "process", "of", "sampling", "subset", "class", "centers", "is", "straightforwar...
def class_center_sample(label, num_classes, num_samples, group=None): """ Class center sample method is proposed from the paper PartialFC that only sample a subset of the class centers. The process of sampling subset class centers is straightforward: 1. First select the positive class centers; 2. Then randomly sample negative class centers. Specifically, given a label tensor, shape [batch_size], select all the positive class centers and randomly sample negative class centers, then remap the input label tensor using the sampled class centers. For more information, Partial FC: Training 10 Million Identities on a Single Machine arxiv: https://arxiv.org/abs/2010.05222 .. hint:: If the number of the positive class centers is greater than the input num_samples, it keeps all the positive class centers and the shape of sampled_class_center will be [num_positive_class_centers]. The API supports CPU, single GPU and multi GPU. Args: label (Tensor): 1-D tensor with shape [N], each label in [0, num_classes) num_classes (int): A positive integer to specify the number of classes at local rank. Note that num_classes of each GPU can be different. num_samples (int): A positive integer to specify the number of class center to sample. group (Group, optional): The abstract representation of group. See paddle.distributed.collective.Group. Default is ``None``. Returns: Tuple of two ``Tensor`` : (remapped_label, sampled_class_center), remapped label using sampled class center, sampled class center from [0, num_classes). Examples: .. code-block:: python :name: code-example1 # CPU or single GPU import paddle num_classes = 20 batch_size = 10 num_samples = 6 label = paddle.randint(low=0, high=num_classes, shape=[batch_size], dtype='int64') remapped_label, sampled_class_index = paddle.nn.functional.class_center_sample(label, num_classes, num_samples) print(label) print(remapped_label) print(sampled_class_index) # the output is #Tensor(shape=[10], dtype=int64, place=CPUPlace, stop_gradient=True, # [11, 5 , 1 , 3 , 12, 2 , 15, 19, 18, 19]) #Tensor(shape=[10], dtype=int64, place=CPUPlace, stop_gradient=True, # [4, 3, 0, 2, 5, 1, 6, 8, 7, 8]) #Tensor(shape=[9], dtype=int64, place=CPUPlace, stop_gradient=True, # [1 , 2 , 3 , 5 , 11, 12, 15, 18, 19]) .. code-block:: python :name: code-example2 # required: distributed # Multi GPU, test_class_center_sample.py import paddle import paddle.distributed as dist strategy = dist.fleet.DistributedStrategy() dist.fleet.init(is_collective=True, strategy=strategy) batch_size = 10 num_samples = 6 rank_id = dist.get_rank() # num_classes of each GPU can be different, e.g num_classes_list = [10, 8] num_classes_list = [10, 10] num_classes = paddle.sum(paddle.to_tensor(num_classes_list)) label = paddle.randint(low=0, high=num_classes.item(), shape=[batch_size], dtype='int64') label_list = [] dist.all_gather(label_list, label) label = paddle.concat(label_list, axis=0) remapped_label, sampled_class_index = paddle.nn.functional.class_center_sample(label, num_classes_list[rank_id], num_samples) print(label) print(remapped_label) print(sampled_class_index) #python -m paddle.distributed.launch --gpus=0,1 test_class_center_sample.py # rank 0 output: #Tensor(shape=[20], dtype=int64, place=CUDAPlace(0), stop_gradient=True, # [10, 17, 15, 11, 9 , 12, 18, 18, 17, 18, 19, 2 , 8 , 13, 11, 13, 9 , 10, 0 , 4 ]) #Tensor(shape=[20], dtype=int64, place=CUDAPlace(0), stop_gradient=True, # [6 , 11, 10, 7 , 4 , 8 , 12, 12, 11, 12, 13, 1 , 3 , 9 , 7 , 9 , 4 , 6 , 0 , 2 ]) #Tensor(shape=[6], dtype=int64, place=CUDAPlace(0), stop_gradient=True, # [0, 2, 4, 8, 9, 3]) # rank 1 output: #Tensor(shape=[20], dtype=int64, place=CUDAPlace(1), stop_gradient=True, # [10, 17, 15, 11, 9 , 12, 18, 18, 17, 18, 19, 2 , 8 , 13, 11, 13, 9 , 10, 0 , 4 ]) #Tensor(shape=[20], dtype=int64, place=CUDAPlace(1), stop_gradient=True, # [6 , 11, 10, 7 , 4 , 8 , 12, 12, 11, 12, 13, 1 , 3 , 9 , 7 , 9 , 4 , 6 , 0 , 2 ]) #Tensor(shape=[7], dtype=int64, place=CUDAPlace(1), stop_gradient=True, # [0, 1, 2, 3, 5, 7, 8]) """ if group is not None and not group.is_member(): return ring_id = 0 if group is None else group.id rank = 0 nranks = 1 if core.is_compiled_with_dist(): parallel_env = paddle.distributed.ParallelEnv() global_rank = parallel_env.rank rank = global_rank if group is None else group.get_group_rank( global_rank) nranks = parallel_env.world_size if group is None else group.nranks if num_samples > num_classes: raise ValueError( 'Expected num_samples less than or equal to {}, got num_samples {}'. format(num_classes, num_samples)) label_size = 1 for dim in list(label.shape): label_size *= dim if label_size != -1 and label_size < 1: raise ValueError('Expected label_size > 0 \ (got label_size: {})'.format(label_size)) label_dims = len(list(label.shape)) if label_dims != 1: raise ValueError('Expected label_dims == 1 \ (got label_dims: {})'.format(label_dims)) seed = None if (seed is None or seed == 0) and default_main_program().random_seed != 0: seed = default_main_program().random_seed if in_dygraph_mode(): remapped_label, sampled_class_center = _C_ops.class_center_sample( label, 'num_classes', num_classes, 'num_samples', num_samples, 'ring_id', ring_id, 'nranks', nranks, 'rank', rank, 'fix_seed', seed is not None, 'seed', seed if seed is not None else 0) return remapped_label, sampled_class_center check_variable_and_dtype(label, 'label', ['int64', 'int32'], 'class_center_sample') op_type = 'class_center_sample' helper = LayerHelper(op_type, **locals()) remapped_label = helper.create_variable_for_type_inference( dtype=label.dtype) sampled_class_center = helper.create_variable_for_type_inference( dtype=label.dtype) helper.append_op( type=op_type, inputs={'Label': label}, outputs={ 'RemappedLabel': remapped_label, 'SampledLocalClassCenter': sampled_class_center }, attrs={ 'num_classes': num_classes, 'num_samples': num_samples, 'ring_id': ring_id, 'nranks': nranks, 'rank': rank, 'fix_seed': seed is not None, 'seed': seed if seed is not None else 0 }) return remapped_label, sampled_class_center
[ "def", "class_center_sample", "(", "label", ",", "num_classes", ",", "num_samples", ",", "group", "=", "None", ")", ":", "if", "group", "is", "not", "None", "and", "not", "group", ".", "is_member", "(", ")", ":", "return", "ring_id", "=", "0", "if", "g...
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/nn/functional/common.py#L1635-L1799
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py3/pandas/io/formats/info.py
python
_initialize_memory_usage
( memory_usage: bool | str | None = None, )
return memory_usage
Get memory usage based on inputs and display options.
Get memory usage based on inputs and display options.
[ "Get", "memory", "usage", "based", "on", "inputs", "and", "display", "options", "." ]
def _initialize_memory_usage( memory_usage: bool | str | None = None, ) -> bool | str: """Get memory usage based on inputs and display options.""" if memory_usage is None: memory_usage = get_option("display.memory_usage") return memory_usage
[ "def", "_initialize_memory_usage", "(", "memory_usage", ":", "bool", "|", "str", "|", "None", "=", "None", ",", ")", "->", "bool", "|", "str", ":", "if", "memory_usage", "is", "None", ":", "memory_usage", "=", "get_option", "(", "\"display.memory_usage\"", "...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/io/formats/info.py#L90-L96
google/llvm-propeller
45c226984fe8377ebfb2ad7713c680d652ba678d
llvm/utils/benchmark/tools/gbench/report.py
python
filter_benchmark
(json_orig, family, replacement="")
return filtered
Apply a filter to the json, and only leave the 'family' of benchmarks.
Apply a filter to the json, and only leave the 'family' of benchmarks.
[ "Apply", "a", "filter", "to", "the", "json", "and", "only", "leave", "the", "family", "of", "benchmarks", "." ]
def filter_benchmark(json_orig, family, replacement=""): """ Apply a filter to the json, and only leave the 'family' of benchmarks. """ regex = re.compile(family) filtered = {} filtered['benchmarks'] = [] for be in json_orig['benchmarks']: if not regex.search(be['name']): continue filteredbench = copy.deepcopy(be) # Do NOT modify the old name! filteredbench['name'] = regex.sub(replacement, filteredbench['name']) filtered['benchmarks'].append(filteredbench) return filtered
[ "def", "filter_benchmark", "(", "json_orig", ",", "family", ",", "replacement", "=", "\"\"", ")", ":", "regex", "=", "re", ".", "compile", "(", "family", ")", "filtered", "=", "{", "}", "filtered", "[", "'benchmarks'", "]", "=", "[", "]", "for", "be", ...
https://github.com/google/llvm-propeller/blob/45c226984fe8377ebfb2ad7713c680d652ba678d/llvm/utils/benchmark/tools/gbench/report.py#L71-L84
devsisters/libquic
8954789a056d8e7d5fcb6452fd1572ca57eb5c4e
src/third_party/protobuf/python/google/protobuf/internal/decoder.py
python
_FloatDecoder
()
return _SimpleDecoder(wire_format.WIRETYPE_FIXED32, InnerDecode)
Returns a decoder for a float field. This code works around a bug in struct.unpack for non-finite 32-bit floating-point values.
Returns a decoder for a float field.
[ "Returns", "a", "decoder", "for", "a", "float", "field", "." ]
def _FloatDecoder(): """Returns a decoder for a float field. This code works around a bug in struct.unpack for non-finite 32-bit floating-point values. """ local_unpack = struct.unpack def InnerDecode(buffer, pos): # We expect a 32-bit value in little-endian byte order. Bit 1 is the sign # bit, bits 2-9 represent the exponent, and bits 10-32 are the significand. new_pos = pos + 4 float_bytes = buffer[pos:new_pos] # If this value has all its exponent bits set, then it's non-finite. # In Python 2.4, struct.unpack will convert it to a finite 64-bit value. # To avoid that, we parse it specially. if (float_bytes[3:4] in b'\x7F\xFF' and float_bytes[2:3] >= b'\x80'): # If at least one significand bit is set... if float_bytes[0:3] != b'\x00\x00\x80': return (_NAN, new_pos) # If sign bit is set... if float_bytes[3:4] == b'\xFF': return (_NEG_INF, new_pos) return (_POS_INF, new_pos) # Note that we expect someone up-stack to catch struct.error and convert # it to _DecodeError -- this way we don't have to set up exception- # handling blocks every time we parse one value. result = local_unpack('<f', float_bytes)[0] return (result, new_pos) return _SimpleDecoder(wire_format.WIRETYPE_FIXED32, InnerDecode)
[ "def", "_FloatDecoder", "(", ")", ":", "local_unpack", "=", "struct", ".", "unpack", "def", "InnerDecode", "(", "buffer", ",", "pos", ")", ":", "# We expect a 32-bit value in little-endian byte order. Bit 1 is the sign", "# bit, bits 2-9 represent the exponent, and bits 10-32 ...
https://github.com/devsisters/libquic/blob/8954789a056d8e7d5fcb6452fd1572ca57eb5c4e/src/third_party/protobuf/python/google/protobuf/internal/decoder.py#L288-L320
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/MimeWriter.py
python
MimeWriter.startbody
(self, ctype, plist=[], prefix=1)
return self._fp
Returns a file-like object for writing the body of the message. The content-type is set to the provided ctype, and the optional parameter, plist, provides additional parameters for the content-type declaration. The optional argument prefix determines where the header is inserted; 0 means append at the end, 1 means insert at the start. The default is to insert at the start.
Returns a file-like object for writing the body of the message.
[ "Returns", "a", "file", "-", "like", "object", "for", "writing", "the", "body", "of", "the", "message", "." ]
def startbody(self, ctype, plist=[], prefix=1): """Returns a file-like object for writing the body of the message. The content-type is set to the provided ctype, and the optional parameter, plist, provides additional parameters for the content-type declaration. The optional argument prefix determines where the header is inserted; 0 means append at the end, 1 means insert at the start. The default is to insert at the start. """ for name, value in plist: ctype = ctype + ';\n %s=\"%s\"' % (name, value) self.addheader("Content-Type", ctype, prefix=prefix) self.flushheaders() self._fp.write("\n") return self._fp
[ "def", "startbody", "(", "self", ",", "ctype", ",", "plist", "=", "[", "]", ",", "prefix", "=", "1", ")", ":", "for", "name", ",", "value", "in", "plist", ":", "ctype", "=", "ctype", "+", "';\\n %s=\\\"%s\\\"'", "%", "(", "name", ",", "value", ")",...
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/MimeWriter.py#L128-L143
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
python/paddle/optimizer/adamw.py
python
AdamW._append_decoupled_weight_decay
(self, block, param_and_grad)
Add decoupled weight decay op. parameter = parameter - parameter * coeff * lr Args: block: block in which variable is to be created param_and_grad: (parameters, gradients) pairs, the parameters need to decay. Raises: Exception: The type of coeff and parameter is not consistent.
Add decoupled weight decay op. parameter = parameter - parameter * coeff * lr Args: block: block in which variable is to be created param_and_grad: (parameters, gradients) pairs, the parameters need to decay. Raises: Exception: The type of coeff and parameter is not consistent.
[ "Add", "decoupled", "weight", "decay", "op", ".", "parameter", "=", "parameter", "-", "parameter", "*", "coeff", "*", "lr", "Args", ":", "block", ":", "block", "in", "which", "variable", "is", "to", "be", "created", "param_and_grad", ":", "(", "parameters"...
def _append_decoupled_weight_decay(self, block, param_and_grad): """ Add decoupled weight decay op. parameter = parameter - parameter * coeff * lr Args: block: block in which variable is to be created param_and_grad: (parameters, gradients) pairs, the parameters need to decay. Raises: Exception: The type of coeff and parameter is not consistent. """ if isinstance(param_and_grad, dict): param_and_grad = self._update_param_group(param_and_grad) param, grad = param_and_grad if self._apply_decay_param_fun is not None \ and not self._apply_decay_param_fun(param.name): return if isinstance(self._learning_rate, float): learning_rate = self._learning_rate else: # NOTE. We add this function to the _append_optimize_op(), # for we must make sure _create_param_lr() be called after # optimizer._create_global_learning_rate(). learning_rate = self._create_param_lr(param_and_grad) with block.program._optimized_guard( [param, grad]), framework.name_scope('weight decay'): self._params_name.add(param.name) # If it has been calculated, the result will be reused. # NOTE(wangxi): In dygraph mode, apply_gradient will be executed # every step, so need clear _lr_to_coeff every step, # we do this in _create_optimization_pass decay_coeff = self._lr_to_coeff.get(learning_rate, None) if decay_coeff is None: # NOTE(wangxi): for pipeline to set device:all with paddle.static.device_guard(None): decay_coeff = 1.0 - learning_rate * self._coeff self._lr_to_coeff[learning_rate] = decay_coeff find_master = (self._multi_precision and param.dtype == core.VarDesc.VarType.FP16) if find_master: master_weight = self._master_weights[param.name] scaled_param = master_weight * decay_coeff paddle.fluid.layers.assign( input=scaled_param, output=master_weight) else: scaled_param = param * decay_coeff paddle.fluid.layers.assign(input=scaled_param, output=param)
[ "def", "_append_decoupled_weight_decay", "(", "self", ",", "block", ",", "param_and_grad", ")", ":", "if", "isinstance", "(", "param_and_grad", ",", "dict", ")", ":", "param_and_grad", "=", "self", ".", "_update_param_group", "(", "param_and_grad", ")", "param", ...
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/optimizer/adamw.py#L205-L256
9miao/CrossApp
1f5375e061bf69841eb19728598f5ae3f508d620
tools/bindings-generator/clang/cindex.py
python
Cursor.result_type
(self)
return self._result_type
Retrieve the Type of the result for this Cursor.
Retrieve the Type of the result for this Cursor.
[ "Retrieve", "the", "Type", "of", "the", "result", "for", "this", "Cursor", "." ]
def result_type(self): """Retrieve the Type of the result for this Cursor.""" if not hasattr(self, '_result_type'): self._result_type = conf.lib.clang_getResultType(self.type) return self._result_type
[ "def", "result_type", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_result_type'", ")", ":", "self", ".", "_result_type", "=", "conf", ".", "lib", ".", "clang_getResultType", "(", "self", ".", "type", ")", "return", "self", ".", "...
https://github.com/9miao/CrossApp/blob/1f5375e061bf69841eb19728598f5ae3f508d620/tools/bindings-generator/clang/cindex.py#L1327-L1332
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_gdi.py
python
PseudoDC.EndDrawing
(*args, **kwargs)
return _gdi_.PseudoDC_EndDrawing(*args, **kwargs)
EndDrawing(self) Ends the group of drawing primitives started with `BeginDrawing`, and invokes whatever optimization is available for this DC type on the current platform.
EndDrawing(self)
[ "EndDrawing", "(", "self", ")" ]
def EndDrawing(*args, **kwargs): """ EndDrawing(self) Ends the group of drawing primitives started with `BeginDrawing`, and invokes whatever optimization is available for this DC type on the current platform. """ return _gdi_.PseudoDC_EndDrawing(*args, **kwargs)
[ "def", "EndDrawing", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gdi_", ".", "PseudoDC_EndDrawing", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_gdi.py#L7566-L7574
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/collections.py
python
Counter.__init__
(*args, **kwds)
Create a new, empty Counter object. And if given, count elements from an input iterable. Or, initialize the count from another mapping of elements to their counts. >>> c = Counter() # a new, empty counter >>> c = Counter('gallahad') # a new counter from an iterable >>> c = Counter({'a': 4, 'b': 2}) # a new counter from a mapping >>> c = Counter(a=4, b=2) # a new counter from keyword args
Create a new, empty Counter object. And if given, count elements from an input iterable. Or, initialize the count from another mapping of elements to their counts.
[ "Create", "a", "new", "empty", "Counter", "object", ".", "And", "if", "given", "count", "elements", "from", "an", "input", "iterable", ".", "Or", "initialize", "the", "count", "from", "another", "mapping", "of", "elements", "to", "their", "counts", "." ]
def __init__(*args, **kwds): '''Create a new, empty Counter object. And if given, count elements from an input iterable. Or, initialize the count from another mapping of elements to their counts. >>> c = Counter() # a new, empty counter >>> c = Counter('gallahad') # a new counter from an iterable >>> c = Counter({'a': 4, 'b': 2}) # a new counter from a mapping >>> c = Counter(a=4, b=2) # a new counter from keyword args ''' if not args: raise TypeError("descriptor '__init__' of 'Counter' object " "needs an argument") self = args[0] args = args[1:] if len(args) > 1: raise TypeError('expected at most 1 arguments, got %d' % len(args)) super(Counter, self).__init__() self.update(*args, **kwds)
[ "def", "__init__", "(", "*", "args", ",", "*", "*", "kwds", ")", ":", "if", "not", "args", ":", "raise", "TypeError", "(", "\"descriptor '__init__' of 'Counter' object \"", "\"needs an argument\"", ")", "self", "=", "args", "[", "0", "]", "args", "=", "args"...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/collections.py#L458-L477
psnonis/FinBERT
c0c555d833a14e2316a3701e59c0b5156f804b4e
bert-gpu/modeling.py
python
embedding_postprocessor
(input_tensor, use_token_type=False, token_type_ids=None, token_type_vocab_size=16, token_type_embedding_name="token_type_embeddings", use_position_embeddings=True, position_embedding_name="position_embeddings", initializer_range=0.02, max_position_embeddings=512, dropout_prob=0.1, use_one_hot_embeddings=False)
return output
Performs various post-processing on a word embedding tensor. Args: input_tensor: float Tensor of shape [batch_size, seq_length, embedding_size]. use_token_type: bool. Whether to add embeddings for `token_type_ids`. token_type_ids: (optional) int32 Tensor of shape [batch_size, seq_length]. Must be specified if `use_token_type` is True. token_type_vocab_size: int. The vocabulary size of `token_type_ids`. token_type_embedding_name: string. The name of the embedding table variable for token type ids. use_position_embeddings: bool. Whether to add position embeddings for the position of each token in the sequence. position_embedding_name: string. The name of the embedding table variable for positional embeddings. initializer_range: float. Range of the weight initialization. max_position_embeddings: int. Maximum sequence length that might ever be used with this model. This can be longer than the sequence length of input_tensor, but cannot be shorter. dropout_prob: float. Dropout probability applied to the final output tensor. use_one_hot_embeddings: (optional) bool. Whether to use one-hot word embeddings or tf.embedding_lookup() for the word embeddings. Returns: float tensor with same shape as `input_tensor`. Raises: ValueError: One of the tensor shapes or input values is invalid.
Performs various post-processing on a word embedding tensor.
[ "Performs", "various", "post", "-", "processing", "on", "a", "word", "embedding", "tensor", "." ]
def embedding_postprocessor(input_tensor, use_token_type=False, token_type_ids=None, token_type_vocab_size=16, token_type_embedding_name="token_type_embeddings", use_position_embeddings=True, position_embedding_name="position_embeddings", initializer_range=0.02, max_position_embeddings=512, dropout_prob=0.1, use_one_hot_embeddings=False): """Performs various post-processing on a word embedding tensor. Args: input_tensor: float Tensor of shape [batch_size, seq_length, embedding_size]. use_token_type: bool. Whether to add embeddings for `token_type_ids`. token_type_ids: (optional) int32 Tensor of shape [batch_size, seq_length]. Must be specified if `use_token_type` is True. token_type_vocab_size: int. The vocabulary size of `token_type_ids`. token_type_embedding_name: string. The name of the embedding table variable for token type ids. use_position_embeddings: bool. Whether to add position embeddings for the position of each token in the sequence. position_embedding_name: string. The name of the embedding table variable for positional embeddings. initializer_range: float. Range of the weight initialization. max_position_embeddings: int. Maximum sequence length that might ever be used with this model. This can be longer than the sequence length of input_tensor, but cannot be shorter. dropout_prob: float. Dropout probability applied to the final output tensor. use_one_hot_embeddings: (optional) bool. Whether to use one-hot word embeddings or tf.embedding_lookup() for the word embeddings. Returns: float tensor with same shape as `input_tensor`. Raises: ValueError: One of the tensor shapes or input values is invalid. """ input_shape = get_shape_list(input_tensor, expected_rank=3) batch_size = input_shape[0] seq_length = input_shape[1] width = input_shape[2] output = input_tensor if use_token_type: if token_type_ids is None: raise ValueError("`token_type_ids` must be specified if" "`use_token_type` is True.") token_type_table = tf.get_variable( name=token_type_embedding_name, shape=[token_type_vocab_size, width], initializer=create_initializer(initializer_range)) flat_token_type_ids = tf.reshape(token_type_ids, [-1]) if use_one_hot_embeddings: # This vocab will be small so we always do one-hot here, since it is # always faster for a small vocabulary. one_hot_ids = tf.one_hot(flat_token_type_ids, depth=token_type_vocab_size) token_type_embeddings = tf.matmul(one_hot_ids, token_type_table) else: token_type_embeddings = tf.gather(token_type_table, flat_token_type_ids) token_type_embeddings = tf.reshape(token_type_embeddings, [batch_size, seq_length, width]) output += token_type_embeddings if use_position_embeddings: full_position_embeddings = tf.get_variable( name=position_embedding_name, shape=[max_position_embeddings, width], initializer=create_initializer(initializer_range)) # Since the position embedding table is a learned variable, we create it # using a (long) sequence length `max_position_embeddings`. The actual # sequence length might be shorter than this, for faster training of # tasks that do not have long sequences. # # So `full_position_embeddings` is effectively an embedding table # for position [0, 1, 2, ..., max_position_embeddings-1], and the current # sequence has positions [0, 1, 2, ... seq_length-1], so we can just # perform a slice. position_embeddings = tf.slice(full_position_embeddings, [0, 0], [seq_length, -1]) num_dims = len(output.shape.as_list()) # Only the last two dimensions are relevant (`seq_length` and `width`), so # we broadcast among the first dimensions, which is typically just # the batch size. position_broadcast_shape = [] for _ in range(num_dims - 2): position_broadcast_shape.append(1) position_broadcast_shape.extend([seq_length, width]) position_embeddings = tf.reshape(position_embeddings, position_broadcast_shape) output += position_embeddings output = layer_norm_and_dropout(output, dropout_prob) return output
[ "def", "embedding_postprocessor", "(", "input_tensor", ",", "use_token_type", "=", "False", ",", "token_type_ids", "=", "None", ",", "token_type_vocab_size", "=", "16", ",", "token_type_embedding_name", "=", "\"token_type_embeddings\"", ",", "use_position_embeddings", "="...
https://github.com/psnonis/FinBERT/blob/c0c555d833a14e2316a3701e59c0b5156f804b4e/bert-gpu/modeling.py#L446-L543
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_gdi.py
python
DC.GetBackgroundMode
(*args, **kwargs)
return _gdi_.DC_GetBackgroundMode(*args, **kwargs)
GetBackgroundMode(self) -> int Returns the current background mode, either ``wx.SOLID`` or ``wx.TRANSPARENT``.
GetBackgroundMode(self) -> int
[ "GetBackgroundMode", "(", "self", ")", "-", ">", "int" ]
def GetBackgroundMode(*args, **kwargs): """ GetBackgroundMode(self) -> int Returns the current background mode, either ``wx.SOLID`` or ``wx.TRANSPARENT``. """ return _gdi_.DC_GetBackgroundMode(*args, **kwargs)
[ "def", "GetBackgroundMode", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gdi_", ".", "DC_GetBackgroundMode", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_gdi.py#L4328-L4335
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/requests/sessions.py
python
SessionRedirectMixin.rebuild_method
(self, prepared_request, response)
When being redirected we may want to change the method of the request based on certain specs or browser behavior.
When being redirected we may want to change the method of the request based on certain specs or browser behavior.
[ "When", "being", "redirected", "we", "may", "want", "to", "change", "the", "method", "of", "the", "request", "based", "on", "certain", "specs", "or", "browser", "behavior", "." ]
def rebuild_method(self, prepared_request, response): """When being redirected we may want to change the method of the request based on certain specs or browser behavior. """ method = prepared_request.method # https://tools.ietf.org/html/rfc7231#section-6.4.4 if response.status_code == codes.see_other and method != 'HEAD': method = 'GET' # Do what the browsers do, despite standards... # First, turn 302s into GETs. if response.status_code == codes.found and method != 'HEAD': method = 'GET' # Second, if a POST is responded to with a 301, turn it into a GET. # This bizarre behaviour is explained in Issue 1704. if response.status_code == codes.moved and method == 'POST': method = 'GET' prepared_request.method = method
[ "def", "rebuild_method", "(", "self", ",", "prepared_request", ",", "response", ")", ":", "method", "=", "prepared_request", ".", "method", "# https://tools.ietf.org/html/rfc7231#section-6.4.4", "if", "response", ".", "status_code", "==", "codes", ".", "see_other", "a...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/requests/sessions.py#L314-L334
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/pdb.py
python
Pdb.bp_commands
(self,frame)
return 1
Call every command that was set for the current active breakpoint (if there is one). Returns True if the normal interaction function must be called, False otherwise.
Call every command that was set for the current active breakpoint (if there is one).
[ "Call", "every", "command", "that", "was", "set", "for", "the", "current", "active", "breakpoint", "(", "if", "there", "is", "one", ")", "." ]
def bp_commands(self,frame): """Call every command that was set for the current active breakpoint (if there is one). Returns True if the normal interaction function must be called, False otherwise.""" # self.currentbp is set in bdb in Bdb.break_here if a breakpoint was hit if getattr(self, "currentbp", False) and \ self.currentbp in self.commands: currentbp = self.currentbp self.currentbp = 0 lastcmd_back = self.lastcmd self.setup(frame, None) for line in self.commands[currentbp]: self.onecmd(line) self.lastcmd = lastcmd_back if not self.commands_silent[currentbp]: self.print_stack_entry(self.stack[self.curindex]) if self.commands_doprompt[currentbp]: self.cmdloop() self.forget() return return 1
[ "def", "bp_commands", "(", "self", ",", "frame", ")", ":", "# self.currentbp is set in bdb in Bdb.break_here if a breakpoint was hit", "if", "getattr", "(", "self", ",", "\"currentbp\"", ",", "False", ")", "and", "self", ".", "currentbp", "in", "self", ".", "command...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/pdb.py#L160-L182
rsummers11/CADLab
976ed959a0b5208bb4173127a7ef732ac73a9b6f
lesion_detector_3DCE/rcnn/processing/generate_anchor.py
python
generate_anchors
(base_size=16, ratios=[0.5, 1, 2], scales=2 ** np.arange(3, 6))
return anchors
Generate anchor (reference) windows by enumerating aspect ratios X scales wrt a reference (0, 0, 15, 15) window.
Generate anchor (reference) windows by enumerating aspect ratios X scales wrt a reference (0, 0, 15, 15) window.
[ "Generate", "anchor", "(", "reference", ")", "windows", "by", "enumerating", "aspect", "ratios", "X", "scales", "wrt", "a", "reference", "(", "0", "0", "15", "15", ")", "window", "." ]
def generate_anchors(base_size=16, ratios=[0.5, 1, 2], scales=2 ** np.arange(3, 6)): """ Generate anchor (reference) windows by enumerating aspect ratios X scales wrt a reference (0, 0, 15, 15) window. """ base_anchor = np.array([1, 1, base_size, base_size]) - 1 ratio_anchors = _ratio_enum(base_anchor, ratios) anchors = np.vstack([_scale_enum(ratio_anchors[i, :], scales) for i in xrange(ratio_anchors.shape[0])]) return anchors
[ "def", "generate_anchors", "(", "base_size", "=", "16", ",", "ratios", "=", "[", "0.5", ",", "1", ",", "2", "]", ",", "scales", "=", "2", "**", "np", ".", "arange", "(", "3", ",", "6", ")", ")", ":", "base_anchor", "=", "np", ".", "array", "(",...
https://github.com/rsummers11/CADLab/blob/976ed959a0b5208bb4173127a7ef732ac73a9b6f/lesion_detector_3DCE/rcnn/processing/generate_anchor.py#L8-L19
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/tools/quantization/quantize_graph.py
python
GraphRewriter.__init__
(self, input_graph, mode, quantized_input_range, fallback_quantization_range=None)
Sets up the class to rewrite a float graph. Args: input_graph: A float graph to transform. mode: A string controlling how quantization is performed - round, quantize, eightbit, or weights. quantized_input_range: if set, assume the input is quantized and represents the range [quantized_input_range[0], quantized_input_range[1]] fallback_quantization_range: if set, then for nodes where the quantization range can't be inferred from the graph, use the range [fallback_quantization_range[0], fallback_quantization_range[1]) instead of using a RequantizationRange node in the graph. Raises: ValueError: Two nodes with the same name were found in the graph.
Sets up the class to rewrite a float graph.
[ "Sets", "up", "the", "class", "to", "rewrite", "a", "float", "graph", "." ]
def __init__(self, input_graph, mode, quantized_input_range, fallback_quantization_range=None): """Sets up the class to rewrite a float graph. Args: input_graph: A float graph to transform. mode: A string controlling how quantization is performed - round, quantize, eightbit, or weights. quantized_input_range: if set, assume the input is quantized and represents the range [quantized_input_range[0], quantized_input_range[1]] fallback_quantization_range: if set, then for nodes where the quantization range can't be inferred from the graph, use the range [fallback_quantization_range[0], fallback_quantization_range[1]) instead of using a RequantizationRange node in the graph. Raises: ValueError: Two nodes with the same name were found in the graph. """ self.input_graph = input_graph self.nodes_map = self.create_nodes_map(input_graph) self.output_graph = None self.mode = mode self.final_node_renames = {} if quantized_input_range: self.input_range = (quantized_input_range[0], quantized_input_range[1]) if self.input_range[0] >= self.input_range[1]: raise ValueError("Invalid quantized_input_range: [%s,%s]" % self.input_range) if self.mode != "eightbit": raise ValueError( "quantized_input_range can only be specified in eightbit mode") else: self.input_range = None if fallback_quantization_range: self.fallback_quantization_range = [ fallback_quantization_range[0], fallback_quantization_range[1] ] if (self.fallback_quantization_range[0] >= self.fallback_quantization_range[1]): raise ValueError("Invalid fallback_quantization_range: [%s,%s]" % self.fallback_quantization_range) if self.mode != "eightbit": raise ValueError("fallback_quantization_range can only be " "specified in eightbit mode") else: self.fallback_quantization_range = None # Data that is valid only during the recursive call to rewrite the graph. self.state = None
[ "def", "__init__", "(", "self", ",", "input_graph", ",", "mode", ",", "quantized_input_range", ",", "fallback_quantization_range", "=", "None", ")", ":", "self", ".", "input_graph", "=", "input_graph", "self", ".", "nodes_map", "=", "self", ".", "create_nodes_ma...
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/tools/quantization/quantize_graph.py#L321-L374
neo-ai/neo-ai-dlr
bf397aa0367a5207654c00d2985f900d94ad1543
python/dlr/counter/phone_home.py
python
PhoneHome.get_model_hash
(self, model)
return name
Get hashsed model name Args: model str: name of model Returns: str: hased str of model
Get hashsed model name
[ "Get", "hashsed", "model", "name" ]
def get_model_hash(self, model): """ Get hashsed model name Args: model str: name of model Returns: str: hased str of model """ hashed = get_hash_string(model.encode()) name = str(hashed.hexdigest()) return name
[ "def", "get_model_hash", "(", "self", ",", "model", ")", ":", "hashed", "=", "get_hash_string", "(", "model", ".", "encode", "(", ")", ")", "name", "=", "str", "(", "hashed", ".", "hexdigest", "(", ")", ")", "return", "name" ]
https://github.com/neo-ai/neo-ai-dlr/blob/bf397aa0367a5207654c00d2985f900d94ad1543/python/dlr/counter/phone_home.py#L173-L184
giuspen/cherrytree
84712f206478fcf9acf30174009ad28c648c6344
pygtk2/modules/core.py
python
CherryTree.bookmarks_handle
(self, *args)
Handle the Bookmarks List
Handle the Bookmarks List
[ "Handle", "the", "Bookmarks", "List" ]
def bookmarks_handle(self, *args): """Handle the Bookmarks List""" if support.bookmarks_handle(self): self.update_window_save_needed("book")
[ "def", "bookmarks_handle", "(", "self", ",", "*", "args", ")", ":", "if", "support", ".", "bookmarks_handle", "(", "self", ")", ":", "self", ".", "update_window_save_needed", "(", "\"book\"", ")" ]
https://github.com/giuspen/cherrytree/blob/84712f206478fcf9acf30174009ad28c648c6344/pygtk2/modules/core.py#L5236-L5239
NicknineTheEagle/TF2-Base
20459c5a7fbc995b6bf54fa85c2f62a101e9fb64
src/thirdparty/protobuf-2.3.0/python/google/protobuf/internal/encoder.py
python
_SignedVarintEncoder
()
return EncodeSignedVarint
Return an encoder for a basic signed varint value (does not include tag).
Return an encoder for a basic signed varint value (does not include tag).
[ "Return", "an", "encoder", "for", "a", "basic", "signed", "varint", "value", "(", "does", "not", "include", "tag", ")", "." ]
def _SignedVarintEncoder(): """Return an encoder for a basic signed varint value (does not include tag).""" local_chr = chr def EncodeSignedVarint(write, value): if value < 0: value += (1 << 64) bits = value & 0x7f value >>= 7 while value: write(local_chr(0x80|bits)) bits = value & 0x7f value >>= 7 return write(local_chr(bits)) return EncodeSignedVarint
[ "def", "_SignedVarintEncoder", "(", ")", ":", "local_chr", "=", "chr", "def", "EncodeSignedVarint", "(", "write", ",", "value", ")", ":", "if", "value", "<", "0", ":", "value", "+=", "(", "1", "<<", "64", ")", "bits", "=", "value", "&", "0x7f", "valu...
https://github.com/NicknineTheEagle/TF2-Base/blob/20459c5a7fbc995b6bf54fa85c2f62a101e9fb64/src/thirdparty/protobuf-2.3.0/python/google/protobuf/internal/encoder.py#L350-L366
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
tools/sampcd_processor.py
python
get_incrementapi
()
this function will get the apis that difference between API_DEV.spec and API_PR.spec.
this function will get the apis that difference between API_DEV.spec and API_PR.spec.
[ "this", "function", "will", "get", "the", "apis", "that", "difference", "between", "API_DEV", ".", "spec", "and", "API_PR", ".", "spec", "." ]
def get_incrementapi(): ''' this function will get the apis that difference between API_DEV.spec and API_PR.spec. ''' global API_DEV_SPEC_FN, API_PR_SPEC_FN, API_DIFF_SPEC_FN ## readonly dev_api = get_api_md5(API_DEV_SPEC_FN) pr_api = get_api_md5(API_PR_SPEC_FN) with open(API_DIFF_SPEC_FN, 'w') as f: for key in pr_api: if key in dev_api: if dev_api[key] != pr_api[key]: logger.debug("%s in dev is %s, different from pr's %s", key, dev_api[key], pr_api[key]) f.write(key) f.write('\n') else: logger.debug("%s is not in dev", key) f.write(key) f.write('\n')
[ "def", "get_incrementapi", "(", ")", ":", "global", "API_DEV_SPEC_FN", ",", "API_PR_SPEC_FN", ",", "API_DIFF_SPEC_FN", "## readonly", "dev_api", "=", "get_api_md5", "(", "API_DEV_SPEC_FN", ")", "pr_api", "=", "get_api_md5", "(", "API_PR_SPEC_FN", ")", "with", "open"...
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/tools/sampcd_processor.py#L532-L550
eclipse/sumo
7132a9b8b6eea734bdec38479026b4d8c4336d03
tools/traci/_vehicle.py
python
VehicleDomain.getEmergencyDecel
(self, vehID)
return self._getUniversal(tc.VAR_EMERGENCY_DECEL, vehID)
getEmergencyDecel(string) -> double Returns the maximal physically possible deceleration in m/s^2 of this vehicle.
getEmergencyDecel(string) -> double
[ "getEmergencyDecel", "(", "string", ")", "-", ">", "double" ]
def getEmergencyDecel(self, vehID): """getEmergencyDecel(string) -> double Returns the maximal physically possible deceleration in m/s^2 of this vehicle. """ return self._getUniversal(tc.VAR_EMERGENCY_DECEL, vehID)
[ "def", "getEmergencyDecel", "(", "self", ",", "vehID", ")", ":", "return", "self", ".", "_getUniversal", "(", "tc", ".", "VAR_EMERGENCY_DECEL", ",", "vehID", ")" ]
https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/traci/_vehicle.py#L647-L652
pristineio/webrtc-mirror
7a5bcdffaab90a05bc1146b2b1ea71c004e54d71
tools_webrtc/presubmit_checks_lib/check_orphan_headers.py
python
IsHeaderInBuildGn
(header_path, build_gn_path)
return header_path in headers_in_build_gn
Returns True if the header is listed in the BUILD.gn file. Args: header_path: the absolute path to the header to check. build_gn_path: the absolute path to the header to check. Returns: bool: True if the header_path is an header that is listed in at least one GN target in the BUILD.gn file specified by the argument build_gn_path.
Returns True if the header is listed in the BUILD.gn file.
[ "Returns", "True", "if", "the", "header", "is", "listed", "in", "the", "BUILD", ".", "gn", "file", "." ]
def IsHeaderInBuildGn(header_path, build_gn_path): """Returns True if the header is listed in the BUILD.gn file. Args: header_path: the absolute path to the header to check. build_gn_path: the absolute path to the header to check. Returns: bool: True if the header_path is an header that is listed in at least one GN target in the BUILD.gn file specified by the argument build_gn_path. """ target_abs_path = os.path.dirname(build_gn_path) build_gn_content = _ReadFile(build_gn_path) headers_in_build_gn = GetHeadersInBuildGnFileSources(build_gn_content, target_abs_path) return header_path in headers_in_build_gn
[ "def", "IsHeaderInBuildGn", "(", "header_path", ",", "build_gn_path", ")", ":", "target_abs_path", "=", "os", ".", "path", ".", "dirname", "(", "build_gn_path", ")", "build_gn_content", "=", "_ReadFile", "(", "build_gn_path", ")", "headers_in_build_gn", "=", "GetH...
https://github.com/pristineio/webrtc-mirror/blob/7a5bcdffaab90a05bc1146b2b1ea71c004e54d71/tools_webrtc/presubmit_checks_lib/check_orphan_headers.py#L77-L93
naver/sling
5671cd445a2caae0b4dd0332299e4cfede05062c
webkit/Tools/Scripts/webkitpy/thirdparty/irc/irclib.py
python
ServerConnection.motd
(self, server="")
Send an MOTD command.
Send an MOTD command.
[ "Send", "an", "MOTD", "command", "." ]
def motd(self, server=""): """Send an MOTD command.""" self.send_raw("MOTD" + (server and (" " + server)))
[ "def", "motd", "(", "self", ",", "server", "=", "\"\"", ")", ":", "self", ".", "send_raw", "(", "\"MOTD\"", "+", "(", "server", "and", "(", "\" \"", "+", "server", ")", ")", ")" ]
https://github.com/naver/sling/blob/5671cd445a2caae0b4dd0332299e4cfede05062c/webkit/Tools/Scripts/webkitpy/thirdparty/irc/irclib.py#L723-L725
isl-org/Open3D
79aec3ddde6a571ce2f28e4096477e52ec465244
python/open3d/visualization/tensorboard_plugin/summary.py
python
_to_integer
(tensor)
Test converting a tensor (TF, PyTorch, Open3D, Numpy array or a scalar) to scalar integer (np.int64) and return it. Return None on failure.
Test converting a tensor (TF, PyTorch, Open3D, Numpy array or a scalar) to scalar integer (np.int64) and return it. Return None on failure.
[ "Test", "converting", "a", "tensor", "(", "TF", "PyTorch", "Open3D", "Numpy", "array", "or", "a", "scalar", ")", "to", "scalar", "integer", "(", "np", ".", "int64", ")", "and", "return", "it", ".", "Return", "None", "on", "failure", "." ]
def _to_integer(tensor): """Test converting a tensor (TF, PyTorch, Open3D, Numpy array or a scalar) to scalar integer (np.int64) and return it. Return None on failure. """ try: if hasattr(tensor, 'ndim') and tensor.ndim > 0: return None if hasattr(tensor, '__len__'): # check for ((int,),) return _to_integer(tensor[0]) # floats are material properties if hasattr(tensor, 'dtype') and 'int' not in repr(tensor.dtype).lower(): return None if hasattr(tensor, 'numpy'): tensor_int = tensor.numpy().astype(np.int64) tensor_int = np.int64(tensor) return tensor_int if tensor_int.size == 1 else None except (TypeError, ValueError, RuntimeError): return None
[ "def", "_to_integer", "(", "tensor", ")", ":", "try", ":", "if", "hasattr", "(", "tensor", ",", "'ndim'", ")", "and", "tensor", ".", "ndim", ">", "0", ":", "return", "None", "if", "hasattr", "(", "tensor", ",", "'__len__'", ")", ":", "# check for ((int...
https://github.com/isl-org/Open3D/blob/79aec3ddde6a571ce2f28e4096477e52ec465244/python/open3d/visualization/tensorboard_plugin/summary.py#L230-L247
9miao/CrossApp
1f5375e061bf69841eb19728598f5ae3f508d620
tools/bindings-generator/clang/cindex.py
python
Type.is_volatile_qualified
(self)
return conf.lib.clang_isVolatileQualifiedType(self)
Determine whether a Type has the "volatile" qualifier set. This does not look through typedefs that may have added "volatile" at a different level.
Determine whether a Type has the "volatile" qualifier set.
[ "Determine", "whether", "a", "Type", "has", "the", "volatile", "qualifier", "set", "." ]
def is_volatile_qualified(self): """Determine whether a Type has the "volatile" qualifier set. This does not look through typedefs that may have added "volatile" at a different level. """ return conf.lib.clang_isVolatileQualifiedType(self)
[ "def", "is_volatile_qualified", "(", "self", ")", ":", "return", "conf", ".", "lib", ".", "clang_isVolatileQualifiedType", "(", "self", ")" ]
https://github.com/9miao/CrossApp/blob/1f5375e061bf69841eb19728598f5ae3f508d620/tools/bindings-generator/clang/cindex.py#L1748-L1754
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_windows.py
python
VarVScrollHelper.RefreshRows
(*args, **kwargs)
return _windows_.VarVScrollHelper_RefreshRows(*args, **kwargs)
RefreshRows(self, size_t from, size_t to)
RefreshRows(self, size_t from, size_t to)
[ "RefreshRows", "(", "self", "size_t", "from", "size_t", "to", ")" ]
def RefreshRows(*args, **kwargs): """RefreshRows(self, size_t from, size_t to)""" return _windows_.VarVScrollHelper_RefreshRows(*args, **kwargs)
[ "def", "RefreshRows", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_windows_", ".", "VarVScrollHelper_RefreshRows", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_windows.py#L2293-L2295
microsoft/TSS.MSR
0f2516fca2cd9929c31d5450e39301c9bde43688
TSS.Py/src/TpmTypes.py
python
TPM2_PCR_Event_REQUEST.fromBytes
(buffer)
return TpmBuffer(buffer).createObj(TPM2_PCR_Event_REQUEST)
Returns new TPM2_PCR_Event_REQUEST object constructed from its marshaled representation in the given byte buffer
Returns new TPM2_PCR_Event_REQUEST object constructed from its marshaled representation in the given byte buffer
[ "Returns", "new", "TPM2_PCR_Event_REQUEST", "object", "constructed", "from", "its", "marshaled", "representation", "in", "the", "given", "byte", "buffer" ]
def fromBytes(buffer): """ Returns new TPM2_PCR_Event_REQUEST object constructed from its marshaled representation in the given byte buffer """ return TpmBuffer(buffer).createObj(TPM2_PCR_Event_REQUEST)
[ "def", "fromBytes", "(", "buffer", ")", ":", "return", "TpmBuffer", "(", "buffer", ")", ".", "createObj", "(", "TPM2_PCR_Event_REQUEST", ")" ]
https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L13767-L13771
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/ops/nn_ops.py
python
_non_atrous_convolution
( input, # pylint: disable=redefined-builtin filter, # pylint: disable=redefined-builtin padding, data_format=None, # pylint: disable=redefined-builtin strides=None, name=None)
Computes sums of N-D convolutions (actually cross correlation). It is required that 1 <= N <= 3. This is used to implement the more generic `convolution` function, which extends the interface of this function with a `dilation_rate` parameter. Args: input: Rank N+2 tensor of type T of shape `[batch_size] + input_spatial_shape + [in_channels]` if `data_format` does not start with `"NC"`, or `[batch_size, in_channels] + input_spatial_shape` if `data_format` starts with `"NC"`. filter: Rank N+2 tensor of type T of shape `filter_spatial_shape + [in_channels, out_channels]`. Rank of either `input` or `filter` must be known. padding: Padding method to use, must be either "VALID" or "SAME". data_format: A string or None. Specifies whether the channel dimension of the `input` and output is the last dimension (default, or if `data_format` does not start with "NC"), or the second dimension (if `data_format` starts with "NC"). For N=1, the valid values are "NWC" (default) and "NCW". For N=2, the valid values are "NHWC" (default) and "NCHW". For N=3, the valid values are "NDHWC" (default) and "NCDHW". strides: Sequence of N positive integers, defaults to `[1] * N`. name: Name prefix to use. Returns: Rank N+2 tensor of type T of shape `[batch_size] + output_spatial_shape + [out_channels]`, where if padding == "SAME": output_spatial_shape = input_spatial_shape if padding == "VALID": output_spatial_shape = input_spatial_shape - filter_spatial_shape + 1. Raises: ValueError: if ranks are incompatible.
Computes sums of N-D convolutions (actually cross correlation).
[ "Computes", "sums", "of", "N", "-", "D", "convolutions", "(", "actually", "cross", "correlation", ")", "." ]
def _non_atrous_convolution( input, # pylint: disable=redefined-builtin filter, # pylint: disable=redefined-builtin padding, data_format=None, # pylint: disable=redefined-builtin strides=None, name=None): """Computes sums of N-D convolutions (actually cross correlation). It is required that 1 <= N <= 3. This is used to implement the more generic `convolution` function, which extends the interface of this function with a `dilation_rate` parameter. Args: input: Rank N+2 tensor of type T of shape `[batch_size] + input_spatial_shape + [in_channels]` if `data_format` does not start with `"NC"`, or `[batch_size, in_channels] + input_spatial_shape` if `data_format` starts with `"NC"`. filter: Rank N+2 tensor of type T of shape `filter_spatial_shape + [in_channels, out_channels]`. Rank of either `input` or `filter` must be known. padding: Padding method to use, must be either "VALID" or "SAME". data_format: A string or None. Specifies whether the channel dimension of the `input` and output is the last dimension (default, or if `data_format` does not start with "NC"), or the second dimension (if `data_format` starts with "NC"). For N=1, the valid values are "NWC" (default) and "NCW". For N=2, the valid values are "NHWC" (default) and "NCHW". For N=3, the valid values are "NDHWC" (default) and "NCDHW". strides: Sequence of N positive integers, defaults to `[1] * N`. name: Name prefix to use. Returns: Rank N+2 tensor of type T of shape `[batch_size] + output_spatial_shape + [out_channels]`, where if padding == "SAME": output_spatial_shape = input_spatial_shape if padding == "VALID": output_spatial_shape = input_spatial_shape - filter_spatial_shape + 1. Raises: ValueError: if ranks are incompatible. """ with ops.name_scope(name, "non_atrous_convolution", [input, filter]) as scope: input = ops.convert_to_tensor(input, name="input") # pylint: disable=redefined-builtin input_shape = input.shape filter = ops.convert_to_tensor(filter, name="filter") # pylint: disable=redefined-builtin filter_shape = filter.shape op = _NonAtrousConvolution( input_shape, filter_shape=filter_shape, padding=padding, data_format=data_format, strides=strides, name=scope) return op(input, filter)
[ "def", "_non_atrous_convolution", "(", "input", ",", "# pylint: disable=redefined-builtin", "filter", ",", "# pylint: disable=redefined-builtin", "padding", ",", "data_format", "=", "None", ",", "# pylint: disable=redefined-builtin", "strides", "=", "None", ",", "name", "="...
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/nn_ops.py#L224-L282
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/xrc.py
python
XmlResource.LoadMenu
(*args, **kwargs)
return _xrc.XmlResource_LoadMenu(*args, **kwargs)
LoadMenu(self, String name) -> Menu
LoadMenu(self, String name) -> Menu
[ "LoadMenu", "(", "self", "String", "name", ")", "-", ">", "Menu" ]
def LoadMenu(*args, **kwargs): """LoadMenu(self, String name) -> Menu""" return _xrc.XmlResource_LoadMenu(*args, **kwargs)
[ "def", "LoadMenu", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_xrc", ".", "XmlResource_LoadMenu", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/xrc.py#L119-L121
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/tkinter/__init__.py
python
Text.replace
(self, index1, index2, chars, *args)
Replaces the range of characters between index1 and index2 with the given characters and tags specified by args. See the method insert for some more information about args, and the method delete for information about the indices.
Replaces the range of characters between index1 and index2 with the given characters and tags specified by args.
[ "Replaces", "the", "range", "of", "characters", "between", "index1", "and", "index2", "with", "the", "given", "characters", "and", "tags", "specified", "by", "args", "." ]
def replace(self, index1, index2, chars, *args): # new in Tk 8.5 """Replaces the range of characters between index1 and index2 with the given characters and tags specified by args. See the method insert for some more information about args, and the method delete for information about the indices.""" self.tk.call(self._w, 'replace', index1, index2, chars, *args)
[ "def", "replace", "(", "self", ",", "index1", ",", "index2", ",", "chars", ",", "*", "args", ")", ":", "# new in Tk 8.5", "self", ".", "tk", ".", "call", "(", "self", ".", "_w", ",", "'replace'", ",", "index1", ",", "index2", ",", "chars", ",", "*"...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/tkinter/__init__.py#L3305-L3311
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
third_party/protobuf/python/google/protobuf/descriptor_pool.py
python
DescriptorPool._ConvertEnumDescriptor
(self, enum_proto, package=None, file_desc=None, containing_type=None, scope=None)
return desc
Make a protobuf EnumDescriptor given an EnumDescriptorProto protobuf. Args: enum_proto: The descriptor_pb2.EnumDescriptorProto protobuf message. package: Optional package name for the new message EnumDescriptor. file_desc: The file containing the enum descriptor. containing_type: The type containing this enum. scope: Scope containing available types. Returns: The added descriptor
Make a protobuf EnumDescriptor given an EnumDescriptorProto protobuf.
[ "Make", "a", "protobuf", "EnumDescriptor", "given", "an", "EnumDescriptorProto", "protobuf", "." ]
def _ConvertEnumDescriptor(self, enum_proto, package=None, file_desc=None, containing_type=None, scope=None): """Make a protobuf EnumDescriptor given an EnumDescriptorProto protobuf. Args: enum_proto: The descriptor_pb2.EnumDescriptorProto protobuf message. package: Optional package name for the new message EnumDescriptor. file_desc: The file containing the enum descriptor. containing_type: The type containing this enum. scope: Scope containing available types. Returns: The added descriptor """ if package: enum_name = '.'.join((package, enum_proto.name)) else: enum_name = enum_proto.name if file_desc is None: file_name = None else: file_name = file_desc.name values = [self._MakeEnumValueDescriptor(value, index) for index, value in enumerate(enum_proto.value)] desc = descriptor.EnumDescriptor(name=enum_proto.name, full_name=enum_name, filename=file_name, file=file_desc, values=values, containing_type=containing_type, options=enum_proto.options) scope[enum_proto.name] = desc scope['.%s' % enum_name] = desc self._enum_descriptors[enum_name] = desc return desc
[ "def", "_ConvertEnumDescriptor", "(", "self", ",", "enum_proto", ",", "package", "=", "None", ",", "file_desc", "=", "None", ",", "containing_type", "=", "None", ",", "scope", "=", "None", ")", ":", "if", "package", ":", "enum_name", "=", "'.'", ".", "jo...
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/protobuf/python/google/protobuf/descriptor_pool.py#L296-L333
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
native_client_sdk/src/tools/oshelpers.py
python
MakeZipPath
(os_path, isdir, iswindows)
return zip_path
Changes a path into zipfile format. # doctest doesn't seem to honor r'' strings, so the backslashes need to be # escaped. >>> MakeZipPath(r'C:\\users\\foobar\\blah', False, True) 'users/foobar/blah' >>> MakeZipPath('/tmp/tmpfoobar/something', False, False) 'tmp/tmpfoobar/something' >>> MakeZipPath('./somefile.txt', False, False) 'somefile.txt' >>> MakeZipPath('somedir', True, False) 'somedir/' >>> MakeZipPath('../dir/filename.txt', False, False) '../dir/filename.txt' >>> MakeZipPath('dir/../filename.txt', False, False) 'filename.txt'
Changes a path into zipfile format.
[ "Changes", "a", "path", "into", "zipfile", "format", "." ]
def MakeZipPath(os_path, isdir, iswindows): """Changes a path into zipfile format. # doctest doesn't seem to honor r'' strings, so the backslashes need to be # escaped. >>> MakeZipPath(r'C:\\users\\foobar\\blah', False, True) 'users/foobar/blah' >>> MakeZipPath('/tmp/tmpfoobar/something', False, False) 'tmp/tmpfoobar/something' >>> MakeZipPath('./somefile.txt', False, False) 'somefile.txt' >>> MakeZipPath('somedir', True, False) 'somedir/' >>> MakeZipPath('../dir/filename.txt', False, False) '../dir/filename.txt' >>> MakeZipPath('dir/../filename.txt', False, False) 'filename.txt' """ zip_path = os_path if iswindows: import ntpath # zipfile paths are always posix-style. They also have the drive # letter and leading slashes removed. zip_path = ntpath.splitdrive(os_path)[1].replace('\\', '/') if zip_path.startswith('/'): zip_path = zip_path[1:] zip_path = posixpath.normpath(zip_path) # zipfile also always appends a slash to a directory name. if isdir: zip_path += '/' return zip_path
[ "def", "MakeZipPath", "(", "os_path", ",", "isdir", ",", "iswindows", ")", ":", "zip_path", "=", "os_path", "if", "iswindows", ":", "import", "ntpath", "# zipfile paths are always posix-style. They also have the drive", "# letter and leading slashes removed.", "zip_path", "...
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/native_client_sdk/src/tools/oshelpers.py#L305-L335
dmlc/xgboost
2775c2a1abd4b5b759ff517617434c8b9aeb4cc0
python-package/xgboost/core.py
python
Booster.copy
(self)
return self.__copy__()
Copy the booster object. Returns ------- booster: `Booster` a copied booster model
Copy the booster object.
[ "Copy", "the", "booster", "object", "." ]
def copy(self) -> "Booster": """Copy the booster object. Returns ------- booster: `Booster` a copied booster model """ return self.__copy__()
[ "def", "copy", "(", "self", ")", "->", "\"Booster\"", ":", "return", "self", ".", "__copy__", "(", ")" ]
https://github.com/dmlc/xgboost/blob/2775c2a1abd4b5b759ff517617434c8b9aeb4cc0/python-package/xgboost/core.py#L1536-L1544
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
torch/distributed/distributed_c10d.py
python
monitored_barrier
(group=GroupMember.WORLD, timeout=None, wait_all_ranks=False)
return group_to_use.monitored_barrier(timeout, wait_all_ranks=wait_all_ranks)
Synchronizes all processes similar to ``torch.distributed.barrier``, but takes a configurable timeout and is able to report ranks that did not pass this barrier within that timeout. Specifically, for non-zero ranks, will block until a send/recv is processed from rank 0. Rank 0 will block until all send /recv from other ranks are processed, and will report failures for ranks that failed to respond in time. Note that if one rank does not reach the monitored_barrier (for example due to a hang), all other ranks would fail in monitored_barrier. This collective will block all processes/ranks in the group, until the whole group exits the function successfully, making it useful for debugging and synchronizing. However, it can have a performance impact and should only be used for debugging or scenarios that require full synchronization points on the host-side. For debugging purposees, this barrier can be inserted before the application's collective calls to check if any ranks are desynchronized. .. note:: Note that this collective is only supported with the GLOO backend. Args: group (ProcessGroup, optional): The process group to work on. If ``None``, the default process group will be used. timeout (datetime.timedelta, optional): Timeout for monitored_barrier. If ``None``, the default process group timeout will be used. wait_all_ranks (bool, optional): Whether to collect all failed ranks or not. By default, this is ``False`` and ``monitored_barrier`` on rank 0 will throw on the first failed rank it encounters in order to fail fast. By setting ``wait_all_ranks=True`` ``monitored_barrier`` will collect all failed ranks and throw an error containing information about all failed ranks. Returns: ``None``. Example:: >>> # Note: Process group initialization omitted on each rank. >>> import torch.distributed as dist >>> if dist.get_rank() != 1: >>> dist.monitored_barrier() # Raises exception indicating that >>> # rank 1 did not call into monitored_barrier. >>> # Example with wait_all_ranks=True >>> if dist.get_rank() == 0: >>> dist.monitored_barrier(wait_all_ranks=True) # Raises exception >>> # indicating that ranks 1, 2, ... world_size - 1 did not call into >>> # monitored_barrier.
Synchronizes all processes similar to ``torch.distributed.barrier``, but takes a configurable timeout and is able to report ranks that did not pass this barrier within that timeout. Specifically, for non-zero ranks, will block until a send/recv is processed from rank 0. Rank 0 will block until all send /recv from other ranks are processed, and will report failures for ranks that failed to respond in time. Note that if one rank does not reach the monitored_barrier (for example due to a hang), all other ranks would fail in monitored_barrier.
[ "Synchronizes", "all", "processes", "similar", "to", "torch", ".", "distributed", ".", "barrier", "but", "takes", "a", "configurable", "timeout", "and", "is", "able", "to", "report", "ranks", "that", "did", "not", "pass", "this", "barrier", "within", "that", ...
def monitored_barrier(group=GroupMember.WORLD, timeout=None, wait_all_ranks=False): """ Synchronizes all processes similar to ``torch.distributed.barrier``, but takes a configurable timeout and is able to report ranks that did not pass this barrier within that timeout. Specifically, for non-zero ranks, will block until a send/recv is processed from rank 0. Rank 0 will block until all send /recv from other ranks are processed, and will report failures for ranks that failed to respond in time. Note that if one rank does not reach the monitored_barrier (for example due to a hang), all other ranks would fail in monitored_barrier. This collective will block all processes/ranks in the group, until the whole group exits the function successfully, making it useful for debugging and synchronizing. However, it can have a performance impact and should only be used for debugging or scenarios that require full synchronization points on the host-side. For debugging purposees, this barrier can be inserted before the application's collective calls to check if any ranks are desynchronized. .. note:: Note that this collective is only supported with the GLOO backend. Args: group (ProcessGroup, optional): The process group to work on. If ``None``, the default process group will be used. timeout (datetime.timedelta, optional): Timeout for monitored_barrier. If ``None``, the default process group timeout will be used. wait_all_ranks (bool, optional): Whether to collect all failed ranks or not. By default, this is ``False`` and ``monitored_barrier`` on rank 0 will throw on the first failed rank it encounters in order to fail fast. By setting ``wait_all_ranks=True`` ``monitored_barrier`` will collect all failed ranks and throw an error containing information about all failed ranks. Returns: ``None``. Example:: >>> # Note: Process group initialization omitted on each rank. >>> import torch.distributed as dist >>> if dist.get_rank() != 1: >>> dist.monitored_barrier() # Raises exception indicating that >>> # rank 1 did not call into monitored_barrier. >>> # Example with wait_all_ranks=True >>> if dist.get_rank() == 0: >>> dist.monitored_barrier(wait_all_ranks=True) # Raises exception >>> # indicating that ranks 1, 2, ... world_size - 1 did not call into >>> # monitored_barrier. """ # Need to call rank not in group before using the group, otherwise # "Invalid process group" error is raised. if _rank_not_in_group(group): _warn_not_in_group("monitored_barrier") return if get_backend(group) != Backend.GLOO: raise RuntimeError("monitored_barrier is only implemented for GLOO backend.") if timeout is None: timeout = default_pg_timeout group_to_use = _get_default_group() if group is None else group return group_to_use.monitored_barrier(timeout, wait_all_ranks=wait_all_ranks)
[ "def", "monitored_barrier", "(", "group", "=", "GroupMember", ".", "WORLD", ",", "timeout", "=", "None", ",", "wait_all_ranks", "=", "False", ")", ":", "# Need to call rank not in group before using the group, otherwise", "# \"Invalid process group\" error is raised.", "if", ...
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/distributed/distributed_c10d.py#L2786-L2848
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
contrib/gizmos/osx_carbon/gizmos.py
python
TreeListCtrl.IsSelected
(*args, **kwargs)
return _gizmos.TreeListCtrl_IsSelected(*args, **kwargs)
IsSelected(self, TreeItemId item) -> bool
IsSelected(self, TreeItemId item) -> bool
[ "IsSelected", "(", "self", "TreeItemId", "item", ")", "-", ">", "bool" ]
def IsSelected(*args, **kwargs): """IsSelected(self, TreeItemId item) -> bool""" return _gizmos.TreeListCtrl_IsSelected(*args, **kwargs)
[ "def", "IsSelected", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gizmos", ".", "TreeListCtrl_IsSelected", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/contrib/gizmos/osx_carbon/gizmos.py#L734-L736
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_misc.py
python
TimerEvent.GetTimer
(*args, **kwargs)
return _misc_.TimerEvent_GetTimer(*args, **kwargs)
GetTimer(self) -> wxTimer
GetTimer(self) -> wxTimer
[ "GetTimer", "(", "self", ")", "-", ">", "wxTimer" ]
def GetTimer(*args, **kwargs): """GetTimer(self) -> wxTimer""" return _misc_.TimerEvent_GetTimer(*args, **kwargs)
[ "def", "GetTimer", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_misc_", ".", "TimerEvent_GetTimer", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_misc.py#L1384-L1386
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_misc.py
python
BitmapDataObject.GetBitmap
(*args, **kwargs)
return _misc_.BitmapDataObject_GetBitmap(*args, **kwargs)
GetBitmap(self) -> Bitmap Returns the bitmap associated with the data object. You may wish to override this method (by deriving from `wx.PyBitmapDataObject`) when offering data on-demand, but this is not required by wxWidgets' internals. Use this method to get data in bitmap form from the `wx.Clipboard`.
GetBitmap(self) -> Bitmap
[ "GetBitmap", "(", "self", ")", "-", ">", "Bitmap" ]
def GetBitmap(*args, **kwargs): """ GetBitmap(self) -> Bitmap Returns the bitmap associated with the data object. You may wish to override this method (by deriving from `wx.PyBitmapDataObject`) when offering data on-demand, but this is not required by wxWidgets' internals. Use this method to get data in bitmap form from the `wx.Clipboard`. """ return _misc_.BitmapDataObject_GetBitmap(*args, **kwargs)
[ "def", "GetBitmap", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_misc_", ".", "BitmapDataObject_GetBitmap", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_misc.py#L5273-L5283
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/io/formats/format.py
python
_get_format_timedelta64
( values: Union[np.ndarray, TimedeltaIndex, TimedeltaArray], nat_rep: str = "NaT", box: bool = False, )
return _formatter
Return a formatter function for a range of timedeltas. These will all have the same format argument If box, then show the return in quotes
Return a formatter function for a range of timedeltas. These will all have the same format argument
[ "Return", "a", "formatter", "function", "for", "a", "range", "of", "timedeltas", ".", "These", "will", "all", "have", "the", "same", "format", "argument" ]
def _get_format_timedelta64( values: Union[np.ndarray, TimedeltaIndex, TimedeltaArray], nat_rep: str = "NaT", box: bool = False, ) -> Callable: """ Return a formatter function for a range of timedeltas. These will all have the same format argument If box, then show the return in quotes """ values_int = values.astype(np.int64) consider_values = values_int != iNaT one_day_nanos = 86400 * 1e9 even_days = ( np.logical_and(consider_values, values_int % one_day_nanos != 0).sum() == 0 ) all_sub_day = ( np.logical_and(consider_values, np.abs(values_int) >= one_day_nanos).sum() == 0 ) if even_days: format = None elif all_sub_day: format = "sub_day" else: format = "long" def _formatter(x): if x is None or (is_scalar(x) and isna(x)): return nat_rep if not isinstance(x, Timedelta): x = Timedelta(x) result = x._repr_base(format=format) if box: result = "'{res}'".format(res=result) return result return _formatter
[ "def", "_get_format_timedelta64", "(", "values", ":", "Union", "[", "np", ".", "ndarray", ",", "TimedeltaIndex", ",", "TimedeltaArray", "]", ",", "nat_rep", ":", "str", "=", "\"NaT\"", ",", "box", ":", "bool", "=", "False", ",", ")", "->", "Callable", ":...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/io/formats/format.py#L1686-L1728
perilouswithadollarsign/cstrike15_src
f82112a2388b841d72cb62ca48ab1846dfcc11c8
thirdparty/protobuf-2.5.0/python/google/protobuf/descriptor.py
python
_NestedDescriptorBase.__init__
(self, options, options_class_name, name, full_name, file, containing_type, serialized_start=None, serialized_end=None)
Constructor. Args: options: Protocol message options or None to use default message options. options_class_name: (str) The class name of the above options. name: (str) Name of this protocol message type. full_name: (str) Fully-qualified name of this protocol message type, which will include protocol "package" name and the name of any enclosing types. file: (FileDescriptor) Reference to file info. containing_type: if provided, this is a nested descriptor, with this descriptor as parent, otherwise None. serialized_start: The start index (inclusive) in block in the file.serialized_pb that describes this descriptor. serialized_end: The end index (exclusive) in block in the file.serialized_pb that describes this descriptor.
Constructor.
[ "Constructor", "." ]
def __init__(self, options, options_class_name, name, full_name, file, containing_type, serialized_start=None, serialized_end=None): """Constructor. Args: options: Protocol message options or None to use default message options. options_class_name: (str) The class name of the above options. name: (str) Name of this protocol message type. full_name: (str) Fully-qualified name of this protocol message type, which will include protocol "package" name and the name of any enclosing types. file: (FileDescriptor) Reference to file info. containing_type: if provided, this is a nested descriptor, with this descriptor as parent, otherwise None. serialized_start: The start index (inclusive) in block in the file.serialized_pb that describes this descriptor. serialized_end: The end index (exclusive) in block in the file.serialized_pb that describes this descriptor. """ super(_NestedDescriptorBase, self).__init__( options, options_class_name) self.name = name # TODO(falk): Add function to calculate full_name instead of having it in # memory? self.full_name = full_name self.file = file self.containing_type = containing_type self._serialized_start = serialized_start self._serialized_end = serialized_end
[ "def", "__init__", "(", "self", ",", "options", ",", "options_class_name", ",", "name", ",", "full_name", ",", "file", ",", "containing_type", ",", "serialized_start", "=", "None", ",", "serialized_end", "=", "None", ")", ":", "super", "(", "_NestedDescriptorB...
https://github.com/perilouswithadollarsign/cstrike15_src/blob/f82112a2388b841d72cb62ca48ab1846dfcc11c8/thirdparty/protobuf-2.5.0/python/google/protobuf/descriptor.py#L115-L148
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/contrib/timeseries/python/timeseries/state_space_models/state_space_model.py
python
StateSpaceModel.initialize_graph
(self, input_statistics=None)
Define variables and ops relevant to the top-level model in an ensemble. For generic model parameters, _define_parameters() is called recursively on all members of an ensemble. Args: input_statistics: A math_utils.InputStatistics object containing input statistics. If None, data-independent defaults are used, which may result in longer or unstable training.
Define variables and ops relevant to the top-level model in an ensemble.
[ "Define", "variables", "and", "ops", "relevant", "to", "the", "top", "-", "level", "model", "in", "an", "ensemble", "." ]
def initialize_graph(self, input_statistics=None): """Define variables and ops relevant to the top-level model in an ensemble. For generic model parameters, _define_parameters() is called recursively on all members of an ensemble. Args: input_statistics: A math_utils.InputStatistics object containing input statistics. If None, data-independent defaults are used, which may result in longer or unstable training. """ self._set_input_statistics(input_statistics=input_statistics) self._define_parameters() with variable_scope.variable_scope(self._variable_scope): self._observation_noise_covariance = ops.convert_to_tensor( self.get_observation_noise_covariance(), dtype=self.dtype) self._kalman_filter = kalman_filter.KalmanFilter(dtype=self.dtype) (self.prior_state_mean, self.prior_state_var) = self._make_priors()
[ "def", "initialize_graph", "(", "self", ",", "input_statistics", "=", "None", ")", ":", "self", ".", "_set_input_statistics", "(", "input_statistics", "=", "input_statistics", ")", "self", ".", "_define_parameters", "(", ")", "with", "variable_scope", ".", "variab...
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/timeseries/python/timeseries/state_space_models/state_space_model.py#L677-L695
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
tools/telemetry/telemetry/core/bitmap.py
python
Bitmap.Diff
(self, other)
return diff
Returns a new Bitmap that represents the difference between this image and another Bitmap.
Returns a new Bitmap that represents the difference between this image and another Bitmap.
[ "Returns", "a", "new", "Bitmap", "that", "represents", "the", "difference", "between", "this", "image", "and", "another", "Bitmap", "." ]
def Diff(self, other): """Returns a new Bitmap that represents the difference between this image and another Bitmap.""" # Output dimensions will be the maximum of the two input dimensions out_width = max(self.width, other.width) out_height = max(self.height, other.height) diff = [[0 for x in xrange(out_width * 3)] for x in xrange(out_height)] # Loop over each pixel and write out the difference for y in range(out_height): for x in range(out_width): if x < self.width and y < self.height: c0 = self.GetPixelColor(x, y) else: c0 = RgbaColor(0, 0, 0, 0) if x < other.width and y < other.height: c1 = other.GetPixelColor(x, y) else: c1 = RgbaColor(0, 0, 0, 0) offset = x * 3 diff[y][offset] = abs(c0.r - c1.r) diff[y][offset+1] = abs(c0.g - c1.g) diff[y][offset+2] = abs(c0.b - c1.b) # This particular method can only save to a file, so the result will be # written into an in-memory buffer and read back into a Bitmap diff_img = png.from_array(diff, mode='RGB') output = cStringIO.StringIO() try: diff_img.save(output) diff = Bitmap.FromPng(output.getvalue()) finally: output.close() return diff
[ "def", "Diff", "(", "self", ",", "other", ")", ":", "# Output dimensions will be the maximum of the two input dimensions", "out_width", "=", "max", "(", "self", ".", "width", ",", "other", ".", "width", ")", "out_height", "=", "max", "(", "self", ".", "height", ...
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/telemetry/telemetry/core/bitmap.py#L281-L319
wy1iu/LargeMargin_Softmax_Loss
c3e9f20e4f16e2b4daf7d358a614366b9b39a6ec
scripts/cpp_lint.py
python
IsCppString
(line)
return ((line.count('"') - line.count(r'\"') - line.count("'\"'")) & 1) == 1
Does line terminate so, that the next symbol is in string constant. This function does not consider single-line nor multi-line comments. Args: line: is a partial line of code starting from the 0..n. Returns: True, if next character appended to 'line' is inside a string constant.
Does line terminate so, that the next symbol is in string constant.
[ "Does", "line", "terminate", "so", "that", "the", "next", "symbol", "is", "in", "string", "constant", "." ]
def IsCppString(line): """Does line terminate so, that the next symbol is in string constant. This function does not consider single-line nor multi-line comments. Args: line: is a partial line of code starting from the 0..n. Returns: True, if next character appended to 'line' is inside a string constant. """ line = line.replace(r'\\', 'XX') # after this, \\" does not match to \" return ((line.count('"') - line.count(r'\"') - line.count("'\"'")) & 1) == 1
[ "def", "IsCppString", "(", "line", ")", ":", "line", "=", "line", ".", "replace", "(", "r'\\\\'", ",", "'XX'", ")", "# after this, \\\\\" does not match to \\\"", "return", "(", "(", "line", ".", "count", "(", "'\"'", ")", "-", "line", ".", "count", "(", ...
https://github.com/wy1iu/LargeMargin_Softmax_Loss/blob/c3e9f20e4f16e2b4daf7d358a614366b9b39a6ec/scripts/cpp_lint.py#L1045-L1059
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/Jinja2/py3/jinja2/sandbox.py
python
safe_range
(*args: int)
return rng
A range that can't generate ranges with a length of more than MAX_RANGE items.
A range that can't generate ranges with a length of more than MAX_RANGE items.
[ "A", "range", "that", "can", "t", "generate", "ranges", "with", "a", "length", "of", "more", "than", "MAX_RANGE", "items", "." ]
def safe_range(*args: int) -> range: """A range that can't generate ranges with a length of more than MAX_RANGE items. """ rng = range(*args) if len(rng) > MAX_RANGE: raise OverflowError( "Range too big. The sandbox blocks ranges larger than" f" MAX_RANGE ({MAX_RANGE})." ) return rng
[ "def", "safe_range", "(", "*", "args", ":", "int", ")", "->", "range", ":", "rng", "=", "range", "(", "*", "args", ")", "if", "len", "(", "rng", ")", ">", "MAX_RANGE", ":", "raise", "OverflowError", "(", "\"Range too big. The sandbox blocks ranges larger tha...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/Jinja2/py3/jinja2/sandbox.py#L97-L109
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/Jinja2/py2/jinja2/filters.py
python
do_mark_safe
(value)
return Markup(value)
Mark the value as safe which means that in an environment with automatic escaping enabled this variable will not be escaped.
Mark the value as safe which means that in an environment with automatic escaping enabled this variable will not be escaped.
[ "Mark", "the", "value", "as", "safe", "which", "means", "that", "in", "an", "environment", "with", "automatic", "escaping", "enabled", "this", "variable", "will", "not", "be", "escaped", "." ]
def do_mark_safe(value): """Mark the value as safe which means that in an environment with automatic escaping enabled this variable will not be escaped. """ return Markup(value)
[ "def", "do_mark_safe", "(", "value", ")", ":", "return", "Markup", "(", "value", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/Jinja2/py2/jinja2/filters.py#L1019-L1023
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/client/timeline.py
python
Timeline._allocate_pids
(self)
Allocate fake process ids for each device in the StepStats.
Allocate fake process ids for each device in the StepStats.
[ "Allocate", "fake", "process", "ids", "for", "each", "device", "in", "the", "StepStats", "." ]
def _allocate_pids(self): """Allocate fake process ids for each device in the StepStats.""" self._allocators_pid = self._alloc_pid() self._chrome_trace.emit_pid('Allocators', self._allocators_pid) # Add processes in the Chrome trace to show compute and data activity. for dev_stats in self._step_stats.dev_stats: device_pid = self._alloc_pid() self._device_pids[dev_stats.device] = device_pid tensors_pid = self._alloc_pid() self._tensor_pids[dev_stats.device] = tensors_pid self._chrome_trace.emit_pid(dev_stats.device + ' Compute', device_pid) self._chrome_trace.emit_pid(dev_stats.device + ' Tensors', tensors_pid)
[ "def", "_allocate_pids", "(", "self", ")", ":", "self", ".", "_allocators_pid", "=", "self", ".", "_alloc_pid", "(", ")", "self", ".", "_chrome_trace", ".", "emit_pid", "(", "'Allocators'", ",", "self", ".", "_allocators_pid", ")", "# Add processes in the Chrome...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/client/timeline.py#L469-L481
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/framework/ops.py
python
get_collection_ref
(key)
return get_default_graph().get_collection_ref(key)
Wrapper for `Graph.get_collection_ref()` using the default graph. See `tf.Graph.get_collection_ref` for more details. Args: key: The key for the collection. For example, the `GraphKeys` class contains many standard names for collections. Returns: The list of values in the collection with the given `name`, or an empty list if no value has been added to that collection. Note that this returns the collection list itself, which can be modified in place to change the collection. @compatibility(eager) Collections are not supported when eager execution is enabled. @end_compatibility
Wrapper for `Graph.get_collection_ref()` using the default graph.
[ "Wrapper", "for", "Graph", ".", "get_collection_ref", "()", "using", "the", "default", "graph", "." ]
def get_collection_ref(key): """Wrapper for `Graph.get_collection_ref()` using the default graph. See `tf.Graph.get_collection_ref` for more details. Args: key: The key for the collection. For example, the `GraphKeys` class contains many standard names for collections. Returns: The list of values in the collection with the given `name`, or an empty list if no value has been added to that collection. Note that this returns the collection list itself, which can be modified in place to change the collection. @compatibility(eager) Collections are not supported when eager execution is enabled. @end_compatibility """ return get_default_graph().get_collection_ref(key)
[ "def", "get_collection_ref", "(", "key", ")", ":", "return", "get_default_graph", "(", ")", ".", "get_collection_ref", "(", "key", ")" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/framework/ops.py#L6638-L6658
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/keras/engine/data_adapter.py
python
DataAdapter.on_epoch_end
(self)
A hook called after each epoch.
A hook called after each epoch.
[ "A", "hook", "called", "after", "each", "epoch", "." ]
def on_epoch_end(self): """A hook called after each epoch.""" pass
[ "def", "on_epoch_end", "(", "self", ")", ":", "pass" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/keras/engine/data_adapter.py#L207-L209
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pyparsing/py3/pyparsing/common.py
python
pyparsing_common.convert_to_date
(fmt: str = "%Y-%m-%d")
return cvt_fn
Helper to create a parse action for converting parsed date string to Python datetime.date Params - - fmt - format to be passed to datetime.strptime (default= ``"%Y-%m-%d"``) Example:: date_expr = pyparsing_common.iso8601_date.copy() date_expr.setParseAction(pyparsing_common.convertToDate()) print(date_expr.parseString("1999-12-31")) prints:: [datetime.date(1999, 12, 31)]
Helper to create a parse action for converting parsed date string to Python datetime.date
[ "Helper", "to", "create", "a", "parse", "action", "for", "converting", "parsed", "date", "string", "to", "Python", "datetime", ".", "date" ]
def convert_to_date(fmt: str = "%Y-%m-%d"): """ Helper to create a parse action for converting parsed date string to Python datetime.date Params - - fmt - format to be passed to datetime.strptime (default= ``"%Y-%m-%d"``) Example:: date_expr = pyparsing_common.iso8601_date.copy() date_expr.setParseAction(pyparsing_common.convertToDate()) print(date_expr.parseString("1999-12-31")) prints:: [datetime.date(1999, 12, 31)] """ def cvt_fn(ss, ll, tt): try: return datetime.strptime(tt[0], fmt).date() except ValueError as ve: raise ParseException(ss, ll, str(ve)) return cvt_fn
[ "def", "convert_to_date", "(", "fmt", ":", "str", "=", "\"%Y-%m-%d\"", ")", ":", "def", "cvt_fn", "(", "ss", ",", "ll", ",", "tt", ")", ":", "try", ":", "return", "datetime", ".", "strptime", "(", "tt", "[", "0", "]", ",", "fmt", ")", ".", "date"...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pyparsing/py3/pyparsing/common.py#L253-L277
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py3/pandas/core/generic.py
python
NDFrame.asfreq
( self: FrameOrSeries, freq, method=None, how: str | None = None, normalize: bool_t = False, fill_value=None, )
return asfreq( self, freq, method=method, how=how, normalize=normalize, fill_value=fill_value, )
Convert time series to specified frequency. Returns the original data conformed to a new index with the specified frequency. If the index of this {klass} is a :class:`~pandas.PeriodIndex`, the new index is the result of transforming the original index with :meth:`PeriodIndex.asfreq <pandas.PeriodIndex.asfreq>` (so the original index will map one-to-one to the new index). Otherwise, the new index will be equivalent to ``pd.date_range(start, end, freq=freq)`` where ``start`` and ``end`` are, respectively, the first and last entries in the original index (see :func:`pandas.date_range`). The values corresponding to any timesteps in the new index which were not present in the original index will be null (``NaN``), unless a method for filling such unknowns is provided (see the ``method`` parameter below). The :meth:`resample` method is more appropriate if an operation on each group of timesteps (such as an aggregate) is necessary to represent the data at the new frequency. Parameters ---------- freq : DateOffset or str Frequency DateOffset or string. method : {{'backfill'/'bfill', 'pad'/'ffill'}}, default None Method to use for filling holes in reindexed Series (note this does not fill NaNs that already were present): * 'pad' / 'ffill': propagate last valid observation forward to next valid * 'backfill' / 'bfill': use NEXT valid observation to fill. how : {{'start', 'end'}}, default end For PeriodIndex only (see PeriodIndex.asfreq). normalize : bool, default False Whether to reset output index to midnight. fill_value : scalar, optional Value to use for missing values, applied during upsampling (note this does not fill NaNs that already were present). Returns ------- {klass} {klass} object reindexed to the specified frequency. See Also -------- reindex : Conform DataFrame to new index with optional filling logic. Notes ----- To learn more about the frequency strings, please see `this link <https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#offset-aliases>`__. Examples -------- Start by creating a series with 4 one minute timestamps. >>> index = pd.date_range('1/1/2000', periods=4, freq='T') >>> series = pd.Series([0.0, None, 2.0, 3.0], index=index) >>> df = pd.DataFrame({{'s': series}}) >>> df s 2000-01-01 00:00:00 0.0 2000-01-01 00:01:00 NaN 2000-01-01 00:02:00 2.0 2000-01-01 00:03:00 3.0 Upsample the series into 30 second bins. >>> df.asfreq(freq='30S') s 2000-01-01 00:00:00 0.0 2000-01-01 00:00:30 NaN 2000-01-01 00:01:00 NaN 2000-01-01 00:01:30 NaN 2000-01-01 00:02:00 2.0 2000-01-01 00:02:30 NaN 2000-01-01 00:03:00 3.0 Upsample again, providing a ``fill value``. >>> df.asfreq(freq='30S', fill_value=9.0) s 2000-01-01 00:00:00 0.0 2000-01-01 00:00:30 9.0 2000-01-01 00:01:00 NaN 2000-01-01 00:01:30 9.0 2000-01-01 00:02:00 2.0 2000-01-01 00:02:30 9.0 2000-01-01 00:03:00 3.0 Upsample again, providing a ``method``. >>> df.asfreq(freq='30S', method='bfill') s 2000-01-01 00:00:00 0.0 2000-01-01 00:00:30 NaN 2000-01-01 00:01:00 NaN 2000-01-01 00:01:30 2.0 2000-01-01 00:02:00 2.0 2000-01-01 00:02:30 3.0 2000-01-01 00:03:00 3.0
Convert time series to specified frequency.
[ "Convert", "time", "series", "to", "specified", "frequency", "." ]
def asfreq( self: FrameOrSeries, freq, method=None, how: str | None = None, normalize: bool_t = False, fill_value=None, ) -> FrameOrSeries: """ Convert time series to specified frequency. Returns the original data conformed to a new index with the specified frequency. If the index of this {klass} is a :class:`~pandas.PeriodIndex`, the new index is the result of transforming the original index with :meth:`PeriodIndex.asfreq <pandas.PeriodIndex.asfreq>` (so the original index will map one-to-one to the new index). Otherwise, the new index will be equivalent to ``pd.date_range(start, end, freq=freq)`` where ``start`` and ``end`` are, respectively, the first and last entries in the original index (see :func:`pandas.date_range`). The values corresponding to any timesteps in the new index which were not present in the original index will be null (``NaN``), unless a method for filling such unknowns is provided (see the ``method`` parameter below). The :meth:`resample` method is more appropriate if an operation on each group of timesteps (such as an aggregate) is necessary to represent the data at the new frequency. Parameters ---------- freq : DateOffset or str Frequency DateOffset or string. method : {{'backfill'/'bfill', 'pad'/'ffill'}}, default None Method to use for filling holes in reindexed Series (note this does not fill NaNs that already were present): * 'pad' / 'ffill': propagate last valid observation forward to next valid * 'backfill' / 'bfill': use NEXT valid observation to fill. how : {{'start', 'end'}}, default end For PeriodIndex only (see PeriodIndex.asfreq). normalize : bool, default False Whether to reset output index to midnight. fill_value : scalar, optional Value to use for missing values, applied during upsampling (note this does not fill NaNs that already were present). Returns ------- {klass} {klass} object reindexed to the specified frequency. See Also -------- reindex : Conform DataFrame to new index with optional filling logic. Notes ----- To learn more about the frequency strings, please see `this link <https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#offset-aliases>`__. Examples -------- Start by creating a series with 4 one minute timestamps. >>> index = pd.date_range('1/1/2000', periods=4, freq='T') >>> series = pd.Series([0.0, None, 2.0, 3.0], index=index) >>> df = pd.DataFrame({{'s': series}}) >>> df s 2000-01-01 00:00:00 0.0 2000-01-01 00:01:00 NaN 2000-01-01 00:02:00 2.0 2000-01-01 00:03:00 3.0 Upsample the series into 30 second bins. >>> df.asfreq(freq='30S') s 2000-01-01 00:00:00 0.0 2000-01-01 00:00:30 NaN 2000-01-01 00:01:00 NaN 2000-01-01 00:01:30 NaN 2000-01-01 00:02:00 2.0 2000-01-01 00:02:30 NaN 2000-01-01 00:03:00 3.0 Upsample again, providing a ``fill value``. >>> df.asfreq(freq='30S', fill_value=9.0) s 2000-01-01 00:00:00 0.0 2000-01-01 00:00:30 9.0 2000-01-01 00:01:00 NaN 2000-01-01 00:01:30 9.0 2000-01-01 00:02:00 2.0 2000-01-01 00:02:30 9.0 2000-01-01 00:03:00 3.0 Upsample again, providing a ``method``. >>> df.asfreq(freq='30S', method='bfill') s 2000-01-01 00:00:00 0.0 2000-01-01 00:00:30 NaN 2000-01-01 00:01:00 NaN 2000-01-01 00:01:30 2.0 2000-01-01 00:02:00 2.0 2000-01-01 00:02:30 3.0 2000-01-01 00:03:00 3.0 """ from pandas.core.resample import asfreq return asfreq( self, freq, method=method, how=how, normalize=normalize, fill_value=fill_value, )
[ "def", "asfreq", "(", "self", ":", "FrameOrSeries", ",", "freq", ",", "method", "=", "None", ",", "how", ":", "str", "|", "None", "=", "None", ",", "normalize", ":", "bool_t", "=", "False", ",", "fill_value", "=", "None", ",", ")", "->", "FrameOrSeri...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/generic.py#L7447-L7569
google/or-tools
2cb85b4eead4c38e1c54b48044f92087cf165bce
ortools/sat/python/cp_model.py
python
CpSolver.BestObjectiveBound
(self)
return self.__solution.best_objective_bound
Returns the best lower (upper) bound found when min(max)imizing.
Returns the best lower (upper) bound found when min(max)imizing.
[ "Returns", "the", "best", "lower", "(", "upper", ")", "bound", "found", "when", "min", "(", "max", ")", "imizing", "." ]
def BestObjectiveBound(self): """Returns the best lower (upper) bound found when min(max)imizing.""" return self.__solution.best_objective_bound
[ "def", "BestObjectiveBound", "(", "self", ")", ":", "return", "self", ".", "__solution", ".", "best_objective_bound" ]
https://github.com/google/or-tools/blob/2cb85b4eead4c38e1c54b48044f92087cf165bce/ortools/sat/python/cp_model.py#L2171-L2173
citizenfx/fivem
88276d40cc7baf8285d02754cc5ae42ec7a8563f
vendor/chromium/mojo/public/tools/bindings/pylib/mojom/parse/parser.py
python
Parser.p_identifier
(self, p)
identifier : NAME | NAME DOT identifier
identifier : NAME | NAME DOT identifier
[ "identifier", ":", "NAME", "|", "NAME", "DOT", "identifier" ]
def p_identifier(self, p): """identifier : NAME | NAME DOT identifier""" p[0] = ''.join(p[1:])
[ "def", "p_identifier", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "''", ".", "join", "(", "p", "[", "1", ":", "]", ")" ]
https://github.com/citizenfx/fivem/blob/88276d40cc7baf8285d02754cc5ae42ec7a8563f/vendor/chromium/mojo/public/tools/bindings/pylib/mojom/parse/parser.py#L411-L414
SpenceKonde/megaTinyCore
1c4a70b18a149fe6bcb551dfa6db11ca50b8997b
megaavr/tools/libs/serial/urlhandler/protocol_loop.py
python
Serial._reconfigure_port
(self)
\ Set communication parameters on opened port. For the loop:// protocol all settings are ignored!
\ Set communication parameters on opened port. For the loop:// protocol all settings are ignored!
[ "\\", "Set", "communication", "parameters", "on", "opened", "port", ".", "For", "the", "loop", ":", "//", "protocol", "all", "settings", "are", "ignored!" ]
def _reconfigure_port(self): """\ Set communication parameters on opened port. For the loop:// protocol all settings are ignored! """ # not that's it of any real use, but it helps in the unit tests if not isinstance(self._baudrate, numbers.Integral) or not 0 < self._baudrate < 2 ** 32: raise ValueError("invalid baudrate: {!r}".format(self._baudrate)) if self.logger: self.logger.info('_reconfigure_port()')
[ "def", "_reconfigure_port", "(", "self", ")", ":", "# not that's it of any real use, but it helps in the unit tests", "if", "not", "isinstance", "(", "self", ".", "_baudrate", ",", "numbers", ".", "Integral", ")", "or", "not", "0", "<", "self", ".", "_baudrate", "...
https://github.com/SpenceKonde/megaTinyCore/blob/1c4a70b18a149fe6bcb551dfa6db11ca50b8997b/megaavr/tools/libs/serial/urlhandler/protocol_loop.py#L88-L97
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/SimpleXMLRPCServer.py
python
remove_duplicates
(lst)
return u.keys()
remove_duplicates([2,2,2,1,3,3]) => [3,1,2] Returns a copy of a list without duplicates. Every list item must be hashable and the order of the items in the resulting list is not defined.
remove_duplicates([2,2,2,1,3,3]) => [3,1,2]
[ "remove_duplicates", "(", "[", "2", "2", "2", "1", "3", "3", "]", ")", "=", ">", "[", "3", "1", "2", "]" ]
def remove_duplicates(lst): """remove_duplicates([2,2,2,1,3,3]) => [3,1,2] Returns a copy of a list without duplicates. Every list item must be hashable and the order of the items in the resulting list is not defined. """ u = {} for x in lst: u[x] = 1 return u.keys()
[ "def", "remove_duplicates", "(", "lst", ")", ":", "u", "=", "{", "}", "for", "x", "in", "lst", ":", "u", "[", "x", "]", "=", "1", "return", "u", ".", "keys", "(", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/SimpleXMLRPCServer.py#L147-L158
Jittor/jittor
e9aca0444c2bdc8e2389d99122954cd0903eec46
python/jittor/transform/__init__.py
python
resize
(img, size, interpolation=Image.BILINEAR)
Function for resizing image. Args:: [in] img(Image.Image): Input image. [in] size: resize size. [h, w] [in] interpolation(int): type of resize. default: PIL.Image.BILINEAR Example:: img = Image.open(...) img_ = transform.resize(img, (100, 100))
Function for resizing image.
[ "Function", "for", "resizing", "image", "." ]
def resize(img, size, interpolation=Image.BILINEAR): ''' Function for resizing image. Args:: [in] img(Image.Image): Input image. [in] size: resize size. [h, w] [in] interpolation(int): type of resize. default: PIL.Image.BILINEAR Example:: img = Image.open(...) img_ = transform.resize(img, (100, 100)) ''' if isinstance(size, Sequence): return img.resize(size[::-1], interpolation) else: w, h = img.size if (h > w): return img.resize((size, int(round(size * h / w))), interpolation) else: return img.resize((int(round(size * w / h)), size), interpolation)
[ "def", "resize", "(", "img", ",", "size", ",", "interpolation", "=", "Image", ".", "BILINEAR", ")", ":", "if", "isinstance", "(", "size", ",", "Sequence", ")", ":", "return", "img", ".", "resize", "(", "size", "[", ":", ":", "-", "1", "]", ",", "...
https://github.com/Jittor/jittor/blob/e9aca0444c2bdc8e2389d99122954cd0903eec46/python/jittor/transform/__init__.py#L58-L80
Polidea/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py
python
SBBreakpoint.MatchesName
(self, *args)
return _lldb.SBBreakpoint_MatchesName(self, *args)
MatchesName(self, str name) -> bool
MatchesName(self, str name) -> bool
[ "MatchesName", "(", "self", "str", "name", ")", "-", ">", "bool" ]
def MatchesName(self, *args): """MatchesName(self, str name) -> bool""" return _lldb.SBBreakpoint_MatchesName(self, *args)
[ "def", "MatchesName", "(", "self", ",", "*", "args", ")", ":", "return", "_lldb", ".", "SBBreakpoint_MatchesName", "(", "self", ",", "*", "args", ")" ]
https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L1593-L1595
qboticslabs/mastering_ros
d83e78f30acc45b0f18522c1d5fae3a7f52974b9
chapter_3_codes/seven_dof_arm_gazebo/scripts/pick_and_place_pick_working.py
python
CokeCanPickAndPlace._publish_places
(self, places)
Publish places as poses, using a PoseArray message
Publish places as poses, using a PoseArray message
[ "Publish", "places", "as", "poses", "using", "a", "PoseArray", "message" ]
def _publish_places(self, places): """ Publish places as poses, using a PoseArray message """ if self._places_pub.get_num_connections() > 0: msg = PoseArray() msg.header.frame_id = self._robot.get_planning_frame() msg.header.stamp = rospy.Time.now() for place in places: msg.poses.append(place.place_pose.pose) self._places_pub.publish(msg)
[ "def", "_publish_places", "(", "self", ",", "places", ")", ":", "if", "self", ".", "_places_pub", ".", "get_num_connections", "(", ")", ">", "0", ":", "msg", "=", "PoseArray", "(", ")", "msg", ".", "header", ".", "frame_id", "=", "self", ".", "_robot",...
https://github.com/qboticslabs/mastering_ros/blob/d83e78f30acc45b0f18522c1d5fae3a7f52974b9/chapter_3_codes/seven_dof_arm_gazebo/scripts/pick_and_place_pick_working.py#L368-L381
psi4/psi4
be533f7f426b6ccc263904e55122899b16663395
psi4/driver/p4util/solvers.py
python
hamiltonian_solver
(engine, guess: List, *, nroot: int, r_convergence: float = 1.0E-4, max_ss_size: int = 100, maxiter: int = 60, verbose: int = 1)
return {"eigvals": best_vals, "eigvecs": list(zip(best_R, best_L)), "stats": stats}
Finds the smallest eigenvalues and associated right and left hand eigenvectors of a large real Hamiltonian eigenvalue problem emulated through an engine. A Hamiltonian eigenvalue problem (EVP) has the following structure: [A B][X] = [1 0](w)[X] [B A][Y] [0 -1](w)[Y] with A, B of some large dimension N, the problem is of dimension 2Nx2N. The real, Hamiltonian EVP can be rewritten as the NxN, non-hermitian EVP: (A+B)(A-B)(X+Y) = w^2(X+Y) With left-hand eigenvectors: (X-Y)(A-B)(A+B) = w^2(X-Y) if (A-B) is positive definite, we can transform the problem to arrive at the hermitian NxN EVP: (A-B)^1/2(A+B)(A-B)^1/2 = w^2 T Where T = (A-B)^-1/2(X+Y). We use a Davidson like iteration where we transform (A+B) (H1) and (A-B) (H2) in to the subspace defined by the trial vectors. The subspace analog of the NxN hermitian EVP is diagonalized and left (X-Y) and right (X+Y) eigenvectors of the NxN non-hermitian EVP are approximated. Residual vectors are formed for both and the guess space is augmented with two correction vectors per iteration. The advantages and properties of this algorithm are described in the literature [stratmann:1998]_ . Parameters ----------- engine : object (subclass of :class:`SolverEngine`) The engine drive all operations involving data structures that have at least one "large" dimension. See :class:`SolverEngine` for requirements guess list {engine dependent} At least `nroot` initial expansion vectors nroot Number of roots desired r_convergence Convergence tolerance for residual vectors max_ss_size: The maximum number of trial vectors in the iterative subspace that will be stored before a collapse is done. maxiter The maximum number of iterations verbose The amount of logging info to print (0 -> none, 1 -> some, >1 -> everything) Returns ------- best_values : numpy.ndarray (nroots, ) The best approximation of the eigenvalues of `w`, computed on the last iteration of the solver best_R: list of `vector` (nroots) The best approximation of the right hand eigenvectors, `X+Y`, computed on the last iteration of the solver. best_L: list of `vector` (nroots) The best approximation of the left hand eigenvectors, `X-Y`, computed on the last iteration of the solver. stats : list of `dict` Statistics collected on each iteration count : int, iteration number res_norm : np.ndarray (nroots, ), the norm of residual vector for each roots val : np.ndarray (nroots, ), the eigenvalue corresponding to each root delta_val : np.ndarray (nroots, ), the change in eigenvalue from the last iteration to this ones collapse : bool, if a subspace collapse was performed product_count : int, the running total of product evaluations that was performed done : bool, if all roots were converged Notes ----- The solution vector is normalized to 1/2 The solver will return even when ``maxiter`` iterations are performed without convergence. The caller **must check** `stats[-1]['done']` for failure and handle each case accordingly. References ---------- R. Eric Stratmann, G. E. Scuseria, and M. J. Frisch, "An efficient implementation of time-dependent density-functional theory for the calculation of excitation energies of large molecules." J. Chem. Phys., 109, 8218 (1998)
Finds the smallest eigenvalues and associated right and left hand eigenvectors of a large real Hamiltonian eigenvalue problem emulated through an engine.
[ "Finds", "the", "smallest", "eigenvalues", "and", "associated", "right", "and", "left", "hand", "eigenvectors", "of", "a", "large", "real", "Hamiltonian", "eigenvalue", "problem", "emulated", "through", "an", "engine", "." ]
def hamiltonian_solver(engine, guess: List, *, nroot: int, r_convergence: float = 1.0E-4, max_ss_size: int = 100, maxiter: int = 60, verbose: int = 1): """Finds the smallest eigenvalues and associated right and left hand eigenvectors of a large real Hamiltonian eigenvalue problem emulated through an engine. A Hamiltonian eigenvalue problem (EVP) has the following structure: [A B][X] = [1 0](w)[X] [B A][Y] [0 -1](w)[Y] with A, B of some large dimension N, the problem is of dimension 2Nx2N. The real, Hamiltonian EVP can be rewritten as the NxN, non-hermitian EVP: (A+B)(A-B)(X+Y) = w^2(X+Y) With left-hand eigenvectors: (X-Y)(A-B)(A+B) = w^2(X-Y) if (A-B) is positive definite, we can transform the problem to arrive at the hermitian NxN EVP: (A-B)^1/2(A+B)(A-B)^1/2 = w^2 T Where T = (A-B)^-1/2(X+Y). We use a Davidson like iteration where we transform (A+B) (H1) and (A-B) (H2) in to the subspace defined by the trial vectors. The subspace analog of the NxN hermitian EVP is diagonalized and left (X-Y) and right (X+Y) eigenvectors of the NxN non-hermitian EVP are approximated. Residual vectors are formed for both and the guess space is augmented with two correction vectors per iteration. The advantages and properties of this algorithm are described in the literature [stratmann:1998]_ . Parameters ----------- engine : object (subclass of :class:`SolverEngine`) The engine drive all operations involving data structures that have at least one "large" dimension. See :class:`SolverEngine` for requirements guess list {engine dependent} At least `nroot` initial expansion vectors nroot Number of roots desired r_convergence Convergence tolerance for residual vectors max_ss_size: The maximum number of trial vectors in the iterative subspace that will be stored before a collapse is done. maxiter The maximum number of iterations verbose The amount of logging info to print (0 -> none, 1 -> some, >1 -> everything) Returns ------- best_values : numpy.ndarray (nroots, ) The best approximation of the eigenvalues of `w`, computed on the last iteration of the solver best_R: list of `vector` (nroots) The best approximation of the right hand eigenvectors, `X+Y`, computed on the last iteration of the solver. best_L: list of `vector` (nroots) The best approximation of the left hand eigenvectors, `X-Y`, computed on the last iteration of the solver. stats : list of `dict` Statistics collected on each iteration count : int, iteration number res_norm : np.ndarray (nroots, ), the norm of residual vector for each roots val : np.ndarray (nroots, ), the eigenvalue corresponding to each root delta_val : np.ndarray (nroots, ), the change in eigenvalue from the last iteration to this ones collapse : bool, if a subspace collapse was performed product_count : int, the running total of product evaluations that was performed done : bool, if all roots were converged Notes ----- The solution vector is normalized to 1/2 The solver will return even when ``maxiter`` iterations are performed without convergence. The caller **must check** `stats[-1]['done']` for failure and handle each case accordingly. References ---------- R. Eric Stratmann, G. E. Scuseria, and M. J. Frisch, "An efficient implementation of time-dependent density-functional theory for the calculation of excitation energies of large molecules." J. Chem. Phys., 109, 8218 (1998) """ nk = nroot iter_info = { "count": 0, "res_norm": np.zeros((nk)), "val": np.zeros((nk)), "delta_val": np.zeros((nk)), # conv defaults to true, and will be flipped when a non-conv root is hit "conv": True, "nvec": 0, "product_count": 0, } print_name = "HamiltonianSolver" title_lines = ["Generalized Hamiltonian Solver", "By Andrew M. James"] _diag_print_heading(title_lines, print_name, max_ss_size, nroot, r_convergence, maxiter, verbose) vecs = guess best_L = [] best_R = [] best_vals = [] stats = [] while iter_info['count'] < maxiter: # increment iteration/ save old vals iter_info['count'] += 1 old_w = iter_info['val'].copy() # reset flags iter_info['collapse'] = False iter_info['done'] = True # get subspace dimension l = len(vecs) iter_info['nvec'] = l # check if subspace dimension has exceeded limits if l >= max_ss_size: iter_info['collapse'] = True # compute [A+B]*v (H1x) and [A-B]*v (H2x) H1x, H2x, nprod = engine.compute_products(vecs) iter_info['product_count'] += nprod # form x*H1x (H1_ss) and x*H2x (H2_ss) H1_ss = np.zeros((l, l)) H2_ss = np.zeros((l, l)) for i in range(l): for j in range(l): H1_ss[i, j] = engine.vector_dot(vecs[i], H1x[j]) H2_ss[i, j] = engine.vector_dot(vecs[i], H2x[j]) _print_array("Subspace Transformed (A+B)", H1_ss, verbose) _print_array("Subspace Transformed (A-B)", H2_ss, verbose) # Diagonalize H2 in the subspace (eigen-decomposition to compute H2^(1/2)) H2_ss_val, H2_ss_vec = np.linalg.eigh(H2_ss) _print_array("eigenvalues H2_ss", H2_ss_val, verbose) _print_array("eigenvectors H2_ss", H2_ss_vec, verbose) # Check H2 is PD # NOTE: If this triggers failure the SCF solution is not stable. A few ways to handle this # 1. Use davidson solver where product function evaluates (H2 * (H1 * X)) # - Poor convergence # 2. Switch to CIS/TDA # - User would probably not expect this # 3. Perform Stability update and restart with new reference if np.any(H2_ss_val < 0.0): msg = ("The H2 matrix is not Positive Definite. " "This means the reference state is not stable.") raise RuntimeError(msg) # Build H2^(1/2) H2_ss_half = np.einsum("ik,k,jk->ij", H2_ss_vec, np.sqrt(H2_ss_val), H2_ss_vec, optimize=True) _print_array("SS Transformed (A-B)^(1/2)", H2_ss_half, verbose) # Build Hermitian SS product (H2)^(1/2)(H1)(H2)^(1/2) Hss = np.einsum('ij,jk,km->im', H2_ss_half, H1_ss, H2_ss_half, optimize=True) _print_array("(H2)^(1/2)(H1)(H2)^(1/2)", Hss, verbose) #diagonalize Hss -> w^2, Tss w2, Tss = np.linalg.eigh(Hss) _print_array("Eigenvalues (A-B)^(1/2)(A+B)(A-B)^(1/2)", w2, verbose) _print_array("Eigvectors (A-B)^(1/2)(A+B)(A-B)^(1/2)", Tss, verbose) # pick positive roots Tss = Tss[:, w2 > 1.0e-10] w2 = w2[w2 > 1.0e-10] # check for invalid eigvals with np.errstate(invalid='raise'): w = np.sqrt(w2) # sort roots idx = w.argsort()[:nk] Tss = Tss[:, idx] w = w[idx] # Extract Rss = H2^{1/2}Tss Rss = np.dot(H2_ss_half, Tss) # Extract Lss = (H1 R)/ w Lss = np.dot(H1_ss, Rss).dot(np.diag(1.0 / w)) # Biorthonormalize R/L solution vectors inners = np.einsum("ix,ix->x", Rss, Lss, optimize=True) Rss = np.einsum("x,ix->ix", 1. / np.sqrt(inners), Rss, optimize=True) Lss = np.einsum("x,ix->ix", 1. / np.sqrt(inners), Lss, optimize=True) # Save best R/L vectors and eigenvalues best_R = _best_vectors(engine, Rss[:, :nk], vecs) best_L = _best_vectors(engine, Lss[:, :nk], vecs) best_vals = w[:nk] # check convergence of each solution new_vecs = [] for k in range(nk): # residual vectors for right and left eigenvectors WR_k = engine.new_vector() WL_k = engine.new_vector() wk = w[k] for i in range(l): H1x_i = H1x[i] H2x_i = H2x[i] WL_k = engine.vector_axpy(Rss[i, k], H1x_i, WL_k) WR_k = engine.vector_axpy(Lss[i, k], H2x_i, WR_k) WL_k = engine.vector_axpy(-1.0 * wk, best_L[k], WL_k) WR_k = engine.vector_axpy(-1.0 * wk, best_R[k], WR_k) norm_R = np.sqrt(engine.vector_dot(WR_k, WR_k)) norm_L = np.sqrt(engine.vector_dot(WL_k, WL_k)) norm = norm_R + norm_L iter_info['res_norm'][k] = norm iter_info['delta_val'][k] = np.abs(old_w[k] - w[k]) iter_info['val'][k] = w[k] # augment the guess space for non-converged roots if (iter_info['res_norm'][k] > r_convergence): iter_info['done'] = False new_vecs.append(engine.precondition(WR_k, w[k])) new_vecs.append(engine.precondition(WL_k, w[k])) # print iteration info to output _diag_print_info(print_name, iter_info, verbose) # save stats for this iteration stats.append(iter_info.copy()) if iter_info['done']: # Finished _diag_print_converged(print_name, stats, w[:nk], rvec=best_R, lvec=best_L, verbose=verbose) break elif iter_info['collapse']: # need to orthonormalize union of the Left/Right solutions on restart vecs = _gs_orth(engine, [], best_R + best_L) else: # Regular subspace update, orthonormalize preconditioned residuals and add to the trial set vecs = _gs_orth(engine, vecs, new_vecs) # always return, the caller should check ret["stats"][-1]['done'] == True for convergence return {"eigvals": best_vals, "eigvecs": list(zip(best_R, best_L)), "stats": stats}
[ "def", "hamiltonian_solver", "(", "engine", ",", "guess", ":", "List", ",", "*", ",", "nroot", ":", "int", ",", "r_convergence", ":", "float", "=", "1.0E-4", ",", "max_ss_size", ":", "int", "=", "100", ",", "maxiter", ":", "int", "=", "60", ",", "ver...
https://github.com/psi4/psi4/blob/be533f7f426b6ccc263904e55122899b16663395/psi4/driver/p4util/solvers.py#L833-L1087
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/inspect.py
python
getabsfile
(object, _filename=None)
return os.path.normcase(os.path.abspath(_filename))
Return an absolute path to the source or compiled file for an object. The idea is for each object to have a unique origin, so this routine normalizes the result as much as possible.
Return an absolute path to the source or compiled file for an object.
[ "Return", "an", "absolute", "path", "to", "the", "source", "or", "compiled", "file", "for", "an", "object", "." ]
def getabsfile(object, _filename=None): """Return an absolute path to the source or compiled file for an object. The idea is for each object to have a unique origin, so this routine normalizes the result as much as possible.""" if _filename is None: _filename = getsourcefile(object) or getfile(object) return os.path.normcase(os.path.abspath(_filename))
[ "def", "getabsfile", "(", "object", ",", "_filename", "=", "None", ")", ":", "if", "_filename", "is", "None", ":", "_filename", "=", "getsourcefile", "(", "object", ")", "or", "getfile", "(", "object", ")", "return", "os", ".", "path", ".", "normcase", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/inspect.py#L702-L709
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/klampt/math/symbolic.py
python
Context.makePyFunction
(self,expr,varorder=None)
Converts an Expression or Function to a Python function ``f(x)`` that takes ``x`` as a list of scalar values, maps those to Variable values, and returns the result of evaluating the expression / function. Args: expr (:class:`Function` or :class:`Expression`): the function or expression to evaluate varorder (list, optional): If given, the list of Variables that should appear in the flattened argument list ``x``. If this isn't provided, then the Variables in ``expr`` are ordered by the order in which were added to this ``Context``. Returns: tuple: A pair ``(f,varorder)``, where: * ``f(x)`` is a 1-argument Python function equivalent to ``expr`` but where ``x`` is a list of variable values. * ``varorder`` gives the order of variables that should be sent in ``x``
Converts an Expression or Function to a Python function ``f(x)`` that takes ``x`` as a list of scalar values, maps those to Variable values, and returns the result of evaluating the expression / function.
[ "Converts", "an", "Expression", "or", "Function", "to", "a", "Python", "function", "f", "(", "x", ")", "that", "takes", "x", "as", "a", "list", "of", "scalar", "values", "maps", "those", "to", "Variable", "values", "and", "returns", "the", "result", "of"...
def makePyFunction(self,expr,varorder=None): """Converts an Expression or Function to a Python function ``f(x)`` that takes ``x`` as a list of scalar values, maps those to Variable values, and returns the result of evaluating the expression / function. Args: expr (:class:`Function` or :class:`Expression`): the function or expression to evaluate varorder (list, optional): If given, the list of Variables that should appear in the flattened argument list ``x``. If this isn't provided, then the Variables in ``expr`` are ordered by the order in which were added to this ``Context``. Returns: tuple: A pair ``(f,varorder)``, where: * ``f(x)`` is a 1-argument Python function equivalent to ``expr`` but where ``x`` is a list of variable values. * ``varorder`` gives the order of variables that should be sent in ``x`` """ if isinstance(expr,Function): if varorder is None: varnames = expr.argNames varorder = [self.variableDict[v] for v in varnames] iorder = list(range(len(varorder))) else: varorder = [(self.variableDict[v] if isinstance(v,str) else v) for v in varorder] iorder = [expr.argNames.index(v.name) for v in varorder] varnames = [v.name for v in varorder] def f(*args): eargs = expr.argNames[:] for i,a in zip(iorder,args): eargs[i] = a #print("Arguments",eargs) return expr(*eargs).evalf(self) return f,varorder assert isinstance(expr,Expression) res = expr.eval(self) if isinstance(res,Expression): rvars = res.vars(self,bound=False) if varorder is None: allorder = dict() for i,v in enumerate(self.variables): allorder[v.name] = i varorder = sorted(rvars,key=lambda v:allorder[v.name]) else: #convert strings to Variables varorder = [(self.variableDict[v] if isinstance(v,str) else v)for v in varorder] vnames = set(v.name for v in varorder) for v in rvars: if v.name not in vnames: warnings.warn("Error while creating Python function corresponding to",res) raise ValueError("Unbound variable "+v.name+" not in given variable order "+",".join([var.name for var in varorder])) def f(*args): #print("Evaluating with order",[str(v) for v in varorder],args) for (v,val) in zip(varorder,args): v.bind(val) res = expr.evalf(self) for (v,val) in zip(varorder,args): v.unbind() return res return (f,varorder) else: if varorder is None: varorder = [] return ((lambda *args: res),varorder)
[ "def", "makePyFunction", "(", "self", ",", "expr", ",", "varorder", "=", "None", ")", ":", "if", "isinstance", "(", "expr", ",", "Function", ")", ":", "if", "varorder", "is", "None", ":", "varnames", "=", "expr", ".", "argNames", "varorder", "=", "[", ...
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/math/symbolic.py#L1499-L1568
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/ops/composite/multitype_ops/negative_impl.py
python
_negative_tensor
(x)
return F.neg_tensor(x)
Returns the negative value of tensor x by element-wise. Returns: Tensor, negative value of x by element-wise.
Returns the negative value of tensor x by element-wise.
[ "Returns", "the", "negative", "value", "of", "tensor", "x", "by", "element", "-", "wise", "." ]
def _negative_tensor(x): """ Returns the negative value of tensor x by element-wise. Returns: Tensor, negative value of x by element-wise. """ return F.neg_tensor(x)
[ "def", "_negative_tensor", "(", "x", ")", ":", "return", "F", ".", "neg_tensor", "(", "x", ")" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/composite/multitype_ops/negative_impl.py#L41-L48
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/propgrid.py
python
PGArrayEditorDialog.EnableCustomNewAction
(*args, **kwargs)
return _propgrid.PGArrayEditorDialog_EnableCustomNewAction(*args, **kwargs)
EnableCustomNewAction(self)
EnableCustomNewAction(self)
[ "EnableCustomNewAction", "(", "self", ")" ]
def EnableCustomNewAction(*args, **kwargs): """EnableCustomNewAction(self)""" return _propgrid.PGArrayEditorDialog_EnableCustomNewAction(*args, **kwargs)
[ "def", "EnableCustomNewAction", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_propgrid", ".", "PGArrayEditorDialog_EnableCustomNewAction", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/propgrid.py#L3185-L3187
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/lite/python/lite.py
python
TFLiteConverterBaseV2.convert
(self, graph_def, input_tensors, output_tensors)
return self._optimize_tflite_model( result, self._quant_mode, quant_io=self.experimental_new_quantizer)
Converts a TensorFlow GraphDef based on instance variables. Args: graph_def: Frozen TensorFlow GraphDef. input_tensors: List of input tensors. output_tensors: List of output tensors. Returns: The converted data in serialized format. Raises: ValueError: No concrete functions is specified. Multiple concrete functions are specified. Input shape is not specified. Invalid quantization parameters.
Converts a TensorFlow GraphDef based on instance variables.
[ "Converts", "a", "TensorFlow", "GraphDef", "based", "on", "instance", "variables", "." ]
def convert(self, graph_def, input_tensors, output_tensors): """Converts a TensorFlow GraphDef based on instance variables. Args: graph_def: Frozen TensorFlow GraphDef. input_tensors: List of input tensors. output_tensors: List of output tensors. Returns: The converted data in serialized format. Raises: ValueError: No concrete functions is specified. Multiple concrete functions are specified. Input shape is not specified. Invalid quantization parameters. """ self._validate_inputs(graph_def, input_tensors) converter_kwargs = self._get_base_converter_args() converter_kwargs.update(self._quant_mode.converter_flags()) if not self.experimental_new_converter: logging.warning( "Please consider switching to the new converter by setting " "experimental_new_converter=True. " "The old converter is deprecated.") else: logging.info("Using new converter: If you encounter a problem " "please file a bug. You can opt-out " "by setting experimental_new_converter=False") # Converts model. result = _convert_graphdef( input_data=graph_def, input_tensors=input_tensors, output_tensors=output_tensors, **converter_kwargs) return self._optimize_tflite_model( result, self._quant_mode, quant_io=self.experimental_new_quantizer)
[ "def", "convert", "(", "self", ",", "graph_def", ",", "input_tensors", ",", "output_tensors", ")", ":", "self", ".", "_validate_inputs", "(", "graph_def", ",", "input_tensors", ")", "converter_kwargs", "=", "self", ".", "_get_base_converter_args", "(", ")", "con...
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/lite/python/lite.py#L1089-L1128
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/_pydecimal.py
python
Decimal.__abs__
(self, round=True, context=None)
return ans
Returns the absolute value of self. If the keyword argument 'round' is false, do not round. The expression self.__abs__(round=False) is equivalent to self.copy_abs().
Returns the absolute value of self.
[ "Returns", "the", "absolute", "value", "of", "self", "." ]
def __abs__(self, round=True, context=None): """Returns the absolute value of self. If the keyword argument 'round' is false, do not round. The expression self.__abs__(round=False) is equivalent to self.copy_abs(). """ if not round: return self.copy_abs() if self._is_special: ans = self._check_nans(context=context) if ans: return ans if self._sign: ans = self.__neg__(context=context) else: ans = self.__pos__(context=context) return ans
[ "def", "__abs__", "(", "self", ",", "round", "=", "True", ",", "context", "=", "None", ")", ":", "if", "not", "round", ":", "return", "self", ".", "copy_abs", "(", ")", "if", "self", ".", "_is_special", ":", "ans", "=", "self", ".", "_check_nans", ...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/_pydecimal.py#L1135-L1155
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/pkg_resources/_vendor/pyparsing.py
python
countedArray
( expr, intExpr=None )
return ( intExpr + arrayExpr ).setName('(len) ' + _ustr(expr) + '...')
Helper to define a counted list of expressions. This helper defines a pattern of the form:: integer expr expr expr... where the leading integer tells how many expr expressions follow. The matched tokens returns the array of expr tokens as a list - the leading count token is suppressed. If C{intExpr} is specified, it should be a pyparsing expression that produces an integer value. Example:: countedArray(Word(alphas)).parseString('2 ab cd ef') # -> ['ab', 'cd'] # in this parser, the leading integer value is given in binary, # '10' indicating that 2 values are in the array binaryConstant = Word('01').setParseAction(lambda t: int(t[0], 2)) countedArray(Word(alphas), intExpr=binaryConstant).parseString('10 ab cd ef') # -> ['ab', 'cd']
Helper to define a counted list of expressions. This helper defines a pattern of the form:: integer expr expr expr... where the leading integer tells how many expr expressions follow. The matched tokens returns the array of expr tokens as a list - the leading count token is suppressed. If C{intExpr} is specified, it should be a pyparsing expression that produces an integer value.
[ "Helper", "to", "define", "a", "counted", "list", "of", "expressions", ".", "This", "helper", "defines", "a", "pattern", "of", "the", "form", "::", "integer", "expr", "expr", "expr", "...", "where", "the", "leading", "integer", "tells", "how", "many", "exp...
def countedArray( expr, intExpr=None ): """ Helper to define a counted list of expressions. This helper defines a pattern of the form:: integer expr expr expr... where the leading integer tells how many expr expressions follow. The matched tokens returns the array of expr tokens as a list - the leading count token is suppressed. If C{intExpr} is specified, it should be a pyparsing expression that produces an integer value. Example:: countedArray(Word(alphas)).parseString('2 ab cd ef') # -> ['ab', 'cd'] # in this parser, the leading integer value is given in binary, # '10' indicating that 2 values are in the array binaryConstant = Word('01').setParseAction(lambda t: int(t[0], 2)) countedArray(Word(alphas), intExpr=binaryConstant).parseString('10 ab cd ef') # -> ['ab', 'cd'] """ arrayExpr = Forward() def countFieldParseAction(s,l,t): n = t[0] arrayExpr << (n and Group(And([expr]*n)) or Group(empty)) return [] if intExpr is None: intExpr = Word(nums).setParseAction(lambda t:int(t[0])) else: intExpr = intExpr.copy() intExpr.setName("arrayLen") intExpr.addParseAction(countFieldParseAction, callDuringTry=True) return ( intExpr + arrayExpr ).setName('(len) ' + _ustr(expr) + '...')
[ "def", "countedArray", "(", "expr", ",", "intExpr", "=", "None", ")", ":", "arrayExpr", "=", "Forward", "(", ")", "def", "countFieldParseAction", "(", "s", ",", "l", ",", "t", ")", ":", "n", "=", "t", "[", "0", "]", "arrayExpr", "<<", "(", "n", "...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/pkg_resources/_vendor/pyparsing.py#L4469-L4498
yrnkrn/zapcc
c6a8aa30006d997eff0d60fd37b0e62b8aa0ea50
tools/clang/bindings/python/clang/cindex.py
python
Type.is_volatile_qualified
(self)
return conf.lib.clang_isVolatileQualifiedType(self)
Determine whether a Type has the "volatile" qualifier set. This does not look through typedefs that may have added "volatile" at a different level.
Determine whether a Type has the "volatile" qualifier set.
[ "Determine", "whether", "a", "Type", "has", "the", "volatile", "qualifier", "set", "." ]
def is_volatile_qualified(self): """Determine whether a Type has the "volatile" qualifier set. This does not look through typedefs that may have added "volatile" at a different level. """ return conf.lib.clang_isVolatileQualifiedType(self)
[ "def", "is_volatile_qualified", "(", "self", ")", ":", "return", "conf", ".", "lib", ".", "clang_isVolatileQualifiedType", "(", "self", ")" ]
https://github.com/yrnkrn/zapcc/blob/c6a8aa30006d997eff0d60fd37b0e62b8aa0ea50/tools/clang/bindings/python/clang/cindex.py#L2271-L2277
hakuna-m/wubiuefi
caec1af0a09c78fd5a345180ada1fe45e0c63493
src/openpgp/sap/msg/KeyMsg.py
python
PublicKeyMsg.add_sig
(self, sigpkt, target)
Add a signature to one of the message's key blocks. :Parameters: - `sigpkt`: Signature packet instance - `target`: string target block leader The signature packet's type will indicate the target type (key ID or user ID value) and the `target` string will be used to distinguish one from the rest. Key IDs are searched first, so funky hex user IDs are not encouraged. :note: For user IDs, `target` is the complete ID string and must match exactly.
Add a signature to one of the message's key blocks.
[ "Add", "a", "signature", "to", "one", "of", "the", "message", "s", "key", "blocks", "." ]
def add_sig(self, sigpkt, target): """Add a signature to one of the message's key blocks. :Parameters: - `sigpkt`: Signature packet instance - `target`: string target block leader The signature packet's type will indicate the target type (key ID or user ID value) and the `target` string will be used to distinguish one from the rest. Key IDs are searched first, so funky hex user IDs are not encouraged. :note: For user IDs, `target` is the complete ID string and must match exactly. """ block = self.get_block(target) block.add_sig(sigpkt)
[ "def", "add_sig", "(", "self", ",", "sigpkt", ",", "target", ")", ":", "block", "=", "self", ".", "get_block", "(", "target", ")", "block", ".", "add_sig", "(", "sigpkt", ")" ]
https://github.com/hakuna-m/wubiuefi/blob/caec1af0a09c78fd5a345180ada1fe45e0c63493/src/openpgp/sap/msg/KeyMsg.py#L86-L102
smilehao/xlua-framework
a03801538be2b0e92d39332d445b22caca1ef61f
ConfigData/trunk/tools/protobuf-2.5.0/protobuf-2.5.0/python/google/protobuf/descriptor_pool.py
python
DescriptorPool._MakeFieldDescriptor
(self, field_proto, message_name, index, is_extension=False)
return descriptor.FieldDescriptor( name=field_proto.name, full_name=full_name, index=index, number=field_proto.number, type=field_proto.type, cpp_type=None, message_type=None, enum_type=None, containing_type=None, label=field_proto.label, has_default_value=False, default_value=None, is_extension=is_extension, extension_scope=None, options=field_proto.options)
Creates a field descriptor from a FieldDescriptorProto. For message and enum type fields, this method will do a look up in the pool for the appropriate descriptor for that type. If it is unavailable, it will fall back to the _source function to create it. If this type is still unavailable, construction will fail. Args: field_proto: The proto describing the field. message_name: The name of the containing message. index: Index of the field is_extension: Indication that this field is for an extension. Returns: An initialized FieldDescriptor object
Creates a field descriptor from a FieldDescriptorProto.
[ "Creates", "a", "field", "descriptor", "from", "a", "FieldDescriptorProto", "." ]
def _MakeFieldDescriptor(self, field_proto, message_name, index, is_extension=False): """Creates a field descriptor from a FieldDescriptorProto. For message and enum type fields, this method will do a look up in the pool for the appropriate descriptor for that type. If it is unavailable, it will fall back to the _source function to create it. If this type is still unavailable, construction will fail. Args: field_proto: The proto describing the field. message_name: The name of the containing message. index: Index of the field is_extension: Indication that this field is for an extension. Returns: An initialized FieldDescriptor object """ if message_name: full_name = '.'.join((message_name, field_proto.name)) else: full_name = field_proto.name return descriptor.FieldDescriptor( name=field_proto.name, full_name=full_name, index=index, number=field_proto.number, type=field_proto.type, cpp_type=None, message_type=None, enum_type=None, containing_type=None, label=field_proto.label, has_default_value=False, default_value=None, is_extension=is_extension, extension_scope=None, options=field_proto.options)
[ "def", "_MakeFieldDescriptor", "(", "self", ",", "field_proto", ",", "message_name", ",", "index", ",", "is_extension", "=", "False", ")", ":", "if", "message_name", ":", "full_name", "=", "'.'", ".", "join", "(", "(", "message_name", ",", "field_proto", "."...
https://github.com/smilehao/xlua-framework/blob/a03801538be2b0e92d39332d445b22caca1ef61f/ConfigData/trunk/tools/protobuf-2.5.0/protobuf-2.5.0/python/google/protobuf/descriptor_pool.py#L335-L375
kismetwireless/kismet
a7c0dc270c960fb1f58bd9cec4601c201885fd4e
capture_sdr_rtl433/KismetCaptureRtl433/kismetexternal/__init__.py
python
Datasource.set_configsource_cb
(self, cb)
Set callback for source configuring :param cb: Callback function, taking seqno and datasource_pb2.Configure record :return: None
Set callback for source configuring
[ "Set", "callback", "for", "source", "configuring" ]
def set_configsource_cb(self, cb): """ Set callback for source configuring :param cb: Callback function, taking seqno and datasource_pb2.Configure record :return: None """ self.configuresource = cb
[ "def", "set_configsource_cb", "(", "self", ",", "cb", ")", ":", "self", ".", "configuresource", "=", "cb" ]
https://github.com/kismetwireless/kismet/blob/a7c0dc270c960fb1f58bd9cec4601c201885fd4e/capture_sdr_rtl433/KismetCaptureRtl433/kismetexternal/__init__.py#L806-L814
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/tracemalloc.py
python
Snapshot.compare_to
(self, old_snapshot, key_type, cumulative=False)
return statistics
Compute the differences with an old snapshot old_snapshot. Get statistics as a sorted list of StatisticDiff instances, grouped by group_by.
Compute the differences with an old snapshot old_snapshot. Get statistics as a sorted list of StatisticDiff instances, grouped by group_by.
[ "Compute", "the", "differences", "with", "an", "old", "snapshot", "old_snapshot", ".", "Get", "statistics", "as", "a", "sorted", "list", "of", "StatisticDiff", "instances", "grouped", "by", "group_by", "." ]
def compare_to(self, old_snapshot, key_type, cumulative=False): """ Compute the differences with an old snapshot old_snapshot. Get statistics as a sorted list of StatisticDiff instances, grouped by group_by. """ new_group = self._group_by(key_type, cumulative) old_group = old_snapshot._group_by(key_type, cumulative) statistics = _compare_grouped_stats(old_group, new_group) statistics.sort(reverse=True, key=StatisticDiff._sort_key) return statistics
[ "def", "compare_to", "(", "self", ",", "old_snapshot", ",", "key_type", ",", "cumulative", "=", "False", ")", ":", "new_group", "=", "self", ".", "_group_by", "(", "key_type", ",", "cumulative", ")", "old_group", "=", "old_snapshot", ".", "_group_by", "(", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/tracemalloc.py#L512-L522
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/_pydecimal.py
python
_convert_other
(other, raiseit=False, allow_float=False)
return NotImplemented
Convert other to Decimal. Verifies that it's ok to use in an implicit construction. If allow_float is true, allow conversion from float; this is used in the comparison methods (__eq__ and friends).
Convert other to Decimal.
[ "Convert", "other", "to", "Decimal", "." ]
def _convert_other(other, raiseit=False, allow_float=False): """Convert other to Decimal. Verifies that it's ok to use in an implicit construction. If allow_float is true, allow conversion from float; this is used in the comparison methods (__eq__ and friends). """ if isinstance(other, Decimal): return other if isinstance(other, int): return Decimal(other) if allow_float and isinstance(other, float): return Decimal.from_float(other) if raiseit: raise TypeError("Unable to convert %s to Decimal" % other) return NotImplemented
[ "def", "_convert_other", "(", "other", ",", "raiseit", "=", "False", ",", "allow_float", "=", "False", ")", ":", "if", "isinstance", "(", "other", ",", "Decimal", ")", ":", "return", "other", "if", "isinstance", "(", "other", ",", "int", ")", ":", "ret...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/_pydecimal.py#L6015-L6032
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
tools/perf/benchmarks/peacekeeper.py
python
_PeaceKeeperBenchmark.CreatePageSet
(self, options)
return page_set.PageSet.FromDict(page_set_dict, os.path.abspath(__file__))
Makes a PageSet for PeaceKeeper benchmarks.
Makes a PageSet for PeaceKeeper benchmarks.
[ "Makes", "a", "PageSet", "for", "PeaceKeeper", "benchmarks", "." ]
def CreatePageSet(self, options): """Makes a PageSet for PeaceKeeper benchmarks.""" # Subclasses are expected to define a class member called query_param. if not hasattr(self, 'test_param'): raise NotImplementedError('test_param not in PeaceKeeper benchmark.') # The docstring of benchmark classes may also be used as a description # when 'run_benchmarks list' is run. description = self.__doc__ or 'PeaceKeeper Benchmark' test_urls = [] for test_name in self.test_param: test_urls.append( {"url": ("http://peacekeeper.futuremark.com/run.action?debug=true&" "repeat=false&forceSuiteName=%s&forceTestName=%s") % (self.tag, test_name) }) page_set_dict = { 'description': description, 'archive_data_file': '../page_sets/data/peacekeeper_%s.json' % self.tag, 'make_javascript_deterministic': False, 'pages': test_urls, } return page_set.PageSet.FromDict(page_set_dict, os.path.abspath(__file__))
[ "def", "CreatePageSet", "(", "self", ",", "options", ")", ":", "# Subclasses are expected to define a class member called query_param.", "if", "not", "hasattr", "(", "self", ",", "'test_param'", ")", ":", "raise", "NotImplementedError", "(", "'test_param not in PeaceKeeper ...
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/perf/benchmarks/peacekeeper.py#L75-L98
arangodb/arangodb
0d658689c7d1b721b314fa3ca27d38303e1570c8
3rdParty/V8/v7.9.317/third_party/jinja2/filters.py
python
do_mark_unsafe
(value)
return text_type(value)
Mark a value as unsafe. This is the reverse operation for :func:`safe`.
Mark a value as unsafe. This is the reverse operation for :func:`safe`.
[ "Mark", "a", "value", "as", "unsafe", ".", "This", "is", "the", "reverse", "operation", "for", ":", "func", ":", "safe", "." ]
def do_mark_unsafe(value): """Mark a value as unsafe. This is the reverse operation for :func:`safe`.""" return text_type(value)
[ "def", "do_mark_unsafe", "(", "value", ")", ":", "return", "text_type", "(", "value", ")" ]
https://github.com/arangodb/arangodb/blob/0d658689c7d1b721b314fa3ca27d38303e1570c8/3rdParty/V8/v7.9.317/third_party/jinja2/filters.py#L890-L892
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Editor/Python/windows/Lib/site-packages/pip/_vendor/distlib/index.py
python
PackageIndex.check_credentials
(self)
Check that ``username`` and ``password`` have been set, and raise an exception if not.
Check that ``username`` and ``password`` have been set, and raise an exception if not.
[ "Check", "that", "username", "and", "password", "have", "been", "set", "and", "raise", "an", "exception", "if", "not", "." ]
def check_credentials(self): """ Check that ``username`` and ``password`` have been set, and raise an exception if not. """ if self.username is None or self.password is None: raise DistlibException('username and password must be set') pm = HTTPPasswordMgr() _, netloc, _, _, _, _ = urlparse(self.url) pm.add_password(self.realm, netloc, self.username, self.password) self.password_handler = HTTPBasicAuthHandler(pm)
[ "def", "check_credentials", "(", "self", ")", ":", "if", "self", ".", "username", "is", "None", "or", "self", ".", "password", "is", "None", ":", "raise", "DistlibException", "(", "'username and password must be set'", ")", "pm", "=", "HTTPPasswordMgr", "(", "...
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/pip/_vendor/distlib/index.py#L101-L111
hfinkel/llvm-project-cxxjit
91084ef018240bbb8e24235ff5cd8c355a9c1a1e
clang/bindings/python/clang/cindex.py
python
Type.get_array_element_type
(self)
return conf.lib.clang_getArrayElementType(self)
Retrieve the type of the elements of the array type.
Retrieve the type of the elements of the array type.
[ "Retrieve", "the", "type", "of", "the", "elements", "of", "the", "array", "type", "." ]
def get_array_element_type(self): """ Retrieve the type of the elements of the array type. """ return conf.lib.clang_getArrayElementType(self)
[ "def", "get_array_element_type", "(", "self", ")", ":", "return", "conf", ".", "lib", ".", "clang_getArrayElementType", "(", "self", ")" ]
https://github.com/hfinkel/llvm-project-cxxjit/blob/91084ef018240bbb8e24235ff5cd8c355a9c1a1e/clang/bindings/python/clang/cindex.py#L2348-L2352
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/python2_version/klampt/sim/simulation.py
python
ActuatorEmulator.substep
(self,dt)
This is called every simulation substep, which occurs at a higher rate than process() is called. dt is the simulation substep.
This is called every simulation substep, which occurs at a higher rate than process() is called. dt is the simulation substep.
[ "This", "is", "called", "every", "simulation", "substep", "which", "occurs", "at", "a", "higher", "rate", "than", "process", "()", "is", "called", ".", "dt", "is", "the", "simulation", "substep", "." ]
def substep(self,dt): """This is called every simulation substep, which occurs at a higher rate than process() is called. dt is the simulation substep. """ pass
[ "def", "substep", "(", "self", ",", "dt", ")", ":", "pass" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/sim/simulation.py#L76-L80
Illumina/manta
75b5c38d4fcd2f6961197b28a41eb61856f2d976
src/python/lib/configureOptions.py
python
ConfigureWorkflowOptions.addWorkflowGroupOptions
(self,group)
Add options to OptionsGroup object which specify parameters which commonly change from run to run
Add options to OptionsGroup object which specify parameters which commonly change from run to run
[ "Add", "options", "to", "OptionsGroup", "object", "which", "specify", "parameters", "which", "commonly", "change", "from", "run", "to", "run" ]
def addWorkflowGroupOptions(self,group) : """ Add options to OptionsGroup object which specify parameters which commonly change from run to run """ pass
[ "def", "addWorkflowGroupOptions", "(", "self", ",", "group", ")", ":", "pass" ]
https://github.com/Illumina/manta/blob/75b5c38d4fcd2f6961197b28a41eb61856f2d976/src/python/lib/configureOptions.py#L53-L58
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
python/paddle/fluid/incubate/fleet/base/fleet_base.py
python
Fleet.worker_endpoints
(self, to_string=False)
Get current server endpoints, such as ["127.0.0.1:1001", "127.0.0.1:1002"]. Returns: list/string: server endpoints
Get current server endpoints, such as ["127.0.0.1:1001", "127.0.0.1:1002"].
[ "Get", "current", "server", "endpoints", "such", "as", "[", "127", ".", "0", ".", "0", ".", "1", ":", "1001", "127", ".", "0", ".", "0", ".", "1", ":", "1002", "]", "." ]
def worker_endpoints(self, to_string=False): """ Get current server endpoints, such as ["127.0.0.1:1001", "127.0.0.1:1002"]. Returns: list/string: server endpoints """ if to_string: return ",".join(self._role_maker.get_trainer_endpoints()) else: return self._role_maker.get_trainer_endpoints()
[ "def", "worker_endpoints", "(", "self", ",", "to_string", "=", "False", ")", ":", "if", "to_string", ":", "return", "\",\"", ".", "join", "(", "self", ".", "_role_maker", ".", "get_trainer_endpoints", "(", ")", ")", "else", ":", "return", "self", ".", "_...
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/fluid/incubate/fleet/base/fleet_base.py#L90-L101
nsnam/ns-3-dev-git
efdb2e21f45c0a87a60b47c547b68fa140a7b686
src/visualizer/visualizer/ipython_view.py
python
ConsoleView.showPrompt
(self, prompt)
! Prints prompt at start of line. @param prompt: Prompt to print. @return none
! Prints prompt at start of line.
[ "!", "Prints", "prompt", "at", "start", "of", "line", "." ]
def showPrompt(self, prompt): """! Prints prompt at start of line. @param prompt: Prompt to print. @return none """ GObject.idle_add(self._showPrompt, prompt)
[ "def", "showPrompt", "(", "self", ",", "prompt", ")", ":", "GObject", ".", "idle_add", "(", "self", ".", "_showPrompt", ",", "prompt", ")" ]
https://github.com/nsnam/ns-3-dev-git/blob/efdb2e21f45c0a87a60b47c547b68fa140a7b686/src/visualizer/visualizer/ipython_view.py#L430-L437
hpi-xnor/BMXNet-v2
af2b1859eafc5c721b1397cef02f946aaf2ce20d
example/ctc/multiproc_data.py
python
MPData.reset
(self)
Resets the generator by stopping all processes
Resets the generator by stopping all processes
[ "Resets", "the", "generator", "by", "stopping", "all", "processes" ]
def reset(self): """Resets the generator by stopping all processes""" self.alive.value = False qsize = 0 try: while True: self.queue.get(timeout=0.1) qsize += 1 except QEmptyExcept: pass print("Queue size on reset: {}".format(qsize)) for i, p in enumerate(self.proc): p.join() self.proc.clear()
[ "def", "reset", "(", "self", ")", ":", "self", ".", "alive", ".", "value", "=", "False", "qsize", "=", "0", "try", ":", "while", "True", ":", "self", ".", "queue", ".", "get", "(", "timeout", "=", "0.1", ")", "qsize", "+=", "1", "except", "QEmpty...
https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/example/ctc/multiproc_data.py#L112-L125
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/ultimatelistctrl.py
python
UltimateListItem.SetFooterText
(self, text)
Sets the text label for the footer item. :param `text`: the text label for the footer item.
Sets the text label for the footer item.
[ "Sets", "the", "text", "label", "for", "the", "footer", "item", "." ]
def SetFooterText(self, text): """ Sets the text label for the footer item. :param `text`: the text label for the footer item. """ self._mask |= ULC_MASK_FOOTER_TEXT self._footerText = text
[ "def", "SetFooterText", "(", "self", ",", "text", ")", ":", "self", ".", "_mask", "|=", "ULC_MASK_FOOTER_TEXT", "self", ".", "_footerText", "=", "text" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/ultimatelistctrl.py#L2176-L2184
TGAC/KAT
e8870331de2b4bb0a1b3b91c6afb8fb9d59e9216
deps/boost/tools/build/src/build/feature.py
python
__validate_feature
(feature)
Generates an error if the feature is unknown.
Generates an error if the feature is unknown.
[ "Generates", "an", "error", "if", "the", "feature", "is", "unknown", "." ]
def __validate_feature (feature): """ Generates an error if the feature is unknown. """ assert isinstance(feature, basestring) if feature not in __all_features: raise BaseException ('unknown feature "%s"' % feature)
[ "def", "__validate_feature", "(", "feature", ")", ":", "assert", "isinstance", "(", "feature", ",", "basestring", ")", "if", "feature", "not", "in", "__all_features", ":", "raise", "BaseException", "(", "'unknown feature \"%s\"'", "%", "feature", ")" ]
https://github.com/TGAC/KAT/blob/e8870331de2b4bb0a1b3b91c6afb8fb9d59e9216/deps/boost/tools/build/src/build/feature.py#L894-L899
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/layers/pooling.py
python
average_pooling3d
(inputs, pool_size, strides, padding='valid', data_format='channels_last', name=None)
return layer.apply(inputs)
Average pooling layer for 3D inputs (e.g. volumes). Arguments: inputs: The tensor over which to pool. Must have rank 5. pool_size: An integer or tuple/list of 3 integers: (pool_depth, pool_height, pool_width) specifying the size of the pooling window. Can be a single integer to specify the same value for all spatial dimensions. strides: An integer or tuple/list of 3 integers, specifying the strides of the pooling operation. Can be a single integer to specify the same value for all spatial dimensions. padding: A string. The padding method, either 'valid' or 'same'. Case-insensitive. data_format: A string. The ordering of the dimensions in the inputs. `channels_last` (default) and `channels_first` are supported. `channels_last` corresponds to inputs with shape `(batch, depth, height, width, channels)` while `channels_first` corresponds to inputs with shape `(batch, channels, depth, height, width)`. name: A string, the name of the layer. Returns: Output tensor. Raises: ValueError: if eager execution is enabled.
Average pooling layer for 3D inputs (e.g. volumes).
[ "Average", "pooling", "layer", "for", "3D", "inputs", "(", "e", ".", "g", ".", "volumes", ")", "." ]
def average_pooling3d(inputs, pool_size, strides, padding='valid', data_format='channels_last', name=None): """Average pooling layer for 3D inputs (e.g. volumes). Arguments: inputs: The tensor over which to pool. Must have rank 5. pool_size: An integer or tuple/list of 3 integers: (pool_depth, pool_height, pool_width) specifying the size of the pooling window. Can be a single integer to specify the same value for all spatial dimensions. strides: An integer or tuple/list of 3 integers, specifying the strides of the pooling operation. Can be a single integer to specify the same value for all spatial dimensions. padding: A string. The padding method, either 'valid' or 'same'. Case-insensitive. data_format: A string. The ordering of the dimensions in the inputs. `channels_last` (default) and `channels_first` are supported. `channels_last` corresponds to inputs with shape `(batch, depth, height, width, channels)` while `channels_first` corresponds to inputs with shape `(batch, channels, depth, height, width)`. name: A string, the name of the layer. Returns: Output tensor. Raises: ValueError: if eager execution is enabled. """ if context.in_eager_mode(): raise ValueError( 'Functional layers are currently not compatible with eager execution.' 'Use tf.layers.AveragePooling3D instead.') layer = AveragePooling3D(pool_size=pool_size, strides=strides, padding=padding, data_format=data_format, name=name) return layer.apply(inputs)
[ "def", "average_pooling3d", "(", "inputs", ",", "pool_size", ",", "strides", ",", "padding", "=", "'valid'", ",", "data_format", "=", "'channels_last'", ",", "name", "=", "None", ")", ":", "if", "context", ".", "in_eager_mode", "(", ")", ":", "raise", "Val...
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/layers/pooling.py#L563-L603
baidu/bigflow
449245016c0df7d1252e85581e588bfc60cefad3
bigflow_python/python/bigflow/base.py
python
Transformer.process
(self, record, *side_inputs)
return []
此方法在处理数据之时被调用,以通知用户要开始处理数据了。 其中record即为待处理的数据。 用户必须返回一个可迭代的对象,其中值将会被放入结果的PCollection中。
此方法在处理数据之时被调用,以通知用户要开始处理数据了。 其中record即为待处理的数据。
[ "此方法在处理数据之时被调用,以通知用户要开始处理数据了。", "其中record即为待处理的数据。" ]
def process(self, record, *side_inputs): """ 此方法在处理数据之时被调用,以通知用户要开始处理数据了。 其中record即为待处理的数据。 用户必须返回一个可迭代的对象,其中值将会被放入结果的PCollection中。 """ return []
[ "def", "process", "(", "self", ",", "record", ",", "*", "side_inputs", ")", ":", "return", "[", "]" ]
https://github.com/baidu/bigflow/blob/449245016c0df7d1252e85581e588bfc60cefad3/bigflow_python/python/bigflow/base.py#L138-L145
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/chardet/__init__.py
python
detect
(byte_str)
return detector.close()
Detect the encoding of the given byte string. :param byte_str: The byte sequence to examine. :type byte_str: ``bytes`` or ``bytearray``
Detect the encoding of the given byte string.
[ "Detect", "the", "encoding", "of", "the", "given", "byte", "string", "." ]
def detect(byte_str): """ Detect the encoding of the given byte string. :param byte_str: The byte sequence to examine. :type byte_str: ``bytes`` or ``bytearray`` """ if not isinstance(byte_str, bytearray): if not isinstance(byte_str, bytes): raise TypeError('Expected object of type bytes or bytearray, got: ' '{}'.format(type(byte_str))) else: byte_str = bytearray(byte_str) detector = UniversalDetector() detector.feed(byte_str) return detector.close()
[ "def", "detect", "(", "byte_str", ")", ":", "if", "not", "isinstance", "(", "byte_str", ",", "bytearray", ")", ":", "if", "not", "isinstance", "(", "byte_str", ",", "bytes", ")", ":", "raise", "TypeError", "(", "'Expected object of type bytes or bytearray, got: ...
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/chardet/__init__.py#L27-L42
CNugteren/CLBlast
4500a03440e2cc54998c0edab366babf5e504d67
scripts/generator/generator/routine.py
python
Routine.arguments_type
(self, flavour)
return (self.options_type() + self.sizes_type() + list(chain(*[self.buffer_type(b) for b in self.scalar_buffers_first()])) + self.scalar_type("alpha", flavour) + list(chain(*[self.buffer_type(b) for b in self.buffers_first()])) + self.scalar_type("beta", flavour) + list(chain(*[self.buffer_type(b) for b in self.buffers_second()])) + list(chain(*[self.buffer_type(b) for b in self.scalar_buffers_second()])) + list(chain(*[self.scalar_type(s, flavour) for s in self.other_scalars()])) + self.batch_count_type())
Retrieves a combination of all the argument types
Retrieves a combination of all the argument types
[ "Retrieves", "a", "combination", "of", "all", "the", "argument", "types" ]
def arguments_type(self, flavour): """Retrieves a combination of all the argument types""" return (self.options_type() + self.sizes_type() + list(chain(*[self.buffer_type(b) for b in self.scalar_buffers_first()])) + self.scalar_type("alpha", flavour) + list(chain(*[self.buffer_type(b) for b in self.buffers_first()])) + self.scalar_type("beta", flavour) + list(chain(*[self.buffer_type(b) for b in self.buffers_second()])) + list(chain(*[self.buffer_type(b) for b in self.scalar_buffers_second()])) + list(chain(*[self.scalar_type(s, flavour) for s in self.other_scalars()])) + self.batch_count_type())
[ "def", "arguments_type", "(", "self", ",", "flavour", ")", ":", "return", "(", "self", ".", "options_type", "(", ")", "+", "self", ".", "sizes_type", "(", ")", "+", "list", "(", "chain", "(", "*", "[", "self", ".", "buffer_type", "(", "b", ")", "fo...
https://github.com/CNugteren/CLBlast/blob/4500a03440e2cc54998c0edab366babf5e504d67/scripts/generator/generator/routine.py#L800-L810
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_core.py
python
App_CleanUp
(*args)
return _core_.App_CleanUp(*args)
App_CleanUp() For internal use only, it is used to cleanup after wxWidgets when Python shuts down.
App_CleanUp()
[ "App_CleanUp", "()" ]
def App_CleanUp(*args): """ App_CleanUp() For internal use only, it is used to cleanup after wxWidgets when Python shuts down. """ return _core_.App_CleanUp(*args)
[ "def", "App_CleanUp", "(", "*", "args", ")", ":", "return", "_core_", ".", "App_CleanUp", "(", "*", "args", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L8412-L8419
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/cgutils.py
python
_StructProxy.__setattr__
(self, field, value)
Store the LLVM *value* into the named *field*.
Store the LLVM *value* into the named *field*.
[ "Store", "the", "LLVM", "*", "value", "*", "into", "the", "named", "*", "field", "*", "." ]
def __setattr__(self, field, value): """ Store the LLVM *value* into the named *field*. """ if field.startswith('_'): return super(_StructProxy, self).__setattr__(field, value) self[self._datamodel.get_field_position(field)] = value
[ "def", "__setattr__", "(", "self", ",", "field", ",", "value", ")", ":", "if", "field", ".", "startswith", "(", "'_'", ")", ":", "return", "super", "(", "_StructProxy", ",", "self", ")", ".", "__setattr__", "(", "field", ",", "value", ")", "self", "[...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/cgutils.py#L159-L165
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/distutils/fcompiler/gnu.py
python
Gnu95FCompiler.wrap_unlinkable_objects
(self, objects, output_dir, extra_dll_dir)
Convert a set of object files that are not compatible with the default linker, to a file that is compatible.
Convert a set of object files that are not compatible with the default linker, to a file that is compatible.
[ "Convert", "a", "set", "of", "object", "files", "that", "are", "not", "compatible", "with", "the", "default", "linker", "to", "a", "file", "that", "is", "compatible", "." ]
def wrap_unlinkable_objects(self, objects, output_dir, extra_dll_dir): """ Convert a set of object files that are not compatible with the default linker, to a file that is compatible. """ if self.c_compiler.compiler_type == "msvc": # Compile a DLL and return the lib for the DLL as # the object. Also keep track of previous DLLs that # we have compiled so that we can link against them. # If there are .a archives, assume they are self-contained # static libraries, and build separate DLLs for each archives = [] plain_objects = [] for obj in objects: if obj.lower().endswith('.a'): archives.append(obj) else: plain_objects.append(obj) chained_libs = [] chained_dlls = [] for archive in archives[::-1]: lib, dll = self._link_wrapper_lib( [archive], output_dir, extra_dll_dir, chained_dlls=chained_dlls, is_archive=True) chained_libs.insert(0, lib) chained_dlls.insert(0, dll) if not plain_objects: return chained_libs lib, dll = self._link_wrapper_lib( plain_objects, output_dir, extra_dll_dir, chained_dlls=chained_dlls, is_archive=False) return [lib] + chained_libs else: raise ValueError("Unsupported C compiler")
[ "def", "wrap_unlinkable_objects", "(", "self", ",", "objects", ",", "output_dir", ",", "extra_dll_dir", ")", ":", "if", "self", ".", "c_compiler", ".", "compiler_type", "==", "\"msvc\"", ":", "# Compile a DLL and return the lib for the DLL as", "# the object. Also keep tr...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/distutils/fcompiler/gnu.py#L488-L531
ApolloAuto/apollo
463fb82f9e979d02dcb25044e60931293ab2dba0
modules/tools/routing/road_show.py
python
draw_id
(x, y, id_string)
Draw id_string on (x, y)
Draw id_string on (x, y)
[ "Draw", "id_string", "on", "(", "x", "y", ")" ]
def draw_id(x, y, id_string): """Draw id_string on (x, y)""" plt.annotate( id_string, xy=(x, y), xytext=(40, -40), textcoords='offset points', ha='right', va='bottom', bbox=dict(boxstyle='round,pad=0.5', fc='green', alpha=0.5), arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=0'))
[ "def", "draw_id", "(", "x", ",", "y", ",", "id_string", ")", ":", "plt", ".", "annotate", "(", "id_string", ",", "xy", "=", "(", "x", ",", "y", ")", ",", "xytext", "=", "(", "40", ",", "-", "40", ")", ",", "textcoords", "=", "'offset points'", ...
https://github.com/ApolloAuto/apollo/blob/463fb82f9e979d02dcb25044e60931293ab2dba0/modules/tools/routing/road_show.py#L84-L94
tuttleofx/TuttleOFX
36fc4cae15092a84ea8c29b9c6658c7cabfadb6e
tools/upload_on_drive.py
python
DriveHelper.create_arbo
(self, tree, parent_id=None)
Create arbo recursively in Drive Call : drive.create_arbo(ARBO.tree). Doesn't re-create folders when they exist. /!/ --- As Arbo as already been generated --- This function should'nt be used anymore. Exception : changes in arbo structure. But in that case be aware, it will affects in place folders and bundles.
Create arbo recursively in Drive Call : drive.create_arbo(ARBO.tree). Doesn't re-create folders when they exist.
[ "Create", "arbo", "recursively", "in", "Drive", "Call", ":", "drive", ".", "create_arbo", "(", "ARBO", ".", "tree", ")", ".", "Doesn", "t", "re", "-", "create", "folders", "when", "they", "exist", "." ]
def create_arbo(self, tree, parent_id=None): """ Create arbo recursively in Drive Call : drive.create_arbo(ARBO.tree). Doesn't re-create folders when they exist. /!/ --- As Arbo as already been generated --- This function should'nt be used anymore. Exception : changes in arbo structure. But in that case be aware, it will affects in place folders and bundles. """ build_parent = parent_id for node in tree: if not isinstance(node, (list, tuple)): build_parent = (self.create_directory(node, parent_id)) else: self.create_arbo(node, build_parent)
[ "def", "create_arbo", "(", "self", ",", "tree", ",", "parent_id", "=", "None", ")", ":", "build_parent", "=", "parent_id", "for", "node", "in", "tree", ":", "if", "not", "isinstance", "(", "node", ",", "(", "list", ",", "tuple", ")", ")", ":", "build...
https://github.com/tuttleofx/TuttleOFX/blob/36fc4cae15092a84ea8c29b9c6658c7cabfadb6e/tools/upload_on_drive.py#L243-L259
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/turtle.py
python
TNavigator.setx
(self, x)
Set the turtle's first coordinate to x Argument: x -- a number (integer or float) Set the turtle's first coordinate to x, leave second coordinate unchanged. Example (for a Turtle instance named turtle): >>> turtle.position() (0.00, 240.00) >>> turtle.setx(10) >>> turtle.position() (10.00, 240.00)
Set the turtle's first coordinate to x
[ "Set", "the", "turtle", "s", "first", "coordinate", "to", "x" ]
def setx(self, x): """Set the turtle's first coordinate to x Argument: x -- a number (integer or float) Set the turtle's first coordinate to x, leave second coordinate unchanged. Example (for a Turtle instance named turtle): >>> turtle.position() (0.00, 240.00) >>> turtle.setx(10) >>> turtle.position() (10.00, 240.00) """ self._goto(Vec2D(x, self._position[1]))
[ "def", "setx", "(", "self", ",", "x", ")", ":", "self", ".", "_goto", "(", "Vec2D", "(", "x", ",", "self", ".", "_position", "[", "1", "]", ")", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/turtle.py#L1707-L1723