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
mapsme/omim
1892903b63f2c85b16ed4966d21fe76aba06b9ba
tools/python/maps_generator/generator/stages.py
python
country_stage_status
(stage: Type[Stage])
return stage
It's helper decorator that works with status file.
It's helper decorator that works with status file.
[ "It", "s", "helper", "decorator", "that", "works", "with", "status", "file", "." ]
def country_stage_status(stage: Type[Stage]) -> Type[Stage]: """It's helper decorator that works with status file.""" def new_apply(method): def apply(obj: Stage, env: "Env", country: AnyStr, *args, **kwargs): name = get_stage_name(obj) _logger = DummyObject() countries_meta = env.countries_meta if "logger" in countries_meta[country]: _logger, _ = countries_meta[country]["logger"] if not env.is_accepted_stage(stage): _logger.info(f"Stage {name} was not accepted.") return if "status" not in countries_meta[country]: countries_meta[country]["status"] = status.Status() country_status = countries_meta[country]["status"] status_file = os.path.join( env.paths.status_path, status.with_stat_ext(country) ) country_status.init(status_file, name) if country_status.need_skip(): _logger.warning(f"Stage {name} was skipped.") return country_status.update_status() method(obj, env, country, *args, **kwargs) return apply stage.apply = new_apply(stage.apply) return stage
[ "def", "country_stage_status", "(", "stage", ":", "Type", "[", "Stage", "]", ")", "->", "Type", "[", "Stage", "]", ":", "def", "new_apply", "(", "method", ")", ":", "def", "apply", "(", "obj", ":", "Stage", ",", "env", ":", "\"Env\"", ",", "country", ":", "AnyStr", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "name", "=", "get_stage_name", "(", "obj", ")", "_logger", "=", "DummyObject", "(", ")", "countries_meta", "=", "env", ".", "countries_meta", "if", "\"logger\"", "in", "countries_meta", "[", "country", "]", ":", "_logger", ",", "_", "=", "countries_meta", "[", "country", "]", "[", "\"logger\"", "]", "if", "not", "env", ".", "is_accepted_stage", "(", "stage", ")", ":", "_logger", ".", "info", "(", "f\"Stage {name} was not accepted.\"", ")", "return", "if", "\"status\"", "not", "in", "countries_meta", "[", "country", "]", ":", "countries_meta", "[", "country", "]", "[", "\"status\"", "]", "=", "status", ".", "Status", "(", ")", "country_status", "=", "countries_meta", "[", "country", "]", "[", "\"status\"", "]", "status_file", "=", "os", ".", "path", ".", "join", "(", "env", ".", "paths", ".", "status_path", ",", "status", ".", "with_stat_ext", "(", "country", ")", ")", "country_status", ".", "init", "(", "status_file", ",", "name", ")", "if", "country_status", ".", "need_skip", "(", ")", ":", "_logger", ".", "warning", "(", "f\"Stage {name} was skipped.\"", ")", "return", "country_status", ".", "update_status", "(", ")", "method", "(", "obj", ",", "env", ",", "country", ",", "*", "args", ",", "*", "*", "kwargs", ")", "return", "apply", "stage", ".", "apply", "=", "new_apply", "(", "stage", ".", "apply", ")", "return", "stage" ]
https://github.com/mapsme/omim/blob/1892903b63f2c85b16ed4966d21fe76aba06b9ba/tools/python/maps_generator/generator/stages.py#L215-L248
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/setuptools/archive_util.py
python
unpack_directory
(filename, extract_dir, progress_filter=default_filter)
Unpack" a directory, using the same interface as for archives Raises ``UnrecognizedFormat`` if `filename` is not a directory
Unpack" a directory, using the same interface as for archives
[ "Unpack", "a", "directory", "using", "the", "same", "interface", "as", "for", "archives" ]
def unpack_directory(filename, extract_dir, progress_filter=default_filter): """"Unpack" a directory, using the same interface as for archives Raises ``UnrecognizedFormat`` if `filename` is not a directory """ if not os.path.isdir(filename): raise UnrecognizedFormat("%s is not a directory" % filename) paths = { filename: ('', extract_dir), } for base, dirs, files in os.walk(filename): src, dst = paths[base] for d in dirs: paths[os.path.join(base, d)] = src + d + '/', os.path.join(dst, d) for f in files: target = os.path.join(dst, f) target = progress_filter(src + f, target) if not target: # skip non-files continue ensure_directory(target) f = os.path.join(base, f) shutil.copyfile(f, target) shutil.copystat(f, target)
[ "def", "unpack_directory", "(", "filename", ",", "extract_dir", ",", "progress_filter", "=", "default_filter", ")", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "filename", ")", ":", "raise", "UnrecognizedFormat", "(", "\"%s is not a directory\"", "%", "filename", ")", "paths", "=", "{", "filename", ":", "(", "''", ",", "extract_dir", ")", ",", "}", "for", "base", ",", "dirs", ",", "files", "in", "os", ".", "walk", "(", "filename", ")", ":", "src", ",", "dst", "=", "paths", "[", "base", "]", "for", "d", "in", "dirs", ":", "paths", "[", "os", ".", "path", ".", "join", "(", "base", ",", "d", ")", "]", "=", "src", "+", "d", "+", "'/'", ",", "os", ".", "path", ".", "join", "(", "dst", ",", "d", ")", "for", "f", "in", "files", ":", "target", "=", "os", ".", "path", ".", "join", "(", "dst", ",", "f", ")", "target", "=", "progress_filter", "(", "src", "+", "f", ",", "target", ")", "if", "not", "target", ":", "# skip non-files", "continue", "ensure_directory", "(", "target", ")", "f", "=", "os", ".", "path", ".", "join", "(", "base", ",", "f", ")", "shutil", ".", "copyfile", "(", "f", ",", "target", ")", "shutil", ".", "copystat", "(", "f", ",", "target", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/setuptools/archive_util.py#L64-L88
lilypond/lilypond
2a14759372979f5b796ee802b0ee3bc15d28b06b
scripts/build/output-distance.py
python
FileLink.name
(self)
return os.path.join(self.prefix(), base)
Returns the \\sourcefilename for this test file
Returns the \\sourcefilename for this test file
[ "Returns", "the", "\\\\", "sourcefilename", "for", "this", "test", "file" ]
def name(self) -> str: """Returns the \\sourcefilename for this test file""" base = os.path.basename(self.file_names[1]) base = os.path.splitext(base)[0] base = hash_to_original_name.get(base, base) base = os.path.splitext(base)[0] return os.path.join(self.prefix(), base)
[ "def", "name", "(", "self", ")", "->", "str", ":", "base", "=", "os", ".", "path", ".", "basename", "(", "self", ".", "file_names", "[", "1", "]", ")", "base", "=", "os", ".", "path", ".", "splitext", "(", "base", ")", "[", "0", "]", "base", "=", "hash_to_original_name", ".", "get", "(", "base", ",", "base", ")", "base", "=", "os", ".", "path", ".", "splitext", "(", "base", ")", "[", "0", "]", "return", "os", ".", "path", ".", "join", "(", "self", ".", "prefix", "(", ")", ",", "base", ")" ]
https://github.com/lilypond/lilypond/blob/2a14759372979f5b796ee802b0ee3bc15d28b06b/scripts/build/output-distance.py#L487-L493
hughperkins/tf-coriander
970d3df6c11400ad68405f22b0c42a52374e94ca
tensorflow/contrib/graph_editor/edit.py
python
detach_outputs
(sgv, control_outputs=None)
return sgv_, output_placeholders
Detach the output of a subgraph view. Args: sgv: the subgraph view to be detached. This argument is converted to a subgraph using the same rules as the function subgraph.make_view. Note that sgv is modified in place. control_outputs: a util.ControlOutputs instance or None. If not None the control outputs are also detached. Returns: A tuple `(sgv, output_placeholders)` where `sgv` is a new subgraph view of the detached subgraph; `output_placeholders` is a list of the created output placeholders. Raises: StandardError: if sgv cannot be converted to a SubGraphView using the same rules than the function subgraph.make_view.
Detach the output of a subgraph view.
[ "Detach", "the", "output", "of", "a", "subgraph", "view", "." ]
def detach_outputs(sgv, control_outputs=None): """Detach the output of a subgraph view. Args: sgv: the subgraph view to be detached. This argument is converted to a subgraph using the same rules as the function subgraph.make_view. Note that sgv is modified in place. control_outputs: a util.ControlOutputs instance or None. If not None the control outputs are also detached. Returns: A tuple `(sgv, output_placeholders)` where `sgv` is a new subgraph view of the detached subgraph; `output_placeholders` is a list of the created output placeholders. Raises: StandardError: if sgv cannot be converted to a SubGraphView using the same rules than the function subgraph.make_view. """ sgv = subgraph.make_view(sgv) # only select outputs with consumers sgv_ = sgv.remap_outputs([output_id for output_id, output_t in enumerate(sgv.outputs) if output_t.consumers()]) # create consumer subgraph and remap consumers_sgv = subgraph.SubGraphView(sgv_.consumers()) consumers_sgv = consumers_sgv.remap_inputs( [input_id for input_id, input_t in enumerate(consumers_sgv.inputs) if input_t in sgv_.outputs]) with sgv_.graph.as_default(): output_placeholders = [ util.make_placeholder_from_tensor(input_t) for input_t in consumers_sgv.inputs ] reroute.swap_outputs(sgv_, output_placeholders) if control_outputs is not None: detach_control_outputs(sgv_, control_outputs) return sgv_, output_placeholders
[ "def", "detach_outputs", "(", "sgv", ",", "control_outputs", "=", "None", ")", ":", "sgv", "=", "subgraph", ".", "make_view", "(", "sgv", ")", "# only select outputs with consumers", "sgv_", "=", "sgv", ".", "remap_outputs", "(", "[", "output_id", "for", "output_id", ",", "output_t", "in", "enumerate", "(", "sgv", ".", "outputs", ")", "if", "output_t", ".", "consumers", "(", ")", "]", ")", "# create consumer subgraph and remap", "consumers_sgv", "=", "subgraph", ".", "SubGraphView", "(", "sgv_", ".", "consumers", "(", ")", ")", "consumers_sgv", "=", "consumers_sgv", ".", "remap_inputs", "(", "[", "input_id", "for", "input_id", ",", "input_t", "in", "enumerate", "(", "consumers_sgv", ".", "inputs", ")", "if", "input_t", "in", "sgv_", ".", "outputs", "]", ")", "with", "sgv_", ".", "graph", ".", "as_default", "(", ")", ":", "output_placeholders", "=", "[", "util", ".", "make_placeholder_from_tensor", "(", "input_t", ")", "for", "input_t", "in", "consumers_sgv", ".", "inputs", "]", "reroute", ".", "swap_outputs", "(", "sgv_", ",", "output_placeholders", ")", "if", "control_outputs", "is", "not", "None", ":", "detach_control_outputs", "(", "sgv_", ",", "control_outputs", ")", "return", "sgv_", ",", "output_placeholders" ]
https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/contrib/graph_editor/edit.py#L101-L138
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py3/sklearn/datasets/_twenty_newsgroups.py
python
strip_newsgroup_header
(text)
return after
Given text in "news" format, strip the headers, by removing everything before the first blank line. Parameters ---------- text : string The text from which to remove the signature block.
Given text in "news" format, strip the headers, by removing everything before the first blank line.
[ "Given", "text", "in", "news", "format", "strip", "the", "headers", "by", "removing", "everything", "before", "the", "first", "blank", "line", "." ]
def strip_newsgroup_header(text): """ Given text in "news" format, strip the headers, by removing everything before the first blank line. Parameters ---------- text : string The text from which to remove the signature block. """ _before, _blankline, after = text.partition('\n\n') return after
[ "def", "strip_newsgroup_header", "(", "text", ")", ":", "_before", ",", "_blankline", ",", "after", "=", "text", ".", "partition", "(", "'\\n\\n'", ")", "return", "after" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/datasets/_twenty_newsgroups.py#L90-L101
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/lookup_ops.py
python
InitializableLookupTableBase.__init__
(self, default_value, initializer)
Construct a table object from a table reference. If requires a table initializer object (subclass of `TableInitializerBase`). It provides the table key and value types, as well as the op to initialize the table. The caller is responsible to execute the initialization op. Args: default_value: The value to use if a key is missing in the table. initializer: The table initializer to use.
Construct a table object from a table reference.
[ "Construct", "a", "table", "object", "from", "a", "table", "reference", "." ]
def __init__(self, default_value, initializer): """Construct a table object from a table reference. If requires a table initializer object (subclass of `TableInitializerBase`). It provides the table key and value types, as well as the op to initialize the table. The caller is responsible to execute the initialization op. Args: default_value: The value to use if a key is missing in the table. initializer: The table initializer to use. """ super(InitializableLookupTableBase, self).__init__(initializer.key_dtype, initializer.value_dtype) self._default_value = ops.convert_to_tensor( default_value, dtype=self._value_dtype) self._default_value.get_shape().merge_with(tensor_shape.TensorShape([])) if isinstance(initializer, trackable_base.Trackable): self._initializer = self._track_trackable(initializer, "_initializer") with ops.init_scope(): self._resource_handle = self._create_resource() if (not context.executing_eagerly() and ops.get_default_graph()._get_control_flow_context() is not None): # pylint: disable=protected-access with ops.init_scope(): self._init_op = self._initialize() else: self._init_op = self._initialize()
[ "def", "__init__", "(", "self", ",", "default_value", ",", "initializer", ")", ":", "super", "(", "InitializableLookupTableBase", ",", "self", ")", ".", "__init__", "(", "initializer", ".", "key_dtype", ",", "initializer", ".", "value_dtype", ")", "self", ".", "_default_value", "=", "ops", ".", "convert_to_tensor", "(", "default_value", ",", "dtype", "=", "self", ".", "_value_dtype", ")", "self", ".", "_default_value", ".", "get_shape", "(", ")", ".", "merge_with", "(", "tensor_shape", ".", "TensorShape", "(", "[", "]", ")", ")", "if", "isinstance", "(", "initializer", ",", "trackable_base", ".", "Trackable", ")", ":", "self", ".", "_initializer", "=", "self", ".", "_track_trackable", "(", "initializer", ",", "\"_initializer\"", ")", "with", "ops", ".", "init_scope", "(", ")", ":", "self", ".", "_resource_handle", "=", "self", ".", "_create_resource", "(", ")", "if", "(", "not", "context", ".", "executing_eagerly", "(", ")", "and", "ops", ".", "get_default_graph", "(", ")", ".", "_get_control_flow_context", "(", ")", "is", "not", "None", ")", ":", "# pylint: disable=protected-access", "with", "ops", ".", "init_scope", "(", ")", ":", "self", ".", "_init_op", "=", "self", ".", "_initialize", "(", ")", "else", ":", "self", ".", "_init_op", "=", "self", ".", "_initialize", "(", ")" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/lookup_ops.py#L154-L179
themighty1/lpfw
7880c0a1aac26ecc33259633c0f866a157ab491e
gui/gui.py
python
queryDialog.closeEvent
(self, event)
in case when user closed the dialog without pressing allow or deny
in case when user closed the dialog without pressing allow or deny
[ "in", "case", "when", "user", "closed", "the", "dialog", "without", "pressing", "allow", "or", "deny" ]
def closeEvent(self, event): "in case when user closed the dialog without pressing allow or deny" print "in closeEvent" msgQueue.put('ADD ' + b64encode(bytearray(self.path, encoding='utf-8')) + ' ' + self.pid + ' IGNORED')
[ "def", "closeEvent", "(", "self", ",", "event", ")", ":", "print", "\"in closeEvent\"", "msgQueue", ".", "put", "(", "'ADD '", "+", "b64encode", "(", "bytearray", "(", "self", ".", "path", ",", "encoding", "=", "'utf-8'", ")", ")", "+", "' '", "+", "self", ".", "pid", "+", "' IGNORED'", ")" ]
https://github.com/themighty1/lpfw/blob/7880c0a1aac26ecc33259633c0f866a157ab491e/gui/gui.py#L81-L84
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/more-itertools/py2/more_itertools/more.py
python
divide
(n, iterable)
return ret
Divide the elements from *iterable* into *n* parts, maintaining order. >>> group_1, group_2 = divide(2, [1, 2, 3, 4, 5, 6]) >>> list(group_1) [1, 2, 3] >>> list(group_2) [4, 5, 6] If the length of *iterable* is not evenly divisible by *n*, then the length of the returned iterables will not be identical: >>> children = divide(3, [1, 2, 3, 4, 5, 6, 7]) >>> [list(c) for c in children] [[1, 2, 3], [4, 5], [6, 7]] If the length of the iterable is smaller than n, then the last returned iterables will be empty: >>> children = divide(5, [1, 2, 3]) >>> [list(c) for c in children] [[1], [2], [3], [], []] This function will exhaust the iterable before returning and may require significant storage. If order is not important, see :func:`distribute`, which does not first pull the iterable into memory.
Divide the elements from *iterable* into *n* parts, maintaining order.
[ "Divide", "the", "elements", "from", "*", "iterable", "*", "into", "*", "n", "*", "parts", "maintaining", "order", "." ]
def divide(n, iterable): """Divide the elements from *iterable* into *n* parts, maintaining order. >>> group_1, group_2 = divide(2, [1, 2, 3, 4, 5, 6]) >>> list(group_1) [1, 2, 3] >>> list(group_2) [4, 5, 6] If the length of *iterable* is not evenly divisible by *n*, then the length of the returned iterables will not be identical: >>> children = divide(3, [1, 2, 3, 4, 5, 6, 7]) >>> [list(c) for c in children] [[1, 2, 3], [4, 5], [6, 7]] If the length of the iterable is smaller than n, then the last returned iterables will be empty: >>> children = divide(5, [1, 2, 3]) >>> [list(c) for c in children] [[1], [2], [3], [], []] This function will exhaust the iterable before returning and may require significant storage. If order is not important, see :func:`distribute`, which does not first pull the iterable into memory. """ if n < 1: raise ValueError('n must be at least 1') seq = tuple(iterable) q, r = divmod(len(seq), n) ret = [] for i in range(n): start = (i * q) + (i if i < r else r) stop = ((i + 1) * q) + (i + 1 if i + 1 < r else r) ret.append(iter(seq[start:stop])) return ret
[ "def", "divide", "(", "n", ",", "iterable", ")", ":", "if", "n", "<", "1", ":", "raise", "ValueError", "(", "'n must be at least 1'", ")", "seq", "=", "tuple", "(", "iterable", ")", "q", ",", "r", "=", "divmod", "(", "len", "(", "seq", ")", ",", "n", ")", "ret", "=", "[", "]", "for", "i", "in", "range", "(", "n", ")", ":", "start", "=", "(", "i", "*", "q", ")", "+", "(", "i", "if", "i", "<", "r", "else", "r", ")", "stop", "=", "(", "(", "i", "+", "1", ")", "*", "q", ")", "+", "(", "i", "+", "1", "if", "i", "+", "1", "<", "r", "else", "r", ")", "ret", ".", "append", "(", "iter", "(", "seq", "[", "start", ":", "stop", "]", ")", ")", "return", "ret" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/more-itertools/py2/more_itertools/more.py#L1339-L1380
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/tensorflow/contrib/graph_editor/reroute.py
python
_RerouteMode.check
(cls, mode)
Check swap mode. Args: mode: an integer representing one of the modes. Returns: True if a is rerouted to b (mode is swap or a2b). True if b is rerouted to a (mode is swap or b2a). Raises: ValueError: if mode is outside the enum range.
Check swap mode.
[ "Check", "swap", "mode", "." ]
def check(cls, mode): """Check swap mode. Args: mode: an integer representing one of the modes. Returns: True if a is rerouted to b (mode is swap or a2b). True if b is rerouted to a (mode is swap or b2a). Raises: ValueError: if mode is outside the enum range. """ if mode == cls.swap: return True, True elif mode == cls.b2a: return False, True elif mode == cls.a2b: return True, False else: raise ValueError("Unknown _RerouteMode: {}".format(mode))
[ "def", "check", "(", "cls", ",", "mode", ")", ":", "if", "mode", "==", "cls", ".", "swap", ":", "return", "True", ",", "True", "elif", "mode", "==", "cls", ".", "b2a", ":", "return", "False", ",", "True", "elif", "mode", "==", "cls", ".", "a2b", ":", "return", "True", ",", "False", "else", ":", "raise", "ValueError", "(", "\"Unknown _RerouteMode: {}\"", ".", "format", "(", "mode", ")", ")" ]
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/contrib/graph_editor/reroute.py#L66-L84
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/keras/distribute/distributed_training_utils_v1.py
python
_build_network_on_replica
(model, mode, inputs=None, targets=None)
return updated_model
Build an updated model on replicas. We create a new Keras model while sharing the variables from the old graph. Building a new sub-graph is required since the original keras model creates placeholders for the input and the output that are not accessible till we call iterator.get_next() inside the step_fn for `fit`/`evaluate`/`predict`. The sharing of weights and layers between the old and the new model guarantee that we're using Strategy variables and any updates on either model are reflected correctly in callbacks and loop iterations. We need to make sure we share the optimizers between the old and the new model as well so that optimizer state is not lost if the user is running fit multiple times. Args: model: Model to be replicated across Replicas mode: Which of fit/eval/predict is building the distributed network inputs: Input variables to be passed to the model targets: Target tensor to be passed to model.compile Returns: A new model with shared layers with the old model.
Build an updated model on replicas.
[ "Build", "an", "updated", "model", "on", "replicas", "." ]
def _build_network_on_replica(model, mode, inputs=None, targets=None): """Build an updated model on replicas. We create a new Keras model while sharing the variables from the old graph. Building a new sub-graph is required since the original keras model creates placeholders for the input and the output that are not accessible till we call iterator.get_next() inside the step_fn for `fit`/`evaluate`/`predict`. The sharing of weights and layers between the old and the new model guarantee that we're using Strategy variables and any updates on either model are reflected correctly in callbacks and loop iterations. We need to make sure we share the optimizers between the old and the new model as well so that optimizer state is not lost if the user is running fit multiple times. Args: model: Model to be replicated across Replicas mode: Which of fit/eval/predict is building the distributed network inputs: Input variables to be passed to the model targets: Target tensor to be passed to model.compile Returns: A new model with shared layers with the old model. """ # Need to do imports here since we run into a circular dependency error. from tensorflow.python.keras import models # pylint: disable=g-import-not-at-top from tensorflow.python.keras.engine import sequential # pylint: disable=g-import-not-at-top # We rely on the internal methods to avoid having share_weights weights in the # public API. if isinstance(model, sequential.Sequential): updated_model = models._clone_sequential_model( model, input_tensors=inputs, layer_fn=models.share_weights) else: updated_model = models._clone_functional_model( model, input_tensors=inputs, layer_fn=models.share_weights) # Callable losses added directly to a functional Model need to be added # here. updated_model._callable_losses = model._callable_losses # Recast all low precision outputs back to float32 since we only casted # the inputs to bfloat16 and not targets. This is done so that we can preserve # precision when calculating the loss value. def _upcast_low_precision_outputs(output): if output.dtype == dtypes.bfloat16: return math_ops.cast(output, dtypes.float32) else: return output updated_model.outputs = [_upcast_low_precision_outputs(o) for o in updated_model.outputs] if isinstance(targets, tuple): targets = nest.flatten(targets) if mode == ModeKeys.PREDICT and inputs is not None: # TPU predict case _custom_compile_for_predict(updated_model) else: updated_model.compile( model.optimizer, model.loss, metrics=metrics_module.clone_metrics(model._compile_metrics), loss_weights=model.loss_weights, sample_weight_mode=model.sample_weight_mode, weighted_metrics=metrics_module.clone_metrics( model._compile_weighted_metrics), target_tensors=targets) return updated_model
[ "def", "_build_network_on_replica", "(", "model", ",", "mode", ",", "inputs", "=", "None", ",", "targets", "=", "None", ")", ":", "# Need to do imports here since we run into a circular dependency error.", "from", "tensorflow", ".", "python", ".", "keras", "import", "models", "# pylint: disable=g-import-not-at-top", "from", "tensorflow", ".", "python", ".", "keras", ".", "engine", "import", "sequential", "# pylint: disable=g-import-not-at-top", "# We rely on the internal methods to avoid having share_weights weights in the", "# public API.", "if", "isinstance", "(", "model", ",", "sequential", ".", "Sequential", ")", ":", "updated_model", "=", "models", ".", "_clone_sequential_model", "(", "model", ",", "input_tensors", "=", "inputs", ",", "layer_fn", "=", "models", ".", "share_weights", ")", "else", ":", "updated_model", "=", "models", ".", "_clone_functional_model", "(", "model", ",", "input_tensors", "=", "inputs", ",", "layer_fn", "=", "models", ".", "share_weights", ")", "# Callable losses added directly to a functional Model need to be added", "# here.", "updated_model", ".", "_callable_losses", "=", "model", ".", "_callable_losses", "# Recast all low precision outputs back to float32 since we only casted", "# the inputs to bfloat16 and not targets. This is done so that we can preserve", "# precision when calculating the loss value.", "def", "_upcast_low_precision_outputs", "(", "output", ")", ":", "if", "output", ".", "dtype", "==", "dtypes", ".", "bfloat16", ":", "return", "math_ops", ".", "cast", "(", "output", ",", "dtypes", ".", "float32", ")", "else", ":", "return", "output", "updated_model", ".", "outputs", "=", "[", "_upcast_low_precision_outputs", "(", "o", ")", "for", "o", "in", "updated_model", ".", "outputs", "]", "if", "isinstance", "(", "targets", ",", "tuple", ")", ":", "targets", "=", "nest", ".", "flatten", "(", "targets", ")", "if", "mode", "==", "ModeKeys", ".", "PREDICT", "and", "inputs", "is", "not", "None", ":", "# TPU predict case", "_custom_compile_for_predict", "(", "updated_model", ")", "else", ":", "updated_model", ".", "compile", "(", "model", ".", "optimizer", ",", "model", ".", "loss", ",", "metrics", "=", "metrics_module", ".", "clone_metrics", "(", "model", ".", "_compile_metrics", ")", ",", "loss_weights", "=", "model", ".", "loss_weights", ",", "sample_weight_mode", "=", "model", ".", "sample_weight_mode", ",", "weighted_metrics", "=", "metrics_module", ".", "clone_metrics", "(", "model", ".", "_compile_weighted_metrics", ")", ",", "target_tensors", "=", "targets", ")", "return", "updated_model" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/keras/distribute/distributed_training_utils_v1.py#L684-L751
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_misc.py
python
JoystickEvent.SetButtonState
(*args, **kwargs)
return _misc_.JoystickEvent_SetButtonState(*args, **kwargs)
SetButtonState(self, int state)
SetButtonState(self, int state)
[ "SetButtonState", "(", "self", "int", "state", ")" ]
def SetButtonState(*args, **kwargs): """SetButtonState(self, int state)""" return _misc_.JoystickEvent_SetButtonState(*args, **kwargs)
[ "def", "SetButtonState", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_misc_", ".", "JoystickEvent_SetButtonState", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_misc.py#L2366-L2368
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/reduce4circleControl.py
python
CWSCDReductionControl.get_raw_data_workspace
(self, exp_no, scan_no, pt_no)
return ws
Get raw workspace
Get raw workspace
[ "Get", "raw", "workspace" ]
def get_raw_data_workspace(self, exp_no, scan_no, pt_no): """ Get raw workspace """ try: ws = self._myRawDataWSDict[(exp_no, scan_no, pt_no)] assert isinstance(ws, mantid.dataobjects.Workspace2D) except KeyError: return None return ws
[ "def", "get_raw_data_workspace", "(", "self", ",", "exp_no", ",", "scan_no", ",", "pt_no", ")", ":", "try", ":", "ws", "=", "self", ".", "_myRawDataWSDict", "[", "(", "exp_no", ",", "scan_no", ",", "pt_no", ")", "]", "assert", "isinstance", "(", "ws", ",", "mantid", ".", "dataobjects", ".", "Workspace2D", ")", "except", "KeyError", ":", "return", "None", "return", "ws" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/reduce4circleControl.py#L3548-L3557
yuxng/DA-RNN
77fbb50b4272514588a10a9f90b7d5f8d46974fb
lib/datasets/shapenet_single.py
python
shapenet_single.gt_roidb
(self)
return gt_roidb
Return the database of ground-truth regions of interest. This function loads/saves from/to a cache file to speed up future calls.
Return the database of ground-truth regions of interest.
[ "Return", "the", "database", "of", "ground", "-", "truth", "regions", "of", "interest", "." ]
def gt_roidb(self): """ Return the database of ground-truth regions of interest. This function loads/saves from/to a cache file to speed up future calls. """ cache_file = os.path.join(self.cache_path, self.name + '_gt_roidb.pkl') if os.path.exists(cache_file): with open(cache_file, 'rb') as fid: roidb = cPickle.load(fid) print '{} gt roidb loaded from {}'.format(self.name, cache_file) return roidb gt_roidb = [self._load_shapenet_single_annotation(index) for index in self.image_index] with open(cache_file, 'wb') as fid: cPickle.dump(gt_roidb, fid, cPickle.HIGHEST_PROTOCOL) print 'wrote gt roidb to {}'.format(cache_file) return gt_roidb
[ "def", "gt_roidb", "(", "self", ")", ":", "cache_file", "=", "os", ".", "path", ".", "join", "(", "self", ".", "cache_path", ",", "self", ".", "name", "+", "'_gt_roidb.pkl'", ")", "if", "os", ".", "path", ".", "exists", "(", "cache_file", ")", ":", "with", "open", "(", "cache_file", ",", "'rb'", ")", "as", "fid", ":", "roidb", "=", "cPickle", ".", "load", "(", "fid", ")", "print", "'{} gt roidb loaded from {}'", ".", "format", "(", "self", ".", "name", ",", "cache_file", ")", "return", "roidb", "gt_roidb", "=", "[", "self", ".", "_load_shapenet_single_annotation", "(", "index", ")", "for", "index", "in", "self", ".", "image_index", "]", "with", "open", "(", "cache_file", ",", "'wb'", ")", "as", "fid", ":", "cPickle", ".", "dump", "(", "gt_roidb", ",", "fid", ",", "cPickle", ".", "HIGHEST_PROTOCOL", ")", "print", "'wrote gt roidb to {}'", ".", "format", "(", "cache_file", ")", "return", "gt_roidb" ]
https://github.com/yuxng/DA-RNN/blob/77fbb50b4272514588a10a9f90b7d5f8d46974fb/lib/datasets/shapenet_single.py#L148-L169
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/turtle.py
python
TNavigator.xcor
(self)
return self._position[0]
Return the turtle's x coordinate. No arguments. Example (for a Turtle instance named turtle): >>> reset() >>> turtle.left(60) >>> turtle.forward(100) >>> print turtle.xcor() 50.0
Return the turtle's x coordinate.
[ "Return", "the", "turtle", "s", "x", "coordinate", "." ]
def xcor(self): """ Return the turtle's x coordinate. No arguments. Example (for a Turtle instance named turtle): >>> reset() >>> turtle.left(60) >>> turtle.forward(100) >>> print turtle.xcor() 50.0 """ return self._position[0]
[ "def", "xcor", "(", "self", ")", ":", "return", "self", ".", "_position", "[", "0", "]" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/turtle.py#L1714-L1726
Tencent/CMONGO
c40380caa14e05509f46993aa8b8da966b09b0b5
src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Node/FS.py
python
FS.Repository
(self, *dirs)
Specify Repository directories to search.
Specify Repository directories to search.
[ "Specify", "Repository", "directories", "to", "search", "." ]
def Repository(self, *dirs): """Specify Repository directories to search.""" for d in dirs: if not isinstance(d, SCons.Node.Node): d = self.Dir(d) self.Top.addRepository(d)
[ "def", "Repository", "(", "self", ",", "*", "dirs", ")", ":", "for", "d", "in", "dirs", ":", "if", "not", "isinstance", "(", "d", ",", "SCons", ".", "Node", ".", "Node", ")", ":", "d", "=", "self", ".", "Dir", "(", "d", ")", "self", ".", "Top", ".", "addRepository", "(", "d", ")" ]
https://github.com/Tencent/CMONGO/blob/c40380caa14e05509f46993aa8b8da966b09b0b5/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Node/FS.py#L1443-L1448
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py2/sklearn/metrics/cluster/bicluster.py
python
consensus_score
(a, b, similarity="jaccard")
return matrix[indices[:, 0], indices[:, 1]].sum() / max(n_a, n_b)
The similarity of two sets of biclusters. Similarity between individual biclusters is computed. Then the best matching between sets is found using the Hungarian algorithm. The final score is the sum of similarities divided by the size of the larger set. Read more in the :ref:`User Guide <biclustering>`. Parameters ---------- a : (rows, columns) Tuple of row and column indicators for a set of biclusters. b : (rows, columns) Another set of biclusters like ``a``. similarity : string or function, optional, default: "jaccard" May be the string "jaccard" to use the Jaccard coefficient, or any function that takes four arguments, each of which is a 1d indicator vector: (a_rows, a_columns, b_rows, b_columns). References ---------- * Hochreiter, Bodenhofer, et. al., 2010. `FABIA: factor analysis for bicluster acquisition <https://www.ncbi.nlm.nih.gov/pmc/articles/PMC2881408/>`__.
The similarity of two sets of biclusters.
[ "The", "similarity", "of", "two", "sets", "of", "biclusters", "." ]
def consensus_score(a, b, similarity="jaccard"): """The similarity of two sets of biclusters. Similarity between individual biclusters is computed. Then the best matching between sets is found using the Hungarian algorithm. The final score is the sum of similarities divided by the size of the larger set. Read more in the :ref:`User Guide <biclustering>`. Parameters ---------- a : (rows, columns) Tuple of row and column indicators for a set of biclusters. b : (rows, columns) Another set of biclusters like ``a``. similarity : string or function, optional, default: "jaccard" May be the string "jaccard" to use the Jaccard coefficient, or any function that takes four arguments, each of which is a 1d indicator vector: (a_rows, a_columns, b_rows, b_columns). References ---------- * Hochreiter, Bodenhofer, et. al., 2010. `FABIA: factor analysis for bicluster acquisition <https://www.ncbi.nlm.nih.gov/pmc/articles/PMC2881408/>`__. """ if similarity == "jaccard": similarity = _jaccard matrix = _pairwise_similarity(a, b, similarity) indices = linear_assignment(1. - matrix) n_a = len(a[0]) n_b = len(b[0]) return matrix[indices[:, 0], indices[:, 1]].sum() / max(n_a, n_b)
[ "def", "consensus_score", "(", "a", ",", "b", ",", "similarity", "=", "\"jaccard\"", ")", ":", "if", "similarity", "==", "\"jaccard\"", ":", "similarity", "=", "_jaccard", "matrix", "=", "_pairwise_similarity", "(", "a", ",", "b", ",", "similarity", ")", "indices", "=", "linear_assignment", "(", "1.", "-", "matrix", ")", "n_a", "=", "len", "(", "a", "[", "0", "]", ")", "n_b", "=", "len", "(", "b", "[", "0", "]", ")", "return", "matrix", "[", "indices", "[", ":", ",", "0", "]", ",", "indices", "[", ":", ",", "1", "]", "]", ".", "sum", "(", ")", "/", "max", "(", "n_a", ",", "n_b", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/metrics/cluster/bicluster.py#L49-L86
libfive/libfive
ab5e354cf6fd992f80aaa9432c52683219515c8a
libfive/bind/python/libfive/stdlib/transforms.py
python
rotate_y
(t, angle, center=(0, 0, 0))
return Shape(stdlib.rotate_y( args[0].ptr, args[1].ptr, tvec3(*[a.ptr for a in args[2]])))
Rotate the given shape by an angle in radians The center of rotation is [0 0 0] or specified by the optional argument
Rotate the given shape by an angle in radians The center of rotation is [0 0 0] or specified by the optional argument
[ "Rotate", "the", "given", "shape", "by", "an", "angle", "in", "radians", "The", "center", "of", "rotation", "is", "[", "0", "0", "0", "]", "or", "specified", "by", "the", "optional", "argument" ]
def rotate_y(t, angle, center=(0, 0, 0)): """ Rotate the given shape by an angle in radians The center of rotation is [0 0 0] or specified by the optional argument """ args = [Shape.wrap(t), Shape.wrap(angle), list([Shape.wrap(i) for i in center])] return Shape(stdlib.rotate_y( args[0].ptr, args[1].ptr, tvec3(*[a.ptr for a in args[2]])))
[ "def", "rotate_y", "(", "t", ",", "angle", ",", "center", "=", "(", "0", ",", "0", ",", "0", ")", ")", ":", "args", "=", "[", "Shape", ".", "wrap", "(", "t", ")", ",", "Shape", ".", "wrap", "(", "angle", ")", ",", "list", "(", "[", "Shape", ".", "wrap", "(", "i", ")", "for", "i", "in", "center", "]", ")", "]", "return", "Shape", "(", "stdlib", ".", "rotate_y", "(", "args", "[", "0", "]", ".", "ptr", ",", "args", "[", "1", "]", ".", "ptr", ",", "tvec3", "(", "*", "[", "a", ".", "ptr", "for", "a", "in", "args", "[", "2", "]", "]", ")", ")", ")" ]
https://github.com/libfive/libfive/blob/ab5e354cf6fd992f80aaa9432c52683219515c8a/libfive/bind/python/libfive/stdlib/transforms.py#L172-L180
Z3Prover/z3
d745d03afdfdf638d66093e2bfbacaf87187f35b
src/api/python/z3/z3.py
python
Float16
(ctx=None)
return FPSortRef(Z3_mk_fpa_sort_16(ctx.ref()), ctx)
Floating-point 16-bit (half) sort.
Floating-point 16-bit (half) sort.
[ "Floating", "-", "point", "16", "-", "bit", "(", "half", ")", "sort", "." ]
def Float16(ctx=None): """Floating-point 16-bit (half) sort.""" ctx = _get_ctx(ctx) return FPSortRef(Z3_mk_fpa_sort_16(ctx.ref()), ctx)
[ "def", "Float16", "(", "ctx", "=", "None", ")", ":", "ctx", "=", "_get_ctx", "(", "ctx", ")", "return", "FPSortRef", "(", "Z3_mk_fpa_sort_16", "(", "ctx", ".", "ref", "(", ")", ")", ",", "ctx", ")" ]
https://github.com/Z3Prover/z3/blob/d745d03afdfdf638d66093e2bfbacaf87187f35b/src/api/python/z3/z3.py#L9274-L9277
snap-stanford/snap-python
d53c51b0a26aa7e3e7400b014cdf728948fde80a
setup/snap.py
python
TMemOut_New
(*args)
return _snap.TMemOut_New(*args)
TMemOut_New(PMem const & Mem) -> PSOut Parameters: Mem: PMem const &
TMemOut_New(PMem const & Mem) -> PSOut
[ "TMemOut_New", "(", "PMem", "const", "&", "Mem", ")", "-", ">", "PSOut" ]
def TMemOut_New(*args): """ TMemOut_New(PMem const & Mem) -> PSOut Parameters: Mem: PMem const & """ return _snap.TMemOut_New(*args)
[ "def", "TMemOut_New", "(", "*", "args", ")", ":", "return", "_snap", ".", "TMemOut_New", "(", "*", "args", ")" ]
https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L8424-L8432
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/zipfile.py
python
_EndRecData
(fpin)
return None
Return data from the "End of Central Directory" record, or None. The data is a list of the nine items in the ZIP "End of central dir" record followed by a tenth item, the file seek offset of this record.
Return data from the "End of Central Directory" record, or None.
[ "Return", "data", "from", "the", "End", "of", "Central", "Directory", "record", "or", "None", "." ]
def _EndRecData(fpin): """Return data from the "End of Central Directory" record, or None. The data is a list of the nine items in the ZIP "End of central dir" record followed by a tenth item, the file seek offset of this record.""" # Determine file size fpin.seek(0, 2) filesize = fpin.tell() # Check to see if this is ZIP file with no archive comment (the # "end of central directory" structure should be the last item in the # file if this is the case). try: fpin.seek(-sizeEndCentDir, 2) except IOError: return None data = fpin.read() if (len(data) == sizeEndCentDir and data[0:4] == stringEndArchive and data[-2:] == b"\000\000"): # the signature is correct and there's no comment, unpack structure endrec = struct.unpack(structEndArchive, data) endrec=list(endrec) # Append a blank comment and record start offset endrec.append("") endrec.append(filesize - sizeEndCentDir) # Try to read the "Zip64 end of central directory" structure return _EndRecData64(fpin, -sizeEndCentDir, endrec) # Either this is not a ZIP file, or it is a ZIP file with an archive # comment. Search the end of the file for the "end of central directory" # record signature. The comment is the last item in the ZIP file and may be # up to 64K long. It is assumed that the "end of central directory" magic # number does not appear in the comment. maxCommentStart = max(filesize - (1 << 16) - sizeEndCentDir, 0) fpin.seek(maxCommentStart, 0) data = fpin.read() start = data.rfind(stringEndArchive) if start >= 0: # found the magic number; attempt to unpack and interpret recData = data[start:start+sizeEndCentDir] if len(recData) != sizeEndCentDir: # Zip file is corrupted. return None endrec = list(struct.unpack(structEndArchive, recData)) commentSize = endrec[_ECD_COMMENT_SIZE] #as claimed by the zip file comment = data[start+sizeEndCentDir:start+sizeEndCentDir+commentSize] endrec.append(comment) endrec.append(maxCommentStart + start) # Try to read the "Zip64 end of central directory" structure return _EndRecData64(fpin, maxCommentStart + start - filesize, endrec) # Unable to find a valid end of central directory structure return None
[ "def", "_EndRecData", "(", "fpin", ")", ":", "# Determine file size", "fpin", ".", "seek", "(", "0", ",", "2", ")", "filesize", "=", "fpin", ".", "tell", "(", ")", "# Check to see if this is ZIP file with no archive comment (the", "# \"end of central directory\" structure should be the last item in the", "# file if this is the case).", "try", ":", "fpin", ".", "seek", "(", "-", "sizeEndCentDir", ",", "2", ")", "except", "IOError", ":", "return", "None", "data", "=", "fpin", ".", "read", "(", ")", "if", "(", "len", "(", "data", ")", "==", "sizeEndCentDir", "and", "data", "[", "0", ":", "4", "]", "==", "stringEndArchive", "and", "data", "[", "-", "2", ":", "]", "==", "b\"\\000\\000\"", ")", ":", "# the signature is correct and there's no comment, unpack structure", "endrec", "=", "struct", ".", "unpack", "(", "structEndArchive", ",", "data", ")", "endrec", "=", "list", "(", "endrec", ")", "# Append a blank comment and record start offset", "endrec", ".", "append", "(", "\"\"", ")", "endrec", ".", "append", "(", "filesize", "-", "sizeEndCentDir", ")", "# Try to read the \"Zip64 end of central directory\" structure", "return", "_EndRecData64", "(", "fpin", ",", "-", "sizeEndCentDir", ",", "endrec", ")", "# Either this is not a ZIP file, or it is a ZIP file with an archive", "# comment. Search the end of the file for the \"end of central directory\"", "# record signature. The comment is the last item in the ZIP file and may be", "# up to 64K long. It is assumed that the \"end of central directory\" magic", "# number does not appear in the comment.", "maxCommentStart", "=", "max", "(", "filesize", "-", "(", "1", "<<", "16", ")", "-", "sizeEndCentDir", ",", "0", ")", "fpin", ".", "seek", "(", "maxCommentStart", ",", "0", ")", "data", "=", "fpin", ".", "read", "(", ")", "start", "=", "data", ".", "rfind", "(", "stringEndArchive", ")", "if", "start", ">=", "0", ":", "# found the magic number; attempt to unpack and interpret", "recData", "=", "data", "[", "start", ":", "start", "+", "sizeEndCentDir", "]", "if", "len", "(", "recData", ")", "!=", "sizeEndCentDir", ":", "# Zip file is corrupted.", "return", "None", "endrec", "=", "list", "(", "struct", ".", "unpack", "(", "structEndArchive", ",", "recData", ")", ")", "commentSize", "=", "endrec", "[", "_ECD_COMMENT_SIZE", "]", "#as claimed by the zip file", "comment", "=", "data", "[", "start", "+", "sizeEndCentDir", ":", "start", "+", "sizeEndCentDir", "+", "commentSize", "]", "endrec", ".", "append", "(", "comment", ")", "endrec", ".", "append", "(", "maxCommentStart", "+", "start", ")", "# Try to read the \"Zip64 end of central directory\" structure", "return", "_EndRecData64", "(", "fpin", ",", "maxCommentStart", "+", "start", "-", "filesize", ",", "endrec", ")", "# Unable to find a valid end of central directory structure", "return", "None" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/zipfile.py#L201-L259
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
lts/deps/v8/third_party/jinja2/compiler.py
python
Frame.soft
(self)
return rv
Return a soft frame. A soft frame may not be modified as standalone thing as it shares the resources with the frame it was created of, but it's not a rootlevel frame any longer. This is only used to implement if-statements.
Return a soft frame. A soft frame may not be modified as standalone thing as it shares the resources with the frame it was created of, but it's not a rootlevel frame any longer.
[ "Return", "a", "soft", "frame", ".", "A", "soft", "frame", "may", "not", "be", "modified", "as", "standalone", "thing", "as", "it", "shares", "the", "resources", "with", "the", "frame", "it", "was", "created", "of", "but", "it", "s", "not", "a", "rootlevel", "frame", "any", "longer", "." ]
def soft(self): """Return a soft frame. A soft frame may not be modified as standalone thing as it shares the resources with the frame it was created of, but it's not a rootlevel frame any longer. This is only used to implement if-statements. """ rv = self.copy() rv.rootlevel = False return rv
[ "def", "soft", "(", "self", ")", ":", "rv", "=", "self", ".", "copy", "(", ")", "rv", ".", "rootlevel", "=", "False", "return", "rv" ]
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/deps/v8/third_party/jinja2/compiler.py#L178-L187
mongodb/mongo
d8ff665343ad29cf286ee2cf4a1960d29371937b
buildscripts/pylinters.py
python
lint_all
(linters, config_dict, file_names)
Lint files command entry point based on working tree.
Lint files command entry point based on working tree.
[ "Lint", "files", "command", "entry", "point", "based", "on", "working", "tree", "." ]
def lint_all(linters, config_dict, file_names): # type: (str, Dict[str, str], List[str]) -> None # pylint: disable=unused-argument """Lint files command entry point based on working tree.""" all_file_names = git.get_files_to_check_working_tree(is_interesting_file) _lint_files(linters, config_dict, all_file_names)
[ "def", "lint_all", "(", "linters", ",", "config_dict", ",", "file_names", ")", ":", "# type: (str, Dict[str, str], List[str]) -> None", "# pylint: disable=unused-argument", "all_file_names", "=", "git", ".", "get_files_to_check_working_tree", "(", "is_interesting_file", ")", "_lint_files", "(", "linters", ",", "config_dict", ",", "all_file_names", ")" ]
https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/pylinters.py#L122-L128
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
lts/tools/gyp/pylib/gyp/xcodeproj_file.py
python
PBXProject.RootGroupsTakeOverOnlyChildren
(self, recurse=False)
Calls TakeOverOnlyChild for all groups in the main group.
Calls TakeOverOnlyChild for all groups in the main group.
[ "Calls", "TakeOverOnlyChild", "for", "all", "groups", "in", "the", "main", "group", "." ]
def RootGroupsTakeOverOnlyChildren(self, recurse=False): """Calls TakeOverOnlyChild for all groups in the main group.""" for group in self._properties['mainGroup']._properties['children']: if isinstance(group, PBXGroup): group.TakeOverOnlyChild(recurse)
[ "def", "RootGroupsTakeOverOnlyChildren", "(", "self", ",", "recurse", "=", "False", ")", ":", "for", "group", "in", "self", ".", "_properties", "[", "'mainGroup'", "]", ".", "_properties", "[", "'children'", "]", ":", "if", "isinstance", "(", "group", ",", "PBXGroup", ")", ":", "group", ".", "TakeOverOnlyChild", "(", "recurse", ")" ]
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/tools/gyp/pylib/gyp/xcodeproj_file.py#L2694-L2699
LiquidPlayer/LiquidCore
9405979363f2353ac9a71ad8ab59685dd7f919c9
deps/node-10.15.3/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/ordered_dict.py
python
OrderedDict.__delitem__
(self, key, dict_delitem=dict.__delitem__)
od.__delitem__(y) <==> del od[y]
od.__delitem__(y) <==> del od[y]
[ "od", ".", "__delitem__", "(", "y", ")", "<", "==", ">", "del", "od", "[", "y", "]" ]
def __delitem__(self, key, dict_delitem=dict.__delitem__): 'od.__delitem__(y) <==> del od[y]' # Deleting an existing item uses self.__map to find the link which is # then removed by updating the links in the predecessor and successor nodes. dict_delitem(self, key) link_prev, link_next, key = self.__map.pop(key) link_prev[1] = link_next link_next[0] = link_prev
[ "def", "__delitem__", "(", "self", ",", "key", ",", "dict_delitem", "=", "dict", ".", "__delitem__", ")", ":", "# Deleting an existing item uses self.__map to find the link which is", "# then removed by updating the links in the predecessor and successor nodes.", "dict_delitem", "(", "self", ",", "key", ")", "link_prev", ",", "link_next", ",", "key", "=", "self", ".", "__map", ".", "pop", "(", "key", ")", "link_prev", "[", "1", "]", "=", "link_next", "link_next", "[", "0", "]", "=", "link_prev" ]
https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/ordered_dict.py#L81-L88
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/dumbdbm.py
python
open
(file, flag=None, mode=0666)
return _Database(file, mode)
Open the database file, filename, and return corresponding object. The flag argument, used to control how the database is opened in the other DBM implementations, is ignored in the dumbdbm module; the database is always opened for update, and will be created if it does not exist. The optional mode argument is the UNIX mode of the file, used only when the database has to be created. It defaults to octal code 0666 (and will be modified by the prevailing umask).
Open the database file, filename, and return corresponding object.
[ "Open", "the", "database", "file", "filename", "and", "return", "corresponding", "object", "." ]
def open(file, flag=None, mode=0666): """Open the database file, filename, and return corresponding object. The flag argument, used to control how the database is opened in the other DBM implementations, is ignored in the dumbdbm module; the database is always opened for update, and will be created if it does not exist. The optional mode argument is the UNIX mode of the file, used only when the database has to be created. It defaults to octal code 0666 (and will be modified by the prevailing umask). """ # flag argument is currently ignored # Modify mode depending on the umask try: um = _os.umask(0) _os.umask(um) except AttributeError: pass else: # Turn off any bits that are set in the umask mode = mode & (~um) return _Database(file, mode)
[ "def", "open", "(", "file", ",", "flag", "=", "None", ",", "mode", "=", "0666", ")", ":", "# flag argument is currently ignored", "# Modify mode depending on the umask", "try", ":", "um", "=", "_os", ".", "umask", "(", "0", ")", "_os", ".", "umask", "(", "um", ")", "except", "AttributeError", ":", "pass", "else", ":", "# Turn off any bits that are set in the umask", "mode", "=", "mode", "&", "(", "~", "um", ")", "return", "_Database", "(", "file", ",", "mode", ")" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/dumbdbm.py#L225-L250
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/scipy/optimize/lbfgsb.py
python
LbfgsInvHessProduct.__init__
(self, sk, yk)
Construct the operator.
Construct the operator.
[ "Construct", "the", "operator", "." ]
def __init__(self, sk, yk): """Construct the operator.""" if sk.shape != yk.shape or sk.ndim != 2: raise ValueError('sk and yk must have matching shape, (n_corrs, n)') n_corrs, n = sk.shape super(LbfgsInvHessProduct, self).__init__( dtype=np.float64, shape=(n, n)) self.sk = sk self.yk = yk self.n_corrs = n_corrs self.rho = 1 / np.einsum('ij,ij->i', sk, yk)
[ "def", "__init__", "(", "self", ",", "sk", ",", "yk", ")", ":", "if", "sk", ".", "shape", "!=", "yk", ".", "shape", "or", "sk", ".", "ndim", "!=", "2", ":", "raise", "ValueError", "(", "'sk and yk must have matching shape, (n_corrs, n)'", ")", "n_corrs", ",", "n", "=", "sk", ".", "shape", "super", "(", "LbfgsInvHessProduct", ",", "self", ")", ".", "__init__", "(", "dtype", "=", "np", ".", "float64", ",", "shape", "=", "(", "n", ",", "n", ")", ")", "self", ".", "sk", "=", "sk", "self", ".", "yk", "=", "yk", "self", ".", "n_corrs", "=", "n_corrs", "self", ".", "rho", "=", "1", "/", "np", ".", "einsum", "(", "'ij,ij->i'", ",", "sk", ",", "yk", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/optimize/lbfgsb.py#L395-L407
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/ops/math_grad.py
python
_MeanGrad
(op, grad)
return math_ops.truediv(sum_grad, math_ops.cast(factor, sum_grad.dtype)), None
Gradient for Mean.
Gradient for Mean.
[ "Gradient", "for", "Mean", "." ]
def _MeanGrad(op, grad): """Gradient for Mean.""" sum_grad = _SumGrad(op, grad)[0] input_shape = op.inputs[0]._shape_tuple() # pylint: disable=protected-access output_shape = op.outputs[0]._shape_tuple() # pylint: disable=protected-access if (input_shape is not None and output_shape is not None and None not in input_shape and None not in output_shape): input_size = np.prod(input_shape) output_size = np.prod(output_shape) factor = input_size // max(output_size, 1) factor = constant_op.constant(factor, dtype=sum_grad.dtype) else: input_shape = array_ops.shape(op.inputs[0]) output_shape = array_ops.shape(op.outputs[0]) factor = _safe_shape_div( math_ops.reduce_prod(input_shape), math_ops.reduce_prod(output_shape)) return math_ops.truediv(sum_grad, math_ops.cast(factor, sum_grad.dtype)), None
[ "def", "_MeanGrad", "(", "op", ",", "grad", ")", ":", "sum_grad", "=", "_SumGrad", "(", "op", ",", "grad", ")", "[", "0", "]", "input_shape", "=", "op", ".", "inputs", "[", "0", "]", ".", "_shape_tuple", "(", ")", "# pylint: disable=protected-access", "output_shape", "=", "op", ".", "outputs", "[", "0", "]", ".", "_shape_tuple", "(", ")", "# pylint: disable=protected-access", "if", "(", "input_shape", "is", "not", "None", "and", "output_shape", "is", "not", "None", "and", "None", "not", "in", "input_shape", "and", "None", "not", "in", "output_shape", ")", ":", "input_size", "=", "np", ".", "prod", "(", "input_shape", ")", "output_size", "=", "np", ".", "prod", "(", "output_shape", ")", "factor", "=", "input_size", "//", "max", "(", "output_size", ",", "1", ")", "factor", "=", "constant_op", ".", "constant", "(", "factor", ",", "dtype", "=", "sum_grad", ".", "dtype", ")", "else", ":", "input_shape", "=", "array_ops", ".", "shape", "(", "op", ".", "inputs", "[", "0", "]", ")", "output_shape", "=", "array_ops", ".", "shape", "(", "op", ".", "outputs", "[", "0", "]", ")", "factor", "=", "_safe_shape_div", "(", "math_ops", ".", "reduce_prod", "(", "input_shape", ")", ",", "math_ops", ".", "reduce_prod", "(", "output_shape", ")", ")", "return", "math_ops", ".", "truediv", "(", "sum_grad", ",", "math_ops", ".", "cast", "(", "factor", ",", "sum_grad", ".", "dtype", ")", ")", ",", "None" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/math_grad.py#L250-L266
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/dataflow.py
python
DataFlowAnalysis.op_STORE_SLICE_1
(self, info, inst)
TOS1[TOS:] = TOS2
TOS1[TOS:] = TOS2
[ "TOS1", "[", "TOS", ":", "]", "=", "TOS2" ]
def op_STORE_SLICE_1(self, info, inst): """ TOS1[TOS:] = TOS2 """ tos = info.pop() tos1 = info.pop() value = info.pop() slicevar = info.make_temp() indexvar = info.make_temp() nonevar = info.make_temp() info.append(inst, base=tos1, start=tos, slicevar=slicevar, value=value, indexvar=indexvar, nonevar=nonevar)
[ "def", "op_STORE_SLICE_1", "(", "self", ",", "info", ",", "inst", ")", ":", "tos", "=", "info", ".", "pop", "(", ")", "tos1", "=", "info", ".", "pop", "(", ")", "value", "=", "info", ".", "pop", "(", ")", "slicevar", "=", "info", ".", "make_temp", "(", ")", "indexvar", "=", "info", ".", "make_temp", "(", ")", "nonevar", "=", "info", ".", "make_temp", "(", ")", "info", ".", "append", "(", "inst", ",", "base", "=", "tos1", ",", "start", "=", "tos", ",", "slicevar", "=", "slicevar", ",", "value", "=", "value", ",", "indexvar", "=", "indexvar", ",", "nonevar", "=", "nonevar", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/dataflow.py#L523-L534
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/tensorflow/contrib/learn/python/learn/estimators/dnn.py
python
DNNClassifier.__init__
(self, hidden_units, feature_columns=None, model_dir=None, n_classes=2, weight_column_name=None, optimizer=None, activation_fn=nn.relu, dropout=None, gradient_clip_norm=None, enable_centered_bias=True, config=None)
Initializes a DNNClassifier instance. Args: hidden_units: List of hidden units per layer. All layers are fully connected. Ex. `[64, 32]` means first layer has 64 nodes and second one has 32. feature_columns: An iterable containing all the feature columns used by the model. All items in the set should be instances of classes derived from `FeatureColumn`. model_dir: Directory to save model parameters, graph and etc. This can also be used to load checkpoints from the directory into a estimator to continue training a previously saved model. n_classes: number of target classes. Default is binary classification. It must be greater than 1. weight_column_name: A string defining feature column name representing weights. It is used to down weight or boost examples during training. It will be multiplied by the loss of the example. optimizer: An instance of `tf.Optimizer` used to train the model. If `None`, will use an Adagrad optimizer. activation_fn: Activation function applied to each layer. If `None`, will use `tf.nn.relu`. dropout: When not `None`, the probability we will drop out a given coordinate. gradient_clip_norm: A float > 0. If provided, gradients are clipped to their global norm with this clipping ratio. See tf.clip_by_global_norm for more details. enable_centered_bias: A bool. If True, estimator will learn a centered bias variable for each class. Rest of the model structure learns the residual after centered bias. config: `RunConfig` object to configure the runtime settings. Returns: A `DNNClassifier` estimator.
Initializes a DNNClassifier instance.
[ "Initializes", "a", "DNNClassifier", "instance", "." ]
def __init__(self, hidden_units, feature_columns=None, model_dir=None, n_classes=2, weight_column_name=None, optimizer=None, activation_fn=nn.relu, dropout=None, gradient_clip_norm=None, enable_centered_bias=True, config=None): """Initializes a DNNClassifier instance. Args: hidden_units: List of hidden units per layer. All layers are fully connected. Ex. `[64, 32]` means first layer has 64 nodes and second one has 32. feature_columns: An iterable containing all the feature columns used by the model. All items in the set should be instances of classes derived from `FeatureColumn`. model_dir: Directory to save model parameters, graph and etc. This can also be used to load checkpoints from the directory into a estimator to continue training a previously saved model. n_classes: number of target classes. Default is binary classification. It must be greater than 1. weight_column_name: A string defining feature column name representing weights. It is used to down weight or boost examples during training. It will be multiplied by the loss of the example. optimizer: An instance of `tf.Optimizer` used to train the model. If `None`, will use an Adagrad optimizer. activation_fn: Activation function applied to each layer. If `None`, will use `tf.nn.relu`. dropout: When not `None`, the probability we will drop out a given coordinate. gradient_clip_norm: A float > 0. If provided, gradients are clipped to their global norm with this clipping ratio. See tf.clip_by_global_norm for more details. enable_centered_bias: A bool. If True, estimator will learn a centered bias variable for each class. Rest of the model structure learns the residual after centered bias. config: `RunConfig` object to configure the runtime settings. Returns: A `DNNClassifier` estimator. """ _changing(feature_columns) super(DNNClassifier, self).__init__( model_dir=model_dir, n_classes=n_classes, weight_column_name=weight_column_name, dnn_feature_columns=feature_columns, dnn_optimizer=optimizer, dnn_hidden_units=hidden_units, dnn_activation_fn=activation_fn, dnn_dropout=dropout, gradient_clip_norm=gradient_clip_norm, enable_centered_bias=enable_centered_bias, config=config) self.feature_columns = feature_columns self.optimizer = optimizer self.activation_fn = activation_fn self.dropout = dropout self.hidden_units = hidden_units self._feature_columns_inferred = False
[ "def", "__init__", "(", "self", ",", "hidden_units", ",", "feature_columns", "=", "None", ",", "model_dir", "=", "None", ",", "n_classes", "=", "2", ",", "weight_column_name", "=", "None", ",", "optimizer", "=", "None", ",", "activation_fn", "=", "nn", ".", "relu", ",", "dropout", "=", "None", ",", "gradient_clip_norm", "=", "None", ",", "enable_centered_bias", "=", "True", ",", "config", "=", "None", ")", ":", "_changing", "(", "feature_columns", ")", "super", "(", "DNNClassifier", ",", "self", ")", ".", "__init__", "(", "model_dir", "=", "model_dir", ",", "n_classes", "=", "n_classes", ",", "weight_column_name", "=", "weight_column_name", ",", "dnn_feature_columns", "=", "feature_columns", ",", "dnn_optimizer", "=", "optimizer", ",", "dnn_hidden_units", "=", "hidden_units", ",", "dnn_activation_fn", "=", "activation_fn", ",", "dnn_dropout", "=", "dropout", ",", "gradient_clip_norm", "=", "gradient_clip_norm", ",", "enable_centered_bias", "=", "enable_centered_bias", ",", "config", "=", "config", ")", "self", ".", "feature_columns", "=", "feature_columns", "self", ".", "optimizer", "=", "optimizer", "self", ".", "activation_fn", "=", "activation_fn", "self", ".", "dropout", "=", "dropout", "self", ".", "hidden_units", "=", "hidden_units", "self", ".", "_feature_columns_inferred", "=", "False" ]
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/contrib/learn/python/learn/estimators/dnn.py#L101-L165
snap-stanford/snap-python
d53c51b0a26aa7e3e7400b014cdf728948fde80a
setup/snap.py
python
TIntHI.IsEnd
(self)
return _snap.TIntHI_IsEnd(self)
IsEnd(TIntHI self) -> bool Parameters: self: THashKeyDatI< TInt,TInt > const *
IsEnd(TIntHI self) -> bool
[ "IsEnd", "(", "TIntHI", "self", ")", "-", ">", "bool" ]
def IsEnd(self): """ IsEnd(TIntHI self) -> bool Parameters: self: THashKeyDatI< TInt,TInt > const * """ return _snap.TIntHI_IsEnd(self)
[ "def", "IsEnd", "(", "self", ")", ":", "return", "_snap", ".", "TIntHI_IsEnd", "(", "self", ")" ]
https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L19047-L19055
Polidea/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py
python
SBAddress.GetOffset
(self)
return _lldb.SBAddress_GetOffset(self)
GetOffset(self) -> addr_t
GetOffset(self) -> addr_t
[ "GetOffset", "(", "self", ")", "-", ">", "addr_t" ]
def GetOffset(self): """GetOffset(self) -> addr_t""" return _lldb.SBAddress_GetOffset(self)
[ "def", "GetOffset", "(", "self", ")", ":", "return", "_lldb", ".", "SBAddress_GetOffset", "(", "self", ")" ]
https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L892-L894
SequoiaDB/SequoiaDB
2894ed7e5bd6fe57330afc900cf76d0ff0df9f64
tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py
python
uCSIsOsmanya
(code)
return ret
Check whether the character is part of Osmanya UCS Block
Check whether the character is part of Osmanya UCS Block
[ "Check", "whether", "the", "character", "is", "part", "of", "Osmanya", "UCS", "Block" ]
def uCSIsOsmanya(code): """Check whether the character is part of Osmanya UCS Block """ ret = libxml2mod.xmlUCSIsOsmanya(code) return ret
[ "def", "uCSIsOsmanya", "(", "code", ")", ":", "ret", "=", "libxml2mod", ".", "xmlUCSIsOsmanya", "(", "code", ")", "return", "ret" ]
https://github.com/SequoiaDB/SequoiaDB/blob/2894ed7e5bd6fe57330afc900cf76d0ff0df9f64/tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py#L2762-L2765
infinit/elle
a8154593c42743f45b9df09daf62b44630c24a02
drake/src/drake/__init__.py
python
BaseNode.name_relative
(self)
return self.__name.name_relative
Node name, relative to the current drakefile.
Node name, relative to the current drakefile.
[ "Node", "name", "relative", "to", "the", "current", "drakefile", "." ]
def name_relative(self): """Node name, relative to the current drakefile.""" return self.__name.name_relative
[ "def", "name_relative", "(", "self", ")", ":", "return", "self", ".", "__name", ".", "name_relative" ]
https://github.com/infinit/elle/blob/a8154593c42743f45b9df09daf62b44630c24a02/drake/src/drake/__init__.py#L1402-L1404
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/training/saver.py
python
saver_from_object_based_checkpoint
(checkpoint_path, var_list=None, builder=None, names_to_keys=None, cached_saver=None)
return cached_saver
Return a `Saver` which reads from an object-based checkpoint. This function validates that all variables in the variables list are remapped in the object-based checkpoint (or `names_to_keys` dict if provided). A saver will be created with the list of remapped variables. The `cached_saver` argument allows the user to pass in a previously created saver, so multiple `saver.restore()` calls don't pollute the graph when graph building. This assumes that keys are consistent, meaning that the 1) `checkpoint_path` checkpoint, and 2) checkpoint used to create the `cached_saver` are the same type of object-based checkpoint. If this argument is set, this function will simply validate that all variables have been remapped by the checkpoint at `checkpoint_path`. Note that in general, `tf.train.Checkpoint` should be used to restore/save an object-based checkpoint. Args: checkpoint_path: string, path to object-based checkpoint var_list: list of `Variables` that appear in the checkpoint. If `None`, `var_list` will be set to all saveable objects. builder: a `BaseSaverBuilder` instance. If `None`, a new `BulkSaverBuilder` will be created. names_to_keys: dict mapping string tensor names to checkpooint keys. If `None`, this dict will be generated from the checkpoint file. cached_saver: Cached `Saver` object with remapped variables. Returns: `Saver` with remapped variables for reading from an object-based checkpoint. Raises: ValueError if the checkpoint provided is not an object-based checkpoint. NotFoundError: If one of the variables in `var_list` can not be found in the checkpoint. This could mean the checkpoint or `names_to_keys` mapping is missing the variable.
Return a `Saver` which reads from an object-based checkpoint.
[ "Return", "a", "Saver", "which", "reads", "from", "an", "object", "-", "based", "checkpoint", "." ]
def saver_from_object_based_checkpoint(checkpoint_path, var_list=None, builder=None, names_to_keys=None, cached_saver=None): """Return a `Saver` which reads from an object-based checkpoint. This function validates that all variables in the variables list are remapped in the object-based checkpoint (or `names_to_keys` dict if provided). A saver will be created with the list of remapped variables. The `cached_saver` argument allows the user to pass in a previously created saver, so multiple `saver.restore()` calls don't pollute the graph when graph building. This assumes that keys are consistent, meaning that the 1) `checkpoint_path` checkpoint, and 2) checkpoint used to create the `cached_saver` are the same type of object-based checkpoint. If this argument is set, this function will simply validate that all variables have been remapped by the checkpoint at `checkpoint_path`. Note that in general, `tf.train.Checkpoint` should be used to restore/save an object-based checkpoint. Args: checkpoint_path: string, path to object-based checkpoint var_list: list of `Variables` that appear in the checkpoint. If `None`, `var_list` will be set to all saveable objects. builder: a `BaseSaverBuilder` instance. If `None`, a new `BulkSaverBuilder` will be created. names_to_keys: dict mapping string tensor names to checkpooint keys. If `None`, this dict will be generated from the checkpoint file. cached_saver: Cached `Saver` object with remapped variables. Returns: `Saver` with remapped variables for reading from an object-based checkpoint. Raises: ValueError if the checkpoint provided is not an object-based checkpoint. NotFoundError: If one of the variables in `var_list` can not be found in the checkpoint. This could mean the checkpoint or `names_to_keys` mapping is missing the variable. """ if names_to_keys is None: try: names_to_keys = object_graph_key_mapping(checkpoint_path) except errors.NotFoundError: raise ValueError("Checkpoint in %s not an object-based checkpoint." % checkpoint_path) if var_list is None: var_list = variables._all_saveable_objects() # pylint: disable=protected-access if builder is None: builder = BulkSaverBuilder() saveables = saveable_object_util.validate_and_slice_inputs(var_list) current_names = set() for saveable in saveables: for spec in saveable.specs: current_names.add(spec.name) previous_names = set(names_to_keys.keys()) missing_names = current_names - previous_names if missing_names: extra_names = previous_names - current_names intersecting_names = previous_names.intersection(current_names) raise errors.NotFoundError( None, None, message=( "\n\nExisting variables not in the checkpoint: %s\n\n" "Variables names when this checkpoint was written which don't " "exist now: %s\n\n" "(%d variable name(s) did match)\n\n" "Could not find some variables in the checkpoint (see names " "above). Saver was attempting to load an object-based checkpoint " "(saved using tf.train.Checkpoint or tf.keras.Model.save_weights) " "using variable names. If the checkpoint was written with eager " "execution enabled, it's possible that variable names have " "changed (for example missing a '_1' suffix). It's also " "possible that there are new variables which did not exist " "when the checkpoint was written. You can construct a " "Saver(var_list=...) with only the variables which previously " "existed, and if variable names have changed you may need to " "make this a dictionary with the old names as keys. If you're " "using an Estimator, you'll need to return a tf.train.Saver " "inside a tf.train.Scaffold from your model_fn.") % (", ".join(sorted(missing_names)), ", ".join( sorted(extra_names)), len(intersecting_names))) for saveable in saveables: for spec in saveable.specs: spec.name = names_to_keys[spec.name] if cached_saver is None: return Saver(saveables) return cached_saver
[ "def", "saver_from_object_based_checkpoint", "(", "checkpoint_path", ",", "var_list", "=", "None", ",", "builder", "=", "None", ",", "names_to_keys", "=", "None", ",", "cached_saver", "=", "None", ")", ":", "if", "names_to_keys", "is", "None", ":", "try", ":", "names_to_keys", "=", "object_graph_key_mapping", "(", "checkpoint_path", ")", "except", "errors", ".", "NotFoundError", ":", "raise", "ValueError", "(", "\"Checkpoint in %s not an object-based checkpoint.\"", "%", "checkpoint_path", ")", "if", "var_list", "is", "None", ":", "var_list", "=", "variables", ".", "_all_saveable_objects", "(", ")", "# pylint: disable=protected-access", "if", "builder", "is", "None", ":", "builder", "=", "BulkSaverBuilder", "(", ")", "saveables", "=", "saveable_object_util", ".", "validate_and_slice_inputs", "(", "var_list", ")", "current_names", "=", "set", "(", ")", "for", "saveable", "in", "saveables", ":", "for", "spec", "in", "saveable", ".", "specs", ":", "current_names", ".", "add", "(", "spec", ".", "name", ")", "previous_names", "=", "set", "(", "names_to_keys", ".", "keys", "(", ")", ")", "missing_names", "=", "current_names", "-", "previous_names", "if", "missing_names", ":", "extra_names", "=", "previous_names", "-", "current_names", "intersecting_names", "=", "previous_names", ".", "intersection", "(", "current_names", ")", "raise", "errors", ".", "NotFoundError", "(", "None", ",", "None", ",", "message", "=", "(", "\"\\n\\nExisting variables not in the checkpoint: %s\\n\\n\"", "\"Variables names when this checkpoint was written which don't \"", "\"exist now: %s\\n\\n\"", "\"(%d variable name(s) did match)\\n\\n\"", "\"Could not find some variables in the checkpoint (see names \"", "\"above). Saver was attempting to load an object-based checkpoint \"", "\"(saved using tf.train.Checkpoint or tf.keras.Model.save_weights) \"", "\"using variable names. If the checkpoint was written with eager \"", "\"execution enabled, it's possible that variable names have \"", "\"changed (for example missing a '_1' suffix). It's also \"", "\"possible that there are new variables which did not exist \"", "\"when the checkpoint was written. You can construct a \"", "\"Saver(var_list=...) with only the variables which previously \"", "\"existed, and if variable names have changed you may need to \"", "\"make this a dictionary with the old names as keys. If you're \"", "\"using an Estimator, you'll need to return a tf.train.Saver \"", "\"inside a tf.train.Scaffold from your model_fn.\"", ")", "%", "(", "\", \"", ".", "join", "(", "sorted", "(", "missing_names", ")", ")", ",", "\", \"", ".", "join", "(", "sorted", "(", "extra_names", ")", ")", ",", "len", "(", "intersecting_names", ")", ")", ")", "for", "saveable", "in", "saveables", ":", "for", "spec", "in", "saveable", ".", "specs", ":", "spec", ".", "name", "=", "names_to_keys", "[", "spec", ".", "name", "]", "if", "cached_saver", "is", "None", ":", "return", "Saver", "(", "saveables", ")", "return", "cached_saver" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/training/saver.py#L1628-L1719
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/_strptime.py
python
TimeRE.__init__
(self, locale_time=None)
Create keys/values. Order of execution is important for dependency reasons.
Create keys/values.
[ "Create", "keys", "/", "values", "." ]
def __init__(self, locale_time=None): """Create keys/values. Order of execution is important for dependency reasons. """ if locale_time: self.locale_time = locale_time else: self.locale_time = LocaleTime() base = super(TimeRE, self) base.__init__({ # The " \d" part of the regex is to make %c from ANSI C work 'd': r"(?P<d>3[0-1]|[1-2]\d|0[1-9]|[1-9]| [1-9])", 'f': r"(?P<f>[0-9]{1,6})", 'H': r"(?P<H>2[0-3]|[0-1]\d|\d)", 'I': r"(?P<I>1[0-2]|0[1-9]|[1-9])", 'j': r"(?P<j>36[0-6]|3[0-5]\d|[1-2]\d\d|0[1-9]\d|00[1-9]|[1-9]\d|0[1-9]|[1-9])", 'm': r"(?P<m>1[0-2]|0[1-9]|[1-9])", 'M': r"(?P<M>[0-5]\d|\d)", 'S': r"(?P<S>6[0-1]|[0-5]\d|\d)", 'U': r"(?P<U>5[0-3]|[0-4]\d|\d)", 'w': r"(?P<w>[0-6])", # W is set below by using 'U' 'y': r"(?P<y>\d\d)", #XXX: Does 'Y' need to worry about having less or more than # 4 digits? 'Y': r"(?P<Y>\d\d\d\d)", 'A': self.__seqToRE(self.locale_time.f_weekday, 'A'), 'a': self.__seqToRE(self.locale_time.a_weekday, 'a'), 'B': self.__seqToRE(self.locale_time.f_month[1:], 'B'), 'b': self.__seqToRE(self.locale_time.a_month[1:], 'b'), 'p': self.__seqToRE(self.locale_time.am_pm, 'p'), 'Z': self.__seqToRE((tz for tz_names in self.locale_time.timezone for tz in tz_names), 'Z'), '%': '%'}) base.__setitem__('W', base.__getitem__('U').replace('U', 'W')) base.__setitem__('c', self.pattern(self.locale_time.LC_date_time)) base.__setitem__('x', self.pattern(self.locale_time.LC_date)) base.__setitem__('X', self.pattern(self.locale_time.LC_time))
[ "def", "__init__", "(", "self", ",", "locale_time", "=", "None", ")", ":", "if", "locale_time", ":", "self", ".", "locale_time", "=", "locale_time", "else", ":", "self", ".", "locale_time", "=", "LocaleTime", "(", ")", "base", "=", "super", "(", "TimeRE", ",", "self", ")", "base", ".", "__init__", "(", "{", "# The \" \\d\" part of the regex is to make %c from ANSI C work", "'d'", ":", "r\"(?P<d>3[0-1]|[1-2]\\d|0[1-9]|[1-9]| [1-9])\"", ",", "'f'", ":", "r\"(?P<f>[0-9]{1,6})\"", ",", "'H'", ":", "r\"(?P<H>2[0-3]|[0-1]\\d|\\d)\"", ",", "'I'", ":", "r\"(?P<I>1[0-2]|0[1-9]|[1-9])\"", ",", "'j'", ":", "r\"(?P<j>36[0-6]|3[0-5]\\d|[1-2]\\d\\d|0[1-9]\\d|00[1-9]|[1-9]\\d|0[1-9]|[1-9])\"", ",", "'m'", ":", "r\"(?P<m>1[0-2]|0[1-9]|[1-9])\"", ",", "'M'", ":", "r\"(?P<M>[0-5]\\d|\\d)\"", ",", "'S'", ":", "r\"(?P<S>6[0-1]|[0-5]\\d|\\d)\"", ",", "'U'", ":", "r\"(?P<U>5[0-3]|[0-4]\\d|\\d)\"", ",", "'w'", ":", "r\"(?P<w>[0-6])\"", ",", "# W is set below by using 'U'", "'y'", ":", "r\"(?P<y>\\d\\d)\"", ",", "#XXX: Does 'Y' need to worry about having less or more than", "# 4 digits?", "'Y'", ":", "r\"(?P<Y>\\d\\d\\d\\d)\"", ",", "'A'", ":", "self", ".", "__seqToRE", "(", "self", ".", "locale_time", ".", "f_weekday", ",", "'A'", ")", ",", "'a'", ":", "self", ".", "__seqToRE", "(", "self", ".", "locale_time", ".", "a_weekday", ",", "'a'", ")", ",", "'B'", ":", "self", ".", "__seqToRE", "(", "self", ".", "locale_time", ".", "f_month", "[", "1", ":", "]", ",", "'B'", ")", ",", "'b'", ":", "self", ".", "__seqToRE", "(", "self", ".", "locale_time", ".", "a_month", "[", "1", ":", "]", ",", "'b'", ")", ",", "'p'", ":", "self", ".", "__seqToRE", "(", "self", ".", "locale_time", ".", "am_pm", ",", "'p'", ")", ",", "'Z'", ":", "self", ".", "__seqToRE", "(", "(", "tz", "for", "tz_names", "in", "self", ".", "locale_time", ".", "timezone", "for", "tz", "in", "tz_names", ")", ",", "'Z'", ")", ",", "'%'", ":", "'%'", "}", ")", "base", ".", "__setitem__", "(", "'W'", ",", "base", ".", "__getitem__", "(", "'U'", ")", ".", "replace", "(", "'U'", ",", "'W'", ")", ")", "base", ".", "__setitem__", "(", "'c'", ",", "self", ".", "pattern", "(", "self", ".", "locale_time", ".", "LC_date_time", ")", ")", "base", ".", "__setitem__", "(", "'x'", ",", "self", ".", "pattern", "(", "self", ".", "locale_time", ".", "LC_date", ")", ")", "base", ".", "__setitem__", "(", "'X'", ",", "self", ".", "pattern", "(", "self", ".", "locale_time", ".", "LC_time", ")", ")" ]
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/_strptime.py#L179-L219
gem5/gem5
141cc37c2d4b93959d4c249b8f7e6a8b2ef75338
util/gem5art/artifact/gem5art/artifact/_artifactdb.py
python
ArtifactMongoDB.__init__
(self, uri: str)
Initialize the mongodb connection and grab pointers to the databases uri is the location of the database in a mongodb compatible form. http://dochub.mongodb.org/core/connections.
Initialize the mongodb connection and grab pointers to the databases uri is the location of the database in a mongodb compatible form. http://dochub.mongodb.org/core/connections.
[ "Initialize", "the", "mongodb", "connection", "and", "grab", "pointers", "to", "the", "databases", "uri", "is", "the", "location", "of", "the", "database", "in", "a", "mongodb", "compatible", "form", ".", "http", ":", "//", "dochub", ".", "mongodb", ".", "org", "/", "core", "/", "connections", "." ]
def __init__(self, uri: str) -> None: """Initialize the mongodb connection and grab pointers to the databases uri is the location of the database in a mongodb compatible form. http://dochub.mongodb.org/core/connections. """ # Note: Need "connect=False" so that we don't connect until the first # time we interact with the database. Required for the gem5 running # celery server self.db = MongoClient(host=uri, connect=False).artifact_database self.artifacts = self.db.artifacts self.fs = gridfs.GridFSBucket(self.db, disable_md5=True)
[ "def", "__init__", "(", "self", ",", "uri", ":", "str", ")", "->", "None", ":", "# Note: Need \"connect=False\" so that we don't connect until the first", "# time we interact with the database. Required for the gem5 running", "# celery server", "self", ".", "db", "=", "MongoClient", "(", "host", "=", "uri", ",", "connect", "=", "False", ")", ".", "artifact_database", "self", ".", "artifacts", "=", "self", ".", "db", ".", "artifacts", "self", ".", "fs", "=", "gridfs", ".", "GridFSBucket", "(", "self", ".", "db", ",", "disable_md5", "=", "True", ")" ]
https://github.com/gem5/gem5/blob/141cc37c2d4b93959d4c249b8f7e6a8b2ef75338/util/gem5art/artifact/gem5art/artifact/_artifactdb.py#L137-L147
aimerykong/Low-Rank-Bilinear-Pooling
487eb2c857fd9c95357a5166b0c15ad0fe135b28
caffe-20160312/scripts/cpp_lint.py
python
_IsTestFilename
(filename)
Determines if the given filename has a suffix that identifies it as a test. Args: filename: The input filename. Returns: True if 'filename' looks like a test, False otherwise.
Determines if the given filename has a suffix that identifies it as a test.
[ "Determines", "if", "the", "given", "filename", "has", "a", "suffix", "that", "identifies", "it", "as", "a", "test", "." ]
def _IsTestFilename(filename): """Determines if the given filename has a suffix that identifies it as a test. Args: filename: The input filename. Returns: True if 'filename' looks like a test, False otherwise. """ if (filename.endswith('_test.cc') or filename.endswith('_unittest.cc') or filename.endswith('_regtest.cc')): return True else: return False
[ "def", "_IsTestFilename", "(", "filename", ")", ":", "if", "(", "filename", ".", "endswith", "(", "'_test.cc'", ")", "or", "filename", ".", "endswith", "(", "'_unittest.cc'", ")", "or", "filename", ".", "endswith", "(", "'_regtest.cc'", ")", ")", ":", "return", "True", "else", ":", "return", "False" ]
https://github.com/aimerykong/Low-Rank-Bilinear-Pooling/blob/487eb2c857fd9c95357a5166b0c15ad0fe135b28/caffe-20160312/scripts/cpp_lint.py#L3603-L3617
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py3/scipy/stats/_multivariate.py
python
ortho_group_gen._process_parameters
(self, dim)
return dim
Dimension N must be specified; it cannot be inferred.
Dimension N must be specified; it cannot be inferred.
[ "Dimension", "N", "must", "be", "specified", ";", "it", "cannot", "be", "inferred", "." ]
def _process_parameters(self, dim): """ Dimension N must be specified; it cannot be inferred. """ if dim is None or not np.isscalar(dim) or dim <= 1 or dim != int(dim): raise ValueError("Dimension of rotation must be specified," "and must be a scalar greater than 1.") return dim
[ "def", "_process_parameters", "(", "self", ",", "dim", ")", ":", "if", "dim", "is", "None", "or", "not", "np", ".", "isscalar", "(", "dim", ")", "or", "dim", "<=", "1", "or", "dim", "!=", "int", "(", "dim", ")", ":", "raise", "ValueError", "(", "\"Dimension of rotation must be specified,\"", "\"and must be a scalar greater than 1.\"", ")", "return", "dim" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/stats/_multivariate.py#L3490-L3499
okex/V3-Open-API-SDK
c5abb0db7e2287718e0055e17e57672ce0ec7fd9
okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/pkg_resources/__init__.py
python
get_supported_platform
()
return plat
Return this platform's maximum compatible version. distutils.util.get_platform() normally reports the minimum version of Mac OS X that would be required to *use* extensions produced by distutils. But what we want when checking compatibility is to know the version of Mac OS X that we are *running*. To allow usage of packages that explicitly require a newer version of Mac OS X, we must also know the current version of the OS. If this condition occurs for any other platform with a version in its platform strings, this function should be extended accordingly.
Return this platform's maximum compatible version.
[ "Return", "this", "platform", "s", "maximum", "compatible", "version", "." ]
def get_supported_platform(): """Return this platform's maximum compatible version. distutils.util.get_platform() normally reports the minimum version of Mac OS X that would be required to *use* extensions produced by distutils. But what we want when checking compatibility is to know the version of Mac OS X that we are *running*. To allow usage of packages that explicitly require a newer version of Mac OS X, we must also know the current version of the OS. If this condition occurs for any other platform with a version in its platform strings, this function should be extended accordingly. """ plat = get_build_platform() m = macosVersionString.match(plat) if m is not None and sys.platform == "darwin": try: plat = 'macosx-%s-%s' % ('.'.join(_macosx_vers()[:2]), m.group(3)) except ValueError: # not Mac OS X pass return plat
[ "def", "get_supported_platform", "(", ")", ":", "plat", "=", "get_build_platform", "(", ")", "m", "=", "macosVersionString", ".", "match", "(", "plat", ")", "if", "m", "is", "not", "None", "and", "sys", ".", "platform", "==", "\"darwin\"", ":", "try", ":", "plat", "=", "'macosx-%s-%s'", "%", "(", "'.'", ".", "join", "(", "_macosx_vers", "(", ")", "[", ":", "2", "]", ")", ",", "m", ".", "group", "(", "3", ")", ")", "except", "ValueError", ":", "# not Mac OS X", "pass", "return", "plat" ]
https://github.com/okex/V3-Open-API-SDK/blob/c5abb0db7e2287718e0055e17e57672ce0ec7fd9/okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/pkg_resources/__init__.py#L175-L196
greenheartgames/greenworks
3ea4ab490b56676de3f0a237c74bcfdb17323e60
deps/cpplint/cpplint.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/greenheartgames/greenworks/blob/3ea4ab490b56676de3f0a237c74bcfdb17323e60/deps/cpplint/cpplint.py#L1381-L1394
hpi-xnor/BMXNet
ed0b201da6667887222b8e4b5f997c4f6b61943d
python/mxnet/ndarray/ndarray.py
python
NDArray.square
(self, *args, **kwargs)
return op.square(self, *args, **kwargs)
Convenience fluent method for :py:func:`square`. The arguments are the same as for :py:func:`square`, with this array as data.
Convenience fluent method for :py:func:`square`.
[ "Convenience", "fluent", "method", "for", ":", "py", ":", "func", ":", "square", "." ]
def square(self, *args, **kwargs): """Convenience fluent method for :py:func:`square`. The arguments are the same as for :py:func:`square`, with this array as data. """ return op.square(self, *args, **kwargs)
[ "def", "square", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "op", ".", "square", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/hpi-xnor/BMXNet/blob/ed0b201da6667887222b8e4b5f997c4f6b61943d/python/mxnet/ndarray/ndarray.py#L1500-L1506
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/tornado/tornado-6/tornado/web.py
python
Application.add_handlers
(self, host_pattern: str, host_handlers: _RuleList)
Appends the given handlers to our handler list. Host patterns are processed sequentially in the order they were added. All matching patterns will be considered.
Appends the given handlers to our handler list.
[ "Appends", "the", "given", "handlers", "to", "our", "handler", "list", "." ]
def add_handlers(self, host_pattern: str, host_handlers: _RuleList) -> None: """Appends the given handlers to our handler list. Host patterns are processed sequentially in the order they were added. All matching patterns will be considered. """ host_matcher = HostMatches(host_pattern) rule = Rule(host_matcher, _ApplicationRouter(self, host_handlers)) self.default_router.rules.insert(-1, rule) if self.default_host is not None: self.wildcard_router.add_rules( [(DefaultHostMatches(self, host_matcher.host_pattern), host_handlers)] )
[ "def", "add_handlers", "(", "self", ",", "host_pattern", ":", "str", ",", "host_handlers", ":", "_RuleList", ")", "->", "None", ":", "host_matcher", "=", "HostMatches", "(", "host_pattern", ")", "rule", "=", "Rule", "(", "host_matcher", ",", "_ApplicationRouter", "(", "self", ",", "host_handlers", ")", ")", "self", ".", "default_router", ".", "rules", ".", "insert", "(", "-", "1", ",", "rule", ")", "if", "self", ".", "default_host", "is", "not", "None", ":", "self", ".", "wildcard_router", ".", "add_rules", "(", "[", "(", "DefaultHostMatches", "(", "self", ",", "host_matcher", ".", "host_pattern", ")", ",", "host_handlers", ")", "]", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/tornado/tornado-6/tornado/web.py#L2112-L2126
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/s3transfer/manager.py
python
TransferManager.download
(self, bucket, key, fileobj, extra_args=None, subscribers=None)
return self._submit_transfer( call_args, DownloadSubmissionTask, extra_main_kwargs)
Downloads a file from S3 :type bucket: str :param bucket: The name of the bucket to download from :type key: str :param key: The name of the key to download from :type fileobj: str or seekable file-like object :param fileobj: The name of a file to download or a seekable file-like object to download. It is recommended to use a filename because file-like objects may result in higher memory usage. :type extra_args: dict :param extra_args: Extra arguments that may be passed to the client operation :type subscribers: list(s3transfer.subscribers.BaseSubscriber) :param subscribers: The list of subscribers to be invoked in the order provided based on the event emit during the process of the transfer request. :rtype: s3transfer.futures.TransferFuture :returns: Transfer future representing the download
Downloads a file from S3
[ "Downloads", "a", "file", "from", "S3" ]
def download(self, bucket, key, fileobj, extra_args=None, subscribers=None): """Downloads a file from S3 :type bucket: str :param bucket: The name of the bucket to download from :type key: str :param key: The name of the key to download from :type fileobj: str or seekable file-like object :param fileobj: The name of a file to download or a seekable file-like object to download. It is recommended to use a filename because file-like objects may result in higher memory usage. :type extra_args: dict :param extra_args: Extra arguments that may be passed to the client operation :type subscribers: list(s3transfer.subscribers.BaseSubscriber) :param subscribers: The list of subscribers to be invoked in the order provided based on the event emit during the process of the transfer request. :rtype: s3transfer.futures.TransferFuture :returns: Transfer future representing the download """ if extra_args is None: extra_args = {} if subscribers is None: subscribers = [] self._validate_all_known_args(extra_args, self.ALLOWED_DOWNLOAD_ARGS) call_args = CallArgs( bucket=bucket, key=key, fileobj=fileobj, extra_args=extra_args, subscribers=subscribers ) extra_main_kwargs = {'io_executor': self._io_executor} if self._bandwidth_limiter: extra_main_kwargs['bandwidth_limiter'] = self._bandwidth_limiter return self._submit_transfer( call_args, DownloadSubmissionTask, extra_main_kwargs)
[ "def", "download", "(", "self", ",", "bucket", ",", "key", ",", "fileobj", ",", "extra_args", "=", "None", ",", "subscribers", "=", "None", ")", ":", "if", "extra_args", "is", "None", ":", "extra_args", "=", "{", "}", "if", "subscribers", "is", "None", ":", "subscribers", "=", "[", "]", "self", ".", "_validate_all_known_args", "(", "extra_args", ",", "self", ".", "ALLOWED_DOWNLOAD_ARGS", ")", "call_args", "=", "CallArgs", "(", "bucket", "=", "bucket", ",", "key", "=", "key", ",", "fileobj", "=", "fileobj", ",", "extra_args", "=", "extra_args", ",", "subscribers", "=", "subscribers", ")", "extra_main_kwargs", "=", "{", "'io_executor'", ":", "self", ".", "_io_executor", "}", "if", "self", ".", "_bandwidth_limiter", ":", "extra_main_kwargs", "[", "'bandwidth_limiter'", "]", "=", "self", ".", "_bandwidth_limiter", "return", "self", ".", "_submit_transfer", "(", "call_args", ",", "DownloadSubmissionTask", ",", "extra_main_kwargs", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/s3transfer/manager.py#L315-L355
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
torch/fx/experimental/unification/multipledispatch/dispatcher.py
python
Dispatcher.help
(self, *args, **kwargs)
Print docstring for the function corresponding to inputs
Print docstring for the function corresponding to inputs
[ "Print", "docstring", "for", "the", "function", "corresponding", "to", "inputs" ]
def help(self, *args, **kwargs): """ Print docstring for the function corresponding to inputs """ print(self._help(*args))
[ "def", "help", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "print", "(", "self", ".", "_help", "(", "*", "args", ")", ")" ]
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/fx/experimental/unification/multipledispatch/dispatcher.py#L362-L364
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemDefectReporter/v1/AWS/lambda-code/SanitizationLambda/sanitization_lambda.py
python
__validate_event
(event)
Validate content of event received.
Validate content of event received.
[ "Validate", "content", "of", "event", "received", "." ]
def __validate_event(event): ''' Validate content of event received. ''' if 'Records' not in event: raise RuntimeError('Malformed event received. (Records)')
[ "def", "__validate_event", "(", "event", ")", ":", "if", "'Records'", "not", "in", "event", ":", "raise", "RuntimeError", "(", "'Malformed event received. (Records)'", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/lambda-code/SanitizationLambda/sanitization_lambda.py#L52-L56
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/quopri.py
python
decode
(input, output, header=False)
Read 'input', apply quoted-printable decoding, and write to 'output'. 'input' and 'output' are binary file objects. If 'header' is true, decode underscore as space (per RFC 1522).
Read 'input', apply quoted-printable decoding, and write to 'output'. 'input' and 'output' are binary file objects. If 'header' is true, decode underscore as space (per RFC 1522).
[ "Read", "input", "apply", "quoted", "-", "printable", "decoding", "and", "write", "to", "output", ".", "input", "and", "output", "are", "binary", "file", "objects", ".", "If", "header", "is", "true", "decode", "underscore", "as", "space", "(", "per", "RFC", "1522", ")", "." ]
def decode(input, output, header=False): """Read 'input', apply quoted-printable decoding, and write to 'output'. 'input' and 'output' are binary file objects. If 'header' is true, decode underscore as space (per RFC 1522).""" if a2b_qp is not None: data = input.read() odata = a2b_qp(data, header=header) output.write(odata) return new = b'' while 1: line = input.readline() if not line: break i, n = 0, len(line) if n > 0 and line[n-1:n] == b'\n': partial = 0; n = n-1 # Strip trailing whitespace while n > 0 and line[n-1:n] in b" \t\r": n = n-1 else: partial = 1 while i < n: c = line[i:i+1] if c == b'_' and header: new = new + b' '; i = i+1 elif c != ESCAPE: new = new + c; i = i+1 elif i+1 == n and not partial: partial = 1; break elif i+1 < n and line[i+1:i+2] == ESCAPE: new = new + ESCAPE; i = i+2 elif i+2 < n and ishex(line[i+1:i+2]) and ishex(line[i+2:i+3]): new = new + bytes((unhex(line[i+1:i+3]),)); i = i+3 else: # Bad escape sequence -- leave it in new = new + c; i = i+1 if not partial: output.write(new + b'\n') new = b'' if new: output.write(new)
[ "def", "decode", "(", "input", ",", "output", ",", "header", "=", "False", ")", ":", "if", "a2b_qp", "is", "not", "None", ":", "data", "=", "input", ".", "read", "(", ")", "odata", "=", "a2b_qp", "(", "data", ",", "header", "=", "header", ")", "output", ".", "write", "(", "odata", ")", "return", "new", "=", "b''", "while", "1", ":", "line", "=", "input", ".", "readline", "(", ")", "if", "not", "line", ":", "break", "i", ",", "n", "=", "0", ",", "len", "(", "line", ")", "if", "n", ">", "0", "and", "line", "[", "n", "-", "1", ":", "n", "]", "==", "b'\\n'", ":", "partial", "=", "0", "n", "=", "n", "-", "1", "# Strip trailing whitespace", "while", "n", ">", "0", "and", "line", "[", "n", "-", "1", ":", "n", "]", "in", "b\" \\t\\r\"", ":", "n", "=", "n", "-", "1", "else", ":", "partial", "=", "1", "while", "i", "<", "n", ":", "c", "=", "line", "[", "i", ":", "i", "+", "1", "]", "if", "c", "==", "b'_'", "and", "header", ":", "new", "=", "new", "+", "b' '", "i", "=", "i", "+", "1", "elif", "c", "!=", "ESCAPE", ":", "new", "=", "new", "+", "c", "i", "=", "i", "+", "1", "elif", "i", "+", "1", "==", "n", "and", "not", "partial", ":", "partial", "=", "1", "break", "elif", "i", "+", "1", "<", "n", "and", "line", "[", "i", "+", "1", ":", "i", "+", "2", "]", "==", "ESCAPE", ":", "new", "=", "new", "+", "ESCAPE", "i", "=", "i", "+", "2", "elif", "i", "+", "2", "<", "n", "and", "ishex", "(", "line", "[", "i", "+", "1", ":", "i", "+", "2", "]", ")", "and", "ishex", "(", "line", "[", "i", "+", "2", ":", "i", "+", "3", "]", ")", ":", "new", "=", "new", "+", "bytes", "(", "(", "unhex", "(", "line", "[", "i", "+", "1", ":", "i", "+", "3", "]", ")", ",", ")", ")", "i", "=", "i", "+", "3", "else", ":", "# Bad escape sequence -- leave it in", "new", "=", "new", "+", "c", "i", "=", "i", "+", "1", "if", "not", "partial", ":", "output", ".", "write", "(", "new", "+", "b'\\n'", ")", "new", "=", "b''", "if", "new", ":", "output", ".", "write", "(", "new", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/quopri.py#L117-L158
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/klampt/math/symbolic_io.py
python
exprFromStr
(context,string,fmt=None,add=False)
Returns an Expression from a string. In auto mode, this reads in constants in klampt.loader JSON- compatible format, standard variables in the form "x", user data in the form of strings prepended with $ (e.g., "$x"), and named expression references in the form of strings prepended with @. Args: context (Context): the context containing possible functions in string string (str): the string to parse. fmt (str, optional): specifies a format for the string. Can be None (auto), 'auto', or 'json' add (bool, optional): if true, adds all variables referenced in the string to the context. Otherwise, undefined variables are referred to as user data. An exception is raised on parsing failure. (Parsing is a little slow, so try not to use it in tight inner loops) Returns: (Expression): the expression represented by str.
Returns an Expression from a string. In auto mode, this reads in constants in klampt.loader JSON- compatible format, standard variables in the form "x", user data in the form of strings prepended with $ (e.g., "$x"), and named expression references in the form of strings prepended with @.
[ "Returns", "an", "Expression", "from", "a", "string", ".", "In", "auto", "mode", "this", "reads", "in", "constants", "in", "klampt", ".", "loader", "JSON", "-", "compatible", "format", "standard", "variables", "in", "the", "form", "x", "user", "data", "in", "the", "form", "of", "strings", "prepended", "with", "$", "(", "e", ".", "g", ".", "$x", ")", "and", "named", "expression", "references", "in", "the", "form", "of", "strings", "prepended", "with", "@", "." ]
def exprFromStr(context,string,fmt=None,add=False): """Returns an Expression from a string. In auto mode, this reads in constants in klampt.loader JSON- compatible format, standard variables in the form "x", user data in the form of strings prepended with $ (e.g., "$x"), and named expression references in the form of strings prepended with @. Args: context (Context): the context containing possible functions in string string (str): the string to parse. fmt (str, optional): specifies a format for the string. Can be None (auto), 'auto', or 'json' add (bool, optional): if true, adds all variables referenced in the string to the context. Otherwise, undefined variables are referred to as user data. An exception is raised on parsing failure. (Parsing is a little slow, so try not to use it in tight inner loops) Returns: (Expression): the expression represented by str. """ if len(string) == 0: raise ValueError("Empty string provided") if fmt == None: if string[0] == '{': fmt = 'json' else: fmt = 'auto' if fmt == 'auto': import re,ast USERDATA_MARKER = '___' EXPR_MARKER = '____' TAGLIST_NAME = '__tagexprlist__' taglist = context.expressions.copy() def __settag__(self,tagname,taglist): assert isinstance(tagname,ConstantExpression) and isinstance(tagname.value,str) taglist[tagname.value] = self return self def __gettag__(tagname,taglist): assert isinstance(tagname,ConstantExpression) and isinstance(tagname.value,str) return taglist[tagname.value] Expression.__settag__ = __settag__ x = re.sub(r"\$(\w+)", r"___\1",string) x = re.sub(r"\#(\w+)", r'.__settag__("\1",__tagexprlist__)',x) x = re.sub(r"\@(\w+)", r'__gettag__("\1",__tagexprlist__)',x) #print "Substituted string",x tree = ast.parse(x,mode='eval') missing_functions = [] missing_names = [] userdata = {} #hack to easily access functions with the class.attribute syntax allFunctions = _builtin_functions.copy() for name,func in context.customFunctions.items(): path = name.split('.') if len(path) == 1: allFunctions[name] = func else: if path[0] not in allFunctions: allFunctions[path[0]] = _Object() root = allFunctions[path[0]] for n in path[1:-1]: if not hasattr(root,n): setattr(root,n,_Object()) root = getattr(root,n) setattr(root,path[-1],func) allFunctions[TAGLIST_NAME] = taglist allFunctions['__gettag__'] = __gettag__ class RewriteVarNames(ast.NodeTransformer): def __init__(self): self.infunc = False def visit_Call(self,node): self.infunc = True self.generic_visit(node) return node def visit_Name(self, node): if self.infunc: self.infunc = False if node.id not in allFunctions: missing_functions.append(node.id) return node if node.id.startswith(USERDATA_MARKER): basename = node.id[len(USERDATA_MARKER):] userdata[node.id] = expr(basename) else: if node.id in context.variableDict: userdata[node.id] = expr(context.variableDict[node.id]) elif add: userdata[node.id] = expr(context.addVar(node.id,'N')) elif node.id == TAGLIST_NAME: pass else: missing_names.append(node.id) userdata[node.id] = expr(node.id) return node def visit_Num(self, node): return ast.copy_location(ast.Call(func=ast.copy_location(ast.Name(id="_const",ctx=ast.Load()),node),args=[node],keywords=[]),node) def visit_Str(self, node): return ast.copy_location(ast.Call(func=ast.copy_location(ast.Name(id="_const",ctx=ast.Load()),node),args=[node],keywords=[]),node) def visit_List(self, node): args = [] for idx, item in enumerate(node.elts): args.append(self.visit(item)) return ast.copy_location(ast.Call(func=ast.copy_location(ast.Name(id="_convert_list",ctx=ast.Load()),node),args=args,keywords=[]),node) def visit_Tuple(self, node): args = [] for idx, item in enumerate(node.elts): args.append(self.visit(item)) return ast.copy_location(ast.Call(func=ast.copy_location(ast.Name(id="_convert_list",ctx=ast.Load()),node),args=args,keywords=[]),node) #print "old tree:",ast.dump(tree) newtree = RewriteVarNames().visit(tree) #print "new tree:",ast.dump(newtree) if len(missing_functions) > 0: raise ValueError("Undefined functions "+','.join(missing_functions)) if len(missing_names) > 0: raise ValueError("Undefined variable "+','.join(missing_names)) allFunctions['_const'] = const allFunctions['_convert_list'] = lambda *args:array(*args) ctree = compile(newtree, filename="<ast>", mode="eval") res = eval(ctree,allFunctions,userdata) delattr(Expression,'__settag__') return res elif fmt == 'json': import json obj = json.parse(str) return exprFromJson(context,obj) else: raise ValueError("Invalid format "+fmt)
[ "def", "exprFromStr", "(", "context", ",", "string", ",", "fmt", "=", "None", ",", "add", "=", "False", ")", ":", "if", "len", "(", "string", ")", "==", "0", ":", "raise", "ValueError", "(", "\"Empty string provided\"", ")", "if", "fmt", "==", "None", ":", "if", "string", "[", "0", "]", "==", "'{'", ":", "fmt", "=", "'json'", "else", ":", "fmt", "=", "'auto'", "if", "fmt", "==", "'auto'", ":", "import", "re", ",", "ast", "USERDATA_MARKER", "=", "'___'", "EXPR_MARKER", "=", "'____'", "TAGLIST_NAME", "=", "'__tagexprlist__'", "taglist", "=", "context", ".", "expressions", ".", "copy", "(", ")", "def", "__settag__", "(", "self", ",", "tagname", ",", "taglist", ")", ":", "assert", "isinstance", "(", "tagname", ",", "ConstantExpression", ")", "and", "isinstance", "(", "tagname", ".", "value", ",", "str", ")", "taglist", "[", "tagname", ".", "value", "]", "=", "self", "return", "self", "def", "__gettag__", "(", "tagname", ",", "taglist", ")", ":", "assert", "isinstance", "(", "tagname", ",", "ConstantExpression", ")", "and", "isinstance", "(", "tagname", ".", "value", ",", "str", ")", "return", "taglist", "[", "tagname", ".", "value", "]", "Expression", ".", "__settag__", "=", "__settag__", "x", "=", "re", ".", "sub", "(", "r\"\\$(\\w+)\"", ",", "r\"___\\1\"", ",", "string", ")", "x", "=", "re", ".", "sub", "(", "r\"\\#(\\w+)\"", ",", "r'.__settag__(\"\\1\",__tagexprlist__)'", ",", "x", ")", "x", "=", "re", ".", "sub", "(", "r\"\\@(\\w+)\"", ",", "r'__gettag__(\"\\1\",__tagexprlist__)'", ",", "x", ")", "#print \"Substituted string\",x", "tree", "=", "ast", ".", "parse", "(", "x", ",", "mode", "=", "'eval'", ")", "missing_functions", "=", "[", "]", "missing_names", "=", "[", "]", "userdata", "=", "{", "}", "#hack to easily access functions with the class.attribute syntax", "allFunctions", "=", "_builtin_functions", ".", "copy", "(", ")", "for", "name", ",", "func", "in", "context", ".", "customFunctions", ".", "items", "(", ")", ":", "path", "=", "name", ".", "split", "(", "'.'", ")", "if", "len", "(", "path", ")", "==", "1", ":", "allFunctions", "[", "name", "]", "=", "func", "else", ":", "if", "path", "[", "0", "]", "not", "in", "allFunctions", ":", "allFunctions", "[", "path", "[", "0", "]", "]", "=", "_Object", "(", ")", "root", "=", "allFunctions", "[", "path", "[", "0", "]", "]", "for", "n", "in", "path", "[", "1", ":", "-", "1", "]", ":", "if", "not", "hasattr", "(", "root", ",", "n", ")", ":", "setattr", "(", "root", ",", "n", ",", "_Object", "(", ")", ")", "root", "=", "getattr", "(", "root", ",", "n", ")", "setattr", "(", "root", ",", "path", "[", "-", "1", "]", ",", "func", ")", "allFunctions", "[", "TAGLIST_NAME", "]", "=", "taglist", "allFunctions", "[", "'__gettag__'", "]", "=", "__gettag__", "class", "RewriteVarNames", "(", "ast", ".", "NodeTransformer", ")", ":", "def", "__init__", "(", "self", ")", ":", "self", ".", "infunc", "=", "False", "def", "visit_Call", "(", "self", ",", "node", ")", ":", "self", ".", "infunc", "=", "True", "self", ".", "generic_visit", "(", "node", ")", "return", "node", "def", "visit_Name", "(", "self", ",", "node", ")", ":", "if", "self", ".", "infunc", ":", "self", ".", "infunc", "=", "False", "if", "node", ".", "id", "not", "in", "allFunctions", ":", "missing_functions", ".", "append", "(", "node", ".", "id", ")", "return", "node", "if", "node", ".", "id", ".", "startswith", "(", "USERDATA_MARKER", ")", ":", "basename", "=", "node", ".", "id", "[", "len", "(", "USERDATA_MARKER", ")", ":", "]", "userdata", "[", "node", ".", "id", "]", "=", "expr", "(", "basename", ")", "else", ":", "if", "node", ".", "id", "in", "context", ".", "variableDict", ":", "userdata", "[", "node", ".", "id", "]", "=", "expr", "(", "context", ".", "variableDict", "[", "node", ".", "id", "]", ")", "elif", "add", ":", "userdata", "[", "node", ".", "id", "]", "=", "expr", "(", "context", ".", "addVar", "(", "node", ".", "id", ",", "'N'", ")", ")", "elif", "node", ".", "id", "==", "TAGLIST_NAME", ":", "pass", "else", ":", "missing_names", ".", "append", "(", "node", ".", "id", ")", "userdata", "[", "node", ".", "id", "]", "=", "expr", "(", "node", ".", "id", ")", "return", "node", "def", "visit_Num", "(", "self", ",", "node", ")", ":", "return", "ast", ".", "copy_location", "(", "ast", ".", "Call", "(", "func", "=", "ast", ".", "copy_location", "(", "ast", ".", "Name", "(", "id", "=", "\"_const\"", ",", "ctx", "=", "ast", ".", "Load", "(", ")", ")", ",", "node", ")", ",", "args", "=", "[", "node", "]", ",", "keywords", "=", "[", "]", ")", ",", "node", ")", "def", "visit_Str", "(", "self", ",", "node", ")", ":", "return", "ast", ".", "copy_location", "(", "ast", ".", "Call", "(", "func", "=", "ast", ".", "copy_location", "(", "ast", ".", "Name", "(", "id", "=", "\"_const\"", ",", "ctx", "=", "ast", ".", "Load", "(", ")", ")", ",", "node", ")", ",", "args", "=", "[", "node", "]", ",", "keywords", "=", "[", "]", ")", ",", "node", ")", "def", "visit_List", "(", "self", ",", "node", ")", ":", "args", "=", "[", "]", "for", "idx", ",", "item", "in", "enumerate", "(", "node", ".", "elts", ")", ":", "args", ".", "append", "(", "self", ".", "visit", "(", "item", ")", ")", "return", "ast", ".", "copy_location", "(", "ast", ".", "Call", "(", "func", "=", "ast", ".", "copy_location", "(", "ast", ".", "Name", "(", "id", "=", "\"_convert_list\"", ",", "ctx", "=", "ast", ".", "Load", "(", ")", ")", ",", "node", ")", ",", "args", "=", "args", ",", "keywords", "=", "[", "]", ")", ",", "node", ")", "def", "visit_Tuple", "(", "self", ",", "node", ")", ":", "args", "=", "[", "]", "for", "idx", ",", "item", "in", "enumerate", "(", "node", ".", "elts", ")", ":", "args", ".", "append", "(", "self", ".", "visit", "(", "item", ")", ")", "return", "ast", ".", "copy_location", "(", "ast", ".", "Call", "(", "func", "=", "ast", ".", "copy_location", "(", "ast", ".", "Name", "(", "id", "=", "\"_convert_list\"", ",", "ctx", "=", "ast", ".", "Load", "(", ")", ")", ",", "node", ")", ",", "args", "=", "args", ",", "keywords", "=", "[", "]", ")", ",", "node", ")", "#print \"old tree:\",ast.dump(tree)", "newtree", "=", "RewriteVarNames", "(", ")", ".", "visit", "(", "tree", ")", "#print \"new tree:\",ast.dump(newtree)", "if", "len", "(", "missing_functions", ")", ">", "0", ":", "raise", "ValueError", "(", "\"Undefined functions \"", "+", "','", ".", "join", "(", "missing_functions", ")", ")", "if", "len", "(", "missing_names", ")", ">", "0", ":", "raise", "ValueError", "(", "\"Undefined variable \"", "+", "','", ".", "join", "(", "missing_names", ")", ")", "allFunctions", "[", "'_const'", "]", "=", "const", "allFunctions", "[", "'_convert_list'", "]", "=", "lambda", "*", "args", ":", "array", "(", "*", "args", ")", "ctree", "=", "compile", "(", "newtree", ",", "filename", "=", "\"<ast>\"", ",", "mode", "=", "\"eval\"", ")", "res", "=", "eval", "(", "ctree", ",", "allFunctions", ",", "userdata", ")", "delattr", "(", "Expression", ",", "'__settag__'", ")", "return", "res", "elif", "fmt", "==", "'json'", ":", "import", "json", "obj", "=", "json", ".", "parse", "(", "str", ")", "return", "exprFromJson", "(", "context", ",", "obj", ")", "else", ":", "raise", "ValueError", "(", "\"Invalid format \"", "+", "fmt", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/math/symbolic_io.py#L317-L444
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/build/waf-1.7.13/lmbrwaflib/cryengine_modules.py
python
GetPlatformSpecificSettings
(ctx, dict, entry, _platform, configuration)
return returnValue
Util function to apply flags based on current platform
Util function to apply flags based on current platform
[ "Util", "function", "to", "apply", "flags", "based", "on", "current", "platform" ]
def GetPlatformSpecificSettings(ctx, dict, entry, _platform, configuration): """ Util function to apply flags based on current platform """ def _to_list( value ): if isinstance(value,list): return value return [ value ] returnValue = [] platforms = ctx.get_current_platform_list(_platform) # Check for entry in <platform>_<entry> style for platform in platforms: platform_entry = platform + '_' + entry if not platform_entry in dict: continue # No platfrom specific entry found returnValue += _to_list( dict[platform_entry] ) if configuration == []: return [] # Dont try to check for configurations if we dont have any # Check for 'test' or 'dedicated' tagged entries if _platform and _platform != 'project_generator': platform_details = ctx.get_target_platform_detail(_platform) configuration_details = platform_details.get_configuration(configuration) if configuration_details.is_test: test_entry = 'test_{}'.format(entry) if test_entry in dict: returnValue += _to_list(dict[test_entry]) for platform in platforms: platform_test_entry = '{}_test_{}'.format(platform, entry) if platform_test_entry in dict: returnValue += _to_list(dict[platform_test_entry]) if configuration_details.is_server: test_entry = 'dedicated_{}'.format(entry) if test_entry in dict: returnValue += _to_list(dict[test_entry]) for platform in platforms: platform_test_entry = '{}_dedicated_{}'.format(platform, entry) if platform_test_entry in dict: returnValue += _to_list(dict[platform_test_entry]) # Check for entry in <configuration>_<entry> style configuration_entry = configuration + '_' + entry if configuration_entry in dict: returnValue += _to_list( dict[configuration_entry] ) # Check for entry in <platform>_<configuration>_<entry> style for platform in platforms: platform_configuration_entry = platform + '_' + configuration + '_' + entry if not platform_configuration_entry in dict: continue # No platfrom /configuration specific entry found returnValue += _to_list( dict[platform_configuration_entry] ) return returnValue
[ "def", "GetPlatformSpecificSettings", "(", "ctx", ",", "dict", ",", "entry", ",", "_platform", ",", "configuration", ")", ":", "def", "_to_list", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "list", ")", ":", "return", "value", "return", "[", "value", "]", "returnValue", "=", "[", "]", "platforms", "=", "ctx", ".", "get_current_platform_list", "(", "_platform", ")", "# Check for entry in <platform>_<entry> style", "for", "platform", "in", "platforms", ":", "platform_entry", "=", "platform", "+", "'_'", "+", "entry", "if", "not", "platform_entry", "in", "dict", ":", "continue", "# No platfrom specific entry found", "returnValue", "+=", "_to_list", "(", "dict", "[", "platform_entry", "]", ")", "if", "configuration", "==", "[", "]", ":", "return", "[", "]", "# Dont try to check for configurations if we dont have any", "# Check for 'test' or 'dedicated' tagged entries", "if", "_platform", "and", "_platform", "!=", "'project_generator'", ":", "platform_details", "=", "ctx", ".", "get_target_platform_detail", "(", "_platform", ")", "configuration_details", "=", "platform_details", ".", "get_configuration", "(", "configuration", ")", "if", "configuration_details", ".", "is_test", ":", "test_entry", "=", "'test_{}'", ".", "format", "(", "entry", ")", "if", "test_entry", "in", "dict", ":", "returnValue", "+=", "_to_list", "(", "dict", "[", "test_entry", "]", ")", "for", "platform", "in", "platforms", ":", "platform_test_entry", "=", "'{}_test_{}'", ".", "format", "(", "platform", ",", "entry", ")", "if", "platform_test_entry", "in", "dict", ":", "returnValue", "+=", "_to_list", "(", "dict", "[", "platform_test_entry", "]", ")", "if", "configuration_details", ".", "is_server", ":", "test_entry", "=", "'dedicated_{}'", ".", "format", "(", "entry", ")", "if", "test_entry", "in", "dict", ":", "returnValue", "+=", "_to_list", "(", "dict", "[", "test_entry", "]", ")", "for", "platform", "in", "platforms", ":", "platform_test_entry", "=", "'{}_dedicated_{}'", ".", "format", "(", "platform", ",", "entry", ")", "if", "platform_test_entry", "in", "dict", ":", "returnValue", "+=", "_to_list", "(", "dict", "[", "platform_test_entry", "]", ")", "# Check for entry in <configuration>_<entry> style", "configuration_entry", "=", "configuration", "+", "'_'", "+", "entry", "if", "configuration_entry", "in", "dict", ":", "returnValue", "+=", "_to_list", "(", "dict", "[", "configuration_entry", "]", ")", "# Check for entry in <platform>_<configuration>_<entry> style", "for", "platform", "in", "platforms", ":", "platform_configuration_entry", "=", "platform", "+", "'_'", "+", "configuration", "+", "'_'", "+", "entry", "if", "not", "platform_configuration_entry", "in", "dict", ":", "continue", "# No platfrom /configuration specific entry found", "returnValue", "+=", "_to_list", "(", "dict", "[", "platform_configuration_entry", "]", ")", "return", "returnValue" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/build/waf-1.7.13/lmbrwaflib/cryengine_modules.py#L2446-L2507
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/turtle.py
python
TNavigator.pos
(self)
return self._position
Return the turtle's current location (x,y), as a Vec2D-vector. Aliases: pos | position No arguments. Example (for a Turtle instance named turtle): >>> turtle.pos() (0.00, 240.00)
Return the turtle's current location (x,y), as a Vec2D-vector.
[ "Return", "the", "turtle", "s", "current", "location", "(", "x", "y", ")", "as", "a", "Vec2D", "-", "vector", "." ]
def pos(self): """Return the turtle's current location (x,y), as a Vec2D-vector. Aliases: pos | position No arguments. Example (for a Turtle instance named turtle): >>> turtle.pos() (0.00, 240.00) """ return self._position
[ "def", "pos", "(", "self", ")", ":", "return", "self", ".", "_position" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/turtle.py#L1616-L1627
google/earthenterprise
0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9
earth_enterprise/src/fusion/portableglobe/servers/search_services/search_service_geplaces.py
python
RegisterSearchService
(search_services)
return search_services[SEARCH_SERVICE_NAME]
Creates a new search service object and adds it by name to the dict. Args: search_services: dict to which the new search service should be added using its name as the key. Returns: the new search service object.
Creates a new search service object and adds it by name to the dict.
[ "Creates", "a", "new", "search", "service", "object", "and", "adds", "it", "by", "name", "to", "the", "dict", "." ]
def RegisterSearchService(search_services): """Creates a new search service object and adds it by name to the dict. Args: search_services: dict to which the new search service should be added using its name as the key. Returns: the new search service object. """ if SEARCH_SERVICE_NAME in search_services.keys(): print "Warning: replacing existing %s service." % SEARCH_SERVICE_NAME search_services[SEARCH_SERVICE_NAME] = GEPlacesSearch() return search_services[SEARCH_SERVICE_NAME]
[ "def", "RegisterSearchService", "(", "search_services", ")", ":", "if", "SEARCH_SERVICE_NAME", "in", "search_services", ".", "keys", "(", ")", ":", "print", "\"Warning: replacing existing %s service.\"", "%", "SEARCH_SERVICE_NAME", "search_services", "[", "SEARCH_SERVICE_NAME", "]", "=", "GEPlacesSearch", "(", ")", "return", "search_services", "[", "SEARCH_SERVICE_NAME", "]" ]
https://github.com/google/earthenterprise/blob/0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9/earth_enterprise/src/fusion/portableglobe/servers/search_services/search_service_geplaces.py#L127-L140
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/tensorflow/contrib/distributions/python/ops/normal_conjugate_posteriors.py
python
normal_congugates_known_sigma_predictive
(prior, sigma, s, n)
return Normal( mu=(prior.mu/sigma0_2 + s/sigma_2) * sigmap_2, sigma=math_ops.sqrt(sigmap_2 + sigma_2))
Posterior predictive Normal distribution w. conjugate prior on the mean. This model assumes that `n` observations (with sum `s`) come from a Normal with unknown mean `mu` (described by the Normal `prior`) and known variance `sigma^2`. The "known sigma predictive" is the distribution of new observations, conditioned on the existing observations and our prior. Accepts a prior Normal distribution object, having parameters `mu0` and `sigma0`, as well as known `sigma` values of the predictive distribution(s) (also assumed Normal), and statistical estimates `s` (the sum(s) of the observations) and `n` (the number(s) of observations). Calculates the Normal distribution(s) `p(x | sigma^2)`: ``` p(x | sigma^2) = int N(x | mu, sigma^2) N(mu | prior.mu, prior.sigma^2) dmu = N(x | prior.mu, 1/(sigma^2 + prior.sigma^2)) ``` Returns the predictive posterior distribution object, with parameters `(mu', sigma'^2)`, where: ``` sigma_n^2 = 1/(1/sigma0^2 + n/sigma^2), mu' = (mu0/sigma0^2 + s/sigma^2) * sigma_n^2. sigma'^2 = sigma_n^2 + sigma^2, ``` Distribution parameters from `prior`, as well as `sigma`, `s`, and `n`. will broadcast in the case of multidimensional sets of parameters. Args: prior: `Normal` object of type `dtype`: the prior distribution having parameters `(mu0, sigma0)`. sigma: tensor of type `dtype`, taking values `sigma > 0`. The known stddev parameter(s). s: Tensor of type `dtype`. The sum(s) of observations. n: Tensor of type `int`. The number(s) of observations. Returns: A new Normal predictive distribution object. Raises: TypeError: if dtype of `s` does not match `dtype`, or `prior` is not a Normal object.
Posterior predictive Normal distribution w. conjugate prior on the mean.
[ "Posterior", "predictive", "Normal", "distribution", "w", ".", "conjugate", "prior", "on", "the", "mean", "." ]
def normal_congugates_known_sigma_predictive(prior, sigma, s, n): """Posterior predictive Normal distribution w. conjugate prior on the mean. This model assumes that `n` observations (with sum `s`) come from a Normal with unknown mean `mu` (described by the Normal `prior`) and known variance `sigma^2`. The "known sigma predictive" is the distribution of new observations, conditioned on the existing observations and our prior. Accepts a prior Normal distribution object, having parameters `mu0` and `sigma0`, as well as known `sigma` values of the predictive distribution(s) (also assumed Normal), and statistical estimates `s` (the sum(s) of the observations) and `n` (the number(s) of observations). Calculates the Normal distribution(s) `p(x | sigma^2)`: ``` p(x | sigma^2) = int N(x | mu, sigma^2) N(mu | prior.mu, prior.sigma^2) dmu = N(x | prior.mu, 1/(sigma^2 + prior.sigma^2)) ``` Returns the predictive posterior distribution object, with parameters `(mu', sigma'^2)`, where: ``` sigma_n^2 = 1/(1/sigma0^2 + n/sigma^2), mu' = (mu0/sigma0^2 + s/sigma^2) * sigma_n^2. sigma'^2 = sigma_n^2 + sigma^2, ``` Distribution parameters from `prior`, as well as `sigma`, `s`, and `n`. will broadcast in the case of multidimensional sets of parameters. Args: prior: `Normal` object of type `dtype`: the prior distribution having parameters `(mu0, sigma0)`. sigma: tensor of type `dtype`, taking values `sigma > 0`. The known stddev parameter(s). s: Tensor of type `dtype`. The sum(s) of observations. n: Tensor of type `int`. The number(s) of observations. Returns: A new Normal predictive distribution object. Raises: TypeError: if dtype of `s` does not match `dtype`, or `prior` is not a Normal object. """ if not isinstance(prior, Normal): raise TypeError("Expected prior to be an instance of type Normal") if s.dtype != prior.dtype: raise TypeError( "Observation sum s.dtype does not match prior dtype: %s vs. %s" % (s.dtype, prior.dtype)) n = math_ops.cast(n, prior.dtype) sigma0_2 = math_ops.square(prior.sigma) sigma_2 = math_ops.square(sigma) sigmap_2 = 1.0/(1/sigma0_2 + n/sigma_2) return Normal( mu=(prior.mu/sigma0_2 + s/sigma_2) * sigmap_2, sigma=math_ops.sqrt(sigmap_2 + sigma_2))
[ "def", "normal_congugates_known_sigma_predictive", "(", "prior", ",", "sigma", ",", "s", ",", "n", ")", ":", "if", "not", "isinstance", "(", "prior", ",", "Normal", ")", ":", "raise", "TypeError", "(", "\"Expected prior to be an instance of type Normal\"", ")", "if", "s", ".", "dtype", "!=", "prior", ".", "dtype", ":", "raise", "TypeError", "(", "\"Observation sum s.dtype does not match prior dtype: %s vs. %s\"", "%", "(", "s", ".", "dtype", ",", "prior", ".", "dtype", ")", ")", "n", "=", "math_ops", ".", "cast", "(", "n", ",", "prior", ".", "dtype", ")", "sigma0_2", "=", "math_ops", ".", "square", "(", "prior", ".", "sigma", ")", "sigma_2", "=", "math_ops", ".", "square", "(", "sigma", ")", "sigmap_2", "=", "1.0", "/", "(", "1", "/", "sigma0_2", "+", "n", "/", "sigma_2", ")", "return", "Normal", "(", "mu", "=", "(", "prior", ".", "mu", "/", "sigma0_2", "+", "s", "/", "sigma_2", ")", "*", "sigmap_2", ",", "sigma", "=", "math_ops", ".", "sqrt", "(", "sigmap_2", "+", "sigma_2", ")", ")" ]
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/contrib/distributions/python/ops/normal_conjugate_posteriors.py#L85-L148
hughperkins/tf-coriander
970d3df6c11400ad68405f22b0c42a52374e94ca
tensorflow/python/training/saver.py
python
BaseSaverBuilder._AddShardedSaveOpsForV2
(self, checkpoint_prefix, per_device)
Add ops to save the params per shard, for the V2 format. Note that the sharded save procedure for the V2 format is different from V1: there is a special "merge" step that merges the small metadata produced from each device. Args: checkpoint_prefix: scalar String Tensor. Interpreted *NOT AS A FILENAME*, but as a prefix of a V2 checkpoint; per_device: A list of (device, BaseSaverBuilder.VarToSave) pairs, as returned by _GroupByDevices(). Returns: An op to save the variables, which, when evaluated, returns the prefix "<user-fed prefix>" only and does not include the sharded spec suffix.
Add ops to save the params per shard, for the V2 format.
[ "Add", "ops", "to", "save", "the", "params", "per", "shard", "for", "the", "V2", "format", "." ]
def _AddShardedSaveOpsForV2(self, checkpoint_prefix, per_device): """Add ops to save the params per shard, for the V2 format. Note that the sharded save procedure for the V2 format is different from V1: there is a special "merge" step that merges the small metadata produced from each device. Args: checkpoint_prefix: scalar String Tensor. Interpreted *NOT AS A FILENAME*, but as a prefix of a V2 checkpoint; per_device: A list of (device, BaseSaverBuilder.VarToSave) pairs, as returned by _GroupByDevices(). Returns: An op to save the variables, which, when evaluated, returns the prefix "<user-fed prefix>" only and does not include the sharded spec suffix. """ # IMPLEMENTATION DETAILS: most clients should skip. # # Suffix for any well-formed "checkpoint_prefix", when sharded. # Transformations: # * Users pass in "save_path" in save() and restore(). Say "myckpt". # * checkpoint_prefix gets fed <save_path><_SHARDED_SUFFIX>. # # Example: # During runtime, a temporary directory is first created, which contains # files # # <train dir>/myckpt_temp/ # part-?????-of-?????{.index, .data-00000-of-00001} # # Before .save() finishes, they will be (hopefully, atomically) renamed to # # <train dir>/ # myckpt{.index, .data-?????-of-?????} # # Users only need to interact with the user-specified prefix, which is # "<train dir>/myckpt" in this case. Save() and Restore() work with the # prefix directly, instead of any physical pathname. (On failure and # subsequent restore, an outdated and orphaned temporary directory can be # safely removed.) _SHARDED_SUFFIX = "_temp_%s/part" % uuid.uuid4().hex tmp_checkpoint_prefix = string_ops.string_join( [checkpoint_prefix, _SHARDED_SUFFIX]) num_shards = len(per_device) sharded_saves = [] sharded_prefixes = [] num_shards_tensor = constant_op.constant(num_shards, name="num_shards") last_device = None for shard, (device, saveables) in enumerate(per_device): last_device = device with ops.device(device): sharded_filename = self.sharded_filename(tmp_checkpoint_prefix, shard, num_shards_tensor) sharded_prefixes.append(sharded_filename) sharded_saves.append(self._AddSaveOps(sharded_filename, saveables)) with ops.control_dependencies([x.op for x in sharded_saves]): # Co-locates the merge step with the last device. with ops.device(last_device): # V2 format write path consists of a metadata merge step. Once merged, # attempts to delete the temporary directory, "<user-fed prefix>_temp". merge_step = gen_io_ops.merge_v2_checkpoints( sharded_prefixes, checkpoint_prefix, delete_old_dirs=True) with ops.control_dependencies([merge_step]): # Returns the prefix "<user-fed prefix>" only. DOES NOT include the # sharded spec suffix. return array_ops.identity(checkpoint_prefix)
[ "def", "_AddShardedSaveOpsForV2", "(", "self", ",", "checkpoint_prefix", ",", "per_device", ")", ":", "# IMPLEMENTATION DETAILS: most clients should skip.", "#", "# Suffix for any well-formed \"checkpoint_prefix\", when sharded.", "# Transformations:", "# * Users pass in \"save_path\" in save() and restore(). Say \"myckpt\".", "# * checkpoint_prefix gets fed <save_path><_SHARDED_SUFFIX>.", "#", "# Example:", "# During runtime, a temporary directory is first created, which contains", "# files", "#", "# <train dir>/myckpt_temp/", "# part-?????-of-?????{.index, .data-00000-of-00001}", "#", "# Before .save() finishes, they will be (hopefully, atomically) renamed to", "#", "# <train dir>/", "# myckpt{.index, .data-?????-of-?????}", "#", "# Users only need to interact with the user-specified prefix, which is", "# \"<train dir>/myckpt\" in this case. Save() and Restore() work with the", "# prefix directly, instead of any physical pathname. (On failure and", "# subsequent restore, an outdated and orphaned temporary directory can be", "# safely removed.)", "_SHARDED_SUFFIX", "=", "\"_temp_%s/part\"", "%", "uuid", ".", "uuid4", "(", ")", ".", "hex", "tmp_checkpoint_prefix", "=", "string_ops", ".", "string_join", "(", "[", "checkpoint_prefix", ",", "_SHARDED_SUFFIX", "]", ")", "num_shards", "=", "len", "(", "per_device", ")", "sharded_saves", "=", "[", "]", "sharded_prefixes", "=", "[", "]", "num_shards_tensor", "=", "constant_op", ".", "constant", "(", "num_shards", ",", "name", "=", "\"num_shards\"", ")", "last_device", "=", "None", "for", "shard", ",", "(", "device", ",", "saveables", ")", "in", "enumerate", "(", "per_device", ")", ":", "last_device", "=", "device", "with", "ops", ".", "device", "(", "device", ")", ":", "sharded_filename", "=", "self", ".", "sharded_filename", "(", "tmp_checkpoint_prefix", ",", "shard", ",", "num_shards_tensor", ")", "sharded_prefixes", ".", "append", "(", "sharded_filename", ")", "sharded_saves", ".", "append", "(", "self", ".", "_AddSaveOps", "(", "sharded_filename", ",", "saveables", ")", ")", "with", "ops", ".", "control_dependencies", "(", "[", "x", ".", "op", "for", "x", "in", "sharded_saves", "]", ")", ":", "# Co-locates the merge step with the last device.", "with", "ops", ".", "device", "(", "last_device", ")", ":", "# V2 format write path consists of a metadata merge step. Once merged,", "# attempts to delete the temporary directory, \"<user-fed prefix>_temp\".", "merge_step", "=", "gen_io_ops", ".", "merge_v2_checkpoints", "(", "sharded_prefixes", ",", "checkpoint_prefix", ",", "delete_old_dirs", "=", "True", ")", "with", "ops", ".", "control_dependencies", "(", "[", "merge_step", "]", ")", ":", "# Returns the prefix \"<user-fed prefix>\" only. DOES NOT include the", "# sharded spec suffix.", "return", "array_ops", ".", "identity", "(", "checkpoint_prefix", ")" ]
https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/training/saver.py#L233-L301
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqt/mantidqt/utils/asynchronous.py
python
BlockingAsyncTaskWithCallback.abort
(self)
Cancel an asynchronous execution
Cancel an asynchronous execution
[ "Cancel", "an", "asynchronous", "execution" ]
def abort(self): """Cancel an asynchronous execution""" # Implementation is based on # https://stackoverflow.com/questions/5019436/python-how-to-terminate-a-blocking-thread ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(self.task.ident), ctypes.py_object(KeyboardInterrupt)) #now try and cancel the running algorithm alg = IAlgorithm._algorithmInThread(self.task.ident) if alg is not None: alg.cancel() time.sleep(0.1)
[ "def", "abort", "(", "self", ")", ":", "# Implementation is based on", "# https://stackoverflow.com/questions/5019436/python-how-to-terminate-a-blocking-thread", "ctypes", ".", "pythonapi", ".", "PyThreadState_SetAsyncExc", "(", "ctypes", ".", "c_long", "(", "self", ".", "task", ".", "ident", ")", ",", "ctypes", ".", "py_object", "(", "KeyboardInterrupt", ")", ")", "#now try and cancel the running algorithm", "alg", "=", "IAlgorithm", ".", "_algorithmInThread", "(", "self", ".", "task", ".", "ident", ")", "if", "alg", "is", "not", "None", ":", "alg", ".", "cancel", "(", ")", "time", ".", "sleep", "(", "0.1", ")" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqt/mantidqt/utils/asynchronous.py#L155-L165
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/fitting_widgets/basic_fitting/basic_fitting_view.py
python
BasicFittingView.current_dataset_name
(self)
return self.workspace_selector.current_dataset_name
Returns the selected dataset name.
Returns the selected dataset name.
[ "Returns", "the", "selected", "dataset", "name", "." ]
def current_dataset_name(self) -> str: """Returns the selected dataset name.""" return self.workspace_selector.current_dataset_name
[ "def", "current_dataset_name", "(", "self", ")", "->", "str", ":", "return", "self", ".", "workspace_selector", ".", "current_dataset_name" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/fitting_widgets/basic_fitting/basic_fitting_view.py#L169-L171
keyboardio/Kaleidoscope
d59604e98b2439d108647f15be52984a6837d360
bin/cpplint.py
python
_CppLintState.ResetErrorCounts
(self)
Sets the module's error statistic back to zero.
Sets the module's error statistic back to zero.
[ "Sets", "the", "module", "s", "error", "statistic", "back", "to", "zero", "." ]
def ResetErrorCounts(self): """Sets the module's error statistic back to zero.""" self.error_count = 0 self.errors_by_category = {}
[ "def", "ResetErrorCounts", "(", "self", ")", ":", "self", ".", "error_count", "=", "0", "self", ".", "errors_by_category", "=", "{", "}" ]
https://github.com/keyboardio/Kaleidoscope/blob/d59604e98b2439d108647f15be52984a6837d360/bin/cpplint.py#L1078-L1081
weolar/miniblink49
1c4678db0594a4abde23d3ebbcc7cd13c3170777
third_party/WebKit/PRESUBMIT.py
python
_CheckWatchlist
(input_api, output_api)
return errors
Check that the WATCHLIST file parses correctly.
Check that the WATCHLIST file parses correctly.
[ "Check", "that", "the", "WATCHLIST", "file", "parses", "correctly", "." ]
def _CheckWatchlist(input_api, output_api): """Check that the WATCHLIST file parses correctly.""" errors = [] for f in input_api.AffectedFiles(): if f.LocalPath() != 'WATCHLISTS': continue import StringIO import logging import watchlists log_buffer = StringIO.StringIO() log_handler = logging.StreamHandler(log_buffer) log_handler.setFormatter( logging.Formatter('%(levelname)s: %(message)s')) logger = logging.getLogger() logger.addHandler(log_handler) wl = watchlists.Watchlists(input_api.change.RepositoryRoot()) logger.removeHandler(log_handler) log_handler.flush() log_buffer.flush() if log_buffer.getvalue(): errors.append(output_api.PresubmitError( 'Cannot parse WATCHLISTS file, please resolve.', log_buffer.getvalue().splitlines())) return errors
[ "def", "_CheckWatchlist", "(", "input_api", ",", "output_api", ")", ":", "errors", "=", "[", "]", "for", "f", "in", "input_api", ".", "AffectedFiles", "(", ")", ":", "if", "f", ".", "LocalPath", "(", ")", "!=", "'WATCHLISTS'", ":", "continue", "import", "StringIO", "import", "logging", "import", "watchlists", "log_buffer", "=", "StringIO", ".", "StringIO", "(", ")", "log_handler", "=", "logging", ".", "StreamHandler", "(", "log_buffer", ")", "log_handler", ".", "setFormatter", "(", "logging", ".", "Formatter", "(", "'%(levelname)s: %(message)s'", ")", ")", "logger", "=", "logging", ".", "getLogger", "(", ")", "logger", ".", "addHandler", "(", "log_handler", ")", "wl", "=", "watchlists", ".", "Watchlists", "(", "input_api", ".", "change", ".", "RepositoryRoot", "(", ")", ")", "logger", ".", "removeHandler", "(", "log_handler", ")", "log_handler", ".", "flush", "(", ")", "log_buffer", ".", "flush", "(", ")", "if", "log_buffer", ".", "getvalue", "(", ")", ":", "errors", ".", "append", "(", "output_api", ".", "PresubmitError", "(", "'Cannot parse WATCHLISTS file, please resolve.'", ",", "log_buffer", ".", "getvalue", "(", ")", ".", "splitlines", "(", ")", ")", ")", "return", "errors" ]
https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/WebKit/PRESUBMIT.py#L39-L66
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
torch/fx/experimental/schema_type_annotation.py
python
AnnotateTypesWithSchema._extract_python_return_type
(self, target : Target)
return sig.return_annotation if sig.return_annotation is not inspect.Signature.empty else None
Given a Python call target, try to extract the Python return annotation if it is available, otherwise return None Args: target (Callable): Python callable to get return annotation for Returns: Optional[Any]: Return annotation from the `target`, or None if it was not available.
Given a Python call target, try to extract the Python return annotation if it is available, otherwise return None
[ "Given", "a", "Python", "call", "target", "try", "to", "extract", "the", "Python", "return", "annotation", "if", "it", "is", "available", "otherwise", "return", "None" ]
def _extract_python_return_type(self, target : Target) -> Optional[Any]: """ Given a Python call target, try to extract the Python return annotation if it is available, otherwise return None Args: target (Callable): Python callable to get return annotation for Returns: Optional[Any]: Return annotation from the `target`, or None if it was not available. """ assert callable(target) try: sig = inspect.signature(target) except (ValueError, TypeError): return None return sig.return_annotation if sig.return_annotation is not inspect.Signature.empty else None
[ "def", "_extract_python_return_type", "(", "self", ",", "target", ":", "Target", ")", "->", "Optional", "[", "Any", "]", ":", "assert", "callable", "(", "target", ")", "try", ":", "sig", "=", "inspect", ".", "signature", "(", "target", ")", "except", "(", "ValueError", ",", "TypeError", ")", ":", "return", "None", "return", "sig", ".", "return_annotation", "if", "sig", ".", "return_annotation", "is", "not", "inspect", ".", "Signature", ".", "empty", "else", "None" ]
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/fx/experimental/schema_type_annotation.py#L91-L111
psi4/psi4
be533f7f426b6ccc263904e55122899b16663395
psi4/driver/p4util/fcidump.py
python
write_eigenvalues
(eigs, mo_idx)
return eigs_dump
Prepare multi-line string with one-particle eigenvalues to be written to the FCIDUMP file.
Prepare multi-line string with one-particle eigenvalues to be written to the FCIDUMP file.
[ "Prepare", "multi", "-", "line", "string", "with", "one", "-", "particle", "eigenvalues", "to", "be", "written", "to", "the", "FCIDUMP", "file", "." ]
def write_eigenvalues(eigs, mo_idx): """Prepare multi-line string with one-particle eigenvalues to be written to the FCIDUMP file. """ eigs_dump = '' iorb = 0 for h, block in enumerate(eigs): for idx, x in np.ndenumerate(block): eigs_dump += '{:29.20E}{:4d}{:4d}{:4d}{:4d}\n'.format(x, mo_idx(iorb), 0, 0, 0) iorb += 1 return eigs_dump
[ "def", "write_eigenvalues", "(", "eigs", ",", "mo_idx", ")", ":", "eigs_dump", "=", "''", "iorb", "=", "0", "for", "h", ",", "block", "in", "enumerate", "(", "eigs", ")", ":", "for", "idx", ",", "x", "in", "np", ".", "ndenumerate", "(", "block", ")", ":", "eigs_dump", "+=", "'{:29.20E}{:4d}{:4d}{:4d}{:4d}\\n'", ".", "format", "(", "x", ",", "mo_idx", "(", "iorb", ")", ",", "0", ",", "0", ",", "0", ")", "iorb", "+=", "1", "return", "eigs_dump" ]
https://github.com/psi4/psi4/blob/be533f7f426b6ccc263904e55122899b16663395/psi4/driver/p4util/fcidump.py#L206-L215
ros-planning/moveit
ee48dc5cedc981d0869352aa3db0b41469c2735c
moveit_commander/src/moveit_commander/robot.py
python
RobotCommander.get_robot_markers
(self, *args)
return mrkr
Get a MarkerArray of the markers that make up this robot Usage: (): get's all markers for current state state (RobotState): gets markers for a particular state values (dict): get markers with given values values, links (dict, list): get markers with given values and these links group (string): get all markers for a group group, values (string, dict): get all markers for a group with desired values
Get a MarkerArray of the markers that make up this robot
[ "Get", "a", "MarkerArray", "of", "the", "markers", "that", "make", "up", "this", "robot" ]
def get_robot_markers(self, *args): """Get a MarkerArray of the markers that make up this robot Usage: (): get's all markers for current state state (RobotState): gets markers for a particular state values (dict): get markers with given values values, links (dict, list): get markers with given values and these links group (string): get all markers for a group group, values (string, dict): get all markers for a group with desired values """ mrkr = MarkerArray() if not args: conversions.msg_from_string(mrkr, self._r.get_robot_markers()) else: if isinstance(args[0], RobotState): msg_str = conversions.msg_to_string(args[0]) conversions.msg_from_string(mrkr, self._r.get_robot_markers(msg_str)) elif isinstance(args[0], dict): conversions.msg_from_string(mrkr, self._r.get_robot_markers(*args)) elif isinstance(args[0], str): conversions.msg_from_string(mrkr, self._r.get_group_markers(*args)) else: raise MoveItCommanderException("Unexpected type") return mrkr
[ "def", "get_robot_markers", "(", "self", ",", "*", "args", ")", ":", "mrkr", "=", "MarkerArray", "(", ")", "if", "not", "args", ":", "conversions", ".", "msg_from_string", "(", "mrkr", ",", "self", ".", "_r", ".", "get_robot_markers", "(", ")", ")", "else", ":", "if", "isinstance", "(", "args", "[", "0", "]", ",", "RobotState", ")", ":", "msg_str", "=", "conversions", ".", "msg_to_string", "(", "args", "[", "0", "]", ")", "conversions", ".", "msg_from_string", "(", "mrkr", ",", "self", ".", "_r", ".", "get_robot_markers", "(", "msg_str", ")", ")", "elif", "isinstance", "(", "args", "[", "0", "]", ",", "dict", ")", ":", "conversions", ".", "msg_from_string", "(", "mrkr", ",", "self", ".", "_r", ".", "get_robot_markers", "(", "*", "args", ")", ")", "elif", "isinstance", "(", "args", "[", "0", "]", ",", "str", ")", ":", "conversions", ".", "msg_from_string", "(", "mrkr", ",", "self", ".", "_r", ".", "get_group_markers", "(", "*", "args", ")", ")", "else", ":", "raise", "MoveItCommanderException", "(", "\"Unexpected type\"", ")", "return", "mrkr" ]
https://github.com/ros-planning/moveit/blob/ee48dc5cedc981d0869352aa3db0b41469c2735c/moveit_commander/src/moveit_commander/robot.py#L168-L192
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/build/waf-1.7.13/lmbrwaflib/android.py
python
adb_copy_output.set_device
(self, device)
Sets the android device (serial number from adb devices command) to copy the file to
Sets the android device (serial number from adb devices command) to copy the file to
[ "Sets", "the", "android", "device", "(", "serial", "number", "from", "adb", "devices", "command", ")", "to", "copy", "the", "file", "to" ]
def set_device(self, device): '''Sets the android device (serial number from adb devices command) to copy the file to''' self.device = device
[ "def", "set_device", "(", "self", ",", "device", ")", ":", "self", ".", "device", "=", "device" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/build/waf-1.7.13/lmbrwaflib/android.py#L2639-L2641
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/setuptools/py2/pkg_resources/__init__.py
python
find_eggs_in_zip
(importer, path_item, only=False)
Find eggs in zip files; possibly multiple nested eggs.
Find eggs in zip files; possibly multiple nested eggs.
[ "Find", "eggs", "in", "zip", "files", ";", "possibly", "multiple", "nested", "eggs", "." ]
def find_eggs_in_zip(importer, path_item, only=False): """ Find eggs in zip files; possibly multiple nested eggs. """ if importer.archive.endswith('.whl'): # wheels are not supported with this finder # they don't have PKG-INFO metadata, and won't ever contain eggs return metadata = EggMetadata(importer) if metadata.has_metadata('PKG-INFO'): yield Distribution.from_filename(path_item, metadata=metadata) if only: # don't yield nested distros return for subitem in metadata.resource_listdir(''): if _is_egg_path(subitem): subpath = os.path.join(path_item, subitem) dists = find_eggs_in_zip(zipimport.zipimporter(subpath), subpath) for dist in dists: yield dist elif subitem.lower().endswith('.dist-info'): subpath = os.path.join(path_item, subitem) submeta = EggMetadata(zipimport.zipimporter(subpath)) submeta.egg_info = subpath yield Distribution.from_location(path_item, subitem, submeta)
[ "def", "find_eggs_in_zip", "(", "importer", ",", "path_item", ",", "only", "=", "False", ")", ":", "if", "importer", ".", "archive", ".", "endswith", "(", "'.whl'", ")", ":", "# wheels are not supported with this finder", "# they don't have PKG-INFO metadata, and won't ever contain eggs", "return", "metadata", "=", "EggMetadata", "(", "importer", ")", "if", "metadata", ".", "has_metadata", "(", "'PKG-INFO'", ")", ":", "yield", "Distribution", ".", "from_filename", "(", "path_item", ",", "metadata", "=", "metadata", ")", "if", "only", ":", "# don't yield nested distros", "return", "for", "subitem", "in", "metadata", ".", "resource_listdir", "(", "''", ")", ":", "if", "_is_egg_path", "(", "subitem", ")", ":", "subpath", "=", "os", ".", "path", ".", "join", "(", "path_item", ",", "subitem", ")", "dists", "=", "find_eggs_in_zip", "(", "zipimport", ".", "zipimporter", "(", "subpath", ")", ",", "subpath", ")", "for", "dist", "in", "dists", ":", "yield", "dist", "elif", "subitem", ".", "lower", "(", ")", ".", "endswith", "(", "'.dist-info'", ")", ":", "subpath", "=", "os", ".", "path", ".", "join", "(", "path_item", ",", "subitem", ")", "submeta", "=", "EggMetadata", "(", "zipimport", ".", "zipimporter", "(", "subpath", ")", ")", "submeta", ".", "egg_info", "=", "subpath", "yield", "Distribution", ".", "from_location", "(", "path_item", ",", "subitem", ",", "submeta", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py2/pkg_resources/__init__.py#L1974-L1998
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py3/pandas/core/arrays/datetimes.py
python
DatetimeArray._local_timestamps
(self)
return tzconversion.tz_convert_from_utc(self.asi8, self.tz)
Convert to an i8 (unix-like nanosecond timestamp) representation while keeping the local timezone and not using UTC. This is used to calculate time-of-day information as if the timestamps were timezone-naive.
Convert to an i8 (unix-like nanosecond timestamp) representation while keeping the local timezone and not using UTC. This is used to calculate time-of-day information as if the timestamps were timezone-naive.
[ "Convert", "to", "an", "i8", "(", "unix", "-", "like", "nanosecond", "timestamp", ")", "representation", "while", "keeping", "the", "local", "timezone", "and", "not", "using", "UTC", ".", "This", "is", "used", "to", "calculate", "time", "-", "of", "-", "day", "information", "as", "if", "the", "timestamps", "were", "timezone", "-", "naive", "." ]
def _local_timestamps(self) -> np.ndarray: """ Convert to an i8 (unix-like nanosecond timestamp) representation while keeping the local timezone and not using UTC. This is used to calculate time-of-day information as if the timestamps were timezone-naive. """ if self.tz is None or timezones.is_utc(self.tz): return self.asi8 return tzconversion.tz_convert_from_utc(self.asi8, self.tz)
[ "def", "_local_timestamps", "(", "self", ")", "->", "np", ".", "ndarray", ":", "if", "self", ".", "tz", "is", "None", "or", "timezones", ".", "is_utc", "(", "self", ".", "tz", ")", ":", "return", "self", ".", "asi8", "return", "tzconversion", ".", "tz_convert_from_utc", "(", "self", ".", "asi8", ",", "self", ".", "tz", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/arrays/datetimes.py#L776-L785
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/numpy/py2/numpy/lib/utils.py
python
get_include
()
return d
Return the directory that contains the NumPy \\*.h header files. Extension modules that need to compile against NumPy should use this function to locate the appropriate include directory. Notes ----- When using ``distutils``, for example in ``setup.py``. :: import numpy as np ... Extension('extension_name', ... include_dirs=[np.get_include()]) ...
Return the directory that contains the NumPy \\*.h header files.
[ "Return", "the", "directory", "that", "contains", "the", "NumPy", "\\\\", "*", ".", "h", "header", "files", "." ]
def get_include(): """ Return the directory that contains the NumPy \\*.h header files. Extension modules that need to compile against NumPy should use this function to locate the appropriate include directory. Notes ----- When using ``distutils``, for example in ``setup.py``. :: import numpy as np ... Extension('extension_name', ... include_dirs=[np.get_include()]) ... """ import numpy if numpy.show_config is None: # running from numpy source directory d = os.path.join(os.path.dirname(numpy.__file__), 'core', 'include') else: # using installed numpy core headers import numpy.core as core d = os.path.join(os.path.dirname(core.__file__), 'include') return d
[ "def", "get_include", "(", ")", ":", "import", "numpy", "if", "numpy", ".", "show_config", "is", "None", ":", "# running from numpy source directory", "d", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "numpy", ".", "__file__", ")", ",", "'core'", ",", "'include'", ")", "else", ":", "# using installed numpy core headers", "import", "numpy", ".", "core", "as", "core", "d", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "core", ".", "__file__", ")", ",", "'include'", ")", "return", "d" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py2/numpy/lib/utils.py#L23-L50
eventql/eventql
7ca0dbb2e683b525620ea30dc40540a22d5eb227
deps/3rdparty/spidermonkey/mozjs/python/requests/requests/api.py
python
get
(url, **kwargs)
return request('get', url, **kwargs)
Sends a GET request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes.
Sends a GET request. Returns :class:`Response` object.
[ "Sends", "a", "GET", "request", ".", "Returns", ":", "class", ":", "Response", "object", "." ]
def get(url, **kwargs): """Sends a GET request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. """ kwargs.setdefault('allow_redirects', True) return request('get', url, **kwargs)
[ "def", "get", "(", "url", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "setdefault", "(", "'allow_redirects'", ",", "True", ")", "return", "request", "(", "'get'", ",", "url", ",", "*", "*", "kwargs", ")" ]
https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/python/requests/requests/api.py#L57-L65
kushview/Element
1cc16380caa2ab79461246ba758b9de1f46db2a5
waflib/Tools/javaw.py
python
javac.post_run
(self)
List class files created
List class files created
[ "List", "class", "files", "created" ]
def post_run(self): """ List class files created """ for node in self.generator.outdir.ant_glob('**/*.class', quiet=True): self.generator.bld.node_sigs[node] = self.uid() self.generator.bld.task_sigs[self.uid()] = self.cache_sig
[ "def", "post_run", "(", "self", ")", ":", "for", "node", "in", "self", ".", "generator", ".", "outdir", ".", "ant_glob", "(", "'**/*.class'", ",", "quiet", "=", "True", ")", ":", "self", ".", "generator", ".", "bld", ".", "node_sigs", "[", "node", "]", "=", "self", ".", "uid", "(", ")", "self", ".", "generator", ".", "bld", ".", "task_sigs", "[", "self", ".", "uid", "(", ")", "]", "=", "self", ".", "cache_sig" ]
https://github.com/kushview/Element/blob/1cc16380caa2ab79461246ba758b9de1f46db2a5/waflib/Tools/javaw.py#L414-L420
microsoft/checkedc-clang
a173fefde5d7877b7750e7ce96dd08cf18baebf2
clang/bindings/python/clang/cindex.py
python
Cursor.get_num_template_arguments
(self)
return conf.lib.clang_Cursor_getNumTemplateArguments(self)
Returns the number of template args associated with this cursor.
Returns the number of template args associated with this cursor.
[ "Returns", "the", "number", "of", "template", "args", "associated", "with", "this", "cursor", "." ]
def get_num_template_arguments(self): """Returns the number of template args associated with this cursor.""" return conf.lib.clang_Cursor_getNumTemplateArguments(self)
[ "def", "get_num_template_arguments", "(", "self", ")", ":", "return", "conf", ".", "lib", ".", "clang_Cursor_getNumTemplateArguments", "(", "self", ")" ]
https://github.com/microsoft/checkedc-clang/blob/a173fefde5d7877b7750e7ce96dd08cf18baebf2/clang/bindings/python/clang/cindex.py#L1806-L1808
thalium/icebox
99d147d5b9269222225443ce171b4fd46d8985d4
third_party/virtualbox/src/VBox/Devices/EFI/Firmware/BaseTools/Scripts/UpdateBuildVersions.py
python
ParseOptions
()
return(parser.parse_args())
Parse the command-line options. The options for this tool will be passed along to the MkBinPkg tool.
Parse the command-line options. The options for this tool will be passed along to the MkBinPkg tool.
[ "Parse", "the", "command", "-", "line", "options", ".", "The", "options", "for", "this", "tool", "will", "be", "passed", "along", "to", "the", "MkBinPkg", "tool", "." ]
def ParseOptions(): """ Parse the command-line options. The options for this tool will be passed along to the MkBinPkg tool. """ parser = ArgumentParser( usage=("%s [options]" % __execname__), description=__copyright__, conflict_handler='resolve') # Standard Tool Options parser.add_argument("--version", action="version", version=__execname__ + " " + __version__) parser.add_argument("-s", "--silent", action="store_true", dest="silent", help="All output will be disabled, pass/fail determined by the exit code") parser.add_argument("-v", "--verbose", action="store_true", dest="verbose", help="Enable verbose output") # Tool specific options parser.add_argument("--revert", action="store_true", dest="REVERT", default=False, help="Revert the BuildVersion files only") parser.add_argument("--svn-test", action="store_true", dest="TEST_SVN", default=False, help="Test if the svn command is available") parser.add_argument("--svnFlag", action="store_true", dest="HAVE_SVN", default=False, help=SUPPRESS) return(parser.parse_args())
[ "def", "ParseOptions", "(", ")", ":", "parser", "=", "ArgumentParser", "(", "usage", "=", "(", "\"%s [options]\"", "%", "__execname__", ")", ",", "description", "=", "__copyright__", ",", "conflict_handler", "=", "'resolve'", ")", "# Standard Tool Options", "parser", ".", "add_argument", "(", "\"--version\"", ",", "action", "=", "\"version\"", ",", "version", "=", "__execname__", "+", "\" \"", "+", "__version__", ")", "parser", ".", "add_argument", "(", "\"-s\"", ",", "\"--silent\"", ",", "action", "=", "\"store_true\"", ",", "dest", "=", "\"silent\"", ",", "help", "=", "\"All output will be disabled, pass/fail determined by the exit code\"", ")", "parser", ".", "add_argument", "(", "\"-v\"", ",", "\"--verbose\"", ",", "action", "=", "\"store_true\"", ",", "dest", "=", "\"verbose\"", ",", "help", "=", "\"Enable verbose output\"", ")", "# Tool specific options", "parser", ".", "add_argument", "(", "\"--revert\"", ",", "action", "=", "\"store_true\"", ",", "dest", "=", "\"REVERT\"", ",", "default", "=", "False", ",", "help", "=", "\"Revert the BuildVersion files only\"", ")", "parser", ".", "add_argument", "(", "\"--svn-test\"", ",", "action", "=", "\"store_true\"", ",", "dest", "=", "\"TEST_SVN\"", ",", "default", "=", "False", ",", "help", "=", "\"Test if the svn command is available\"", ")", "parser", ".", "add_argument", "(", "\"--svnFlag\"", ",", "action", "=", "\"store_true\"", ",", "dest", "=", "\"HAVE_SVN\"", ",", "default", "=", "False", ",", "help", "=", "SUPPRESS", ")", "return", "(", "parser", ".", "parse_args", "(", ")", ")" ]
https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/VBox/Devices/EFI/Firmware/BaseTools/Scripts/UpdateBuildVersions.py#L42-L72
rdiankov/openrave
d1a23023fd4b58f077d2ca949ceaf1b91f3f13d7
python/interfaces/TaskManipulation.py
python
TaskManipulation.ReleaseActive
(self,movingdir=None,execute=None,outputtraj=None,outputfinal=None,translationstepmult=None,finestep=None,outputtrajobj=None)
return final,traj
See :ref:`module-taskmanipulation-releaseactive`
See :ref:`module-taskmanipulation-releaseactive`
[ "See", ":", "ref", ":", "module", "-", "taskmanipulation", "-", "releaseactive" ]
def ReleaseActive(self,movingdir=None,execute=None,outputtraj=None,outputfinal=None,translationstepmult=None,finestep=None,outputtrajobj=None): """See :ref:`module-taskmanipulation-releaseactive` """ cmd = 'ReleaseActive ' if movingdir is not None: assert(len(movingdir) == self.robot.GetActiveDOF()) cmd += 'movingdir %s '%(' '.join(str(f) for f in movingdir)) if execute is not None: cmd += 'execute %d '%execute if (outputtraj is not None and outputtraj) or (outputtrajobj is not None and outputtrajobj): cmd += 'outputtraj ' if outputfinal: cmd += 'outputfinal' if translationstepmult is not None: cmd += 'translationstepmult %.15e '%translationstepmult if finestep is not None: cmd += 'finestep %.15e '%finestep res = self.prob.SendCommand(cmd) if res is None: raise PlanningError('ReleaseActive') resvalues = res if outputfinal: resvaluesSplit = resvalues.split() final = array([float64(resvaluesSplit[i]) for i in range(self.robot.GetActiveDOF())]) resvalues = resvalues[sum(len(resvaluesSplit[i])+1 for i in range(self.robot.GetActiveDOF())):] else: final=None if (outputtraj is not None and outputtraj) or (outputtrajobj is not None and outputtrajobj): traj = resvalues if outputtrajobj is not None and outputtrajobj: newtraj = RaveCreateTrajectory(self.prob.GetEnv(),'') newtraj.deserialize(traj) traj = newtraj else: traj = None return final,traj
[ "def", "ReleaseActive", "(", "self", ",", "movingdir", "=", "None", ",", "execute", "=", "None", ",", "outputtraj", "=", "None", ",", "outputfinal", "=", "None", ",", "translationstepmult", "=", "None", ",", "finestep", "=", "None", ",", "outputtrajobj", "=", "None", ")", ":", "cmd", "=", "'ReleaseActive '", "if", "movingdir", "is", "not", "None", ":", "assert", "(", "len", "(", "movingdir", ")", "==", "self", ".", "robot", ".", "GetActiveDOF", "(", ")", ")", "cmd", "+=", "'movingdir %s '", "%", "(", "' '", ".", "join", "(", "str", "(", "f", ")", "for", "f", "in", "movingdir", ")", ")", "if", "execute", "is", "not", "None", ":", "cmd", "+=", "'execute %d '", "%", "execute", "if", "(", "outputtraj", "is", "not", "None", "and", "outputtraj", ")", "or", "(", "outputtrajobj", "is", "not", "None", "and", "outputtrajobj", ")", ":", "cmd", "+=", "'outputtraj '", "if", "outputfinal", ":", "cmd", "+=", "'outputfinal'", "if", "translationstepmult", "is", "not", "None", ":", "cmd", "+=", "'translationstepmult %.15e '", "%", "translationstepmult", "if", "finestep", "is", "not", "None", ":", "cmd", "+=", "'finestep %.15e '", "%", "finestep", "res", "=", "self", ".", "prob", ".", "SendCommand", "(", "cmd", ")", "if", "res", "is", "None", ":", "raise", "PlanningError", "(", "'ReleaseActive'", ")", "resvalues", "=", "res", "if", "outputfinal", ":", "resvaluesSplit", "=", "resvalues", ".", "split", "(", ")", "final", "=", "array", "(", "[", "float64", "(", "resvaluesSplit", "[", "i", "]", ")", "for", "i", "in", "range", "(", "self", ".", "robot", ".", "GetActiveDOF", "(", ")", ")", "]", ")", "resvalues", "=", "resvalues", "[", "sum", "(", "len", "(", "resvaluesSplit", "[", "i", "]", ")", "+", "1", "for", "i", "in", "range", "(", "self", ".", "robot", ".", "GetActiveDOF", "(", ")", ")", ")", ":", "]", "else", ":", "final", "=", "None", "if", "(", "outputtraj", "is", "not", "None", "and", "outputtraj", ")", "or", "(", "outputtrajobj", "is", "not", "None", "and", "outputtrajobj", ")", ":", "traj", "=", "resvalues", "if", "outputtrajobj", "is", "not", "None", "and", "outputtrajobj", ":", "newtraj", "=", "RaveCreateTrajectory", "(", "self", ".", "prob", ".", "GetEnv", "(", ")", ",", "''", ")", "newtraj", ".", "deserialize", "(", "traj", ")", "traj", "=", "newtraj", "else", ":", "traj", "=", "None", "return", "final", ",", "traj" ]
https://github.com/rdiankov/openrave/blob/d1a23023fd4b58f077d2ca949ceaf1b91f3f13d7/python/interfaces/TaskManipulation.py#L262-L297
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/contrib/graph_editor/transform.py
python
_TmpInfo.new_name
(self, name)
return name_
Compute a destination name from a source name. Args: name: the name to be "transformed". Returns: The transformed name. Raises: ValueError: if the source scope is used (that is, not an empty string) and the source name does not belong to the source scope.
Compute a destination name from a source name.
[ "Compute", "a", "destination", "name", "from", "a", "source", "name", "." ]
def new_name(self, name): """Compute a destination name from a source name. Args: name: the name to be "transformed". Returns: The transformed name. Raises: ValueError: if the source scope is used (that is, not an empty string) and the source name does not belong to the source scope. """ scope = self.scope if not name.startswith(scope): raise ValueError("{} does not belong to source scope: {}.".format( name, scope)) rel_name = name[len(scope):] name_ = self.scope_ + rel_name return name_
[ "def", "new_name", "(", "self", ",", "name", ")", ":", "scope", "=", "self", ".", "scope", "if", "not", "name", ".", "startswith", "(", "scope", ")", ":", "raise", "ValueError", "(", "\"{} does not belong to source scope: {}.\"", ".", "format", "(", "name", ",", "scope", ")", ")", "rel_name", "=", "name", "[", "len", "(", "scope", ")", ":", "]", "name_", "=", "self", ".", "scope_", "+", "rel_name", "return", "name_" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/graph_editor/transform.py#L332-L349
macchina-io/macchina.io
ef24ba0e18379c3dd48fb84e6dbf991101cb8db0
platform/JS/V8/tools/gyp/pylib/gyp/generator/eclipse.py
python
GetJavaSourceDirs
(target_list, target_dicts, toplevel_dir)
Generates a sequence of all likely java package root directories.
Generates a sequence of all likely java package root directories.
[ "Generates", "a", "sequence", "of", "all", "likely", "java", "package", "root", "directories", "." ]
def GetJavaSourceDirs(target_list, target_dicts, toplevel_dir): '''Generates a sequence of all likely java package root directories.''' for target_name in target_list: target = target_dicts[target_name] for action in target.get('actions', []): for input_ in action['inputs']: if (os.path.splitext(input_)[1] == '.java' and not input_.startswith('$')): dir_ = os.path.dirname(os.path.join(os.path.dirname(target_name), input_)) # If there is a parent 'src' or 'java' folder, navigate up to it - # these are canonical package root names in Chromium. This will # break if 'src' or 'java' exists in the package structure. This # could be further improved by inspecting the java file for the # package name if this proves to be too fragile in practice. parent_search = dir_ while os.path.basename(parent_search) not in ['src', 'java']: parent_search, _ = os.path.split(parent_search) if not parent_search or parent_search == toplevel_dir: # Didn't find a known root, just return the original path yield dir_ break else: yield parent_search
[ "def", "GetJavaSourceDirs", "(", "target_list", ",", "target_dicts", ",", "toplevel_dir", ")", ":", "for", "target_name", "in", "target_list", ":", "target", "=", "target_dicts", "[", "target_name", "]", "for", "action", "in", "target", ".", "get", "(", "'actions'", ",", "[", "]", ")", ":", "for", "input_", "in", "action", "[", "'inputs'", "]", ":", "if", "(", "os", ".", "path", ".", "splitext", "(", "input_", ")", "[", "1", "]", "==", "'.java'", "and", "not", "input_", ".", "startswith", "(", "'$'", ")", ")", ":", "dir_", "=", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "target_name", ")", ",", "input_", ")", ")", "# If there is a parent 'src' or 'java' folder, navigate up to it -", "# these are canonical package root names in Chromium. This will", "# break if 'src' or 'java' exists in the package structure. This", "# could be further improved by inspecting the java file for the", "# package name if this proves to be too fragile in practice.", "parent_search", "=", "dir_", "while", "os", ".", "path", ".", "basename", "(", "parent_search", ")", "not", "in", "[", "'src'", ",", "'java'", "]", ":", "parent_search", ",", "_", "=", "os", ".", "path", ".", "split", "(", "parent_search", ")", "if", "not", "parent_search", "or", "parent_search", "==", "toplevel_dir", ":", "# Didn't find a known root, just return the original path", "yield", "dir_", "break", "else", ":", "yield", "parent_search" ]
https://github.com/macchina-io/macchina.io/blob/ef24ba0e18379c3dd48fb84e6dbf991101cb8db0/platform/JS/V8/tools/gyp/pylib/gyp/generator/eclipse.py#L384-L407
apache/qpid-proton
6bcdfebb55ea3554bc29b1901422532db331a591
python/proton/_endpoints.py
python
Connection.remote_desired_capabilities
(self)
return dat2obj(pn_connection_remote_desired_capabilities(self._impl))
The capabilities desired by the remote peer for this connection. This operation will return a :class:`Data` object that is valid until the connection object is freed. This :class:`Data` object will be empty until the remote connection is opened as indicated by the :const:`REMOTE_ACTIVE` flag. :type: :class:`Data`
The capabilities desired by the remote peer for this connection.
[ "The", "capabilities", "desired", "by", "the", "remote", "peer", "for", "this", "connection", "." ]
def remote_desired_capabilities(self): """ The capabilities desired by the remote peer for this connection. This operation will return a :class:`Data` object that is valid until the connection object is freed. This :class:`Data` object will be empty until the remote connection is opened as indicated by the :const:`REMOTE_ACTIVE` flag. :type: :class:`Data` """ return dat2obj(pn_connection_remote_desired_capabilities(self._impl))
[ "def", "remote_desired_capabilities", "(", "self", ")", ":", "return", "dat2obj", "(", "pn_connection_remote_desired_capabilities", "(", "self", ".", "_impl", ")", ")" ]
https://github.com/apache/qpid-proton/blob/6bcdfebb55ea3554bc29b1901422532db331a591/python/proton/_endpoints.py#L336-L347
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/setuptools/py3/setuptools/_vendor/packaging/specifiers.py
python
BaseSpecifier.__hash__
(self)
Returns a hash value for this Specifier like object.
Returns a hash value for this Specifier like object.
[ "Returns", "a", "hash", "value", "for", "this", "Specifier", "like", "object", "." ]
def __hash__(self) -> int: """ Returns a hash value for this Specifier like object. """
[ "def", "__hash__", "(", "self", ")", "->", "int", ":" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py3/setuptools/_vendor/packaging/specifiers.py#L48-L51
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Draft/draftguitools/gui_snapper.py
python
Snapper.getApparentPoint
(self, x, y)
return pt
Return a 3D point, projected on the current working plane.
Return a 3D point, projected on the current working plane.
[ "Return", "a", "3D", "point", "projected", "on", "the", "current", "working", "plane", "." ]
def getApparentPoint(self, x, y): """Return a 3D point, projected on the current working plane.""" view = Draft.get3DView() pt = view.getPoint(x, y) if self.mask != "z": if hasattr(App,"DraftWorkingPlane"): if view.getCameraType() == "Perspective": camera = view.getCameraNode() p = camera.getField("position").getValue() dv = pt.sub(App.Vector(p[0], p[1], p[2])) else: dv = view.getViewDirection() return App.DraftWorkingPlane.projectPoint(pt, dv) return pt
[ "def", "getApparentPoint", "(", "self", ",", "x", ",", "y", ")", ":", "view", "=", "Draft", ".", "get3DView", "(", ")", "pt", "=", "view", ".", "getPoint", "(", "x", ",", "y", ")", "if", "self", ".", "mask", "!=", "\"z\"", ":", "if", "hasattr", "(", "App", ",", "\"DraftWorkingPlane\"", ")", ":", "if", "view", ".", "getCameraType", "(", ")", "==", "\"Perspective\"", ":", "camera", "=", "view", ".", "getCameraNode", "(", ")", "p", "=", "camera", ".", "getField", "(", "\"position\"", ")", ".", "getValue", "(", ")", "dv", "=", "pt", ".", "sub", "(", "App", ".", "Vector", "(", "p", "[", "0", "]", ",", "p", "[", "1", "]", ",", "p", "[", "2", "]", ")", ")", "else", ":", "dv", "=", "view", ".", "getViewDirection", "(", ")", "return", "App", ".", "DraftWorkingPlane", ".", "projectPoint", "(", "pt", ",", "dv", ")", "return", "pt" ]
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Draft/draftguitools/gui_snapper.py#L543-L556
openmm/openmm
cb293447c4fc8b03976dfe11399f107bab70f3d9
wrappers/python/openmm/app/statedatareporter.py
python
StateDataReporter.report
(self, simulation, state)
Generate a report. Parameters ---------- simulation : Simulation The Simulation to generate a report for state : State The current state of the simulation
Generate a report.
[ "Generate", "a", "report", "." ]
def report(self, simulation, state): """Generate a report. Parameters ---------- simulation : Simulation The Simulation to generate a report for state : State The current state of the simulation """ if not self._hasInitialized: self._initializeConstants(simulation) headers = self._constructHeaders() if not self._append: print('#"%s"' % ('"'+self._separator+'"').join(headers), file=self._out) try: self._out.flush() except AttributeError: pass self._initialClockTime = time.time() self._initialSimulationTime = state.getTime() self._initialSteps = simulation.currentStep self._hasInitialized = True # Check for errors. self._checkForErrors(simulation, state) # Query for the values values = self._constructReportValues(simulation, state) # Write the values. print(self._separator.join(str(v) for v in values), file=self._out) try: self._out.flush() except AttributeError: pass
[ "def", "report", "(", "self", ",", "simulation", ",", "state", ")", ":", "if", "not", "self", ".", "_hasInitialized", ":", "self", ".", "_initializeConstants", "(", "simulation", ")", "headers", "=", "self", ".", "_constructHeaders", "(", ")", "if", "not", "self", ".", "_append", ":", "print", "(", "'#\"%s\"'", "%", "(", "'\"'", "+", "self", ".", "_separator", "+", "'\"'", ")", ".", "join", "(", "headers", ")", ",", "file", "=", "self", ".", "_out", ")", "try", ":", "self", ".", "_out", ".", "flush", "(", ")", "except", "AttributeError", ":", "pass", "self", ".", "_initialClockTime", "=", "time", ".", "time", "(", ")", "self", ".", "_initialSimulationTime", "=", "state", ".", "getTime", "(", ")", "self", ".", "_initialSteps", "=", "simulation", ".", "currentStep", "self", ".", "_hasInitialized", "=", "True", "# Check for errors.", "self", ".", "_checkForErrors", "(", "simulation", ",", "state", ")", "# Query for the values", "values", "=", "self", ".", "_constructReportValues", "(", "simulation", ",", "state", ")", "# Write the values.", "print", "(", "self", ".", "_separator", ".", "join", "(", "str", "(", "v", ")", "for", "v", "in", "values", ")", ",", "file", "=", "self", ".", "_out", ")", "try", ":", "self", ".", "_out", ".", "flush", "(", ")", "except", "AttributeError", ":", "pass" ]
https://github.com/openmm/openmm/blob/cb293447c4fc8b03976dfe11399f107bab70f3d9/wrappers/python/openmm/app/statedatareporter.py#L181-L216
microsoft/TSS.MSR
0f2516fca2cd9929c31d5450e39301c9bde43688
TSS.Py/src/TpmTypes.py
python
ContextLoadResponse.fromBytes
(buffer)
return TpmBuffer(buffer).createObj(ContextLoadResponse)
Returns new ContextLoadResponse object constructed from its marshaled representation in the given byte buffer
Returns new ContextLoadResponse object constructed from its marshaled representation in the given byte buffer
[ "Returns", "new", "ContextLoadResponse", "object", "constructed", "from", "its", "marshaled", "representation", "in", "the", "given", "byte", "buffer" ]
def fromBytes(buffer): """ Returns new ContextLoadResponse object constructed from its marshaled representation in the given byte buffer """ return TpmBuffer(buffer).createObj(ContextLoadResponse)
[ "def", "fromBytes", "(", "buffer", ")", ":", "return", "TpmBuffer", "(", "buffer", ")", ".", "createObj", "(", "ContextLoadResponse", ")" ]
https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L16185-L16189
trailofbits/llvm-sanitizer-tutorial
d29dfeec7f51fbf234fd0080f28f2b30cd0b6e99
llvm/tools/clang/tools/scan-build-py/libscanbuild/arguments.py
python
parse_args_for_scan_build
()
return args
Parse and validate command-line arguments for scan-build.
Parse and validate command-line arguments for scan-build.
[ "Parse", "and", "validate", "command", "-", "line", "arguments", "for", "scan", "-", "build", "." ]
def parse_args_for_scan_build(): """ Parse and validate command-line arguments for scan-build. """ from_build_command = True parser = create_analyze_parser(from_build_command) args = parser.parse_args() reconfigure_logging(args.verbose) logging.debug('Raw arguments %s', sys.argv) normalize_args_for_analyze(args, from_build_command) validate_args_for_analyze(parser, args, from_build_command) logging.debug('Parsed arguments: %s', args) return args
[ "def", "parse_args_for_scan_build", "(", ")", ":", "from_build_command", "=", "True", "parser", "=", "create_analyze_parser", "(", "from_build_command", ")", "args", "=", "parser", ".", "parse_args", "(", ")", "reconfigure_logging", "(", "args", ".", "verbose", ")", "logging", ".", "debug", "(", "'Raw arguments %s'", ",", "sys", ".", "argv", ")", "normalize_args_for_analyze", "(", "args", ",", "from_build_command", ")", "validate_args_for_analyze", "(", "parser", ",", "args", ",", "from_build_command", ")", "logging", ".", "debug", "(", "'Parsed arguments: %s'", ",", "args", ")", "return", "args" ]
https://github.com/trailofbits/llvm-sanitizer-tutorial/blob/d29dfeec7f51fbf234fd0080f28f2b30cd0b6e99/llvm/tools/clang/tools/scan-build-py/libscanbuild/arguments.py#L62-L75
JavierIH/zowi
830c1284154b8167c9131deb9c45189fd9e67b54
code/python-client/Oscillator.py
python
Oscillator.O
(self, value)
Attribute: Set the offset
Attribute: Set the offset
[ "Attribute", ":", "Set", "the", "offset" ]
def O(self, value): """Attribute: Set the offset""" self.set_O(value)
[ "def", "O", "(", "self", ",", "value", ")", ":", "self", ".", "set_O", "(", "value", ")" ]
https://github.com/JavierIH/zowi/blob/830c1284154b8167c9131deb9c45189fd9e67b54/code/python-client/Oscillator.py#L124-L126
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
tools/auto_bisect/query_crbug.py
python
QuerySingleIssue
(issue_id, url_template=SINGLE_ISSUE_URL)
return json.loads(response)
Queries the tracker for a specific issue. Returns a dict. This uses the deprecated Issue Tracker API to fetch a JSON representation of the issue details. Args: issue_id: An int or string representing the issue id. url_template: URL to query the tracker with '%s' instead of the bug id. Returns: A dictionary as parsed by the JSON library from the tracker response. Raises: urllib2.HTTPError when appropriate.
Queries the tracker for a specific issue. Returns a dict.
[ "Queries", "the", "tracker", "for", "a", "specific", "issue", ".", "Returns", "a", "dict", "." ]
def QuerySingleIssue(issue_id, url_template=SINGLE_ISSUE_URL): """Queries the tracker for a specific issue. Returns a dict. This uses the deprecated Issue Tracker API to fetch a JSON representation of the issue details. Args: issue_id: An int or string representing the issue id. url_template: URL to query the tracker with '%s' instead of the bug id. Returns: A dictionary as parsed by the JSON library from the tracker response. Raises: urllib2.HTTPError when appropriate. """ assert str(issue_id).isdigit() response = urllib2.urlopen(url_template % issue_id).read() return json.loads(response)
[ "def", "QuerySingleIssue", "(", "issue_id", ",", "url_template", "=", "SINGLE_ISSUE_URL", ")", ":", "assert", "str", "(", "issue_id", ")", ".", "isdigit", "(", ")", "response", "=", "urllib2", ".", "urlopen", "(", "url_template", "%", "issue_id", ")", ".", "read", "(", ")", "return", "json", ".", "loads", "(", "response", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/auto_bisect/query_crbug.py#L24-L42
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/boto/boto/ec2/volume.py
python
Volume.create_snapshot
(self, description=None, dry_run=False)
return self.connection.create_snapshot( self.id, description, dry_run=dry_run )
Create a snapshot of this EBS Volume. :type description: str :param description: A description of the snapshot. Limited to 256 characters. :rtype: :class:`boto.ec2.snapshot.Snapshot` :return: The created Snapshot object
Create a snapshot of this EBS Volume.
[ "Create", "a", "snapshot", "of", "this", "EBS", "Volume", "." ]
def create_snapshot(self, description=None, dry_run=False): """ Create a snapshot of this EBS Volume. :type description: str :param description: A description of the snapshot. Limited to 256 characters. :rtype: :class:`boto.ec2.snapshot.Snapshot` :return: The created Snapshot object """ return self.connection.create_snapshot( self.id, description, dry_run=dry_run )
[ "def", "create_snapshot", "(", "self", ",", "description", "=", "None", ",", "dry_run", "=", "False", ")", ":", "return", "self", ".", "connection", ".", "create_snapshot", "(", "self", ".", "id", ",", "description", ",", "dry_run", "=", "dry_run", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/ec2/volume.py#L190-L205
fabianschenk/REVO
eb949c0fdbcdf0be09a38464eb0592a90803947f
thirdparty/Sophus/py/sophus/se2.py
python
Se2.__init__
(self, so2, t)
internally represented by a unit complex number z and a translation 2-vector
internally represented by a unit complex number z and a translation 2-vector
[ "internally", "represented", "by", "a", "unit", "complex", "number", "z", "and", "a", "translation", "2", "-", "vector" ]
def __init__(self, so2, t): """ internally represented by a unit complex number z and a translation 2-vector """ self.so2 = so2 self.t = t
[ "def", "__init__", "(", "self", ",", "so2", ",", "t", ")", ":", "self", ".", "so2", "=", "so2", "self", ".", "t", "=", "t" ]
https://github.com/fabianschenk/REVO/blob/eb949c0fdbcdf0be09a38464eb0592a90803947f/thirdparty/Sophus/py/sophus/se2.py#L11-L15
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/setuptools/extern/__init__.py
python
VendorImporter.find_module
(self, fullname, path=None)
return self
Return self when fullname starts with root_name and the target module is one vendored through this importer.
Return self when fullname starts with root_name and the target module is one vendored through this importer.
[ "Return", "self", "when", "fullname", "starts", "with", "root_name", "and", "the", "target", "module", "is", "one", "vendored", "through", "this", "importer", "." ]
def find_module(self, fullname, path=None): """ Return self when fullname starts with root_name and the target module is one vendored through this importer. """ root, base, target = fullname.partition(self.root_name + '.') if root: return if not any(map(target.startswith, self.vendored_names)): return return self
[ "def", "find_module", "(", "self", ",", "fullname", ",", "path", "=", "None", ")", ":", "root", ",", "base", ",", "target", "=", "fullname", ".", "partition", "(", "self", ".", "root_name", "+", "'.'", ")", "if", "root", ":", "return", "if", "not", "any", "(", "map", "(", "target", ".", "startswith", ",", "self", ".", "vendored_names", ")", ")", ":", "return", "return", "self" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/setuptools/extern/__init__.py#L23-L33
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/ops/_grad/grad_math_ops.py
python
get_bprop_truncate_div
(self)
return bprop
Grad definition for `TruncateDiv` operation.
Grad definition for `TruncateDiv` operation.
[ "Grad", "definition", "for", "TruncateDiv", "operation", "." ]
def get_bprop_truncate_div(self): """Grad definition for `TruncateDiv` operation.""" def bprop(x, y, out, dout): return zeros_like(x), zeros_like(y) return bprop
[ "def", "get_bprop_truncate_div", "(", "self", ")", ":", "def", "bprop", "(", "x", ",", "y", ",", "out", ",", "dout", ")", ":", "return", "zeros_like", "(", "x", ")", ",", "zeros_like", "(", "y", ")", "return", "bprop" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/_grad/grad_math_ops.py#L400-L406
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/nn/probability/distribution/exponential.py
python
Exponential._mode
(self, rate=None)
return self.fill(self.dtype, self.shape(rate), 0.)
r""" .. math:: MODE(EXP) = 0.
r""" .. math:: MODE(EXP) = 0.
[ "r", "..", "math", "::", "MODE", "(", "EXP", ")", "=", "0", "." ]
def _mode(self, rate=None): r""" .. math:: MODE(EXP) = 0. """ rate = self._check_param_type(rate) return self.fill(self.dtype, self.shape(rate), 0.)
[ "def", "_mode", "(", "self", ",", "rate", "=", "None", ")", ":", "rate", "=", "self", ".", "_check_param_type", "(", "rate", ")", "return", "self", ".", "fill", "(", "self", ".", "dtype", ",", "self", ".", "shape", "(", "rate", ")", ",", "0.", ")" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/nn/probability/distribution/exponential.py#L218-L224
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
deps/src/libxml2-2.9.1/python/libxml2class.py
python
xmlDoc.addDocEntity
(self, name, type, ExternalID, SystemID, content)
return __tmp
Register a new entity for this document.
Register a new entity for this document.
[ "Register", "a", "new", "entity", "for", "this", "document", "." ]
def addDocEntity(self, name, type, ExternalID, SystemID, content): """Register a new entity for this document. """ ret = libxml2mod.xmlAddDocEntity(self._o, name, type, ExternalID, SystemID, content) if ret is None:raise treeError('xmlAddDocEntity() failed') __tmp = xmlEntity(_obj=ret) return __tmp
[ "def", "addDocEntity", "(", "self", ",", "name", ",", "type", ",", "ExternalID", ",", "SystemID", ",", "content", ")", ":", "ret", "=", "libxml2mod", ".", "xmlAddDocEntity", "(", "self", ".", "_o", ",", "name", ",", "type", ",", "ExternalID", ",", "SystemID", ",", "content", ")", "if", "ret", "is", "None", ":", "raise", "treeError", "(", "'xmlAddDocEntity() failed'", ")", "__tmp", "=", "xmlEntity", "(", "_obj", "=", "ret", ")", "return", "__tmp" ]
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/deps/src/libxml2-2.9.1/python/libxml2class.py#L3313-L3318
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/Tkinter.py
python
Misc.selection_own
(self, **kw)
Become owner of X selection. A keyword parameter selection specifies the name of the selection (default PRIMARY).
Become owner of X selection.
[ "Become", "owner", "of", "X", "selection", "." ]
def selection_own(self, **kw): """Become owner of X selection. A keyword parameter selection specifies the name of the selection (default PRIMARY).""" self.tk.call(('selection', 'own') + self._options(kw) + (self._w,))
[ "def", "selection_own", "(", "self", ",", "*", "*", "kw", ")", ":", "self", ".", "tk", ".", "call", "(", "(", "'selection'", ",", "'own'", ")", "+", "self", ".", "_options", "(", "kw", ")", "+", "(", "self", ".", "_w", ",", ")", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/Tkinter.py#L693-L699
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
models/AI-Model-Zoo/caffe-xilinx/tools/extra/parse_log.py
python
write_csv
(output_filename, dict_list, delimiter, verbose=False)
Write a CSV file
Write a CSV file
[ "Write", "a", "CSV", "file" ]
def write_csv(output_filename, dict_list, delimiter, verbose=False): """Write a CSV file """ if not dict_list: if verbose: print('Not writing %s; no lines to write' % output_filename) return dialect = csv.excel dialect.delimiter = delimiter with open(output_filename, 'w') as f: dict_writer = csv.DictWriter(f, fieldnames=dict_list[0].keys(), dialect=dialect) dict_writer.writeheader() dict_writer.writerows(dict_list) if verbose: print 'Wrote %s' % output_filename
[ "def", "write_csv", "(", "output_filename", ",", "dict_list", ",", "delimiter", ",", "verbose", "=", "False", ")", ":", "if", "not", "dict_list", ":", "if", "verbose", ":", "print", "(", "'Not writing %s; no lines to write'", "%", "output_filename", ")", "return", "dialect", "=", "csv", ".", "excel", "dialect", ".", "delimiter", "=", "delimiter", "with", "open", "(", "output_filename", ",", "'w'", ")", "as", "f", ":", "dict_writer", "=", "csv", ".", "DictWriter", "(", "f", ",", "fieldnames", "=", "dict_list", "[", "0", "]", ".", "keys", "(", ")", ",", "dialect", "=", "dialect", ")", "dict_writer", ".", "writeheader", "(", ")", "dict_writer", ".", "writerows", "(", "dict_list", ")", "if", "verbose", ":", "print", "'Wrote %s'", "%", "output_filename" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/models/AI-Model-Zoo/caffe-xilinx/tools/extra/parse_log.py#L148-L166
Tencent/Pebble
68315f176d9e328a233ace29b7579a829f89879f
tools/blade/src/blade/proto_library_target.py
python
ProtoLibrary._check_proto_srcs_name
(self, srcs_list)
_check_proto_srcs_name. Checks whether the proto file's name ends with 'proto'.
_check_proto_srcs_name.
[ "_check_proto_srcs_name", "." ]
def _check_proto_srcs_name(self, srcs_list): """_check_proto_srcs_name. Checks whether the proto file's name ends with 'proto'. """ err = 0 for src in srcs_list: base_name = os.path.basename(src) pos = base_name.rfind('.') if pos == -1: err = 1 file_suffix = base_name[pos + 1:] if file_suffix != 'proto': err = 1 if err == 1: console.error_exit('invalid proto file name %s' % src)
[ "def", "_check_proto_srcs_name", "(", "self", ",", "srcs_list", ")", ":", "err", "=", "0", "for", "src", "in", "srcs_list", ":", "base_name", "=", "os", ".", "path", ".", "basename", "(", "src", ")", "pos", "=", "base_name", ".", "rfind", "(", "'.'", ")", "if", "pos", "==", "-", "1", ":", "err", "=", "1", "file_suffix", "=", "base_name", "[", "pos", "+", "1", ":", "]", "if", "file_suffix", "!=", "'proto'", ":", "err", "=", "1", "if", "err", "==", "1", ":", "console", ".", "error_exit", "(", "'invalid proto file name %s'", "%", "src", ")" ]
https://github.com/Tencent/Pebble/blob/68315f176d9e328a233ace29b7579a829f89879f/tools/blade/src/blade/proto_library_target.py#L59-L75
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/tools/docs/py_guide_parser.py
python
md_files_in_dir
(py_guide_src_dir)
return [(full, f) for full, f in all_in_dir if os.path.isfile(full) and f.endswith('.md')]
Returns a list of filename (full_path, base) pairs for guide files.
Returns a list of filename (full_path, base) pairs for guide files.
[ "Returns", "a", "list", "of", "filename", "(", "full_path", "base", ")", "pairs", "for", "guide", "files", "." ]
def md_files_in_dir(py_guide_src_dir): """Returns a list of filename (full_path, base) pairs for guide files.""" all_in_dir = [(os.path.join(py_guide_src_dir, f), f) for f in os.listdir(py_guide_src_dir)] return [(full, f) for full, f in all_in_dir if os.path.isfile(full) and f.endswith('.md')]
[ "def", "md_files_in_dir", "(", "py_guide_src_dir", ")", ":", "all_in_dir", "=", "[", "(", "os", ".", "path", ".", "join", "(", "py_guide_src_dir", ",", "f", ")", ",", "f", ")", "for", "f", "in", "os", ".", "listdir", "(", "py_guide_src_dir", ")", "]", "return", "[", "(", "full", ",", "f", ")", "for", "full", ",", "f", "in", "all_in_dir", "if", "os", ".", "path", ".", "isfile", "(", "full", ")", "and", "f", ".", "endswith", "(", "'.md'", ")", "]" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/tools/docs/py_guide_parser.py#L26-L31
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/propgrid.py
python
PropertyGrid.SelectProperty
(*args, **kwargs)
return _propgrid.PropertyGrid_SelectProperty(*args, **kwargs)
SelectProperty(self, PGPropArg id, bool focus=False) -> bool
SelectProperty(self, PGPropArg id, bool focus=False) -> bool
[ "SelectProperty", "(", "self", "PGPropArg", "id", "bool", "focus", "=", "False", ")", "-", ">", "bool" ]
def SelectProperty(*args, **kwargs): """SelectProperty(self, PGPropArg id, bool focus=False) -> bool""" return _propgrid.PropertyGrid_SelectProperty(*args, **kwargs)
[ "def", "SelectProperty", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_propgrid", ".", "PropertyGrid_SelectProperty", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/propgrid.py#L2195-L2197
RegrowthStudios/SoACode-Public
c3ddd69355b534d5e70e2e6d0c489b4e93ab1ffe
utils/git-hooks/cpplint/cpplint.py
python
ResetNolintSuppressions
()
Resets the set of NOLINT suppressions to empty.
Resets the set of NOLINT suppressions to empty.
[ "Resets", "the", "set", "of", "NOLINT", "suppressions", "to", "empty", "." ]
def ResetNolintSuppressions(): "Resets the set of NOLINT suppressions to empty." _error_suppressions.clear()
[ "def", "ResetNolintSuppressions", "(", ")", ":", "_error_suppressions", ".", "clear", "(", ")" ]
https://github.com/RegrowthStudios/SoACode-Public/blob/c3ddd69355b534d5e70e2e6d0c489b4e93ab1ffe/utils/git-hooks/cpplint/cpplint.py#L348-L350
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
python/paddle/vision/ops.py
python
roi_align
(x, boxes, boxes_num, output_size, spatial_scale=1.0, sampling_ratio=-1, aligned=True, name=None)
This operator implements the roi_align layer. Region of Interest (RoI) Align operator (also known as RoI Align) is to perform bilinear interpolation on inputs of nonuniform sizes to obtain fixed-size feature maps (e.g. 7*7), as described in Mask R-CNN. Dividing each region proposal into equal-sized sections with the pooled_width and pooled_height. Location remains the origin result. In each ROI bin, the value of the four regularly sampled locations are computed directly through bilinear interpolation. The output is the mean of four locations. Thus avoid the misaligned problem. Args: x (Tensor): Input feature, 4D-Tensor with the shape of [N,C,H,W], where N is the batch size, C is the input channel, H is Height, W is weight. The data type is float32 or float64. boxes (Tensor): Boxes (RoIs, Regions of Interest) to pool over. It should be a 2-D Tensor of shape (num_boxes, 4). The data type is float32 or float64. Given as [[x1, y1, x2, y2], ...], (x1, y1) is the top left coordinates, and (x2, y2) is the bottom right coordinates. boxes_num (Tensor): The number of boxes contained in each picture in the batch, the data type is int32. output_size (int or Tuple[int, int]): The pooled output size(h, w), data type is int32. If int, h and w are both equal to output_size. spatial_scale (float32): Multiplicative spatial scale factor to translate ROI coords from their input scale to the scale used when pooling. Default: 1.0 sampling_ratio (int32): number of sampling points in the interpolation grid used to compute the output value of each pooled output bin. If > 0, then exactly ``sampling_ratio x sampling_ratio`` sampling points per bin are used. If <= 0, then an adaptive number of grid points are used (computed as ``ceil(roi_width / output_width)``, and likewise for height). Default: -1 aligned (bool): If False, use the legacy implementation. If True, pixel shift the box coordinates it by -0.5 for a better alignment with the two neighboring pixel indices. This version is used in Detectron2. Default: True name(str, optional): For detailed information, please refer to : ref:`api_guide_Name`. Usually name is no need to set and None by default. Returns: Tensor: The output of ROIAlignOp is a 4-D tensor with shape (num_boxes, channels, pooled_h, pooled_w). The data type is float32 or float64. Examples: .. code-block:: python import paddle from paddle.vision.ops import roi_align data = paddle.rand([1, 256, 32, 32]) boxes = paddle.rand([3, 4]) boxes[:, 2] += boxes[:, 0] + 3 boxes[:, 3] += boxes[:, 1] + 4 boxes_num = paddle.to_tensor([3]).astype('int32') align_out = roi_align(data, boxes, boxes_num, output_size=3) assert align_out.shape == [3, 256, 3, 3]
This operator implements the roi_align layer. Region of Interest (RoI) Align operator (also known as RoI Align) is to perform bilinear interpolation on inputs of nonuniform sizes to obtain fixed-size feature maps (e.g. 7*7), as described in Mask R-CNN.
[ "This", "operator", "implements", "the", "roi_align", "layer", ".", "Region", "of", "Interest", "(", "RoI", ")", "Align", "operator", "(", "also", "known", "as", "RoI", "Align", ")", "is", "to", "perform", "bilinear", "interpolation", "on", "inputs", "of", "nonuniform", "sizes", "to", "obtain", "fixed", "-", "size", "feature", "maps", "(", "e", ".", "g", ".", "7", "*", "7", ")", "as", "described", "in", "Mask", "R", "-", "CNN", "." ]
def roi_align(x, boxes, boxes_num, output_size, spatial_scale=1.0, sampling_ratio=-1, aligned=True, name=None): """ This operator implements the roi_align layer. Region of Interest (RoI) Align operator (also known as RoI Align) is to perform bilinear interpolation on inputs of nonuniform sizes to obtain fixed-size feature maps (e.g. 7*7), as described in Mask R-CNN. Dividing each region proposal into equal-sized sections with the pooled_width and pooled_height. Location remains the origin result. In each ROI bin, the value of the four regularly sampled locations are computed directly through bilinear interpolation. The output is the mean of four locations. Thus avoid the misaligned problem. Args: x (Tensor): Input feature, 4D-Tensor with the shape of [N,C,H,W], where N is the batch size, C is the input channel, H is Height, W is weight. The data type is float32 or float64. boxes (Tensor): Boxes (RoIs, Regions of Interest) to pool over. It should be a 2-D Tensor of shape (num_boxes, 4). The data type is float32 or float64. Given as [[x1, y1, x2, y2], ...], (x1, y1) is the top left coordinates, and (x2, y2) is the bottom right coordinates. boxes_num (Tensor): The number of boxes contained in each picture in the batch, the data type is int32. output_size (int or Tuple[int, int]): The pooled output size(h, w), data type is int32. If int, h and w are both equal to output_size. spatial_scale (float32): Multiplicative spatial scale factor to translate ROI coords from their input scale to the scale used when pooling. Default: 1.0 sampling_ratio (int32): number of sampling points in the interpolation grid used to compute the output value of each pooled output bin. If > 0, then exactly ``sampling_ratio x sampling_ratio`` sampling points per bin are used. If <= 0, then an adaptive number of grid points are used (computed as ``ceil(roi_width / output_width)``, and likewise for height). Default: -1 aligned (bool): If False, use the legacy implementation. If True, pixel shift the box coordinates it by -0.5 for a better alignment with the two neighboring pixel indices. This version is used in Detectron2. Default: True name(str, optional): For detailed information, please refer to : ref:`api_guide_Name`. Usually name is no need to set and None by default. Returns: Tensor: The output of ROIAlignOp is a 4-D tensor with shape (num_boxes, channels, pooled_h, pooled_w). The data type is float32 or float64. Examples: .. code-block:: python import paddle from paddle.vision.ops import roi_align data = paddle.rand([1, 256, 32, 32]) boxes = paddle.rand([3, 4]) boxes[:, 2] += boxes[:, 0] + 3 boxes[:, 3] += boxes[:, 1] + 4 boxes_num = paddle.to_tensor([3]).astype('int32') align_out = roi_align(data, boxes, boxes_num, output_size=3) assert align_out.shape == [3, 256, 3, 3] """ check_type(output_size, 'output_size', (int, tuple), 'roi_align') if isinstance(output_size, int): output_size = (output_size, output_size) pooled_height, pooled_width = output_size if in_dygraph_mode(): assert boxes_num is not None, "boxes_num should not be None in dygraph mode." align_out = _C_ops.roi_align( x, boxes, boxes_num, "pooled_height", pooled_height, "pooled_width", pooled_width, "spatial_scale", spatial_scale, "sampling_ratio", sampling_ratio, "aligned", aligned) return align_out else: check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'roi_align') check_variable_and_dtype(boxes, 'boxes', ['float32', 'float64'], 'roi_align') helper = LayerHelper('roi_align', **locals()) dtype = helper.input_dtype() align_out = helper.create_variable_for_type_inference(dtype) inputs = { "X": x, "ROIs": boxes, } if boxes_num is not None: inputs['RoisNum'] = boxes_num helper.append_op( type="roi_align", inputs=inputs, outputs={"Out": align_out}, attrs={ "pooled_height": pooled_height, "pooled_width": pooled_width, "spatial_scale": spatial_scale, "sampling_ratio": sampling_ratio, "aligned": aligned, }) return align_out
[ "def", "roi_align", "(", "x", ",", "boxes", ",", "boxes_num", ",", "output_size", ",", "spatial_scale", "=", "1.0", ",", "sampling_ratio", "=", "-", "1", ",", "aligned", "=", "True", ",", "name", "=", "None", ")", ":", "check_type", "(", "output_size", ",", "'output_size'", ",", "(", "int", ",", "tuple", ")", ",", "'roi_align'", ")", "if", "isinstance", "(", "output_size", ",", "int", ")", ":", "output_size", "=", "(", "output_size", ",", "output_size", ")", "pooled_height", ",", "pooled_width", "=", "output_size", "if", "in_dygraph_mode", "(", ")", ":", "assert", "boxes_num", "is", "not", "None", ",", "\"boxes_num should not be None in dygraph mode.\"", "align_out", "=", "_C_ops", ".", "roi_align", "(", "x", ",", "boxes", ",", "boxes_num", ",", "\"pooled_height\"", ",", "pooled_height", ",", "\"pooled_width\"", ",", "pooled_width", ",", "\"spatial_scale\"", ",", "spatial_scale", ",", "\"sampling_ratio\"", ",", "sampling_ratio", ",", "\"aligned\"", ",", "aligned", ")", "return", "align_out", "else", ":", "check_variable_and_dtype", "(", "x", ",", "'x'", ",", "[", "'float32'", ",", "'float64'", "]", ",", "'roi_align'", ")", "check_variable_and_dtype", "(", "boxes", ",", "'boxes'", ",", "[", "'float32'", ",", "'float64'", "]", ",", "'roi_align'", ")", "helper", "=", "LayerHelper", "(", "'roi_align'", ",", "*", "*", "locals", "(", ")", ")", "dtype", "=", "helper", ".", "input_dtype", "(", ")", "align_out", "=", "helper", ".", "create_variable_for_type_inference", "(", "dtype", ")", "inputs", "=", "{", "\"X\"", ":", "x", ",", "\"ROIs\"", ":", "boxes", ",", "}", "if", "boxes_num", "is", "not", "None", ":", "inputs", "[", "'RoisNum'", "]", "=", "boxes_num", "helper", ".", "append_op", "(", "type", "=", "\"roi_align\"", ",", "inputs", "=", "inputs", ",", "outputs", "=", "{", "\"Out\"", ":", "align_out", "}", ",", "attrs", "=", "{", "\"pooled_height\"", ":", "pooled_height", ",", "\"pooled_width\"", ":", "pooled_width", ",", "\"spatial_scale\"", ":", "spatial_scale", ",", "\"sampling_ratio\"", ":", "sampling_ratio", ",", "\"aligned\"", ":", "aligned", ",", "}", ")", "return", "align_out" ]
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/vision/ops.py#L1145-L1252
google/orbit
7c0a530f402f0c3753d0bc52f8e3eb620f65d017
third_party/include-what-you-use/fix_includes.py
python
ParseOneFile
(f, iwyu_record)
return file_lines
Given a file object, read and classify the lines of the file. For each file that iwyu_output mentions, we return a list of LineInfo objects, which is a parsed version of each line, including not only its content but its 'type', its 'key', etc. Arguments: f: an iterable object returning lines from a file. iwyu_record: the IWYUOutputRecord struct for this source file. Returns: An array of LineInfo objects. The first element is always a dummy element, so the first line of the file is at retval[1], matching the way iwyu counts line numbers.
Given a file object, read and classify the lines of the file.
[ "Given", "a", "file", "object", "read", "and", "classify", "the", "lines", "of", "the", "file", "." ]
def ParseOneFile(f, iwyu_record): """Given a file object, read and classify the lines of the file. For each file that iwyu_output mentions, we return a list of LineInfo objects, which is a parsed version of each line, including not only its content but its 'type', its 'key', etc. Arguments: f: an iterable object returning lines from a file. iwyu_record: the IWYUOutputRecord struct for this source file. Returns: An array of LineInfo objects. The first element is always a dummy element, so the first line of the file is at retval[1], matching the way iwyu counts line numbers. """ file_lines = [LineInfo(None)] for line in f: file_lines.append(LineInfo(line)) _CalculateLineTypesAndKeys(file_lines, iwyu_record) _CalculateMoveSpans(file_lines, iwyu_record.seen_forward_declare_lines) _CalculateReorderSpans(file_lines) return file_lines
[ "def", "ParseOneFile", "(", "f", ",", "iwyu_record", ")", ":", "file_lines", "=", "[", "LineInfo", "(", "None", ")", "]", "for", "line", "in", "f", ":", "file_lines", ".", "append", "(", "LineInfo", "(", "line", ")", ")", "_CalculateLineTypesAndKeys", "(", "file_lines", ",", "iwyu_record", ")", "_CalculateMoveSpans", "(", "file_lines", ",", "iwyu_record", ".", "seen_forward_declare_lines", ")", "_CalculateReorderSpans", "(", "file_lines", ")", "return", "file_lines" ]
https://github.com/google/orbit/blob/7c0a530f402f0c3753d0bc52f8e3eb620f65d017/third_party/include-what-you-use/fix_includes.py#L965-L987
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_misc.py
python
ConfigBase.Exists
(*args, **kwargs)
return _misc_.ConfigBase_Exists(*args, **kwargs)
Exists(self, String name) -> bool Returns True if either a group or an entry with a given name exists
Exists(self, String name) -> bool
[ "Exists", "(", "self", "String", "name", ")", "-", ">", "bool" ]
def Exists(*args, **kwargs): """ Exists(self, String name) -> bool Returns True if either a group or an entry with a given name exists """ return _misc_.ConfigBase_Exists(*args, **kwargs)
[ "def", "Exists", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_misc_", ".", "ConfigBase_Exists", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_misc.py#L3239-L3245
citizenfx/fivem
88276d40cc7baf8285d02754cc5ae42ec7a8563f
vendor/chromium/base/win/embedded_i18n/create_string_rc.py
python
GrdHandler.__init__
(self, string_id_set)
Constructs a handler that reads selected strings from a .grd file. The dict attribute |messages| is populated with the strings that are read. Args: string_id_set: An optional set of message identifiers to extract; all messages are extracted if empty.
Constructs a handler that reads selected strings from a .grd file.
[ "Constructs", "a", "handler", "that", "reads", "selected", "strings", "from", "a", ".", "grd", "file", "." ]
def __init__(self, string_id_set): """Constructs a handler that reads selected strings from a .grd file. The dict attribute |messages| is populated with the strings that are read. Args: string_id_set: An optional set of message identifiers to extract; all messages are extracted if empty. """ sax.handler.ContentHandler.__init__(self) self.messages = {} self.referenced_xtb_files = [] self.__id_set = string_id_set self.__message_name = None self.__element_stack = [] self.__text_scraps = [] self.__characters_callback = None
[ "def", "__init__", "(", "self", ",", "string_id_set", ")", ":", "sax", ".", "handler", ".", "ContentHandler", ".", "__init__", "(", "self", ")", "self", ".", "messages", "=", "{", "}", "self", ".", "referenced_xtb_files", "=", "[", "]", "self", ".", "__id_set", "=", "string_id_set", "self", ".", "__message_name", "=", "None", "self", ".", "__element_stack", "=", "[", "]", "self", ".", "__text_scraps", "=", "[", "]", "self", ".", "__characters_callback", "=", "None" ]
https://github.com/citizenfx/fivem/blob/88276d40cc7baf8285d02754cc5ae42ec7a8563f/vendor/chromium/base/win/embedded_i18n/create_string_rc.py#L84-L100
luliyucoordinate/Leetcode
96afcdc54807d1d184e881a075d1dbf3371e31fb
src/0142-Linked-List-Cycle-II/0142.py
python
Solution.findDuplicate
(self, nums)
return -1
:type nums: List[int] :rtype: int
:type nums: List[int] :rtype: int
[ ":", "type", "nums", ":", "List", "[", "int", "]", ":", "rtype", ":", "int" ]
def findDuplicate(self, nums): """ :type nums: List[int] :rtype: int """ if len(nums) > 1: slow = nums[0] fast = nums[nums[0]] while slow != fast: slow = nums[slow] fast = nums[nums[fast]] entry = 0 while entry != slow: entry = nums[entry] slow = nums[slow] return entry return -1
[ "def", "findDuplicate", "(", "self", ",", "nums", ")", ":", "if", "len", "(", "nums", ")", ">", "1", ":", "slow", "=", "nums", "[", "0", "]", "fast", "=", "nums", "[", "nums", "[", "0", "]", "]", "while", "slow", "!=", "fast", ":", "slow", "=", "nums", "[", "slow", "]", "fast", "=", "nums", "[", "nums", "[", "fast", "]", "]", "entry", "=", "0", "while", "entry", "!=", "slow", ":", "entry", "=", "nums", "[", "entry", "]", "slow", "=", "nums", "[", "slow", "]", "return", "entry", "return", "-", "1" ]
https://github.com/luliyucoordinate/Leetcode/blob/96afcdc54807d1d184e881a075d1dbf3371e31fb/src/0142-Linked-List-Cycle-II/0142.py#L8-L27
htcondor/htcondor
4829724575176d1d6c936e4693dfd78a728569b0
src/condor_scripts/adstash/utils.py
python
time_remaining
(starttime, timeout, positive=True)
return timeout - elapsed
Return the remaining time (in seconds) until starttime + timeout Returns 0 if there is no time remaining
Return the remaining time (in seconds) until starttime + timeout Returns 0 if there is no time remaining
[ "Return", "the", "remaining", "time", "(", "in", "seconds", ")", "until", "starttime", "+", "timeout", "Returns", "0", "if", "there", "is", "no", "time", "remaining" ]
def time_remaining(starttime, timeout, positive=True): """ Return the remaining time (in seconds) until starttime + timeout Returns 0 if there is no time remaining """ elapsed = time.time() - starttime if positive: return max(0, timeout - elapsed) return timeout - elapsed
[ "def", "time_remaining", "(", "starttime", ",", "timeout", ",", "positive", "=", "True", ")", ":", "elapsed", "=", "time", ".", "time", "(", ")", "-", "starttime", "if", "positive", ":", "return", "max", "(", "0", ",", "timeout", "-", "elapsed", ")", "return", "timeout", "-", "elapsed" ]
https://github.com/htcondor/htcondor/blob/4829724575176d1d6c936e4693dfd78a728569b0/src/condor_scripts/adstash/utils.py#L118-L126
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/strings.py
python
cat_core
(list_of_columns: List, sep: str)
return np.sum(arr_with_sep, axis=0)
Auxiliary function for :meth:`str.cat` Parameters ---------- list_of_columns : list of numpy arrays List of arrays to be concatenated with sep; these arrays may not contain NaNs! sep : string The separator string for concatenating the columns. Returns ------- nd.array The concatenation of list_of_columns with sep.
Auxiliary function for :meth:`str.cat`
[ "Auxiliary", "function", "for", ":", "meth", ":", "str", ".", "cat" ]
def cat_core(list_of_columns: List, sep: str): """ Auxiliary function for :meth:`str.cat` Parameters ---------- list_of_columns : list of numpy arrays List of arrays to be concatenated with sep; these arrays may not contain NaNs! sep : string The separator string for concatenating the columns. Returns ------- nd.array The concatenation of list_of_columns with sep. """ if sep == "": # no need to interleave sep if it is empty arr_of_cols = np.asarray(list_of_columns, dtype=object) return np.sum(arr_of_cols, axis=0) list_with_sep = [sep] * (2 * len(list_of_columns) - 1) list_with_sep[::2] = list_of_columns arr_with_sep = np.asarray(list_with_sep, dtype=object) return np.sum(arr_with_sep, axis=0)
[ "def", "cat_core", "(", "list_of_columns", ":", "List", ",", "sep", ":", "str", ")", ":", "if", "sep", "==", "\"\"", ":", "# no need to interleave sep if it is empty", "arr_of_cols", "=", "np", ".", "asarray", "(", "list_of_columns", ",", "dtype", "=", "object", ")", "return", "np", ".", "sum", "(", "arr_of_cols", ",", "axis", "=", "0", ")", "list_with_sep", "=", "[", "sep", "]", "*", "(", "2", "*", "len", "(", "list_of_columns", ")", "-", "1", ")", "list_with_sep", "[", ":", ":", "2", "]", "=", "list_of_columns", "arr_with_sep", "=", "np", ".", "asarray", "(", "list_with_sep", ",", "dtype", "=", "object", ")", "return", "np", ".", "sum", "(", "arr_with_sep", ",", "axis", "=", "0", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/strings.py#L59-L83
cms-sw/cmssw
fd9de012d503d3405420bcbeec0ec879baa57cf2
Alignment/MuonAlignment/python/svgfig.py
python
Ticks.interpret
(self)
Evaluate and return optimal ticks and miniticks according to the standard minitick specification. Normally only used internally.
Evaluate and return optimal ticks and miniticks according to the standard minitick specification.
[ "Evaluate", "and", "return", "optimal", "ticks", "and", "miniticks", "according", "to", "the", "standard", "minitick", "specification", "." ]
def interpret(self): """Evaluate and return optimal ticks and miniticks according to the standard minitick specification. Normally only used internally. """ if self.labels == None or self.labels == False: format = lambda x: "" elif self.labels == True: format = unumber elif isinstance(self.labels, str): format = lambda x: (self.labels % x) elif callable(self.labels): format = self.labels else: raise TypeError("labels must be None/False, True, a format string, or a number->string function") # Now for the ticks ticks = self.ticks # Case 1: ticks is None/False if ticks == None or ticks == False: return {}, [] # Case 2: ticks is the number of desired ticks elif isinstance(ticks, (int, long)): if ticks == True: ticks = -10 if self.logbase == None: ticks = self.compute_ticks(ticks, format) else: ticks = self.compute_logticks(self.logbase, ticks, format) # Now for the miniticks if self.miniticks == True: if self.logbase == None: return ticks, self.compute_miniticks(ticks) else: return ticks, self.compute_logminiticks(self.logbase) elif isinstance(self.miniticks, (int, long)): return ticks, self.regular_miniticks(self.miniticks) elif getattr(self.miniticks, "__iter__", False): return ticks, self.miniticks elif self.miniticks == False or self.miniticks == None: return ticks, [] else: raise TypeError("miniticks must be None/False, True, a number of desired miniticks, or a list of numbers") # Cases 3 & 4: ticks is iterable elif getattr(ticks, "__iter__", False): # Case 3: ticks is some kind of list if not isinstance(ticks, dict): output = {} eps = _epsilon * (self.high - self.low) for x in ticks: if format == unumber and abs(x) < eps: output[x] = u"0" else: output[x] = format(x) ticks = output # Case 4: ticks is a dict else: pass # Now for the miniticks if self.miniticks == True: if self.logbase == None: return ticks, self.compute_miniticks(ticks) else: return ticks, self.compute_logminiticks(self.logbase) elif isinstance(self.miniticks, (int, long)): return ticks, self.regular_miniticks(self.miniticks) elif getattr(self.miniticks, "__iter__", False): return ticks, self.miniticks elif self.miniticks == False or self.miniticks == None: return ticks, [] else: raise TypeError("miniticks must be None/False, True, a number of desired miniticks, or a list of numbers") else: raise TypeError("ticks must be None/False, a number of desired ticks, a list of numbers, or a dictionary of explicit markers")
[ "def", "interpret", "(", "self", ")", ":", "if", "self", ".", "labels", "==", "None", "or", "self", ".", "labels", "==", "False", ":", "format", "=", "lambda", "x", ":", "\"\"", "elif", "self", ".", "labels", "==", "True", ":", "format", "=", "unumber", "elif", "isinstance", "(", "self", ".", "labels", ",", "str", ")", ":", "format", "=", "lambda", "x", ":", "(", "self", ".", "labels", "%", "x", ")", "elif", "callable", "(", "self", ".", "labels", ")", ":", "format", "=", "self", ".", "labels", "else", ":", "raise", "TypeError", "(", "\"labels must be None/False, True, a format string, or a number->string function\"", ")", "# Now for the ticks", "ticks", "=", "self", ".", "ticks", "# Case 1: ticks is None/False", "if", "ticks", "==", "None", "or", "ticks", "==", "False", ":", "return", "{", "}", ",", "[", "]", "# Case 2: ticks is the number of desired ticks", "elif", "isinstance", "(", "ticks", ",", "(", "int", ",", "long", ")", ")", ":", "if", "ticks", "==", "True", ":", "ticks", "=", "-", "10", "if", "self", ".", "logbase", "==", "None", ":", "ticks", "=", "self", ".", "compute_ticks", "(", "ticks", ",", "format", ")", "else", ":", "ticks", "=", "self", ".", "compute_logticks", "(", "self", ".", "logbase", ",", "ticks", ",", "format", ")", "# Now for the miniticks", "if", "self", ".", "miniticks", "==", "True", ":", "if", "self", ".", "logbase", "==", "None", ":", "return", "ticks", ",", "self", ".", "compute_miniticks", "(", "ticks", ")", "else", ":", "return", "ticks", ",", "self", ".", "compute_logminiticks", "(", "self", ".", "logbase", ")", "elif", "isinstance", "(", "self", ".", "miniticks", ",", "(", "int", ",", "long", ")", ")", ":", "return", "ticks", ",", "self", ".", "regular_miniticks", "(", "self", ".", "miniticks", ")", "elif", "getattr", "(", "self", ".", "miniticks", ",", "\"__iter__\"", ",", "False", ")", ":", "return", "ticks", ",", "self", ".", "miniticks", "elif", "self", ".", "miniticks", "==", "False", "or", "self", ".", "miniticks", "==", "None", ":", "return", "ticks", ",", "[", "]", "else", ":", "raise", "TypeError", "(", "\"miniticks must be None/False, True, a number of desired miniticks, or a list of numbers\"", ")", "# Cases 3 & 4: ticks is iterable", "elif", "getattr", "(", "ticks", ",", "\"__iter__\"", ",", "False", ")", ":", "# Case 3: ticks is some kind of list", "if", "not", "isinstance", "(", "ticks", ",", "dict", ")", ":", "output", "=", "{", "}", "eps", "=", "_epsilon", "*", "(", "self", ".", "high", "-", "self", ".", "low", ")", "for", "x", "in", "ticks", ":", "if", "format", "==", "unumber", "and", "abs", "(", "x", ")", "<", "eps", ":", "output", "[", "x", "]", "=", "u\"0\"", "else", ":", "output", "[", "x", "]", "=", "format", "(", "x", ")", "ticks", "=", "output", "# Case 4: ticks is a dict", "else", ":", "pass", "# Now for the miniticks", "if", "self", ".", "miniticks", "==", "True", ":", "if", "self", ".", "logbase", "==", "None", ":", "return", "ticks", ",", "self", ".", "compute_miniticks", "(", "ticks", ")", "else", ":", "return", "ticks", ",", "self", ".", "compute_logminiticks", "(", "self", ".", "logbase", ")", "elif", "isinstance", "(", "self", ".", "miniticks", ",", "(", "int", ",", "long", ")", ")", ":", "return", "ticks", ",", "self", ".", "regular_miniticks", "(", "self", ".", "miniticks", ")", "elif", "getattr", "(", "self", ".", "miniticks", ",", "\"__iter__\"", ",", "False", ")", ":", "return", "ticks", ",", "self", ".", "miniticks", "elif", "self", ".", "miniticks", "==", "False", "or", "self", ".", "miniticks", "==", "None", ":", "return", "ticks", ",", "[", "]", "else", ":", "raise", "TypeError", "(", "\"miniticks must be None/False, True, a number of desired miniticks, or a list of numbers\"", ")", "else", ":", "raise", "TypeError", "(", "\"ticks must be None/False, a number of desired ticks, a list of numbers, or a dictionary of explicit markers\"", ")" ]
https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/Alignment/MuonAlignment/python/svgfig.py#L2508-L2600
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/python2_version/klampt/src/robotsim.py
python
RobotModel.interpolate
(self, a, b, u)
return _robotsim.RobotModel_interpolate(self, a, b, u)
interpolate(RobotModel self, doubleVector a, doubleVector b, double u) Interpolates smoothly between two configurations, properly taking into account nonstandard joints. Returns: (list of n floats): The configuration that is u fraction of the way from a to b
interpolate(RobotModel self, doubleVector a, doubleVector b, double u)
[ "interpolate", "(", "RobotModel", "self", "doubleVector", "a", "doubleVector", "b", "double", "u", ")" ]
def interpolate(self, a, b, u): """ interpolate(RobotModel self, doubleVector a, doubleVector b, double u) Interpolates smoothly between two configurations, properly taking into account nonstandard joints. Returns: (list of n floats): The configuration that is u fraction of the way from a to b """ return _robotsim.RobotModel_interpolate(self, a, b, u)
[ "def", "interpolate", "(", "self", ",", "a", ",", "b", ",", "u", ")", ":", "return", "_robotsim", ".", "RobotModel_interpolate", "(", "self", ",", "a", ",", "b", ",", "u", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/src/robotsim.py#L5053-L5068
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py2/sklearn/linear_model/base.py
python
LinearClassifierMixin._predict_proba_lr
(self, X)
Probability estimation for OvR logistic regression. Positive class probabilities are computed as 1. / (1. + np.exp(-self.decision_function(X))); multiclass is handled by normalizing that over all classes.
Probability estimation for OvR logistic regression.
[ "Probability", "estimation", "for", "OvR", "logistic", "regression", "." ]
def _predict_proba_lr(self, X): """Probability estimation for OvR logistic regression. Positive class probabilities are computed as 1. / (1. + np.exp(-self.decision_function(X))); multiclass is handled by normalizing that over all classes. """ prob = self.decision_function(X) prob *= -1 np.exp(prob, prob) prob += 1 np.reciprocal(prob, prob) if prob.ndim == 1: return np.vstack([1 - prob, prob]).T else: # OvR normalization, like LibLinear's predict_probability prob /= prob.sum(axis=1).reshape((prob.shape[0], -1)) return prob
[ "def", "_predict_proba_lr", "(", "self", ",", "X", ")", ":", "prob", "=", "self", ".", "decision_function", "(", "X", ")", "prob", "*=", "-", "1", "np", ".", "exp", "(", "prob", ",", "prob", ")", "prob", "+=", "1", "np", ".", "reciprocal", "(", "prob", ",", "prob", ")", "if", "prob", ".", "ndim", "==", "1", ":", "return", "np", ".", "vstack", "(", "[", "1", "-", "prob", ",", "prob", "]", ")", ".", "T", "else", ":", "# OvR normalization, like LibLinear's predict_probability", "prob", "/=", "prob", ".", "sum", "(", "axis", "=", "1", ")", ".", "reshape", "(", "(", "prob", ".", "shape", "[", "0", "]", ",", "-", "1", ")", ")", "return", "prob" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/linear_model/base.py#L343-L360