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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/learn/python/learn/graph_actions.py | python | run_feeds_iter | (output_dict, feed_dicts, restore_checkpoint_path=None) | Run `output_dict` tensors with each input in `feed_dicts`.
If `restore_checkpoint_path` is supplied, restore from checkpoint. Otherwise,
init all variables.
Args:
output_dict: A `dict` mapping string names to `Tensor` objects to run.
Tensors must all be from the same graph.
feed_dicts: Iterable of `dict` objects of input values to feed.
restore_checkpoint_path: A string containing the path to a checkpoint to
restore.
Yields:
A sequence of dicts of values read from `output_dict` tensors, one item
yielded for each item in `feed_dicts`. Keys are the same as `output_dict`,
values are the results read from the corresponding `Tensor` in
`output_dict`.
Raises:
ValueError: if `output_dict` or `feed_dicts` is None or empty. | Run `output_dict` tensors with each input in `feed_dicts`. | [
"Run",
"output_dict",
"tensors",
"with",
"each",
"input",
"in",
"feed_dicts",
"."
] | def run_feeds_iter(output_dict, feed_dicts, restore_checkpoint_path=None):
"""Run `output_dict` tensors with each input in `feed_dicts`.
If `restore_checkpoint_path` is supplied, restore from checkpoint. Otherwise,
init all variables.
Args:
output_dict: A `dict` mapping string names to `Tensor` objects to run.
Tensors must all be from the same graph.
feed_dicts: Iterable of `dict` objects of input values to feed.
restore_checkpoint_path: A string containing the path to a checkpoint to
restore.
Yields:
A sequence of dicts of values read from `output_dict` tensors, one item
yielded for each item in `feed_dicts`. Keys are the same as `output_dict`,
values are the results read from the corresponding `Tensor` in
`output_dict`.
Raises:
ValueError: if `output_dict` or `feed_dicts` is None or empty.
"""
if not output_dict:
raise ValueError('output_dict is invalid: %s.' % output_dict)
if not feed_dicts:
raise ValueError('feed_dicts is invalid: %s.' % feed_dicts)
graph = contrib_ops.get_graph_from_inputs(output_dict.values())
with graph.as_default() as g:
with tf_session.Session('') as session:
session.run(
resources.initialize_resources(resources.shared_resources() +
resources.local_resources()))
if restore_checkpoint_path:
_restore_from_checkpoint(session, g, restore_checkpoint_path)
else:
session.run(variables.global_variables_initializer())
session.run(variables.local_variables_initializer())
session.run(lookup_ops.tables_initializer())
coord = coordinator.Coordinator()
threads = None
try:
threads = queue_runner.start_queue_runners(session, coord=coord)
for f in feed_dicts:
yield session.run(output_dict, f)
finally:
coord.request_stop()
if threads:
coord.join(threads, stop_grace_period_secs=120) | [
"def",
"run_feeds_iter",
"(",
"output_dict",
",",
"feed_dicts",
",",
"restore_checkpoint_path",
"=",
"None",
")",
":",
"if",
"not",
"output_dict",
":",
"raise",
"ValueError",
"(",
"'output_dict is invalid: %s.'",
"%",
"output_dict",
")",
"if",
"not",
"feed_dicts",
... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/learn/python/learn/graph_actions.py#L654-L702 | ||
danxuhk/ContinuousCRF-CNN | 2b6dcaf179620f118b225ed12c890414ca828e21 | python/caffe/detector.py | python | Detector.crop | (self, im, window) | return crop | Crop a window from the image for detection. Include surrounding context
according to the `context_pad` configuration.
Parameters
----------
im: H x W x K image ndarray to crop.
window: bounding box coordinates as ymin, xmin, ymax, xmax.
Returns
-------
crop: cropped window. | Crop a window from the image for detection. Include surrounding context
according to the `context_pad` configuration. | [
"Crop",
"a",
"window",
"from",
"the",
"image",
"for",
"detection",
".",
"Include",
"surrounding",
"context",
"according",
"to",
"the",
"context_pad",
"configuration",
"."
] | def crop(self, im, window):
"""
Crop a window from the image for detection. Include surrounding context
according to the `context_pad` configuration.
Parameters
----------
im: H x W x K image ndarray to crop.
window: bounding box coordinates as ymin, xmin, ymax, xmax.
Returns
-------
crop: cropped window.
"""
# Crop window from the image.
crop = im[window[0]:window[2], window[1]:window[3]]
if self.context_pad:
box = window.copy()
crop_size = self.blobs[self.inputs[0]].width # assumes square
scale = crop_size / (1. * crop_size - self.context_pad * 2)
# Crop a box + surrounding context.
half_h = (box[2] - box[0] + 1) / 2.
half_w = (box[3] - box[1] + 1) / 2.
center = (box[0] + half_h, box[1] + half_w)
scaled_dims = scale * np.array((-half_h, -half_w, half_h, half_w))
box = np.round(np.tile(center, 2) + scaled_dims)
full_h = box[2] - box[0] + 1
full_w = box[3] - box[1] + 1
scale_h = crop_size / full_h
scale_w = crop_size / full_w
pad_y = round(max(0, -box[0]) * scale_h) # amount out-of-bounds
pad_x = round(max(0, -box[1]) * scale_w)
# Clip box to image dimensions.
im_h, im_w = im.shape[:2]
box = np.clip(box, 0., [im_h, im_w, im_h, im_w])
clip_h = box[2] - box[0] + 1
clip_w = box[3] - box[1] + 1
assert(clip_h > 0 and clip_w > 0)
crop_h = round(clip_h * scale_h)
crop_w = round(clip_w * scale_w)
if pad_y + crop_h > crop_size:
crop_h = crop_size - pad_y
if pad_x + crop_w > crop_size:
crop_w = crop_size - pad_x
# collect with context padding and place in input
# with mean padding
context_crop = im[box[0]:box[2], box[1]:box[3]]
context_crop = caffe.io.resize_image(context_crop, (crop_h, crop_w))
crop = np.ones(self.crop_dims, dtype=np.float32) * self.crop_mean
crop[pad_y:(pad_y + crop_h), pad_x:(pad_x + crop_w)] = context_crop
return crop | [
"def",
"crop",
"(",
"self",
",",
"im",
",",
"window",
")",
":",
"# Crop window from the image.",
"crop",
"=",
"im",
"[",
"window",
"[",
"0",
"]",
":",
"window",
"[",
"2",
"]",
",",
"window",
"[",
"1",
"]",
":",
"window",
"[",
"3",
"]",
"]",
"if",... | https://github.com/danxuhk/ContinuousCRF-CNN/blob/2b6dcaf179620f118b225ed12c890414ca828e21/python/caffe/detector.py#L125-L179 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/boto/boto/ec2/cloudwatch/__init__.py | python | CloudWatchConnection.put_metric_alarm | (self, alarm) | return self.get_status('PutMetricAlarm', params) | Creates or updates an alarm and associates it with the specified Amazon
CloudWatch metric. Optionally, this operation can associate one or more
Amazon Simple Notification Service resources with the alarm.
When this operation creates an alarm, the alarm state is immediately
set to INSUFFICIENT_DATA. The alarm is evaluated and its StateValue is
set appropriately. Any actions associated with the StateValue is then
executed.
When updating an existing alarm, its StateValue is left unchanged.
:type alarm: boto.ec2.cloudwatch.alarm.MetricAlarm
:param alarm: MetricAlarm object. | Creates or updates an alarm and associates it with the specified Amazon
CloudWatch metric. Optionally, this operation can associate one or more
Amazon Simple Notification Service resources with the alarm. | [
"Creates",
"or",
"updates",
"an",
"alarm",
"and",
"associates",
"it",
"with",
"the",
"specified",
"Amazon",
"CloudWatch",
"metric",
".",
"Optionally",
"this",
"operation",
"can",
"associate",
"one",
"or",
"more",
"Amazon",
"Simple",
"Notification",
"Service",
"r... | def put_metric_alarm(self, alarm):
"""
Creates or updates an alarm and associates it with the specified Amazon
CloudWatch metric. Optionally, this operation can associate one or more
Amazon Simple Notification Service resources with the alarm.
When this operation creates an alarm, the alarm state is immediately
set to INSUFFICIENT_DATA. The alarm is evaluated and its StateValue is
set appropriately. Any actions associated with the StateValue is then
executed.
When updating an existing alarm, its StateValue is left unchanged.
:type alarm: boto.ec2.cloudwatch.alarm.MetricAlarm
:param alarm: MetricAlarm object.
"""
params = {
'AlarmName': alarm.name,
'MetricName': alarm.metric,
'Namespace': alarm.namespace,
'Statistic': alarm.statistic,
'ComparisonOperator': alarm.comparison,
'Threshold': alarm.threshold,
'EvaluationPeriods': alarm.evaluation_periods,
'Period': alarm.period,
}
if alarm.actions_enabled is not None:
params['ActionsEnabled'] = alarm.actions_enabled
if alarm.alarm_actions:
self.build_list_params(params, alarm.alarm_actions,
'AlarmActions.member.%s')
if alarm.description:
params['AlarmDescription'] = alarm.description
if alarm.dimensions:
self.build_dimension_param(alarm.dimensions, params)
if alarm.insufficient_data_actions:
self.build_list_params(params, alarm.insufficient_data_actions,
'InsufficientDataActions.member.%s')
if alarm.ok_actions:
self.build_list_params(params, alarm.ok_actions,
'OKActions.member.%s')
if alarm.unit:
params['Unit'] = alarm.unit
alarm.connection = self
return self.get_status('PutMetricAlarm', params) | [
"def",
"put_metric_alarm",
"(",
"self",
",",
"alarm",
")",
":",
"params",
"=",
"{",
"'AlarmName'",
":",
"alarm",
".",
"name",
",",
"'MetricName'",
":",
"alarm",
".",
"metric",
",",
"'Namespace'",
":",
"alarm",
".",
"namespace",
",",
"'Statistic'",
":",
"... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/ec2/cloudwatch/__init__.py#L484-L528 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/idlelib/search.py | python | _search_dialog | (parent) | Display search test box. | Display search test box. | [
"Display",
"search",
"test",
"box",
"."
] | def _search_dialog(parent): # htest #
"Display search test box."
from tkinter import Toplevel, Text
from tkinter.ttk import Frame, Button
top = Toplevel(parent)
top.title("Test SearchDialog")
x, y = map(int, parent.geometry().split('+')[1:])
top.geometry("+%d+%d" % (x, y + 175))
frame = Frame(top)
frame.pack()
text = Text(frame, inactiveselectbackground='gray')
text.pack()
text.insert("insert","This is a sample string.\n"*5)
def show_find():
text.tag_add('sel', '1.0', 'end')
_setup(text).open(text)
text.tag_remove('sel', '1.0', 'end')
button = Button(frame, text="Search (selection ignored)", command=show_find)
button.pack() | [
"def",
"_search_dialog",
"(",
"parent",
")",
":",
"# htest #",
"from",
"tkinter",
"import",
"Toplevel",
",",
"Text",
"from",
"tkinter",
".",
"ttk",
"import",
"Frame",
",",
"Button",
"top",
"=",
"Toplevel",
"(",
"parent",
")",
"top",
".",
"title",
"(",
"\... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/idlelib/search.py#L135-L157 | ||
fatih/subvim | 241b6d170597857105da219c9b7d36059e9f11fb | vim/base/YouCompleteMe/third_party/jedi/jedi/evaluate.py | python | follow_call | (call) | return follow_call_path(path, s.parent, s.start_pos) | Follow a call is following a function, variable, string, etc. | Follow a call is following a function, variable, string, etc. | [
"Follow",
"a",
"call",
"is",
"following",
"a",
"function",
"variable",
"string",
"etc",
"."
] | def follow_call(call):
"""Follow a call is following a function, variable, string, etc."""
path = call.generate_call_path()
# find the statement of the Scope
s = call
while not s.parent.isinstance(pr.IsScope):
s = s.parent
return follow_call_path(path, s.parent, s.start_pos) | [
"def",
"follow_call",
"(",
"call",
")",
":",
"path",
"=",
"call",
".",
"generate_call_path",
"(",
")",
"# find the statement of the Scope",
"s",
"=",
"call",
"while",
"not",
"s",
".",
"parent",
".",
"isinstance",
"(",
"pr",
".",
"IsScope",
")",
":",
"s",
... | https://github.com/fatih/subvim/blob/241b6d170597857105da219c9b7d36059e9f11fb/vim/base/YouCompleteMe/third_party/jedi/jedi/evaluate.py#L692-L700 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py3/scipy/optimize/_trustregion_constr/qp_subproblem.py | python | sphere_intersections | (z, d, trust_radius,
entire_line=False) | return ta, tb, intersect | Find the intersection between segment (or line) and spherical constraints.
Find the intersection between the segment (or line) defined by the
parametric equation ``x(t) = z + t*d`` and the ball
``||x|| <= trust_radius``.
Parameters
----------
z : array_like, shape (n,)
Initial point.
d : array_like, shape (n,)
Direction.
trust_radius : float
Ball radius.
entire_line : bool, optional
When ``True`` the function returns the intersection between the line
``x(t) = z + t*d`` (``t`` can assume any value) and the ball
``||x|| <= trust_radius``. When ``False`` returns the intersection
between the segment ``x(t) = z + t*d``, ``0 <= t <= 1``, and the ball.
Returns
-------
ta, tb : float
The line/segment ``x(t) = z + t*d`` is inside the ball for
for ``ta <= t <= tb``.
intersect : bool
When ``True`` there is a intersection between the line/segment
and the sphere. On the other hand, when ``False``, there is no
intersection. | Find the intersection between segment (or line) and spherical constraints. | [
"Find",
"the",
"intersection",
"between",
"segment",
"(",
"or",
"line",
")",
"and",
"spherical",
"constraints",
"."
] | def sphere_intersections(z, d, trust_radius,
entire_line=False):
"""Find the intersection between segment (or line) and spherical constraints.
Find the intersection between the segment (or line) defined by the
parametric equation ``x(t) = z + t*d`` and the ball
``||x|| <= trust_radius``.
Parameters
----------
z : array_like, shape (n,)
Initial point.
d : array_like, shape (n,)
Direction.
trust_radius : float
Ball radius.
entire_line : bool, optional
When ``True`` the function returns the intersection between the line
``x(t) = z + t*d`` (``t`` can assume any value) and the ball
``||x|| <= trust_radius``. When ``False`` returns the intersection
between the segment ``x(t) = z + t*d``, ``0 <= t <= 1``, and the ball.
Returns
-------
ta, tb : float
The line/segment ``x(t) = z + t*d`` is inside the ball for
for ``ta <= t <= tb``.
intersect : bool
When ``True`` there is a intersection between the line/segment
and the sphere. On the other hand, when ``False``, there is no
intersection.
"""
# Special case when d=0
if norm(d) == 0:
return 0, 0, False
# Check for inf trust_radius
if np.isinf(trust_radius):
if entire_line:
ta = -np.inf
tb = np.inf
else:
ta = 0
tb = 1
intersect = True
return ta, tb, intersect
a = np.dot(d, d)
b = 2 * np.dot(z, d)
c = np.dot(z, z) - trust_radius**2
discriminant = b*b - 4*a*c
if discriminant < 0:
intersect = False
return 0, 0, intersect
sqrt_discriminant = np.sqrt(discriminant)
# The following calculation is mathematically
# equivalent to:
# ta = (-b - sqrt_discriminant) / (2*a)
# tb = (-b + sqrt_discriminant) / (2*a)
# but produce smaller round off errors.
# Look at Matrix Computation p.97
# for a better justification.
aux = b + copysign(sqrt_discriminant, b)
ta = -aux / (2*a)
tb = -2*c / aux
ta, tb = sorted([ta, tb])
if entire_line:
intersect = True
else:
# Checks to see if intersection happens
# within vectors length.
if tb < 0 or ta > 1:
intersect = False
ta = 0
tb = 0
else:
intersect = True
# Restrict intersection interval
# between 0 and 1.
ta = max(0, ta)
tb = min(1, tb)
return ta, tb, intersect | [
"def",
"sphere_intersections",
"(",
"z",
",",
"d",
",",
"trust_radius",
",",
"entire_line",
"=",
"False",
")",
":",
"# Special case when d=0",
"if",
"norm",
"(",
"d",
")",
"==",
"0",
":",
"return",
"0",
",",
"0",
",",
"False",
"# Check for inf trust_radius",... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/optimize/_trustregion_constr/qp_subproblem.py#L66-L149 | |
openai/triton | 7b48340ffddd7d2624b0330b219eb05b673c086b | python/triton/code_gen.py | python | autotune | (configs, key, prune_configs_by=None, reset_to_zero=None) | return decorator | Decorator for auto-tuning a :code:`triton.jit`'d function.
.. highlight:: python
.. code-block:: python
@triton.autotune(configs=[
triton.Config(meta={'BLOCK_SIZE': 128}, num_warps=4),
triton.Config(meta={'BLOCK_SIZE': 1024}, num_warps=8),
],
key=['x_size'] # the two above configs will be evaluated anytime
# the value of x_size changes
)
@triton.jit
def kernel(x_ptr, x_size, **META):
BLOCK_SIZE = META['BLOCK_SIZE']
:note: When all the configurations are evaluated, the kernel will run multiple time.
This means that whatever value the kernel updates will be updated multiple times.
To avoid this undesired behavior, you can use the `reset_to_zero` argument, which
reset the value of the provided tensor to `zero` before running any configuration.
:param configs: a list of :code:`triton.Config` objects
:type configs: list[triton.Config]
:param key: a list of argument names whose change in value will trigger the evaluation of all provided configs.
:type key: list[str]
:param prune_configs_by: a dict of functions that are used to prune configs, fields:
'perf_model': performance model used to predicate running time with different configs, returns running time
'top_k': number of configs to bench
'prune_num_stages_by'(optional): a function used to prune num_stages. It take configs:List[Config] as its input, and returns pruned configs.
:param reset_to_zero: a list of argument names whose value will be reset to zero before evaluating any configs.
:type reset_to_zero: list[str] | Decorator for auto-tuning a :code:`triton.jit`'d function. | [
"Decorator",
"for",
"auto",
"-",
"tuning",
"a",
":",
"code",
":",
"triton",
".",
"jit",
"d",
"function",
"."
] | def autotune(configs, key, prune_configs_by=None, reset_to_zero=None):
"""
Decorator for auto-tuning a :code:`triton.jit`'d function.
.. highlight:: python
.. code-block:: python
@triton.autotune(configs=[
triton.Config(meta={'BLOCK_SIZE': 128}, num_warps=4),
triton.Config(meta={'BLOCK_SIZE': 1024}, num_warps=8),
],
key=['x_size'] # the two above configs will be evaluated anytime
# the value of x_size changes
)
@triton.jit
def kernel(x_ptr, x_size, **META):
BLOCK_SIZE = META['BLOCK_SIZE']
:note: When all the configurations are evaluated, the kernel will run multiple time.
This means that whatever value the kernel updates will be updated multiple times.
To avoid this undesired behavior, you can use the `reset_to_zero` argument, which
reset the value of the provided tensor to `zero` before running any configuration.
:param configs: a list of :code:`triton.Config` objects
:type configs: list[triton.Config]
:param key: a list of argument names whose change in value will trigger the evaluation of all provided configs.
:type key: list[str]
:param prune_configs_by: a dict of functions that are used to prune configs, fields:
'perf_model': performance model used to predicate running time with different configs, returns running time
'top_k': number of configs to bench
'prune_num_stages_by'(optional): a function used to prune num_stages. It take configs:List[Config] as its input, and returns pruned configs.
:param reset_to_zero: a list of argument names whose value will be reset to zero before evaluating any configs.
:type reset_to_zero: list[str]
"""
def decorator(fn):
def wrapper(kernel):
return Autotuner(kernel, fn.arg_names, configs, key, reset_to_zero, prune_configs_by)
fn.kernel_decorators.append(wrapper)
return fn
return decorator | [
"def",
"autotune",
"(",
"configs",
",",
"key",
",",
"prune_configs_by",
"=",
"None",
",",
"reset_to_zero",
"=",
"None",
")",
":",
"def",
"decorator",
"(",
"fn",
")",
":",
"def",
"wrapper",
"(",
"kernel",
")",
":",
"return",
"Autotuner",
"(",
"kernel",
... | https://github.com/openai/triton/blob/7b48340ffddd7d2624b0330b219eb05b673c086b/python/triton/code_gen.py#L1069-L1110 | |
weolar/miniblink49 | 1c4678db0594a4abde23d3ebbcc7cd13c3170777 | third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/autopep8.py | python | fix_e265 | (source, aggressive=False) | return ''.join(fixed_lines) | Format block comments. | Format block comments. | [
"Format",
"block",
"comments",
"."
] | def fix_e265(source, aggressive=False): # pylint: disable=unused-argument
"""Format block comments."""
if '#' not in source:
# Optimization.
return source
ignored_line_numbers = multiline_string_lines(
source,
include_docstrings=True) | set(commented_out_code_lines(source))
fixed_lines = []
sio = io.StringIO(source)
for (line_number, line) in enumerate(sio.readlines(), start=1):
if (
line.lstrip().startswith('#') and
line_number not in ignored_line_numbers
):
indentation = _get_indentation(line)
line = line.lstrip()
# Normalize beginning if not a shebang.
if len(line) > 1:
if (
# Leave multiple spaces like '# ' alone.
(line.count('#') > 1 or line[1].isalnum())
# Leave stylistic outlined blocks alone.
and not line.rstrip().endswith('#')
):
line = '# ' + line.lstrip('# \t')
fixed_lines.append(indentation + line)
else:
fixed_lines.append(line)
return ''.join(fixed_lines) | [
"def",
"fix_e265",
"(",
"source",
",",
"aggressive",
"=",
"False",
")",
":",
"# pylint: disable=unused-argument",
"if",
"'#'",
"not",
"in",
"source",
":",
"# Optimization.",
"return",
"source",
"ignored_line_numbers",
"=",
"multiline_string_lines",
"(",
"source",
",... | https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/autopep8.py#L1150-L1184 | |
RGF-team/rgf | 272afb85b4c91571f576e5fc83ecfacce3672eb4 | python-package/rgf/utils.py | python | CommonRGFEstimatorBase.n_features_ | (self) | The number of features when `fit` is performed. | The number of features when `fit` is performed. | [
"The",
"number",
"of",
"features",
"when",
"fit",
"is",
"performed",
"."
] | def n_features_(self):
"""The number of features when `fit` is performed."""
if not hasattr(self, '_n_features'):
raise NotFittedError(NOT_FITTED_ERROR_DESC)
else:
return self._n_features | [
"def",
"n_features_",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_n_features'",
")",
":",
"raise",
"NotFittedError",
"(",
"NOT_FITTED_ERROR_DESC",
")",
"else",
":",
"return",
"self",
".",
"_n_features"
] | https://github.com/RGF-team/rgf/blob/272afb85b4c91571f576e5fc83ecfacce3672eb4/python-package/rgf/utils.py#L398-L403 | ||
D-X-Y/caffe-faster-rcnn | eb50c97ff48f3df115d0e85fe0a32b0c7e2aa4cb | scripts/cpp_lint.py | python | IsCppString | (line) | return ((line.count('"') - line.count(r'\"') - line.count("'\"'")) & 1) == 1 | Does line terminate so, that the next symbol is in string constant.
This function does not consider single-line nor multi-line comments.
Args:
line: is a partial line of code starting from the 0..n.
Returns:
True, if next character appended to 'line' is inside a
string constant. | Does line terminate so, that the next symbol is in string constant. | [
"Does",
"line",
"terminate",
"so",
"that",
"the",
"next",
"symbol",
"is",
"in",
"string",
"constant",
"."
] | def IsCppString(line):
"""Does line terminate so, that the next symbol is in string constant.
This function does not consider single-line nor multi-line comments.
Args:
line: is a partial line of code starting from the 0..n.
Returns:
True, if next character appended to 'line' is inside a
string constant.
"""
line = line.replace(r'\\', 'XX') # after this, \\" does not match to \"
return ((line.count('"') - line.count(r'\"') - line.count("'\"'")) & 1) == 1 | [
"def",
"IsCppString",
"(",
"line",
")",
":",
"line",
"=",
"line",
".",
"replace",
"(",
"r'\\\\'",
",",
"'XX'",
")",
"# after this, \\\\\" does not match to \\\"",
"return",
"(",
"(",
"line",
".",
"count",
"(",
"'\"'",
")",
"-",
"line",
".",
"count",
"(",
... | https://github.com/D-X-Y/caffe-faster-rcnn/blob/eb50c97ff48f3df115d0e85fe0a32b0c7e2aa4cb/scripts/cpp_lint.py#L1049-L1063 | |
lballabio/quantlib-old | 136336947ed4fea9ecc1da6edad188700e821739 | gensrc/gensrc/enumerations/enumerationlist.py | python | EnumerationList.__init__ | (self) | Initialize the EnumerationList object and load enumeration parameters from
available config files. | Initialize the EnumerationList object and load enumeration parameters from
available config files. | [
"Initialize",
"the",
"EnumerationList",
"object",
"and",
"load",
"enumeration",
"parameters",
"from",
"available",
"config",
"files",
"."
] | def __init__(self):
"""Initialize the EnumerationList object and load enumeration parameters from
available config files."""
self.typeDict_ = {}
if os.path.exists('metadata/enumerations/enumeratedtypes.xml'):
xmlEnumTypes = xmlreader.XmlReader('metadata/enumerations/enumeratedtypes')
xmlEnumTypes.serializeObjectDict(self, enumeratedtypes.EnumeratedTypeGroup)
xmlEnumTypes.serializeProperty(self, common.ENUM_TYPE_COPYRIGHT)
self.hasEnumeratedTypes = True
for item in self.enumeratedTypeGroups_.values():
self.typeDict_[item.type()] = item.includeFile()
else:
self.hasEnumeratedTypes = False
if os.path.exists('metadata/enumerations/enumeratedclasses.xml'):
xmlEnumClasses = xmlreader.XmlReader('metadata/enumerations/enumeratedclasses')
xmlEnumClasses.serializeObjectDict(self, enumeratedclasses.EnumeratedClassGroup)
xmlEnumClasses.serializeProperty(self, common.ENUM_CLASS_COPYRIGHT)
self.hasEnumeratedClasses = True
for item in self.enumeratedClassGroups_.values():
self.typeDict_[item.className()] = item.includeFile()
else:
self.hasEnumeratedClasses= False
if os.path.exists('metadata/enumerations/enumeratedpairs.xml'):
xmlEnumPairs = xmlreader.XmlReader('metadata/enumerations/enumeratedpairs')
xmlEnumPairs.serializeObjectDict(self, enumeratedpairs.EnumeratedPairGroup)
xmlEnumPairs.serializeProperty(self, common.ENUM_PAIR_COPYRIGHT)
self.hasEnumeratedPairs = True
for item in self.enumeratedPairGroups_.values():
self.typeDict_[item.className()] = item.includeFile()
else:
self.hasEnumeratedPairs = False | [
"def",
"__init__",
"(",
"self",
")",
":",
"self",
".",
"typeDict_",
"=",
"{",
"}",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"'metadata/enumerations/enumeratedtypes.xml'",
")",
":",
"xmlEnumTypes",
"=",
"xmlreader",
".",
"XmlReader",
"(",
"'metadata/enumera... | https://github.com/lballabio/quantlib-old/blob/136336947ed4fea9ecc1da6edad188700e821739/gensrc/gensrc/enumerations/enumerationlist.py#L74-L108 | ||
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | chrome/browser/extensions/PRESUBMIT.py | python | HistogramValueChecker.GetDeletedLinesFromScmDiff | (self, affected_file) | return results | Return a list of of line numbers (1-based) corresponding to lines
deleted from the new source file (if they had been present in it). Note
that if multiple contiguous lines have been deleted, the returned list will
contain contiguous line number entries. To prevent false positives, we
return deleted line numbers *only* from diff chunks which decrease the size
of the new file.
Note: We need this method because we have access to neither the old file
content nor the list of "delete" changes from the current presubmit script
API. | Return a list of of line numbers (1-based) corresponding to lines
deleted from the new source file (if they had been present in it). Note
that if multiple contiguous lines have been deleted, the returned list will
contain contiguous line number entries. To prevent false positives, we
return deleted line numbers *only* from diff chunks which decrease the size
of the new file. | [
"Return",
"a",
"list",
"of",
"of",
"line",
"numbers",
"(",
"1",
"-",
"based",
")",
"corresponding",
"to",
"lines",
"deleted",
"from",
"the",
"new",
"source",
"file",
"(",
"if",
"they",
"had",
"been",
"present",
"in",
"it",
")",
".",
"Note",
"that",
"... | def GetDeletedLinesFromScmDiff(self, affected_file):
"""Return a list of of line numbers (1-based) corresponding to lines
deleted from the new source file (if they had been present in it). Note
that if multiple contiguous lines have been deleted, the returned list will
contain contiguous line number entries. To prevent false positives, we
return deleted line numbers *only* from diff chunks which decrease the size
of the new file.
Note: We need this method because we have access to neither the old file
content nor the list of "delete" changes from the current presubmit script
API.
"""
results = []
line_num = 0
deleting_lines = False
for line in affected_file.GenerateScmDiff().splitlines():
# Parse the unified diff chunk optional section heading, which looks like
# @@ -l,s +l,s @@ optional section heading
m = self.input_api.re.match(
r'^@@ \-([0-9]+)\,([0-9]+) \+([0-9]+)\,([0-9]+) @@', line)
if m:
old_line_num = int(m.group(1))
old_size = int(m.group(2))
new_line_num = int(m.group(3))
new_size = int(m.group(4))
line_num = new_line_num
# Return line numbers only from diff chunks decreasing the size of the
# new file
deleting_lines = old_size > new_size
continue
if not line.startswith('-'):
line_num += 1
if deleting_lines and line.startswith('-') and not line.startswith('--'):
results.append(line_num)
return results | [
"def",
"GetDeletedLinesFromScmDiff",
"(",
"self",
",",
"affected_file",
")",
":",
"results",
"=",
"[",
"]",
"line_num",
"=",
"0",
"deleting_lines",
"=",
"False",
"for",
"line",
"in",
"affected_file",
".",
"GenerateScmDiff",
"(",
")",
".",
"splitlines",
"(",
... | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/chrome/browser/extensions/PRESUBMIT.py#L185-L220 | |
zlgopen/awtk | 2c49e854a78749d9092907c027a7fba9062be549 | 3rd/mbedtls/scripts/assemble_changelog.py | python | TextChangelogFormat.extract_top_version | (cls, changelog_file_content) | return (changelog_file_content[:top_version_start],
top_version_title, top_version_body,
changelog_file_content[top_version_end:]) | A version section starts with a line starting with '='. | A version section starts with a line starting with '='. | [
"A",
"version",
"section",
"starts",
"with",
"a",
"line",
"starting",
"with",
"=",
"."
] | def extract_top_version(cls, changelog_file_content):
"""A version section starts with a line starting with '='."""
m = re.search(cls._top_version_re, changelog_file_content)
top_version_start = m.start(1)
top_version_end = m.end(2)
top_version_title = m.group(1)
top_version_body = m.group(2)
if cls.is_released_version(top_version_title):
top_version_end = top_version_start
top_version_title = cls._unreleased_version_text + b'\n\n'
top_version_body = b''
return (changelog_file_content[:top_version_start],
top_version_title, top_version_body,
changelog_file_content[top_version_end:]) | [
"def",
"extract_top_version",
"(",
"cls",
",",
"changelog_file_content",
")",
":",
"m",
"=",
"re",
".",
"search",
"(",
"cls",
".",
"_top_version_re",
",",
"changelog_file_content",
")",
"top_version_start",
"=",
"m",
".",
"start",
"(",
"1",
")",
"top_version_e... | https://github.com/zlgopen/awtk/blob/2c49e854a78749d9092907c027a7fba9062be549/3rd/mbedtls/scripts/assemble_changelog.py#L131-L144 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/ops/linalg/sparse/sparse_csr_matrix_grad.py | python | _SparseMatrixSparseMatMulGrad | (op, grad) | return (_PruneCSRMatrix(grad_a, a), _PruneCSRMatrix(grad_b, b)) | Gradient for sparse_matrix_sparse_mat_mul op. | Gradient for sparse_matrix_sparse_mat_mul op. | [
"Gradient",
"for",
"sparse_matrix_sparse_mat_mul",
"op",
"."
] | def _SparseMatrixSparseMatMulGrad(op, grad):
"""Gradient for sparse_matrix_sparse_mat_mul op."""
t_a = op.get_attr("transpose_a")
t_b = op.get_attr("transpose_b")
adj_a = op.get_attr("adjoint_a")
adj_b = op.get_attr("adjoint_b")
dtype = op.get_attr("type")
# input to sparse_matrix_sparse_mat_mul is (A, B) with CSR A and B.
# Output is CSR:
# C = opA(A) . opB(B)
# where opA = transpose if transpose_a = True else identity
# and opB = transpose if transpose_b = True else identity
a = op.inputs[0]
b = op.inputs[1]
conj = math_ops.conj
matmul = sparse_csr_matrix_ops.sparse_matrix_sparse_mat_mul
if not t_a and not t_b:
if not adj_a:
if not adj_b:
grad_a = matmul(grad, b, adjoint_b=True, type=dtype)
grad_b = matmul(a, grad, adjoint_a=True, type=dtype)
else:
grad_a = matmul(grad, b, type=dtype)
grad_b = matmul(grad, a, adjoint_a=True, type=dtype)
else:
if not adj_b:
grad_a = matmul(b, grad, adjoint_b=True, type=dtype)
grad_b = matmul(a, grad, type=dtype)
else:
grad_a = matmul(b, grad, adjoint_a=True, adjoint_b=True, type=dtype)
grad_b = matmul(grad, a, adjoint_a=True, adjoint_b=True, type=dtype)
elif not adj_a and not adj_b:
if not t_a and t_b:
grad_a = matmul(grad, conj(b), type=dtype)
grad_b = matmul(grad, conj(a), transpose_a=True, type=dtype)
elif t_a and not t_b:
grad_a = matmul(conj(b), grad, transpose_b=True, type=dtype)
grad_b = matmul(conj(a), grad, type=dtype)
else:
grad_a = matmul(b, grad, adjoint_a=True, transpose_b=True, type=dtype)
grad_b = matmul(grad, a, transpose_a=True, adjoint_b=True, type=dtype)
elif adj_a and t_b:
grad_a = matmul(b, grad, transpose_a=True, adjoint_b=True, type=dtype)
grad_b = matmul(grad, a, transpose_a=True, transpose_b=True, type=dtype)
elif t_a and adj_b:
grad_a = matmul(b, grad, transpose_a=True, transpose_b=True, type=dtype)
grad_b = matmul(grad, a, adjoint_a=True, transpose_b=True, type=dtype)
# TODO(tabakg): There should be a C++ function for sparse-sparse
# multiplication with pre-determined indices, instead of pruning after the
# multiplication.
return (_PruneCSRMatrix(grad_a, a), _PruneCSRMatrix(grad_b, b)) | [
"def",
"_SparseMatrixSparseMatMulGrad",
"(",
"op",
",",
"grad",
")",
":",
"t_a",
"=",
"op",
".",
"get_attr",
"(",
"\"transpose_a\"",
")",
"t_b",
"=",
"op",
".",
"get_attr",
"(",
"\"transpose_b\"",
")",
"adj_a",
"=",
"op",
".",
"get_attr",
"(",
"\"adjoint_a... | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/linalg/sparse/sparse_csr_matrix_grad.py#L300-L352 | |
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Arch/ArchComponent.py | python | Component.processSubShapes | (self,obj,base,placement=None) | return base | Add Additions and Subtractions to a base shape.
If Additions exist, fuse them to the base shape. If no base is
provided, just fuse other additions to the first addition.
If Subtractions exist, cut them from the base shape. Roofs and Windows
are treated uniquely, as they define their own Shape to subtract from
parent shapes using their .getSubVolume() methods.
TODO determine what the purpose of the placement argument is.
Parameters
----------
obj: <App::FeaturePython>
The component object.
base: <Part.Shape>, optional
The base shape to add Additions and Subtractions to.
placement: <Base.Placement>, optional
Prior to adding or subtracting subshapes, the <Base.Placement> of
the subshapes are multiplied by the inverse of this parameter.
Returns
-------
<Part.Shape>
The base shape, with the additions and subtractions performed. | Add Additions and Subtractions to a base shape. | [
"Add",
"Additions",
"and",
"Subtractions",
"to",
"a",
"base",
"shape",
"."
] | def processSubShapes(self,obj,base,placement=None):
"""Add Additions and Subtractions to a base shape.
If Additions exist, fuse them to the base shape. If no base is
provided, just fuse other additions to the first addition.
If Subtractions exist, cut them from the base shape. Roofs and Windows
are treated uniquely, as they define their own Shape to subtract from
parent shapes using their .getSubVolume() methods.
TODO determine what the purpose of the placement argument is.
Parameters
----------
obj: <App::FeaturePython>
The component object.
base: <Part.Shape>, optional
The base shape to add Additions and Subtractions to.
placement: <Base.Placement>, optional
Prior to adding or subtracting subshapes, the <Base.Placement> of
the subshapes are multiplied by the inverse of this parameter.
Returns
-------
<Part.Shape>
The base shape, with the additions and subtractions performed.
"""
import Draft,Part
#print("Processing subshapes of ",obj.Label, " : ",obj.Additions)
if placement:
if self.isIdentity(placement):
placement = None
else:
placement = FreeCAD.Placement(placement)
placement = placement.inverse()
# treat additions
for o in obj.Additions:
if not base:
if hasattr(o,'Shape'):
base = o.Shape
else:
if base.isNull():
if hasattr(o,'Shape'):
base = o.Shape
else:
# special case, both walls with coinciding endpoints
import ArchWall
js = ArchWall.mergeShapes(o,obj)
if js:
add = js.cut(base)
if placement:
add.Placement = add.Placement.multiply(placement)
base = base.fuse(add)
elif hasattr(o,'Shape'):
if o.Shape and not o.Shape.isNull() and o.Shape.Solids:
s = o.Shape.copy()
if placement:
s.Placement = s.Placement.multiply(placement)
if base:
if base.Solids:
try:
base = base.fuse(s)
except Part.OCCError:
print("Arch: unable to fuse object ", obj.Name, " with ", o.Name)
else:
base = s
# treat subtractions
subs = obj.Subtractions
for link in obj.InListRecursive:
if hasattr(link,"Hosts"):
if link.Hosts:
if obj in link.Hosts:
subs.append(link)
elif hasattr(link,"Host") and Draft.getType(link) != "Rebar":
if link.Host == obj:
subs.append(link)
for o in subs:
if base:
if base.isNull():
base = None
if base:
subvolume = None
if (Draft.getType(o.getLinkedObject()) == "Window") or (Draft.isClone(o,"Window",True)):
# windows can be additions or subtractions, treated the same way
subvolume = o.getLinkedObject().Proxy.getSubVolume(o)
elif (Draft.getType(o) == "Roof") or (Draft.isClone(o,"Roof")):
# roofs define their own special subtraction volume
subvolume = o.Proxy.getSubVolume(o)
elif hasattr(o,"Subvolume") and hasattr(o.Subvolume,"Shape"):
# Any other object with a Subvolume property
subvolume = o.Subvolume.Shape.copy()
if hasattr(o,"Placement"):
subvolume.Placement = subvolume.Placement.multiply(o.Placement)
if subvolume:
if base.Solids and subvolume.Solids:
if placement:
subvolume.Placement = subvolume.Placement.multiply(placement)
if len(base.Solids) > 1:
base = Part.makeCompound([sol.cut(subvolume) for sol in base.Solids])
else:
base = base.cut(subvolume)
elif hasattr(o,'Shape'):
# no subvolume, we subtract the whole shape
if o.Shape:
if not o.Shape.isNull():
if o.Shape.Solids and base.Solids:
s = o.Shape.copy()
if placement:
s.Placement = s.Placement.multiply(placement)
try:
if len(base.Solids) > 1:
base = Part.makeCompound([sol.cut(s) for sol in base.Solids])
else:
base = base.cut(s)
except Part.OCCError:
print("Arch: unable to cut object ",o.Name, " from ", obj.Name)
return base | [
"def",
"processSubShapes",
"(",
"self",
",",
"obj",
",",
"base",
",",
"placement",
"=",
"None",
")",
":",
"import",
"Draft",
",",
"Part",
"#print(\"Processing subshapes of \",obj.Label, \" : \",obj.Additions)",
"if",
"placement",
":",
"if",
"self",
".",
"isIdentity"... | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Arch/ArchComponent.py#L681-L807 | |
intel-iot-devkit/how-to-code-samples | b4ea616f36bbfa2e042beb1698f968cfd651d79f | access-control/python/iot_access_control/hardware/dfrobot.py | python | DfrobotBoard.change_background | (self, color) | Change LCD screen background color.
No effect on the dfrobot. | Change LCD screen background color.
No effect on the dfrobot. | [
"Change",
"LCD",
"screen",
"background",
"color",
".",
"No",
"effect",
"on",
"the",
"dfrobot",
"."
] | def change_background(self, color):
"""
Change LCD screen background color.
No effect on the dfrobot.
"""
pass | [
"def",
"change_background",
"(",
"self",
",",
"color",
")",
":",
"pass"
] | https://github.com/intel-iot-devkit/how-to-code-samples/blob/b4ea616f36bbfa2e042beb1698f968cfd651d79f/access-control/python/iot_access_control/hardware/dfrobot.py#L103-L110 | ||
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/ops/tensor_array_ops.py | python | _GraphTensorArray.split | (self, value, lengths, name=None) | See TensorArray. | See TensorArray. | [
"See",
"TensorArray",
"."
] | def split(self, value, lengths, name=None):
"""See TensorArray."""
with ops.name_scope(name, "TensorArraySplit",
[self._handle, value, lengths]):
value = ops.convert_to_tensor(value, dtype=self._dtype, name="value")
with self._maybe_colocate_with(value):
lengths_64 = math_ops.cast(lengths, dtypes.int64)
if not context.executing_eagerly():
clengths = tensor_util.constant_value(lengths_64)
if value.shape.dims is not None and clengths is not None:
if clengths.shape and clengths.max() == clengths.min():
self._check_element_shape(
tensor_shape.TensorShape([clengths[0]
]).concatenate(value.shape[1:]))
flow_out = gen_data_flow_ops.tensor_array_split_v3(
handle=self._handle,
value=value,
lengths=lengths_64,
flow_in=self._flow,
name=name)
return build_ta_with_new_flow(self, flow_out) | [
"def",
"split",
"(",
"self",
",",
"value",
",",
"lengths",
",",
"name",
"=",
"None",
")",
":",
"with",
"ops",
".",
"name_scope",
"(",
"name",
",",
"\"TensorArraySplit\"",
",",
"[",
"self",
".",
"_handle",
",",
"value",
",",
"lengths",
"]",
")",
":",
... | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/tensor_array_ops.py#L354-L374 | ||
rodeofx/OpenWalter | 6116fbe3f04f1146c854afbfbdbe944feaee647e | walter/maya/scripts/AEwalterStandinTemplate.py | python | WalterToolbar.__onTextured | (self, triggered) | Callback when user pressed Bounding Box button. | Callback when user pressed Bounding Box button. | [
"Callback",
"when",
"user",
"pressed",
"Bounding",
"Box",
"button",
"."
] | def __onTextured(self, triggered):
"""Callback when user pressed Bounding Box button."""
cmds.setAttr('%s.overrideTexturing' % self._nodeName, triggered)
cmds.setAttr('%s.overrideEnabled' % self._nodeName, not triggered) | [
"def",
"__onTextured",
"(",
"self",
",",
"triggered",
")",
":",
"cmds",
".",
"setAttr",
"(",
"'%s.overrideTexturing'",
"%",
"self",
".",
"_nodeName",
",",
"triggered",
")",
"cmds",
".",
"setAttr",
"(",
"'%s.overrideEnabled'",
"%",
"self",
".",
"_nodeName",
"... | https://github.com/rodeofx/OpenWalter/blob/6116fbe3f04f1146c854afbfbdbe944feaee647e/walter/maya/scripts/AEwalterStandinTemplate.py#L248-L251 | ||
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/klampt/model/trajectory.py | python | SO3HermiteTrajectory.postTransform | (self, R:Rotation) | Postmultiplies every rotation in here by the se3 element
R. In other words, if R rotates a local frame F to frame F',
this method converts this SO3HermiteTrajectory from describing how F'
rotates to how F rotates. | Postmultiplies every rotation in here by the se3 element
R. In other words, if R rotates a local frame F to frame F',
this method converts this SO3HermiteTrajectory from describing how F'
rotates to how F rotates. | [
"Postmultiplies",
"every",
"rotation",
"in",
"here",
"by",
"the",
"se3",
"element",
"R",
".",
"In",
"other",
"words",
"if",
"R",
"rotates",
"a",
"local",
"frame",
"F",
"to",
"frame",
"F",
"this",
"method",
"converts",
"this",
"SO3HermiteTrajectory",
"from",
... | def postTransform(self, R:Rotation) -> None:
"""Postmultiplies every rotation in here by the se3 element
R. In other words, if R rotates a local frame F to frame F',
this method converts this SO3HermiteTrajectory from describing how F'
rotates to how F rotates."""
for i,m in enumerate(self.milestones):
assert len(m) == 18
mq = m[:9]
mv = m[9:]
self.milestones[i] = so3.mul(mq,R) + so3.mul(mv,R) | [
"def",
"postTransform",
"(",
"self",
",",
"R",
":",
"Rotation",
")",
"->",
"None",
":",
"for",
"i",
",",
"m",
"in",
"enumerate",
"(",
"self",
".",
"milestones",
")",
":",
"assert",
"len",
"(",
"m",
")",
"==",
"18",
"mq",
"=",
"m",
"[",
":",
"9"... | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/model/trajectory.py#L1380-L1389 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/lib/function_base.py | python | iterable | (y) | return True | Check whether or not an object can be iterated over.
Parameters
----------
y : object
Input object.
Returns
-------
b : bool
Return ``True`` if the object has an iterator method or is a
sequence and ``False`` otherwise.
Examples
--------
>>> np.iterable([1, 2, 3])
True
>>> np.iterable(2)
False | Check whether or not an object can be iterated over. | [
"Check",
"whether",
"or",
"not",
"an",
"object",
"can",
"be",
"iterated",
"over",
"."
] | def iterable(y):
"""
Check whether or not an object can be iterated over.
Parameters
----------
y : object
Input object.
Returns
-------
b : bool
Return ``True`` if the object has an iterator method or is a
sequence and ``False`` otherwise.
Examples
--------
>>> np.iterable([1, 2, 3])
True
>>> np.iterable(2)
False
"""
try:
iter(y)
except TypeError:
return False
return True | [
"def",
"iterable",
"(",
"y",
")",
":",
"try",
":",
"iter",
"(",
"y",
")",
"except",
"TypeError",
":",
"return",
"False",
"return",
"True"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/lib/function_base.py#L258-L286 | |
LiquidPlayer/LiquidCore | 9405979363f2353ac9a71ad8ab59685dd7f919c9 | deps/node-10.15.3/tools/jinja2/sandbox.py | python | SandboxedEnvironment.call_binop | (self, context, operator, left, right) | return self.binop_table[operator](left, right) | For intercepted binary operator calls (:meth:`intercepted_binops`)
this function is executed instead of the builtin operator. This can
be used to fine tune the behavior of certain operators.
.. versionadded:: 2.6 | For intercepted binary operator calls (:meth:`intercepted_binops`)
this function is executed instead of the builtin operator. This can
be used to fine tune the behavior of certain operators. | [
"For",
"intercepted",
"binary",
"operator",
"calls",
"(",
":",
"meth",
":",
"intercepted_binops",
")",
"this",
"function",
"is",
"executed",
"instead",
"of",
"the",
"builtin",
"operator",
".",
"This",
"can",
"be",
"used",
"to",
"fine",
"tune",
"the",
"behavi... | def call_binop(self, context, operator, left, right):
"""For intercepted binary operator calls (:meth:`intercepted_binops`)
this function is executed instead of the builtin operator. This can
be used to fine tune the behavior of certain operators.
.. versionadded:: 2.6
"""
return self.binop_table[operator](left, right) | [
"def",
"call_binop",
"(",
"self",
",",
"context",
",",
"operator",
",",
"left",
",",
"right",
")",
":",
"return",
"self",
".",
"binop_table",
"[",
"operator",
"]",
"(",
"left",
",",
"right",
")"
] | https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/tools/jinja2/sandbox.py#L341-L348 | |
facebookincubator/BOLT | 88c70afe9d388ad430cc150cc158641701397f70 | third-party/benchmark/tools/gbench/report.py | python | get_unique_benchmark_names | (json) | return uniqued | While *keeping* the order, give all the unique 'names' used for benchmarks. | While *keeping* the order, give all the unique 'names' used for benchmarks. | [
"While",
"*",
"keeping",
"*",
"the",
"order",
"give",
"all",
"the",
"unique",
"names",
"used",
"for",
"benchmarks",
"."
] | def get_unique_benchmark_names(json):
"""
While *keeping* the order, give all the unique 'names' used for benchmarks.
"""
seen = set()
uniqued = [x['name'] for x in json['benchmarks']
if x['name'] not in seen and
(seen.add(x['name']) or True)]
return uniqued | [
"def",
"get_unique_benchmark_names",
"(",
"json",
")",
":",
"seen",
"=",
"set",
"(",
")",
"uniqued",
"=",
"[",
"x",
"[",
"'name'",
"]",
"for",
"x",
"in",
"json",
"[",
"'benchmarks'",
"]",
"if",
"x",
"[",
"'name'",
"]",
"not",
"in",
"seen",
"and",
"... | https://github.com/facebookincubator/BOLT/blob/88c70afe9d388ad430cc150cc158641701397f70/third-party/benchmark/tools/gbench/report.py#L102-L110 | |
idaholab/moose | 9eeebc65e098b4c30f8205fb41591fd5b61eb6ff | python/chigger/base/ChiggerObject.py | python | ChiggerObject.updateOptions | (self, *args) | return changed | Apply the supplied option objects to this object and the contained ChiggerFilterSourceBase
objects. (override)
Inputs:
see ChiggerResultBase | Apply the supplied option objects to this object and the contained ChiggerFilterSourceBase
objects. (override) | [
"Apply",
"the",
"supplied",
"option",
"objects",
"to",
"this",
"object",
"and",
"the",
"contained",
"ChiggerFilterSourceBase",
"objects",
".",
"(",
"override",
")"
] | def updateOptions(self, *args):
"""
Apply the supplied option objects to this object and the contained ChiggerFilterSourceBase
objects. (override)
Inputs:
see ChiggerResultBase
"""
changed = [self.needsUpdate()]
for sub in args:
changed.append(self._options.update(sub))
changed = any(changed)
self.setNeedsUpdate(changed)
return changed | [
"def",
"updateOptions",
"(",
"self",
",",
"*",
"args",
")",
":",
"changed",
"=",
"[",
"self",
".",
"needsUpdate",
"(",
")",
"]",
"for",
"sub",
"in",
"args",
":",
"changed",
".",
"append",
"(",
"self",
".",
"_options",
".",
"update",
"(",
"sub",
")"... | https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/chigger/base/ChiggerObject.py#L130-L143 | |
NVIDIA/TensorRT | 42805f078052daad1a98bc5965974fcffaad0960 | tools/Polygraphy/polygraphy/util/util.py | python | unpack_args | (args, num) | return args[0:num] | Extracts the specified number of arguments from a tuple, padding with
`None` if the tuple length is insufficient.
Args:
args (Tuple[object]): The tuple of arguments
num (int): The number of elements desired.
Returns:
Tuple[object]: A tuple containing `num` arguments, padded with `None` if `len(args) < num` | Extracts the specified number of arguments from a tuple, padding with
`None` if the tuple length is insufficient. | [
"Extracts",
"the",
"specified",
"number",
"of",
"arguments",
"from",
"a",
"tuple",
"padding",
"with",
"None",
"if",
"the",
"tuple",
"length",
"is",
"insufficient",
"."
] | def unpack_args(args, num):
"""
Extracts the specified number of arguments from a tuple, padding with
`None` if the tuple length is insufficient.
Args:
args (Tuple[object]): The tuple of arguments
num (int): The number of elements desired.
Returns:
Tuple[object]: A tuple containing `num` arguments, padded with `None` if `len(args) < num`
"""
args = args if is_sequence(args) else (args,)
args += (None,) * (num - len(args))
return args[0:num] | [
"def",
"unpack_args",
"(",
"args",
",",
"num",
")",
":",
"args",
"=",
"args",
"if",
"is_sequence",
"(",
"args",
")",
"else",
"(",
"args",
",",
")",
"args",
"+=",
"(",
"None",
",",
")",
"*",
"(",
"num",
"-",
"len",
"(",
"args",
")",
")",
"return... | https://github.com/NVIDIA/TensorRT/blob/42805f078052daad1a98bc5965974fcffaad0960/tools/Polygraphy/polygraphy/util/util.py#L228-L242 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/aui/framemanager.py | python | AuiPaneInfo.__init__ | (self) | Default class constructor. | Default class constructor. | [
"Default",
"class",
"constructor",
"."
] | def __init__(self):
""" Default class constructor. """
self.window = None
self.frame = None
self.state = 0
self.dock_direction = AUI_DOCK_LEFT
self.dock_layer = 0
self.dock_row = 0
self.dock_pos = 0
self.minimize_mode = AUI_MINIMIZE_POS_SMART
self.floating_pos = wx.Point(-1, -1)
self.floating_size = wx.Size(-1, -1)
self.best_size = wx.Size(-1, -1)
self.min_size = wx.Size(-1, -1)
self.max_size = wx.Size(-1, -1)
self.dock_proportion = 0
self.caption = ""
self.buttons = []
self.name = ""
self.icon = wx.NullIcon
self.rect = wx.Rect()
self.notebook_id = -1
self.transparent = 255
self.needsTransparency = False
self.previousDockPos = None
self.previousDockSize = 0
self.snapped = 0
self.minimize_target = None
self.DefaultPane() | [
"def",
"__init__",
"(",
"self",
")",
":",
"self",
".",
"window",
"=",
"None",
"self",
".",
"frame",
"=",
"None",
"self",
".",
"state",
"=",
"0",
"self",
".",
"dock_direction",
"=",
"AUI_DOCK_LEFT",
"self",
".",
"dock_layer",
"=",
"0",
"self",
".",
"d... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/aui/framemanager.py#L524-L554 | ||
CRYTEK/CRYENGINE | 232227c59a220cbbd311576f0fbeba7bb53b2a8c | Editor/Python/windows/Lib/site-packages/setuptools/command/egg_info.py | python | FileList.prune | (self, dir) | return self._remove_files(match.match) | Filter out files from 'dir/'. | Filter out files from 'dir/'. | [
"Filter",
"out",
"files",
"from",
"dir",
"/",
"."
] | def prune(self, dir):
"""Filter out files from 'dir/'."""
match = translate_pattern(os.path.join(dir, '**'))
return self._remove_files(match.match) | [
"def",
"prune",
"(",
"self",
",",
"dir",
")",
":",
"match",
"=",
"translate_pattern",
"(",
"os",
".",
"path",
".",
"join",
"(",
"dir",
",",
"'**'",
")",
")",
"return",
"self",
".",
"_remove_files",
"(",
"match",
".",
"match",
")"
] | https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/setuptools/command/egg_info.py#L449-L452 | |
RegrowthStudios/SoACode-Public | c3ddd69355b534d5e70e2e6d0c489b4e93ab1ffe | utils/git-hooks/cpplint/cpplint.py | python | IsErrorSuppressedByNolint | (category, linenum) | return (linenum in _error_suppressions.get(category, set()) or
linenum in _error_suppressions.get(None, set())) | Returns true if the specified error category is suppressed on this line.
Consults the global error_suppressions map populated by
ParseNolintSuppressions/ResetNolintSuppressions.
Args:
category: str, the category of the error.
linenum: int, the current line number.
Returns:
bool, True iff the error should be suppressed due to a NOLINT comment. | Returns true if the specified error category is suppressed on this line. | [
"Returns",
"true",
"if",
"the",
"specified",
"error",
"category",
"is",
"suppressed",
"on",
"this",
"line",
"."
] | def IsErrorSuppressedByNolint(category, linenum):
"""Returns true if the specified error category is suppressed on this line.
Consults the global error_suppressions map populated by
ParseNolintSuppressions/ResetNolintSuppressions.
Args:
category: str, the category of the error.
linenum: int, the current line number.
Returns:
bool, True iff the error should be suppressed due to a NOLINT comment.
"""
return (linenum in _error_suppressions.get(category, set()) or
linenum in _error_suppressions.get(None, set())) | [
"def",
"IsErrorSuppressedByNolint",
"(",
"category",
",",
"linenum",
")",
":",
"return",
"(",
"linenum",
"in",
"_error_suppressions",
".",
"get",
"(",
"category",
",",
"set",
"(",
")",
")",
"or",
"linenum",
"in",
"_error_suppressions",
".",
"get",
"(",
"None... | https://github.com/RegrowthStudios/SoACode-Public/blob/c3ddd69355b534d5e70e2e6d0c489b4e93ab1ffe/utils/git-hooks/cpplint/cpplint.py#L353-L366 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/AWSPythonSDK/1.5.8/docutils/utils/math/math2html.py | python | EndingList.findending | (self, pos) | return None | Find the ending at the current position | Find the ending at the current position | [
"Find",
"the",
"ending",
"at",
"the",
"current",
"position"
] | def findending(self, pos):
"Find the ending at the current position"
if len(self.endings) == 0:
return None
for index, ending in enumerate(reversed(self.endings)):
if ending.checkin(pos):
return ending
if not ending.optional:
return None
return None | [
"def",
"findending",
"(",
"self",
",",
"pos",
")",
":",
"if",
"len",
"(",
"self",
".",
"endings",
")",
"==",
"0",
":",
"return",
"None",
"for",
"index",
",",
"ending",
"in",
"enumerate",
"(",
"reversed",
"(",
"self",
".",
"endings",
")",
")",
":",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/docutils/utils/math/math2html.py#L1975-L1984 | |
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/python/lib/io/file_io.py | python | FileIO.name | (self) | return self.__name | Returns the file name. | Returns the file name. | [
"Returns",
"the",
"file",
"name",
"."
] | def name(self):
"""Returns the file name."""
return self.__name | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"self",
".",
"__name"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/lib/io/file_io.py#L62-L64 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/richtext.py | python | RichTextCtrl.WriteBitmap | (*args, **kwargs) | return _richtext.RichTextCtrl_WriteBitmap(*args, **kwargs) | WriteBitmap(self, Bitmap bitmap, int bitmapType=BITMAP_TYPE_PNG) -> bool
Write a bitmap at the current insertion point. Supply optional type to
use for internal and file storage of the raw data. | WriteBitmap(self, Bitmap bitmap, int bitmapType=BITMAP_TYPE_PNG) -> bool | [
"WriteBitmap",
"(",
"self",
"Bitmap",
"bitmap",
"int",
"bitmapType",
"=",
"BITMAP_TYPE_PNG",
")",
"-",
">",
"bool"
] | def WriteBitmap(*args, **kwargs):
"""
WriteBitmap(self, Bitmap bitmap, int bitmapType=BITMAP_TYPE_PNG) -> bool
Write a bitmap at the current insertion point. Supply optional type to
use for internal and file storage of the raw data.
"""
return _richtext.RichTextCtrl_WriteBitmap(*args, **kwargs) | [
"def",
"WriteBitmap",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_richtext",
".",
"RichTextCtrl_WriteBitmap",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/richtext.py#L3262-L3269 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/grid.py | python | PyGridTableBase._setCallbackInfo | (*args, **kwargs) | return _grid.PyGridTableBase__setCallbackInfo(*args, **kwargs) | _setCallbackInfo(self, PyObject self, PyObject _class) | _setCallbackInfo(self, PyObject self, PyObject _class) | [
"_setCallbackInfo",
"(",
"self",
"PyObject",
"self",
"PyObject",
"_class",
")"
] | def _setCallbackInfo(*args, **kwargs):
"""_setCallbackInfo(self, PyObject self, PyObject _class)"""
return _grid.PyGridTableBase__setCallbackInfo(*args, **kwargs) | [
"def",
"_setCallbackInfo",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_grid",
".",
"PyGridTableBase__setCallbackInfo",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/grid.py#L937-L939 | |
flexflow/FlexFlow | 581fad8ba8d10a16a3102ee2b406b0319586df24 | python/flexflow/core/flexflow_cffi.py | python | FFModel.tanh | (self, input, name=None) | return Tensor(handle, owner_op_type=OpType.TANH) | Hyperbolic tangent activation function.
:param input: the input Tensor.
:type input: Tensor
:param name: the name of the layer. Default is None.
:type name: string
:returns: Tensor -- the output tensor. | Hyperbolic tangent activation function.
:param input: the input Tensor.
:type input: Tensor
:param name: the name of the layer. Default is None.
:type name: string | [
"Hyperbolic",
"tangent",
"activation",
"function",
".",
":",
"param",
"input",
":",
"the",
"input",
"Tensor",
".",
":",
"type",
"input",
":",
"Tensor",
":",
"param",
"name",
":",
"the",
"name",
"of",
"the",
"layer",
".",
"Default",
"is",
"None",
".",
"... | def tanh(self, input, name=None):
"""Hyperbolic tangent activation function.
:param input: the input Tensor.
:type input: Tensor
:param name: the name of the layer. Default is None.
:type name: string
:returns: Tensor -- the output tensor.
"""
c_name = get_c_name(name)
handle = ffc.flexflow_model_add_tanh(self.handle, input.handle, c_name)
self.add_layer(OpType.TANH, name)
return Tensor(handle, owner_op_type=OpType.TANH) | [
"def",
"tanh",
"(",
"self",
",",
"input",
",",
"name",
"=",
"None",
")",
":",
"c_name",
"=",
"get_c_name",
"(",
"name",
")",
"handle",
"=",
"ffc",
".",
"flexflow_model_add_tanh",
"(",
"self",
".",
"handle",
",",
"input",
".",
"handle",
",",
"c_name",
... | https://github.com/flexflow/FlexFlow/blob/581fad8ba8d10a16a3102ee2b406b0319586df24/python/flexflow/core/flexflow_cffi.py#L1573-L1587 | |
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | tools/telemetry/third_party/pyserial/serial/serialposix.py | python | PosixSerial.setXON | (self, level=True) | \
Manually control flow - when software flow control is enabled.
This will send XON (true) and XOFF (false) to the other device.
WARNING: this function is not portable to different platforms! | \
Manually control flow - when software flow control is enabled.
This will send XON (true) and XOFF (false) to the other device.
WARNING: this function is not portable to different platforms! | [
"\\",
"Manually",
"control",
"flow",
"-",
"when",
"software",
"flow",
"control",
"is",
"enabled",
".",
"This",
"will",
"send",
"XON",
"(",
"true",
")",
"and",
"XOFF",
"(",
"false",
")",
"to",
"the",
"other",
"device",
".",
"WARNING",
":",
"this",
"func... | def setXON(self, level=True):
"""\
Manually control flow - when software flow control is enabled.
This will send XON (true) and XOFF (false) to the other device.
WARNING: this function is not portable to different platforms!
"""
if not self.hComPort: raise portNotOpenError
if enable:
termios.tcflow(self.fd, TERMIOS.TCION)
else:
termios.tcflow(self.fd, TERMIOS.TCIOFF) | [
"def",
"setXON",
"(",
"self",
",",
"level",
"=",
"True",
")",
":",
"if",
"not",
"self",
".",
"hComPort",
":",
"raise",
"portNotOpenError",
"if",
"enable",
":",
"termios",
".",
"tcflow",
"(",
"self",
".",
"fd",
",",
"TERMIOS",
".",
"TCION",
")",
"else... | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/telemetry/third_party/pyserial/serial/serialposix.py#L616-L626 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/lite/experimental/micro/examples/micro_vision/utils/raw_to_bitmap.py | python | reshape_bitmaps | (frame_list, width, height, channels) | return bitmap_list | Reshape flat integer arrays.
Args:
frame_list: list of 1-D arrays to represent raw image data
width: image width in pixels
height: image height in pixels
channels: color channel count
Returns:
list of numpy arrays to represent bitmap images | Reshape flat integer arrays. | [
"Reshape",
"flat",
"integer",
"arrays",
"."
] | def reshape_bitmaps(frame_list, width, height, channels):
"""Reshape flat integer arrays.
Args:
frame_list: list of 1-D arrays to represent raw image data
width: image width in pixels
height: image height in pixels
channels: color channel count
Returns:
list of numpy arrays to represent bitmap images
"""
bitmap_list = []
for frame in frame_list:
shape = (height, width, channels) if channels > 1 else (height, width)
bitmap = np.reshape(frame, shape)
bitmap = np.flip(bitmap, 0)
bitmap_list.append(bitmap)
return bitmap_list | [
"def",
"reshape_bitmaps",
"(",
"frame_list",
",",
"width",
",",
"height",
",",
"channels",
")",
":",
"bitmap_list",
"=",
"[",
"]",
"for",
"frame",
"in",
"frame_list",
":",
"shape",
"=",
"(",
"height",
",",
"width",
",",
"channels",
")",
"if",
"channels",... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/lite/experimental/micro/examples/micro_vision/utils/raw_to_bitmap.py#L86-L105 | |
fatih/subvim | 241b6d170597857105da219c9b7d36059e9f11fb | vim/base/YouCompleteMe/third_party/jedi/jedi/api_classes.py | python | BaseDefinition.doc | (self) | r"""
Return a document string for this completion object.
Example:
>>> from jedi import Script
>>> source = '''\
... def f(a, b=1):
... "Document for function f."
... '''
>>> script = Script(source, 1, len('def f'), 'example.py')
>>> d = script.goto_definitions()[0]
>>> print(d.doc)
f(a, b = 1)
<BLANKLINE>
Document for function f.
Notice that useful extra information is added to the actual
docstring. For function, it is call signature. If you need
actual docstring, use :attr:`raw_doc` instead.
>>> print(d.raw_doc)
Document for function f. | r"""
Return a document string for this completion object. | [
"r",
"Return",
"a",
"document",
"string",
"for",
"this",
"completion",
"object",
"."
] | def doc(self):
r"""
Return a document string for this completion object.
Example:
>>> from jedi import Script
>>> source = '''\
... def f(a, b=1):
... "Document for function f."
... '''
>>> script = Script(source, 1, len('def f'), 'example.py')
>>> d = script.goto_definitions()[0]
>>> print(d.doc)
f(a, b = 1)
<BLANKLINE>
Document for function f.
Notice that useful extra information is added to the actual
docstring. For function, it is call signature. If you need
actual docstring, use :attr:`raw_doc` instead.
>>> print(d.raw_doc)
Document for function f.
"""
try:
return self._definition.doc
except AttributeError:
return self.raw_doc | [
"def",
"doc",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"_definition",
".",
"doc",
"except",
"AttributeError",
":",
"return",
"self",
".",
"raw_doc"
] | https://github.com/fatih/subvim/blob/241b6d170597857105da219c9b7d36059e9f11fb/vim/base/YouCompleteMe/third_party/jedi/jedi/api_classes.py#L217-L246 | ||
ucbrise/confluo | 578883a4f7fbbb4aea78c342d366f5122ef598f7 | pyclient/confluo/rpc/schema.py | python | Column.apply | (self, data) | return Field(self.idx_, self.data_type_, data[self.offset_: self.offset_ + self.data_type_.size_]) | Adds data to the column.
Args:
data: The data to add.
Returns:
A field containing the data. | Adds data to the column. | [
"Adds",
"data",
"to",
"the",
"column",
"."
] | def apply(self, data):
""" Adds data to the column.
Args:
data: The data to add.
Returns:
A field containing the data.
"""
return Field(self.idx_, self.data_type_, data[self.offset_: self.offset_ + self.data_type_.size_]) | [
"def",
"apply",
"(",
"self",
",",
"data",
")",
":",
"return",
"Field",
"(",
"self",
".",
"idx_",
",",
"self",
".",
"data_type_",
",",
"data",
"[",
"self",
".",
"offset_",
":",
"self",
".",
"offset_",
"+",
"self",
".",
"data_type_",
".",
"size_",
"]... | https://github.com/ucbrise/confluo/blob/578883a4f7fbbb4aea78c342d366f5122ef598f7/pyclient/confluo/rpc/schema.py#L118-L127 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/nntplib.py | python | _NNTPBase.descriptions | (self, group_pattern) | return self._getdescriptions(group_pattern, True) | Get descriptions for a range of groups. | Get descriptions for a range of groups. | [
"Get",
"descriptions",
"for",
"a",
"range",
"of",
"groups",
"."
] | def descriptions(self, group_pattern):
"""Get descriptions for a range of groups."""
return self._getdescriptions(group_pattern, True) | [
"def",
"descriptions",
"(",
"self",
",",
"group_pattern",
")",
":",
"return",
"self",
".",
"_getdescriptions",
"(",
"group_pattern",
",",
"True",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/nntplib.py#L647-L649 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/extern/aui/aui_utilities.py | python | LightContrastColour | (c) | return StepColour(c, amount) | Creates a new, lighter colour based on the input colour `c`.
:param Colour `c`: the input colour to analyze. | Creates a new, lighter colour based on the input colour `c`. | [
"Creates",
"a",
"new",
"lighter",
"colour",
"based",
"on",
"the",
"input",
"colour",
"c",
"."
] | def LightContrastColour(c):
"""
Creates a new, lighter colour based on the input colour `c`.
:param Colour `c`: the input colour to analyze.
"""
amount = 120
# if the colour is especially dark, then
# make the contrast even lighter
if c.Red() < 128 and c.Green() < 128 and c.Blue() < 128:
amount = 160
return StepColour(c, amount) | [
"def",
"LightContrastColour",
"(",
"c",
")",
":",
"amount",
"=",
"120",
"# if the colour is especially dark, then",
"# make the contrast even lighter",
"if",
"c",
".",
"Red",
"(",
")",
"<",
"128",
"and",
"c",
".",
"Green",
"(",
")",
"<",
"128",
"and",
"c",
"... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/extern/aui/aui_utilities.py#L79-L93 | |
apache/incubator-mxnet | f03fb23f1d103fec9541b5ae59ee06b1734a51d9 | python/mxnet/_numpy_op_doc.py | python | _np_diagflat | (array, k=0) | Create a two-dimensional array with the flattened input as a diagonal.
Parameters
----------
arr : ndarray
Input data, which is flattened and set as the `k`-th
diagonal of the output.
k : int, optional
Diagonal to set; 0, the default, corresponds to the "main" diagonal,
a positive (negative) `k` giving the number of the diagonal above
(below) the main.
Returns
-------
out : ndarray
The 2-D output array.
See Also
--------
diag : MATLAB work-alike for 1-D and 2-D arrays.
diagonal : Return specified diagonals.
trace : Sum along diagonals.
Examples
--------
>>> np.diagflat([[1,2], [3,4]])
array([[1, 0, 0, 0],
[0, 2, 0, 0],
[0, 0, 3, 0],
[0, 0, 0, 4]])
>>> np.diagflat([1,2], 1)
array([[0, 1, 0],
[0, 0, 2],
[0, 0, 0]]) | Create a two-dimensional array with the flattened input as a diagonal.
Parameters
----------
arr : ndarray
Input data, which is flattened and set as the `k`-th
diagonal of the output.
k : int, optional
Diagonal to set; 0, the default, corresponds to the "main" diagonal,
a positive (negative) `k` giving the number of the diagonal above
(below) the main.
Returns
-------
out : ndarray
The 2-D output array.
See Also
--------
diag : MATLAB work-alike for 1-D and 2-D arrays.
diagonal : Return specified diagonals.
trace : Sum along diagonals.
Examples
--------
>>> np.diagflat([[1,2], [3,4]])
array([[1, 0, 0, 0],
[0, 2, 0, 0],
[0, 0, 3, 0],
[0, 0, 0, 4]])
>>> np.diagflat([1,2], 1)
array([[0, 1, 0],
[0, 0, 2],
[0, 0, 0]]) | [
"Create",
"a",
"two",
"-",
"dimensional",
"array",
"with",
"the",
"flattened",
"input",
"as",
"a",
"diagonal",
".",
"Parameters",
"----------",
"arr",
":",
"ndarray",
"Input",
"data",
"which",
"is",
"flattened",
"and",
"set",
"as",
"the",
"k",
"-",
"th",
... | def _np_diagflat(array, k=0):
"""
Create a two-dimensional array with the flattened input as a diagonal.
Parameters
----------
arr : ndarray
Input data, which is flattened and set as the `k`-th
diagonal of the output.
k : int, optional
Diagonal to set; 0, the default, corresponds to the "main" diagonal,
a positive (negative) `k` giving the number of the diagonal above
(below) the main.
Returns
-------
out : ndarray
The 2-D output array.
See Also
--------
diag : MATLAB work-alike for 1-D and 2-D arrays.
diagonal : Return specified diagonals.
trace : Sum along diagonals.
Examples
--------
>>> np.diagflat([[1,2], [3,4]])
array([[1, 0, 0, 0],
[0, 2, 0, 0],
[0, 0, 3, 0],
[0, 0, 0, 4]])
>>> np.diagflat([1,2], 1)
array([[0, 1, 0],
[0, 0, 2],
[0, 0, 0]])
"""
pass | [
"def",
"_np_diagflat",
"(",
"array",
",",
"k",
"=",
"0",
")",
":",
"pass"
] | https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/_numpy_op_doc.py#L861-L894 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/ultimatelistctrl.py | python | UltimateListMainWindow.EditLabel | (self, item) | return self._textctrl | Starts editing an item label.
:param `item`: an instance of :class:`UltimateListItem`. | Starts editing an item label. | [
"Starts",
"editing",
"an",
"item",
"label",
"."
] | def EditLabel(self, item):
"""
Starts editing an item label.
:param `item`: an instance of :class:`UltimateListItem`.
"""
if item < 0 or item >= self.GetItemCount():
raise Exception("wrong index in UltimateListCtrl.EditLabel()")
le = UltimateListEvent(wxEVT_COMMAND_LIST_BEGIN_LABEL_EDIT, self.GetParent().GetId())
le.SetEventObject(self.GetParent())
le.m_itemIndex = item
data = self.GetLine(item)
le.m_item = data.GetItem(0, le.m_item)
self._textctrl = UltimateListTextCtrl(self, item)
if self.GetParent().GetEventHandler().ProcessEvent(le) and not le.IsAllowed():
# vetoed by user code
return
# We have to call this here because the label in question might just have
# been added and no screen update taken place.
if self._dirty:
wx.SafeYield()
# Pending events dispatched by wx.SafeYield might have changed the item
# count
if item >= self.GetItemCount():
return None
# modified
self._textctrl.SetFocus()
return self._textctrl | [
"def",
"EditLabel",
"(",
"self",
",",
"item",
")",
":",
"if",
"item",
"<",
"0",
"or",
"item",
">=",
"self",
".",
"GetItemCount",
"(",
")",
":",
"raise",
"Exception",
"(",
"\"wrong index in UltimateListCtrl.EditLabel()\"",
")",
"le",
"=",
"UltimateListEvent",
... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/ultimatelistctrl.py#L7356-L7390 | |
stan-dev/math | 5fd79f89933269a4ca4d8dd1fde2a36d53d4768c | lib/boost_1.75.0/status/boost_check_library.py | python | check_library.get_library_meta | (self) | return None | Fetches the meta data for the current library. The data could be in
the superlib meta data file. If we can't find the data None is returned. | Fetches the meta data for the current library. The data could be in
the superlib meta data file. If we can't find the data None is returned. | [
"Fetches",
"the",
"meta",
"data",
"for",
"the",
"current",
"library",
".",
"The",
"data",
"could",
"be",
"in",
"the",
"superlib",
"meta",
"data",
"file",
".",
"If",
"we",
"can",
"t",
"find",
"the",
"data",
"None",
"is",
"returned",
"."
] | def get_library_meta(self):
'''
Fetches the meta data for the current library. The data could be in
the superlib meta data file. If we can't find the data None is returned.
'''
parent_dir = os.path.dirname(self.library_dir)
if self.test_file_exists(os.path.join(self.library_dir,'meta'),['libraries.json']):
with open(os.path.join(self.library_dir,'meta','libraries.json'),'r') as f:
meta_data = json.load(f)
if isinstance(meta_data,list):
for lib in meta_data:
if lib['key'] == self.library_key:
return lib
elif 'key' in meta_data and meta_data['key'] == self.library_key:
return meta_data
if not self.test_dir_exists(os.path.join(self.library_dir,'meta')) \
and self.test_file_exists(os.path.join(parent_dir,'meta'),['libraries.json']):
with open(os.path.join(parent_dir,'meta','libraries.json'),'r') as f:
libraries_json = json.load(f)
if isinstance(libraries_json,list):
for lib in libraries_json:
if lib['key'] == self.library_key:
return lib
return None | [
"def",
"get_library_meta",
"(",
"self",
")",
":",
"parent_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"self",
".",
"library_dir",
")",
"if",
"self",
".",
"test_file_exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"library_dir",
"... | https://github.com/stan-dev/math/blob/5fd79f89933269a4ca4d8dd1fde2a36d53d4768c/lib/boost_1.75.0/status/boost_check_library.py#L182-L205 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/contrib/timeseries/python/timeseries/ar_model.py | python | ARModel.prediction_ops | (self, times, values) | return {"activations": activations,
"mean": predicted_mean,
"covariance": predicted_covariance} | Compute model predictions given input data.
Args:
times: A [batch size, self.window_size] integer Tensor, the first
self.input_window_size times in each part of the batch indicating
input features, and the last self.output_window_size times indicating
prediction times.
values: A [batch size, self.input_window_size, self.num_features] Tensor
with input features.
Returns:
Tuple (predicted_mean, predicted_covariance), where each element is a
Tensor with shape [batch size, self.output_window_size,
self.num_features]. | Compute model predictions given input data. | [
"Compute",
"model",
"predictions",
"given",
"input",
"data",
"."
] | def prediction_ops(self, times, values):
"""Compute model predictions given input data.
Args:
times: A [batch size, self.window_size] integer Tensor, the first
self.input_window_size times in each part of the batch indicating
input features, and the last self.output_window_size times indicating
prediction times.
values: A [batch size, self.input_window_size, self.num_features] Tensor
with input features.
Returns:
Tuple (predicted_mean, predicted_covariance), where each element is a
Tensor with shape [batch size, self.output_window_size,
self.num_features].
"""
times.get_shape().assert_is_compatible_with([None, self.window_size])
activations = []
if self.input_window_size:
values.get_shape().assert_is_compatible_with(
[None, self.input_window_size, self.num_features])
# Create input features.
if self._periods:
_, time_features = self._compute_time_features(times)
activation_size = self.window_size * self._buckets * len(self._periods)
activation = array_ops.reshape(time_features, [-1, activation_size])
else:
activation_size = 0
activation = None
if self.input_window_size:
inp = array_ops.slice(values, [0, 0, 0], [-1, self.input_window_size, -1])
inp_size = self.input_window_size * self.num_features
inp = array_ops.reshape(inp, [-1, inp_size])
if activation is not None:
activation = array_ops.concat([inp, activation], 1)
else:
activation = inp
activation_size += inp_size
assert activation_size
activations.append((activation, activation_size))
# Create hidden layers.
activations += self._create_hidden_stack(activation, activation_size)
# Create mean and convariance ops.
predicted_mean = self._predicted_mean_op(activations)
predicted_covariance = self._predicted_covariance_op(activations,
self.num_features)
return {"activations": activations,
"mean": predicted_mean,
"covariance": predicted_covariance} | [
"def",
"prediction_ops",
"(",
"self",
",",
"times",
",",
"values",
")",
":",
"times",
".",
"get_shape",
"(",
")",
".",
"assert_is_compatible_with",
"(",
"[",
"None",
",",
"self",
".",
"window_size",
"]",
")",
"activations",
"=",
"[",
"]",
"if",
"self",
... | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/timeseries/python/timeseries/ar_model.py#L166-L214 | |
openmm/openmm | cb293447c4fc8b03976dfe11399f107bab70f3d9 | wrappers/python/openmm/app/topology.py | python | Topology.getNumResidues | (self) | return self._numResidues | Return the number of residues in the Topology. | Return the number of residues in the Topology. | [
"Return",
"the",
"number",
"of",
"residues",
"in",
"the",
"Topology",
"."
] | def getNumResidues(self):
"""Return the number of residues in the Topology.
"""
return self._numResidues | [
"def",
"getNumResidues",
"(",
"self",
")",
":",
"return",
"self",
".",
"_numResidues"
] | https://github.com/openmm/openmm/blob/cb293447c4fc8b03976dfe11399f107bab70f3d9/wrappers/python/openmm/app/topology.py#L105-L108 | |
tensorflow/io | 92b44e180674a8af0e12e405530f7343e3e693e4 | tensorflow_io/python/experimental/avro_record_dataset_ops.py | python | _AvroRecordDataset.__optional_param_to_tensor | (
argument_name,
argument_value,
argument_default=0,
argument_dtype=tf.dtypes.int64,
) | return tf.constant(argument_default, dtype=argument_dtype, name=argument_name) | optional_param_to_tensor | optional_param_to_tensor | [
"optional_param_to_tensor"
] | def __optional_param_to_tensor(
argument_name,
argument_value,
argument_default=0,
argument_dtype=tf.dtypes.int64,
):
"""optional_param_to_tensor"""
if argument_value is not None:
return tf.convert_to_tensor(
argument_value, dtype=argument_dtype, name=argument_name
)
return tf.constant(argument_default, dtype=argument_dtype, name=argument_name) | [
"def",
"__optional_param_to_tensor",
"(",
"argument_name",
",",
"argument_value",
",",
"argument_default",
"=",
"0",
",",
"argument_dtype",
"=",
"tf",
".",
"dtypes",
".",
"int64",
",",
")",
":",
"if",
"argument_value",
"is",
"not",
"None",
":",
"return",
"tf",... | https://github.com/tensorflow/io/blob/92b44e180674a8af0e12e405530f7343e3e693e4/tensorflow_io/python/experimental/avro_record_dataset_ops.py#L165-L176 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/protobuf/py3/google/protobuf/internal/type_checkers.py | python | GetTypeChecker | (field) | return _VALUE_CHECKERS[field.cpp_type] | Returns a type checker for a message field of the specified types.
Args:
field: FieldDescriptor object for this field.
Returns:
An instance of TypeChecker which can be used to verify the types
of values assigned to a field of the specified type. | Returns a type checker for a message field of the specified types. | [
"Returns",
"a",
"type",
"checker",
"for",
"a",
"message",
"field",
"of",
"the",
"specified",
"types",
"."
] | def GetTypeChecker(field):
"""Returns a type checker for a message field of the specified types.
Args:
field: FieldDescriptor object for this field.
Returns:
An instance of TypeChecker which can be used to verify the types
of values assigned to a field of the specified type.
"""
if (field.cpp_type == _FieldDescriptor.CPPTYPE_STRING and
field.type == _FieldDescriptor.TYPE_STRING):
return UnicodeValueChecker()
if field.cpp_type == _FieldDescriptor.CPPTYPE_ENUM:
if SupportsOpenEnums(field):
# When open enums are supported, any int32 can be assigned.
return _VALUE_CHECKERS[_FieldDescriptor.CPPTYPE_INT32]
else:
return EnumValueChecker(field.enum_type)
return _VALUE_CHECKERS[field.cpp_type] | [
"def",
"GetTypeChecker",
"(",
"field",
")",
":",
"if",
"(",
"field",
".",
"cpp_type",
"==",
"_FieldDescriptor",
".",
"CPPTYPE_STRING",
"and",
"field",
".",
"type",
"==",
"_FieldDescriptor",
".",
"TYPE_STRING",
")",
":",
"return",
"UnicodeValueChecker",
"(",
")... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/protobuf/py3/google/protobuf/internal/type_checkers.py#L93-L112 | |
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/python2_version/klampt/math/optimize.py | python | OptimizationProblemBuilder.satisfiesInequalities | (self,margin=0) | return all(r <= -margin for r in res) | Returns True if the for currently bound state x, every entry of the (hard) inequality residuals is
<= -margin (default 0). | Returns True if the for currently bound state x, every entry of the (hard) inequality residuals is
<= -margin (default 0). | [
"Returns",
"True",
"if",
"the",
"for",
"currently",
"bound",
"state",
"x",
"every",
"entry",
"of",
"the",
"(",
"hard",
")",
"inequality",
"residuals",
"is",
"<",
"=",
"-",
"margin",
"(",
"default",
"0",
")",
"."
] | def satisfiesInequalities(self,margin=0):
"""Returns True if the for currently bound state x, every entry of the (hard) inequality residuals is
<= -margin (default 0)."""
for v in self.optimizationVariables:
assert v.value is not None,"All optimization variables must be bound"
res = self.inequalityResidual()
if len(res) == 0: return True
return all(r <= -margin for r in res) | [
"def",
"satisfiesInequalities",
"(",
"self",
",",
"margin",
"=",
"0",
")",
":",
"for",
"v",
"in",
"self",
".",
"optimizationVariables",
":",
"assert",
"v",
".",
"value",
"is",
"not",
"None",
",",
"\"All optimization variables must be bound\"",
"res",
"=",
"sel... | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/math/optimize.py#L969-L976 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/xml/sax/handler.py | python | ContentHandler.endElementNS | (self, name, qname) | Signals the end of an element in namespace mode.
The name parameter contains the name of the element type, just
as with the startElementNS event. | Signals the end of an element in namespace mode. | [
"Signals",
"the",
"end",
"of",
"an",
"element",
"in",
"namespace",
"mode",
"."
] | def endElementNS(self, name, qname):
"""Signals the end of an element in namespace mode.
The name parameter contains the name of the element type, just
as with the startElementNS event.""" | [
"def",
"endElementNS",
"(",
"self",
",",
"name",
",",
"qname",
")",
":"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/xml/sax/handler.py#L152-L156 | ||
gv22ga/dlib-face-recognition-android | 42d6305cbd85833f2b85bb79b70ab9ab004153c9 | tools/lint/cpplint.py | python | FindEndOfExpressionInLine | (line, startpos, stack) | return (-1, stack) | Find the position just after the end of current parenthesized expression.
Args:
line: a CleansedLines line.
startpos: start searching at this position.
stack: nesting stack at startpos.
Returns:
On finding matching end: (index just after matching end, None)
On finding an unclosed expression: (-1, None)
Otherwise: (-1, new stack at end of this line) | Find the position just after the end of current parenthesized expression.
Args:
line: a CleansedLines line.
startpos: start searching at this position.
stack: nesting stack at startpos.
Returns:
On finding matching end: (index just after matching end, None)
On finding an unclosed expression: (-1, None)
Otherwise: (-1, new stack at end of this line) | [
"Find",
"the",
"position",
"just",
"after",
"the",
"end",
"of",
"current",
"parenthesized",
"expression",
".",
"Args",
":",
"line",
":",
"a",
"CleansedLines",
"line",
".",
"startpos",
":",
"start",
"searching",
"at",
"this",
"position",
".",
"stack",
":",
... | def FindEndOfExpressionInLine(line, startpos, stack):
"""Find the position just after the end of current parenthesized expression.
Args:
line: a CleansedLines line.
startpos: start searching at this position.
stack: nesting stack at startpos.
Returns:
On finding matching end: (index just after matching end, None)
On finding an unclosed expression: (-1, None)
Otherwise: (-1, new stack at end of this line)
"""
for i in xrange(startpos, len(line)):
char = line[i]
if char in '([{':
# Found start of parenthesized expression, push to expression stack
stack.append(char)
elif char == '<':
# Found potential start of template argument list
if i > 0 and line[i - 1] == '<':
# Left shift operator
if stack and stack[-1] == '<':
stack.pop()
if not stack:
return (-1, None)
elif i > 0 and Search(r'\boperator\s*$', line[0:i]):
# operator<, don't add to stack
continue
else:
# Tentative start of template argument list
stack.append('<')
elif char in ')]}':
# Found end of parenthesized expression.
#
# If we are currently expecting a matching '>', the pending '<'
# must have been an operator. Remove them from expression stack.
while stack and stack[-1] == '<':
stack.pop()
if not stack:
return (-1, None)
if ((stack[-1] == '(' and char == ')') or
(stack[-1] == '[' and char == ']') or
(stack[-1] == '{' and char == '}')):
stack.pop()
if not stack:
return (i + 1, None)
else:
# Mismatched parentheses
return (-1, None)
elif char == '>':
# Found potential end of template argument list.
# Ignore "->" and operator functions
if (i > 0 and
(line[i - 1] == '-' or Search(r'\boperator\s*$', line[0:i - 1]))):
continue
# Pop the stack if there is a matching '<'. Otherwise, ignore
# this '>' since it must be an operator.
if stack:
if stack[-1] == '<':
stack.pop()
if not stack:
return (i + 1, None)
elif char == ';':
# Found something that look like end of statements. If we are currently
# expecting a '>', the matching '<' must have been an operator, since
# template argument list should not contain statements.
while stack and stack[-1] == '<':
stack.pop()
if not stack:
return (-1, None)
# Did not find end of expression or unbalanced parentheses on this line
return (-1, stack) | [
"def",
"FindEndOfExpressionInLine",
"(",
"line",
",",
"startpos",
",",
"stack",
")",
":",
"for",
"i",
"in",
"xrange",
"(",
"startpos",
",",
"len",
"(",
"line",
")",
")",
":",
"char",
"=",
"line",
"[",
"i",
"]",
"if",
"char",
"in",
"'([{'",
":",
"# ... | https://github.com/gv22ga/dlib-face-recognition-android/blob/42d6305cbd85833f2b85bb79b70ab9ab004153c9/tools/lint/cpplint.py#L1408-L1481 | |
mysql/mysql-workbench | 2f35f9034f015cbcd22139a60e1baa2e3e8e795c | modules/db.mssql/db_mssql_grt.py | python | reverseEngineerView | (connection, schema, view_name) | return view | Reverse engineers a view for the given schema.
Parameters:
===========
connection: an object of the class :class:`db_mgmt_Connection` storing the parameters
for the connection.
schema: a schema object (an instance of :class:`grt.classes.db_mssql_Schema`). This
object must have its ``owner`` and ``name`` attributes properly set.
view_name: the name of the view to reverse engineer.
Return value:
=============
view: an object of the class :class:`grt.classes.db_mssql_View` with the retrieved information. | Reverse engineers a view for the given schema. | [
"Reverse",
"engineers",
"a",
"view",
"for",
"the",
"given",
"schema",
"."
] | def reverseEngineerView(connection, schema, view_name):
"""Reverse engineers a view for the given schema.
Parameters:
===========
connection: an object of the class :class:`db_mgmt_Connection` storing the parameters
for the connection.
schema: a schema object (an instance of :class:`grt.classes.db_mssql_Schema`). This
object must have its ``owner`` and ``name`` attributes properly set.
view_name: the name of the view to reverse engineer.
Return value:
=============
view: an object of the class :class:`grt.classes.db_mssql_View` with the retrieved information.
"""
# The queries are taken from http://msdn.microsoft.com/en-us/library/ms345522.aspx#_FAQ35
query = 'USE %s' % quoteIdentifier(schema.owner.name)# catalog
execute_query(connection, query)
query_post_90 = """SELECT definition
FROM sys.sql_modules
WHERE object_id = OBJECT_ID('%s.%s')
"""
query_pre_90 = """SELECT VIEW_DEFINITION AS definition
FROM INFORMATION_SCHEMA.VIEWS
WHERE TABLE_SCHEMA='%s' AND TABLE_NAME='%s'"""
serverVersion = connected_server_version(connection)
query = query_pre_90 if serverVersion.majorNumber < 9 else query_post_90
query = query % (schema.name, view_name)
resultset = execute_query(connection, query )
if resultset:
view = grt.classes.db_mssql_View()
view.name = view_name or ""
view.owner = schema
view.sqlDefinition = resultset[0][0]
return view | [
"def",
"reverseEngineerView",
"(",
"connection",
",",
"schema",
",",
"view_name",
")",
":",
"# The queries are taken from http://msdn.microsoft.com/en-us/library/ms345522.aspx#_FAQ35",
"query",
"=",
"'USE %s'",
"%",
"quoteIdentifier",
"(",
"schema",
".",
"owner",
".",
"name... | https://github.com/mysql/mysql-workbench/blob/2f35f9034f015cbcd22139a60e1baa2e3e8e795c/modules/db.mssql/db_mssql_grt.py#L993-L1031 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | tools/coverity/coverity.py | python | _ReleaseLock | (lock_file, lock_filename) | Removes the lockfile. Function-ized so we can bail from anywhere | Removes the lockfile. Function-ized so we can bail from anywhere | [
"Removes",
"the",
"lockfile",
".",
"Function",
"-",
"ized",
"so",
"we",
"can",
"bail",
"from",
"anywhere"
] | def _ReleaseLock(lock_file, lock_filename):
"""Removes the lockfile. Function-ized so we can bail from anywhere"""
os.close(lock_file)
os.remove(lock_filename) | [
"def",
"_ReleaseLock",
"(",
"lock_file",
",",
"lock_filename",
")",
":",
"os",
".",
"close",
"(",
"lock_file",
")",
"os",
".",
"remove",
"(",
"lock_filename",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/coverity/coverity.py#L99-L102 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/pydoc.py | python | TextDoc.docclass | (self, object, name=None, mod=None, *ignored) | return title + '\n' + self.indent(contents.rstrip(), ' | ') + '\n' | Produce text documentation for a given class object. | Produce text documentation for a given class object. | [
"Produce",
"text",
"documentation",
"for",
"a",
"given",
"class",
"object",
"."
] | def docclass(self, object, name=None, mod=None, *ignored):
"""Produce text documentation for a given class object."""
realname = object.__name__
name = name or realname
bases = object.__bases__
def makename(c, m=object.__module__):
return classname(c, m)
if name == realname:
title = 'class ' + self.bold(realname)
else:
title = self.bold(name) + ' = class ' + realname
if bases:
parents = map(makename, bases)
title = title + '(%s)' % ', '.join(parents)
contents = []
push = contents.append
try:
signature = inspect.signature(object)
except (ValueError, TypeError):
signature = None
if signature:
argspec = str(signature)
if argspec and argspec != '()':
push(name + argspec + '\n')
doc = getdoc(object)
if doc:
push(doc + '\n')
# List the mro, if non-trivial.
mro = deque(inspect.getmro(object))
if len(mro) > 2:
push("Method resolution order:")
for base in mro:
push(' ' + makename(base))
push('')
# List the built-in subclasses, if any:
subclasses = sorted(
(str(cls.__name__) for cls in type.__subclasses__(object)
if not cls.__name__.startswith("_") and cls.__module__ == "builtins"),
key=str.lower
)
no_of_subclasses = len(subclasses)
MAX_SUBCLASSES_TO_DISPLAY = 4
if subclasses:
push("Built-in subclasses:")
for subclassname in subclasses[:MAX_SUBCLASSES_TO_DISPLAY]:
push(' ' + subclassname)
if no_of_subclasses > MAX_SUBCLASSES_TO_DISPLAY:
push(' ... and ' +
str(no_of_subclasses - MAX_SUBCLASSES_TO_DISPLAY) +
' other subclasses')
push('')
# Cute little class to pump out a horizontal rule between sections.
class HorizontalRule:
def __init__(self):
self.needone = 0
def maybe(self):
if self.needone:
push('-' * 70)
self.needone = 1
hr = HorizontalRule()
def spill(msg, attrs, predicate):
ok, attrs = _split_list(attrs, predicate)
if ok:
hr.maybe()
push(msg)
for name, kind, homecls, value in ok:
try:
value = getattr(object, name)
except Exception:
# Some descriptors may meet a failure in their __get__.
# (bug #1785)
push(self.docdata(value, name, mod))
else:
push(self.document(value,
name, mod, object))
return attrs
def spilldescriptors(msg, attrs, predicate):
ok, attrs = _split_list(attrs, predicate)
if ok:
hr.maybe()
push(msg)
for name, kind, homecls, value in ok:
push(self.docdata(value, name, mod))
return attrs
def spilldata(msg, attrs, predicate):
ok, attrs = _split_list(attrs, predicate)
if ok:
hr.maybe()
push(msg)
for name, kind, homecls, value in ok:
doc = getdoc(value)
try:
obj = getattr(object, name)
except AttributeError:
obj = homecls.__dict__[name]
push(self.docother(obj, name, mod, maxlen=70, doc=doc) +
'\n')
return attrs
attrs = [(name, kind, cls, value)
for name, kind, cls, value in classify_class_attrs(object)
if visiblename(name, obj=object)]
while attrs:
if mro:
thisclass = mro.popleft()
else:
thisclass = attrs[0][2]
attrs, inherited = _split_list(attrs, lambda t: t[2] is thisclass)
if object is not builtins.object and thisclass is builtins.object:
attrs = inherited
continue
elif thisclass is object:
tag = "defined here"
else:
tag = "inherited from %s" % classname(thisclass,
object.__module__)
sort_attributes(attrs, object)
# Pump out the attrs, segregated by kind.
attrs = spill("Methods %s:\n" % tag, attrs,
lambda t: t[1] == 'method')
attrs = spill("Class methods %s:\n" % tag, attrs,
lambda t: t[1] == 'class method')
attrs = spill("Static methods %s:\n" % tag, attrs,
lambda t: t[1] == 'static method')
attrs = spilldescriptors("Readonly properties %s:\n" % tag, attrs,
lambda t: t[1] == 'readonly property')
attrs = spilldescriptors("Data descriptors %s:\n" % tag, attrs,
lambda t: t[1] == 'data descriptor')
attrs = spilldata("Data and other attributes %s:\n" % tag, attrs,
lambda t: t[1] == 'data')
assert attrs == []
attrs = inherited
contents = '\n'.join(contents)
if not contents:
return title + '\n'
return title + '\n' + self.indent(contents.rstrip(), ' | ') + '\n' | [
"def",
"docclass",
"(",
"self",
",",
"object",
",",
"name",
"=",
"None",
",",
"mod",
"=",
"None",
",",
"*",
"ignored",
")",
":",
"realname",
"=",
"object",
".",
"__name__",
"name",
"=",
"name",
"or",
"realname",
"bases",
"=",
"object",
".",
"__bases_... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/pydoc.py#L1300-L1452 | |
cms-sw/cmssw | fd9de012d503d3405420bcbeec0ec879baa57cf2 | Validation/RecoTrack/python/plotting/ntupleDataFormat.py | python | _Object._checkIsValid | (self) | Raise an exception if the object index is not valid. | Raise an exception if the object index is not valid. | [
"Raise",
"an",
"exception",
"if",
"the",
"object",
"index",
"is",
"not",
"valid",
"."
] | def _checkIsValid(self):
"""Raise an exception if the object index is not valid."""
if not self.isValid():
raise Exception("%s is not valid" % self.__class__.__name__) | [
"def",
"_checkIsValid",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"isValid",
"(",
")",
":",
"raise",
"Exception",
"(",
"\"%s is not valid\"",
"%",
"self",
".",
"__class__",
".",
"__name__",
")"
] | https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/Validation/RecoTrack/python/plotting/ntupleDataFormat.py#L76-L79 | ||
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/python/ops/variables.py | python | Variable.assign_add | (self, delta, use_locking=False) | return state_ops.assign_add(self._variable, delta, use_locking=use_locking) | Adds a value to this variable.
This is essentially a shortcut for `assign_add(self, delta)`.
Args:
delta: A `Tensor`. The value to add to this variable.
use_locking: If `True`, use locking during the operation.
Returns:
A `Tensor` that will hold the new value of this variable after
the addition has completed. | Adds a value to this variable. | [
"Adds",
"a",
"value",
"to",
"this",
"variable",
"."
] | def assign_add(self, delta, use_locking=False):
"""Adds a value to this variable.
This is essentially a shortcut for `assign_add(self, delta)`.
Args:
delta: A `Tensor`. The value to add to this variable.
use_locking: If `True`, use locking during the operation.
Returns:
A `Tensor` that will hold the new value of this variable after
the addition has completed.
"""
return state_ops.assign_add(self._variable, delta, use_locking=use_locking) | [
"def",
"assign_add",
"(",
"self",
",",
"delta",
",",
"use_locking",
"=",
"False",
")",
":",
"return",
"state_ops",
".",
"assign_add",
"(",
"self",
".",
"_variable",
",",
"delta",
",",
"use_locking",
"=",
"use_locking",
")"
] | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/python/ops/variables.py#L503-L516 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py2/pandas/util/_validators.py | python | validate_args | (fname, args, max_fname_arg_count, compat_args) | Checks whether the length of the `*args` argument passed into a function
has at most `len(compat_args)` arguments and whether or not all of these
elements in `args` are set to their default values.
fname: str
The name of the function being passed the `*args` parameter
args: tuple
The `*args` parameter passed into a function
max_fname_arg_count: int
The maximum number of arguments that the function `fname`
can accept, excluding those in `args`. Used for displaying
appropriate error messages. Must be non-negative.
compat_args: OrderedDict
A ordered dictionary of keys and their associated default values.
In order to accommodate buggy behaviour in some versions of `numpy`,
where a signature displayed keyword arguments but then passed those
arguments **positionally** internally when calling downstream
implementations, an ordered dictionary ensures that the original
order of the keyword arguments is enforced. Note that if there is
only one key, a generic dict can be passed in as well.
Raises
------
TypeError if `args` contains more values than there are `compat_args`
ValueError if `args` contains values that do not correspond to those
of the default values specified in `compat_args` | Checks whether the length of the `*args` argument passed into a function
has at most `len(compat_args)` arguments and whether or not all of these
elements in `args` are set to their default values. | [
"Checks",
"whether",
"the",
"length",
"of",
"the",
"*",
"args",
"argument",
"passed",
"into",
"a",
"function",
"has",
"at",
"most",
"len",
"(",
"compat_args",
")",
"arguments",
"and",
"whether",
"or",
"not",
"all",
"of",
"these",
"elements",
"in",
"args",
... | def validate_args(fname, args, max_fname_arg_count, compat_args):
"""
Checks whether the length of the `*args` argument passed into a function
has at most `len(compat_args)` arguments and whether or not all of these
elements in `args` are set to their default values.
fname: str
The name of the function being passed the `*args` parameter
args: tuple
The `*args` parameter passed into a function
max_fname_arg_count: int
The maximum number of arguments that the function `fname`
can accept, excluding those in `args`. Used for displaying
appropriate error messages. Must be non-negative.
compat_args: OrderedDict
A ordered dictionary of keys and their associated default values.
In order to accommodate buggy behaviour in some versions of `numpy`,
where a signature displayed keyword arguments but then passed those
arguments **positionally** internally when calling downstream
implementations, an ordered dictionary ensures that the original
order of the keyword arguments is enforced. Note that if there is
only one key, a generic dict can be passed in as well.
Raises
------
TypeError if `args` contains more values than there are `compat_args`
ValueError if `args` contains values that do not correspond to those
of the default values specified in `compat_args`
"""
_check_arg_length(fname, args, max_fname_arg_count, compat_args)
# We do this so that we can provide a more informative
# error message about the parameters that we are not
# supporting in the pandas implementation of 'fname'
kwargs = dict(zip(compat_args, args))
_check_for_default_values(fname, kwargs, compat_args) | [
"def",
"validate_args",
"(",
"fname",
",",
"args",
",",
"max_fname_arg_count",
",",
"compat_args",
")",
":",
"_check_arg_length",
"(",
"fname",
",",
"args",
",",
"max_fname_arg_count",
",",
"compat_args",
")",
"# We do this so that we can provide a more informative",
"#... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/util/_validators.py#L72-L111 | ||
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/ops/data_flow_ops.py | python | QueueBase._check_enqueue_dtypes | (self, vals) | return tensors | Validate and convert `vals` to a list of `Tensor`s.
The `vals` argument can be a Tensor, a list or tuple of tensors, or a
dictionary with tensor values.
If it is a dictionary, the queue must have been constructed with a
`names` attribute and the dictionary keys must match the queue names.
If the queue was constructed with a `names` attribute, `vals` must
be a dictionary.
Args:
vals: A tensor, a list or tuple of tensors, or a dictionary..
Returns:
A list of `Tensor` objects.
Raises:
ValueError: If `vals` is invalid. | Validate and convert `vals` to a list of `Tensor`s. | [
"Validate",
"and",
"convert",
"vals",
"to",
"a",
"list",
"of",
"Tensor",
"s",
"."
] | def _check_enqueue_dtypes(self, vals):
"""Validate and convert `vals` to a list of `Tensor`s.
The `vals` argument can be a Tensor, a list or tuple of tensors, or a
dictionary with tensor values.
If it is a dictionary, the queue must have been constructed with a
`names` attribute and the dictionary keys must match the queue names.
If the queue was constructed with a `names` attribute, `vals` must
be a dictionary.
Args:
vals: A tensor, a list or tuple of tensors, or a dictionary..
Returns:
A list of `Tensor` objects.
Raises:
ValueError: If `vals` is invalid.
"""
if isinstance(vals, dict):
if not self._names:
raise ValueError("Queue must have names to enqueue a dictionary")
if sorted(self._names, key=str) != sorted(vals.keys(), key=str):
raise ValueError("Keys in dictionary to enqueue do not match "
"names of Queue. Dictionary: (%s), Queue: (%s)" %
(sorted(vals.keys()), sorted(self._names)))
# The order of values in `self._names` indicates the order in which the
# tensors in the dictionary `vals` must be listed.
vals = [vals[k] for k in self._names]
else:
if self._names:
raise ValueError("You must enqueue a dictionary in a Queue with names")
if not isinstance(vals, (list, tuple)):
vals = [vals]
tensors = []
for i, (val, dtype) in enumerate(zip(vals, self._dtypes)):
tensors.append(ops.convert_to_tensor(val, dtype=dtype,
name="component_%d" % i))
return tensors | [
"def",
"_check_enqueue_dtypes",
"(",
"self",
",",
"vals",
")",
":",
"if",
"isinstance",
"(",
"vals",
",",
"dict",
")",
":",
"if",
"not",
"self",
".",
"_names",
":",
"raise",
"ValueError",
"(",
"\"Queue must have names to enqueue a dictionary\"",
")",
"if",
"so... | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/ops/data_flow_ops.py#L239-L280 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/resource_variable_ops.py | python | ResourceVariable._init_from_args | (self,
initial_value=None,
trainable=None,
collections=None,
caching_device=None,
name=None,
dtype=None,
constraint=None,
synchronization=None,
aggregation=None,
distribute_strategy=None,
shape=None) | Creates a variable.
Args:
initial_value: A `Tensor`, or Python object convertible to a `Tensor`,
which is the initial value for the Variable. The initial value must have
a shape specified unless `validate_shape` is set to False. Can also be a
callable with no argument that returns the initial value when called.
(Note that initializer functions from init_ops.py must first be bound
to a shape before being used here.)
trainable: If `True`, the default, also adds the variable to the graph
collection `GraphKeys.TRAINABLE_VARIABLES`. This collection is used as
the default list of variables to use by the `Optimizer` classes.
Defaults to `True`, unless `synchronization` is set to `ON_READ`, in
which case it defaults to `False`.
collections: List of graph collections keys. The new variable is added to
these collections. Defaults to `[GraphKeys.GLOBAL_VARIABLES]`.
caching_device: Optional device string or function describing where the
Variable should be cached for reading. Defaults to the Variable's
device. If not `None`, caches on another device. Typical use is to
cache on the device where the Ops using the Variable reside, to
deduplicate copying through `Switch` and other conditional statements.
name: Optional name for the variable. Defaults to `'Variable'` and gets
uniquified automatically.
dtype: If set, initial_value will be converted to the given type.
If None, either the datatype will be kept (if initial_value is
a Tensor) or float32 will be used (if it is a Python object convertible
to a Tensor).
constraint: An optional projection function to be applied to the variable
after being updated by an `Optimizer` (e.g. used to implement norm
constraints or value constraints for layer weights). The function must
take as input the unprojected Tensor representing the value of the
variable and return the Tensor for the projected value
(which must have the same shape). Constraints are not safe to
use when doing asynchronous distributed training.
synchronization: Indicates when a distributed a variable will be
aggregated. Accepted values are constants defined in the class
`tf.VariableSynchronization`. By default the synchronization is set to
`AUTO` and the current `DistributionStrategy` chooses
when to synchronize.
aggregation: Indicates how a distributed variable will be aggregated.
Accepted values are constants defined in the class
`tf.VariableAggregation`.
distribute_strategy: DistributionStrategy under which this variable
was created.
shape: (optional) The shape of this variable. If None, the shape of
`initial_value` will be used. When setting this argument to
`tf.TensorShape(None)` (representing an unspecified shape), the variable
can be assigned with values of different shapes.
Raises:
ValueError: If the initial value is not specified, or does not have a
shape and `validate_shape` is `True`.
@compatibility(eager)
When Eager Execution is enabled, variables are never added to collections.
It is not implicitly added to the `GLOBAL_VARIABLES` or
`TRAINABLE_VARIABLES` collections, and the `collections` argument is
ignored.
@end_compatibility | Creates a variable. | [
"Creates",
"a",
"variable",
"."
] | def _init_from_args(self,
initial_value=None,
trainable=None,
collections=None,
caching_device=None,
name=None,
dtype=None,
constraint=None,
synchronization=None,
aggregation=None,
distribute_strategy=None,
shape=None):
"""Creates a variable.
Args:
initial_value: A `Tensor`, or Python object convertible to a `Tensor`,
which is the initial value for the Variable. The initial value must have
a shape specified unless `validate_shape` is set to False. Can also be a
callable with no argument that returns the initial value when called.
(Note that initializer functions from init_ops.py must first be bound
to a shape before being used here.)
trainable: If `True`, the default, also adds the variable to the graph
collection `GraphKeys.TRAINABLE_VARIABLES`. This collection is used as
the default list of variables to use by the `Optimizer` classes.
Defaults to `True`, unless `synchronization` is set to `ON_READ`, in
which case it defaults to `False`.
collections: List of graph collections keys. The new variable is added to
these collections. Defaults to `[GraphKeys.GLOBAL_VARIABLES]`.
caching_device: Optional device string or function describing where the
Variable should be cached for reading. Defaults to the Variable's
device. If not `None`, caches on another device. Typical use is to
cache on the device where the Ops using the Variable reside, to
deduplicate copying through `Switch` and other conditional statements.
name: Optional name for the variable. Defaults to `'Variable'` and gets
uniquified automatically.
dtype: If set, initial_value will be converted to the given type.
If None, either the datatype will be kept (if initial_value is
a Tensor) or float32 will be used (if it is a Python object convertible
to a Tensor).
constraint: An optional projection function to be applied to the variable
after being updated by an `Optimizer` (e.g. used to implement norm
constraints or value constraints for layer weights). The function must
take as input the unprojected Tensor representing the value of the
variable and return the Tensor for the projected value
(which must have the same shape). Constraints are not safe to
use when doing asynchronous distributed training.
synchronization: Indicates when a distributed a variable will be
aggregated. Accepted values are constants defined in the class
`tf.VariableSynchronization`. By default the synchronization is set to
`AUTO` and the current `DistributionStrategy` chooses
when to synchronize.
aggregation: Indicates how a distributed variable will be aggregated.
Accepted values are constants defined in the class
`tf.VariableAggregation`.
distribute_strategy: DistributionStrategy under which this variable
was created.
shape: (optional) The shape of this variable. If None, the shape of
`initial_value` will be used. When setting this argument to
`tf.TensorShape(None)` (representing an unspecified shape), the variable
can be assigned with values of different shapes.
Raises:
ValueError: If the initial value is not specified, or does not have a
shape and `validate_shape` is `True`.
@compatibility(eager)
When Eager Execution is enabled, variables are never added to collections.
It is not implicitly added to the `GLOBAL_VARIABLES` or
`TRAINABLE_VARIABLES` collections, and the `collections` argument is
ignored.
@end_compatibility
"""
synchronization, aggregation, trainable = (
variables.validate_synchronization_aggregation_trainable(
synchronization, aggregation, trainable, name))
if initial_value is None:
raise ValueError("initial_value must be specified.")
init_from_fn = callable(initial_value)
if isinstance(initial_value, ops.Tensor) and hasattr(
initial_value, "graph") and initial_value.graph.building_function:
raise ValueError("Tensor-typed variable initializers must either be "
"wrapped in an init_scope or callable "
"(e.g., `tf.Variable(lambda : "
"tf.truncated_normal([10, 40]))`) when building "
"functions. Please file a feature request if this "
"restriction inconveniences you.")
if collections is None:
collections = [ops.GraphKeys.GLOBAL_VARIABLES]
if not isinstance(collections, (list, tuple, set)):
raise ValueError(
"collections argument to Variable constructor must be a list, tuple, "
"or set. Got %s of type %s" % (collections, type(collections)))
if constraint is not None and not callable(constraint):
raise ValueError("The `constraint` argument must be a callable.")
if isinstance(initial_value, trackable.CheckpointInitialValue):
self._maybe_initialize_trackable()
self._update_uid = initial_value.checkpoint_position.restore_uid
initial_value = initial_value.wrapped_value
if trainable and ops.GraphKeys.TRAINABLE_VARIABLES not in collections:
collections = list(collections) + [ops.GraphKeys.TRAINABLE_VARIABLES]
with ops.init_scope():
self._in_graph_mode = not context.executing_eagerly()
with ops.name_scope(name, "Variable", []
if init_from_fn else [initial_value]) as name:
# pylint: disable=protected-access
handle_name = ops.name_from_scope_name(name)
if self._in_graph_mode:
shared_name = handle_name
unique_id = shared_name
else:
# When in eager mode use a uid for the shared_name, to prevent
# accidental sharing.
unique_id = "%s_%d" % (handle_name, ops.uid())
shared_name = context.shared_name()
# Use attr_scope and device(None) to simulate the behavior of
# colocate_with when the variable we want to colocate with doesn't
# yet exist.
device_context_manager = (
ops.device if self._in_graph_mode else ops.NullContextmanager)
attr = attr_value_pb2.AttrValue(
list=attr_value_pb2.AttrValue.ListValue(
s=[compat.as_bytes("loc:@%s" % handle_name)]))
with ops.get_default_graph()._attr_scope({"_class": attr}):
with ops.name_scope("Initializer"), device_context_manager(None):
initial_value = ops.convert_to_tensor(
initial_value() if init_from_fn else initial_value,
name="initial_value", dtype=dtype)
if shape is not None:
if not initial_value.shape.is_compatible_with(shape):
raise ValueError(
"The initial value's shape (%s) is not compatible with "
"the explicitly supplied `shape` argument (%s)." %
(initial_value.shape, shape))
else:
shape = initial_value.shape
handle = eager_safe_variable_handle(
initial_value=initial_value,
shape=shape,
shared_name=shared_name,
name=name,
graph_mode=self._in_graph_mode)
# pylint: disable=protected-access
if (self._in_graph_mode and initial_value is not None and
initial_value.op._get_control_flow_context() is not None):
raise ValueError(
"Initializer for variable %s is from inside a control-flow "
"construct, such as a loop or conditional. When creating a "
"variable inside a loop or conditional, use a lambda as the "
"initializer." % name)
# pylint: enable=protected-access
dtype = initial_value.dtype.base_dtype
if self._in_graph_mode:
with ops.name_scope("IsInitialized"):
is_initialized_op = (
gen_resource_variable_ops.var_is_initialized_op(handle))
if initial_value is not None:
# pylint: disable=g-backslash-continuation
with ops.name_scope("Assign") as n, \
ops.colocate_with(None, ignore_existing=True), \
ops.device(handle.device):
# pylint: disable=protected-access
initializer_op = (
gen_resource_variable_ops.assign_variable_op(
handle,
variables._try_guard_against_uninitialized_dependencies(
name,
initial_value),
name=n))
# pylint: enable=protected-access
# pylint: enable=g-backslash-continuation
with ops.name_scope("Read"):
# Manually assign reads to the handle's device to avoid log
# messages.
with ops.device(handle.device):
value = gen_resource_variable_ops.read_variable_op(handle, dtype)
_maybe_set_handle_data(dtype, handle, value)
graph_element = value
if caching_device is not None:
# Variables may be created in a tf.device() or ops.colocate_with()
# context. At the same time, users would expect caching device to
# be independent of this context, and/or would not expect the
# current device context to be merged with the caching device
# spec. Therefore we reset the colocation stack before creating
# the cached value. Note that resetting the colocation stack will
# also reset the device stack.
with ops.colocate_with(None, ignore_existing=True):
with ops.device(caching_device):
cached_value = array_ops.identity(value)
else:
cached_value = None
else:
gen_resource_variable_ops.assign_variable_op(handle, initial_value)
is_initialized_op = None
initializer_op = None
graph_element = None
if caching_device:
with ops.device(caching_device):
cached_value = gen_resource_variable_ops.read_variable_op(
handle, dtype)
_maybe_set_handle_data(dtype, handle, cached_value)
else:
cached_value = None
if not context.executing_eagerly():
# Eager variables are only added to collections if they are part of an
# eager variable store (otherwise in an interactive session they would
# hog memory and cause OOM). This is done in ops/variable_scope.py.
ops.add_to_collections(collections, self)
elif ops.GraphKeys.GLOBAL_STEP in collections:
ops.add_to_collections(ops.GraphKeys.GLOBAL_STEP, self)
initial_value = initial_value if self._in_graph_mode else None
super(ResourceVariable, self).__init__(
trainable=trainable, shape=shape, dtype=dtype, handle=handle,
synchronization=synchronization, constraint=constraint,
aggregation=aggregation, distribute_strategy=distribute_strategy,
name=name, unique_id=unique_id, handle_name=handle_name,
graph_element=graph_element, initial_value=initial_value,
initializer_op=initializer_op, is_initialized_op=is_initialized_op,
cached_value=cached_value) | [
"def",
"_init_from_args",
"(",
"self",
",",
"initial_value",
"=",
"None",
",",
"trainable",
"=",
"None",
",",
"collections",
"=",
"None",
",",
"caching_device",
"=",
"None",
",",
"name",
"=",
"None",
",",
"dtype",
"=",
"None",
",",
"constraint",
"=",
"No... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/resource_variable_ops.py#L1408-L1630 | ||
mapnik/mapnik | f3da900c355e1d15059c4a91b00203dcc9d9f0ef | scons/scons-local-4.1.0/SCons/Node/FS.py | python | Dir.get_abspath | (self) | return self._abspath | Get the absolute path of the file. | Get the absolute path of the file. | [
"Get",
"the",
"absolute",
"path",
"of",
"the",
"file",
"."
] | def get_abspath(self):
"""Get the absolute path of the file."""
return self._abspath | [
"def",
"get_abspath",
"(",
"self",
")",
":",
"return",
"self",
".",
"_abspath"
] | https://github.com/mapnik/mapnik/blob/f3da900c355e1d15059c4a91b00203dcc9d9f0ef/scons/scons-local-4.1.0/SCons/Node/FS.py#L1914-L1916 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/winpython/py3compat.py | python | is_binary_string | (obj) | Return True if `obj` is a binary string, False if it is anything else | Return True if `obj` is a binary string, False if it is anything else | [
"Return",
"True",
"if",
"obj",
"is",
"a",
"binary",
"string",
"False",
"if",
"it",
"is",
"anything",
"else"
] | def is_binary_string(obj):
"""Return True if `obj` is a binary string, False if it is anything else"""
if PY2:
# Python 2
return isinstance(obj, str)
else:
# Python 3
return isinstance(obj, bytes) | [
"def",
"is_binary_string",
"(",
"obj",
")",
":",
"if",
"PY2",
":",
"# Python 2",
"return",
"isinstance",
"(",
"obj",
",",
"str",
")",
"else",
":",
"# Python 3",
"return",
"isinstance",
"(",
"obj",
",",
"bytes",
")"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/winpython/py3compat.py#L90-L97 | ||
microsoft/ivy | 9f3c7ecc0b2383129fdd0953e10890d98d09a82d | ivy/ivy_logic_parser.py | python | p_term_var | (p) | term : var | term : var | [
"term",
":",
"var"
] | def p_term_var(p):
'term : var'
p[0] = p[1] | [
"def",
"p_term_var",
"(",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"p",
"[",
"1",
"]"
] | https://github.com/microsoft/ivy/blob/9f3c7ecc0b2383129fdd0953e10890d98d09a82d/ivy/ivy_logic_parser.py#L157-L159 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/idlelib/CallTipWindow.py | python | CallTip.position_window | (self) | Check if needs to reposition the window, and if so - do it. | Check if needs to reposition the window, and if so - do it. | [
"Check",
"if",
"needs",
"to",
"reposition",
"the",
"window",
"and",
"if",
"so",
"-",
"do",
"it",
"."
] | def position_window(self):
"""Check if needs to reposition the window, and if so - do it."""
curline = int(self.widget.index("insert").split('.')[0])
if curline == self.lastline:
return
self.lastline = curline
self.widget.see("insert")
if curline == self.parenline:
box = self.widget.bbox("%d.%d" % (self.parenline,
self.parencol))
else:
box = self.widget.bbox("%d.0" % curline)
if not box:
box = list(self.widget.bbox("insert"))
# align to left of window
box[0] = 0
box[2] = 0
x = box[0] + self.widget.winfo_rootx() + 2
y = box[1] + box[3] + self.widget.winfo_rooty()
self.tipwindow.wm_geometry("+%d+%d" % (x, y)) | [
"def",
"position_window",
"(",
"self",
")",
":",
"curline",
"=",
"int",
"(",
"self",
".",
"widget",
".",
"index",
"(",
"\"insert\"",
")",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
"]",
")",
"if",
"curline",
"==",
"self",
".",
"lastline",
":",
"retur... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/idlelib/CallTipWindow.py#L27-L46 | ||
mongodb/mongo | d8ff665343ad29cf286ee2cf4a1960d29371937b | buildscripts/idl/idl/binder.py | python | _validate_single_bson_type | (ctxt, idl_type, syntax_type) | return True | Validate bson serialization type is correct for a type. | Validate bson serialization type is correct for a type. | [
"Validate",
"bson",
"serialization",
"type",
"is",
"correct",
"for",
"a",
"type",
"."
] | def _validate_single_bson_type(ctxt, idl_type, syntax_type):
# type: (errors.ParserContext, Union[syntax.Type, ast.Type], str) -> bool
"""Validate bson serialization type is correct for a type."""
bson_type = idl_type.bson_serialization_type[0]
# Any and Chain are only valid if they are the only bson types specified
if bson_type in ["any", "chain"]:
return True
if not bson.is_valid_bson_type(bson_type):
ctxt.add_bad_bson_type_error(idl_type, syntax_type, idl_type.name, bson_type)
return False
# Validate bindata_subytpe
if bson_type == "bindata":
subtype = idl_type.bindata_subtype
if subtype is None:
subtype = "<unknown>"
if not bson.is_valid_bindata_subtype(subtype):
ctxt.add_bad_bson_bindata_subtype_value_error(idl_type, syntax_type, idl_type.name,
subtype)
elif idl_type.bindata_subtype is not None:
ctxt.add_bad_bson_bindata_subtype_error(idl_type, syntax_type, idl_type.name, bson_type)
return True | [
"def",
"_validate_single_bson_type",
"(",
"ctxt",
",",
"idl_type",
",",
"syntax_type",
")",
":",
"# type: (errors.ParserContext, Union[syntax.Type, ast.Type], str) -> bool",
"bson_type",
"=",
"idl_type",
".",
"bson_serialization_type",
"[",
"0",
"]",
"# Any and Chain are only v... | https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/idl/idl/binder.py#L44-L70 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_windows.py | python | StatusBar.GetStatusWidth | (*args, **kwargs) | return _windows_.StatusBar_GetStatusWidth(*args, **kwargs) | GetStatusWidth(self, int n) -> int | GetStatusWidth(self, int n) -> int | [
"GetStatusWidth",
"(",
"self",
"int",
"n",
")",
"-",
">",
"int"
] | def GetStatusWidth(*args, **kwargs):
"""GetStatusWidth(self, int n) -> int"""
return _windows_.StatusBar_GetStatusWidth(*args, **kwargs) | [
"def",
"GetStatusWidth",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_windows_",
".",
"StatusBar_GetStatusWidth",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_windows.py#L1267-L1269 | |
hfinkel/llvm-project-cxxjit | 91084ef018240bbb8e24235ff5cd8c355a9c1a1e | clang/bindings/python/clang/cindex.py | python | Token.location | (self) | return conf.lib.clang_getTokenLocation(self._tu, self) | The SourceLocation this Token occurs at. | The SourceLocation this Token occurs at. | [
"The",
"SourceLocation",
"this",
"Token",
"occurs",
"at",
"."
] | def location(self):
"""The SourceLocation this Token occurs at."""
return conf.lib.clang_getTokenLocation(self._tu, self) | [
"def",
"location",
"(",
"self",
")",
":",
"return",
"conf",
".",
"lib",
".",
"clang_getTokenLocation",
"(",
"self",
".",
"_tu",
",",
"self",
")"
] | https://github.com/hfinkel/llvm-project-cxxjit/blob/91084ef018240bbb8e24235ff5cd8c355a9c1a1e/clang/bindings/python/clang/cindex.py#L3294-L3296 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/telemetry/telemetry/core/util.py | python | WaitFor | (condition, timeout) | Waits for up to |timeout| secs for the function |condition| to return True.
Polling frequency is (elapsed_time / 10), with a min of .1s and max of 5s.
Returns:
Result of |condition| function (if present). | Waits for up to |timeout| secs for the function |condition| to return True. | [
"Waits",
"for",
"up",
"to",
"|timeout|",
"secs",
"for",
"the",
"function",
"|condition|",
"to",
"return",
"True",
"."
] | def WaitFor(condition, timeout):
"""Waits for up to |timeout| secs for the function |condition| to return True.
Polling frequency is (elapsed_time / 10), with a min of .1s and max of 5s.
Returns:
Result of |condition| function (if present).
"""
min_poll_interval = 0.1
max_poll_interval = 5
output_interval = 300
def GetConditionString():
if condition.__name__ == '<lambda>':
try:
return inspect.getsource(condition).strip()
except IOError:
pass
return condition.__name__
start_time = time.time()
last_output_time = start_time
while True:
res = condition()
if res:
return res
now = time.time()
elapsed_time = now - start_time
last_output_elapsed_time = now - last_output_time
if elapsed_time > timeout:
raise exceptions.TimeoutException('Timed out while waiting %ds for %s.' %
(timeout, GetConditionString()))
if last_output_elapsed_time > output_interval:
logging.info('Continuing to wait %ds for %s. Elapsed: %ds.', timeout,
GetConditionString(), elapsed_time)
last_output_time = time.time()
poll_interval = min(
max(elapsed_time / 10., min_poll_interval), max_poll_interval)
time.sleep(poll_interval) | [
"def",
"WaitFor",
"(",
"condition",
",",
"timeout",
")",
":",
"min_poll_interval",
"=",
"0.1",
"max_poll_interval",
"=",
"5",
"output_interval",
"=",
"300",
"def",
"GetConditionString",
"(",
")",
":",
"if",
"condition",
".",
"__name__",
"==",
"'<lambda>'",
":"... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/telemetry/core/util.py#L63-L101 | ||
hfinkel/llvm-project-cxxjit | 91084ef018240bbb8e24235ff5cd8c355a9c1a1e | llvm/examples/Kaleidoscope/MCJIT/complete/genk-timing.py | python | KScriptGenerator.updateFunctionCallMap | (self, caller, callee) | Maintains a map of functions that are called from other functions | Maintains a map of functions that are called from other functions | [
"Maintains",
"a",
"map",
"of",
"functions",
"that",
"are",
"called",
"from",
"other",
"functions"
] | def updateFunctionCallMap(self, caller, callee):
"""Maintains a map of functions that are called from other functions"""
if not caller in self.calledFunctionTable:
self.calledFunctionTable[caller] = []
if not callee in self.calledFunctionTable[caller]:
self.calledFunctionTable[caller].append(callee)
if not caller in self.comprehensiveCalledFunctionTable:
self.comprehensiveCalledFunctionTable[caller] = []
self.comprehensiveCalledFunctionTable[caller].append(callee) | [
"def",
"updateFunctionCallMap",
"(",
"self",
",",
"caller",
",",
"callee",
")",
":",
"if",
"not",
"caller",
"in",
"self",
".",
"calledFunctionTable",
":",
"self",
".",
"calledFunctionTable",
"[",
"caller",
"]",
"=",
"[",
"]",
"if",
"not",
"callee",
"in",
... | https://github.com/hfinkel/llvm-project-cxxjit/blob/91084ef018240bbb8e24235ff5cd8c355a9c1a1e/llvm/examples/Kaleidoscope/MCJIT/complete/genk-timing.py#L63-L71 | ||
jeog/TDAmeritradeAPI | 91c738afd7d57b54f6231170bd64c2550fafd34d | python/tdma_api/get.py | python | OptionChainAnalyticalGetter.get_volatility | (self) | return clib.get_val(self._abi('GetVolatility'), c_double, self._obj) | Returns implied volatility(for calculations) being used. | Returns implied volatility(for calculations) being used. | [
"Returns",
"implied",
"volatility",
"(",
"for",
"calculations",
")",
"being",
"used",
"."
] | def get_volatility(self):
"""Returns implied volatility(for calculations) being used."""
return clib.get_val(self._abi('GetVolatility'), c_double, self._obj) | [
"def",
"get_volatility",
"(",
"self",
")",
":",
"return",
"clib",
".",
"get_val",
"(",
"self",
".",
"_abi",
"(",
"'GetVolatility'",
")",
",",
"c_double",
",",
"self",
".",
"_obj",
")"
] | https://github.com/jeog/TDAmeritradeAPI/blob/91c738afd7d57b54f6231170bd64c2550fafd34d/python/tdma_api/get.py#L1022-L1024 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/training/saving/functional_saver.py | python | _get_mapped_registered_save_fn | (fn, trackables, call_with_mapped_captures) | Converts the function to a python or tf.function with a single file arg. | Converts the function to a python or tf.function with a single file arg. | [
"Converts",
"the",
"function",
"to",
"a",
"python",
"or",
"tf",
".",
"function",
"with",
"a",
"single",
"file",
"arg",
"."
] | def _get_mapped_registered_save_fn(fn, trackables, call_with_mapped_captures):
"""Converts the function to a python or tf.function with a single file arg."""
if call_with_mapped_captures is None:
def mapped_fn(file_prefix):
return fn(trackables=trackables, file_prefix=file_prefix)
return mapped_fn
else:
tf_fn = def_function.function(fn, autograph=False)
concrete = tf_fn.get_concrete_function(
trackables=trackables,
file_prefix=tensor_spec.TensorSpec(shape=(), dtype=dtypes.string))
def mapped_fn(file_prefix):
return call_with_mapped_captures(concrete, [file_prefix])
return mapped_fn | [
"def",
"_get_mapped_registered_save_fn",
"(",
"fn",
",",
"trackables",
",",
"call_with_mapped_captures",
")",
":",
"if",
"call_with_mapped_captures",
"is",
"None",
":",
"def",
"mapped_fn",
"(",
"file_prefix",
")",
":",
"return",
"fn",
"(",
"trackables",
"=",
"trac... | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/training/saving/functional_saver.py#L136-L149 | ||
ideawu/ssdb-rocks | a3cbb322cafb2f493252829c608e2239df98c9ac | deps/cpy/antlr3/tokens.py | python | Token.getType | (self) | @brief Get the type of the token.
Using setter/getter methods is deprecated. Use o.type instead. | @brief Get the type of the token. | [
"@brief",
"Get",
"the",
"type",
"of",
"the",
"token",
"."
] | def getType(self):
"""@brief Get the type of the token.
Using setter/getter methods is deprecated. Use o.type instead."""
raise NotImplementedError | [
"def",
"getType",
"(",
"self",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/ideawu/ssdb-rocks/blob/a3cbb322cafb2f493252829c608e2239df98c9ac/deps/cpy/antlr3/tokens.py#L59-L64 | ||
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/ros_comm/rospy/src/rospy/impl/tcpros_pubsub.py | python | TCPROSHandler.get_supported | (self) | return [[TCPROS]] | Get supported protocols | Get supported protocols | [
"Get",
"supported",
"protocols"
] | def get_supported(self):
"""
Get supported protocols
"""
return [[TCPROS]] | [
"def",
"get_supported",
"(",
"self",
")",
":",
"return",
"[",
"[",
"TCPROS",
"]",
"]"
] | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/ros_comm/rospy/src/rospy/impl/tcpros_pubsub.py#L282-L286 | |
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | current/deps/v8/third_party/jinja2/nodes.py | python | Node.find_all | (self, node_type) | Find all the nodes of a given type. If the type is a tuple,
the check is performed for any of the tuple items. | Find all the nodes of a given type. If the type is a tuple,
the check is performed for any of the tuple items. | [
"Find",
"all",
"the",
"nodes",
"of",
"a",
"given",
"type",
".",
"If",
"the",
"type",
"is",
"a",
"tuple",
"the",
"check",
"is",
"performed",
"for",
"any",
"of",
"the",
"tuple",
"items",
"."
] | def find_all(self, node_type):
"""Find all the nodes of a given type. If the type is a tuple,
the check is performed for any of the tuple items.
"""
for child in self.iter_child_nodes():
if isinstance(child, node_type):
yield child
for result in child.find_all(node_type):
yield result | [
"def",
"find_all",
"(",
"self",
",",
"node_type",
")",
":",
"for",
"child",
"in",
"self",
".",
"iter_child_nodes",
"(",
")",
":",
"if",
"isinstance",
"(",
"child",
",",
"node_type",
")",
":",
"yield",
"child",
"for",
"result",
"in",
"child",
".",
"find... | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/current/deps/v8/third_party/jinja2/nodes.py#L184-L192 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/collections.py | python | OrderedDict.keys | (self) | return list(self) | od.keys() -> list of keys in od | od.keys() -> list of keys in od | [
"od",
".",
"keys",
"()",
"-",
">",
"list",
"of",
"keys",
"in",
"od"
] | def keys(self):
'od.keys() -> list of keys in od'
return list(self) | [
"def",
"keys",
"(",
"self",
")",
":",
"return",
"list",
"(",
"self",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/collections.py#L100-L102 | |
stack-of-tasks/pinocchio | 593d4d43fded997bb9aa2421f4e55294dbd233c4 | bindings/python/pinocchio/robot_wrapper.py | python | RobotWrapper.computeFrameJacobian | (self, q, frame_id) | return pin.computeFrameJacobian(self.model, self.data, q, frame_id) | Similar to getFrameJacobian but does not need pin.computeJointJacobians and
pin.updateFramePlacements to update internal value of self.data related to frames. | Similar to getFrameJacobian but does not need pin.computeJointJacobians and
pin.updateFramePlacements to update internal value of self.data related to frames. | [
"Similar",
"to",
"getFrameJacobian",
"but",
"does",
"not",
"need",
"pin",
".",
"computeJointJacobians",
"and",
"pin",
".",
"updateFramePlacements",
"to",
"update",
"internal",
"value",
"of",
"self",
".",
"data",
"related",
"to",
"frames",
"."
] | def computeFrameJacobian(self, q, frame_id):
"""
Similar to getFrameJacobian but does not need pin.computeJointJacobians and
pin.updateFramePlacements to update internal value of self.data related to frames.
"""
return pin.computeFrameJacobian(self.model, self.data, q, frame_id) | [
"def",
"computeFrameJacobian",
"(",
"self",
",",
"q",
",",
"frame_id",
")",
":",
"return",
"pin",
".",
"computeFrameJacobian",
"(",
"self",
".",
"model",
",",
"self",
".",
"data",
",",
"q",
",",
"frame_id",
")"
] | https://github.com/stack-of-tasks/pinocchio/blob/593d4d43fded997bb9aa2421f4e55294dbd233c4/bindings/python/pinocchio/robot_wrapper.py#L227-L232 | |
mapnik/mapnik | f3da900c355e1d15059c4a91b00203dcc9d9f0ef | scons/scons-local-4.1.0/SCons/Platform/__init__.py | python | platform_module | (name = platform_default()) | return sys.modules[full_name] | Return the imported module for the platform.
This looks for a module name that matches the specified argument.
If the name is unspecified, we fetch the appropriate default for
our execution environment. | Return the imported module for the platform. | [
"Return",
"the",
"imported",
"module",
"for",
"the",
"platform",
"."
] | def platform_module(name = platform_default()):
"""Return the imported module for the platform.
This looks for a module name that matches the specified argument.
If the name is unspecified, we fetch the appropriate default for
our execution environment.
"""
full_name = 'SCons.Platform.' + name
if full_name not in sys.modules:
if os.name == 'java':
eval(full_name)
else:
try:
# the specific platform module is a relative import
mod = importlib.import_module("." + name, __name__)
except ImportError:
try:
import zipimport
importer = zipimport.zipimporter( sys.modules['SCons.Platform'].__path__[0] )
mod = importer.load_module(full_name)
except ImportError:
raise SCons.Errors.UserError("No platform named '%s'" % name)
setattr(SCons.Platform, name, mod)
return sys.modules[full_name] | [
"def",
"platform_module",
"(",
"name",
"=",
"platform_default",
"(",
")",
")",
":",
"full_name",
"=",
"'SCons.Platform.'",
"+",
"name",
"if",
"full_name",
"not",
"in",
"sys",
".",
"modules",
":",
"if",
"os",
".",
"name",
"==",
"'java'",
":",
"eval",
"(",... | https://github.com/mapnik/mapnik/blob/f3da900c355e1d15059c4a91b00203dcc9d9f0ef/scons/scons-local-4.1.0/SCons/Platform/__init__.py#L86-L109 | |
trailofbits/llvm-sanitizer-tutorial | d29dfeec7f51fbf234fd0080f28f2b30cd0b6e99 | llvm/projects/compiler-rt/lib/sanitizer_common/scripts/cpplint.py | python | CloseExpression | (clean_lines, linenum, pos) | return (line, clean_lines.NumLines(), -1) | If input points to ( or { or [, finds the position that closes it.
If lines[linenum][pos] points to a '(' or '{' or '[', finds the
linenum/pos that correspond to the closing of the expression.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
pos: A position on the line.
Returns:
A tuple (line, linenum, pos) pointer *past* the closing brace, or
(line, len(lines), -1) if we never find a close. Note we ignore
strings and comments when matching; and the line we return is the
'cleansed' line at linenum. | If input points to ( or { or [, finds the position that closes it. | [
"If",
"input",
"points",
"to",
"(",
"or",
"{",
"or",
"[",
"finds",
"the",
"position",
"that",
"closes",
"it",
"."
] | def CloseExpression(clean_lines, linenum, pos):
"""If input points to ( or { or [, finds the position that closes it.
If lines[linenum][pos] points to a '(' or '{' or '[', finds the
linenum/pos that correspond to the closing of the expression.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
pos: A position on the line.
Returns:
A tuple (line, linenum, pos) pointer *past* the closing brace, or
(line, len(lines), -1) if we never find a close. Note we ignore
strings and comments when matching; and the line we return is the
'cleansed' line at linenum.
"""
line = clean_lines.elided[linenum]
startchar = line[pos]
if startchar not in '({[':
return (line, clean_lines.NumLines(), -1)
if startchar == '(': endchar = ')'
if startchar == '[': endchar = ']'
if startchar == '{': endchar = '}'
# Check first line
end_pos = FindEndOfExpressionInLine(line, pos, 0, startchar, endchar)
if end_pos > -1:
return (line, linenum, end_pos)
tail = line[pos:]
num_open = tail.count(startchar) - tail.count(endchar)
while linenum < clean_lines.NumLines() - 1:
linenum += 1
line = clean_lines.elided[linenum]
delta = line.count(startchar) - line.count(endchar)
if num_open + delta <= 0:
return (line, linenum,
FindEndOfExpressionInLine(line, 0, num_open, startchar, endchar))
num_open += delta
# Did not find endchar before end of file, give up
return (line, clean_lines.NumLines(), -1) | [
"def",
"CloseExpression",
"(",
"clean_lines",
",",
"linenum",
",",
"pos",
")",
":",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"startchar",
"=",
"line",
"[",
"pos",
"]",
"if",
"startchar",
"not",
"in",
"'({['",
":",
"return",
"(",
... | https://github.com/trailofbits/llvm-sanitizer-tutorial/blob/d29dfeec7f51fbf234fd0080f28f2b30cd0b6e99/llvm/projects/compiler-rt/lib/sanitizer_common/scripts/cpplint.py#L1054-L1096 | |
mapnik/mapnik | f3da900c355e1d15059c4a91b00203dcc9d9f0ef | scons/scons-local-4.1.0/SCons/Tool/mslink.py | python | _windowsLdmodTargets | (target, source, env, for_signature) | return _dllTargets(target, source, env, for_signature, 'LDMODULE') | Get targets for loadable modules. | Get targets for loadable modules. | [
"Get",
"targets",
"for",
"loadable",
"modules",
"."
] | def _windowsLdmodTargets(target, source, env, for_signature):
"""Get targets for loadable modules."""
return _dllTargets(target, source, env, for_signature, 'LDMODULE') | [
"def",
"_windowsLdmodTargets",
"(",
"target",
",",
"source",
",",
"env",
",",
"for_signature",
")",
":",
"return",
"_dllTargets",
"(",
"target",
",",
"source",
",",
"env",
",",
"for_signature",
",",
"'LDMODULE'",
")"
] | https://github.com/mapnik/mapnik/blob/f3da900c355e1d15059c4a91b00203dcc9d9f0ef/scons/scons-local-4.1.0/SCons/Tool/mslink.py#L84-L86 | |
mingchen/protobuf-ios | 0958df34558cd54cb7b6e6ca5c8855bf3d475046 | compiler/python/google/protobuf/internal/input_stream.py | python | InputStreamBuffer.EndOfStream | (self) | return self._pos >= len(self._buffer) | Returns true iff we're at the end of the stream.
If this returns true, then a call to any other InputStream method
will raise an exception. | Returns true iff we're at the end of the stream.
If this returns true, then a call to any other InputStream method
will raise an exception. | [
"Returns",
"true",
"iff",
"we",
"re",
"at",
"the",
"end",
"of",
"the",
"stream",
".",
"If",
"this",
"returns",
"true",
"then",
"a",
"call",
"to",
"any",
"other",
"InputStream",
"method",
"will",
"raise",
"an",
"exception",
"."
] | def EndOfStream(self):
"""Returns true iff we're at the end of the stream.
If this returns true, then a call to any other InputStream method
will raise an exception.
"""
return self._pos >= len(self._buffer) | [
"def",
"EndOfStream",
"(",
"self",
")",
":",
"return",
"self",
".",
"_pos",
">=",
"len",
"(",
"self",
".",
"_buffer",
")"
] | https://github.com/mingchen/protobuf-ios/blob/0958df34558cd54cb7b6e6ca5c8855bf3d475046/compiler/python/google/protobuf/internal/input_stream.py#L78-L83 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/setuptools/dist.py | python | Distribution._suffix_for | (req) | return ':' + str(req.marker) if req.marker else '' | For a requirement, return the 'extras_require' suffix for
that requirement. | For a requirement, return the 'extras_require' suffix for
that requirement. | [
"For",
"a",
"requirement",
"return",
"the",
"extras_require",
"suffix",
"for",
"that",
"requirement",
"."
] | def _suffix_for(req):
"""
For a requirement, return the 'extras_require' suffix for
that requirement.
"""
return ':' + str(req.marker) if req.marker else '' | [
"def",
"_suffix_for",
"(",
"req",
")",
":",
"return",
"':'",
"+",
"str",
"(",
"req",
".",
"marker",
")",
"if",
"req",
".",
"marker",
"else",
"''"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/setuptools/dist.py#L513-L518 | |
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | media/tools/constrained_network_server/cns.py | python | PortAllocator.Cleanup | (self, interface, all_ports=False) | Cleans up expired ports, or if all_ports=True, all allocated ports.
By default, ports which haven't been used for self._expiry_time_secs are
torn down. If all_ports=True then they are torn down regardless.
Args:
interface: Interface the constrained network is setup on.
all_ports: Should all ports be torn down regardless of expiration? | Cleans up expired ports, or if all_ports=True, all allocated ports. | [
"Cleans",
"up",
"expired",
"ports",
"or",
"if",
"all_ports",
"=",
"True",
"all",
"allocated",
"ports",
"."
] | def Cleanup(self, interface, all_ports=False):
"""Cleans up expired ports, or if all_ports=True, all allocated ports.
By default, ports which haven't been used for self._expiry_time_secs are
torn down. If all_ports=True then they are torn down regardless.
Args:
interface: Interface the constrained network is setup on.
all_ports: Should all ports be torn down regardless of expiration?
"""
with self._port_lock:
self._CleanupLocked(all_ports) | [
"def",
"Cleanup",
"(",
"self",
",",
"interface",
",",
"all_ports",
"=",
"False",
")",
":",
"with",
"self",
".",
"_port_lock",
":",
"self",
".",
"_CleanupLocked",
"(",
"all_ports",
")"
] | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/media/tools/constrained_network_server/cns.py#L159-L170 | ||
zju3dv/clean-pvnet | 5870c509e3cc205e1bb28910a7b1a9a3c8add9a8 | lib/utils/base_utils.py | python | project | (xyz, K, RT) | return xy | xyz: [N, 3]
K: [3, 3]
RT: [3, 4] | xyz: [N, 3]
K: [3, 3]
RT: [3, 4] | [
"xyz",
":",
"[",
"N",
"3",
"]",
"K",
":",
"[",
"3",
"3",
"]",
"RT",
":",
"[",
"3",
"4",
"]"
] | def project(xyz, K, RT):
"""
xyz: [N, 3]
K: [3, 3]
RT: [3, 4]
"""
xyz = np.dot(xyz, RT[:, :3].T) + RT[:, 3:].T
xyz = np.dot(xyz, K.T)
xy = xyz[:, :2] / xyz[:, 2:]
return xy | [
"def",
"project",
"(",
"xyz",
",",
"K",
",",
"RT",
")",
":",
"xyz",
"=",
"np",
".",
"dot",
"(",
"xyz",
",",
"RT",
"[",
":",
",",
":",
"3",
"]",
".",
"T",
")",
"+",
"RT",
"[",
":",
",",
"3",
":",
"]",
".",
"T",
"xyz",
"=",
"np",
".",
... | https://github.com/zju3dv/clean-pvnet/blob/5870c509e3cc205e1bb28910a7b1a9a3c8add9a8/lib/utils/base_utils.py#L17-L26 | |
papyrussolution/OpenPapyrus | bbfb5ec2ea2109b8e2f125edd838e12eaf7b8b91 | Src/OSF/protobuf-3.19.1/python/google/protobuf/text_format.py | python | _Printer.__init__ | (
self,
out,
indent=0,
as_utf8=False,
as_one_line=False,
use_short_repeated_primitives=False,
pointy_brackets=False,
use_index_order=False,
float_format=None,
double_format=None,
use_field_number=False,
descriptor_pool=None,
message_formatter=None,
print_unknown_fields=False,
force_colon=False) | Initialize the Printer.
Double values can be formatted compactly with 15 digits of precision
(which is the most that IEEE 754 "double" can guarantee) using
double_format='.15g'. To ensure that converting to text and back to a proto
will result in an identical value, double_format='.17g' should be used.
Args:
out: To record the text format result.
indent: The initial indent level for pretty print.
as_utf8: Return unescaped Unicode for non-ASCII characters.
In Python 3 actual Unicode characters may appear as is in strings.
In Python 2 the return value will be valid UTF-8 rather than ASCII.
as_one_line: Don't introduce newlines between fields.
use_short_repeated_primitives: Use short repeated format for primitives.
pointy_brackets: If True, use angle brackets instead of curly braces for
nesting.
use_index_order: If True, print fields of a proto message using the order
defined in source code instead of the field number. By default, use the
field number order.
float_format: If set, use this to specify float field formatting
(per the "Format Specification Mini-Language"); otherwise, shortest
float that has same value in wire will be printed. Also affect double
field if double_format is not set but float_format is set.
double_format: If set, use this to specify double field formatting
(per the "Format Specification Mini-Language"); if it is not set but
float_format is set, use float_format. Otherwise, str() is used.
use_field_number: If True, print field numbers instead of names.
descriptor_pool: A DescriptorPool used to resolve Any types.
message_formatter: A function(message, indent, as_one_line): unicode|None
to custom format selected sub-messages (usually based on message type).
Use to pretty print parts of the protobuf for easier diffing.
print_unknown_fields: If True, unknown fields will be printed.
force_colon: If set, a colon will be added after the field name even if
the field is a proto message. | Initialize the Printer. | [
"Initialize",
"the",
"Printer",
"."
] | def __init__(
self,
out,
indent=0,
as_utf8=False,
as_one_line=False,
use_short_repeated_primitives=False,
pointy_brackets=False,
use_index_order=False,
float_format=None,
double_format=None,
use_field_number=False,
descriptor_pool=None,
message_formatter=None,
print_unknown_fields=False,
force_colon=False):
"""Initialize the Printer.
Double values can be formatted compactly with 15 digits of precision
(which is the most that IEEE 754 "double" can guarantee) using
double_format='.15g'. To ensure that converting to text and back to a proto
will result in an identical value, double_format='.17g' should be used.
Args:
out: To record the text format result.
indent: The initial indent level for pretty print.
as_utf8: Return unescaped Unicode for non-ASCII characters.
In Python 3 actual Unicode characters may appear as is in strings.
In Python 2 the return value will be valid UTF-8 rather than ASCII.
as_one_line: Don't introduce newlines between fields.
use_short_repeated_primitives: Use short repeated format for primitives.
pointy_brackets: If True, use angle brackets instead of curly braces for
nesting.
use_index_order: If True, print fields of a proto message using the order
defined in source code instead of the field number. By default, use the
field number order.
float_format: If set, use this to specify float field formatting
(per the "Format Specification Mini-Language"); otherwise, shortest
float that has same value in wire will be printed. Also affect double
field if double_format is not set but float_format is set.
double_format: If set, use this to specify double field formatting
(per the "Format Specification Mini-Language"); if it is not set but
float_format is set, use float_format. Otherwise, str() is used.
use_field_number: If True, print field numbers instead of names.
descriptor_pool: A DescriptorPool used to resolve Any types.
message_formatter: A function(message, indent, as_one_line): unicode|None
to custom format selected sub-messages (usually based on message type).
Use to pretty print parts of the protobuf for easier diffing.
print_unknown_fields: If True, unknown fields will be printed.
force_colon: If set, a colon will be added after the field name even if
the field is a proto message.
"""
self.out = out
self.indent = indent
self.as_utf8 = as_utf8
self.as_one_line = as_one_line
self.use_short_repeated_primitives = use_short_repeated_primitives
self.pointy_brackets = pointy_brackets
self.use_index_order = use_index_order
self.float_format = float_format
if double_format is not None:
self.double_format = double_format
else:
self.double_format = float_format
self.use_field_number = use_field_number
self.descriptor_pool = descriptor_pool
self.message_formatter = message_formatter
self.print_unknown_fields = print_unknown_fields
self.force_colon = force_colon | [
"def",
"__init__",
"(",
"self",
",",
"out",
",",
"indent",
"=",
"0",
",",
"as_utf8",
"=",
"False",
",",
"as_one_line",
"=",
"False",
",",
"use_short_repeated_primitives",
"=",
"False",
",",
"pointy_brackets",
"=",
"False",
",",
"use_index_order",
"=",
"False... | https://github.com/papyrussolution/OpenPapyrus/blob/bbfb5ec2ea2109b8e2f125edd838e12eaf7b8b91/Src/OSF/protobuf-3.19.1/python/google/protobuf/text_format.py#L323-L391 | ||
bigartm/bigartm | 47e37f982de87aa67bfd475ff1f39da696b181b3 | python/artm/artm_model.py | python | ARTM.remove_theta | (self) | :Description: removes cached theta matrix | :Description: removes cached theta matrix | [
":",
"Description",
":",
"removes",
"cached",
"theta",
"matrix"
] | def remove_theta(self):
"""
:Description: removes cached theta matrix
"""
self.master.clear_theta_cache() | [
"def",
"remove_theta",
"(",
"self",
")",
":",
"self",
".",
"master",
".",
"clear_theta_cache",
"(",
")"
] | https://github.com/bigartm/bigartm/blob/47e37f982de87aa67bfd475ff1f39da696b181b3/python/artm/artm_model.py#L962-L966 | ||
albertz/openlierox | d316c14a8eb57848ef56e9bfa7b23a56f694a51b | tools/DedicatedServerVideo/gdata/youtube/service.py | python | YouTubeService.AddSubscriptionToQuery | (self, query, my_username = 'default') | return self.Post(subscription_entry, post_uri,
converter=gdata.youtube.YouTubeSubscriptionEntryFromString) | Add a new subscription to a specific keyword query to the currently
authenticated user's account.
Needs authentication
Args:
query: A string representing the keyword query to subscribe to.
my_username: An optional string representing the username of the user
that is to be subscribed. Defaults to currently authenticated user.
Returns:
A new YouTubeSubscriptionEntry if successful. | Add a new subscription to a specific keyword query to the currently
authenticated user's account. | [
"Add",
"a",
"new",
"subscription",
"to",
"a",
"specific",
"keyword",
"query",
"to",
"the",
"currently",
"authenticated",
"user",
"s",
"account",
"."
] | def AddSubscriptionToQuery(self, query, my_username = 'default'):
"""Add a new subscription to a specific keyword query to the currently
authenticated user's account.
Needs authentication
Args:
query: A string representing the keyword query to subscribe to.
my_username: An optional string representing the username of the user
that is to be subscribed. Defaults to currently authenticated user.
Returns:
A new YouTubeSubscriptionEntry if successful.
"""
subscription_category = atom.Category(
scheme=YOUTUBE_SUBSCRIPTION_CATEGORY_SCHEME,
term='query')
subscription_query_string = gdata.youtube.QueryString(text=query)
subscription_entry = gdata.youtube.YouTubeSubscriptionEntry(
category=subscription_category,
query_string=subscription_query_string)
post_uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, my_username,
'subscriptions')
return self.Post(subscription_entry, post_uri,
converter=gdata.youtube.YouTubeSubscriptionEntryFromString) | [
"def",
"AddSubscriptionToQuery",
"(",
"self",
",",
"query",
",",
"my_username",
"=",
"'default'",
")",
":",
"subscription_category",
"=",
"atom",
".",
"Category",
"(",
"scheme",
"=",
"YOUTUBE_SUBSCRIPTION_CATEGORY_SCHEME",
",",
"term",
"=",
"'query'",
")",
"subscr... | https://github.com/albertz/openlierox/blob/d316c14a8eb57848ef56e9bfa7b23a56f694a51b/tools/DedicatedServerVideo/gdata/youtube/service.py#L1123-L1150 | |
oracle/graaljs | 36a56e8e993d45fc40939a3a4d9c0c24990720f1 | graal-nodejs/tools/gyp/pylib/gyp/xcodeproj_file.py | python | XCObject._EncodeString | (self, value) | return '"' + _escaped.sub(self._EncodeTransform, value) + '"' | Encodes a string to be placed in the project file output, mimicking
Xcode behavior. | Encodes a string to be placed in the project file output, mimicking
Xcode behavior. | [
"Encodes",
"a",
"string",
"to",
"be",
"placed",
"in",
"the",
"project",
"file",
"output",
"mimicking",
"Xcode",
"behavior",
"."
] | def _EncodeString(self, value):
"""Encodes a string to be placed in the project file output, mimicking
Xcode behavior.
"""
# Use quotation marks when any character outside of the range A-Z, a-z, 0-9,
# $ (dollar sign), . (period), and _ (underscore) is present. Also use
# quotation marks to represent empty strings.
#
# Escape " (double-quote) and \ (backslash) by preceding them with a
# backslash.
#
# Some characters below the printable ASCII range are encoded specially:
# 7 ^G BEL is encoded as "\a"
# 8 ^H BS is encoded as "\b"
# 11 ^K VT is encoded as "\v"
# 12 ^L NP is encoded as "\f"
# 127 ^? DEL is passed through as-is without escaping
# - In PBXFileReference and PBXBuildFile objects:
# 9 ^I HT is passed through as-is without escaping
# 10 ^J NL is passed through as-is without escaping
# 13 ^M CR is passed through as-is without escaping
# - In other objects:
# 9 ^I HT is encoded as "\t"
# 10 ^J NL is encoded as "\n"
# 13 ^M CR is encoded as "\n" rendering it indistinguishable from
# 10 ^J NL
# All other characters within the ASCII control character range (0 through
# 31 inclusive) are encoded as "\U001f" referring to the Unicode code point
# in hexadecimal. For example, character 14 (^N SO) is encoded as "\U000e".
# Characters above the ASCII range are passed through to the output encoded
# as UTF-8 without any escaping. These mappings are contained in the
# class' _encode_transforms list.
if _unquoted.search(value) and not _quoted.search(value):
return value
return '"' + _escaped.sub(self._EncodeTransform, value) + '"' | [
"def",
"_EncodeString",
"(",
"self",
",",
"value",
")",
":",
"# Use quotation marks when any character outside of the range A-Z, a-z, 0-9,",
"# $ (dollar sign), . (period), and _ (underscore) is present. Also use",
"# quotation marks to represent empty strings.",
"#",
"# Escape \" (double-q... | https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/tools/gyp/pylib/gyp/xcodeproj_file.py#L545-L582 | |
apache/mesos | 97d9a4063332aae3825d78de71611657e05cf5e2 | src/python/cli_new/lib/cli/mesos.py | python | TaskIO._detect_exit_sequence | (self, chunk) | return chunk | Detects if 'self.exit_sequence' is present in 'chunk'.
If a partial exit sequence is detected at the end of 'chunk', then
more characters are read from 'stdin' and appended to 'chunk' in
search of the full sequence. Since python cannot pass variables by
reference, we return a modified 'chunk' with the extra characters
read if necessary.
If the exit sequence is found, the class variable
'exit_sequence_detected' is set to True.
:param chunk: a byte array to search for the exit sequence in
:type chunk: byte array
:returns: a modified byte array containing the original 'chunk' plus
any extra characters read in search of the exit sequence
:rtype: byte array | Detects if 'self.exit_sequence' is present in 'chunk'. | [
"Detects",
"if",
"self",
".",
"exit_sequence",
"is",
"present",
"in",
"chunk",
"."
] | def _detect_exit_sequence(self, chunk):
"""
Detects if 'self.exit_sequence' is present in 'chunk'.
If a partial exit sequence is detected at the end of 'chunk', then
more characters are read from 'stdin' and appended to 'chunk' in
search of the full sequence. Since python cannot pass variables by
reference, we return a modified 'chunk' with the extra characters
read if necessary.
If the exit sequence is found, the class variable
'exit_sequence_detected' is set to True.
:param chunk: a byte array to search for the exit sequence in
:type chunk: byte array
:returns: a modified byte array containing the original 'chunk' plus
any extra characters read in search of the exit sequence
:rtype: byte array
"""
if not self.supports_exit_sequence:
return chunk
if chunk.find(self.exit_sequence) != -1:
self.exit_sequence_detected = True
return chunk
for i in reversed(range(1, len(self.exit_sequence))):
if self.exit_sequence[:-i] == chunk[len(chunk)-i:]:
chunk += os.read(sys.stdin.fileno(), 1)
return self._detect_exit_sequence(chunk)
return chunk | [
"def",
"_detect_exit_sequence",
"(",
"self",
",",
"chunk",
")",
":",
"if",
"not",
"self",
".",
"supports_exit_sequence",
":",
"return",
"chunk",
"if",
"chunk",
".",
"find",
"(",
"self",
".",
"exit_sequence",
")",
"!=",
"-",
"1",
":",
"self",
".",
"exit_s... | https://github.com/apache/mesos/blob/97d9a4063332aae3825d78de71611657e05cf5e2/src/python/cli_new/lib/cli/mesos.py#L740-L771 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | contrib/gizmos/gtk/gizmos.py | python | StaticPicture.SetCustomScale | (*args, **kwargs) | return _gizmos.StaticPicture_SetCustomScale(*args, **kwargs) | SetCustomScale(self, float sx, float sy) | SetCustomScale(self, float sx, float sy) | [
"SetCustomScale",
"(",
"self",
"float",
"sx",
"float",
"sy",
")"
] | def SetCustomScale(*args, **kwargs):
"""SetCustomScale(self, float sx, float sy)"""
return _gizmos.StaticPicture_SetCustomScale(*args, **kwargs) | [
"def",
"SetCustomScale",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gizmos",
".",
"StaticPicture_SetCustomScale",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/contrib/gizmos/gtk/gizmos.py#L1031-L1033 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/fitting_widgets/general_fitting/general_fitting_options_view.py | python | GeneralFittingOptionsView.__init__ | (self, parent: QWidget = None) | Initializes the GeneralFittingOptionsView. By default the simultaneous options are disabled. | Initializes the GeneralFittingOptionsView. By default the simultaneous options are disabled. | [
"Initializes",
"the",
"GeneralFittingOptionsView",
".",
"By",
"default",
"the",
"simultaneous",
"options",
"are",
"disabled",
"."
] | def __init__(self, parent: QWidget = None):
"""Initializes the GeneralFittingOptionsView. By default the simultaneous options are disabled."""
super(GeneralFittingOptionsView, self).__init__(parent)
self.setupUi(self)
self.disable_simultaneous_fit_options()
self._setup_simultaneous_fit_by_combo_box(MA_FIT_BY_OPTIONS) | [
"def",
"__init__",
"(",
"self",
",",
"parent",
":",
"QWidget",
"=",
"None",
")",
":",
"super",
"(",
"GeneralFittingOptionsView",
",",
"self",
")",
".",
"__init__",
"(",
"parent",
")",
"self",
".",
"setupUi",
"(",
"self",
")",
"self",
".",
"disable_simult... | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/fitting_widgets/general_fitting/general_fitting_options_view.py#L21-L28 | ||
asLody/whale | 6a661b27cc4cf83b7b5a3b02451597ee1ac7f264 | whale/cpplint.py | python | NestingState.InAsmBlock | (self) | return self.stack and self.stack[-1].inline_asm != _NO_ASM | Check if we are currently one level inside an inline ASM block.
Returns:
True if the top of the stack is a block containing inline ASM. | Check if we are currently one level inside an inline ASM block. | [
"Check",
"if",
"we",
"are",
"currently",
"one",
"level",
"inside",
"an",
"inline",
"ASM",
"block",
"."
] | def InAsmBlock(self):
"""Check if we are currently one level inside an inline ASM block.
Returns:
True if the top of the stack is a block containing inline ASM.
"""
return self.stack and self.stack[-1].inline_asm != _NO_ASM | [
"def",
"InAsmBlock",
"(",
"self",
")",
":",
"return",
"self",
".",
"stack",
"and",
"self",
".",
"stack",
"[",
"-",
"1",
"]",
".",
"inline_asm",
"!=",
"_NO_ASM"
] | https://github.com/asLody/whale/blob/6a661b27cc4cf83b7b5a3b02451597ee1ac7f264/whale/cpplint.py#L2465-L2471 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/base64.py | python | decodestring | (s) | return decodebytes(s) | Legacy alias of decodebytes(). | Legacy alias of decodebytes(). | [
"Legacy",
"alias",
"of",
"decodebytes",
"()",
"."
] | def decodestring(s):
"""Legacy alias of decodebytes()."""
import warnings
warnings.warn("decodestring() is a deprecated alias since Python 3.1, "
"use decodebytes()",
DeprecationWarning, 2)
return decodebytes(s) | [
"def",
"decodestring",
"(",
"s",
")",
":",
"import",
"warnings",
"warnings",
".",
"warn",
"(",
"\"decodestring() is a deprecated alias since Python 3.1, \"",
"\"use decodebytes()\"",
",",
"DeprecationWarning",
",",
"2",
")",
"return",
"decodebytes",
"(",
"s",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/base64.py#L548-L554 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/richtext.py | python | RichTextCtrl.EndSuppressUndo | (*args, **kwargs) | return _richtext.RichTextCtrl_EndSuppressUndo(*args, **kwargs) | EndSuppressUndo(self) -> bool
End suppressing undo history for commands. | EndSuppressUndo(self) -> bool | [
"EndSuppressUndo",
"(",
"self",
")",
"-",
">",
"bool"
] | def EndSuppressUndo(*args, **kwargs):
"""
EndSuppressUndo(self) -> bool
End suppressing undo history for commands.
"""
return _richtext.RichTextCtrl_EndSuppressUndo(*args, **kwargs) | [
"def",
"EndSuppressUndo",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_richtext",
".",
"RichTextCtrl_EndSuppressUndo",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/richtext.py#L3877-L3883 | |
pisa-engine/pisa | 0efb7926d4928c8aae672ba4d7a1419891f2676d | script/ext/baker.py | python | Baker.return_individual_keyword_doc | (self, cmd, keyname, head, rindent=None) | return ret | Return documentation for optional arguments. | Return documentation for optional arguments. | [
"Return",
"documentation",
"for",
"optional",
"arguments",
"."
] | def return_individual_keyword_doc(self, cmd, keyname, head, rindent=None):
"""
Return documentation for optional arguments.
"""
ret = []
if rindent is None:
rindent = len(head) + 2
if keyname in cmd.paramdocs:
paras = process_docstring(cmd.paramdocs.get(keyname, ""))
formatted = format_paras(paras, 76, indent=rindent, lstripline=[0])
ret.append(" " + head + formatted[0])
for line in formatted[1:]:
ret.append(" " + line)
else:
ret.append(" " + head.rstrip())
return ret | [
"def",
"return_individual_keyword_doc",
"(",
"self",
",",
"cmd",
",",
"keyname",
",",
"head",
",",
"rindent",
"=",
"None",
")",
":",
"ret",
"=",
"[",
"]",
"if",
"rindent",
"is",
"None",
":",
"rindent",
"=",
"len",
"(",
"head",
")",
"+",
"2",
"if",
... | https://github.com/pisa-engine/pisa/blob/0efb7926d4928c8aae672ba4d7a1419891f2676d/script/ext/baker.py#L483-L498 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/flatmenu.py | python | MenuEntryInfo.SetTextBitmap | (self, bmp) | Sets the associated menu bitmap.
:param `bmp`: a valid :class:`Bitmap` object. | Sets the associated menu bitmap. | [
"Sets",
"the",
"associated",
"menu",
"bitmap",
"."
] | def SetTextBitmap(self, bmp):
"""
Sets the associated menu bitmap.
:param `bmp`: a valid :class:`Bitmap` object.
"""
self._textBmp = bmp | [
"def",
"SetTextBitmap",
"(",
"self",
",",
"bmp",
")",
":",
"self",
".",
"_textBmp",
"=",
"bmp"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/flatmenu.py#L2304-L2311 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/dataclasses.py | python | make_dataclass | (cls_name, fields, *, bases=(), namespace=None, init=True,
repr=True, eq=True, order=False, unsafe_hash=False,
frozen=False) | return dataclass(cls, init=init, repr=repr, eq=eq, order=order,
unsafe_hash=unsafe_hash, frozen=frozen) | Return a new dynamically created dataclass.
The dataclass name will be 'cls_name'. 'fields' is an iterable
of either (name), (name, type) or (name, type, Field) objects. If type is
omitted, use the string 'typing.Any'. Field objects are created by
the equivalent of calling 'field(name, type [, Field-info])'.
C = make_dataclass('C', ['x', ('y', int), ('z', int, field(init=False))], bases=(Base,))
is equivalent to:
@dataclass
class C(Base):
x: 'typing.Any'
y: int
z: int = field(init=False)
For the bases and namespace parameters, see the builtin type() function.
The parameters init, repr, eq, order, unsafe_hash, and frozen are passed to
dataclass(). | Return a new dynamically created dataclass. | [
"Return",
"a",
"new",
"dynamically",
"created",
"dataclass",
"."
] | def make_dataclass(cls_name, fields, *, bases=(), namespace=None, init=True,
repr=True, eq=True, order=False, unsafe_hash=False,
frozen=False):
"""Return a new dynamically created dataclass.
The dataclass name will be 'cls_name'. 'fields' is an iterable
of either (name), (name, type) or (name, type, Field) objects. If type is
omitted, use the string 'typing.Any'. Field objects are created by
the equivalent of calling 'field(name, type [, Field-info])'.
C = make_dataclass('C', ['x', ('y', int), ('z', int, field(init=False))], bases=(Base,))
is equivalent to:
@dataclass
class C(Base):
x: 'typing.Any'
y: int
z: int = field(init=False)
For the bases and namespace parameters, see the builtin type() function.
The parameters init, repr, eq, order, unsafe_hash, and frozen are passed to
dataclass().
"""
if namespace is None:
namespace = {}
else:
# Copy namespace since we're going to mutate it.
namespace = namespace.copy()
# While we're looking through the field names, validate that they
# are identifiers, are not keywords, and not duplicates.
seen = set()
anns = {}
for item in fields:
if isinstance(item, str):
name = item
tp = 'typing.Any'
elif len(item) == 2:
name, tp, = item
elif len(item) == 3:
name, tp, spec = item
namespace[name] = spec
else:
raise TypeError(f'Invalid field: {item!r}')
if not isinstance(name, str) or not name.isidentifier():
raise TypeError(f'Field names must be valid identifiers: {name!r}')
if keyword.iskeyword(name):
raise TypeError(f'Field names must not be keywords: {name!r}')
if name in seen:
raise TypeError(f'Field name duplicated: {name!r}')
seen.add(name)
anns[name] = tp
namespace['__annotations__'] = anns
# We use `types.new_class()` instead of simply `type()` to allow dynamic creation
# of generic dataclassses.
cls = types.new_class(cls_name, bases, {}, lambda ns: ns.update(namespace))
return dataclass(cls, init=init, repr=repr, eq=eq, order=order,
unsafe_hash=unsafe_hash, frozen=frozen) | [
"def",
"make_dataclass",
"(",
"cls_name",
",",
"fields",
",",
"*",
",",
"bases",
"=",
"(",
")",
",",
"namespace",
"=",
"None",
",",
"init",
"=",
"True",
",",
"repr",
"=",
"True",
",",
"eq",
"=",
"True",
",",
"order",
"=",
"False",
",",
"unsafe_hash... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/dataclasses.py#L1170-L1233 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/dataview.py | python | DataViewVirtualListModel.IsEnabledByRow | (*args, **kwargs) | return _dataview.DataViewVirtualListModel_IsEnabledByRow(*args, **kwargs) | IsEnabledByRow(self, unsigned int row, unsigned int col) -> bool | IsEnabledByRow(self, unsigned int row, unsigned int col) -> bool | [
"IsEnabledByRow",
"(",
"self",
"unsigned",
"int",
"row",
"unsigned",
"int",
"col",
")",
"-",
">",
"bool"
] | def IsEnabledByRow(*args, **kwargs):
"""IsEnabledByRow(self, unsigned int row, unsigned int col) -> bool"""
return _dataview.DataViewVirtualListModel_IsEnabledByRow(*args, **kwargs) | [
"def",
"IsEnabledByRow",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_dataview",
".",
"DataViewVirtualListModel_IsEnabledByRow",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/dataview.py#L997-L999 | |
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/python/ops/script_ops.py | python | py_func | (func, inp, Tout, stateful=True, name=None) | return result if is_list_or_tuple else result[0] | Wraps a python function and uses it as a TensorFlow op.
Given a python function `func`, which takes numpy arrays as its
inputs and returns numpy arrays as its outputs, wrap this function as an
operation in a TensorFlow graph. The following snippet constructs a simple
TensorFlow graph that invokes the `np.sinh()` NumPy function as a operation
in the graph:
```python
def my_func(x):
# x will be a numpy array with the contents of the placeholder below
return np.sinh(x)
inp = tf.placeholder(tf.float32)
y = tf.py_func(my_func, [inp], tf.float32)
```
**N.B.** The `tf.py_func()` operation has the following known limitations:
* The body of the function (i.e. `func`) will not be serialized in a
`GraphDef`. Therefore, you should not use this function if you need to
serialize your model and restore it in a different environment.
* The operation must run in the same address space as the Python program
that calls `tf.py_func()`. If you are using distributed TensorFlow, you
must run a `tf.train.Server` in the same process as the program that calls
`tf.py_func()` and you must pin the created operation to a device in that
server (e.g. using `with tf.device():`).
Args:
func: A Python function, which accepts a list of NumPy `ndarray` objects
having element types that match the corresponding `tf.Tensor` objects
in `inp`, and returns a list of `ndarray` objects (or a single `ndarray`)
having element types that match the corresponding values in `Tout`.
inp: A list of `Tensor` objects.
Tout: A list or tuple of tensorflow data types or a single tensorflow data
type if there is only one, indicating what `func` returns.
stateful: (Boolean.) If True, the function should be considered stateful.
If a function is stateless, when given the same input it will return the
same output and have no observable side effects. Optimizations such as
common subexpression elimination are only performed on stateless
operations.
name: A name for the operation (optional).
Returns:
A list of `Tensor` or a single `Tensor` which `func` computes. | Wraps a python function and uses it as a TensorFlow op. | [
"Wraps",
"a",
"python",
"function",
"and",
"uses",
"it",
"as",
"a",
"TensorFlow",
"op",
"."
] | def py_func(func, inp, Tout, stateful=True, name=None):
"""Wraps a python function and uses it as a TensorFlow op.
Given a python function `func`, which takes numpy arrays as its
inputs and returns numpy arrays as its outputs, wrap this function as an
operation in a TensorFlow graph. The following snippet constructs a simple
TensorFlow graph that invokes the `np.sinh()` NumPy function as a operation
in the graph:
```python
def my_func(x):
# x will be a numpy array with the contents of the placeholder below
return np.sinh(x)
inp = tf.placeholder(tf.float32)
y = tf.py_func(my_func, [inp], tf.float32)
```
**N.B.** The `tf.py_func()` operation has the following known limitations:
* The body of the function (i.e. `func`) will not be serialized in a
`GraphDef`. Therefore, you should not use this function if you need to
serialize your model and restore it in a different environment.
* The operation must run in the same address space as the Python program
that calls `tf.py_func()`. If you are using distributed TensorFlow, you
must run a `tf.train.Server` in the same process as the program that calls
`tf.py_func()` and you must pin the created operation to a device in that
server (e.g. using `with tf.device():`).
Args:
func: A Python function, which accepts a list of NumPy `ndarray` objects
having element types that match the corresponding `tf.Tensor` objects
in `inp`, and returns a list of `ndarray` objects (or a single `ndarray`)
having element types that match the corresponding values in `Tout`.
inp: A list of `Tensor` objects.
Tout: A list or tuple of tensorflow data types or a single tensorflow data
type if there is only one, indicating what `func` returns.
stateful: (Boolean.) If True, the function should be considered stateful.
If a function is stateless, when given the same input it will return the
same output and have no observable side effects. Optimizations such as
common subexpression elimination are only performed on stateless
operations.
name: A name for the operation (optional).
Returns:
A list of `Tensor` or a single `Tensor` which `func` computes.
"""
token = _py_funcs.insert(func)
# We tie the registered function's life-time with the current
# default graph. I.e., when the current graph is destroyed, we
# should remove its py funcs.
g = ops.get_default_graph()
# pylint: disable=protected-access
while isinstance(g, function._FuncGraph):
# If the py_func was declared inside a _FuncGraph, its lifetime should be
# bound to that of the outer graph instead.
g = g._outer_graph
cleanup = CleanupFunc(token)
# TODO(zhifengc): Consider adding a Graph method to collect
# `cleanup` objects in one of its member.
if not hasattr(g, "_cleanup_py_funcs_used_in_graph"):
g._cleanup_py_funcs_used_in_graph = []
# When g is destroyed, elements in _cleanup_py_funcs_used_in_graph
# will be destroyed and their __del__ will remove the 'token' from
# the funcs registry.
g._cleanup_py_funcs_used_in_graph.append(cleanup)
# pylint: enable=protected-access
if isinstance(Tout, (list, tuple)):
is_list_or_tuple = True
else:
Tout = [Tout]
is_list_or_tuple = False
# pylint: disable=protected-access
if stateful:
result = gen_script_ops._py_func(
input=inp, token=token, Tout=Tout, name=name)
else:
result = gen_script_ops._py_func_stateless(
input=inp, token=token, Tout=Tout, name=name)
# pylint: enable=protected-access
return result if is_list_or_tuple else result[0] | [
"def",
"py_func",
"(",
"func",
",",
"inp",
",",
"Tout",
",",
"stateful",
"=",
"True",
",",
"name",
"=",
"None",
")",
":",
"token",
"=",
"_py_funcs",
".",
"insert",
"(",
"func",
")",
"# We tie the registered function's life-time with the current",
"# default grap... | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/ops/script_ops.py#L123-L208 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/distribute/cross_device_utils.py | python | group_by_size | (input_tensors, bytes_per_pack) | return packs | Groups `input_tensors` into chunks of `bytes_per_pack`.
The method preserves the original order of `input_tensors`. The grouping is
best effort, each pack could have more or less bytes than `bytes_per_pack`.
It only groups values with known shape.
Args:
input_tensors: a list of Tensor.
bytes_per_pack: an integer.
Returns:
A list of packs of Tensor. All values are grouped into one pack if
`bytes_per_pack` is zero or any of the value has unknown shape. | Groups `input_tensors` into chunks of `bytes_per_pack`. | [
"Groups",
"input_tensors",
"into",
"chunks",
"of",
"bytes_per_pack",
"."
] | def group_by_size(input_tensors, bytes_per_pack):
"""Groups `input_tensors` into chunks of `bytes_per_pack`.
The method preserves the original order of `input_tensors`. The grouping is
best effort, each pack could have more or less bytes than `bytes_per_pack`.
It only groups values with known shape.
Args:
input_tensors: a list of Tensor.
bytes_per_pack: an integer.
Returns:
A list of packs of Tensor. All values are grouped into one pack if
`bytes_per_pack` is zero or any of the value has unknown shape.
"""
if bytes_per_pack == 0:
return [input_tensors]
packs = []
last_pack_size = 0
for value in input_tensors:
num_elements = value.shape.num_elements()
if num_elements is None:
# Can't pack values with unknown shape.
logging.warning(
'not packing values due to the unknown or inconsistent shape of %s',
value)
return [input_tensors]
size = num_elements * value.dtype.size
# Try to keep each pack as close to bytes_per_pack as possible, while each
# pack is at least bytes_per_pack large. I.E. we err on the side of having
# few but large packs.
if not packs or last_pack_size > bytes_per_pack:
packs.append([])
last_pack_size = 0
packs[-1].append(value)
last_pack_size += size
return packs | [
"def",
"group_by_size",
"(",
"input_tensors",
",",
"bytes_per_pack",
")",
":",
"if",
"bytes_per_pack",
"==",
"0",
":",
"return",
"[",
"input_tensors",
"]",
"packs",
"=",
"[",
"]",
"last_pack_size",
"=",
"0",
"for",
"value",
"in",
"input_tensors",
":",
"num_e... | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/distribute/cross_device_utils.py#L666-L703 | |
glotzerlab/hoomd-blue | f7f97abfa3fcc2522fa8d458d65d0aeca7ba781a | hoomd/write/table.py | python | _TableInternal._get_log_dict | (self) | return {
key: value[0]
for key, value in dict_flatten(self.logger.log()).items()
} | Get a flattened dict for writing to output. | Get a flattened dict for writing to output. | [
"Get",
"a",
"flattened",
"dict",
"for",
"writing",
"to",
"output",
"."
] | def _get_log_dict(self):
"""Get a flattened dict for writing to output."""
return {
key: value[0]
for key, value in dict_flatten(self.logger.log()).items()
} | [
"def",
"_get_log_dict",
"(",
"self",
")",
":",
"return",
"{",
"key",
":",
"value",
"[",
"0",
"]",
"for",
"key",
",",
"value",
"in",
"dict_flatten",
"(",
"self",
".",
"logger",
".",
"log",
"(",
")",
")",
".",
"items",
"(",
")",
"}"
] | https://github.com/glotzerlab/hoomd-blue/blob/f7f97abfa3fcc2522fa8d458d65d0aeca7ba781a/hoomd/write/table.py#L232-L237 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/stc.py | python | StyledTextCtrl.MarkerDefineRGBAImage | (*args, **kwargs) | return _stc.StyledTextCtrl_MarkerDefineRGBAImage(*args, **kwargs) | MarkerDefineRGBAImage(self, int markerNumber, unsigned char pixels) | MarkerDefineRGBAImage(self, int markerNumber, unsigned char pixels) | [
"MarkerDefineRGBAImage",
"(",
"self",
"int",
"markerNumber",
"unsigned",
"char",
"pixels",
")"
] | def MarkerDefineRGBAImage(*args, **kwargs):
"""MarkerDefineRGBAImage(self, int markerNumber, unsigned char pixels)"""
return _stc.StyledTextCtrl_MarkerDefineRGBAImage(*args, **kwargs) | [
"def",
"MarkerDefineRGBAImage",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextCtrl_MarkerDefineRGBAImage",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/stc.py#L6369-L6371 | |
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/python/ops/math_grad.py | python | _SinGrad | (op, grad) | Returns grad * cos(x). | Returns grad * cos(x). | [
"Returns",
"grad",
"*",
"cos",
"(",
"x",
")",
"."
] | def _SinGrad(op, grad):
"""Returns grad * cos(x)."""
x = op.inputs[0]
with ops.control_dependencies([grad.op]):
x = math_ops.conj(x)
return grad * math_ops.cos(x) | [
"def",
"_SinGrad",
"(",
"op",
",",
"grad",
")",
":",
"x",
"=",
"op",
".",
"inputs",
"[",
"0",
"]",
"with",
"ops",
".",
"control_dependencies",
"(",
"[",
"grad",
".",
"op",
"]",
")",
":",
"x",
"=",
"math_ops",
".",
"conj",
"(",
"x",
")",
"return... | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/ops/math_grad.py#L476-L481 | ||
rdkit/rdkit | ede860ae316d12d8568daf5ee800921c3389c84e | rdkit/sping/colors.py | python | Color.toHexRGB | (self) | return (r << 16) + (g << 8) + b | Convert the color back to an integer suitable for the | Convert the color back to an integer suitable for the | [
"Convert",
"the",
"color",
"back",
"to",
"an",
"integer",
"suitable",
"for",
"the"
] | def toHexRGB(self):
"Convert the color back to an integer suitable for the "
"0xRRGGBB hex representation"
r = int(0xFF * self.red)
g = int(0xFF * self.green)
b = int(0xFF * self.blue)
# print "r= %d, g=%d, b = %d" % (r,b,g)
return (r << 16) + (g << 8) + b | [
"def",
"toHexRGB",
"(",
"self",
")",
":",
"\"0xRRGGBB hex representation\"",
"r",
"=",
"int",
"(",
"0xFF",
"*",
"self",
".",
"red",
")",
"g",
"=",
"int",
"(",
"0xFF",
"*",
"self",
".",
"green",
")",
"b",
"=",
"int",
"(",
"0xFF",
"*",
"self",
".",
... | https://github.com/rdkit/rdkit/blob/ede860ae316d12d8568daf5ee800921c3389c84e/rdkit/sping/colors.py#L59-L66 | |
verilog-to-routing/vtr-verilog-to-routing | d9719cf7374821156c3cee31d66991cb85578562 | vtr_flow/scripts/python_libs/vtr/parse_vtr_task.py | python | check_two_files | (
config,
first_results_filepath,
second_results_filepath,
first_name="task",
second_name="golden",
) | return num_qor_failures | Compare two files results | Compare two files results | [
"Compare",
"two",
"files",
"results"
] | def check_two_files(
config,
first_results_filepath,
second_results_filepath,
first_name="task",
second_name="golden",
):
"""Compare two files results"""
first_results = load_parse_results(first_results_filepath)
second_results = load_parse_results(second_results_filepath)
# Verify that the architecture and circuit are specified
for param in ["architecture", "circuit", "script_params"]:
if param not in first_results.PRIMARY_KEYS:
raise InspectError(
"Required param '{}' missing from {} results: {}".format(
param, first_name, first_results_filepath
),
first_results_filepath,
)
if param not in second_results.PRIMARY_KEYS:
raise InspectError(
"Required param '{}' missing from {} results: {}".format(
param, second_name, second_results_filepath
),
second_results_filepath,
)
# Verify that all params and pass requirement metric are included in both the result files
# We do not worry about non-pass_requriements elements being different or missing
pass_req_filepath = str(paths.pass_requirements_path / config.pass_requirements_file)
pass_requirements = load_pass_requirements(pass_req_filepath)
for metric in pass_requirements.keys():
for (
(arch, circuit, script_params),
result,
) in first_results.all_metrics().items():
if metric not in result:
raise InspectError(
"Required metric '{}' missing from {} results".format(metric, first_name),
first_results_filepath,
)
for (
(arch, circuit, script_params),
result,
) in second_results.all_metrics().items():
if metric not in result:
raise InspectError(
"Required metric '{}' missing from {} results".format(metric, second_name),
second_results_filepath,
)
# Load the primary keys for result files
second_primary_keys = []
for (arch, circuit, script_params), _ in second_results.all_metrics().items():
second_primary_keys.append((arch, circuit, script_params))
first_primary_keys = []
for (arch, circuit, script_params), _ in first_results.all_metrics().items():
first_primary_keys.append((arch, circuit, script_params))
# Ensure that first result file has all the second result file cases
for arch, circuit, script_params in second_primary_keys:
if first_results.metrics(arch, circuit, script_params) is None:
raise InspectError(
"Required case {}/{} missing from {} results: {}".format(
arch, circuit, first_name, first_results_filepath
)
)
# Warn about any elements in first result file that are not found in second result file
for arch, circuit, script_params in first_primary_keys:
if second_results.metrics(arch, circuit, script_params) is None:
print(
"Warning: {} includes result for {}/{} missing in {} results".format(
first_name, arch, circuit, second_name
)
)
num_qor_failures = 0
# Verify that the first results pass each metric for all cases in the second results
for (arch, circuit, script_params) in second_primary_keys:
second_metrics = second_results.metrics(arch, circuit, script_params)
first_metrics = first_results.metrics(arch, circuit, script_params)
first_fail = True
for metric in pass_requirements.keys():
if not metric in second_metrics:
print("Warning: Metric {} missing from {} results".format(metric, second_name))
continue
if not metric in first_metrics:
print("Warning: Metric {} missing from {} results".format(metric, first_name))
continue
try:
metric_passed, reason = pass_requirements[metric].check_passed(
second_metrics[metric], first_metrics[metric], second_name
)
except InspectError as error:
metric_passed = False
reason = error.msg
if not metric_passed:
if first_fail:
print(
"\n{}...[Fail]".format(
"/".join(str((Path(config.config_dir).parent)).split("/")[-3:])
)
)
first_fail = False
print("[Fail]\n{}/{}/{} {} {}".format(arch, circuit, script_params, metric, reason))
num_qor_failures += 1
return num_qor_failures | [
"def",
"check_two_files",
"(",
"config",
",",
"first_results_filepath",
",",
"second_results_filepath",
",",
"first_name",
"=",
"\"task\"",
",",
"second_name",
"=",
"\"golden\"",
",",
")",
":",
"first_results",
"=",
"load_parse_results",
"(",
"first_results_filepath",
... | https://github.com/verilog-to-routing/vtr-verilog-to-routing/blob/d9719cf7374821156c3cee31d66991cb85578562/vtr_flow/scripts/python_libs/vtr/parse_vtr_task.py#L343-L457 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.