nwo
stringlengths
5
86
sha
stringlengths
40
40
path
stringlengths
4
189
language
stringclasses
1 value
identifier
stringlengths
1
94
parameters
stringlengths
2
4.03k
argument_list
stringclasses
1 value
return_statement
stringlengths
0
11.5k
docstring
stringlengths
1
33.2k
docstring_summary
stringlengths
0
5.15k
docstring_tokens
list
function
stringlengths
34
151k
function_tokens
list
url
stringlengths
90
278
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/lib-tk/turtle.py
python
RawTurtle.reset
(self)
Delete the turtle's drawings and restore its default values. No argument. , Delete the turtle's drawings from the screen, re-center the turtle and set variables to the default values. Example (for a Turtle instance named turtle): >>> turtle.position() (0.00,-22.00) >>> turtle.heading() 100.0 >>> turtle.reset() >>> turtle.position() (0.00,0.00) >>> turtle.heading() 0.0
Delete the turtle's drawings and restore its default values.
[ "Delete", "the", "turtle", "s", "drawings", "and", "restore", "its", "default", "values", "." ]
def reset(self): """Delete the turtle's drawings and restore its default values. No argument. , Delete the turtle's drawings from the screen, re-center the turtle and set variables to the default values. Example (for a Turtle instance named turtle): >>> turtle.position() (0.00,-22.00) >>> turtle.heading() 100.0 >>> turtle.reset() >>> turtle.position() (0.00,0.00) >>> turtle.heading() 0.0 """ TNavigator.reset(self) TPen._reset(self) self._clear() self._drawturtle() self._update()
[ "def", "reset", "(", "self", ")", ":", "TNavigator", ".", "reset", "(", "self", ")", "TPen", ".", "_reset", "(", "self", ")", "self", ".", "_clear", "(", ")", "self", ".", "_drawturtle", "(", ")", "self", ".", "_update", "(", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/lib-tk/turtle.py#L2464-L2487
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/s3transfer/futures.py
python
ExecutorFuture.__init__
(self, future)
A future returned from the executor Currently, it is just a wrapper around a concurrent.futures.Future. However, this can eventually grow to implement the needed functionality of concurrent.futures.Future if we move off of the library and not affect the rest of the codebase. :type future: concurrent.futures.Future :param future: The underlying future
A future returned from the executor
[ "A", "future", "returned", "from", "the", "executor" ]
def __init__(self, future): """A future returned from the executor Currently, it is just a wrapper around a concurrent.futures.Future. However, this can eventually grow to implement the needed functionality of concurrent.futures.Future if we move off of the library and not affect the rest of the codebase. :type future: concurrent.futures.Future :param future: The underlying future """ self._future = future
[ "def", "__init__", "(", "self", ",", "future", ")", ":", "self", ".", "_future", "=", "future" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/s3transfer/futures.py#L478-L489
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_internal/models/target_python.py
python
TargetPython.format_given
(self)
return ' '.join( f'{key}={value!r}' for key, value in key_values if value is not None )
Format the given, non-None attributes for display.
[]
def format_given(self): # type: () -> str """ Format the given, non-None attributes for display. """ display_version = None if self._given_py_version_info is not None: display_version = '.'.join( str(part) for part in self._given_py_version_info ) key_values = [ ('platforms', self.platforms), ('version_info', display_version), ('abis', self.abis), ('implementation', self.implementation), ] return ' '.join( f'{key}={value!r}' for key, value in key_values if value is not None )
[ "def", "format_given", "(", "self", ")", ":", "# type: () -> str", "display_version", "=", "None", "if", "self", ".", "_given_py_version_info", "is", "not", "None", ":", "display_version", "=", "'.'", ".", "join", "(", "str", "(", "part", ")", "for", "part", "in", "self", ".", "_given_py_version_info", ")", "key_values", "=", "[", "(", "'platforms'", ",", "self", ".", "platforms", ")", ",", "(", "'version_info'", ",", "display_version", ")", ",", "(", "'abis'", ",", "self", ".", "abis", ")", ",", "(", "'implementation'", ",", "self", ".", "implementation", ")", ",", "]", "return", "' '", ".", "join", "(", "f'{key}={value!r}'", "for", "key", ",", "value", "in", "key_values", "if", "value", "is", "not", "None", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_internal/models/target_python.py#L141-L181
apple/swift-lldb
d74be846ef3e62de946df343e8c234bde93a8912
examples/python/file_extract.py
python
FileExtract.get_uint16
(self, fail_value=0)
Extract a single uint16_t from the binary file at the current file position, returns a single integer
Extract a single uint16_t from the binary file at the current file position, returns a single integer
[ "Extract", "a", "single", "uint16_t", "from", "the", "binary", "file", "at", "the", "current", "file", "position", "returns", "a", "single", "integer" ]
def get_uint16(self, fail_value=0): '''Extract a single uint16_t from the binary file at the current file position, returns a single integer''' s = self.read_size(2) if s: v, = struct.unpack(self.byte_order + 'H', s) return v else: return fail_value
[ "def", "get_uint16", "(", "self", ",", "fail_value", "=", "0", ")", ":", "s", "=", "self", ".", "read_size", "(", "2", ")", "if", "s", ":", "v", ",", "=", "struct", ".", "unpack", "(", "self", ".", "byte_order", "+", "'H'", ",", "s", ")", "return", "v", "else", ":", "return", "fail_value" ]
https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/examples/python/file_extract.py#L90-L97
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/ipaddress.py
python
IPv6Address.is_unspecified
(self)
return self._ip == 0
Test if the address is unspecified. Returns: A boolean, True if this is the unspecified address as defined in RFC 2373 2.5.2.
Test if the address is unspecified.
[ "Test", "if", "the", "address", "is", "unspecified", "." ]
def is_unspecified(self): """Test if the address is unspecified. Returns: A boolean, True if this is the unspecified address as defined in RFC 2373 2.5.2. """ return self._ip == 0
[ "def", "is_unspecified", "(", "self", ")", ":", "return", "self", ".", "_ip", "==", "0" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/ipaddress.py#L2022-L2030
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/ops/partitioned_variables.py
python
create_partitioned_variables
( shape, slicing, initializer, dtype=dtypes.float32, trainable=True, collections=None, name=None, reuse=None)
Create a list of partitioned variables according to the given `slicing`. Currently only one dimension of the full variable can be sliced, and the full variable can be reconstructed by the concatenation of the returned list along that dimension. Args: shape: List of integers. The shape of the full variable. slicing: List of integers. How to partition the variable. Must be of the same length as `shape`. Each value indicate how many slices to create in the corresponding dimension. Presently only one of the values can be more than 1; that is, the variable can only be sliced along one dimension. For convenience, The requested number of partitions does not have to divide the corresponding dimension evenly. If it does not, the shapes of the partitions are incremented by 1 starting from partition 0 until all slack is absorbed. The adjustment rules may change in the future, but as you can save/restore these variables with different slicing specifications this should not be a problem. initializer: A `Tensor` of shape `shape` or a variable initializer function. If a function, it will be called once for each slice, passing the shape and data type of the slice as parameters. The function must return a tensor with the same shape as the slice. dtype: Type of the variables. Ignored if `initializer` is a `Tensor`. trainable: If True also add all the variables to the graph collection `GraphKeys.TRAINABLE_VARIABLES`. collections: List of graph collections keys to add the variables to. Defaults to `[GraphKeys.GLOBAL_VARIABLES]`. name: Optional name for the full variable. Defaults to `"PartitionedVariable"` and gets uniquified automatically. reuse: Boolean or `None`; if `True` and name is set, it would reuse previously created variables. if `False` it will create new variables. if `None`, it would inherit the parent scope reuse. Returns: A list of Variables corresponding to the slicing. Raises: ValueError: If any of the arguments is malformed.
Create a list of partitioned variables according to the given `slicing`.
[ "Create", "a", "list", "of", "partitioned", "variables", "according", "to", "the", "given", "slicing", "." ]
def create_partitioned_variables( shape, slicing, initializer, dtype=dtypes.float32, trainable=True, collections=None, name=None, reuse=None): """Create a list of partitioned variables according to the given `slicing`. Currently only one dimension of the full variable can be sliced, and the full variable can be reconstructed by the concatenation of the returned list along that dimension. Args: shape: List of integers. The shape of the full variable. slicing: List of integers. How to partition the variable. Must be of the same length as `shape`. Each value indicate how many slices to create in the corresponding dimension. Presently only one of the values can be more than 1; that is, the variable can only be sliced along one dimension. For convenience, The requested number of partitions does not have to divide the corresponding dimension evenly. If it does not, the shapes of the partitions are incremented by 1 starting from partition 0 until all slack is absorbed. The adjustment rules may change in the future, but as you can save/restore these variables with different slicing specifications this should not be a problem. initializer: A `Tensor` of shape `shape` or a variable initializer function. If a function, it will be called once for each slice, passing the shape and data type of the slice as parameters. The function must return a tensor with the same shape as the slice. dtype: Type of the variables. Ignored if `initializer` is a `Tensor`. trainable: If True also add all the variables to the graph collection `GraphKeys.TRAINABLE_VARIABLES`. collections: List of graph collections keys to add the variables to. Defaults to `[GraphKeys.GLOBAL_VARIABLES]`. name: Optional name for the full variable. Defaults to `"PartitionedVariable"` and gets uniquified automatically. reuse: Boolean or `None`; if `True` and name is set, it would reuse previously created variables. if `False` it will create new variables. if `None`, it would inherit the parent scope reuse. Returns: A list of Variables corresponding to the slicing. Raises: ValueError: If any of the arguments is malformed. """ logging.warn( "create_partitioned_variables is deprecated. Use " "tf.get_variable with a partitioner set, or " "tf.get_partitioned_variable_list, instead.") if len(shape) != len(slicing): raise ValueError("The 'shape' and 'slicing' of a partitioned Variable " "must have the length: shape: %s, slicing: %s" % (shape, slicing)) if len(shape) < 1: raise ValueError("A partitioned Variable must have rank at least 1: " "shape: %s" % shape) # Legacy: we are provided the slicing directly, so just pass it to # the partitioner. partitioner = lambda **unused_kwargs: slicing with variable_scope.variable_scope( name, "PartitionedVariable", reuse=reuse): # pylint: disable=protected-access partitioned_var = variable_scope._get_partitioned_variable( name=None, shape=shape, dtype=dtype, initializer=initializer, trainable=trainable, partitioner=partitioner, collections=collections) return list(partitioned_var)
[ "def", "create_partitioned_variables", "(", "shape", ",", "slicing", ",", "initializer", ",", "dtype", "=", "dtypes", ".", "float32", ",", "trainable", "=", "True", ",", "collections", "=", "None", ",", "name", "=", "None", ",", "reuse", "=", "None", ")", ":", "logging", ".", "warn", "(", "\"create_partitioned_variables is deprecated. Use \"", "\"tf.get_variable with a partitioner set, or \"", "\"tf.get_partitioned_variable_list, instead.\"", ")", "if", "len", "(", "shape", ")", "!=", "len", "(", "slicing", ")", ":", "raise", "ValueError", "(", "\"The 'shape' and 'slicing' of a partitioned Variable \"", "\"must have the length: shape: %s, slicing: %s\"", "%", "(", "shape", ",", "slicing", ")", ")", "if", "len", "(", "shape", ")", "<", "1", ":", "raise", "ValueError", "(", "\"A partitioned Variable must have rank at least 1: \"", "\"shape: %s\"", "%", "shape", ")", "# Legacy: we are provided the slicing directly, so just pass it to", "# the partitioner.", "partitioner", "=", "lambda", "*", "*", "unused_kwargs", ":", "slicing", "with", "variable_scope", ".", "variable_scope", "(", "name", ",", "\"PartitionedVariable\"", ",", "reuse", "=", "reuse", ")", ":", "# pylint: disable=protected-access", "partitioned_var", "=", "variable_scope", ".", "_get_partitioned_variable", "(", "name", "=", "None", ",", "shape", "=", "shape", ",", "dtype", "=", "dtype", ",", "initializer", "=", "initializer", ",", "trainable", "=", "trainable", ",", "partitioner", "=", "partitioner", ",", "collections", "=", "collections", ")", "return", "list", "(", "partitioned_var", ")" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/ops/partitioned_variables.py#L235-L307
intel/caffe
3f494b442ee3f9d17a07b09ecbd5fa2bbda00836
examples/faster-rcnn/lib/roi_data_layer/minibatch.py
python
_project_im_rois
(im_rois, im_scale_factor)
return rois
Project image RoIs into the rescaled training image.
Project image RoIs into the rescaled training image.
[ "Project", "image", "RoIs", "into", "the", "rescaled", "training", "image", "." ]
def _project_im_rois(im_rois, im_scale_factor): """Project image RoIs into the rescaled training image.""" rois = im_rois * im_scale_factor return rois
[ "def", "_project_im_rois", "(", "im_rois", ",", "im_scale_factor", ")", ":", "rois", "=", "im_rois", "*", "im_scale_factor", "return", "rois" ]
https://github.com/intel/caffe/blob/3f494b442ee3f9d17a07b09ecbd5fa2bbda00836/examples/faster-rcnn/lib/roi_data_layer/minibatch.py#L151-L154
llvm/llvm-project
ffa6262cb4e2a335d26416fad39a581b4f98c5f4
llvm/utils/lit/lit/util.py
python
to_unicode
(s)
return s
Return the parameter as type which supports unicode, possibly decoding it. In Python2, this is the unicode type. In Python3 it's the str type.
Return the parameter as type which supports unicode, possibly decoding it.
[ "Return", "the", "parameter", "as", "type", "which", "supports", "unicode", "possibly", "decoding", "it", "." ]
def to_unicode(s): """Return the parameter as type which supports unicode, possibly decoding it. In Python2, this is the unicode type. In Python3 it's the str type. """ if isinstance(s, bytes): # In Python2, this branch is taken for both 'str' and 'bytes'. # In Python3, this branch is taken only for 'bytes'. return s.decode('utf-8') return s
[ "def", "to_unicode", "(", "s", ")", ":", "if", "isinstance", "(", "s", ",", "bytes", ")", ":", "# In Python2, this branch is taken for both 'str' and 'bytes'.", "# In Python3, this branch is taken only for 'bytes'.", "return", "s", ".", "decode", "(", "'utf-8'", ")", "return", "s" ]
https://github.com/llvm/llvm-project/blob/ffa6262cb4e2a335d26416fad39a581b4f98c5f4/llvm/utils/lit/lit/util.py#L98-L109
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/mindrecord/tools/tfrecord_to_mr.py
python
TFRecordToMR.transform
(self)
return t.res
Encapsulate the run function to exit normally
Encapsulate the run function to exit normally
[ "Encapsulate", "the", "run", "function", "to", "exit", "normally" ]
def transform(self): """ Encapsulate the run function to exit normally """ t = ExceptionThread(target=self.run) t.daemon = True t.start() t.join() if t.exitcode != 0: raise t.exception return t.res
[ "def", "transform", "(", "self", ")", ":", "t", "=", "ExceptionThread", "(", "target", "=", "self", ".", "run", ")", "t", ".", "daemon", "=", "True", "t", ".", "start", "(", ")", "t", ".", "join", "(", ")", "if", "t", ".", "exitcode", "!=", "0", ":", "raise", "t", ".", "exception", "return", "t", ".", "res" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/mindrecord/tools/tfrecord_to_mr.py#L314-L325
mhammond/pywin32
44afd86ba8485194df93234639243252deeb40d5
com/win32com/makegw/makegwparse.py
python
ArgFormatter.GetBuildForInterfacePostCode
(self)
return ""
Get a string of C++ code to be executed after (ie, to finalise) the Py_BuildValue conversion for Interfaces
Get a string of C++ code to be executed after (ie, to finalise) the Py_BuildValue conversion for Interfaces
[ "Get", "a", "string", "of", "C", "++", "code", "to", "be", "executed", "after", "(", "ie", "to", "finalise", ")", "the", "Py_BuildValue", "conversion", "for", "Interfaces" ]
def GetBuildForInterfacePostCode(self): "Get a string of C++ code to be executed after (ie, to finalise) the Py_BuildValue conversion for Interfaces" if DEBUG: return "/* GetBuildForInterfacePostCode goes here: %s */\n" % self.arg.name return ""
[ "def", "GetBuildForInterfacePostCode", "(", "self", ")", ":", "if", "DEBUG", ":", "return", "\"/* GetBuildForInterfacePostCode goes here: %s */\\n\"", "%", "self", ".", "arg", ".", "name", "return", "\"\"" ]
https://github.com/mhammond/pywin32/blob/44afd86ba8485194df93234639243252deeb40d5/com/win32com/makegw/makegwparse.py#L183-L187
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/idlelib/macosx.py
python
setupApp
(root, flist)
Perform initial OS X customizations if needed. Called from pyshell.main() after initial calls to Tk() There are currently three major versions of Tk in use on OS X: 1. Aqua Cocoa Tk (native default since OS X 10.6) 2. Aqua Carbon Tk (original native, 32-bit only, deprecated) 3. X11 (supported by some third-party distributors, deprecated) There are various differences among the three that affect IDLE behavior, primarily with menus, mouse key events, and accelerators. Some one-time customizations are performed here. Others are dynamically tested throughout idlelib by calls to the isAquaTk(), isCarbonTk(), isCocoaTk(), isXQuartz() functions which are initialized here as well.
Perform initial OS X customizations if needed. Called from pyshell.main() after initial calls to Tk()
[ "Perform", "initial", "OS", "X", "customizations", "if", "needed", ".", "Called", "from", "pyshell", ".", "main", "()", "after", "initial", "calls", "to", "Tk", "()" ]
def setupApp(root, flist): """ Perform initial OS X customizations if needed. Called from pyshell.main() after initial calls to Tk() There are currently three major versions of Tk in use on OS X: 1. Aqua Cocoa Tk (native default since OS X 10.6) 2. Aqua Carbon Tk (original native, 32-bit only, deprecated) 3. X11 (supported by some third-party distributors, deprecated) There are various differences among the three that affect IDLE behavior, primarily with menus, mouse key events, and accelerators. Some one-time customizations are performed here. Others are dynamically tested throughout idlelib by calls to the isAquaTk(), isCarbonTk(), isCocoaTk(), isXQuartz() functions which are initialized here as well. """ if isAquaTk(): hideTkConsole(root) overrideRootMenu(root, flist) addOpenEventSupport(root, flist) fixb2context(root)
[ "def", "setupApp", "(", "root", ",", "flist", ")", ":", "if", "isAquaTk", "(", ")", ":", "hideTkConsole", "(", "root", ")", "overrideRootMenu", "(", "root", ",", "flist", ")", "addOpenEventSupport", "(", "root", ",", "flist", ")", "fixb2context", "(", "root", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/idlelib/macosx.py#L262-L282
microsoft/ELL
a1d6bacc37a14879cc025d9be2ba40b1a0632315
tools/utilities/pythonlibs/audio/training/dataset.py
python
Dataset.to_categorical
(self, labels, num_categories)
return result
Convert the labels to vector format useful for training, for example the label 3 out of 10 possible categories would become this vector: "0 0 0 1 0 0 0 0 0 0 0".
Convert the labels to vector format useful for training, for example the label 3 out of 10 possible categories would become this vector: "0 0 0 1 0 0 0 0 0 0 0".
[ "Convert", "the", "labels", "to", "vector", "format", "useful", "for", "training", "for", "example", "the", "label", "3", "out", "of", "10", "possible", "categories", "would", "become", "this", "vector", ":", "0", "0", "0", "1", "0", "0", "0", "0", "0", "0", "0", "." ]
def to_categorical(self, labels, num_categories): """ Convert the labels to vector format useful for training, for example the label 3 out of 10 possible categories would become this vector: "0 0 0 1 0 0 0 0 0 0 0". """ labels_arr = np.array(labels, dtype="int").ravel() num_rows = len(labels_arr) result = np.zeros((num_rows, num_categories)) result[np.arange(num_rows), labels_arr] = 1 return result
[ "def", "to_categorical", "(", "self", ",", "labels", ",", "num_categories", ")", ":", "labels_arr", "=", "np", ".", "array", "(", "labels", ",", "dtype", "=", "\"int\"", ")", ".", "ravel", "(", ")", "num_rows", "=", "len", "(", "labels_arr", ")", "result", "=", "np", ".", "zeros", "(", "(", "num_rows", ",", "num_categories", ")", ")", "result", "[", "np", ".", "arange", "(", "num_rows", ")", ",", "labels_arr", "]", "=", "1", "return", "result" ]
https://github.com/microsoft/ELL/blob/a1d6bacc37a14879cc025d9be2ba40b1a0632315/tools/utilities/pythonlibs/audio/training/dataset.py#L112-L121
openvinotoolkit/openvino
dedcbeafa8b84cccdc55ca64b8da516682b381c7
tools/pot/tools/frame_extractor/extractor.py
python
extract_frames_and_make_dataset
( video_file, output_dir, dataset_size, frame_step, ext='png')
Extracts frames with the highest motion value and creates dataset in specified directory :param video_file: path to video file :param output_dir: directory to save extracted images as dataset :param dataset_size: number of images to extract :param frame_step: step to drop frames from video and exclude launching of algorithm for them :param ext: extension of images in dataset
Extracts frames with the highest motion value and creates dataset in specified directory :param video_file: path to video file :param output_dir: directory to save extracted images as dataset :param dataset_size: number of images to extract :param frame_step: step to drop frames from video and exclude launching of algorithm for them :param ext: extension of images in dataset
[ "Extracts", "frames", "with", "the", "highest", "motion", "value", "and", "creates", "dataset", "in", "specified", "directory", ":", "param", "video_file", ":", "path", "to", "video", "file", ":", "param", "output_dir", ":", "directory", "to", "save", "extracted", "images", "as", "dataset", ":", "param", "dataset_size", ":", "number", "of", "images", "to", "extract", ":", "param", "frame_step", ":", "step", "to", "drop", "frames", "from", "video", "and", "exclude", "launching", "of", "algorithm", "for", "them", ":", "param", "ext", ":", "extension", "of", "images", "in", "dataset" ]
def extract_frames_and_make_dataset( video_file, output_dir, dataset_size, frame_step, ext='png'): """ Extracts frames with the highest motion value and creates dataset in specified directory :param video_file: path to video file :param output_dir: directory to save extracted images as dataset :param dataset_size: number of images to extract :param frame_step: step to drop frames from video and exclude launching of algorithm for them :param ext: extension of images in dataset """ frames_by_motion = sort_frame_indices_by_motion(video_file, frame_step) loader = video_loader.VideoLoader(video_file) if dataset_size is None: dataset_size = len(loader) if dataset_size > len(loader): raise RuntimeError('Number of images in output dataset should' ' not be bigger than number of images in video') dataset_indices = sorted(frames_by_motion[:dataset_size]) output_dir = Path(output_dir) for idx, dataset_idx in enumerate(dataset_indices): frame = loader[dataset_idx] cv.imwrite(str(output_dir / '{}.{}'.format(idx, ext)), frame)
[ "def", "extract_frames_and_make_dataset", "(", "video_file", ",", "output_dir", ",", "dataset_size", ",", "frame_step", ",", "ext", "=", "'png'", ")", ":", "frames_by_motion", "=", "sort_frame_indices_by_motion", "(", "video_file", ",", "frame_step", ")", "loader", "=", "video_loader", ".", "VideoLoader", "(", "video_file", ")", "if", "dataset_size", "is", "None", ":", "dataset_size", "=", "len", "(", "loader", ")", "if", "dataset_size", ">", "len", "(", "loader", ")", ":", "raise", "RuntimeError", "(", "'Number of images in output dataset should'", "' not be bigger than number of images in video'", ")", "dataset_indices", "=", "sorted", "(", "frames_by_motion", "[", ":", "dataset_size", "]", ")", "output_dir", "=", "Path", "(", "output_dir", ")", "for", "idx", ",", "dataset_idx", "in", "enumerate", "(", "dataset_indices", ")", ":", "frame", "=", "loader", "[", "dataset_idx", "]", "cv", ".", "imwrite", "(", "str", "(", "output_dir", "/", "'{}.{}'", ".", "format", "(", "idx", ",", "ext", ")", ")", ",", "frame", ")" ]
https://github.com/openvinotoolkit/openvino/blob/dedcbeafa8b84cccdc55ca64b8da516682b381c7/tools/pot/tools/frame_extractor/extractor.py#L57-L81
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/logging/handlers.py
python
NTEventLogHandler.close
(self)
Clean up this handler. You can remove the application name from the registry as a source of event log entries. However, if you do this, you will not be able to see the events as you intended in the Event Log Viewer - it needs to be able to access the registry to get the DLL name.
Clean up this handler.
[ "Clean", "up", "this", "handler", "." ]
def close(self): """ Clean up this handler. You can remove the application name from the registry as a source of event log entries. However, if you do this, you will not be able to see the events as you intended in the Event Log Viewer - it needs to be able to access the registry to get the DLL name. """ #self._welu.RemoveSourceFromRegistry(self.appname, self.logtype) logging.Handler.close(self)
[ "def", "close", "(", "self", ")", ":", "#self._welu.RemoveSourceFromRegistry(self.appname, self.logtype)", "logging", ".", "Handler", ".", "close", "(", "self", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/logging/handlers.py#L1111-L1122
apache/incubator-mxnet
f03fb23f1d103fec9541b5ae59ee06b1734a51d9
python/mxnet/base.py
python
_valid_error_name
(name)
return all(x.isalnum() or x in "_." for x in name)
Check whether name is a valid error name.
Check whether name is a valid error name.
[ "Check", "whether", "name", "is", "a", "valid", "error", "name", "." ]
def _valid_error_name(name): """Check whether name is a valid error name.""" return all(x.isalnum() or x in "_." for x in name)
[ "def", "_valid_error_name", "(", "name", ")", ":", "return", "all", "(", "x", ".", "isalnum", "(", ")", "or", "x", "in", "\"_.\"", "for", "x", "in", "name", ")" ]
https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/base.py#L140-L142
hpi-xnor/BMXNet
ed0b201da6667887222b8e4b5f997c4f6b61943d
python/mxnet/symbol/symbol.py
python
Symbol.debug_str
(self)
return py_str(debug_str.value)
Gets a debug string of symbol. It contains Symbol output, variables and operators in the computation graph with their inputs, variables and attributes. Returns ------- string Debug string of the symbol. Examples -------- >>> a = mx.sym.Variable('a') >>> b = mx.sym.sin(a) >>> c = 2 * a + b >>> d = mx.sym.FullyConnected(data=c, num_hidden=10) >>> d.debug_str() >>> print d.debug_str() Symbol Outputs: output[0]=fullyconnected0(0) Variable:a -------------------- Op:_mul_scalar, Name=_mulscalar0 Inputs: arg[0]=a(0) version=0 Attrs: scalar=2 -------------------- Op:sin, Name=sin0 Inputs: arg[0]=a(0) version=0 -------------------- Op:elemwise_add, Name=_plus0 Inputs: arg[0]=_mulscalar0(0) arg[1]=sin0(0) Variable:fullyconnected0_weight Variable:fullyconnected0_bias -------------------- Op:FullyConnected, Name=fullyconnected0 Inputs: arg[0]=_plus0(0) arg[1]=fullyconnected0_weight(0) version=0 arg[2]=fullyconnected0_bias(0) version=0 Attrs: num_hidden=10
Gets a debug string of symbol.
[ "Gets", "a", "debug", "string", "of", "symbol", "." ]
def debug_str(self): """Gets a debug string of symbol. It contains Symbol output, variables and operators in the computation graph with their inputs, variables and attributes. Returns ------- string Debug string of the symbol. Examples -------- >>> a = mx.sym.Variable('a') >>> b = mx.sym.sin(a) >>> c = 2 * a + b >>> d = mx.sym.FullyConnected(data=c, num_hidden=10) >>> d.debug_str() >>> print d.debug_str() Symbol Outputs: output[0]=fullyconnected0(0) Variable:a -------------------- Op:_mul_scalar, Name=_mulscalar0 Inputs: arg[0]=a(0) version=0 Attrs: scalar=2 -------------------- Op:sin, Name=sin0 Inputs: arg[0]=a(0) version=0 -------------------- Op:elemwise_add, Name=_plus0 Inputs: arg[0]=_mulscalar0(0) arg[1]=sin0(0) Variable:fullyconnected0_weight Variable:fullyconnected0_bias -------------------- Op:FullyConnected, Name=fullyconnected0 Inputs: arg[0]=_plus0(0) arg[1]=fullyconnected0_weight(0) version=0 arg[2]=fullyconnected0_bias(0) version=0 Attrs: num_hidden=10 """ debug_str = ctypes.c_char_p() check_call(_LIB.MXSymbolPrint( self.handle, ctypes.byref(debug_str))) return py_str(debug_str.value)
[ "def", "debug_str", "(", "self", ")", ":", "debug_str", "=", "ctypes", ".", "c_char_p", "(", ")", "check_call", "(", "_LIB", ".", "MXSymbolPrint", "(", "self", ".", "handle", ",", "ctypes", ".", "byref", "(", "debug_str", ")", ")", ")", "return", "py_str", "(", "debug_str", ".", "value", ")" ]
https://github.com/hpi-xnor/BMXNet/blob/ed0b201da6667887222b8e4b5f997c4f6b61943d/python/mxnet/symbol/symbol.py#L1108-L1159
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/contrib/learn/python/learn/models.py
python
linear_regression
(x, y, init_mean=None, init_stddev=1.0)
Creates linear regression TensorFlow subgraph. Args: x: tensor or placeholder for input features. y: tensor or placeholder for labels. init_mean: the mean value to use for initialization. init_stddev: the standard deviation to use for initialization. Returns: Predictions and loss tensors. Side effects: The variables linear_regression.weights and linear_regression.bias are initialized as follows. If init_mean is not None, then initialization will be done using a random normal initializer with the given init_mean and init_stddv. (These may be set to 0.0 each if a zero initialization is desirable for convex use cases.) If init_mean is None, then the uniform_unit_scaling_initialzer will be used.
Creates linear regression TensorFlow subgraph.
[ "Creates", "linear", "regression", "TensorFlow", "subgraph", "." ]
def linear_regression(x, y, init_mean=None, init_stddev=1.0): """Creates linear regression TensorFlow subgraph. Args: x: tensor or placeholder for input features. y: tensor or placeholder for labels. init_mean: the mean value to use for initialization. init_stddev: the standard deviation to use for initialization. Returns: Predictions and loss tensors. Side effects: The variables linear_regression.weights and linear_regression.bias are initialized as follows. If init_mean is not None, then initialization will be done using a random normal initializer with the given init_mean and init_stddv. (These may be set to 0.0 each if a zero initialization is desirable for convex use cases.) If init_mean is None, then the uniform_unit_scaling_initialzer will be used. """ with vs.variable_scope('linear_regression'): scope_name = vs.get_variable_scope().name summary.histogram('%s.x' % scope_name, x) summary.histogram('%s.y' % scope_name, y) dtype = x.dtype.base_dtype y_shape = y.get_shape() if len(y_shape) == 1: output_shape = 1 else: output_shape = y_shape[1] # Set up the requested initialization. if init_mean is None: weights = vs.get_variable( 'weights', [x.get_shape()[1], output_shape], dtype=dtype) bias = vs.get_variable('bias', [output_shape], dtype=dtype) else: weights = vs.get_variable( 'weights', [x.get_shape()[1], output_shape], initializer=init_ops.random_normal_initializer( init_mean, init_stddev, dtype=dtype), dtype=dtype) bias = vs.get_variable( 'bias', [output_shape], initializer=init_ops.random_normal_initializer( init_mean, init_stddev, dtype=dtype), dtype=dtype) summary.histogram('%s.weights' % scope_name, weights) summary.histogram('%s.bias' % scope_name, bias) return losses_ops.mean_squared_error_regressor(x, y, weights, bias)
[ "def", "linear_regression", "(", "x", ",", "y", ",", "init_mean", "=", "None", ",", "init_stddev", "=", "1.0", ")", ":", "with", "vs", ".", "variable_scope", "(", "'linear_regression'", ")", ":", "scope_name", "=", "vs", ".", "get_variable_scope", "(", ")", ".", "name", "summary", ".", "histogram", "(", "'%s.x'", "%", "scope_name", ",", "x", ")", "summary", ".", "histogram", "(", "'%s.y'", "%", "scope_name", ",", "y", ")", "dtype", "=", "x", ".", "dtype", ".", "base_dtype", "y_shape", "=", "y", ".", "get_shape", "(", ")", "if", "len", "(", "y_shape", ")", "==", "1", ":", "output_shape", "=", "1", "else", ":", "output_shape", "=", "y_shape", "[", "1", "]", "# Set up the requested initialization.", "if", "init_mean", "is", "None", ":", "weights", "=", "vs", ".", "get_variable", "(", "'weights'", ",", "[", "x", ".", "get_shape", "(", ")", "[", "1", "]", ",", "output_shape", "]", ",", "dtype", "=", "dtype", ")", "bias", "=", "vs", ".", "get_variable", "(", "'bias'", ",", "[", "output_shape", "]", ",", "dtype", "=", "dtype", ")", "else", ":", "weights", "=", "vs", ".", "get_variable", "(", "'weights'", ",", "[", "x", ".", "get_shape", "(", ")", "[", "1", "]", ",", "output_shape", "]", ",", "initializer", "=", "init_ops", ".", "random_normal_initializer", "(", "init_mean", ",", "init_stddev", ",", "dtype", "=", "dtype", ")", ",", "dtype", "=", "dtype", ")", "bias", "=", "vs", ".", "get_variable", "(", "'bias'", ",", "[", "output_shape", "]", ",", "initializer", "=", "init_ops", ".", "random_normal_initializer", "(", "init_mean", ",", "init_stddev", ",", "dtype", "=", "dtype", ")", ",", "dtype", "=", "dtype", ")", "summary", ".", "histogram", "(", "'%s.weights'", "%", "scope_name", ",", "weights", ")", "summary", ".", "histogram", "(", "'%s.bias'", "%", "scope_name", ",", "bias", ")", "return", "losses_ops", ".", "mean_squared_error_regressor", "(", "x", ",", "y", ",", "weights", ",", "bias", ")" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/learn/python/learn/models.py#L59-L107
ROCmSoftwarePlatform/hipCaffe
4ec5d482515cce532348553b6db6d00d015675d5
scripts/cpp_lint.py
python
CleanseComments
(line)
return _RE_PATTERN_CLEANSE_LINE_C_COMMENTS.sub('', line)
Removes //-comments and single-line C-style /* */ comments. Args: line: A line of C++ source. Returns: The line with single-line comments removed.
Removes //-comments and single-line C-style /* */ comments.
[ "Removes", "//", "-", "comments", "and", "single", "-", "line", "C", "-", "style", "/", "*", "*", "/", "comments", "." ]
def CleanseComments(line): """Removes //-comments and single-line C-style /* */ comments. Args: line: A line of C++ source. Returns: The line with single-line comments removed. """ commentpos = line.find('//') if commentpos != -1 and not IsCppString(line[:commentpos]): line = line[:commentpos].rstrip() # get rid of /* ... */ return _RE_PATTERN_CLEANSE_LINE_C_COMMENTS.sub('', line)
[ "def", "CleanseComments", "(", "line", ")", ":", "commentpos", "=", "line", ".", "find", "(", "'//'", ")", "if", "commentpos", "!=", "-", "1", "and", "not", "IsCppString", "(", "line", "[", ":", "commentpos", "]", ")", ":", "line", "=", "line", "[", ":", "commentpos", "]", ".", "rstrip", "(", ")", "# get rid of /* ... */", "return", "_RE_PATTERN_CLEANSE_LINE_C_COMMENTS", ".", "sub", "(", "''", ",", "line", ")" ]
https://github.com/ROCmSoftwarePlatform/hipCaffe/blob/4ec5d482515cce532348553b6db6d00d015675d5/scripts/cpp_lint.py#L1167-L1180
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/prompt-toolkit/py2/prompt_toolkit/key_binding/bindings/named_commands.py
python
beginning_of_line
(event)
Move to the start of the current line.
Move to the start of the current line.
[ "Move", "to", "the", "start", "of", "the", "current", "line", "." ]
def beginning_of_line(event): " Move to the start of the current line. " buff = event.current_buffer buff.cursor_position += buff.document.get_start_of_line_position(after_whitespace=False)
[ "def", "beginning_of_line", "(", "event", ")", ":", "buff", "=", "event", ".", "current_buffer", "buff", ".", "cursor_position", "+=", "buff", ".", "document", ".", "get_start_of_line_position", "(", "after_whitespace", "=", "False", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/prompt-toolkit/py2/prompt_toolkit/key_binding/bindings/named_commands.py#L54-L57
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py3/scipy/signal/wavelets.py
python
ricker
(points, a)
return total
Return a Ricker wavelet, also known as the "Mexican hat wavelet". It models the function: ``A (1 - x^2/a^2) exp(-x^2/2 a^2)``, where ``A = 2/sqrt(3a)pi^1/4``. Parameters ---------- points : int Number of points in `vector`. Will be centered around 0. a : scalar Width parameter of the wavelet. Returns ------- vector : (N,) ndarray Array of length `points` in shape of ricker curve. Examples -------- >>> from scipy import signal >>> import matplotlib.pyplot as plt >>> points = 100 >>> a = 4.0 >>> vec2 = signal.ricker(points, a) >>> print(len(vec2)) 100 >>> plt.plot(vec2) >>> plt.show()
Return a Ricker wavelet, also known as the "Mexican hat wavelet".
[ "Return", "a", "Ricker", "wavelet", "also", "known", "as", "the", "Mexican", "hat", "wavelet", "." ]
def ricker(points, a): """ Return a Ricker wavelet, also known as the "Mexican hat wavelet". It models the function: ``A (1 - x^2/a^2) exp(-x^2/2 a^2)``, where ``A = 2/sqrt(3a)pi^1/4``. Parameters ---------- points : int Number of points in `vector`. Will be centered around 0. a : scalar Width parameter of the wavelet. Returns ------- vector : (N,) ndarray Array of length `points` in shape of ricker curve. Examples -------- >>> from scipy import signal >>> import matplotlib.pyplot as plt >>> points = 100 >>> a = 4.0 >>> vec2 = signal.ricker(points, a) >>> print(len(vec2)) 100 >>> plt.plot(vec2) >>> plt.show() """ A = 2 / (np.sqrt(3 * a) * (np.pi**0.25)) wsq = a**2 vec = np.arange(0, points) - (points - 1.0) / 2 xsq = vec**2 mod = (1 - xsq / wsq) gauss = np.exp(-xsq / (2 * wsq)) total = A * mod * gauss return total
[ "def", "ricker", "(", "points", ",", "a", ")", ":", "A", "=", "2", "/", "(", "np", ".", "sqrt", "(", "3", "*", "a", ")", "*", "(", "np", ".", "pi", "**", "0.25", ")", ")", "wsq", "=", "a", "**", "2", "vec", "=", "np", ".", "arange", "(", "0", ",", "points", ")", "-", "(", "points", "-", "1.0", ")", "/", "2", "xsq", "=", "vec", "**", "2", "mod", "=", "(", "1", "-", "xsq", "/", "wsq", ")", "gauss", "=", "np", ".", "exp", "(", "-", "xsq", "/", "(", "2", "*", "wsq", ")", ")", "total", "=", "A", "*", "mod", "*", "gauss", "return", "total" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/signal/wavelets.py#L264-L308
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/threading.py
python
_Event.set
(self)
Set the internal flag to true. All threads waiting for the flag to become true are awakened. Threads that call wait() once the flag is true will not block at all.
Set the internal flag to true.
[ "Set", "the", "internal", "flag", "to", "true", "." ]
def set(self): """Set the internal flag to true. All threads waiting for the flag to become true are awakened. Threads that call wait() once the flag is true will not block at all. """ self.__cond.acquire() try: self.__flag = True self.__cond.notify_all() finally: self.__cond.release()
[ "def", "set", "(", "self", ")", ":", "self", ".", "__cond", ".", "acquire", "(", ")", "try", ":", "self", ".", "__flag", "=", "True", "self", ".", "__cond", ".", "notify_all", "(", ")", "finally", ":", "self", ".", "__cond", ".", "release", "(", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/threading.py#L573-L585
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/cgi.py
python
parse_header
(line)
return key, pdict
Parse a Content-type like header. Return the main content-type and a dictionary of options.
Parse a Content-type like header.
[ "Parse", "a", "Content", "-", "type", "like", "header", "." ]
def parse_header(line): """Parse a Content-type like header. Return the main content-type and a dictionary of options. """ parts = _parseparam(';' + line) key = parts.next() pdict = {} for p in parts: i = p.find('=') if i >= 0: name = p[:i].strip().lower() value = p[i+1:].strip() if len(value) >= 2 and value[0] == value[-1] == '"': value = value[1:-1] value = value.replace('\\\\', '\\').replace('\\"', '"') pdict[name] = value return key, pdict
[ "def", "parse_header", "(", "line", ")", ":", "parts", "=", "_parseparam", "(", "';'", "+", "line", ")", "key", "=", "parts", ".", "next", "(", ")", "pdict", "=", "{", "}", "for", "p", "in", "parts", ":", "i", "=", "p", ".", "find", "(", "'='", ")", "if", "i", ">=", "0", ":", "name", "=", "p", "[", ":", "i", "]", ".", "strip", "(", ")", ".", "lower", "(", ")", "value", "=", "p", "[", "i", "+", "1", ":", "]", ".", "strip", "(", ")", "if", "len", "(", "value", ")", ">=", "2", "and", "value", "[", "0", "]", "==", "value", "[", "-", "1", "]", "==", "'\"'", ":", "value", "=", "value", "[", "1", ":", "-", "1", "]", "value", "=", "value", ".", "replace", "(", "'\\\\\\\\'", ",", "'\\\\'", ")", ".", "replace", "(", "'\\\\\"'", ",", "'\"'", ")", "pdict", "[", "name", "]", "=", "value", "return", "key", ",", "pdict" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/cgi.py#L304-L322
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/email/_parseaddr.py
python
AddrlistClass.getaddrspec
(self)
return EMPTYSTRING.join(aslist) + self.getdomain()
Parse an RFC 2822 addr-spec.
Parse an RFC 2822 addr-spec.
[ "Parse", "an", "RFC", "2822", "addr", "-", "spec", "." ]
def getaddrspec(self): """Parse an RFC 2822 addr-spec.""" aslist = [] self.gotonext() while self.pos < len(self.field): if self.field[self.pos] == '.': aslist.append('.') self.pos += 1 elif self.field[self.pos] == '"': aslist.append('"%s"' % self.getquote()) elif self.field[self.pos] in self.atomends: break else: aslist.append(self.getatom()) self.gotonext() if self.pos >= len(self.field) or self.field[self.pos] != '@': return EMPTYSTRING.join(aslist) aslist.append('@') self.pos += 1 self.gotonext() return EMPTYSTRING.join(aslist) + self.getdomain()
[ "def", "getaddrspec", "(", "self", ")", ":", "aslist", "=", "[", "]", "self", ".", "gotonext", "(", ")", "while", "self", ".", "pos", "<", "len", "(", "self", ".", "field", ")", ":", "if", "self", ".", "field", "[", "self", ".", "pos", "]", "==", "'.'", ":", "aslist", ".", "append", "(", "'.'", ")", "self", ".", "pos", "+=", "1", "elif", "self", ".", "field", "[", "self", ".", "pos", "]", "==", "'\"'", ":", "aslist", ".", "append", "(", "'\"%s\"'", "%", "self", ".", "getquote", "(", ")", ")", "elif", "self", ".", "field", "[", "self", ".", "pos", "]", "in", "self", ".", "atomends", ":", "break", "else", ":", "aslist", ".", "append", "(", "self", ".", "getatom", "(", ")", ")", "self", ".", "gotonext", "(", ")", "if", "self", ".", "pos", ">=", "len", "(", "self", ".", "field", ")", "or", "self", ".", "field", "[", "self", ".", "pos", "]", "!=", "'@'", ":", "return", "EMPTYSTRING", ".", "join", "(", "aslist", ")", "aslist", ".", "append", "(", "'@'", ")", "self", ".", "pos", "+=", "1", "self", ".", "gotonext", "(", ")", "return", "EMPTYSTRING", ".", "join", "(", "aslist", ")", "+", "self", ".", "getdomain", "(", ")" ]
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/email/_parseaddr.py#L299-L322
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/python/ops/variable_scope.py
python
variable_op_scope
(values, name_or_scope, default_name=None, initializer=None, regularizer=None, caching_device=None, partitioner=None, custom_getter=None, reuse=None, dtype=None, use_resource=None)
Deprecated: context manager for defining an op that creates variables.
Deprecated: context manager for defining an op that creates variables.
[ "Deprecated", ":", "context", "manager", "for", "defining", "an", "op", "that", "creates", "variables", "." ]
def variable_op_scope(values, name_or_scope, default_name=None, initializer=None, regularizer=None, caching_device=None, partitioner=None, custom_getter=None, reuse=None, dtype=None, use_resource=None): """Deprecated: context manager for defining an op that creates variables.""" logging.warn("tf.variable_op_scope(values, name, default_name) is deprecated," " use tf.variable_scope(name, default_name, values)") with variable_scope(name_or_scope, default_name=default_name, values=values, initializer=initializer, regularizer=regularizer, caching_device=caching_device, partitioner=partitioner, custom_getter=custom_getter, reuse=reuse, dtype=dtype, use_resource=use_resource) as scope: yield scope
[ "def", "variable_op_scope", "(", "values", ",", "name_or_scope", ",", "default_name", "=", "None", ",", "initializer", "=", "None", ",", "regularizer", "=", "None", ",", "caching_device", "=", "None", ",", "partitioner", "=", "None", ",", "custom_getter", "=", "None", ",", "reuse", "=", "None", ",", "dtype", "=", "None", ",", "use_resource", "=", "None", ")", ":", "logging", ".", "warn", "(", "\"tf.variable_op_scope(values, name, default_name) is deprecated,\"", "\" use tf.variable_scope(name, default_name, values)\"", ")", "with", "variable_scope", "(", "name_or_scope", ",", "default_name", "=", "default_name", ",", "values", "=", "values", ",", "initializer", "=", "initializer", ",", "regularizer", "=", "regularizer", ",", "caching_device", "=", "caching_device", ",", "partitioner", "=", "partitioner", ",", "custom_getter", "=", "custom_getter", ",", "reuse", "=", "reuse", ",", "dtype", "=", "dtype", ",", "use_resource", "=", "use_resource", ")", "as", "scope", ":", "yield", "scope" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/ops/variable_scope.py#L1605-L1630
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/richtext.py
python
RichTextBuffer.BeginTextColour
(*args, **kwargs)
return _richtext.RichTextBuffer_BeginTextColour(*args, **kwargs)
BeginTextColour(self, Colour colour) -> bool
BeginTextColour(self, Colour colour) -> bool
[ "BeginTextColour", "(", "self", "Colour", "colour", ")", "-", ">", "bool" ]
def BeginTextColour(*args, **kwargs): """BeginTextColour(self, Colour colour) -> bool""" return _richtext.RichTextBuffer_BeginTextColour(*args, **kwargs)
[ "def", "BeginTextColour", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_richtext", ".", "RichTextBuffer_BeginTextColour", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/richtext.py#L2373-L2375
microsoft/onnxruntime
f92e47e95b13a240e37caf7b36577983544f98fc
orttraining/orttraining/python/training/ortmodule/_graph_execution_manager.py
python
GraphExecutionManager._get_session_config
(self)
return session_options, providers, provider_options
Creates and returns the session configuration to be used for the ExecutionAgent
Creates and returns the session configuration to be used for the ExecutionAgent
[ "Creates", "and", "returns", "the", "session", "configuration", "to", "be", "used", "for", "the", "ExecutionAgent" ]
def _get_session_config(self): """Creates and returns the session configuration to be used for the ExecutionAgent""" if _are_deterministic_algorithms_enabled(): if self._debug_options.logging.log_level <= _logger.LogLevel.INFO: warnings.warn("ORTModule's determinism will be enabled because PyTorch's determinism is enabled.", UserWarning) providers = None provider_options = None if self._device.type == 'cuda': # Configure the InferenceSessions to use the specific GPU on which the model is placed. providers = (["ROCMExecutionProvider"] if self.is_rocm_pytorch else [ "CUDAExecutionProvider"]) providers.append("CPUExecutionProvider") provider_option_map = {"device_id": str(self._device.index)} if not self.is_rocm_pytorch: # Set Conv algo search mode to HEURISTIC, which is same as PyTorch's default setting. provider_option_map["cudnn_conv_algo_search"] = "HEURISTIC" provider_option_map["cudnn_conv_use_max_workspace"] = "1" if self._use_external_gpu_allocator: provider_option_map["gpu_external_alloc"] = str(self._torch_alloc) provider_option_map["gpu_external_free"] = str(self._torch_free) provider_option_map["gpu_external_empty_cache"] = str(self._torch_empty_cache) provider_options = [provider_option_map, {}] elif self._device.type == 'cpu': providers = ["CPUExecutionProvider"] provider_options = [{}] elif self._device.type == 'ort': provider_info = C.get_ort_device_provider_info(self._device.index) assert len(provider_info.keys()) == 1 providers = list(provider_info.keys()) provider_options = [provider_info[providers[0]]] session_options = onnxruntime.SessionOptions() session_options.enable_mem_pattern = False session_options.enable_mem_reuse = False session_options.use_deterministic_compute = _are_deterministic_algorithms_enabled() # default to PRIORITY_BASED execution order session_options.execution_order = onnxruntime.ExecutionOrder.PRIORITY_BASED # 0:Verbose, 1:Info, 2:Warning. 3:Error, 4:Fatal. Default is 2. session_options.log_severity_level = int( self._debug_options.logging.log_level) if self._debug_options.save_onnx_models.save: session_options.optimized_model_filepath = \ os.path.join(self._debug_options.save_onnx_models.path, _onnx_models._get_onnx_file_name( self._debug_options.save_onnx_models.name_prefix, 'execution_model', self._export_mode)) return session_options, providers, provider_options
[ "def", "_get_session_config", "(", "self", ")", ":", "if", "_are_deterministic_algorithms_enabled", "(", ")", ":", "if", "self", ".", "_debug_options", ".", "logging", ".", "log_level", "<=", "_logger", ".", "LogLevel", ".", "INFO", ":", "warnings", ".", "warn", "(", "\"ORTModule's determinism will be enabled because PyTorch's determinism is enabled.\"", ",", "UserWarning", ")", "providers", "=", "None", "provider_options", "=", "None", "if", "self", ".", "_device", ".", "type", "==", "'cuda'", ":", "# Configure the InferenceSessions to use the specific GPU on which the model is placed.", "providers", "=", "(", "[", "\"ROCMExecutionProvider\"", "]", "if", "self", ".", "is_rocm_pytorch", "else", "[", "\"CUDAExecutionProvider\"", "]", ")", "providers", ".", "append", "(", "\"CPUExecutionProvider\"", ")", "provider_option_map", "=", "{", "\"device_id\"", ":", "str", "(", "self", ".", "_device", ".", "index", ")", "}", "if", "not", "self", ".", "is_rocm_pytorch", ":", "# Set Conv algo search mode to HEURISTIC, which is same as PyTorch's default setting.", "provider_option_map", "[", "\"cudnn_conv_algo_search\"", "]", "=", "\"HEURISTIC\"", "provider_option_map", "[", "\"cudnn_conv_use_max_workspace\"", "]", "=", "\"1\"", "if", "self", ".", "_use_external_gpu_allocator", ":", "provider_option_map", "[", "\"gpu_external_alloc\"", "]", "=", "str", "(", "self", ".", "_torch_alloc", ")", "provider_option_map", "[", "\"gpu_external_free\"", "]", "=", "str", "(", "self", ".", "_torch_free", ")", "provider_option_map", "[", "\"gpu_external_empty_cache\"", "]", "=", "str", "(", "self", ".", "_torch_empty_cache", ")", "provider_options", "=", "[", "provider_option_map", ",", "{", "}", "]", "elif", "self", ".", "_device", ".", "type", "==", "'cpu'", ":", "providers", "=", "[", "\"CPUExecutionProvider\"", "]", "provider_options", "=", "[", "{", "}", "]", "elif", "self", ".", "_device", ".", "type", "==", "'ort'", ":", "provider_info", "=", "C", ".", "get_ort_device_provider_info", "(", "self", ".", "_device", ".", "index", ")", "assert", "len", "(", "provider_info", ".", "keys", "(", ")", ")", "==", "1", "providers", "=", "list", "(", "provider_info", ".", "keys", "(", ")", ")", "provider_options", "=", "[", "provider_info", "[", "providers", "[", "0", "]", "]", "]", "session_options", "=", "onnxruntime", ".", "SessionOptions", "(", ")", "session_options", ".", "enable_mem_pattern", "=", "False", "session_options", ".", "enable_mem_reuse", "=", "False", "session_options", ".", "use_deterministic_compute", "=", "_are_deterministic_algorithms_enabled", "(", ")", "# default to PRIORITY_BASED execution order", "session_options", ".", "execution_order", "=", "onnxruntime", ".", "ExecutionOrder", ".", "PRIORITY_BASED", "# 0:Verbose, 1:Info, 2:Warning. 3:Error, 4:Fatal. Default is 2.", "session_options", ".", "log_severity_level", "=", "int", "(", "self", ".", "_debug_options", ".", "logging", ".", "log_level", ")", "if", "self", ".", "_debug_options", ".", "save_onnx_models", ".", "save", ":", "session_options", ".", "optimized_model_filepath", "=", "os", ".", "path", ".", "join", "(", "self", ".", "_debug_options", ".", "save_onnx_models", ".", "path", ",", "_onnx_models", ".", "_get_onnx_file_name", "(", "self", ".", "_debug_options", ".", "save_onnx_models", ".", "name_prefix", ",", "'execution_model'", ",", "self", ".", "_export_mode", ")", ")", "return", "session_options", ",", "providers", ",", "provider_options" ]
https://github.com/microsoft/onnxruntime/blob/f92e47e95b13a240e37caf7b36577983544f98fc/orttraining/orttraining/python/training/ortmodule/_graph_execution_manager.py#L249-L300
llvm/llvm-project
ffa6262cb4e2a335d26416fad39a581b4f98c5f4
mlir/python/mlir/dialects/linalg/opdsl/lang/affine.py
python
AffineBinaryExprDef.visit_affine_exprs
(self, callback)
Visits all AffineExprDefs including self.
Visits all AffineExprDefs including self.
[ "Visits", "all", "AffineExprDefs", "including", "self", "." ]
def visit_affine_exprs(self, callback): """Visits all AffineExprDefs including self.""" super().visit_affine_exprs(callback) self.lhs.visit_affine_exprs(callback) self.rhs.visit_affine_exprs(callback)
[ "def", "visit_affine_exprs", "(", "self", ",", "callback", ")", ":", "super", "(", ")", ".", "visit_affine_exprs", "(", "callback", ")", "self", ".", "lhs", ".", "visit_affine_exprs", "(", "callback", ")", "self", ".", "rhs", ".", "visit_affine_exprs", "(", "callback", ")" ]
https://github.com/llvm/llvm-project/blob/ffa6262cb4e2a335d26416fad39a581b4f98c5f4/mlir/python/mlir/dialects/linalg/opdsl/lang/affine.py#L220-L224
apache/incubator-mxnet
f03fb23f1d103fec9541b5ae59ee06b1734a51d9
python/mxnet/gluon/probability/distributions/binomial.py
python
Binomial.prob
(self)
return logit2prob(self.logit, True)
Get the probability of sampling `1`. Returns ------- Tensor Parameter tensor.
Get the probability of sampling `1`.
[ "Get", "the", "probability", "of", "sampling", "1", "." ]
def prob(self): """Get the probability of sampling `1`. Returns ------- Tensor Parameter tensor. """ # pylint: disable=method-hidden return logit2prob(self.logit, True)
[ "def", "prob", "(", "self", ")", ":", "# pylint: disable=method-hidden", "return", "logit2prob", "(", "self", ".", "logit", ",", "True", ")" ]
https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/gluon/probability/distributions/binomial.py#L66-L75
apache/incubator-mxnet
f03fb23f1d103fec9541b5ae59ee06b1734a51d9
python/mxnet/symbol/symbol.py
python
split_v2
(ary, indices_or_sections, axis=0, squeeze_axis=False)
return _internal._split_v2(ary, indices, axis, squeeze_axis, sections)
Split an array into multiple sub-arrays. Parameters ---------- ary : NDArray Array to be divided into sub-arrays. indices_or_sections : int or tuple of ints If `indices_or_sections` is an integer, N, the array will be divided into N equal arrays along `axis`. If such a split is not possible, an error is raised. If `indices_or_sections` is a 1-D array of sorted integers, the entries indicate where along `axis` the array is split. For example, ``[2, 3]`` would, for ``axis=0``, result in - ary[:2] - ary[2:3] - ary[3:] If an index exceeds the dimension of the array along `axis`, an empty sub-array is returned correspondingly. axis : int, optional The axis along which to split, default is 0. squeeze_axis: boolean, optional Whether to squeeze the axis of sub-arrays or not, only useful when size of the sub-arrays are 1 on the `axis`. Default is False. Returns ------- out : Symbol The created Symbol
Split an array into multiple sub-arrays.
[ "Split", "an", "array", "into", "multiple", "sub", "-", "arrays", "." ]
def split_v2(ary, indices_or_sections, axis=0, squeeze_axis=False): """Split an array into multiple sub-arrays. Parameters ---------- ary : NDArray Array to be divided into sub-arrays. indices_or_sections : int or tuple of ints If `indices_or_sections` is an integer, N, the array will be divided into N equal arrays along `axis`. If such a split is not possible, an error is raised. If `indices_or_sections` is a 1-D array of sorted integers, the entries indicate where along `axis` the array is split. For example, ``[2, 3]`` would, for ``axis=0``, result in - ary[:2] - ary[2:3] - ary[3:] If an index exceeds the dimension of the array along `axis`, an empty sub-array is returned correspondingly. axis : int, optional The axis along which to split, default is 0. squeeze_axis: boolean, optional Whether to squeeze the axis of sub-arrays or not, only useful when size of the sub-arrays are 1 on the `axis`. Default is False. Returns ------- out : Symbol The created Symbol """ indices = [] sections = 0 if isinstance(indices_or_sections, int): sections = indices_or_sections elif isinstance(indices_or_sections, tuple): indices = [0] + list(indices_or_sections) else: raise ValueError('indices_or_sections must either int or tuple of ints') return _internal._split_v2(ary, indices, axis, squeeze_axis, sections)
[ "def", "split_v2", "(", "ary", ",", "indices_or_sections", ",", "axis", "=", "0", ",", "squeeze_axis", "=", "False", ")", ":", "indices", "=", "[", "]", "sections", "=", "0", "if", "isinstance", "(", "indices_or_sections", ",", "int", ")", ":", "sections", "=", "indices_or_sections", "elif", "isinstance", "(", "indices_or_sections", ",", "tuple", ")", ":", "indices", "=", "[", "0", "]", "+", "list", "(", "indices_or_sections", ")", "else", ":", "raise", "ValueError", "(", "'indices_or_sections must either int or tuple of ints'", ")", "return", "_internal", ".", "_split_v2", "(", "ary", ",", "indices", ",", "axis", ",", "squeeze_axis", ",", "sections", ")" ]
https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/symbol/symbol.py#L3273-L3311
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/stringold.py
python
lower
(s)
return s.lower()
lower(s) -> string Return a copy of the string s converted to lowercase.
lower(s) -> string
[ "lower", "(", "s", ")", "-", ">", "string" ]
def lower(s): """lower(s) -> string Return a copy of the string s converted to lowercase. """ return s.lower()
[ "def", "lower", "(", "s", ")", ":", "return", "s", ".", "lower", "(", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/stringold.py#L46-L52
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/klampt/robotsim.py
python
Geometry3D.getGeometricPrimitive
(self)
return _robotsim.Geometry3D_getGeometricPrimitive(self)
r""" Returns a GeometricPrimitive if this geometry is of type GeometricPrimitive.
r""" Returns a GeometricPrimitive if this geometry is of type GeometricPrimitive.
[ "r", "Returns", "a", "GeometricPrimitive", "if", "this", "geometry", "is", "of", "type", "GeometricPrimitive", "." ]
def getGeometricPrimitive(self) -> "GeometricPrimitive": r""" Returns a GeometricPrimitive if this geometry is of type GeometricPrimitive. """ return _robotsim.Geometry3D_getGeometricPrimitive(self)
[ "def", "getGeometricPrimitive", "(", "self", ")", "->", "\"GeometricPrimitive\"", ":", "return", "_robotsim", ".", "Geometry3D_getGeometricPrimitive", "(", "self", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/robotsim.py#L2103-L2108
jackaudio/jack2
21b293dbc37d42446141a08922cdec0d2550c6a0
waflib/Tools/c_aliases.py
python
get_extensions
(lst)
return ret
Returns the file extensions for the list of files given as input :param lst: files to process :list lst: list of string or :py:class:`waflib.Node.Node` :return: list of file extensions :rtype: list of string
Returns the file extensions for the list of files given as input
[ "Returns", "the", "file", "extensions", "for", "the", "list", "of", "files", "given", "as", "input" ]
def get_extensions(lst): """ Returns the file extensions for the list of files given as input :param lst: files to process :list lst: list of string or :py:class:`waflib.Node.Node` :return: list of file extensions :rtype: list of string """ ret = [] for x in Utils.to_list(lst): if not isinstance(x, str): x = x.name ret.append(x[x.rfind('.') + 1:]) return ret
[ "def", "get_extensions", "(", "lst", ")", ":", "ret", "=", "[", "]", "for", "x", "in", "Utils", ".", "to_list", "(", "lst", ")", ":", "if", "not", "isinstance", "(", "x", ",", "str", ")", ":", "x", "=", "x", ".", "name", "ret", ".", "append", "(", "x", "[", "x", ".", "rfind", "(", "'.'", ")", "+", "1", ":", "]", ")", "return", "ret" ]
https://github.com/jackaudio/jack2/blob/21b293dbc37d42446141a08922cdec0d2550c6a0/waflib/Tools/c_aliases.py#L10-L24
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
tools/telemetry/third_party/png/png.py
python
Writer.write
(self, outfile, rows)
Write a PNG image to the output file. `rows` should be an iterable that yields each row in boxed row flat pixel format. The rows should be the rows of the original image, so there should be ``self.height`` rows of ``self.width * self.planes`` values. If `interlace` is specified (when creating the instance), then an interlaced PNG file will be written. Supply the rows in the normal image order; the interlacing is carried out internally. .. note :: Interlacing will require the entire image to be in working memory.
Write a PNG image to the output file. `rows` should be an iterable that yields each row in boxed row flat pixel format. The rows should be the rows of the original image, so there should be ``self.height`` rows of ``self.width * self.planes`` values. If `interlace` is specified (when creating the instance), then an interlaced PNG file will be written. Supply the rows in the normal image order; the interlacing is carried out internally. .. note ::
[ "Write", "a", "PNG", "image", "to", "the", "output", "file", ".", "rows", "should", "be", "an", "iterable", "that", "yields", "each", "row", "in", "boxed", "row", "flat", "pixel", "format", ".", "The", "rows", "should", "be", "the", "rows", "of", "the", "original", "image", "so", "there", "should", "be", "self", ".", "height", "rows", "of", "self", ".", "width", "*", "self", ".", "planes", "values", ".", "If", "interlace", "is", "specified", "(", "when", "creating", "the", "instance", ")", "then", "an", "interlaced", "PNG", "file", "will", "be", "written", ".", "Supply", "the", "rows", "in", "the", "normal", "image", "order", ";", "the", "interlacing", "is", "carried", "out", "internally", ".", "..", "note", "::" ]
def write(self, outfile, rows): """Write a PNG image to the output file. `rows` should be an iterable that yields each row in boxed row flat pixel format. The rows should be the rows of the original image, so there should be ``self.height`` rows of ``self.width * self.planes`` values. If `interlace` is specified (when creating the instance), then an interlaced PNG file will be written. Supply the rows in the normal image order; the interlacing is carried out internally. .. note :: Interlacing will require the entire image to be in working memory. """ if self.interlace: fmt = 'BH'[self.bitdepth > 8] a = array(fmt, itertools.chain(*rows)) return self.write_array(outfile, a) else: nrows = self.write_passes(outfile, rows) if nrows != self.height: raise ValueError( "rows supplied (%d) does not match height (%d)" % (nrows, self.height))
[ "def", "write", "(", "self", ",", "outfile", ",", "rows", ")", ":", "if", "self", ".", "interlace", ":", "fmt", "=", "'BH'", "[", "self", ".", "bitdepth", ">", "8", "]", "a", "=", "array", "(", "fmt", ",", "itertools", ".", "chain", "(", "*", "rows", ")", ")", "return", "self", ".", "write_array", "(", "outfile", ",", "a", ")", "else", ":", "nrows", "=", "self", ".", "write_passes", "(", "outfile", ",", "rows", ")", "if", "nrows", "!=", "self", ".", "height", ":", "raise", "ValueError", "(", "\"rows supplied (%d) does not match height (%d)\"", "%", "(", "nrows", ",", "self", ".", "height", ")", ")" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/telemetry/third_party/png/png.py#L626-L649
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/build/waf-1.7.13/waflib/Tools/errcheck.py
python
enhance_lib
()
modify existing classes and methods
modify existing classes and methods
[ "modify", "existing", "classes", "and", "methods" ]
def enhance_lib(): """ modify existing classes and methods """ for m in meths_typos: replace(m) # catch '..' in ant_glob patterns def ant_glob(self, *k, **kw): if k: lst=Utils.to_list(k[0]) for pat in lst: if '..' in pat.split('/'): Logs.error("In ant_glob pattern %r: '..' means 'two dots', not 'parent directory'" % k[0]) if kw.get('remove', True): try: if self.is_child_of(self.ctx.bldnode) and not kw.get('quiet', False): Logs.error('Using ant_glob on the build folder (%r) is dangerous (quiet=True to disable this warning)' % self) except AttributeError: pass return self.old_ant_glob(*k, **kw) Node.Node.old_ant_glob = Node.Node.ant_glob Node.Node.ant_glob = ant_glob # catch conflicting ext_in/ext_out/before/after declarations old = Task.is_before def is_before(t1, t2): ret = old(t1, t2) if ret and old(t2, t1): Logs.error('Contradictory order constraints in classes %r %r' % (t1, t2)) return ret Task.is_before = is_before # check for bld(feature='cshlib') where no 'c' is given - this can be either a mistake or on purpose # so we only issue a warning def check_err_features(self): lst = self.to_list(self.features) if 'shlib' in lst: Logs.error('feature shlib -> cshlib, dshlib or cxxshlib') for x in ('c', 'cxx', 'd', 'fc'): if not x in lst and lst and lst[0] in [x+y for y in ('program', 'shlib', 'stlib')]: Logs.error('%r features is probably missing %r' % (self, x)) TaskGen.feature('*')(check_err_features) # check for erroneous order constraints def check_err_order(self): if not hasattr(self, 'rule') and not 'subst' in Utils.to_list(self.features): for x in ('before', 'after', 'ext_in', 'ext_out'): if hasattr(self, x): Logs.warn('Erroneous order constraint %r on non-rule based task generator %r' % (x, self)) else: for x in ('before', 'after'): for y in self.to_list(getattr(self, x, [])): if not Task.classes.get(y, None): Logs.error('Erroneous order constraint %s=%r on %r (no such class)' % (x, y, self)) TaskGen.feature('*')(check_err_order) # check for @extension used with @feature/@before_method/@after_method def check_compile(self): check_invalid_constraints(self) try: ret = self.orig_compile() finally: check_same_targets(self) return ret Build.BuildContext.orig_compile = Build.BuildContext.compile Build.BuildContext.compile = check_compile # check for invalid build groups #914 def use_rec(self, name, **kw): try: y = self.bld.get_tgen_by_name(name) except Errors.WafError: pass else: idx = self.bld.get_group_idx(self) odx = self.bld.get_group_idx(y) if odx > idx: msg = "Invalid 'use' across build groups:" if Logs.verbose > 1: msg += '\n target %r\n uses:\n %r' % (self, y) else: msg += " %r uses %r (try 'waf -v -v' for the full error)" % (self.name, name) raise Errors.WafError(msg) self.orig_use_rec(name, **kw) TaskGen.task_gen.orig_use_rec = TaskGen.task_gen.use_rec TaskGen.task_gen.use_rec = use_rec # check for env.append def getattri(self, name, default=None): if name == 'append' or name == 'add': raise Errors.WafError('env.append and env.add do not exist: use env.append_value/env.append_unique') elif name == 'prepend': raise Errors.WafError('env.prepend does not exist: use env.prepend_value') if name in self.__slots__: return object.__getattr__(self, name, default) else: return self[name] ConfigSet.ConfigSet.__getattr__ = getattri
[ "def", "enhance_lib", "(", ")", ":", "for", "m", "in", "meths_typos", ":", "replace", "(", "m", ")", "# catch '..' in ant_glob patterns", "def", "ant_glob", "(", "self", ",", "*", "k", ",", "*", "*", "kw", ")", ":", "if", "k", ":", "lst", "=", "Utils", ".", "to_list", "(", "k", "[", "0", "]", ")", "for", "pat", "in", "lst", ":", "if", "'..'", "in", "pat", ".", "split", "(", "'/'", ")", ":", "Logs", ".", "error", "(", "\"In ant_glob pattern %r: '..' means 'two dots', not 'parent directory'\"", "%", "k", "[", "0", "]", ")", "if", "kw", ".", "get", "(", "'remove'", ",", "True", ")", ":", "try", ":", "if", "self", ".", "is_child_of", "(", "self", ".", "ctx", ".", "bldnode", ")", "and", "not", "kw", ".", "get", "(", "'quiet'", ",", "False", ")", ":", "Logs", ".", "error", "(", "'Using ant_glob on the build folder (%r) is dangerous (quiet=True to disable this warning)'", "%", "self", ")", "except", "AttributeError", ":", "pass", "return", "self", ".", "old_ant_glob", "(", "*", "k", ",", "*", "*", "kw", ")", "Node", ".", "Node", ".", "old_ant_glob", "=", "Node", ".", "Node", ".", "ant_glob", "Node", ".", "Node", ".", "ant_glob", "=", "ant_glob", "# catch conflicting ext_in/ext_out/before/after declarations", "old", "=", "Task", ".", "is_before", "def", "is_before", "(", "t1", ",", "t2", ")", ":", "ret", "=", "old", "(", "t1", ",", "t2", ")", "if", "ret", "and", "old", "(", "t2", ",", "t1", ")", ":", "Logs", ".", "error", "(", "'Contradictory order constraints in classes %r %r'", "%", "(", "t1", ",", "t2", ")", ")", "return", "ret", "Task", ".", "is_before", "=", "is_before", "# check for bld(feature='cshlib') where no 'c' is given - this can be either a mistake or on purpose", "# so we only issue a warning", "def", "check_err_features", "(", "self", ")", ":", "lst", "=", "self", ".", "to_list", "(", "self", ".", "features", ")", "if", "'shlib'", "in", "lst", ":", "Logs", ".", "error", "(", "'feature shlib -> cshlib, dshlib or cxxshlib'", ")", "for", "x", "in", "(", "'c'", ",", "'cxx'", ",", "'d'", ",", "'fc'", ")", ":", "if", "not", "x", "in", "lst", "and", "lst", "and", "lst", "[", "0", "]", "in", "[", "x", "+", "y", "for", "y", "in", "(", "'program'", ",", "'shlib'", ",", "'stlib'", ")", "]", ":", "Logs", ".", "error", "(", "'%r features is probably missing %r'", "%", "(", "self", ",", "x", ")", ")", "TaskGen", ".", "feature", "(", "'*'", ")", "(", "check_err_features", ")", "# check for erroneous order constraints", "def", "check_err_order", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'rule'", ")", "and", "not", "'subst'", "in", "Utils", ".", "to_list", "(", "self", ".", "features", ")", ":", "for", "x", "in", "(", "'before'", ",", "'after'", ",", "'ext_in'", ",", "'ext_out'", ")", ":", "if", "hasattr", "(", "self", ",", "x", ")", ":", "Logs", ".", "warn", "(", "'Erroneous order constraint %r on non-rule based task generator %r'", "%", "(", "x", ",", "self", ")", ")", "else", ":", "for", "x", "in", "(", "'before'", ",", "'after'", ")", ":", "for", "y", "in", "self", ".", "to_list", "(", "getattr", "(", "self", ",", "x", ",", "[", "]", ")", ")", ":", "if", "not", "Task", ".", "classes", ".", "get", "(", "y", ",", "None", ")", ":", "Logs", ".", "error", "(", "'Erroneous order constraint %s=%r on %r (no such class)'", "%", "(", "x", ",", "y", ",", "self", ")", ")", "TaskGen", ".", "feature", "(", "'*'", ")", "(", "check_err_order", ")", "# check for @extension used with @feature/@before_method/@after_method", "def", "check_compile", "(", "self", ")", ":", "check_invalid_constraints", "(", "self", ")", "try", ":", "ret", "=", "self", ".", "orig_compile", "(", ")", "finally", ":", "check_same_targets", "(", "self", ")", "return", "ret", "Build", ".", "BuildContext", ".", "orig_compile", "=", "Build", ".", "BuildContext", ".", "compile", "Build", ".", "BuildContext", ".", "compile", "=", "check_compile", "# check for invalid build groups #914", "def", "use_rec", "(", "self", ",", "name", ",", "*", "*", "kw", ")", ":", "try", ":", "y", "=", "self", ".", "bld", ".", "get_tgen_by_name", "(", "name", ")", "except", "Errors", ".", "WafError", ":", "pass", "else", ":", "idx", "=", "self", ".", "bld", ".", "get_group_idx", "(", "self", ")", "odx", "=", "self", ".", "bld", ".", "get_group_idx", "(", "y", ")", "if", "odx", ">", "idx", ":", "msg", "=", "\"Invalid 'use' across build groups:\"", "if", "Logs", ".", "verbose", ">", "1", ":", "msg", "+=", "'\\n target %r\\n uses:\\n %r'", "%", "(", "self", ",", "y", ")", "else", ":", "msg", "+=", "\" %r uses %r (try 'waf -v -v' for the full error)\"", "%", "(", "self", ".", "name", ",", "name", ")", "raise", "Errors", ".", "WafError", "(", "msg", ")", "self", ".", "orig_use_rec", "(", "name", ",", "*", "*", "kw", ")", "TaskGen", ".", "task_gen", ".", "orig_use_rec", "=", "TaskGen", ".", "task_gen", ".", "use_rec", "TaskGen", ".", "task_gen", ".", "use_rec", "=", "use_rec", "# check for env.append", "def", "getattri", "(", "self", ",", "name", ",", "default", "=", "None", ")", ":", "if", "name", "==", "'append'", "or", "name", "==", "'add'", ":", "raise", "Errors", ".", "WafError", "(", "'env.append and env.add do not exist: use env.append_value/env.append_unique'", ")", "elif", "name", "==", "'prepend'", ":", "raise", "Errors", ".", "WafError", "(", "'env.prepend does not exist: use env.prepend_value'", ")", "if", "name", "in", "self", ".", "__slots__", ":", "return", "object", ".", "__getattr__", "(", "self", ",", "name", ",", "default", ")", "else", ":", "return", "self", "[", "name", "]", "ConfigSet", ".", "ConfigSet", ".", "__getattr__", "=", "getattri" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/build/waf-1.7.13/waflib/Tools/errcheck.py#L111-L209
daijifeng001/caffe-rfcn
543f8f6a4b7c88256ea1445ae951a12d1ad9cffd
scripts/cpp_lint.py
python
_CppLintState.PrintErrorCounts
(self)
Print a summary of errors by category, and the total.
Print a summary of errors by category, and the total.
[ "Print", "a", "summary", "of", "errors", "by", "category", "and", "the", "total", "." ]
def PrintErrorCounts(self): """Print a summary of errors by category, and the total.""" for category, count in self.errors_by_category.iteritems(): sys.stderr.write('Category \'%s\' errors found: %d\n' % (category, count)) sys.stderr.write('Total errors found: %d\n' % self.error_count)
[ "def", "PrintErrorCounts", "(", "self", ")", ":", "for", "category", ",", "count", "in", "self", ".", "errors_by_category", ".", "iteritems", "(", ")", ":", "sys", ".", "stderr", ".", "write", "(", "'Category \\'%s\\' errors found: %d\\n'", "%", "(", "category", ",", "count", ")", ")", "sys", ".", "stderr", ".", "write", "(", "'Total errors found: %d\\n'", "%", "self", ".", "error_count", ")" ]
https://github.com/daijifeng001/caffe-rfcn/blob/543f8f6a4b7c88256ea1445ae951a12d1ad9cffd/scripts/cpp_lint.py#L757-L762
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/scipy/optimize/optimize.py
python
_minimize_scalar_brent
(func, brack=None, args=(), xtol=1.48e-8, maxiter=500, **unknown_options)
return OptimizeResult(fun=fval, x=x, nit=nit, nfev=nfev, success=nit < maxiter)
Options ------- maxiter : int Maximum number of iterations to perform. xtol : float Relative error in solution `xopt` acceptable for convergence. Notes ----- Uses inverse parabolic interpolation when possible to speed up convergence of golden section method.
Options ------- maxiter : int Maximum number of iterations to perform. xtol : float Relative error in solution `xopt` acceptable for convergence.
[ "Options", "-------", "maxiter", ":", "int", "Maximum", "number", "of", "iterations", "to", "perform", ".", "xtol", ":", "float", "Relative", "error", "in", "solution", "xopt", "acceptable", "for", "convergence", "." ]
def _minimize_scalar_brent(func, brack=None, args=(), xtol=1.48e-8, maxiter=500, **unknown_options): """ Options ------- maxiter : int Maximum number of iterations to perform. xtol : float Relative error in solution `xopt` acceptable for convergence. Notes ----- Uses inverse parabolic interpolation when possible to speed up convergence of golden section method. """ _check_unknown_options(unknown_options) tol = xtol if tol < 0: raise ValueError('tolerance should be >= 0, got %r' % tol) brent = Brent(func=func, args=args, tol=tol, full_output=True, maxiter=maxiter) brent.set_bracket(brack) brent.optimize() x, fval, nit, nfev = brent.get_result(full_output=True) return OptimizeResult(fun=fval, x=x, nit=nit, nfev=nfev, success=nit < maxiter)
[ "def", "_minimize_scalar_brent", "(", "func", ",", "brack", "=", "None", ",", "args", "=", "(", ")", ",", "xtol", "=", "1.48e-8", ",", "maxiter", "=", "500", ",", "*", "*", "unknown_options", ")", ":", "_check_unknown_options", "(", "unknown_options", ")", "tol", "=", "xtol", "if", "tol", "<", "0", ":", "raise", "ValueError", "(", "'tolerance should be >= 0, got %r'", "%", "tol", ")", "brent", "=", "Brent", "(", "func", "=", "func", ",", "args", "=", "args", ",", "tol", "=", "tol", ",", "full_output", "=", "True", ",", "maxiter", "=", "maxiter", ")", "brent", ".", "set_bracket", "(", "brack", ")", "brent", ".", "optimize", "(", ")", "x", ",", "fval", ",", "nit", ",", "nfev", "=", "brent", ".", "get_result", "(", "full_output", "=", "True", ")", "return", "OptimizeResult", "(", "fun", "=", "fval", ",", "x", "=", "x", ",", "nit", "=", "nit", ",", "nfev", "=", "nfev", ",", "success", "=", "nit", "<", "maxiter", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/optimize/optimize.py#L1984-L2012
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/telemetry/third_party/web-page-replay/third_party/dns/resolver.py
python
zone_for_name
(name, rdclass=dns.rdataclass.IN, tcp=False, resolver=None)
Find the name of the zone which contains the specified name. @param name: the query name @type name: absolute dns.name.Name object or string @param rdclass: The query class @type rdclass: int @param tcp: use TCP to make the query (default is False). @type tcp: bool @param resolver: the resolver to use @type resolver: dns.resolver.Resolver object or None @rtype: dns.name.Name
Find the name of the zone which contains the specified name.
[ "Find", "the", "name", "of", "the", "zone", "which", "contains", "the", "specified", "name", "." ]
def zone_for_name(name, rdclass=dns.rdataclass.IN, tcp=False, resolver=None): """Find the name of the zone which contains the specified name. @param name: the query name @type name: absolute dns.name.Name object or string @param rdclass: The query class @type rdclass: int @param tcp: use TCP to make the query (default is False). @type tcp: bool @param resolver: the resolver to use @type resolver: dns.resolver.Resolver object or None @rtype: dns.name.Name""" if isinstance(name, (str, unicode)): name = dns.name.from_text(name, dns.name.root) if resolver is None: resolver = get_default_resolver() if not name.is_absolute(): raise NotAbsolute(name) while 1: try: answer = resolver.query(name, dns.rdatatype.SOA, rdclass, tcp) return name except (dns.resolver.NXDOMAIN, dns.resolver.NoAnswer): try: name = name.parent() except dns.name.NoParent: raise NoRootSOA
[ "def", "zone_for_name", "(", "name", ",", "rdclass", "=", "dns", ".", "rdataclass", ".", "IN", ",", "tcp", "=", "False", ",", "resolver", "=", "None", ")", ":", "if", "isinstance", "(", "name", ",", "(", "str", ",", "unicode", ")", ")", ":", "name", "=", "dns", ".", "name", ".", "from_text", "(", "name", ",", "dns", ".", "name", ".", "root", ")", "if", "resolver", "is", "None", ":", "resolver", "=", "get_default_resolver", "(", ")", "if", "not", "name", ".", "is_absolute", "(", ")", ":", "raise", "NotAbsolute", "(", "name", ")", "while", "1", ":", "try", ":", "answer", "=", "resolver", ".", "query", "(", "name", ",", "dns", ".", "rdatatype", ".", "SOA", ",", "rdclass", ",", "tcp", ")", "return", "name", "except", "(", "dns", ".", "resolver", ".", "NXDOMAIN", ",", "dns", ".", "resolver", ".", "NoAnswer", ")", ":", "try", ":", "name", "=", "name", ".", "parent", "(", ")", "except", "dns", ".", "name", ".", "NoParent", ":", "raise", "NoRootSOA" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/third_party/web-page-replay/third_party/dns/resolver.py#L734-L761
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py2/scipy/sparse/linalg/_expm_multiply.py
python
LazyOperatorNormInfo.alpha
(self, p)
return max(self.d(p), self.d(p+1))
Lazily compute max(d(p), d(p+1)).
Lazily compute max(d(p), d(p+1)).
[ "Lazily", "compute", "max", "(", "d", "(", "p", ")", "d", "(", "p", "+", "1", "))", "." ]
def alpha(self, p): """ Lazily compute max(d(p), d(p+1)). """ return max(self.d(p), self.d(p+1))
[ "def", "alpha", "(", "self", ",", "p", ")", ":", "return", "max", "(", "self", ".", "d", "(", "p", ")", ",", "self", ".", "d", "(", "p", "+", "1", ")", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/sparse/linalg/_expm_multiply.py#L361-L365
MythTV/mythtv
d282a209cb8be85d036f85a62a8ec971b67d45f4
mythtv/bindings/python/MythTV/methodheap.py
python
MythDB.searchRecord
(self, init=False, key=None, value=None)
return None
obj.searchRecord(**kwargs) -> list of Record objects Supports the following keywords: type, chanid, starttime, startdate, endtime enddate, title, subtitle, category, profile recgroup, station, seriesid, programid, playgroup, inetref
obj.searchRecord(**kwargs) -> list of Record objects
[ "obj", ".", "searchRecord", "(", "**", "kwargs", ")", "-", ">", "list", "of", "Record", "objects" ]
def searchRecord(self, init=False, key=None, value=None): """ obj.searchRecord(**kwargs) -> list of Record objects Supports the following keywords: type, chanid, starttime, startdate, endtime enddate, title, subtitle, category, profile recgroup, station, seriesid, programid, playgroup, inetref """ if init: init.table = 'record' init.handler = Record return None if key in ('type','chanid','starttime','startdate','endtime','enddate', 'title','subtitle','category','profile','recgroup', 'station','seriesid','programid','playgroup','inetref'): return ('%s=?' % key, value, 0) return None
[ "def", "searchRecord", "(", "self", ",", "init", "=", "False", ",", "key", "=", "None", ",", "value", "=", "None", ")", ":", "if", "init", ":", "init", ".", "table", "=", "'record'", "init", ".", "handler", "=", "Record", "return", "None", "if", "key", "in", "(", "'type'", ",", "'chanid'", ",", "'starttime'", ",", "'startdate'", ",", "'endtime'", ",", "'enddate'", ",", "'title'", ",", "'subtitle'", ",", "'category'", ",", "'profile'", ",", "'recgroup'", ",", "'station'", ",", "'seriesid'", ",", "'programid'", ",", "'playgroup'", ",", "'inetref'", ")", ":", "return", "(", "'%s=?'", "%", "key", ",", "value", ",", "0", ")", "return", "None" ]
https://github.com/MythTV/mythtv/blob/d282a209cb8be85d036f85a62a8ec971b67d45f4/mythtv/bindings/python/MythTV/methodheap.py#L940-L959
include-what-you-use/include-what-you-use
208fbfffa5d69364b9f78e427caa443441279283
fix_includes.py
python
_LinesAreAllBlank
(file_lines, start_line, end_line)
return True
Returns true iff all lines in [start_line, end_line) are blank/deleted.
Returns true iff all lines in [start_line, end_line) are blank/deleted.
[ "Returns", "true", "iff", "all", "lines", "in", "[", "start_line", "end_line", ")", "are", "blank", "/", "deleted", "." ]
def _LinesAreAllBlank(file_lines, start_line, end_line): """Returns true iff all lines in [start_line, end_line) are blank/deleted.""" for line_number in range(start_line, end_line): if (not file_lines[line_number].deleted and file_lines[line_number].type != _BLANK_LINE_RE): return False return True
[ "def", "_LinesAreAllBlank", "(", "file_lines", ",", "start_line", ",", "end_line", ")", ":", "for", "line_number", "in", "range", "(", "start_line", ",", "end_line", ")", ":", "if", "(", "not", "file_lines", "[", "line_number", "]", ".", "deleted", "and", "file_lines", "[", "line_number", "]", ".", "type", "!=", "_BLANK_LINE_RE", ")", ":", "return", "False", "return", "True" ]
https://github.com/include-what-you-use/include-what-you-use/blob/208fbfffa5d69364b9f78e427caa443441279283/fix_includes.py#L901-L907
facebookincubator/BOLT
88c70afe9d388ad430cc150cc158641701397f70
libcxx/utils/libcxx/sym_check/extract.py
python
NMExtractor.__init__
(self, static_lib)
Initialize the nm executable and flags that will be used to extract symbols from shared libraries.
Initialize the nm executable and flags that will be used to extract symbols from shared libraries.
[ "Initialize", "the", "nm", "executable", "and", "flags", "that", "will", "be", "used", "to", "extract", "symbols", "from", "shared", "libraries", "." ]
def __init__(self, static_lib): """ Initialize the nm executable and flags that will be used to extract symbols from shared libraries. """ self.nm_exe = self.find_tool() if self.nm_exe is None: # ERROR no NM found print("ERROR: Could not find nm") sys.exit(1) self.static_lib = static_lib self.flags = ['-P', '-g']
[ "def", "__init__", "(", "self", ",", "static_lib", ")", ":", "self", ".", "nm_exe", "=", "self", ".", "find_tool", "(", ")", "if", "self", ".", "nm_exe", "is", "None", ":", "# ERROR no NM found", "print", "(", "\"ERROR: Could not find nm\"", ")", "sys", ".", "exit", "(", "1", ")", "self", ".", "static_lib", "=", "static_lib", "self", ".", "flags", "=", "[", "'-P'", ",", "'-g'", "]" ]
https://github.com/facebookincubator/BOLT/blob/88c70afe9d388ad430cc150cc158641701397f70/libcxx/utils/libcxx/sym_check/extract.py#L34-L45
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/httplib.py
python
HTTP.getreply
(self, buffering=False)
return response.status, response.reason, response.msg
Compat definition since superclass does not define it. Returns a tuple consisting of: - server status code (e.g. '200' if all goes well) - server "reason" corresponding to status code - any RFC822 headers in the response from the server
Compat definition since superclass does not define it.
[ "Compat", "definition", "since", "superclass", "does", "not", "define", "it", "." ]
def getreply(self, buffering=False): """Compat definition since superclass does not define it. Returns a tuple consisting of: - server status code (e.g. '200' if all goes well) - server "reason" corresponding to status code - any RFC822 headers in the response from the server """ try: if not buffering: response = self._conn.getresponse() else: #only add this keyword if non-default for compatibility #with other connection classes response = self._conn.getresponse(buffering) except BadStatusLine, e: ### hmm. if getresponse() ever closes the socket on a bad request, ### then we are going to have problems with self.sock ### should we keep this behavior? do people use it? # keep the socket open (as a file), and return it self.file = self._conn.sock.makefile('rb', 0) # close our socket -- we want to restart after any protocol error self.close() self.headers = None return -1, e.line, None self.headers = response.msg self.file = response.fp return response.status, response.reason, response.msg
[ "def", "getreply", "(", "self", ",", "buffering", "=", "False", ")", ":", "try", ":", "if", "not", "buffering", ":", "response", "=", "self", ".", "_conn", ".", "getresponse", "(", ")", "else", ":", "#only add this keyword if non-default for compatibility", "#with other connection classes", "response", "=", "self", ".", "_conn", ".", "getresponse", "(", "buffering", ")", "except", "BadStatusLine", ",", "e", ":", "### hmm. if getresponse() ever closes the socket on a bad request,", "### then we are going to have problems with self.sock", "### should we keep this behavior? do people use it?", "# keep the socket open (as a file), and return it", "self", ".", "file", "=", "self", ".", "_conn", ".", "sock", ".", "makefile", "(", "'rb'", ",", "0", ")", "# close our socket -- we want to restart after any protocol error", "self", ".", "close", "(", ")", "self", ".", "headers", "=", "None", "return", "-", "1", ",", "e", ".", "line", ",", "None", "self", ".", "headers", "=", "response", ".", "msg", "self", ".", "file", "=", "response", ".", "fp", "return", "response", ".", "status", ",", "response", ".", "reason", ",", "response", ".", "msg" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/httplib.py#L1107-L1138
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib2to3/fixer_util.py
python
touch_import
(package, name, node)
Works like `does_tree_import` but adds an import statement if it was not imported.
Works like `does_tree_import` but adds an import statement if it was not imported.
[ "Works", "like", "does_tree_import", "but", "adds", "an", "import", "statement", "if", "it", "was", "not", "imported", "." ]
def touch_import(package, name, node): """ Works like `does_tree_import` but adds an import statement if it was not imported. """ def is_import_stmt(node): return (node.type == syms.simple_stmt and node.children and is_import(node.children[0])) root = find_root(node) if does_tree_import(package, name, root): return # figure out where to insert the new import. First try to find # the first import and then skip to the last one. insert_pos = offset = 0 for idx, node in enumerate(root.children): if not is_import_stmt(node): continue for offset, node2 in enumerate(root.children[idx:]): if not is_import_stmt(node2): break insert_pos = idx + offset break # if there are no imports where we can insert, find the docstring. # if that also fails, we stick to the beginning of the file if insert_pos == 0: for idx, node in enumerate(root.children): if (node.type == syms.simple_stmt and node.children and node.children[0].type == token.STRING): insert_pos = idx + 1 break if package is None: import_ = Node(syms.import_name, [ Leaf(token.NAME, u"import"), Leaf(token.NAME, name, prefix=u" ") ]) else: import_ = FromImport(package, [Leaf(token.NAME, name, prefix=u" ")]) children = [import_, Newline()] root.insert_child(insert_pos, Node(syms.simple_stmt, children))
[ "def", "touch_import", "(", "package", ",", "name", ",", "node", ")", ":", "def", "is_import_stmt", "(", "node", ")", ":", "return", "(", "node", ".", "type", "==", "syms", ".", "simple_stmt", "and", "node", ".", "children", "and", "is_import", "(", "node", ".", "children", "[", "0", "]", ")", ")", "root", "=", "find_root", "(", "node", ")", "if", "does_tree_import", "(", "package", ",", "name", ",", "root", ")", ":", "return", "# figure out where to insert the new import. First try to find", "# the first import and then skip to the last one.", "insert_pos", "=", "offset", "=", "0", "for", "idx", ",", "node", "in", "enumerate", "(", "root", ".", "children", ")", ":", "if", "not", "is_import_stmt", "(", "node", ")", ":", "continue", "for", "offset", ",", "node2", "in", "enumerate", "(", "root", ".", "children", "[", "idx", ":", "]", ")", ":", "if", "not", "is_import_stmt", "(", "node2", ")", ":", "break", "insert_pos", "=", "idx", "+", "offset", "break", "# if there are no imports where we can insert, find the docstring.", "# if that also fails, we stick to the beginning of the file", "if", "insert_pos", "==", "0", ":", "for", "idx", ",", "node", "in", "enumerate", "(", "root", ".", "children", ")", ":", "if", "(", "node", ".", "type", "==", "syms", ".", "simple_stmt", "and", "node", ".", "children", "and", "node", ".", "children", "[", "0", "]", ".", "type", "==", "token", ".", "STRING", ")", ":", "insert_pos", "=", "idx", "+", "1", "break", "if", "package", "is", "None", ":", "import_", "=", "Node", "(", "syms", ".", "import_name", ",", "[", "Leaf", "(", "token", ".", "NAME", ",", "u\"import\"", ")", ",", "Leaf", "(", "token", ".", "NAME", ",", "name", ",", "prefix", "=", "u\" \"", ")", "]", ")", "else", ":", "import_", "=", "FromImport", "(", "package", ",", "[", "Leaf", "(", "token", ".", "NAME", ",", "name", ",", "prefix", "=", "u\" \"", ")", "]", ")", "children", "=", "[", "import_", ",", "Newline", "(", ")", "]", "root", ".", "insert_child", "(", "insert_pos", ",", "Node", "(", "syms", ".", "simple_stmt", ",", "children", ")", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib2to3/fixer_util.py#L294-L336
thalium/icebox
99d147d5b9269222225443ce171b4fd46d8985d4
third_party/virtualbox/src/VBox/Devices/EFI/Firmware/AppPkg/Applications/Python/PyMod-2.7.2/Lib/pydoc.py
python
writedocs
(dir, pkgpath='', done=None)
return
Write out HTML documentation for all modules in a directory tree.
Write out HTML documentation for all modules in a directory tree.
[ "Write", "out", "HTML", "documentation", "for", "all", "modules", "in", "a", "directory", "tree", "." ]
def writedocs(dir, pkgpath='', done=None): """Write out HTML documentation for all modules in a directory tree.""" if done is None: done = {} for importer, modname, ispkg in pkgutil.walk_packages([dir], pkgpath): writedoc(modname) return
[ "def", "writedocs", "(", "dir", ",", "pkgpath", "=", "''", ",", "done", "=", "None", ")", ":", "if", "done", "is", "None", ":", "done", "=", "{", "}", "for", "importer", ",", "modname", ",", "ispkg", "in", "pkgutil", ".", "walk_packages", "(", "[", "dir", "]", ",", "pkgpath", ")", ":", "writedoc", "(", "modname", ")", "return" ]
https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/VBox/Devices/EFI/Firmware/AppPkg/Applications/Python/PyMod-2.7.2/Lib/pydoc.py#L1531-L1536
larroy/clearskies_core
3574ddf0edc8555454c7044126e786a6c29444dc
tools/gyp/pylib/gyp/generator/ninja.py
python
CalculateGeneratorInputInfo
(params)
Called by __init__ to initialize generator values based on params.
Called by __init__ to initialize generator values based on params.
[ "Called", "by", "__init__", "to", "initialize", "generator", "values", "based", "on", "params", "." ]
def CalculateGeneratorInputInfo(params): """Called by __init__ to initialize generator values based on params.""" # E.g. "out/gypfiles" toplevel = params['options'].toplevel_dir qualified_out_dir = os.path.normpath(os.path.join( toplevel, ComputeOutputDir(params), 'gypfiles')) global generator_filelist_paths generator_filelist_paths = { 'toplevel': toplevel, 'qualified_out_dir': qualified_out_dir, }
[ "def", "CalculateGeneratorInputInfo", "(", "params", ")", ":", "# E.g. \"out/gypfiles\"", "toplevel", "=", "params", "[", "'options'", "]", ".", "toplevel_dir", "qualified_out_dir", "=", "os", ".", "path", ".", "normpath", "(", "os", ".", "path", ".", "join", "(", "toplevel", ",", "ComputeOutputDir", "(", "params", ")", ",", "'gypfiles'", ")", ")", "global", "generator_filelist_paths", "generator_filelist_paths", "=", "{", "'toplevel'", ":", "toplevel", ",", "'qualified_out_dir'", ":", "qualified_out_dir", ",", "}" ]
https://github.com/larroy/clearskies_core/blob/3574ddf0edc8555454c7044126e786a6c29444dc/tools/gyp/pylib/gyp/generator/ninja.py#L1512-L1523
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/closure_compiler/compile2.py
python
Checker._create_temp_file
(self, contents)
return tmp_file.name
Creates an owned temporary file with |contents|. Args: content: A string of the file contens to write to a temporary file. Return: The filepath of the newly created, written, and closed temporary file.
Creates an owned temporary file with |contents|.
[ "Creates", "an", "owned", "temporary", "file", "with", "|contents|", "." ]
def _create_temp_file(self, contents): """Creates an owned temporary file with |contents|. Args: content: A string of the file contens to write to a temporary file. Return: The filepath of the newly created, written, and closed temporary file. """ with tempfile.NamedTemporaryFile(mode="wt", delete=False) as tmp_file: self._temp_files.append(tmp_file.name) tmp_file.write(contents) return tmp_file.name
[ "def", "_create_temp_file", "(", "self", ",", "contents", ")", ":", "with", "tempfile", ".", "NamedTemporaryFile", "(", "mode", "=", "\"wt\"", ",", "delete", "=", "False", ")", "as", "tmp_file", ":", "self", ".", "_temp_files", ".", "append", "(", "tmp_file", ".", "name", ")", "tmp_file", ".", "write", "(", "contents", ")", "return", "tmp_file", ".", "name" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/closure_compiler/compile2.py#L178-L190
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/ElementalAnalysis/PeriodicTable/periodic_table.py
python
PeriodicTable.setSelection
(self, symbols)
Set selected elements. This causes the sigSelectionChanged signal to be emitted, even if the selection didn't actually change. :param List[str] symbols: List of symbols of elements to be selected (e.g. *["Fe", "Hg", "Li"]*)
Set selected elements.
[ "Set", "selected", "elements", "." ]
def setSelection(self, symbols): """Set selected elements. This causes the sigSelectionChanged signal to be emitted, even if the selection didn't actually change. :param List[str] symbols: List of symbols of elements to be selected (e.g. *["Fe", "Hg", "Li"]*) """ # accept list of PeriodicTableItems as input, because getSelection # returns these objects and it makes sense to have getter and setter # use same type of data if isinstance(symbols[0], PeriodicTableItem): symbols = [elmt.symbol for elmt in symbols] for (e, b) in self._eltButtons.items(): b.setSelected(e in symbols) self.sigSelectionChanged.emit(self.getSelection())
[ "def", "setSelection", "(", "self", ",", "symbols", ")", ":", "# accept list of PeriodicTableItems as input, because getSelection", "# returns these objects and it makes sense to have getter and setter", "# use same type of data", "if", "isinstance", "(", "symbols", "[", "0", "]", ",", "PeriodicTableItem", ")", ":", "symbols", "=", "[", "elmt", ".", "symbol", "for", "elmt", "in", "symbols", "]", "for", "(", "e", ",", "b", ")", "in", "self", ".", "_eltButtons", ".", "items", "(", ")", ":", "b", ".", "setSelected", "(", "e", "in", "symbols", ")", "self", ".", "sigSelectionChanged", ".", "emit", "(", "self", ".", "getSelection", "(", ")", ")" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/ElementalAnalysis/PeriodicTable/periodic_table.py#L592-L609
freesurfer/freesurfer
6dbe527d43ffa611acb2cd112e9469f9bfec8e36
python/freesurfer/subfields/hippocampus.py
python
HippoAmygdalaSubfields.get_label_groups
(self)
return labelGroups
Return a group (list of lists) of label names that determine the class reductions for the primary image-fitting stage.
Return a group (list of lists) of label names that determine the class reductions for the primary image-fitting stage.
[ "Return", "a", "group", "(", "list", "of", "lists", ")", "of", "label", "names", "that", "determine", "the", "class", "reductions", "for", "the", "primary", "image", "-", "fitting", "stage", "." ]
def get_label_groups(self): """ Return a group (list of lists) of label names that determine the class reductions for the primary image-fitting stage. """ if not self.highResImage: labelGroups = [ ['Left-Cerebral-Cortex', 'Left-Hippocampus', 'Left-Amygdala', 'subiculum-head', 'subiculum-body', 'Hippocampal_tail', 'GC-ML-DG-head', 'GC-ML-DG-body', 'CA4-head', 'CA4-body', 'presubiculum-head', 'presubiculum-body', 'CA1-head', 'CA1-body', 'parasubiculum', 'CA3-head', 'CA3-body', 'HATA', 'Lateral-nucleus', 'Paralaminar-nucleus', 'Basal-nucleus', 'Hippocampal-amygdala-transition-HATA', 'Accessory-Basal-nucleus', 'Amygdala-background', 'Corticoamygdaloid-transitio', 'Central-nucleus', 'Cortical-nucleus', 'Medial-nucleus', 'Anterior-amygdaloid-area-AAA', 'molecular_layer_HP-body', 'molecular_layer_HP-head']] else: labelGroups = [ ['Left-Cerebral-Cortex', 'Left-Hippocampus', 'Left-Amygdala', 'subiculum-head', 'subiculum-body', 'Hippocampal_tail', 'GC-ML-DG-head', 'GC-ML-DG-body', 'CA4-head', 'CA4-body', 'presubiculum-head', 'presubiculum-body', 'CA1-head', 'CA1-body', 'parasubiculum', 'CA3-head', 'CA3-body', 'HATA', 'Lateral-nucleus', 'Paralaminar-nucleus', 'Basal-nucleus', 'Hippocampal-amygdala-transition-HATA', 'Accessory-Basal-nucleus', 'Amygdala-background', 'Corticoamygdaloid-transitio', 'Central-nucleus', 'Cortical-nucleus', 'Medial-nucleus', 'Anterior-amygdaloid-area-AAA'], ['molecular_layer_HP-body', 'molecular_layer_HP-head']] labelGroups.append(['Left-Cerebral-White-Matter', 'fimbria']) labelGroups.append(['alveus']) labelGroups.append(['Left-Lateral-Ventricle', 'Background-CSF', 'SUSPICIOUS', 'Left-hippocampus-intensity-abnormality']) labelGroups.append(['hippocampal-fissure']) labelGroups.append(['Left-Pallidum']) labelGroups.append(['Left-Putamen']) labelGroups.append(['Left-Caudate']) labelGroups.append(['Left-Thalamus-Proper']) labelGroups.append(['Left-choroid-plexus']) labelGroups.append(['Left-VentralDC']) labelGroups.append(['Left-Accumbens-area']) labelGroups.append(['Unknown', 'Background-tissue']) return labelGroups
[ "def", "get_label_groups", "(", "self", ")", ":", "if", "not", "self", ".", "highResImage", ":", "labelGroups", "=", "[", "[", "'Left-Cerebral-Cortex'", ",", "'Left-Hippocampus'", ",", "'Left-Amygdala'", ",", "'subiculum-head'", ",", "'subiculum-body'", ",", "'Hippocampal_tail'", ",", "'GC-ML-DG-head'", ",", "'GC-ML-DG-body'", ",", "'CA4-head'", ",", "'CA4-body'", ",", "'presubiculum-head'", ",", "'presubiculum-body'", ",", "'CA1-head'", ",", "'CA1-body'", ",", "'parasubiculum'", ",", "'CA3-head'", ",", "'CA3-body'", ",", "'HATA'", ",", "'Lateral-nucleus'", ",", "'Paralaminar-nucleus'", ",", "'Basal-nucleus'", ",", "'Hippocampal-amygdala-transition-HATA'", ",", "'Accessory-Basal-nucleus'", ",", "'Amygdala-background'", ",", "'Corticoamygdaloid-transitio'", ",", "'Central-nucleus'", ",", "'Cortical-nucleus'", ",", "'Medial-nucleus'", ",", "'Anterior-amygdaloid-area-AAA'", ",", "'molecular_layer_HP-body'", ",", "'molecular_layer_HP-head'", "]", "]", "else", ":", "labelGroups", "=", "[", "[", "'Left-Cerebral-Cortex'", ",", "'Left-Hippocampus'", ",", "'Left-Amygdala'", ",", "'subiculum-head'", ",", "'subiculum-body'", ",", "'Hippocampal_tail'", ",", "'GC-ML-DG-head'", ",", "'GC-ML-DG-body'", ",", "'CA4-head'", ",", "'CA4-body'", ",", "'presubiculum-head'", ",", "'presubiculum-body'", ",", "'CA1-head'", ",", "'CA1-body'", ",", "'parasubiculum'", ",", "'CA3-head'", ",", "'CA3-body'", ",", "'HATA'", ",", "'Lateral-nucleus'", ",", "'Paralaminar-nucleus'", ",", "'Basal-nucleus'", ",", "'Hippocampal-amygdala-transition-HATA'", ",", "'Accessory-Basal-nucleus'", ",", "'Amygdala-background'", ",", "'Corticoamygdaloid-transitio'", ",", "'Central-nucleus'", ",", "'Cortical-nucleus'", ",", "'Medial-nucleus'", ",", "'Anterior-amygdaloid-area-AAA'", "]", ",", "[", "'molecular_layer_HP-body'", ",", "'molecular_layer_HP-head'", "]", "]", "labelGroups", ".", "append", "(", "[", "'Left-Cerebral-White-Matter'", ",", "'fimbria'", "]", ")", "labelGroups", ".", "append", "(", "[", "'alveus'", "]", ")", "labelGroups", ".", "append", "(", "[", "'Left-Lateral-Ventricle'", ",", "'Background-CSF'", ",", "'SUSPICIOUS'", ",", "'Left-hippocampus-intensity-abnormality'", "]", ")", "labelGroups", ".", "append", "(", "[", "'hippocampal-fissure'", "]", ")", "labelGroups", ".", "append", "(", "[", "'Left-Pallidum'", "]", ")", "labelGroups", ".", "append", "(", "[", "'Left-Putamen'", "]", ")", "labelGroups", ".", "append", "(", "[", "'Left-Caudate'", "]", ")", "labelGroups", ".", "append", "(", "[", "'Left-Thalamus-Proper'", "]", ")", "labelGroups", ".", "append", "(", "[", "'Left-choroid-plexus'", "]", ")", "labelGroups", ".", "append", "(", "[", "'Left-VentralDC'", "]", ")", "labelGroups", ".", "append", "(", "[", "'Left-Accumbens-area'", "]", ")", "labelGroups", ".", "append", "(", "[", "'Unknown'", ",", "'Background-tissue'", "]", ")", "return", "labelGroups" ]
https://github.com/freesurfer/freesurfer/blob/6dbe527d43ffa611acb2cd112e9469f9bfec8e36/python/freesurfer/subfields/hippocampus.py#L330-L365
giuspen/cherrytree
84712f206478fcf9acf30174009ad28c648c6344
pygtk2/modules/core.py
python
CherryTree.find_in_selected_node
(self, *args)
Search for a pattern in the selected Node
Search for a pattern in the selected Node
[ "Search", "for", "a", "pattern", "in", "the", "selected", "Node" ]
def find_in_selected_node(self, *args): """Search for a pattern in the selected Node""" if not self.is_there_selected_node_or_error(): return self.find_handler.find_in_selected_node()
[ "def", "find_in_selected_node", "(", "self", ",", "*", "args", ")", ":", "if", "not", "self", ".", "is_there_selected_node_or_error", "(", ")", ":", "return", "self", ".", "find_handler", ".", "find_in_selected_node", "(", ")" ]
https://github.com/giuspen/cherrytree/blob/84712f206478fcf9acf30174009ad28c648c6344/pygtk2/modules/core.py#L3357-L3360
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/ragged/ragged_map_ops.py
python
_convert_declared_ragged
(current, declared)
Converts an output with RaggedTensorType into a _RaggedTensorComponents.
Converts an output with RaggedTensorType into a _RaggedTensorComponents.
[ "Converts", "an", "output", "with", "RaggedTensorType", "into", "a", "_RaggedTensorComponents", "." ]
def _convert_declared_ragged(current, declared): """Converts an output with RaggedTensorType into a _RaggedTensorComponents.""" # Check that the ragged ranks match up. # + 1 to account for the rank of the outermost dimension. current_ragged_rank = getattr(current, "ragged_rank", 0) if declared.ragged_rank != current_ragged_rank + 1: raise ValueError( "The declared ragged rank (%d) mismatches the result (%d)" % (declared.ragged_rank, current_ragged_rank + 1)) # Check that dtypes match up. if declared.dtype != current.dtype: raise ValueError( "The declared dtype (%s) mismatches the result (%s)" % (declared.dtype, current.dtype)) if (isinstance(current, ragged_tensor.RaggedTensor) and declared.row_splits_dtype != current.row_splits.dtype): if not ragged_config.auto_cast_partition_dtype(): raise ValueError( "The declared row_splits dtype (%s) mismatches the result (%s)." " Use RaggedTensor.with_row_splits_dtype to convert it." % (declared.row_splits_dtype, current.row_splits.dtype)) current = current.with_row_splits_dtype(declared.row_splits_dtype) if isinstance(current, ragged_tensor.RaggedTensor): return current else: nrows = array_ops.shape(current, out_type=declared.row_splits_dtype)[0] row_length = array_ops.expand_dims(nrows, axis=0) return _RaggedTensorComponents( flat_values=current, nested_row_lengths=(), outer_row_length=row_length)
[ "def", "_convert_declared_ragged", "(", "current", ",", "declared", ")", ":", "# Check that the ragged ranks match up.", "# + 1 to account for the rank of the outermost dimension.", "current_ragged_rank", "=", "getattr", "(", "current", ",", "\"ragged_rank\"", ",", "0", ")", "if", "declared", ".", "ragged_rank", "!=", "current_ragged_rank", "+", "1", ":", "raise", "ValueError", "(", "\"The declared ragged rank (%d) mismatches the result (%d)\"", "%", "(", "declared", ".", "ragged_rank", ",", "current_ragged_rank", "+", "1", ")", ")", "# Check that dtypes match up.", "if", "declared", ".", "dtype", "!=", "current", ".", "dtype", ":", "raise", "ValueError", "(", "\"The declared dtype (%s) mismatches the result (%s)\"", "%", "(", "declared", ".", "dtype", ",", "current", ".", "dtype", ")", ")", "if", "(", "isinstance", "(", "current", ",", "ragged_tensor", ".", "RaggedTensor", ")", "and", "declared", ".", "row_splits_dtype", "!=", "current", ".", "row_splits", ".", "dtype", ")", ":", "if", "not", "ragged_config", ".", "auto_cast_partition_dtype", "(", ")", ":", "raise", "ValueError", "(", "\"The declared row_splits dtype (%s) mismatches the result (%s).\"", "\" Use RaggedTensor.with_row_splits_dtype to convert it.\"", "%", "(", "declared", ".", "row_splits_dtype", ",", "current", ".", "row_splits", ".", "dtype", ")", ")", "current", "=", "current", ".", "with_row_splits_dtype", "(", "declared", ".", "row_splits_dtype", ")", "if", "isinstance", "(", "current", ",", "ragged_tensor", ".", "RaggedTensor", ")", ":", "return", "current", "else", ":", "nrows", "=", "array_ops", ".", "shape", "(", "current", ",", "out_type", "=", "declared", ".", "row_splits_dtype", ")", "[", "0", "]", "row_length", "=", "array_ops", ".", "expand_dims", "(", "nrows", ",", "axis", "=", "0", ")", "return", "_RaggedTensorComponents", "(", "flat_values", "=", "current", ",", "nested_row_lengths", "=", "(", ")", ",", "outer_row_length", "=", "row_length", ")" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/ragged/ragged_map_ops.py#L430-L462
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Code/Tools/waf-1.7.13/waflib/Node.py
python
Node.find_resource
(self, lst)
return node
Try to find a declared build node or a source file :param lst: path :type lst: string or list of string
Try to find a declared build node or a source file
[ "Try", "to", "find", "a", "declared", "build", "node", "or", "a", "source", "file" ]
def find_resource(self, lst): """ Try to find a declared build node or a source file :param lst: path :type lst: string or list of string """ if isinstance(lst, str): lst = [x for x in split_path(lst) if x and x != '.'] node = self.get_bld().search_node(lst) if not node: self = self.get_src() node = self.find_node(lst) if node: if os.path.isdir(node.abspath()): return None return node
[ "def", "find_resource", "(", "self", ",", "lst", ")", ":", "if", "isinstance", "(", "lst", ",", "str", ")", ":", "lst", "=", "[", "x", "for", "x", "in", "split_path", "(", "lst", ")", "if", "x", "and", "x", "!=", "'.'", "]", "node", "=", "self", ".", "get_bld", "(", ")", ".", "search_node", "(", "lst", ")", "if", "not", "node", ":", "self", "=", "self", ".", "get_src", "(", ")", "node", "=", "self", ".", "find_node", "(", "lst", ")", "if", "node", ":", "if", "os", ".", "path", ".", "isdir", "(", "node", ".", "abspath", "(", ")", ")", ":", "return", "None", "return", "node" ]
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Code/Tools/waf-1.7.13/waflib/Node.py#L673-L690
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/ed_stc.py
python
EditraStc.SetCurrentCol
(self, column)
Set the current column position on the currently line extending the selection. @param column: Column to move to
Set the current column position on the currently line extending the selection. @param column: Column to move to
[ "Set", "the", "current", "column", "position", "on", "the", "currently", "line", "extending", "the", "selection", ".", "@param", "column", ":", "Column", "to", "move", "to" ]
def SetCurrentCol(self, column): """Set the current column position on the currently line extending the selection. @param column: Column to move to """ cline = self.GetCurrentLineNum() lstart = self.PositionFromLine(cline) lend = self.GetLineEndPosition(cline) linelen = lend - lstart if column > linelen: column = linelen self.SetCurrentPos(lstart + column)
[ "def", "SetCurrentCol", "(", "self", ",", "column", ")", ":", "cline", "=", "self", ".", "GetCurrentLineNum", "(", ")", "lstart", "=", "self", ".", "PositionFromLine", "(", "cline", ")", "lend", "=", "self", ".", "GetLineEndPosition", "(", "cline", ")", "linelen", "=", "lend", "-", "lstart", "if", "column", ">", "linelen", ":", "column", "=", "linelen", "self", ".", "SetCurrentPos", "(", "lstart", "+", "column", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/ed_stc.py#L581-L593
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/xrc.py
python
XmlResource.LoadOnDialog
(*args, **kwargs)
return _xrc.XmlResource_LoadOnDialog(*args, **kwargs)
LoadOnDialog(self, wxDialog dlg, Window parent, String name) -> bool
LoadOnDialog(self, wxDialog dlg, Window parent, String name) -> bool
[ "LoadOnDialog", "(", "self", "wxDialog", "dlg", "Window", "parent", "String", "name", ")", "-", ">", "bool" ]
def LoadOnDialog(*args, **kwargs): """LoadOnDialog(self, wxDialog dlg, Window parent, String name) -> bool""" return _xrc.XmlResource_LoadOnDialog(*args, **kwargs)
[ "def", "LoadOnDialog", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_xrc", ".", "XmlResource_LoadOnDialog", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/xrc.py#L139-L141
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/setuptools/command/easy_install.py
python
WindowsScriptWriter._get_script_args
(cls, type_, name, header, script_text)
For Windows, add a .py extension
For Windows, add a .py extension
[ "For", "Windows", "add", "a", ".", "py", "extension" ]
def _get_script_args(cls, type_, name, header, script_text): "For Windows, add a .py extension" ext = dict(console='.pya', gui='.pyw')[type_] if ext not in os.environ['PATHEXT'].lower().split(';'): msg = ( "{ext} not listed in PATHEXT; scripts will not be " "recognized as executables." ).format(**locals()) warnings.warn(msg, UserWarning) old = ['.pya', '.py', '-script.py', '.pyc', '.pyo', '.pyw', '.exe'] old.remove(ext) header = cls._adjust_header(type_, header) blockers = [name + x for x in old] yield name + ext, header + script_text, 't', blockers
[ "def", "_get_script_args", "(", "cls", ",", "type_", ",", "name", ",", "header", ",", "script_text", ")", ":", "ext", "=", "dict", "(", "console", "=", "'.pya'", ",", "gui", "=", "'.pyw'", ")", "[", "type_", "]", "if", "ext", "not", "in", "os", ".", "environ", "[", "'PATHEXT'", "]", ".", "lower", "(", ")", ".", "split", "(", "';'", ")", ":", "msg", "=", "(", "\"{ext} not listed in PATHEXT; scripts will not be \"", "\"recognized as executables.\"", ")", ".", "format", "(", "*", "*", "locals", "(", ")", ")", "warnings", ".", "warn", "(", "msg", ",", "UserWarning", ")", "old", "=", "[", "'.pya'", ",", "'.py'", ",", "'-script.py'", ",", "'.pyc'", ",", "'.pyo'", ",", "'.pyw'", ",", "'.exe'", "]", "old", ".", "remove", "(", "ext", ")", "header", "=", "cls", ".", "_adjust_header", "(", "type_", ",", "header", ")", "blockers", "=", "[", "name", "+", "x", "for", "x", "in", "old", "]", "yield", "name", "+", "ext", ",", "header", "+", "script_text", ",", "'t'", ",", "blockers" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/setuptools/command/easy_install.py#L2185-L2198
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py2/sklearn/metrics/scorer.py
python
_passthrough_scorer
(estimator, *args, **kwargs)
return estimator.score(*args, **kwargs)
Function that wraps estimator.score
Function that wraps estimator.score
[ "Function", "that", "wraps", "estimator", ".", "score" ]
def _passthrough_scorer(estimator, *args, **kwargs): """Function that wraps estimator.score""" return estimator.score(*args, **kwargs)
[ "def", "_passthrough_scorer", "(", "estimator", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "estimator", ".", "score", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/metrics/scorer.py#L217-L219
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/ma/core.py
python
_convert2ma.getdoc
(self)
return doc
Return the doc of the function (from the doc of the method).
Return the doc of the function (from the doc of the method).
[ "Return", "the", "doc", "of", "the", "function", "(", "from", "the", "doc", "of", "the", "method", ")", "." ]
def getdoc(self): "Return the doc of the function (from the doc of the method)." doc = getattr(self._func, '__doc__', None) sig = get_object_signature(self._func) if doc: # Add the signature of the function at the beginning of the doc if sig: sig = "%s%s\n" % (self._func.__name__, sig) doc = sig + doc return doc
[ "def", "getdoc", "(", "self", ")", ":", "doc", "=", "getattr", "(", "self", ".", "_func", ",", "'__doc__'", ",", "None", ")", "sig", "=", "get_object_signature", "(", "self", ".", "_func", ")", "if", "doc", ":", "# Add the signature of the function at the beginning of the doc", "if", "sig", ":", "sig", "=", "\"%s%s\\n\"", "%", "(", "self", ".", "_func", ".", "__name__", ",", "sig", ")", "doc", "=", "sig", "+", "doc", "return", "doc" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/ma/core.py#L8001-L8010
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/unicode.py
python
unicode_isidentifier
(data)
return impl
Implements UnicodeType.isidentifier()
Implements UnicodeType.isidentifier()
[ "Implements", "UnicodeType", ".", "isidentifier", "()" ]
def unicode_isidentifier(data): """Implements UnicodeType.isidentifier()""" def impl(data): length = len(data) if length == 0: return False first_cp = _get_code_point(data, 0) if not _PyUnicode_IsXidStart(first_cp) and first_cp != 0x5F: return False for i in range(1, length): code_point = _get_code_point(data, i) if not _PyUnicode_IsXidContinue(code_point): return False return True return impl
[ "def", "unicode_isidentifier", "(", "data", ")", ":", "def", "impl", "(", "data", ")", ":", "length", "=", "len", "(", "data", ")", "if", "length", "==", "0", ":", "return", "False", "first_cp", "=", "_get_code_point", "(", "data", ",", "0", ")", "if", "not", "_PyUnicode_IsXidStart", "(", "first_cp", ")", "and", "first_cp", "!=", "0x5F", ":", "return", "False", "for", "i", "in", "range", "(", "1", ",", "length", ")", ":", "code_point", "=", "_get_code_point", "(", "data", ",", "i", ")", "if", "not", "_PyUnicode_IsXidContinue", "(", "code_point", ")", ":", "return", "False", "return", "True", "return", "impl" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/unicode.py#L1921-L1940
openvinotoolkit/openvino
dedcbeafa8b84cccdc55ca64b8da516682b381c7
tools/mo/openvino/tools/mo/utils/cli_parser.py
python
readable_dirs_or_empty
(paths: str)
return paths
Checks that comma separated list of paths are readable directories of if it is empty. :param paths: comma separated list of paths. :return: comma separated list of paths.
Checks that comma separated list of paths are readable directories of if it is empty. :param paths: comma separated list of paths. :return: comma separated list of paths.
[ "Checks", "that", "comma", "separated", "list", "of", "paths", "are", "readable", "directories", "of", "if", "it", "is", "empty", ".", ":", "param", "paths", ":", "comma", "separated", "list", "of", "paths", ".", ":", "return", ":", "comma", "separated", "list", "of", "paths", "." ]
def readable_dirs_or_empty(paths: str): """ Checks that comma separated list of paths are readable directories of if it is empty. :param paths: comma separated list of paths. :return: comma separated list of paths. """ if paths: return readable_dirs(paths) return paths
[ "def", "readable_dirs_or_empty", "(", "paths", ":", "str", ")", ":", "if", "paths", ":", "return", "readable_dirs", "(", "paths", ")", "return", "paths" ]
https://github.com/openvinotoolkit/openvino/blob/dedcbeafa8b84cccdc55ca64b8da516682b381c7/tools/mo/openvino/tools/mo/utils/cli_parser.py#L176-L184
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/contrib/linalg/python/ops/linear_operator.py
python
LinearOperator.to_dense
(self, name="to_dense")
Return a dense (batch) matrix representing this operator.
Return a dense (batch) matrix representing this operator.
[ "Return", "a", "dense", "(", "batch", ")", "matrix", "representing", "this", "operator", "." ]
def to_dense(self, name="to_dense"): """Return a dense (batch) matrix representing this operator.""" with self._name_scope(name): return self._to_dense()
[ "def", "to_dense", "(", "self", ",", "name", "=", "\"to_dense\"", ")", ":", "with", "self", ".", "_name_scope", "(", "name", ")", ":", "return", "self", ".", "_to_dense", "(", ")" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/linalg/python/ops/linear_operator.py#L860-L863
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/lib/io/file_io.py
python
read_file_to_string
(filename, binary_mode=False)
return f.read()
Reads the entire contents of a file to a string. Args: filename: string, path to a file binary_mode: whether to open the file in binary mode or not. This changes the type of the object returned. Returns: contents of the file as a string or bytes. Raises: errors.OpError: Raises variety of errors that are subtypes e.g. NotFoundError etc.
Reads the entire contents of a file to a string.
[ "Reads", "the", "entire", "contents", "of", "a", "file", "to", "a", "string", "." ]
def read_file_to_string(filename, binary_mode=False): """Reads the entire contents of a file to a string. Args: filename: string, path to a file binary_mode: whether to open the file in binary mode or not. This changes the type of the object returned. Returns: contents of the file as a string or bytes. Raises: errors.OpError: Raises variety of errors that are subtypes e.g. NotFoundError etc. """ if binary_mode: f = FileIO(filename, mode="rb") else: f = FileIO(filename, mode="r") return f.read()
[ "def", "read_file_to_string", "(", "filename", ",", "binary_mode", "=", "False", ")", ":", "if", "binary_mode", ":", "f", "=", "FileIO", "(", "filename", ",", "mode", "=", "\"rb\"", ")", "else", ":", "f", "=", "FileIO", "(", "filename", ",", "mode", "=", "\"r\"", ")", "return", "f", ".", "read", "(", ")" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/lib/io/file_io.py#L314-L333
microsoft/TSS.MSR
0f2516fca2cd9929c31d5450e39301c9bde43688
TSS.Py/src/TpmTypes.py
python
RSA_DecryptResponse.fromTpm
(buf)
return buf.createObj(RSA_DecryptResponse)
Returns new RSA_DecryptResponse object constructed from its marshaled representation in the given TpmBuffer buffer
Returns new RSA_DecryptResponse object constructed from its marshaled representation in the given TpmBuffer buffer
[ "Returns", "new", "RSA_DecryptResponse", "object", "constructed", "from", "its", "marshaled", "representation", "in", "the", "given", "TpmBuffer", "buffer" ]
def fromTpm(buf): """ Returns new RSA_DecryptResponse object constructed from its marshaled representation in the given TpmBuffer buffer """ return buf.createObj(RSA_DecryptResponse)
[ "def", "fromTpm", "(", "buf", ")", ":", "return", "buf", ".", "createObj", "(", "RSA_DecryptResponse", ")" ]
https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L10801-L10805
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/aui.py
python
AuiMDIParentFrame.SetArtProvider
(*args, **kwargs)
return _aui.AuiMDIParentFrame_SetArtProvider(*args, **kwargs)
SetArtProvider(self, AuiTabArt provider)
SetArtProvider(self, AuiTabArt provider)
[ "SetArtProvider", "(", "self", "AuiTabArt", "provider", ")" ]
def SetArtProvider(*args, **kwargs): """SetArtProvider(self, AuiTabArt provider)""" return _aui.AuiMDIParentFrame_SetArtProvider(*args, **kwargs)
[ "def", "SetArtProvider", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_aui", ".", "AuiMDIParentFrame_SetArtProvider", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/aui.py#L1437-L1439
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_core.py
python
Window.Navigate
(*args, **kwargs)
return _core_.Window_Navigate(*args, **kwargs)
Navigate(self, int flags=NavigationKeyEvent.IsForward) -> bool Does keyboard navigation starting from this window to another. This is equivalient to self.GetParent().NavigateIn().
Navigate(self, int flags=NavigationKeyEvent.IsForward) -> bool
[ "Navigate", "(", "self", "int", "flags", "=", "NavigationKeyEvent", ".", "IsForward", ")", "-", ">", "bool" ]
def Navigate(*args, **kwargs): """ Navigate(self, int flags=NavigationKeyEvent.IsForward) -> bool Does keyboard navigation starting from this window to another. This is equivalient to self.GetParent().NavigateIn(). """ return _core_.Window_Navigate(*args, **kwargs)
[ "def", "Navigate", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "Window_Navigate", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L10204-L10211
Jittor/jittor
e9aca0444c2bdc8e2389d99122954cd0903eec46
python/jittor/init.py
python
zero_
(var)
return var.assign(zero(var.shape, var.dtype))
Inplace initialize variable with zero. Args: var (Jittor Var): Var to initialize with zero. Return: var itself. Example:: from jittor import init from jittor import nn linear = nn.Linear(2,2) init.zero_(linear.weight) print(linear.weight) # output: [[0.,0.],[0.,0.]] linear.weight.zero_() # This is ok too
Inplace initialize variable with zero.
[ "Inplace", "initialize", "variable", "with", "zero", "." ]
def zero_(var): ''' Inplace initialize variable with zero. Args: var (Jittor Var): Var to initialize with zero. Return: var itself. Example:: from jittor import init from jittor import nn linear = nn.Linear(2,2) init.zero_(linear.weight) print(linear.weight) # output: [[0.,0.],[0.,0.]] linear.weight.zero_() # This is ok too ''' return var.assign(zero(var.shape, var.dtype))
[ "def", "zero_", "(", "var", ")", ":", "return", "var", ".", "assign", "(", "zero", "(", "var", ".", "shape", ",", "var", ".", "dtype", ")", ")" ]
https://github.com/Jittor/jittor/blob/e9aca0444c2bdc8e2389d99122954cd0903eec46/python/jittor/init.py#L138-L159
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/Tkinter.py
python
Spinbox.insert
(self, index, s)
return self.tk.call(self._w, 'insert', index, s)
Insert string s at index Returns an empty string.
Insert string s at index
[ "Insert", "string", "s", "at", "index" ]
def insert(self, index, s): """Insert string s at index Returns an empty string. """ return self.tk.call(self._w, 'insert', index, s)
[ "def", "insert", "(", "self", ",", "index", ",", "s", ")", ":", "return", "self", ".", "tk", ".", "call", "(", "self", ".", "_w", ",", "'insert'", ",", "index", ",", "s", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/Tkinter.py#L3451-L3456
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/logging/handlers.py
python
SysLogHandler.emit
(self, record)
Emit a record. The record is formatted, and then sent to the syslog server. If exception information is present, it is NOT sent to the server.
Emit a record.
[ "Emit", "a", "record", "." ]
def emit(self, record): """ Emit a record. The record is formatted, and then sent to the syslog server. If exception information is present, it is NOT sent to the server. """ try: msg = self.format(record) if self.ident: msg = self.ident + msg if self.append_nul: msg += '\000' # We need to convert record level to lowercase, maybe this will # change in the future. prio = '<%d>' % self.encodePriority(self.facility, self.mapPriority(record.levelname)) prio = prio.encode('utf-8') # Message is a string. Convert to bytes as required by RFC 5424 msg = msg.encode('utf-8') msg = prio + msg if self.unixsocket: try: self.socket.send(msg) except OSError: self.socket.close() self._connect_unixsocket(self.address) self.socket.send(msg) elif self.socktype == socket.SOCK_DGRAM: self.socket.sendto(msg, self.address) else: self.socket.sendall(msg) except Exception: self.handleError(record)
[ "def", "emit", "(", "self", ",", "record", ")", ":", "try", ":", "msg", "=", "self", ".", "format", "(", "record", ")", "if", "self", ".", "ident", ":", "msg", "=", "self", ".", "ident", "+", "msg", "if", "self", ".", "append_nul", ":", "msg", "+=", "'\\000'", "# We need to convert record level to lowercase, maybe this will", "# change in the future.", "prio", "=", "'<%d>'", "%", "self", ".", "encodePriority", "(", "self", ".", "facility", ",", "self", ".", "mapPriority", "(", "record", ".", "levelname", ")", ")", "prio", "=", "prio", ".", "encode", "(", "'utf-8'", ")", "# Message is a string. Convert to bytes as required by RFC 5424", "msg", "=", "msg", ".", "encode", "(", "'utf-8'", ")", "msg", "=", "prio", "+", "msg", "if", "self", ".", "unixsocket", ":", "try", ":", "self", ".", "socket", ".", "send", "(", "msg", ")", "except", "OSError", ":", "self", ".", "socket", ".", "close", "(", ")", "self", ".", "_connect_unixsocket", "(", "self", ".", "address", ")", "self", ".", "socket", ".", "send", "(", "msg", ")", "elif", "self", ".", "socktype", "==", "socket", ".", "SOCK_DGRAM", ":", "self", ".", "socket", ".", "sendto", "(", "msg", ",", "self", ".", "address", ")", "else", ":", "self", ".", "socket", ".", "sendall", "(", "msg", ")", "except", "Exception", ":", "self", ".", "handleError", "(", "record", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/logging/handlers.py#L910-L944
google/syzygy
8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5
third_party/numpy/files/numpy/oldnumeric/ma.py
python
masked_binary_operation.__call__
(self, a, b, *args, **kwargs)
return masked_array(result, m)
Execute the call behavior.
Execute the call behavior.
[ "Execute", "the", "call", "behavior", "." ]
def __call__ (self, a, b, *args, **kwargs): "Execute the call behavior." m = mask_or(getmask(a), getmask(b)) d1 = filled(a, self.fillx) d2 = filled(b, self.filly) result = self.f(d1, d2, *args, **kwargs) if isinstance(result, ndarray) \ and m.ndim != 0 \ and m.shape != result.shape: m = mask_or(getmaskarray(a), getmaskarray(b)) return masked_array(result, m)
[ "def", "__call__", "(", "self", ",", "a", ",", "b", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "m", "=", "mask_or", "(", "getmask", "(", "a", ")", ",", "getmask", "(", "b", ")", ")", "d1", "=", "filled", "(", "a", ",", "self", ".", "fillx", ")", "d2", "=", "filled", "(", "b", ",", "self", ".", "filly", ")", "result", "=", "self", ".", "f", "(", "d1", ",", "d2", ",", "*", "args", ",", "*", "*", "kwargs", ")", "if", "isinstance", "(", "result", ",", "ndarray", ")", "and", "m", ".", "ndim", "!=", "0", "and", "m", ".", "shape", "!=", "result", ".", "shape", ":", "m", "=", "mask_or", "(", "getmaskarray", "(", "a", ")", ",", "getmaskarray", "(", "b", ")", ")", "return", "masked_array", "(", "result", ",", "m", ")" ]
https://github.com/google/syzygy/blob/8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5/third_party/numpy/files/numpy/oldnumeric/ma.py#L381-L391
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/corrections_tab_widget/background_corrections_model.py
python
BackgroundCorrectionsModel.set_background_correction_mode
(self, mode: str)
Sets the current background correction mode in the context.
Sets the current background correction mode in the context.
[ "Sets", "the", "current", "background", "correction", "mode", "in", "the", "context", "." ]
def set_background_correction_mode(self, mode: str) -> None: """Sets the current background correction mode in the context.""" self._corrections_context.background_corrections_mode = mode
[ "def", "set_background_correction_mode", "(", "self", ",", "mode", ":", "str", ")", "->", "None", ":", "self", ".", "_corrections_context", ".", "background_corrections_mode", "=", "mode" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/corrections_tab_widget/background_corrections_model.py#L200-L202
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/ops/_op_impl/cpu/arg_max_with_value.py
python
_arg_max_with_value_cpu
()
return
ArgMaxWithValue cpu register
ArgMaxWithValue cpu register
[ "ArgMaxWithValue", "cpu", "register" ]
def _arg_max_with_value_cpu(): """ArgMaxWithValue cpu register""" return
[ "def", "_arg_max_with_value_cpu", "(", ")", ":", "return" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/_op_impl/cpu/arg_max_with_value.py#L29-L31
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_layers2.py
python
convert_bidirectional
( builder, layer, input_names, output_names, keras_layer, respect_train )
Convert a bidirectional layer from keras to coreml. Currently assumes the units are LSTMs. Parameters ---------- keras_layer: layer A keras layer object. builder: NeuralNetworkBuilder A neural network builder object. respect_train: boolean Whether to honor Keras' "trainable" flag (unsupported).
Convert a bidirectional layer from keras to coreml. Currently assumes the units are LSTMs.
[ "Convert", "a", "bidirectional", "layer", "from", "keras", "to", "coreml", ".", "Currently", "assumes", "the", "units", "are", "LSTMs", "." ]
def convert_bidirectional( builder, layer, input_names, output_names, keras_layer, respect_train ): """ Convert a bidirectional layer from keras to coreml. Currently assumes the units are LSTMs. Parameters ---------- keras_layer: layer A keras layer object. builder: NeuralNetworkBuilder A neural network builder object. respect_train: boolean Whether to honor Keras' "trainable" flag (unsupported). """ input_size = keras_layer.input_shape[-1] lstm_layer = keras_layer.forward_layer if type(lstm_layer) != _keras.layers.recurrent.LSTM: raise TypeError("Bidirectional layers only supported with LSTM") if lstm_layer.go_backwards: raise TypeError(" 'go_backwards' mode not supported with Bidirectional layers") output_all = keras_layer.return_sequences hidden_size = lstm_layer.units # Keras: I C F O; W_x, W_h, b # CoreML: I F O G; W_h and W_x are separated # Keras has all forward weights, followed by backward in the same order W_h, W_x, b = ([], [], []) keras_W_h = keras_layer.forward_layer.get_weights()[1].T W_h.append(keras_W_h[0 * hidden_size :][:hidden_size]) W_h.append(keras_W_h[1 * hidden_size :][:hidden_size]) W_h.append(keras_W_h[3 * hidden_size :][:hidden_size]) W_h.append(keras_W_h[2 * hidden_size :][:hidden_size]) keras_W_x = keras_layer.forward_layer.get_weights()[0].T W_x.append(keras_W_x[0 * hidden_size :][:hidden_size]) W_x.append(keras_W_x[1 * hidden_size :][:hidden_size]) W_x.append(keras_W_x[3 * hidden_size :][:hidden_size]) W_x.append(keras_W_x[2 * hidden_size :][:hidden_size]) if keras_layer.forward_layer.use_bias: keras_b = keras_layer.forward_layer.get_weights()[2] b.append(keras_b[0 * hidden_size :][:hidden_size]) b.append(keras_b[1 * hidden_size :][:hidden_size]) b.append(keras_b[3 * hidden_size :][:hidden_size]) b.append(keras_b[2 * hidden_size :][:hidden_size]) if len(b) == 0: b = None W_h_back, W_x_back, b_back = ([], [], []) keras_W_h = keras_layer.backward_layer.get_weights()[1].T W_h_back.append(keras_W_h[0 * hidden_size :][:hidden_size]) W_h_back.append(keras_W_h[1 * hidden_size :][:hidden_size]) W_h_back.append(keras_W_h[3 * hidden_size :][:hidden_size]) W_h_back.append(keras_W_h[2 * hidden_size :][:hidden_size]) keras_W_x = keras_layer.backward_layer.get_weights()[0].T W_x_back.append(keras_W_x[0 * hidden_size :][:hidden_size]) W_x_back.append(keras_W_x[1 * hidden_size :][:hidden_size]) W_x_back.append(keras_W_x[3 * hidden_size :][:hidden_size]) W_x_back.append(keras_W_x[2 * hidden_size :][:hidden_size]) if keras_layer.backward_layer.use_bias: keras_b = keras_layer.backward_layer.get_weights()[2] b_back.append(keras_b[0 * hidden_size :][:hidden_size]) b_back.append(keras_b[1 * hidden_size :][:hidden_size]) b_back.append(keras_b[3 * hidden_size :][:hidden_size]) b_back.append(keras_b[2 * hidden_size :][:hidden_size]) if len(b_back) == 0: b_back = None if (b == None and b_back != None) or (b != None and b_back == None): raise ValueError( "Unsupported Bi-directional LSTM configuration. Bias " "must be enabled/disabled for both directions." ) # Set activation type inner_activation_str = _get_recurrent_activation_name_from_keras( lstm_layer.recurrent_activation ) activation_str = _get_recurrent_activation_name_from_keras(lstm_layer.activation) output_name_1 = output_names[0] if hasattr(keras_layer, "merge_mode"): merge_mode = keras_layer.merge_mode if merge_mode not in ["concat", "sum", "mul", "ave"]: raise NotImplementedError( "merge_mode '%s' in Bidirectional LSTM " "not supported currently" % merge_mode ) if merge_mode != "concat": output_name_1 += "_concatenated_bilstm_output" # Add to the network builder.add_bidirlstm( name=layer, W_h=W_h, W_x=W_x, b=b, W_h_back=W_h_back, W_x_back=W_x_back, b_back=b_back, hidden_size=hidden_size, input_size=input_size, input_names=input_names, output_names=[output_name_1] + output_names[1:], inner_activation=inner_activation_str, cell_state_update_activation=activation_str, output_activation=activation_str, forget_bias=lstm_layer.unit_forget_bias, output_all=output_all, ) if output_name_1 != output_names[0]: mode = "CONCAT" if merge_mode == "sum": mode = "ADD" elif merge_mode == "ave": mode = "AVE" elif merge_mode == "mul": mode = "MULTIPLY" builder.add_split( name=layer + "_split", input_name=output_name_1, output_names=[output_names[0] + "_forward", output_names[0] + "_backward"], ) builder.add_elementwise( name=layer + "_elementwise", input_names=[output_names[0] + "_forward", output_names[0] + "_backward"], output_name=output_names[0], mode=mode, ) if respect_train and keras_layer.trainable: logging.warning( "Bidirectional layer '%s' is marked updatable, but " "Core ML does not yet support updating layers of this " "type. The layer will be frozen in Core ML.", layer, )
[ "def", "convert_bidirectional", "(", "builder", ",", "layer", ",", "input_names", ",", "output_names", ",", "keras_layer", ",", "respect_train", ")", ":", "input_size", "=", "keras_layer", ".", "input_shape", "[", "-", "1", "]", "lstm_layer", "=", "keras_layer", ".", "forward_layer", "if", "type", "(", "lstm_layer", ")", "!=", "_keras", ".", "layers", ".", "recurrent", ".", "LSTM", ":", "raise", "TypeError", "(", "\"Bidirectional layers only supported with LSTM\"", ")", "if", "lstm_layer", ".", "go_backwards", ":", "raise", "TypeError", "(", "\" 'go_backwards' mode not supported with Bidirectional layers\"", ")", "output_all", "=", "keras_layer", ".", "return_sequences", "hidden_size", "=", "lstm_layer", ".", "units", "# Keras: I C F O; W_x, W_h, b", "# CoreML: I F O G; W_h and W_x are separated", "# Keras has all forward weights, followed by backward in the same order", "W_h", ",", "W_x", ",", "b", "=", "(", "[", "]", ",", "[", "]", ",", "[", "]", ")", "keras_W_h", "=", "keras_layer", ".", "forward_layer", ".", "get_weights", "(", ")", "[", "1", "]", ".", "T", "W_h", ".", "append", "(", "keras_W_h", "[", "0", "*", "hidden_size", ":", "]", "[", ":", "hidden_size", "]", ")", "W_h", ".", "append", "(", "keras_W_h", "[", "1", "*", "hidden_size", ":", "]", "[", ":", "hidden_size", "]", ")", "W_h", ".", "append", "(", "keras_W_h", "[", "3", "*", "hidden_size", ":", "]", "[", ":", "hidden_size", "]", ")", "W_h", ".", "append", "(", "keras_W_h", "[", "2", "*", "hidden_size", ":", "]", "[", ":", "hidden_size", "]", ")", "keras_W_x", "=", "keras_layer", ".", "forward_layer", ".", "get_weights", "(", ")", "[", "0", "]", ".", "T", "W_x", ".", "append", "(", "keras_W_x", "[", "0", "*", "hidden_size", ":", "]", "[", ":", "hidden_size", "]", ")", "W_x", ".", "append", "(", "keras_W_x", "[", "1", "*", "hidden_size", ":", "]", "[", ":", "hidden_size", "]", ")", "W_x", ".", "append", "(", "keras_W_x", "[", "3", "*", "hidden_size", ":", "]", "[", ":", "hidden_size", "]", ")", "W_x", ".", "append", "(", "keras_W_x", "[", "2", "*", "hidden_size", ":", "]", "[", ":", "hidden_size", "]", ")", "if", "keras_layer", ".", "forward_layer", ".", "use_bias", ":", "keras_b", "=", "keras_layer", ".", "forward_layer", ".", "get_weights", "(", ")", "[", "2", "]", "b", ".", "append", "(", "keras_b", "[", "0", "*", "hidden_size", ":", "]", "[", ":", "hidden_size", "]", ")", "b", ".", "append", "(", "keras_b", "[", "1", "*", "hidden_size", ":", "]", "[", ":", "hidden_size", "]", ")", "b", ".", "append", "(", "keras_b", "[", "3", "*", "hidden_size", ":", "]", "[", ":", "hidden_size", "]", ")", "b", ".", "append", "(", "keras_b", "[", "2", "*", "hidden_size", ":", "]", "[", ":", "hidden_size", "]", ")", "if", "len", "(", "b", ")", "==", "0", ":", "b", "=", "None", "W_h_back", ",", "W_x_back", ",", "b_back", "=", "(", "[", "]", ",", "[", "]", ",", "[", "]", ")", "keras_W_h", "=", "keras_layer", ".", "backward_layer", ".", "get_weights", "(", ")", "[", "1", "]", ".", "T", "W_h_back", ".", "append", "(", "keras_W_h", "[", "0", "*", "hidden_size", ":", "]", "[", ":", "hidden_size", "]", ")", "W_h_back", ".", "append", "(", "keras_W_h", "[", "1", "*", "hidden_size", ":", "]", "[", ":", "hidden_size", "]", ")", "W_h_back", ".", "append", "(", "keras_W_h", "[", "3", "*", "hidden_size", ":", "]", "[", ":", "hidden_size", "]", ")", "W_h_back", ".", "append", "(", "keras_W_h", "[", "2", "*", "hidden_size", ":", "]", "[", ":", "hidden_size", "]", ")", "keras_W_x", "=", "keras_layer", ".", "backward_layer", ".", "get_weights", "(", ")", "[", "0", "]", ".", "T", "W_x_back", ".", "append", "(", "keras_W_x", "[", "0", "*", "hidden_size", ":", "]", "[", ":", "hidden_size", "]", ")", "W_x_back", ".", "append", "(", "keras_W_x", "[", "1", "*", "hidden_size", ":", "]", "[", ":", "hidden_size", "]", ")", "W_x_back", ".", "append", "(", "keras_W_x", "[", "3", "*", "hidden_size", ":", "]", "[", ":", "hidden_size", "]", ")", "W_x_back", ".", "append", "(", "keras_W_x", "[", "2", "*", "hidden_size", ":", "]", "[", ":", "hidden_size", "]", ")", "if", "keras_layer", ".", "backward_layer", ".", "use_bias", ":", "keras_b", "=", "keras_layer", ".", "backward_layer", ".", "get_weights", "(", ")", "[", "2", "]", "b_back", ".", "append", "(", "keras_b", "[", "0", "*", "hidden_size", ":", "]", "[", ":", "hidden_size", "]", ")", "b_back", ".", "append", "(", "keras_b", "[", "1", "*", "hidden_size", ":", "]", "[", ":", "hidden_size", "]", ")", "b_back", ".", "append", "(", "keras_b", "[", "3", "*", "hidden_size", ":", "]", "[", ":", "hidden_size", "]", ")", "b_back", ".", "append", "(", "keras_b", "[", "2", "*", "hidden_size", ":", "]", "[", ":", "hidden_size", "]", ")", "if", "len", "(", "b_back", ")", "==", "0", ":", "b_back", "=", "None", "if", "(", "b", "==", "None", "and", "b_back", "!=", "None", ")", "or", "(", "b", "!=", "None", "and", "b_back", "==", "None", ")", ":", "raise", "ValueError", "(", "\"Unsupported Bi-directional LSTM configuration. Bias \"", "\"must be enabled/disabled for both directions.\"", ")", "# Set activation type", "inner_activation_str", "=", "_get_recurrent_activation_name_from_keras", "(", "lstm_layer", ".", "recurrent_activation", ")", "activation_str", "=", "_get_recurrent_activation_name_from_keras", "(", "lstm_layer", ".", "activation", ")", "output_name_1", "=", "output_names", "[", "0", "]", "if", "hasattr", "(", "keras_layer", ",", "\"merge_mode\"", ")", ":", "merge_mode", "=", "keras_layer", ".", "merge_mode", "if", "merge_mode", "not", "in", "[", "\"concat\"", ",", "\"sum\"", ",", "\"mul\"", ",", "\"ave\"", "]", ":", "raise", "NotImplementedError", "(", "\"merge_mode '%s' in Bidirectional LSTM \"", "\"not supported currently\"", "%", "merge_mode", ")", "if", "merge_mode", "!=", "\"concat\"", ":", "output_name_1", "+=", "\"_concatenated_bilstm_output\"", "# Add to the network", "builder", ".", "add_bidirlstm", "(", "name", "=", "layer", ",", "W_h", "=", "W_h", ",", "W_x", "=", "W_x", ",", "b", "=", "b", ",", "W_h_back", "=", "W_h_back", ",", "W_x_back", "=", "W_x_back", ",", "b_back", "=", "b_back", ",", "hidden_size", "=", "hidden_size", ",", "input_size", "=", "input_size", ",", "input_names", "=", "input_names", ",", "output_names", "=", "[", "output_name_1", "]", "+", "output_names", "[", "1", ":", "]", ",", "inner_activation", "=", "inner_activation_str", ",", "cell_state_update_activation", "=", "activation_str", ",", "output_activation", "=", "activation_str", ",", "forget_bias", "=", "lstm_layer", ".", "unit_forget_bias", ",", "output_all", "=", "output_all", ",", ")", "if", "output_name_1", "!=", "output_names", "[", "0", "]", ":", "mode", "=", "\"CONCAT\"", "if", "merge_mode", "==", "\"sum\"", ":", "mode", "=", "\"ADD\"", "elif", "merge_mode", "==", "\"ave\"", ":", "mode", "=", "\"AVE\"", "elif", "merge_mode", "==", "\"mul\"", ":", "mode", "=", "\"MULTIPLY\"", "builder", ".", "add_split", "(", "name", "=", "layer", "+", "\"_split\"", ",", "input_name", "=", "output_name_1", ",", "output_names", "=", "[", "output_names", "[", "0", "]", "+", "\"_forward\"", ",", "output_names", "[", "0", "]", "+", "\"_backward\"", "]", ",", ")", "builder", ".", "add_elementwise", "(", "name", "=", "layer", "+", "\"_elementwise\"", ",", "input_names", "=", "[", "output_names", "[", "0", "]", "+", "\"_forward\"", ",", "output_names", "[", "0", "]", "+", "\"_backward\"", "]", ",", "output_name", "=", "output_names", "[", "0", "]", ",", "mode", "=", "mode", ",", ")", "if", "respect_train", "and", "keras_layer", ".", "trainable", ":", "logging", ".", "warning", "(", "\"Bidirectional layer '%s' is marked updatable, but \"", "\"Core ML does not yet support updating layers of this \"", "\"type. The layer will be frozen in Core ML.\"", ",", "layer", ",", ")" ]
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_layers2.py#L1420-L1567
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/boto/boto/route53/status.py
python
Status.update
(self)
return status
Update the status of this request.
Update the status of this request.
[ "Update", "the", "status", "of", "this", "request", "." ]
def update(self): """ Update the status of this request.""" status = self.route53connection.get_change(self.id)['GetChangeResponse']['ChangeInfo']['Status'] self.status = status return status
[ "def", "update", "(", "self", ")", ":", "status", "=", "self", ".", "route53connection", ".", "get_change", "(", "self", ".", "id", ")", "[", "'GetChangeResponse'", "]", "[", "'ChangeInfo'", "]", "[", "'Status'", "]", "self", ".", "status", "=", "status", "return", "status" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/route53/status.py#L35-L39
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_gdi.py
python
DC.DrawRectangleRect
(*args, **kwargs)
return _gdi_.DC_DrawRectangleRect(*args, **kwargs)
DrawRectangleRect(self, Rect rect) Draws a rectangle with the given top left corner, and with the given size. The current pen is used for the outline and the current brush for filling the shape.
DrawRectangleRect(self, Rect rect)
[ "DrawRectangleRect", "(", "self", "Rect", "rect", ")" ]
def DrawRectangleRect(*args, **kwargs): """ DrawRectangleRect(self, Rect rect) Draws a rectangle with the given top left corner, and with the given size. The current pen is used for the outline and the current brush for filling the shape. """ return _gdi_.DC_DrawRectangleRect(*args, **kwargs)
[ "def", "DrawRectangleRect", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gdi_", ".", "DC_DrawRectangleRect", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_gdi.py#L3548-L3556
hpi-xnor/BMXNet
ed0b201da6667887222b8e4b5f997c4f6b61943d
python/mxnet/symbol/symbol.py
python
Symbol.split
(self, *args, **kwargs)
return op.split(self, *args, **kwargs)
Convenience fluent method for :py:func:`split`. The arguments are the same as for :py:func:`split`, with this array as data.
Convenience fluent method for :py:func:`split`.
[ "Convenience", "fluent", "method", "for", ":", "py", ":", "func", ":", "split", "." ]
def split(self, *args, **kwargs): """Convenience fluent method for :py:func:`split`. The arguments are the same as for :py:func:`split`, with this array as data. """ return op.split(self, *args, **kwargs)
[ "def", "split", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "op", ".", "split", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/hpi-xnor/BMXNet/blob/ed0b201da6667887222b8e4b5f997c4f6b61943d/python/mxnet/symbol/symbol.py#L1815-L1821
simsong/bulk_extractor
738911df22b7066ca9e1662f4131fb44090a4196
python/identify_filenames.py
python
byterundb.process_fi
(self,fi)
Read an XML file and add each byte run to this database
Read an XML file and add each byte run to this database
[ "Read", "an", "XML", "file", "and", "add", "each", "byte", "run", "to", "this", "database" ]
def process_fi(self,fi): """Read an XML file and add each byte run to this database""" def gval(x): """Always return X as bytes""" if x==None: return b'' if type(x)==bytes: return x if type(x)!=str: x = str(x) return x.encode('utf-8') for run in fi.byte_runs(): try: fname = gval(fi.filename()) md5val = gval(fi.md5()) if not fi.allocated(): fname = b'*' + fname; if args.mactimes: fileinfo = (fname, md5val, gval(fi.crtime()), gval(fi.ctime()), gval(fi.mtime()), gval(fi.atime())) else: fileinfo = (fname, md5val) self.add_extent(run.img_offset,run.len,fileinfo) except TypeError as e: pass
[ "def", "process_fi", "(", "self", ",", "fi", ")", ":", "def", "gval", "(", "x", ")", ":", "\"\"\"Always return X as bytes\"\"\"", "if", "x", "==", "None", ":", "return", "b''", "if", "type", "(", "x", ")", "==", "bytes", ":", "return", "x", "if", "type", "(", "x", ")", "!=", "str", ":", "x", "=", "str", "(", "x", ")", "return", "x", ".", "encode", "(", "'utf-8'", ")", "for", "run", "in", "fi", ".", "byte_runs", "(", ")", ":", "try", ":", "fname", "=", "gval", "(", "fi", ".", "filename", "(", ")", ")", "md5val", "=", "gval", "(", "fi", ".", "md5", "(", ")", ")", "if", "not", "fi", ".", "allocated", "(", ")", ":", "fname", "=", "b'*'", "+", "fname", "if", "args", ".", "mactimes", ":", "fileinfo", "=", "(", "fname", ",", "md5val", ",", "gval", "(", "fi", ".", "crtime", "(", ")", ")", ",", "gval", "(", "fi", ".", "ctime", "(", ")", ")", ",", "gval", "(", "fi", ".", "mtime", "(", ")", ")", ",", "gval", "(", "fi", ".", "atime", "(", ")", ")", ")", "else", ":", "fileinfo", "=", "(", "fname", ",", "md5val", ")", "self", ".", "add_extent", "(", "run", ".", "img_offset", ",", "run", ".", "len", ",", "fileinfo", ")", "except", "TypeError", "as", "e", ":", "pass" ]
https://github.com/simsong/bulk_extractor/blob/738911df22b7066ca9e1662f4131fb44090a4196/python/identify_filenames.py#L87-L107
pristineio/webrtc-mirror
7a5bcdffaab90a05bc1146b2b1ea71c004e54d71
webrtc/rtc_tools/py_event_log_analyzer/rtp_analyzer.py
python
RTPStatistics.PlotStatistics
(self)
Plots changes in delay and average bandwidth.
Plots changes in delay and average bandwidth.
[ "Plots", "changes", "in", "delay", "and", "average", "bandwidth", "." ]
def PlotStatistics(self): """Plots changes in delay and average bandwidth.""" start_ms = self.data_points[0].real_send_time_ms stop_ms = self.data_points[-1].real_send_time_ms time_axis = numpy.arange(start_ms / 1000, stop_ms / 1000, RTPStatistics.PLOT_RESOLUTION_MS / 1000) delay = CalculateDelay(start_ms, stop_ms, RTPStatistics.PLOT_RESOLUTION_MS, self.data_points) plt.figure(1) plt.plot(time_axis, delay[:len(time_axis)]) plt.xlabel("Send time [s]") plt.ylabel("Relative transport delay [ms]") plt.figure(2) plt.plot(time_axis[:len(self.smooth_bw_kbps)], self.smooth_bw_kbps) plt.xlabel("Send time [s]") plt.ylabel("Bandwidth [kbps]") plt.show()
[ "def", "PlotStatistics", "(", "self", ")", ":", "start_ms", "=", "self", ".", "data_points", "[", "0", "]", ".", "real_send_time_ms", "stop_ms", "=", "self", ".", "data_points", "[", "-", "1", "]", ".", "real_send_time_ms", "time_axis", "=", "numpy", ".", "arange", "(", "start_ms", "/", "1000", ",", "stop_ms", "/", "1000", ",", "RTPStatistics", ".", "PLOT_RESOLUTION_MS", "/", "1000", ")", "delay", "=", "CalculateDelay", "(", "start_ms", ",", "stop_ms", ",", "RTPStatistics", ".", "PLOT_RESOLUTION_MS", ",", "self", ".", "data_points", ")", "plt", ".", "figure", "(", "1", ")", "plt", ".", "plot", "(", "time_axis", ",", "delay", "[", ":", "len", "(", "time_axis", ")", "]", ")", "plt", ".", "xlabel", "(", "\"Send time [s]\"", ")", "plt", ".", "ylabel", "(", "\"Relative transport delay [ms]\"", ")", "plt", ".", "figure", "(", "2", ")", "plt", ".", "plot", "(", "time_axis", "[", ":", "len", "(", "self", ".", "smooth_bw_kbps", ")", "]", ",", "self", ".", "smooth_bw_kbps", ")", "plt", ".", "xlabel", "(", "\"Send time [s]\"", ")", "plt", ".", "ylabel", "(", "\"Bandwidth [kbps]\"", ")", "plt", ".", "show", "(", ")" ]
https://github.com/pristineio/webrtc-mirror/blob/7a5bcdffaab90a05bc1146b2b1ea71c004e54d71/webrtc/rtc_tools/py_event_log_analyzer/rtp_analyzer.py#L249-L271
intel/caffe
3f494b442ee3f9d17a07b09ecbd5fa2bbda00836
examples/rfcn/lib/rpn/proposal_target_layer.py
python
ProposalTargetLayer.reshape
(self, bottom, top)
Reshaping happens during the call to forward.
Reshaping happens during the call to forward.
[ "Reshaping", "happens", "during", "the", "call", "to", "forward", "." ]
def reshape(self, bottom, top): """Reshaping happens during the call to forward.""" pass
[ "def", "reshape", "(", "self", ",", "bottom", ",", "top", ")", ":", "pass" ]
https://github.com/intel/caffe/blob/3f494b442ee3f9d17a07b09ecbd5fa2bbda00836/examples/rfcn/lib/rpn/proposal_target_layer.py#L106-L108
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/importlib/_bootstrap_external.py
python
ExtensionFileLoader.is_package
(self, fullname)
return any(file_name == '__init__' + suffix for suffix in EXTENSION_SUFFIXES)
Return True if the extension module is a package.
Return True if the extension module is a package.
[ "Return", "True", "if", "the", "extension", "module", "is", "a", "package", "." ]
def is_package(self, fullname): """Return True if the extension module is a package.""" file_name = _path_split(self.path)[1] return any(file_name == '__init__' + suffix for suffix in EXTENSION_SUFFIXES)
[ "def", "is_package", "(", "self", ",", "fullname", ")", ":", "file_name", "=", "_path_split", "(", "self", ".", "path", ")", "[", "1", "]", "return", "any", "(", "file_name", "==", "'__init__'", "+", "suffix", "for", "suffix", "in", "EXTENSION_SUFFIXES", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/importlib/_bootstrap_external.py#L1054-L1058
kushview/Element
1cc16380caa2ab79461246ba758b9de1f46db2a5
waflib/extras/msvs.py
python
vsnode_project.get_key
(self, node)
return 'ClInclude'
required for writing the source files
required for writing the source files
[ "required", "for", "writing", "the", "source", "files" ]
def get_key(self, node): """ required for writing the source files """ name = node.name if name.endswith(('.cpp', '.c')): return 'ClCompile' return 'ClInclude'
[ "def", "get_key", "(", "self", ",", "node", ")", ":", "name", "=", "node", ".", "name", "if", "name", ".", "endswith", "(", "(", "'.cpp'", ",", "'.c'", ")", ")", ":", "return", "'ClCompile'", "return", "'ClInclude'" ]
https://github.com/kushview/Element/blob/1cc16380caa2ab79461246ba758b9de1f46db2a5/waflib/extras/msvs.py#L556-L563
perilouswithadollarsign/cstrike15_src
f82112a2388b841d72cb62ca48ab1846dfcc11c8
thirdparty/protobuf-2.5.0/python/mox.py
python
ExpectedMethodCallsError.__init__
(self, expected_methods)
Init exception. Args: # expected_methods: A sequence of MockMethod objects that should have been # called. expected_methods: [MockMethod] Raises: ValueError: if expected_methods contains no methods.
Init exception.
[ "Init", "exception", "." ]
def __init__(self, expected_methods): """Init exception. Args: # expected_methods: A sequence of MockMethod objects that should have been # called. expected_methods: [MockMethod] Raises: ValueError: if expected_methods contains no methods. """ if not expected_methods: raise ValueError("There must be at least one expected method") Error.__init__(self) self._expected_methods = expected_methods
[ "def", "__init__", "(", "self", ",", "expected_methods", ")", ":", "if", "not", "expected_methods", ":", "raise", "ValueError", "(", "\"There must be at least one expected method\"", ")", "Error", ".", "__init__", "(", "self", ")", "self", ".", "_expected_methods", "=", "expected_methods" ]
https://github.com/perilouswithadollarsign/cstrike15_src/blob/f82112a2388b841d72cb62ca48ab1846dfcc11c8/thirdparty/protobuf-2.5.0/python/mox.py#L79-L94
root-project/root
fcd3583bb14852bf2e8cd2415717cbaac0e75896
bindings/experimental/distrdf/python/DistRDF/ComputationGraphGenerator.py
python
ComputationGraphGenerator.trigger_computation_graph
(self, starting_node, range_id)
return actions
Trigger the computation graph. The list of actions to be performed is retrieved by calling generate_computation_graph. Afterwards, the C++ RDF computation graph is triggered through the `ROOT::Internal::RDF::TriggerRun` function with the GIL released. Args: starting_node (ROOT.RDF.RNode): The node where the generation of the computation graph is started. Either an actual RDataFrame or the result of a Range operation (in case of empty data source). range_id (int): The id of the current range. Needed to assign a file name to a partial Snapshot if it was requested. Returns: list: A list of objects that can be either used as or converted into mergeable values.
Trigger the computation graph.
[ "Trigger", "the", "computation", "graph", "." ]
def trigger_computation_graph(self, starting_node, range_id): """ Trigger the computation graph. The list of actions to be performed is retrieved by calling generate_computation_graph. Afterwards, the C++ RDF computation graph is triggered through the `ROOT::Internal::RDF::TriggerRun` function with the GIL released. Args: starting_node (ROOT.RDF.RNode): The node where the generation of the computation graph is started. Either an actual RDataFrame or the result of a Range operation (in case of empty data source). range_id (int): The id of the current range. Needed to assign a file name to a partial Snapshot if it was requested. Returns: list: A list of objects that can be either used as or converted into mergeable values. """ actions = self.generate_computation_graph(starting_node, range_id) # Trigger computation graph with the GIL released rnode = ROOT.RDF.AsRNode(starting_node) ROOT.Internal.RDF.TriggerRun.__release_gil__ = True ROOT.Internal.RDF.TriggerRun(rnode) # Return a list of objects that can be later merged. In most cases this # is still made of RResultPtrs that will then be used as input arguments # to `ROOT::RDF::Detail::GetMergeableValue`. For `AsNumpy`, it returns # an instance of `AsNumpyResult`. For `Snapshot`, it returns a # `SnapshotResult` return actions
[ "def", "trigger_computation_graph", "(", "self", ",", "starting_node", ",", "range_id", ")", ":", "actions", "=", "self", ".", "generate_computation_graph", "(", "starting_node", ",", "range_id", ")", "# Trigger computation graph with the GIL released", "rnode", "=", "ROOT", ".", "RDF", ".", "AsRNode", "(", "starting_node", ")", "ROOT", ".", "Internal", ".", "RDF", ".", "TriggerRun", ".", "__release_gil__", "=", "True", "ROOT", ".", "Internal", ".", "RDF", ".", "TriggerRun", "(", "rnode", ")", "# Return a list of objects that can be later merged. In most cases this", "# is still made of RResultPtrs that will then be used as input arguments", "# to `ROOT::RDF::Detail::GetMergeableValue`. For `AsNumpy`, it returns", "# an instance of `AsNumpyResult`. For `Snapshot`, it returns a", "# `SnapshotResult`", "return", "actions" ]
https://github.com/root-project/root/blob/fcd3583bb14852bf2e8cd2415717cbaac0e75896/bindings/experimental/distrdf/python/DistRDF/ComputationGraphGenerator.py#L175-L207
eventql/eventql
7ca0dbb2e683b525620ea30dc40540a22d5eb227
deps/3rdparty/spidermonkey/mozjs/python/mozbuild/mozbuild/util.py
python
FileAvoidWrite.close
(self)
return existed, True
Stop accepting writes, compare file contents, and rewrite if needed. Returns a tuple of bools indicating what action was performed: (file existed, file updated) If ``capture_diff`` was specified at construction time and the underlying file was changed, ``.diff`` will be populated with the diff of the result.
Stop accepting writes, compare file contents, and rewrite if needed.
[ "Stop", "accepting", "writes", "compare", "file", "contents", "and", "rewrite", "if", "needed", "." ]
def close(self): """Stop accepting writes, compare file contents, and rewrite if needed. Returns a tuple of bools indicating what action was performed: (file existed, file updated) If ``capture_diff`` was specified at construction time and the underlying file was changed, ``.diff`` will be populated with the diff of the result. """ buf = self.getvalue() StringIO.close(self) existed = False old_content = None try: existing = open(self.name, 'rU') existed = True except IOError: pass else: try: old_content = existing.read() if old_content == buf: return True, False except IOError: pass finally: existing.close() ensureParentDir(self.name) with open(self.name, 'w') as file: file.write(buf) if self._capture_diff: try: old_lines = old_content.splitlines() if old_content else [] new_lines = buf.splitlines() self.diff = difflib.unified_diff(old_lines, new_lines, self.name, self.name, n=4, lineterm='') # FileAvoidWrite isn't unicode/bytes safe. So, files with non-ascii # content or opened and written in different modes may involve # implicit conversion and this will make Python unhappy. Since # diffing isn't a critical feature, we just ignore the failure. # This can go away once FileAvoidWrite uses io.BytesIO and # io.StringIO. But that will require a lot of work. except (UnicodeDecodeError, UnicodeEncodeError): self.diff = 'Binary or non-ascii file changed: %s' % self.name return existed, True
[ "def", "close", "(", "self", ")", ":", "buf", "=", "self", ".", "getvalue", "(", ")", "StringIO", ".", "close", "(", "self", ")", "existed", "=", "False", "old_content", "=", "None", "try", ":", "existing", "=", "open", "(", "self", ".", "name", ",", "'rU'", ")", "existed", "=", "True", "except", "IOError", ":", "pass", "else", ":", "try", ":", "old_content", "=", "existing", ".", "read", "(", ")", "if", "old_content", "==", "buf", ":", "return", "True", ",", "False", "except", "IOError", ":", "pass", "finally", ":", "existing", ".", "close", "(", ")", "ensureParentDir", "(", "self", ".", "name", ")", "with", "open", "(", "self", ".", "name", ",", "'w'", ")", "as", "file", ":", "file", ".", "write", "(", "buf", ")", "if", "self", ".", "_capture_diff", ":", "try", ":", "old_lines", "=", "old_content", ".", "splitlines", "(", ")", "if", "old_content", "else", "[", "]", "new_lines", "=", "buf", ".", "splitlines", "(", ")", "self", ".", "diff", "=", "difflib", ".", "unified_diff", "(", "old_lines", ",", "new_lines", ",", "self", ".", "name", ",", "self", ".", "name", ",", "n", "=", "4", ",", "lineterm", "=", "''", ")", "# FileAvoidWrite isn't unicode/bytes safe. So, files with non-ascii", "# content or opened and written in different modes may involve", "# implicit conversion and this will make Python unhappy. Since", "# diffing isn't a critical feature, we just ignore the failure.", "# This can go away once FileAvoidWrite uses io.BytesIO and", "# io.StringIO. But that will require a lot of work.", "except", "(", "UnicodeDecodeError", ",", "UnicodeEncodeError", ")", ":", "self", ".", "diff", "=", "'Binary or non-ascii file changed: %s'", "%", "self", ".", "name", "return", "existed", ",", "True" ]
https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/python/mozbuild/mozbuild/util.py#L116-L167
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/profiler/internal/flops_registry.py
python
_list_product
(lst)
return result
Computes product of element of the list.
Computes product of element of the list.
[ "Computes", "product", "of", "element", "of", "the", "list", "." ]
def _list_product(lst): """Computes product of element of the list.""" result = 1 for item in lst: result *= item return result
[ "def", "_list_product", "(", "lst", ")", ":", "result", "=", "1", "for", "item", "in", "lst", ":", "result", "*=", "item", "return", "result" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/profiler/internal/flops_registry.py#L52-L57
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/scipy/sparse/sputils.py
python
upcast_char
(*args)
return t
Same as `upcast` but taking dtype.char as input (faster).
Same as `upcast` but taking dtype.char as input (faster).
[ "Same", "as", "upcast", "but", "taking", "dtype", ".", "char", "as", "input", "(", "faster", ")", "." ]
def upcast_char(*args): """Same as `upcast` but taking dtype.char as input (faster).""" t = _upcast_memo.get(args) if t is not None: return t t = upcast(*map(np.dtype, args)) _upcast_memo[args] = t return t
[ "def", "upcast_char", "(", "*", "args", ")", ":", "t", "=", "_upcast_memo", ".", "get", "(", "args", ")", "if", "t", "is", "not", "None", ":", "return", "t", "t", "=", "upcast", "(", "*", "map", "(", "np", ".", "dtype", ",", "args", ")", ")", "_upcast_memo", "[", "args", "]", "=", "t", "return", "t" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/sparse/sputils.py#L62-L69
mapnik/mapnik
f3da900c355e1d15059c4a91b00203dcc9d9f0ef
scons/scons-local-4.1.0/SCons/Builder.py
python
DictCmdGenerator.add_action
(self, suffix, action)
Add a suffix-action pair to the mapping.
Add a suffix-action pair to the mapping.
[ "Add", "a", "suffix", "-", "action", "pair", "to", "the", "mapping", "." ]
def add_action(self, suffix, action): """Add a suffix-action pair to the mapping. """ self[suffix] = action
[ "def", "add_action", "(", "self", ",", "suffix", ",", "action", ")", ":", "self", "[", "suffix", "]", "=", "action" ]
https://github.com/mapnik/mapnik/blob/f3da900c355e1d15059c4a91b00203dcc9d9f0ef/scons/scons-local-4.1.0/SCons/Builder.py#L140-L143
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
torch/cuda/_utils.py
python
_get_device_index
(device: Any, optional: bool = False, allow_cpu: bool = False)
return _torch_get_device_index(device, optional, allow_cpu)
r"""Gets the device index from :attr:`device`, which can be a torch.device object, a Python integer, or ``None``. If :attr:`device` is a torch.device object, returns the device index if it is a CUDA device. Note that for a CUDA device without a specified index, i.e., ``torch.device('cuda')``, this will return the current default CUDA device if :attr:`optional` is ``True``. If :attr:`allow_cpu` is ``True``, CPU devices will be accepted and ``-1`` will be returned in this case. If :attr:`device` is a Python integer, it is returned as is. If :attr:`device` is ``None``, this will return the current default CUDA device if :attr:`optional` is ``True``.
r"""Gets the device index from :attr:`device`, which can be a torch.device object, a Python integer, or ``None``.
[ "r", "Gets", "the", "device", "index", "from", ":", "attr", ":", "device", "which", "can", "be", "a", "torch", ".", "device", "object", "a", "Python", "integer", "or", "None", "." ]
def _get_device_index(device: Any, optional: bool = False, allow_cpu: bool = False) -> int: r"""Gets the device index from :attr:`device`, which can be a torch.device object, a Python integer, or ``None``. If :attr:`device` is a torch.device object, returns the device index if it is a CUDA device. Note that for a CUDA device without a specified index, i.e., ``torch.device('cuda')``, this will return the current default CUDA device if :attr:`optional` is ``True``. If :attr:`allow_cpu` is ``True``, CPU devices will be accepted and ``-1`` will be returned in this case. If :attr:`device` is a Python integer, it is returned as is. If :attr:`device` is ``None``, this will return the current default CUDA device if :attr:`optional` is ``True``. """ if isinstance(device, str): device = torch.device(device) if isinstance(device, torch.device): if allow_cpu: if device.type not in ['cuda', 'cpu']: raise ValueError('Expected a cuda or cpu device, but got: {}'.format(device)) elif device.type != 'cuda': raise ValueError('Expected a cuda device, but got: {}'.format(device)) if not torch.jit.is_scripting(): if isinstance(device, torch.cuda.device): return device.idx return _torch_get_device_index(device, optional, allow_cpu)
[ "def", "_get_device_index", "(", "device", ":", "Any", ",", "optional", ":", "bool", "=", "False", ",", "allow_cpu", ":", "bool", "=", "False", ")", "->", "int", ":", "if", "isinstance", "(", "device", ",", "str", ")", ":", "device", "=", "torch", ".", "device", "(", "device", ")", "if", "isinstance", "(", "device", ",", "torch", ".", "device", ")", ":", "if", "allow_cpu", ":", "if", "device", ".", "type", "not", "in", "[", "'cuda'", ",", "'cpu'", "]", ":", "raise", "ValueError", "(", "'Expected a cuda or cpu device, but got: {}'", ".", "format", "(", "device", ")", ")", "elif", "device", ".", "type", "!=", "'cuda'", ":", "raise", "ValueError", "(", "'Expected a cuda device, but got: {}'", ".", "format", "(", "device", ")", ")", "if", "not", "torch", ".", "jit", ".", "is_scripting", "(", ")", ":", "if", "isinstance", "(", "device", ",", "torch", ".", "cuda", ".", "device", ")", ":", "return", "device", ".", "idx", "return", "_torch_get_device_index", "(", "device", ",", "optional", ",", "allow_cpu", ")" ]
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/cuda/_utils.py#L7-L34
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/external/bazel_tools/tools/android/merge_manifests.py
python
MergeManifests._ReplaceArgumentPlaceholders
(self, dom)
Replaces argument placeholders with their values. Modifies the attribute values of the input node. Args: dom: Xml node that should get placeholders replaced.
Replaces argument placeholders with their values.
[ "Replaces", "argument", "placeholders", "with", "their", "values", "." ]
def _ReplaceArgumentPlaceholders(self, dom): """Replaces argument placeholders with their values. Modifies the attribute values of the input node. Args: dom: Xml node that should get placeholders replaced. """ placeholders = { 'packageName': self._merger_dom.getElementsByTagName( self._MANIFEST).item(0).getAttribute(self._PACKAGE), } for element in dom.getElementsByTagName('*'): for i in range(element.attributes.length): attr = element.attributes.item(i) attr.value = self._ReplaceArgumentHelper(placeholders, attr.value)
[ "def", "_ReplaceArgumentPlaceholders", "(", "self", ",", "dom", ")", ":", "placeholders", "=", "{", "'packageName'", ":", "self", ".", "_merger_dom", ".", "getElementsByTagName", "(", "self", ".", "_MANIFEST", ")", ".", "item", "(", "0", ")", ".", "getAttribute", "(", "self", ".", "_PACKAGE", ")", ",", "}", "for", "element", "in", "dom", ".", "getElementsByTagName", "(", "'*'", ")", ":", "for", "i", "in", "range", "(", "element", ".", "attributes", ".", "length", ")", ":", "attr", "=", "element", ".", "attributes", ".", "item", "(", "i", ")", "attr", ".", "value", "=", "self", ".", "_ReplaceArgumentHelper", "(", "placeholders", ",", "attr", ".", "value", ")" ]
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/external/bazel_tools/tools/android/merge_manifests.py#L253-L270
apache/arrow
af33dd1157eb8d7d9bfac25ebf61445b793b7943
python/pyarrow/dataset.py
python
parquet_dataset
(metadata_path, schema=None, filesystem=None, format=None, partitioning=None, partition_base_dir=None)
return factory.finish(schema)
Create a FileSystemDataset from a `_metadata` file created via `pyarrrow.parquet.write_metadata`. Parameters ---------- metadata_path : path, Path pointing to a single file parquet metadata file schema : Schema, optional Optionally provide the Schema for the Dataset, in which case it will not be inferred from the source. filesystem : FileSystem or URI string, default None If a single path is given as source and filesystem is None, then the filesystem will be inferred from the path. If an URI string is passed, then a filesystem object is constructed using the URI's optional path component as a directory prefix. See the examples below. Note that the URIs on Windows must follow 'file:///C:...' or 'file:/C:...' patterns. format : ParquetFileFormat An instance of a ParquetFileFormat if special options needs to be passed. partitioning : Partitioning, PartitioningFactory, str, list of str The partitioning scheme specified with the ``partitioning()`` function. A flavor string can be used as shortcut, and with a list of field names a DirectionaryPartitioning will be inferred. partition_base_dir : str, optional For the purposes of applying the partitioning, paths will be stripped of the partition_base_dir. Files not matching the partition_base_dir prefix will be skipped for partitioning discovery. The ignored files will still be part of the Dataset, but will not have partition information. Returns ------- FileSystemDataset
Create a FileSystemDataset from a `_metadata` file created via `pyarrrow.parquet.write_metadata`.
[ "Create", "a", "FileSystemDataset", "from", "a", "_metadata", "file", "created", "via", "pyarrrow", ".", "parquet", ".", "write_metadata", "." ]
def parquet_dataset(metadata_path, schema=None, filesystem=None, format=None, partitioning=None, partition_base_dir=None): """ Create a FileSystemDataset from a `_metadata` file created via `pyarrrow.parquet.write_metadata`. Parameters ---------- metadata_path : path, Path pointing to a single file parquet metadata file schema : Schema, optional Optionally provide the Schema for the Dataset, in which case it will not be inferred from the source. filesystem : FileSystem or URI string, default None If a single path is given as source and filesystem is None, then the filesystem will be inferred from the path. If an URI string is passed, then a filesystem object is constructed using the URI's optional path component as a directory prefix. See the examples below. Note that the URIs on Windows must follow 'file:///C:...' or 'file:/C:...' patterns. format : ParquetFileFormat An instance of a ParquetFileFormat if special options needs to be passed. partitioning : Partitioning, PartitioningFactory, str, list of str The partitioning scheme specified with the ``partitioning()`` function. A flavor string can be used as shortcut, and with a list of field names a DirectionaryPartitioning will be inferred. partition_base_dir : str, optional For the purposes of applying the partitioning, paths will be stripped of the partition_base_dir. Files not matching the partition_base_dir prefix will be skipped for partitioning discovery. The ignored files will still be part of the Dataset, but will not have partition information. Returns ------- FileSystemDataset """ from pyarrow.fs import LocalFileSystem, _ensure_filesystem if format is None: format = ParquetFileFormat() elif not isinstance(format, ParquetFileFormat): raise ValueError("format argument must be a ParquetFileFormat") if filesystem is None: filesystem = LocalFileSystem() else: filesystem = _ensure_filesystem(filesystem) metadata_path = filesystem.normalize_path(_stringify_path(metadata_path)) options = ParquetFactoryOptions( partition_base_dir=partition_base_dir, partitioning=_ensure_partitioning(partitioning) ) factory = ParquetDatasetFactory( metadata_path, filesystem, format, options=options) return factory.finish(schema)
[ "def", "parquet_dataset", "(", "metadata_path", ",", "schema", "=", "None", ",", "filesystem", "=", "None", ",", "format", "=", "None", ",", "partitioning", "=", "None", ",", "partition_base_dir", "=", "None", ")", ":", "from", "pyarrow", ".", "fs", "import", "LocalFileSystem", ",", "_ensure_filesystem", "if", "format", "is", "None", ":", "format", "=", "ParquetFileFormat", "(", ")", "elif", "not", "isinstance", "(", "format", ",", "ParquetFileFormat", ")", ":", "raise", "ValueError", "(", "\"format argument must be a ParquetFileFormat\"", ")", "if", "filesystem", "is", "None", ":", "filesystem", "=", "LocalFileSystem", "(", ")", "else", ":", "filesystem", "=", "_ensure_filesystem", "(", "filesystem", ")", "metadata_path", "=", "filesystem", ".", "normalize_path", "(", "_stringify_path", "(", "metadata_path", ")", ")", "options", "=", "ParquetFactoryOptions", "(", "partition_base_dir", "=", "partition_base_dir", ",", "partitioning", "=", "_ensure_partitioning", "(", "partitioning", ")", ")", "factory", "=", "ParquetDatasetFactory", "(", "metadata_path", ",", "filesystem", ",", "format", ",", "options", "=", "options", ")", "return", "factory", ".", "finish", "(", "schema", ")" ]
https://github.com/apache/arrow/blob/af33dd1157eb8d7d9bfac25ebf61445b793b7943/python/pyarrow/dataset.py#L449-L508
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/build/waf-1.7.13/waflib/extras/review.py
python
ReviewContext.format_option
(self, name, help, actual, default, term_width)
return out
Return the string representing the option specified.
Return the string representing the option specified.
[ "Return", "the", "string", "representing", "the", "option", "specified", "." ]
def format_option(self, name, help, actual, default, term_width): """ Return the string representing the option specified. """ def val_to_str(val): if val == None or val == '': return "(void)" return str(val) max_name_len = 20 sep_len = 2 w = textwrap.TextWrapper() w.width = term_width - 1 if w.width < 60: w.width = 60 out = "" # format the help out += w.fill(help) + "\n" # format the name name_len = len(name) out += Logs.colors.CYAN + name + Logs.colors.NORMAL # set the indentation used when the value wraps to the next line w.subsequent_indent = " ".rjust(max_name_len + sep_len) w.width -= (max_name_len + sep_len) # the name string is too long, switch to the next line if name_len > max_name_len: out += "\n" + w.subsequent_indent # fill the remaining of the line with spaces else: out += " ".rjust(max_name_len + sep_len - name_len) # format the actual value, if there is one if actual != None: out += Logs.colors.BOLD + w.fill(val_to_str(actual)) + Logs.colors.NORMAL + "\n" + w.subsequent_indent # format the default value default_fmt = val_to_str(default) if actual != None: default_fmt = "default: " + default_fmt out += Logs.colors.NORMAL + w.fill(default_fmt) + Logs.colors.NORMAL return out
[ "def", "format_option", "(", "self", ",", "name", ",", "help", ",", "actual", ",", "default", ",", "term_width", ")", ":", "def", "val_to_str", "(", "val", ")", ":", "if", "val", "==", "None", "or", "val", "==", "''", ":", "return", "\"(void)\"", "return", "str", "(", "val", ")", "max_name_len", "=", "20", "sep_len", "=", "2", "w", "=", "textwrap", ".", "TextWrapper", "(", ")", "w", ".", "width", "=", "term_width", "-", "1", "if", "w", ".", "width", "<", "60", ":", "w", ".", "width", "=", "60", "out", "=", "\"\"", "# format the help", "out", "+=", "w", ".", "fill", "(", "help", ")", "+", "\"\\n\"", "# format the name", "name_len", "=", "len", "(", "name", ")", "out", "+=", "Logs", ".", "colors", ".", "CYAN", "+", "name", "+", "Logs", ".", "colors", ".", "NORMAL", "# set the indentation used when the value wraps to the next line", "w", ".", "subsequent_indent", "=", "\" \"", ".", "rjust", "(", "max_name_len", "+", "sep_len", ")", "w", ".", "width", "-=", "(", "max_name_len", "+", "sep_len", ")", "# the name string is too long, switch to the next line", "if", "name_len", ">", "max_name_len", ":", "out", "+=", "\"\\n\"", "+", "w", ".", "subsequent_indent", "# fill the remaining of the line with spaces", "else", ":", "out", "+=", "\" \"", ".", "rjust", "(", "max_name_len", "+", "sep_len", "-", "name_len", ")", "# format the actual value, if there is one", "if", "actual", "!=", "None", ":", "out", "+=", "Logs", ".", "colors", ".", "BOLD", "+", "w", ".", "fill", "(", "val_to_str", "(", "actual", ")", ")", "+", "Logs", ".", "colors", ".", "NORMAL", "+", "\"\\n\"", "+", "w", ".", "subsequent_indent", "# format the default value", "default_fmt", "=", "val_to_str", "(", "default", ")", "if", "actual", "!=", "None", ":", "default_fmt", "=", "\"default: \"", "+", "default_fmt", "out", "+=", "Logs", ".", "colors", ".", "NORMAL", "+", "w", ".", "fill", "(", "default_fmt", ")", "+", "Logs", ".", "colors", ".", "NORMAL", "return", "out" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/build/waf-1.7.13/waflib/extras/review.py#L273-L320
simsong/bulk_extractor
738911df22b7066ca9e1662f4131fb44090a4196
python/dfxml.py
python
extentdb.run_for_sector
(self,sector_number,count=1)
return byte_run(len=count*self.sectorsize,img_offset=sector_number * self.sectorsize)
Returns the run for a specified sector, and optionally a count of sectors
Returns the run for a specified sector, and optionally a count of sectors
[ "Returns", "the", "run", "for", "a", "specified", "sector", "and", "optionally", "a", "count", "of", "sectors" ]
def run_for_sector(self,sector_number,count=1): """Returns the run for a specified sector, and optionally a count of sectors""" return byte_run(len=count*self.sectorsize,img_offset=sector_number * self.sectorsize)
[ "def", "run_for_sector", "(", "self", ",", "sector_number", ",", "count", "=", "1", ")", ":", "return", "byte_run", "(", "len", "=", "count", "*", "self", ".", "sectorsize", ",", "img_offset", "=", "sector_number", "*", "self", ".", "sectorsize", ")" ]
https://github.com/simsong/bulk_extractor/blob/738911df22b7066ca9e1662f4131fb44090a4196/python/dfxml.py#L1420-L1422
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/_pydecimal.py
python
Decimal.__add__
(self, other, context=None)
return ans
Returns self + other. -INF + INF (or the reverse) cause InvalidOperation errors.
Returns self + other.
[ "Returns", "self", "+", "other", "." ]
def __add__(self, other, context=None): """Returns self + other. -INF + INF (or the reverse) cause InvalidOperation errors. """ other = _convert_other(other) if other is NotImplemented: return other if context is None: context = getcontext() if self._is_special or other._is_special: ans = self._check_nans(other, context) if ans: return ans if self._isinfinity(): # If both INF, same sign => same as both, opposite => error. if self._sign != other._sign and other._isinfinity(): return context._raise_error(InvalidOperation, '-INF + INF') return Decimal(self) if other._isinfinity(): return Decimal(other) # Can't both be infinity here exp = min(self._exp, other._exp) negativezero = 0 if context.rounding == ROUND_FLOOR and self._sign != other._sign: # If the answer is 0, the sign should be negative, in this case. negativezero = 1 if not self and not other: sign = min(self._sign, other._sign) if negativezero: sign = 1 ans = _dec_from_triple(sign, '0', exp) ans = ans._fix(context) return ans if not self: exp = max(exp, other._exp - context.prec-1) ans = other._rescale(exp, context.rounding) ans = ans._fix(context) return ans if not other: exp = max(exp, self._exp - context.prec-1) ans = self._rescale(exp, context.rounding) ans = ans._fix(context) return ans op1 = _WorkRep(self) op2 = _WorkRep(other) op1, op2 = _normalize(op1, op2, context.prec) result = _WorkRep() if op1.sign != op2.sign: # Equal and opposite if op1.int == op2.int: ans = _dec_from_triple(negativezero, '0', exp) ans = ans._fix(context) return ans if op1.int < op2.int: op1, op2 = op2, op1 # OK, now abs(op1) > abs(op2) if op1.sign == 1: result.sign = 1 op1.sign, op2.sign = op2.sign, op1.sign else: result.sign = 0 # So we know the sign, and op1 > 0. elif op1.sign == 1: result.sign = 1 op1.sign, op2.sign = (0, 0) else: result.sign = 0 # Now, op1 > abs(op2) > 0 if op2.sign == 0: result.int = op1.int + op2.int else: result.int = op1.int - op2.int result.exp = op1.exp ans = Decimal(result) ans = ans._fix(context) return ans
[ "def", "__add__", "(", "self", ",", "other", ",", "context", "=", "None", ")", ":", "other", "=", "_convert_other", "(", "other", ")", "if", "other", "is", "NotImplemented", ":", "return", "other", "if", "context", "is", "None", ":", "context", "=", "getcontext", "(", ")", "if", "self", ".", "_is_special", "or", "other", ".", "_is_special", ":", "ans", "=", "self", ".", "_check_nans", "(", "other", ",", "context", ")", "if", "ans", ":", "return", "ans", "if", "self", ".", "_isinfinity", "(", ")", ":", "# If both INF, same sign => same as both, opposite => error.", "if", "self", ".", "_sign", "!=", "other", ".", "_sign", "and", "other", ".", "_isinfinity", "(", ")", ":", "return", "context", ".", "_raise_error", "(", "InvalidOperation", ",", "'-INF + INF'", ")", "return", "Decimal", "(", "self", ")", "if", "other", ".", "_isinfinity", "(", ")", ":", "return", "Decimal", "(", "other", ")", "# Can't both be infinity here", "exp", "=", "min", "(", "self", ".", "_exp", ",", "other", ".", "_exp", ")", "negativezero", "=", "0", "if", "context", ".", "rounding", "==", "ROUND_FLOOR", "and", "self", ".", "_sign", "!=", "other", ".", "_sign", ":", "# If the answer is 0, the sign should be negative, in this case.", "negativezero", "=", "1", "if", "not", "self", "and", "not", "other", ":", "sign", "=", "min", "(", "self", ".", "_sign", ",", "other", ".", "_sign", ")", "if", "negativezero", ":", "sign", "=", "1", "ans", "=", "_dec_from_triple", "(", "sign", ",", "'0'", ",", "exp", ")", "ans", "=", "ans", ".", "_fix", "(", "context", ")", "return", "ans", "if", "not", "self", ":", "exp", "=", "max", "(", "exp", ",", "other", ".", "_exp", "-", "context", ".", "prec", "-", "1", ")", "ans", "=", "other", ".", "_rescale", "(", "exp", ",", "context", ".", "rounding", ")", "ans", "=", "ans", ".", "_fix", "(", "context", ")", "return", "ans", "if", "not", "other", ":", "exp", "=", "max", "(", "exp", ",", "self", ".", "_exp", "-", "context", ".", "prec", "-", "1", ")", "ans", "=", "self", ".", "_rescale", "(", "exp", ",", "context", ".", "rounding", ")", "ans", "=", "ans", ".", "_fix", "(", "context", ")", "return", "ans", "op1", "=", "_WorkRep", "(", "self", ")", "op2", "=", "_WorkRep", "(", "other", ")", "op1", ",", "op2", "=", "_normalize", "(", "op1", ",", "op2", ",", "context", ".", "prec", ")", "result", "=", "_WorkRep", "(", ")", "if", "op1", ".", "sign", "!=", "op2", ".", "sign", ":", "# Equal and opposite", "if", "op1", ".", "int", "==", "op2", ".", "int", ":", "ans", "=", "_dec_from_triple", "(", "negativezero", ",", "'0'", ",", "exp", ")", "ans", "=", "ans", ".", "_fix", "(", "context", ")", "return", "ans", "if", "op1", ".", "int", "<", "op2", ".", "int", ":", "op1", ",", "op2", "=", "op2", ",", "op1", "# OK, now abs(op1) > abs(op2)", "if", "op1", ".", "sign", "==", "1", ":", "result", ".", "sign", "=", "1", "op1", ".", "sign", ",", "op2", ".", "sign", "=", "op2", ".", "sign", ",", "op1", ".", "sign", "else", ":", "result", ".", "sign", "=", "0", "# So we know the sign, and op1 > 0.", "elif", "op1", ".", "sign", "==", "1", ":", "result", ".", "sign", "=", "1", "op1", ".", "sign", ",", "op2", ".", "sign", "=", "(", "0", ",", "0", ")", "else", ":", "result", ".", "sign", "=", "0", "# Now, op1 > abs(op2) > 0", "if", "op2", ".", "sign", "==", "0", ":", "result", ".", "int", "=", "op1", ".", "int", "+", "op2", ".", "int", "else", ":", "result", ".", "int", "=", "op1", ".", "int", "-", "op2", ".", "int", "result", ".", "exp", "=", "op1", ".", "exp", "ans", "=", "Decimal", "(", "result", ")", "ans", "=", "ans", ".", "_fix", "(", "context", ")", "return", "ans" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/_pydecimal.py#L1157-L1241
Harick1/caffe-yolo
eea92bf3ddfe4d0ff6b0b3ba9b15c029a83ed9a3
scripts/cpp_lint.py
python
_ClassifyInclude
(fileinfo, include, is_system)
return _OTHER_HEADER
Figures out what kind of header 'include' is. Args: fileinfo: The current file cpplint is running over. A FileInfo instance. include: The path to a #included file. is_system: True if the #include used <> rather than "". Returns: One of the _XXX_HEADER constants. For example: >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'stdio.h', True) _C_SYS_HEADER >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'string', True) _CPP_SYS_HEADER >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/foo.h', False) _LIKELY_MY_HEADER >>> _ClassifyInclude(FileInfo('foo/foo_unknown_extension.cc'), ... 'bar/foo_other_ext.h', False) _POSSIBLE_MY_HEADER >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/bar.h', False) _OTHER_HEADER
Figures out what kind of header 'include' is.
[ "Figures", "out", "what", "kind", "of", "header", "include", "is", "." ]
def _ClassifyInclude(fileinfo, include, is_system): """Figures out what kind of header 'include' is. Args: fileinfo: The current file cpplint is running over. A FileInfo instance. include: The path to a #included file. is_system: True if the #include used <> rather than "". Returns: One of the _XXX_HEADER constants. For example: >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'stdio.h', True) _C_SYS_HEADER >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'string', True) _CPP_SYS_HEADER >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/foo.h', False) _LIKELY_MY_HEADER >>> _ClassifyInclude(FileInfo('foo/foo_unknown_extension.cc'), ... 'bar/foo_other_ext.h', False) _POSSIBLE_MY_HEADER >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/bar.h', False) _OTHER_HEADER """ # This is a list of all standard c++ header files, except # those already checked for above. is_cpp_h = include in _CPP_HEADERS if is_system: if is_cpp_h: return _CPP_SYS_HEADER else: return _C_SYS_HEADER # If the target file and the include we're checking share a # basename when we drop common extensions, and the include # lives in . , then it's likely to be owned by the target file. target_dir, target_base = ( os.path.split(_DropCommonSuffixes(fileinfo.RepositoryName()))) include_dir, include_base = os.path.split(_DropCommonSuffixes(include)) if target_base == include_base and ( include_dir == target_dir or include_dir == os.path.normpath(target_dir + '/../public')): return _LIKELY_MY_HEADER # If the target and include share some initial basename # component, it's possible the target is implementing the # include, so it's allowed to be first, but we'll never # complain if it's not there. target_first_component = _RE_FIRST_COMPONENT.match(target_base) include_first_component = _RE_FIRST_COMPONENT.match(include_base) if (target_first_component and include_first_component and target_first_component.group(0) == include_first_component.group(0)): return _POSSIBLE_MY_HEADER return _OTHER_HEADER
[ "def", "_ClassifyInclude", "(", "fileinfo", ",", "include", ",", "is_system", ")", ":", "# This is a list of all standard c++ header files, except", "# those already checked for above.", "is_cpp_h", "=", "include", "in", "_CPP_HEADERS", "if", "is_system", ":", "if", "is_cpp_h", ":", "return", "_CPP_SYS_HEADER", "else", ":", "return", "_C_SYS_HEADER", "# If the target file and the include we're checking share a", "# basename when we drop common extensions, and the include", "# lives in . , then it's likely to be owned by the target file.", "target_dir", ",", "target_base", "=", "(", "os", ".", "path", ".", "split", "(", "_DropCommonSuffixes", "(", "fileinfo", ".", "RepositoryName", "(", ")", ")", ")", ")", "include_dir", ",", "include_base", "=", "os", ".", "path", ".", "split", "(", "_DropCommonSuffixes", "(", "include", ")", ")", "if", "target_base", "==", "include_base", "and", "(", "include_dir", "==", "target_dir", "or", "include_dir", "==", "os", ".", "path", ".", "normpath", "(", "target_dir", "+", "'/../public'", ")", ")", ":", "return", "_LIKELY_MY_HEADER", "# If the target and include share some initial basename", "# component, it's possible the target is implementing the", "# include, so it's allowed to be first, but we'll never", "# complain if it's not there.", "target_first_component", "=", "_RE_FIRST_COMPONENT", ".", "match", "(", "target_base", ")", "include_first_component", "=", "_RE_FIRST_COMPONENT", ".", "match", "(", "include_base", ")", "if", "(", "target_first_component", "and", "include_first_component", "and", "target_first_component", ".", "group", "(", "0", ")", "==", "include_first_component", ".", "group", "(", "0", ")", ")", ":", "return", "_POSSIBLE_MY_HEADER", "return", "_OTHER_HEADER" ]
https://github.com/Harick1/caffe-yolo/blob/eea92bf3ddfe4d0ff6b0b3ba9b15c029a83ed9a3/scripts/cpp_lint.py#L3620-L3676
AngoraFuzzer/Angora
80e81c8590077bc0ac069dbd367da8ce405ff618
llvm_mode/dfsan_rt/sanitizer_common/scripts/cpplint.py
python
_OutputFormat
()
return _cpplint_state.output_format
Gets the module's output format.
Gets the module's output format.
[ "Gets", "the", "module", "s", "output", "format", "." ]
def _OutputFormat(): """Gets the module's output format.""" return _cpplint_state.output_format
[ "def", "_OutputFormat", "(", ")", ":", "return", "_cpplint_state", ".", "output_format" ]
https://github.com/AngoraFuzzer/Angora/blob/80e81c8590077bc0ac069dbd367da8ce405ff618/llvm_mode/dfsan_rt/sanitizer_common/scripts/cpplint.py#L631-L633
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/customtreectrl.py
python
CustomTreeCtrl.AssignButtonsImageList
(self, imageList)
Assigns the button image list. :param `imageList`: an instance of :class:`ImageList`.
Assigns the button image list.
[ "Assigns", "the", "button", "image", "list", "." ]
def AssignButtonsImageList(self, imageList): """ Assigns the button image list. :param `imageList`: an instance of :class:`ImageList`. """ self.SetButtonsImageList(imageList) self._ownsImageListButtons = True
[ "def", "AssignButtonsImageList", "(", "self", ",", "imageList", ")", ":", "self", ".", "SetButtonsImageList", "(", "imageList", ")", "self", ".", "_ownsImageListButtons", "=", "True" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/customtreectrl.py#L6248-L6256
hpi-xnor/BMXNet
ed0b201da6667887222b8e4b5f997c4f6b61943d
python/mxnet/ndarray/ndarray.py
python
NDArray.log2
(self, *args, **kwargs)
return op.log2(self, *args, **kwargs)
Convenience fluent method for :py:func:`log2`. The arguments are the same as for :py:func:`log2`, with this array as data.
Convenience fluent method for :py:func:`log2`.
[ "Convenience", "fluent", "method", "for", ":", "py", ":", "func", ":", "log2", "." ]
def log2(self, *args, **kwargs): """Convenience fluent method for :py:func:`log2`. The arguments are the same as for :py:func:`log2`, with this array as data. """ return op.log2(self, *args, **kwargs)
[ "def", "log2", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "op", ".", "log2", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/hpi-xnor/BMXNet/blob/ed0b201da6667887222b8e4b5f997c4f6b61943d/python/mxnet/ndarray/ndarray.py#L1452-L1458
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
scripts/CrystalTools/PeakReport.py
python
PeakReport.set_show_background
(self, show_background)
Arguments: show_background -- True to show background
Arguments: show_background -- True to show background
[ "Arguments", ":", "show_background", "--", "True", "to", "show", "background" ]
def set_show_background(self, show_background): """ Arguments: show_background -- True to show background """ self.__show_background = show_background
[ "def", "set_show_background", "(", "self", ",", "show_background", ")", ":", "self", ".", "__show_background", "=", "show_background" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/CrystalTools/PeakReport.py#L59-L64
smartdevicelink/sdl_core
68f082169e0a40fccd9eb0db3c83911c28870f07
tools/infrastructure/api_compare.py
python
console_print
(summary_result)
Function which prints summary result to console
Function which prints summary result to console
[ "Function", "which", "prints", "summary", "result", "to", "console" ]
def console_print(summary_result): """Function which prints summary result to console""" for rpc_name in sorted(summary_result.keys()): print("\n" + "---" * 60) print(colors.HEADER + rpc_name + colors.ENDC) for problematic_item in summary_result[rpc_name]: item = summary_result[rpc_name][problematic_item] if len(item) > 0: print(colors.UNDERLINE + problematic_item + colors.ENDC) if type(item) is not dict: print("{}{}{}".format(colors.WARN, item, colors.ENDC)) elif type(item) is dict: for param in item.keys(): item_print = colors.UNDERLINE + param + colors.ENDC print("{} {}".format("Parameter name: ", item_print)) res_val = item[param] for key in res_val: print(key, ":", colors.FAIL, res_val[key], colors.ENDC)
[ "def", "console_print", "(", "summary_result", ")", ":", "for", "rpc_name", "in", "sorted", "(", "summary_result", ".", "keys", "(", ")", ")", ":", "print", "(", "\"\\n\"", "+", "\"---\"", "*", "60", ")", "print", "(", "colors", ".", "HEADER", "+", "rpc_name", "+", "colors", ".", "ENDC", ")", "for", "problematic_item", "in", "summary_result", "[", "rpc_name", "]", ":", "item", "=", "summary_result", "[", "rpc_name", "]", "[", "problematic_item", "]", "if", "len", "(", "item", ")", ">", "0", ":", "print", "(", "colors", ".", "UNDERLINE", "+", "problematic_item", "+", "colors", ".", "ENDC", ")", "if", "type", "(", "item", ")", "is", "not", "dict", ":", "print", "(", "\"{}{}{}\"", ".", "format", "(", "colors", ".", "WARN", ",", "item", ",", "colors", ".", "ENDC", ")", ")", "elif", "type", "(", "item", ")", "is", "dict", ":", "for", "param", "in", "item", ".", "keys", "(", ")", ":", "item_print", "=", "colors", ".", "UNDERLINE", "+", "param", "+", "colors", ".", "ENDC", "print", "(", "\"{} {}\"", ".", "format", "(", "\"Parameter name: \"", ",", "item_print", ")", ")", "res_val", "=", "item", "[", "param", "]", "for", "key", "in", "res_val", ":", "print", "(", "key", ",", "\":\"", ",", "colors", ".", "FAIL", ",", "res_val", "[", "key", "]", ",", "colors", ".", "ENDC", ")" ]
https://github.com/smartdevicelink/sdl_core/blob/68f082169e0a40fccd9eb0db3c83911c28870f07/tools/infrastructure/api_compare.py#L234-L251
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
src/external/boost/boost_1_68_0/tools/build/src/build/property.py
python
validate
(properties)
Exit with error if any of the properties is not valid. properties may be a single property or a sequence of properties.
Exit with error if any of the properties is not valid. properties may be a single property or a sequence of properties.
[ "Exit", "with", "error", "if", "any", "of", "the", "properties", "is", "not", "valid", ".", "properties", "may", "be", "a", "single", "property", "or", "a", "sequence", "of", "properties", "." ]
def validate (properties): """ Exit with error if any of the properties is not valid. properties may be a single property or a sequence of properties. """ if isinstance(properties, Property): properties = [properties] assert is_iterable_typed(properties, Property) for p in properties: __validate1(p)
[ "def", "validate", "(", "properties", ")", ":", "if", "isinstance", "(", "properties", ",", "Property", ")", ":", "properties", "=", "[", "properties", "]", "assert", "is_iterable_typed", "(", "properties", ",", "Property", ")", "for", "p", "in", "properties", ":", "__validate1", "(", "p", ")" ]
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/external/boost/boost_1_68_0/tools/build/src/build/property.py#L356-L364
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/numpy_support.py
python
ufunc_can_cast
(from_, to, has_mixed_inputs, casting='safe')
return np.can_cast(from_, to, casting)
A variant of np.can_cast() that can allow casting any integer to any real or complex type, in case the operation has mixed-kind inputs. For example we want `np.power(float32, int32)` to be computed using SP arithmetic and return `float32`. However, `np.sqrt(int32)` should use DP arithmetic and return `float64`.
A variant of np.can_cast() that can allow casting any integer to any real or complex type, in case the operation has mixed-kind inputs.
[ "A", "variant", "of", "np", ".", "can_cast", "()", "that", "can", "allow", "casting", "any", "integer", "to", "any", "real", "or", "complex", "type", "in", "case", "the", "operation", "has", "mixed", "-", "kind", "inputs", "." ]
def ufunc_can_cast(from_, to, has_mixed_inputs, casting='safe'): """ A variant of np.can_cast() that can allow casting any integer to any real or complex type, in case the operation has mixed-kind inputs. For example we want `np.power(float32, int32)` to be computed using SP arithmetic and return `float32`. However, `np.sqrt(int32)` should use DP arithmetic and return `float64`. """ from_ = np.dtype(from_) to = np.dtype(to) if has_mixed_inputs and from_.kind in 'iu' and to.kind in 'cf': # Decide that all integers can cast to any real or complex type. return True return np.can_cast(from_, to, casting)
[ "def", "ufunc_can_cast", "(", "from_", ",", "to", ",", "has_mixed_inputs", ",", "casting", "=", "'safe'", ")", ":", "from_", "=", "np", ".", "dtype", "(", "from_", ")", "to", "=", "np", ".", "dtype", "(", "to", ")", "if", "has_mixed_inputs", "and", "from_", ".", "kind", "in", "'iu'", "and", "to", ".", "kind", "in", "'cf'", ":", "# Decide that all integers can cast to any real or complex type.", "return", "True", "return", "np", ".", "can_cast", "(", "from_", ",", "to", ",", "casting", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/numpy_support.py#L328-L343
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Tools/msi/msilib.py
python
Directory.start_component
(self, component = None, feature = None, flags = None, keyfile = None, uuid=None)
Add an entry to the Component table, and make this component the current for this directory. If no component name is given, the directory name is used. If no feature is given, the current feature is used. If no flags are given, the directory's default flags are used. If no keyfile is given, the KeyPath is left null in the Component table.
Add an entry to the Component table, and make this component the current for this directory. If no component name is given, the directory name is used. If no feature is given, the current feature is used. If no flags are given, the directory's default flags are used. If no keyfile is given, the KeyPath is left null in the Component table.
[ "Add", "an", "entry", "to", "the", "Component", "table", "and", "make", "this", "component", "the", "current", "for", "this", "directory", ".", "If", "no", "component", "name", "is", "given", "the", "directory", "name", "is", "used", ".", "If", "no", "feature", "is", "given", "the", "current", "feature", "is", "used", ".", "If", "no", "flags", "are", "given", "the", "directory", "s", "default", "flags", "are", "used", ".", "If", "no", "keyfile", "is", "given", "the", "KeyPath", "is", "left", "null", "in", "the", "Component", "table", "." ]
def start_component(self, component = None, feature = None, flags = None, keyfile = None, uuid=None): """Add an entry to the Component table, and make this component the current for this directory. If no component name is given, the directory name is used. If no feature is given, the current feature is used. If no flags are given, the directory's default flags are used. If no keyfile is given, the KeyPath is left null in the Component table.""" if flags is None: flags = self.componentflags if uuid is None: uuid = gen_uuid() else: uuid = uuid.upper() if component is None: component = self.logical self.component = component if Win64: flags |= 256 if keyfile: keyid = self.cab.gen_id(self.absolute, keyfile) self.keyfiles[keyfile] = keyid else: keyid = None add_data(self.db, "Component", [(component, uuid, self.logical, flags, None, keyid)]) if feature is None: feature = current_feature add_data(self.db, "FeatureComponents", [(feature.id, component)])
[ "def", "start_component", "(", "self", ",", "component", "=", "None", ",", "feature", "=", "None", ",", "flags", "=", "None", ",", "keyfile", "=", "None", ",", "uuid", "=", "None", ")", ":", "if", "flags", "is", "None", ":", "flags", "=", "self", ".", "componentflags", "if", "uuid", "is", "None", ":", "uuid", "=", "gen_uuid", "(", ")", "else", ":", "uuid", "=", "uuid", ".", "upper", "(", ")", "if", "component", "is", "None", ":", "component", "=", "self", ".", "logical", "self", ".", "component", "=", "component", "if", "Win64", ":", "flags", "|=", "256", "if", "keyfile", ":", "keyid", "=", "self", ".", "cab", ".", "gen_id", "(", "self", ".", "absolute", ",", "keyfile", ")", "self", ".", "keyfiles", "[", "keyfile", "]", "=", "keyid", "else", ":", "keyid", "=", "None", "add_data", "(", "self", ".", "db", ",", "\"Component\"", ",", "[", "(", "component", ",", "uuid", ",", "self", ".", "logical", ",", "flags", ",", "None", ",", "keyid", ")", "]", ")", "if", "feature", "is", "None", ":", "feature", "=", "current_feature", "add_data", "(", "self", ".", "db", ",", "\"FeatureComponents\"", ",", "[", "(", "feature", ".", "id", ",", "component", ")", "]", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Tools/msi/msilib.py#L456-L483
mongodb/mongo
d8ff665343ad29cf286ee2cf4a1960d29371937b
buildscripts/task_generation/suite_split_strategies.py
python
greedy_division
(tests_runtimes: List[TestRuntime], max_time_seconds: float, max_suites: Optional[int] = None, max_tests_per_suite: Optional[int] = None, logger: Any = LOGGER)
return [[test.test_name for test in test_list] for test_list in suites]
Divide the given tests into suites. Each suite should be able to execute in less than the max time specified. If a single test has a runtime greater than `max_time_seconds`, it will be run in a suite on its own. If max_suites is reached before assigning all tests to a suite, the remaining tests will be divided up among the created suites. Note: If `max_suites` is hit, suites may have more tests than `max_tests_per_suite` and may have runtimes longer than `max_time_seconds`. :param tests_runtimes: List of tuples containing test names and test runtimes. :param max_time_seconds: Maximum runtime to add to a single bucket. :param max_suites: Maximum number of suites to create. :param max_tests_per_suite: Maximum number of tests to add to a single suite. :param logger: Logger to write log output to. :return: List of Suite objects representing grouping of tests.
Divide the given tests into suites.
[ "Divide", "the", "given", "tests", "into", "suites", "." ]
def greedy_division(tests_runtimes: List[TestRuntime], max_time_seconds: float, max_suites: Optional[int] = None, max_tests_per_suite: Optional[int] = None, logger: Any = LOGGER) -> List[List[str]]: """ Divide the given tests into suites. Each suite should be able to execute in less than the max time specified. If a single test has a runtime greater than `max_time_seconds`, it will be run in a suite on its own. If max_suites is reached before assigning all tests to a suite, the remaining tests will be divided up among the created suites. Note: If `max_suites` is hit, suites may have more tests than `max_tests_per_suite` and may have runtimes longer than `max_time_seconds`. :param tests_runtimes: List of tuples containing test names and test runtimes. :param max_time_seconds: Maximum runtime to add to a single bucket. :param max_suites: Maximum number of suites to create. :param max_tests_per_suite: Maximum number of tests to add to a single suite. :param logger: Logger to write log output to. :return: List of Suite objects representing grouping of tests. """ suites = [] last_test_processed = len(tests_runtimes) logger.debug("Determines suites for runtime", max_runtime_seconds=max_time_seconds, max_suites=max_suites, max_tests_per_suite=max_tests_per_suite) current_test_list = [] for idx, test_instance in enumerate(tests_runtimes): logger.debug("Adding test", test=test_instance, suite_index=len(suites)) if _new_suite_needed(current_test_list, test_instance.runtime, max_time_seconds, max_tests_per_suite): logger.debug("Finished suite", test_runtime=test_instance.runtime, max_time=max_time_seconds, suite_index=len(suites)) if current_test_list: suites.append(current_test_list) current_test_list = [] if max_suites and len(suites) >= max_suites: last_test_processed = idx break current_test_list.append(test_instance) if current_test_list: suites.append(current_test_list) if max_suites and last_test_processed < len(tests_runtimes): # We must have hit the max suite limit, just randomly add the remaining tests to suites. divide_remaining_tests_among_suites(tests_runtimes[last_test_processed:], suites) return [[test.test_name for test in test_list] for test_list in suites]
[ "def", "greedy_division", "(", "tests_runtimes", ":", "List", "[", "TestRuntime", "]", ",", "max_time_seconds", ":", "float", ",", "max_suites", ":", "Optional", "[", "int", "]", "=", "None", ",", "max_tests_per_suite", ":", "Optional", "[", "int", "]", "=", "None", ",", "logger", ":", "Any", "=", "LOGGER", ")", "->", "List", "[", "List", "[", "str", "]", "]", ":", "suites", "=", "[", "]", "last_test_processed", "=", "len", "(", "tests_runtimes", ")", "logger", ".", "debug", "(", "\"Determines suites for runtime\"", ",", "max_runtime_seconds", "=", "max_time_seconds", ",", "max_suites", "=", "max_suites", ",", "max_tests_per_suite", "=", "max_tests_per_suite", ")", "current_test_list", "=", "[", "]", "for", "idx", ",", "test_instance", "in", "enumerate", "(", "tests_runtimes", ")", ":", "logger", ".", "debug", "(", "\"Adding test\"", ",", "test", "=", "test_instance", ",", "suite_index", "=", "len", "(", "suites", ")", ")", "if", "_new_suite_needed", "(", "current_test_list", ",", "test_instance", ".", "runtime", ",", "max_time_seconds", ",", "max_tests_per_suite", ")", ":", "logger", ".", "debug", "(", "\"Finished suite\"", ",", "test_runtime", "=", "test_instance", ".", "runtime", ",", "max_time", "=", "max_time_seconds", ",", "suite_index", "=", "len", "(", "suites", ")", ")", "if", "current_test_list", ":", "suites", ".", "append", "(", "current_test_list", ")", "current_test_list", "=", "[", "]", "if", "max_suites", "and", "len", "(", "suites", ")", ">=", "max_suites", ":", "last_test_processed", "=", "idx", "break", "current_test_list", ".", "append", "(", "test_instance", ")", "if", "current_test_list", ":", "suites", ".", "append", "(", "current_test_list", ")", "if", "max_suites", "and", "last_test_processed", "<", "len", "(", "tests_runtimes", ")", ":", "# We must have hit the max suite limit, just randomly add the remaining tests to suites.", "divide_remaining_tests_among_suites", "(", "tests_runtimes", "[", "last_test_processed", ":", "]", ",", "suites", ")", "return", "[", "[", "test", ".", "test_name", "for", "test", "in", "test_list", "]", "for", "test_list", "in", "suites", "]" ]
https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/task_generation/suite_split_strategies.py#L54-L103