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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
oracle/graaljs | 36a56e8e993d45fc40939a3a4d9c0c24990720f1 | graal-nodejs/tools/inspector_protocol/jinja2/environment.py | python | Environment.get_or_select_template | (self, template_name_or_list,
parent=None, globals=None) | return self.select_template(template_name_or_list, parent, globals) | Does a typecheck and dispatches to :meth:`select_template`
if an iterable of template names is given, otherwise to
:meth:`get_template`.
.. versionadded:: 2.3 | Does a typecheck and dispatches to :meth:`select_template`
if an iterable of template names is given, otherwise to
:meth:`get_template`. | [
"Does",
"a",
"typecheck",
"and",
"dispatches",
"to",
":",
"meth",
":",
"select_template",
"if",
"an",
"iterable",
"of",
"template",
"names",
"is",
"given",
"otherwise",
"to",
":",
"meth",
":",
"get_template",
"."
] | def get_or_select_template(self, template_name_or_list,
parent=None, globals=None):
"""Does a typecheck and dispatches to :meth:`select_template`
if an iterable of template names is given, otherwise to
:meth:`get_template`.
.. versionadded:: 2.3
"""
if isinstance(template_name_or_list, string_types):
return self.get_template(template_name_or_list, parent, globals)
elif isinstance(template_name_or_list, Template):
return template_name_or_list
return self.select_template(template_name_or_list, parent, globals) | [
"def",
"get_or_select_template",
"(",
"self",
",",
"template_name_or_list",
",",
"parent",
"=",
"None",
",",
"globals",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"template_name_or_list",
",",
"string_types",
")",
":",
"return",
"self",
".",
"get_template",... | https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/tools/inspector_protocol/jinja2/environment.py#L860-L872 | |
stitchEm/stitchEm | 0f399501d41ab77933677f2907f41f80ceb704d7 | lib/bindings/samples/server/glfw.py | python | set_window_close_callback | (window, cbfun) | Sets the close callback for the specified window.
Wrapper for:
GLFWwindowclosefun glfwSetWindowCloseCallback(GLFWwindow* window, GLFWwindowclosefun cbfun); | Sets the close callback for the specified window. | [
"Sets",
"the",
"close",
"callback",
"for",
"the",
"specified",
"window",
"."
] | def set_window_close_callback(window, cbfun):
"""
Sets the close callback for the specified window.
Wrapper for:
GLFWwindowclosefun glfwSetWindowCloseCallback(GLFWwindow* window, GLFWwindowclosefun cbfun);
"""
window_addr = ctypes.cast(ctypes.pointer(window),
ctypes.POINTER(ctypes.c_long)).contents.value
if window_addr in _window_close_callback_repository:
previous_callback = _window_close_callback_repository[window_addr]
else:
previous_callback = None
if cbfun is None:
cbfun = 0
c_cbfun = _GLFWwindowclosefun(cbfun)
_window_close_callback_repository[window_addr] = (cbfun, c_cbfun)
cbfun = c_cbfun
_glfw.glfwSetWindowCloseCallback(window, cbfun)
if previous_callback is not None and previous_callback[0] != 0:
return previous_callback[0] | [
"def",
"set_window_close_callback",
"(",
"window",
",",
"cbfun",
")",
":",
"window_addr",
"=",
"ctypes",
".",
"cast",
"(",
"ctypes",
".",
"pointer",
"(",
"window",
")",
",",
"ctypes",
".",
"POINTER",
"(",
"ctypes",
".",
"c_long",
")",
")",
".",
"contents... | https://github.com/stitchEm/stitchEm/blob/0f399501d41ab77933677f2907f41f80ceb704d7/lib/bindings/samples/server/glfw.py#L1282-L1302 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/protobuf/py2/google/protobuf/internal/well_known_types.py | python | Timestamp.ToDatetime | (self) | return _EPOCH_DATETIME + timedelta(
seconds=self.seconds, microseconds=_RoundTowardZero(
self.nanos, _NANOS_PER_MICROSECOND)) | Converts Timestamp to datetime. | Converts Timestamp to datetime. | [
"Converts",
"Timestamp",
"to",
"datetime",
"."
] | def ToDatetime(self):
"""Converts Timestamp to datetime."""
return _EPOCH_DATETIME + timedelta(
seconds=self.seconds, microseconds=_RoundTowardZero(
self.nanos, _NANOS_PER_MICROSECOND)) | [
"def",
"ToDatetime",
"(",
"self",
")",
":",
"return",
"_EPOCH_DATETIME",
"+",
"timedelta",
"(",
"seconds",
"=",
"self",
".",
"seconds",
",",
"microseconds",
"=",
"_RoundTowardZero",
"(",
"self",
".",
"nanos",
",",
"_NANOS_PER_MICROSECOND",
")",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/protobuf/py2/google/protobuf/internal/well_known_types.py#L239-L243 | |
netket/netket | 0d534e54ecbf25b677ea72af6b85947979420652 | netket/utils/group/axial.py | python | inversion | () | return PGSymmetry(-np.eye(3)) | Returns a 3D inversion as a `PGSymmetry`. | Returns a 3D inversion as a `PGSymmetry`. | [
"Returns",
"a",
"3D",
"inversion",
"as",
"a",
"PGSymmetry",
"."
] | def inversion() -> PGSymmetry:
"""Returns a 3D inversion as a `PGSymmetry`."""
return PGSymmetry(-np.eye(3)) | [
"def",
"inversion",
"(",
")",
"->",
"PGSymmetry",
":",
"return",
"PGSymmetry",
"(",
"-",
"np",
".",
"eye",
"(",
"3",
")",
")"
] | https://github.com/netket/netket/blob/0d534e54ecbf25b677ea72af6b85947979420652/netket/utils/group/axial.py#L100-L102 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/Tkinter.py | python | Misc.wait_window | (self, window=None) | Wait until a WIDGET is destroyed.
If no parameter is given self is used. | Wait until a WIDGET is destroyed. | [
"Wait",
"until",
"a",
"WIDGET",
"is",
"destroyed",
"."
] | def wait_window(self, window=None):
"""Wait until a WIDGET is destroyed.
If no parameter is given self is used."""
if window is None:
window = self
self.tk.call('tkwait', 'window', window._w) | [
"def",
"wait_window",
"(",
"self",
",",
"window",
"=",
"None",
")",
":",
"if",
"window",
"is",
"None",
":",
"window",
"=",
"self",
"self",
".",
"tk",
".",
"call",
"(",
"'tkwait'",
",",
"'window'",
",",
"window",
".",
"_w",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/Tkinter.py#L434-L440 | ||
pytorch/pytorch | 7176c92687d3cc847cc046bf002269c6949a21c2 | torch/distributed/launcher/api.py | python | _get_entrypoint_name | (
entrypoint: Union[Callable, str, None], args: List[Any]
) | Retrive entrypoint name with the rule:
1. If entrypoint is a function, use ``entrypont.__qualname__``.
2. If entrypoint is a string, check its value:
2.1 if entrypoint equals to ``sys.executable`` (like "python"), use the first element from ``args``
which does not start with hifen letter (for example, "-u" will be skipped).
2.2 otherwise, use ``entrypoint`` value.
3. Otherwise, return empty string. | Retrive entrypoint name with the rule:
1. If entrypoint is a function, use ``entrypont.__qualname__``.
2. If entrypoint is a string, check its value:
2.1 if entrypoint equals to ``sys.executable`` (like "python"), use the first element from ``args``
which does not start with hifen letter (for example, "-u" will be skipped).
2.2 otherwise, use ``entrypoint`` value.
3. Otherwise, return empty string. | [
"Retrive",
"entrypoint",
"name",
"with",
"the",
"rule",
":",
"1",
".",
"If",
"entrypoint",
"is",
"a",
"function",
"use",
"entrypont",
".",
"__qualname__",
".",
"2",
".",
"If",
"entrypoint",
"is",
"a",
"string",
"check",
"its",
"value",
":",
"2",
".",
"... | def _get_entrypoint_name(
entrypoint: Union[Callable, str, None], args: List[Any]
) -> str:
"""Retrive entrypoint name with the rule:
1. If entrypoint is a function, use ``entrypont.__qualname__``.
2. If entrypoint is a string, check its value:
2.1 if entrypoint equals to ``sys.executable`` (like "python"), use the first element from ``args``
which does not start with hifen letter (for example, "-u" will be skipped).
2.2 otherwise, use ``entrypoint`` value.
3. Otherwise, return empty string.
"""
if isinstance(entrypoint, Callable): # type: ignore[arg-type]
return entrypoint.__name__ # type: ignore[union-attr]
elif isinstance(entrypoint, str):
if entrypoint == sys.executable:
return next((arg for arg in args if arg[0] != "-"), "")
else:
return entrypoint
else:
return "" | [
"def",
"_get_entrypoint_name",
"(",
"entrypoint",
":",
"Union",
"[",
"Callable",
",",
"str",
",",
"None",
"]",
",",
"args",
":",
"List",
"[",
"Any",
"]",
")",
"->",
"str",
":",
"if",
"isinstance",
"(",
"entrypoint",
",",
"Callable",
")",
":",
"# type: ... | https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/distributed/launcher/api.py#L134-L153 | ||
MVIG-SJTU/RMPE | 5188c230ec800c12be7369c3619615bc9b020aa4 | python/caffe/io.py | python | Transformer.set_mean | (self, in_, mean) | Set the mean to subtract for centering the data.
Parameters
----------
in_ : which input to assign this mean.
mean : mean ndarray (input dimensional or broadcastable) | Set the mean to subtract for centering the data. | [
"Set",
"the",
"mean",
"to",
"subtract",
"for",
"centering",
"the",
"data",
"."
] | def set_mean(self, in_, mean):
"""
Set the mean to subtract for centering the data.
Parameters
----------
in_ : which input to assign this mean.
mean : mean ndarray (input dimensional or broadcastable)
"""
self.__check_input(in_)
ms = mean.shape
if mean.ndim == 1:
# broadcast channels
if ms[0] != self.inputs[in_][1]:
raise ValueError('Mean channels incompatible with input.')
mean = mean[:, np.newaxis, np.newaxis]
else:
# elementwise mean
if len(ms) == 2:
ms = (1,) + ms
if len(ms) != 3:
raise ValueError('Mean shape invalid')
if ms != self.inputs[in_][1:]:
raise ValueError('Mean shape incompatible with input shape.')
self.mean[in_] = mean | [
"def",
"set_mean",
"(",
"self",
",",
"in_",
",",
"mean",
")",
":",
"self",
".",
"__check_input",
"(",
"in_",
")",
"ms",
"=",
"mean",
".",
"shape",
"if",
"mean",
".",
"ndim",
"==",
"1",
":",
"# broadcast channels",
"if",
"ms",
"[",
"0",
"]",
"!=",
... | https://github.com/MVIG-SJTU/RMPE/blob/5188c230ec800c12be7369c3619615bc9b020aa4/python/caffe/io.py#L236-L260 | ||
FEniCS/dolfinx | 3dfdf038cccdb70962865b58a63bf29c2e55ec6e | python/dolfinx/fem/formmanipulations.py | python | adjoint | (form: ufl.Form, reordered_arguments=None) | return ufl.adjoint(form, reordered_arguments=(v1, v0)) | Compute adjoint of a bilinear form by changing the ordering (count)
of the test and trial functions.
The functions wraps ``ufl.adjoint``, and by default UFL will create new
``Argument`` s. To specify the ``Argument`` s rather than creating new ones,
pass a tuple of ``Argument`` s as ``reordered_arguments``.
See the documentation for ``ufl.adjoint`` for more details. | Compute adjoint of a bilinear form by changing the ordering (count)
of the test and trial functions. | [
"Compute",
"adjoint",
"of",
"a",
"bilinear",
"form",
"by",
"changing",
"the",
"ordering",
"(",
"count",
")",
"of",
"the",
"test",
"and",
"trial",
"functions",
"."
] | def adjoint(form: ufl.Form, reordered_arguments=None) -> ufl.Form:
"""Compute adjoint of a bilinear form by changing the ordering (count)
of the test and trial functions.
The functions wraps ``ufl.adjoint``, and by default UFL will create new
``Argument`` s. To specify the ``Argument`` s rather than creating new ones,
pass a tuple of ``Argument`` s as ``reordered_arguments``.
See the documentation for ``ufl.adjoint`` for more details.
"""
if reordered_arguments is not None:
return ufl.adjoint(form, reordered_arguments=reordered_arguments)
# Extract form arguments
arguments = form.arguments()
if len(arguments) != 2:
raise RuntimeError(
"Cannot compute adjoint of form, form is not bilinear")
if any(arg.part() is not None for arg in arguments):
raise RuntimeError(
"Cannot compute adjoint of form, parts not supported")
# Create new Arguments in the same spaces (NB: Order does not matter
# anymore here because number is absolute)
v1 = function.Argument(arguments[1].function_space,
arguments[0].number(), arguments[0].part())
v0 = function.Argument(arguments[0].function_space,
arguments[1].number(), arguments[1].part())
# Return form with swapped arguments as new arguments
return ufl.adjoint(form, reordered_arguments=(v1, v0)) | [
"def",
"adjoint",
"(",
"form",
":",
"ufl",
".",
"Form",
",",
"reordered_arguments",
"=",
"None",
")",
"->",
"ufl",
".",
"Form",
":",
"if",
"reordered_arguments",
"is",
"not",
"None",
":",
"return",
"ufl",
".",
"adjoint",
"(",
"form",
",",
"reordered_argu... | https://github.com/FEniCS/dolfinx/blob/3dfdf038cccdb70962865b58a63bf29c2e55ec6e/python/dolfinx/fem/formmanipulations.py#L12-L43 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/build/waf-1.7.13/lmbrwaflib/packaging.py | python | PackageContext.is_valid_package_request | (self, **kw) | return True | Returns if the platform and configuration specified for the package_task match what the package context has been created for | Returns if the platform and configuration specified for the package_task match what the package context has been created for | [
"Returns",
"if",
"the",
"platform",
"and",
"configuration",
"specified",
"for",
"the",
"package_task",
"match",
"what",
"the",
"package",
"context",
"has",
"been",
"created",
"for"
] | def is_valid_package_request(self, **kw):
""" Returns if the platform and configuration specified for the package_task match what the package context has been created for"""
executable_name = kw.get('target', None)
if not executable_name:
Logs.warn('[WARN] Skipping package because no target was specified.')
return False
if not self.is_platform_and_config_valid(**kw):
return False
task_gen_name = kw.get('task_gen_name', executable_name)
if self.options.project_spec:
modules_in_spec = self.loaded_specs_dict[self.options.project_spec]['modules']
if task_gen_name not in modules_in_spec:
Logs.debug('package: Skipping packaging {} because it is not part of the spec {}'.format(task_gen_name, self.options.project_spec))
return False
if self.options.targets and executable_name not in self.options.targets.split(','):
Logs.debug('package: Skipping packaging {} because it is not part of the specified targets {}'.format(executable_name, self.options.targets))
return False
return True | [
"def",
"is_valid_package_request",
"(",
"self",
",",
"*",
"*",
"kw",
")",
":",
"executable_name",
"=",
"kw",
".",
"get",
"(",
"'target'",
",",
"None",
")",
"if",
"not",
"executable_name",
":",
"Logs",
".",
"warn",
"(",
"'[WARN] Skipping package because no targ... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/build/waf-1.7.13/lmbrwaflib/packaging.py#L1071-L1093 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_gdi.py | python | PseudoDC.DrawBitmap | (*args, **kwargs) | return _gdi_.PseudoDC_DrawBitmap(*args, **kwargs) | DrawBitmap(self, Bitmap bmp, int x, int y, bool useMask=False)
Draw a bitmap on the device context at the specified point. If
*transparent* is true and the bitmap has a transparency mask, (or
alpha channel on the platforms that support it) then the bitmap will
be drawn transparently. | DrawBitmap(self, Bitmap bmp, int x, int y, bool useMask=False) | [
"DrawBitmap",
"(",
"self",
"Bitmap",
"bmp",
"int",
"x",
"int",
"y",
"bool",
"useMask",
"=",
"False",
")"
] | def DrawBitmap(*args, **kwargs):
"""
DrawBitmap(self, Bitmap bmp, int x, int y, bool useMask=False)
Draw a bitmap on the device context at the specified point. If
*transparent* is true and the bitmap has a transparency mask, (or
alpha channel on the platforms that support it) then the bitmap will
be drawn transparently.
"""
return _gdi_.PseudoDC_DrawBitmap(*args, **kwargs) | [
"def",
"DrawBitmap",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gdi_",
".",
"PseudoDC_DrawBitmap",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_gdi.py#L8226-L8235 | |
hakuna-m/wubiuefi | caec1af0a09c78fd5a345180ada1fe45e0c63493 | src/pypack/altgraph/Dot.py | python | Dot.all_node_style | (self, **kwargs) | Modifies all node styles | Modifies all node styles | [
"Modifies",
"all",
"node",
"styles"
] | def all_node_style(self, **kwargs):
'''
Modifies all node styles
'''
for node in self.nodes:
self.node_style(node, **kwargs) | [
"def",
"all_node_style",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"node",
"in",
"self",
".",
"nodes",
":",
"self",
".",
"node_style",
"(",
"node",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/hakuna-m/wubiuefi/blob/caec1af0a09c78fd5a345180ada1fe45e0c63493/src/pypack/altgraph/Dot.py#L170-L175 | ||
SeisSol/SeisSol | 955fbeb8c5d40d3363a2da0edc611259aebe1653 | postprocessing/science/GroundMotionParametersMaps/ComputeGroundMotionParametersFromSurfaceOutput_Hybrid.py | python | gmrotdpp_withPG | (acceleration_x, time_step_x, acceleration_y, time_step_y, periods,
percentile, damping=0.05, units="cm/s/s", method="Nigam-Jennings") | return res | modified from gmrotdpp to also return gmrotdpp(PGA, PGV and PGD)
This is much faster than gmrotdpp_slow | modified from gmrotdpp to also return gmrotdpp(PGA, PGV and PGD)
This is much faster than gmrotdpp_slow | [
"modified",
"from",
"gmrotdpp",
"to",
"also",
"return",
"gmrotdpp",
"(",
"PGA",
"PGV",
"and",
"PGD",
")",
"This",
"is",
"much",
"faster",
"than",
"gmrotdpp_slow"
] | def gmrotdpp_withPG(acceleration_x, time_step_x, acceleration_y, time_step_y, periods,
percentile, damping=0.05, units="cm/s/s", method="Nigam-Jennings"):
"""
modified from gmrotdpp to also return gmrotdpp(PGA, PGV and PGD)
This is much faster than gmrotdpp_slow
"""
from smtk.intensity_measures import get_response_spectrum,equalise_series,rotate_horizontal
if (percentile > 100. + 1E-9) or (percentile < 0.):
raise ValueError("Percentile for GMRotDpp must be between 0. and 100.")
# Get the time-series corresponding to the SDOF
sax, _, x_a, _, _ = get_response_spectrum(acceleration_x,
time_step_x,
periods, damping,
units, method)
say, _, y_a, _, _ = get_response_spectrum(acceleration_y,
time_step_y,
periods, damping,
units, method)
x_a, y_a = equalise_series(x_a, y_a)
#TU: this is the part I m adding
#compute vel and disp from acceleration and
#add to the spectral acceleration time series
velocity_x = time_step_x * cumtrapz(acceleration_x[0:-1], initial=0.)
displacement_x = time_step_x * cumtrapz(velocity_x, initial=0.)
x_a = np.column_stack((acceleration_x[0:-1], velocity_x, displacement_x, x_a))
velocity_y = time_step_y * cumtrapz(acceleration_y[0:-1], initial=0.)
displacement_y = time_step_y * cumtrapz(velocity_y, initial=0.)
y_a = np.column_stack((acceleration_y[0:-1], velocity_y, displacement_y, y_a))
angles = np.arange(0., 90., 1.)
max_a_theta = np.zeros([len(angles), len(periods)+3], dtype=float)
max_a_theta[0, :] = np.sqrt(np.max(np.fabs(x_a), axis=0) *
np.max(np.fabs(y_a), axis=0))
for iloc, theta in enumerate(angles):
if iloc == 0:
max_a_theta[iloc, :] = np.sqrt(np.max(np.fabs(x_a), axis=0) *
np.max(np.fabs(y_a), axis=0))
else:
rot_x, rot_y = rotate_horizontal(x_a, y_a, theta)
max_a_theta[iloc, :] = np.sqrt(np.max(np.fabs(rot_x), axis=0) *
np.max(np.fabs(rot_y), axis=0))
gmrotd = np.percentile(max_a_theta, percentile, axis=0)
res = {"PGA": gmrotd[0],
"PGV": gmrotd[1],
"PGD": gmrotd[2],
"Acceleration": gmrotd[3:]}
if args.CAV:
cav = compute_cav_gmrot(acceleration_x, time_step_x, acceleration_y, time_step_y, angles, percentile)
res['CAV']=cav
return res | [
"def",
"gmrotdpp_withPG",
"(",
"acceleration_x",
",",
"time_step_x",
",",
"acceleration_y",
",",
"time_step_y",
",",
"periods",
",",
"percentile",
",",
"damping",
"=",
"0.05",
",",
"units",
"=",
"\"cm/s/s\"",
",",
"method",
"=",
"\"Nigam-Jennings\"",
")",
":",
... | https://github.com/SeisSol/SeisSol/blob/955fbeb8c5d40d3363a2da0edc611259aebe1653/postprocessing/science/GroundMotionParametersMaps/ComputeGroundMotionParametersFromSurfaceOutput_Hybrid.py#L96-L151 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/autograph/pyct/cfg.py | python | GraphBuilder.enter_loop_section | (self, section_id, entry_node) | Enters a loop section.
Loop sections define an entry node. The end of the section always flows back
to the entry node. These admit continue jump nodes which also flow to the
entry node.
Args:
section_id: Hashable, the same node that will be used in calls to the
ast_node arg passed to add_continue_node
entry_node: ast.AST, the entry node into the loop (e.g. the test node
for while loops) | Enters a loop section. | [
"Enters",
"a",
"loop",
"section",
"."
] | def enter_loop_section(self, section_id, entry_node):
"""Enters a loop section.
Loop sections define an entry node. The end of the section always flows back
to the entry node. These admit continue jump nodes which also flow to the
entry node.
Args:
section_id: Hashable, the same node that will be used in calls to the
ast_node arg passed to add_continue_node
entry_node: ast.AST, the entry node into the loop (e.g. the test node
for while loops)
"""
assert section_id not in self.section_entry
assert section_id not in self.continues
self.continues[section_id] = set()
node = self.add_ordinary_node(entry_node)
self.section_entry[section_id] = node | [
"def",
"enter_loop_section",
"(",
"self",
",",
"section_id",
",",
"entry_node",
")",
":",
"assert",
"section_id",
"not",
"in",
"self",
".",
"section_entry",
"assert",
"section_id",
"not",
"in",
"self",
".",
"continues",
"self",
".",
"continues",
"[",
"section_... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/autograph/pyct/cfg.py#L476-L493 | ||
trilinos/Trilinos | 6168be6dd51e35e1cd681e9c4b24433e709df140 | packages/seacas/scripts/exomerge3.py | python | ExodusModel._translate_element_type | (self, element_block_id, new_element_type,
scheme) | Convert elements within a block to a new type. | Convert elements within a block to a new type. | [
"Convert",
"elements",
"within",
"a",
"block",
"to",
"a",
"new",
"type",
"."
] | def _translate_element_type(self, element_block_id, new_element_type,
scheme):
"""Convert elements within a block to a new type."""
[element_block_id] = self._format_element_block_id_list(
[element_block_id], single=True)
old_element_type = self._get_standard_element_type(
self._get_element_type(element_block_id))
new_element_type = self._get_standard_element_type(new_element_type)
old_nodes_per_element = self.NODES_PER_ELEMENT[old_element_type]
new_nodes_per_element = self.NODES_PER_ELEMENT[new_element_type]
element_multiplier = len(scheme)
# Make a list of nodes which need duplicated and nodes which need
# averaged. We will assign indices to these after we determine how
# many there are of each.
duplicate_nodes = set()
averaged_nodes = set()
connectivity = self.get_connectivity(element_block_id)
element_count = self.get_element_count(element_block_id)
for element_index in range(element_count):
local_node = connectivity[element_index *
old_nodes_per_element:(element_index +
1) *
old_nodes_per_element]
for new_element in scheme:
for new_node in new_element:
if isinstance(new_node, int):
duplicate_nodes.add(local_node[new_node])
else:
averaged_nodes.add(
tuple(local_node[x] for x in new_node))
# create new nodes
next_node_index = len(self.nodes)
duplicate_nodes = sorted(duplicate_nodes)
averaged_nodes = sorted(averaged_nodes)
self._duplicate_nodes(duplicate_nodes, [])
self._create_averaged_nodes(averaged_nodes, [])
# assign node indices
duplicate_nodes = dict((x, next_node_index + index)
for index, x in enumerate(duplicate_nodes))
next_node_index += len(duplicate_nodes)
averaged_nodes = dict((x, next_node_index + index)
for index, x in enumerate(averaged_nodes))
# create the connectivity for the new element block
new_connectivity = []
for element_index in range(element_count):
local_node = connectivity[element_index *
old_nodes_per_element:(element_index +
1) *
old_nodes_per_element]
for new_element in scheme:
for new_node in new_element:
if isinstance(new_node, int):
new_connectivity.append(
duplicate_nodes[local_node[new_node]])
else:
new_connectivity.append(averaged_nodes[tuple(
local_node[x] for x in new_node)])
# create the new block
temporary_element_block_id = self._new_element_block_id()
self.create_element_block(temporary_element_block_id, [
new_element_type,
len(new_connectivity) // new_nodes_per_element,
new_nodes_per_element, 0
], new_connectivity)
temporary_element_fields = self._get_element_block_fields(
temporary_element_block_id)
# transfer element values
fields = self._get_element_block_fields(element_block_id)
for field_name in self.get_element_field_names(element_block_id):
values = fields[field_name]
new_values = [list(x) for x in values]
new_values = [[
x for x in these_values for _ in range(element_multiplier)
] for these_values in new_values]
temporary_element_fields[field_name] = new_values
# for each face in the old scheme, find all of its nodes
old_face_mapping = self._get_face_mapping(old_element_type)
old_face_nodes = [set(x) for _, x in old_face_mapping]
new_face_mapping = self._get_face_mapping(new_element_type)
face_translation = [[] for _ in range(len(old_face_nodes))]
for new_element_index, new_element in enumerate(scheme):
for new_face_index, (_,
face_members) in enumerate(new_face_mapping):
# find all nodes used by this new face
used_nodes = set()
for face_member in face_members:
if isinstance(new_element[face_member], int):
used_nodes.add(new_element[face_member])
else:
used_nodes.update(new_element[face_member])
# see if these are a subset of nodes in the old set
for old_face_index, old_members in enumerate(old_face_nodes):
if used_nodes <= old_members:
face_translation[old_face_index].append(
(new_element_index, new_face_index))
# update self.side_sets
for side_set_id in self.get_side_set_ids():
members = self.get_side_set_members(side_set_id)
fields = self._get_side_set_fields(side_set_id)
old_members = list(members)
for member_index, (block_id, element_index,
face_index) in enumerate(old_members):
if block_id == element_block_id:
# add some new faces
for new_faces in face_translation[face_index]:
members.append(
(temporary_element_block_id,
element_index * len(scheme) + new_faces[0],
new_faces[1]))
# add values for the new faces
for all_values in list(fields.values()):
for values in all_values:
for _ in face_translation[face_index]:
values.append(values[member_index])
# delete the old block and rename the new one
self.delete_element_block(element_block_id)
self.rename_element_block(temporary_element_block_id, element_block_id) | [
"def",
"_translate_element_type",
"(",
"self",
",",
"element_block_id",
",",
"new_element_type",
",",
"scheme",
")",
":",
"[",
"element_block_id",
"]",
"=",
"self",
".",
"_format_element_block_id_list",
"(",
"[",
"element_block_id",
"]",
",",
"single",
"=",
"True"... | https://github.com/trilinos/Trilinos/blob/6168be6dd51e35e1cd681e9c4b24433e709df140/packages/seacas/scripts/exomerge3.py#L2789-L2905 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/dtypes/missing.py | python | _maybe_fill | (arr, fill_value=np.nan) | return arr | if we have a compatible fill_value and arr dtype, then fill | if we have a compatible fill_value and arr dtype, then fill | [
"if",
"we",
"have",
"a",
"compatible",
"fill_value",
"and",
"arr",
"dtype",
"then",
"fill"
] | def _maybe_fill(arr, fill_value=np.nan):
"""
if we have a compatible fill_value and arr dtype, then fill
"""
if _isna_compat(arr, fill_value):
arr.fill(fill_value)
return arr | [
"def",
"_maybe_fill",
"(",
"arr",
",",
"fill_value",
"=",
"np",
".",
"nan",
")",
":",
"if",
"_isna_compat",
"(",
"arr",
",",
"fill_value",
")",
":",
"arr",
".",
"fill",
"(",
"fill_value",
")",
"return",
"arr"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/dtypes/missing.py#L521-L527 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/ntpath.py | python | expandvars | (path) | return res | Expand shell variables of the forms $var, ${var} and %var%.
Unknown variables are left unchanged. | Expand shell variables of the forms $var, ${var} and %var%. | [
"Expand",
"shell",
"variables",
"of",
"the",
"forms",
"$var",
"$",
"{",
"var",
"}",
"and",
"%var%",
"."
] | def expandvars(path):
"""Expand shell variables of the forms $var, ${var} and %var%.
Unknown variables are left unchanged."""
if '$' not in path and '%' not in path:
return path
import string
varchars = string.ascii_letters + string.digits + '_-'
res = ''
index = 0
pathlen = len(path)
while index < pathlen:
c = path[index]
if c == '\'': # no expansion within single quotes
path = path[index + 1:]
pathlen = len(path)
try:
index = path.index('\'')
res = res + '\'' + path[:index + 1]
except ValueError:
res = res + path
index = pathlen - 1
elif c == '%': # variable or '%'
if path[index + 1:index + 2] == '%':
res = res + c
index = index + 1
else:
path = path[index+1:]
pathlen = len(path)
try:
index = path.index('%')
except ValueError:
res = res + '%' + path
index = pathlen - 1
else:
var = path[:index]
if var in os.environ:
res = res + os.environ[var]
else:
res = res + '%' + var + '%'
elif c == '$': # variable or '$$'
if path[index + 1:index + 2] == '$':
res = res + c
index = index + 1
elif path[index + 1:index + 2] == '{':
path = path[index+2:]
pathlen = len(path)
try:
index = path.index('}')
var = path[:index]
if var in os.environ:
res = res + os.environ[var]
else:
res = res + '${' + var + '}'
except ValueError:
res = res + '${' + path
index = pathlen - 1
else:
var = ''
index = index + 1
c = path[index:index + 1]
while c != '' and c in varchars:
var = var + c
index = index + 1
c = path[index:index + 1]
if var in os.environ:
res = res + os.environ[var]
else:
res = res + '$' + var
if c != '':
index = index - 1
else:
res = res + c
index = index + 1
return res | [
"def",
"expandvars",
"(",
"path",
")",
":",
"if",
"'$'",
"not",
"in",
"path",
"and",
"'%'",
"not",
"in",
"path",
":",
"return",
"path",
"import",
"string",
"varchars",
"=",
"string",
".",
"ascii_letters",
"+",
"string",
".",
"digits",
"+",
"'_-'",
"res... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/ntpath.py#L317-L391 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/richtext.py | python | RichTextParagraph_GetDefaultTabs | (*args) | return _richtext.RichTextParagraph_GetDefaultTabs(*args) | RichTextParagraph_GetDefaultTabs() -> wxArrayInt | RichTextParagraph_GetDefaultTabs() -> wxArrayInt | [
"RichTextParagraph_GetDefaultTabs",
"()",
"-",
">",
"wxArrayInt"
] | def RichTextParagraph_GetDefaultTabs(*args):
"""RichTextParagraph_GetDefaultTabs() -> wxArrayInt"""
return _richtext.RichTextParagraph_GetDefaultTabs(*args) | [
"def",
"RichTextParagraph_GetDefaultTabs",
"(",
"*",
"args",
")",
":",
"return",
"_richtext",
".",
"RichTextParagraph_GetDefaultTabs",
"(",
"*",
"args",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/richtext.py#L2076-L2078 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/plat-riscos/riscospath.py | python | getsize | (p) | return st[stat.ST_SIZE] | Return the size of a file, reported by os.stat(). | Return the size of a file, reported by os.stat(). | [
"Return",
"the",
"size",
"of",
"a",
"file",
"reported",
"by",
"os",
".",
"stat",
"()",
"."
] | def getsize(p):
"""
Return the size of a file, reported by os.stat().
"""
st= os.stat(p)
return st[stat.ST_SIZE] | [
"def",
"getsize",
"(",
"p",
")",
":",
"st",
"=",
"os",
".",
"stat",
"(",
"p",
")",
"return",
"st",
"[",
"stat",
".",
"ST_SIZE",
"]"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/plat-riscos/riscospath.py#L185-L190 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py2/scipy/signal/ltisys.py | python | TransferFunction.to_tf | (self) | return copy.deepcopy(self) | Return a copy of the current `TransferFunction` system.
Returns
-------
sys : instance of `TransferFunction`
The current system (copy) | Return a copy of the current `TransferFunction` system. | [
"Return",
"a",
"copy",
"of",
"the",
"current",
"TransferFunction",
"system",
"."
] | def to_tf(self):
"""
Return a copy of the current `TransferFunction` system.
Returns
-------
sys : instance of `TransferFunction`
The current system (copy)
"""
return copy.deepcopy(self) | [
"def",
"to_tf",
"(",
"self",
")",
":",
"return",
"copy",
".",
"deepcopy",
"(",
"self",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/signal/ltisys.py#L641-L651 | |
Tencent/Pebble | 68315f176d9e328a233ace29b7579a829f89879f | tools/blade/src/blade/cc_targets.py | python | CcTarget._check_incorrect_no_warning | (self) | check if warning=no is correctly used or not. | check if warning=no is correctly used or not. | [
"check",
"if",
"warning",
"=",
"no",
"is",
"correctly",
"used",
"or",
"not",
"."
] | def _check_incorrect_no_warning(self):
"""check if warning=no is correctly used or not. """
warning = self.data.get('warning', 'yes')
srcs = self.srcs
if not srcs or warning != 'no':
return
keywords_list = self.blade.get_sources_keyword_list()
for keyword in keywords_list:
if keyword in self.path:
return
illegal_path_list = []
for keyword in keywords_list:
illegal_path_list += [s for s in srcs if not keyword in s]
if illegal_path_list:
console.warning("//%s:%s : warning='no' is only allowed "
"for code in thirdparty." % (
self.key[0], self.key[1])) | [
"def",
"_check_incorrect_no_warning",
"(",
"self",
")",
":",
"warning",
"=",
"self",
".",
"data",
".",
"get",
"(",
"'warning'",
",",
"'yes'",
")",
"srcs",
"=",
"self",
".",
"srcs",
"if",
"not",
"srcs",
"or",
"warning",
"!=",
"'no'",
":",
"return",
"key... | https://github.com/Tencent/Pebble/blob/68315f176d9e328a233ace29b7579a829f89879f/tools/blade/src/blade/cc_targets.py#L133-L152 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/tkinter/__init__.py | python | Radiobutton.invoke | (self) | return self.tk.call(self._w, 'invoke') | Toggle the button and invoke a command if given as resource. | Toggle the button and invoke a command if given as resource. | [
"Toggle",
"the",
"button",
"and",
"invoke",
"a",
"command",
"if",
"given",
"as",
"resource",
"."
] | def invoke(self):
"""Toggle the button and invoke a command if given as resource."""
return self.tk.call(self._w, 'invoke') | [
"def",
"invoke",
"(",
"self",
")",
":",
"return",
"self",
".",
"tk",
".",
"call",
"(",
"self",
".",
"_w",
",",
"'invoke'",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/tkinter/__init__.py#L2992-L2994 | |
gromacs/gromacs | 7dec3a3f99993cf5687a122de3e12de31c21c399 | python_packaging/src/gmxapi/operation.py | python | SubgraphBuilder.build | (self) | return lambda subgraph=subgraph: subgraph | Build the subgraph by defining some new operations.
Examine the subgraph variables. Variables with handles to data sources
in the SubgraphContext represent work that needs to be executed on
a subgraph execution or iteration. Variables with handles to data sources
outside of the subgraph represent work that needs to be executed once
on only the first iteration to initialize the subgraph.
Construct a factory for the fused operation that performs the work to
update the variables on a single iteration.
Construct a factory for the fused operation that performs the work to
update the variables on subsequent iterations and which will be fed
the outputs of a previous iteration. Both of the generated operations
have the same output signature.
Construct and wrap the generator function to recursively append work
to the graph and update until condition is satisfied.
TODO: Explore how to drop work from the graph once there are no more
references to its output, including check-point machinery. | Build the subgraph by defining some new operations. | [
"Build",
"the",
"subgraph",
"by",
"defining",
"some",
"new",
"operations",
"."
] | def build(self):
"""Build the subgraph by defining some new operations.
Examine the subgraph variables. Variables with handles to data sources
in the SubgraphContext represent work that needs to be executed on
a subgraph execution or iteration. Variables with handles to data sources
outside of the subgraph represent work that needs to be executed once
on only the first iteration to initialize the subgraph.
Construct a factory for the fused operation that performs the work to
update the variables on a single iteration.
Construct a factory for the fused operation that performs the work to
update the variables on subsequent iterations and which will be fed
the outputs of a previous iteration. Both of the generated operations
have the same output signature.
Construct and wrap the generator function to recursively append work
to the graph and update until condition is satisfied.
TODO: Explore how to drop work from the graph once there are no more
references to its output, including check-point machinery.
"""
logger.debug('Finalizing subgraph definition.')
inputs = collections.OrderedDict()
for key, value in self.variables.items():
# TODO: What if we don't want to provide default values?
inputs[key] = value
updates = self._staging
class Subgraph(object):
def __init__(self, input_futures, update_sources):
self.values = collections.OrderedDict([(key, value.result()) for key, value in
input_futures.items()])
logger.debug('subgraph initialized with {}'.format(
', '.join(['{}: {}'.format(key, value) for key, value in self.values.items()])))
self.futures = collections.OrderedDict([(key, value) for key, value in
input_futures.items()])
self.update_sources = collections.OrderedDict([(key, value) for key, value in
update_sources.items()])
logger.debug('Subgraph updates staged:')
for update, source in self.update_sources.items():
logger.debug(' {} = {}'.format(update, source))
def run(self):
for name in self.update_sources:
result = self.update_sources[name].result()
logger.debug('Update: {} = {}'.format(name, result))
self.values[name] = result
# Replace the data sources in the futures.
for name in self.update_sources:
self.futures[name].resource_manager = gmx.make_constant(
self.values[name]).resource_manager
for name in self.update_sources:
self.update_sources[name]._reset()
subgraph = Subgraph(inputs, updates)
return lambda subgraph=subgraph: subgraph | [
"def",
"build",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"'Finalizing subgraph definition.'",
")",
"inputs",
"=",
"collections",
".",
"OrderedDict",
"(",
")",
"for",
"key",
",",
"value",
"in",
"self",
".",
"variables",
".",
"items",
"(",
")",
... | https://github.com/gromacs/gromacs/blob/7dec3a3f99993cf5687a122de3e12de31c21c399/python_packaging/src/gmxapi/operation.py#L3577-L3636 | |
BitMEX/api-connectors | 37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812 | auto-generated/python/swagger_client/models/wallet.py | python | Wallet.__init__ | (self, account=None, currency=None, prev_deposited=None, prev_withdrawn=None, prev_transfer_in=None, prev_transfer_out=None, prev_amount=None, prev_timestamp=None, delta_deposited=None, delta_withdrawn=None, delta_transfer_in=None, delta_transfer_out=None, delta_amount=None, deposited=None, withdrawn=None, transfer_in=None, transfer_out=None, amount=None, pending_credit=None, pending_debit=None, confirmed_debit=None, timestamp=None, addr=None, script=None, withdrawal_lock=None) | Wallet - a model defined in Swagger | Wallet - a model defined in Swagger | [
"Wallet",
"-",
"a",
"model",
"defined",
"in",
"Swagger"
] | def __init__(self, account=None, currency=None, prev_deposited=None, prev_withdrawn=None, prev_transfer_in=None, prev_transfer_out=None, prev_amount=None, prev_timestamp=None, delta_deposited=None, delta_withdrawn=None, delta_transfer_in=None, delta_transfer_out=None, delta_amount=None, deposited=None, withdrawn=None, transfer_in=None, transfer_out=None, amount=None, pending_credit=None, pending_debit=None, confirmed_debit=None, timestamp=None, addr=None, script=None, withdrawal_lock=None): # noqa: E501
"""Wallet - a model defined in Swagger""" # noqa: E501
self._account = None
self._currency = None
self._prev_deposited = None
self._prev_withdrawn = None
self._prev_transfer_in = None
self._prev_transfer_out = None
self._prev_amount = None
self._prev_timestamp = None
self._delta_deposited = None
self._delta_withdrawn = None
self._delta_transfer_in = None
self._delta_transfer_out = None
self._delta_amount = None
self._deposited = None
self._withdrawn = None
self._transfer_in = None
self._transfer_out = None
self._amount = None
self._pending_credit = None
self._pending_debit = None
self._confirmed_debit = None
self._timestamp = None
self._addr = None
self._script = None
self._withdrawal_lock = None
self.discriminator = None
self.account = account
self.currency = currency
if prev_deposited is not None:
self.prev_deposited = prev_deposited
if prev_withdrawn is not None:
self.prev_withdrawn = prev_withdrawn
if prev_transfer_in is not None:
self.prev_transfer_in = prev_transfer_in
if prev_transfer_out is not None:
self.prev_transfer_out = prev_transfer_out
if prev_amount is not None:
self.prev_amount = prev_amount
if prev_timestamp is not None:
self.prev_timestamp = prev_timestamp
if delta_deposited is not None:
self.delta_deposited = delta_deposited
if delta_withdrawn is not None:
self.delta_withdrawn = delta_withdrawn
if delta_transfer_in is not None:
self.delta_transfer_in = delta_transfer_in
if delta_transfer_out is not None:
self.delta_transfer_out = delta_transfer_out
if delta_amount is not None:
self.delta_amount = delta_amount
if deposited is not None:
self.deposited = deposited
if withdrawn is not None:
self.withdrawn = withdrawn
if transfer_in is not None:
self.transfer_in = transfer_in
if transfer_out is not None:
self.transfer_out = transfer_out
if amount is not None:
self.amount = amount
if pending_credit is not None:
self.pending_credit = pending_credit
if pending_debit is not None:
self.pending_debit = pending_debit
if confirmed_debit is not None:
self.confirmed_debit = confirmed_debit
if timestamp is not None:
self.timestamp = timestamp
if addr is not None:
self.addr = addr
if script is not None:
self.script = script
if withdrawal_lock is not None:
self.withdrawal_lock = withdrawal_lock | [
"def",
"__init__",
"(",
"self",
",",
"account",
"=",
"None",
",",
"currency",
"=",
"None",
",",
"prev_deposited",
"=",
"None",
",",
"prev_withdrawn",
"=",
"None",
",",
"prev_transfer_in",
"=",
"None",
",",
"prev_transfer_out",
"=",
"None",
",",
"prev_amount"... | https://github.com/BitMEX/api-connectors/blob/37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812/auto-generated/python/swagger_client/models/wallet.py#L89-L166 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/datetime.py | python | _days_before_year | (year) | return y*365 + y//4 - y//100 + y//400 | year -> number of days before January 1st of year. | year -> number of days before January 1st of year. | [
"year",
"-",
">",
"number",
"of",
"days",
"before",
"January",
"1st",
"of",
"year",
"."
] | def _days_before_year(year):
"year -> number of days before January 1st of year."
y = year - 1
return y*365 + y//4 - y//100 + y//400 | [
"def",
"_days_before_year",
"(",
"year",
")",
":",
"y",
"=",
"year",
"-",
"1",
"return",
"y",
"*",
"365",
"+",
"y",
"//",
"4",
"-",
"y",
"//",
"100",
"+",
"y",
"//",
"400"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/datetime.py#L41-L44 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/stc.py | python | StyledTextEvent.SetPosition | (*args, **kwargs) | return _stc.StyledTextEvent_SetPosition(*args, **kwargs) | SetPosition(self, int pos) | SetPosition(self, int pos) | [
"SetPosition",
"(",
"self",
"int",
"pos",
")"
] | def SetPosition(*args, **kwargs):
"""SetPosition(self, int pos)"""
return _stc.StyledTextEvent_SetPosition(*args, **kwargs) | [
"def",
"SetPosition",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextEvent_SetPosition",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/stc.py#L7026-L7028 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/requests/utils.py | python | stream_decode_response_unicode | (iterator, r) | Stream decodes a iterator. | Stream decodes a iterator. | [
"Stream",
"decodes",
"a",
"iterator",
"."
] | def stream_decode_response_unicode(iterator, r):
"""Stream decodes a iterator."""
if r.encoding is None:
for item in iterator:
yield item
return
decoder = codecs.getincrementaldecoder(r.encoding)(errors='replace')
for chunk in iterator:
rv = decoder.decode(chunk)
if rv:
yield rv
rv = decoder.decode(b'', final=True)
if rv:
yield rv | [
"def",
"stream_decode_response_unicode",
"(",
"iterator",
",",
"r",
")",
":",
"if",
"r",
".",
"encoding",
"is",
"None",
":",
"for",
"item",
"in",
"iterator",
":",
"yield",
"item",
"return",
"decoder",
"=",
"codecs",
".",
"getincrementaldecoder",
"(",
"r",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/requests/utils.py#L511-L526 | ||
SoarGroup/Soar | a1c5e249499137a27da60533c72969eef3b8ab6b | 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/SoarGroup/Soar/blob/a1c5e249499137a27da60533c72969eef3b8ab6b/scons/scons-local-4.1.0/SCons/Tool/mslink.py#L84-L86 | |
okex/V3-Open-API-SDK | c5abb0db7e2287718e0055e17e57672ce0ec7fd9 | okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/distlib/resources.py | python | finder_for_path | (path) | return result | Return a resource finder for a path, which should represent a container.
:param path: The path.
:return: A :class:`ResourceFinder` instance for the path. | Return a resource finder for a path, which should represent a container. | [
"Return",
"a",
"resource",
"finder",
"for",
"a",
"path",
"which",
"should",
"represent",
"a",
"container",
"."
] | def finder_for_path(path):
"""
Return a resource finder for a path, which should represent a container.
:param path: The path.
:return: A :class:`ResourceFinder` instance for the path.
"""
result = None
# calls any path hooks, gets importer into cache
pkgutil.get_importer(path)
loader = sys.path_importer_cache.get(path)
finder = _finder_registry.get(type(loader))
if finder:
module = _dummy_module
module.__file__ = os.path.join(path, '')
module.__loader__ = loader
result = finder(module)
return result | [
"def",
"finder_for_path",
"(",
"path",
")",
":",
"result",
"=",
"None",
"# calls any path hooks, gets importer into cache",
"pkgutil",
".",
"get_importer",
"(",
"path",
")",
"loader",
"=",
"sys",
".",
"path_importer_cache",
".",
"get",
"(",
"path",
")",
"finder",
... | https://github.com/okex/V3-Open-API-SDK/blob/c5abb0db7e2287718e0055e17e57672ce0ec7fd9/okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/distlib/resources.py#L338-L355 | |
PaddlePaddle/Paddle | 1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c | python/paddle/fluid/initializer.py | python | Initializer._compute_fans | (self, var) | return (fan_in, fan_out) | Compute the fan_in and the fan_out for layers
This method computes the fan_in and the fan_out
for neural network layers, if not specified. It is
not possible to perfectly estimate fan_in and fan_out.
This method will estimate it correctly for matrix multiply and
convolutions.
Args:
var: variable for which fan_in and fan_out have to be computed
Returns:
tuple of two integers (fan_in, fan_out) | Compute the fan_in and the fan_out for layers | [
"Compute",
"the",
"fan_in",
"and",
"the",
"fan_out",
"for",
"layers"
] | def _compute_fans(self, var):
"""Compute the fan_in and the fan_out for layers
This method computes the fan_in and the fan_out
for neural network layers, if not specified. It is
not possible to perfectly estimate fan_in and fan_out.
This method will estimate it correctly for matrix multiply and
convolutions.
Args:
var: variable for which fan_in and fan_out have to be computed
Returns:
tuple of two integers (fan_in, fan_out)
"""
shape = var.shape
if not shape or len(shape) == 0:
fan_in = fan_out = 1
elif len(shape) == 1:
fan_in = fan_out = shape[0]
elif len(shape) == 2:
# This is the case for simple matrix multiply
fan_in = shape[0]
fan_out = shape[1]
else:
# Assume this to be a convolutional kernel
# In PaddlePaddle, the shape of the kernel is like:
# [num_filters, num_filter_channels, ...] where the remaining
# dimensions are the filter_size
receptive_field_size = np.prod(shape[2:])
fan_in = shape[1] * receptive_field_size
fan_out = shape[0] * receptive_field_size
return (fan_in, fan_out) | [
"def",
"_compute_fans",
"(",
"self",
",",
"var",
")",
":",
"shape",
"=",
"var",
".",
"shape",
"if",
"not",
"shape",
"or",
"len",
"(",
"shape",
")",
"==",
"0",
":",
"fan_in",
"=",
"fan_out",
"=",
"1",
"elif",
"len",
"(",
"shape",
")",
"==",
"1",
... | https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/fluid/initializer.py#L61-L94 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/bigtable/python/ops/bigtable_api.py | python | BigtableTable.scan_range | (self, start, end, probability=None, columns=None, **kwargs) | return _BigtableScanDataset(self, "", start, end, normalized, probability) | Retrieves rows (including values) from the Bigtable service.
Rows with row-keys between `start` and `end` will be retrieved.
Specifying the columns to retrieve for each row is done by either using
kwargs or in the columns parameter. To retrieve values of the columns "c1",
and "c2" from the column family "cfa", and the value of the column "c3"
from column family "cfb", the following datasets (`ds1`, and `ds2`) are
equivalent:
```
table = # ...
ds1 = table.scan_range("row_start", "row_end", columns=[("cfa", "c1"),
("cfa", "c2"),
("cfb", "c3")])
ds2 = table.scan_range("row_start", "row_end", cfa=["c1", "c2"], cfb="c3")
```
Note: only the latest value of a cell will be retrieved.
Args:
start: The start of the range when scanning by range.
end: (Optional.) The end of the range when scanning by range.
probability: (Optional.) A float between 0 (exclusive) and 1 (inclusive).
A non-1 value indicates to probabilistically sample rows with the
provided probability.
columns: The columns to read. Note: most commonly, they are expressed as
kwargs. Use the columns value if you are using column families that are
reserved. The value of columns and kwargs are merged. Columns is a list
of tuples of strings ("column_family", "column_qualifier").
**kwargs: The column families and columns to read. Keys are treated as
column_families, and values can be either lists of strings, or strings
that are treated as the column qualifier (column name).
Returns:
A `tf.data.Dataset` returning the row keys and the cell contents.
Raises:
ValueError: If the configured probability is unexpected. | Retrieves rows (including values) from the Bigtable service. | [
"Retrieves",
"rows",
"(",
"including",
"values",
")",
"from",
"the",
"Bigtable",
"service",
"."
] | def scan_range(self, start, end, probability=None, columns=None, **kwargs):
"""Retrieves rows (including values) from the Bigtable service.
Rows with row-keys between `start` and `end` will be retrieved.
Specifying the columns to retrieve for each row is done by either using
kwargs or in the columns parameter. To retrieve values of the columns "c1",
and "c2" from the column family "cfa", and the value of the column "c3"
from column family "cfb", the following datasets (`ds1`, and `ds2`) are
equivalent:
```
table = # ...
ds1 = table.scan_range("row_start", "row_end", columns=[("cfa", "c1"),
("cfa", "c2"),
("cfb", "c3")])
ds2 = table.scan_range("row_start", "row_end", cfa=["c1", "c2"], cfb="c3")
```
Note: only the latest value of a cell will be retrieved.
Args:
start: The start of the range when scanning by range.
end: (Optional.) The end of the range when scanning by range.
probability: (Optional.) A float between 0 (exclusive) and 1 (inclusive).
A non-1 value indicates to probabilistically sample rows with the
provided probability.
columns: The columns to read. Note: most commonly, they are expressed as
kwargs. Use the columns value if you are using column families that are
reserved. The value of columns and kwargs are merged. Columns is a list
of tuples of strings ("column_family", "column_qualifier").
**kwargs: The column families and columns to read. Keys are treated as
column_families, and values can be either lists of strings, or strings
that are treated as the column qualifier (column name).
Returns:
A `tf.data.Dataset` returning the row keys and the cell contents.
Raises:
ValueError: If the configured probability is unexpected.
"""
probability = _normalize_probability(probability)
normalized = _normalize_columns(columns, kwargs)
return _BigtableScanDataset(self, "", start, end, normalized, probability) | [
"def",
"scan_range",
"(",
"self",
",",
"start",
",",
"end",
",",
"probability",
"=",
"None",
",",
"columns",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"probability",
"=",
"_normalize_probability",
"(",
"probability",
")",
"normalized",
"=",
"_normali... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/bigtable/python/ops/bigtable_api.py#L283-L326 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Source/ThirdParty/CEF3/pristine/cef_source/tools/git_util.py | python | get_commit_number | (path = '.', branch = 'HEAD') | return '0' | Returns the number of commits in the specified branch/tag/hash. | Returns the number of commits in the specified branch/tag/hash. | [
"Returns",
"the",
"number",
"of",
"commits",
"in",
"the",
"specified",
"branch",
"/",
"tag",
"/",
"hash",
"."
] | def get_commit_number(path = '.', branch = 'HEAD'):
""" Returns the number of commits in the specified branch/tag/hash. """
cmd = "%s rev-list --count %s" % (git_exe, branch)
result = exec_cmd(cmd, path)
if result['out'] != '':
return result['out'].strip()
return '0' | [
"def",
"get_commit_number",
"(",
"path",
"=",
"'.'",
",",
"branch",
"=",
"'HEAD'",
")",
":",
"cmd",
"=",
"\"%s rev-list --count %s\"",
"%",
"(",
"git_exe",
",",
"branch",
")",
"result",
"=",
"exec_cmd",
"(",
"cmd",
",",
"path",
")",
"if",
"result",
"[",
... | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Source/ThirdParty/CEF3/pristine/cef_source/tools/git_util.py#L35-L41 | |
CRYTEK/CRYENGINE | 232227c59a220cbbd311576f0fbeba7bb53b2a8c | Code/Tools/waf-1.7.13/waflib/Tools/c_preproc.py | python | stringize | (lst) | return "".join(lst) | Merge a list of tokens into a string
:param lst: a list of tokens
:type lst: list of tuple(token, value)
:rtype: string | Merge a list of tokens into a string | [
"Merge",
"a",
"list",
"of",
"tokens",
"into",
"a",
"string"
] | def stringize(lst):
"""
Merge a list of tokens into a string
:param lst: a list of tokens
:type lst: list of tuple(token, value)
:rtype: string
"""
lst = [str(v2) for (p2, v2) in lst]
return "".join(lst) | [
"def",
"stringize",
"(",
"lst",
")",
":",
"lst",
"=",
"[",
"str",
"(",
"v2",
")",
"for",
"(",
"p2",
",",
"v2",
")",
"in",
"lst",
"]",
"return",
"\"\"",
".",
"join",
"(",
"lst",
")"
] | https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Code/Tools/waf-1.7.13/waflib/Tools/c_preproc.py#L363-L372 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/protobuf/py2/google/protobuf/descriptor.py | python | FileDescriptor.CopyToProto | (self, proto) | Copies this to a descriptor_pb2.FileDescriptorProto.
Args:
proto: An empty descriptor_pb2.FileDescriptorProto. | Copies this to a descriptor_pb2.FileDescriptorProto. | [
"Copies",
"this",
"to",
"a",
"descriptor_pb2",
".",
"FileDescriptorProto",
"."
] | def CopyToProto(self, proto):
"""Copies this to a descriptor_pb2.FileDescriptorProto.
Args:
proto: An empty descriptor_pb2.FileDescriptorProto.
"""
proto.ParseFromString(self.serialized_pb) | [
"def",
"CopyToProto",
"(",
"self",
",",
"proto",
")",
":",
"proto",
".",
"ParseFromString",
"(",
"self",
".",
"serialized_pb",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/protobuf/py2/google/protobuf/descriptor.py#L1014-L1020 | ||
CRYTEK/CRYENGINE | 232227c59a220cbbd311576f0fbeba7bb53b2a8c | Editor/Python/windows/Lib/site-packages/pkg_resources/__init__.py | python | WorkingSet.find | (self, req) | return dist | Find a distribution matching requirement `req`
If there is an active distribution for the requested project, this
returns it as long as it meets the version requirement specified by
`req`. But, if there is an active distribution for the project and it
does *not* meet the `req` requirement, ``VersionConflict`` is raised.
If there is no active distribution for the requested project, ``None``
is returned. | Find a distribution matching requirement `req` | [
"Find",
"a",
"distribution",
"matching",
"requirement",
"req"
] | def find(self, req):
"""Find a distribution matching requirement `req`
If there is an active distribution for the requested project, this
returns it as long as it meets the version requirement specified by
`req`. But, if there is an active distribution for the project and it
does *not* meet the `req` requirement, ``VersionConflict`` is raised.
If there is no active distribution for the requested project, ``None``
is returned.
"""
dist = self.by_key.get(req.key)
if dist is not None and dist not in req:
# XXX add more info
raise VersionConflict(dist, req)
return dist | [
"def",
"find",
"(",
"self",
",",
"req",
")",
":",
"dist",
"=",
"self",
".",
"by_key",
".",
"get",
"(",
"req",
".",
"key",
")",
"if",
"dist",
"is",
"not",
"None",
"and",
"dist",
"not",
"in",
"req",
":",
"# XXX add more info",
"raise",
"VersionConflict... | https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/pkg_resources/__init__.py#L630-L644 | |
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/contrib/learn/python/learn/learn_io/graph_io.py | python | read_keyed_batch_features | (file_pattern,
batch_size,
features,
reader,
randomize_input=True,
num_epochs=None,
queue_capacity=10000,
reader_num_threads=1,
feature_queue_capacity=100,
num_queue_runners=2,
parse_fn=None,
name=None) | Adds operations to read, queue, batch and parse `Example` protos.
Given file pattern (or list of files), will setup a queue for file names,
read `Example` proto using provided `reader`, use batch queue to create
batches of examples of size `batch_size` and parse example given `features`
specification.
All queue runners are added to the queue runners collection, and may be
started via `start_queue_runners`.
All ops are added to the default graph.
Args:
file_pattern: List of files or pattern of file paths containing
`Example` records. See `tf.gfile.Glob` for pattern rules.
batch_size: An int or scalar `Tensor` specifying the batch size to use.
features: A `dict` mapping feature keys to `FixedLenFeature` or
`VarLenFeature` values.
reader: A function or class that returns an object with
`read` method, (filename tensor) -> (example tensor).
randomize_input: Whether the input should be randomized.
num_epochs: Integer specifying the number of times to read through the
dataset. If None, cycles through the dataset forever. NOTE - If specified,
creates a variable that must be initialized, so call
tf.initialize_local_variables() as shown in the tests.
queue_capacity: Capacity for input queue.
reader_num_threads: The number of threads to read examples.
feature_queue_capacity: Capacity of the parsed features queue.
num_queue_runners: Number of queue runners to start for the feature queue,
Adding multiple queue runners for the parsed example queue helps maintain
a full queue when the subsequent computations overall are cheaper than
parsing.
parse_fn: Parsing function, takes `Example` Tensor returns parsed
representation. If `None`, no parsing is done.
name: Name of resulting op.
Returns:
Returns tuple of:
- `Tensor` of string keys.
- A dict of `Tensor` or `SparseTensor` objects for each in `features`.
Raises:
ValueError: for invalid inputs. | Adds operations to read, queue, batch and parse `Example` protos. | [
"Adds",
"operations",
"to",
"read",
"queue",
"batch",
"and",
"parse",
"Example",
"protos",
"."
] | def read_keyed_batch_features(file_pattern,
batch_size,
features,
reader,
randomize_input=True,
num_epochs=None,
queue_capacity=10000,
reader_num_threads=1,
feature_queue_capacity=100,
num_queue_runners=2,
parse_fn=None,
name=None):
"""Adds operations to read, queue, batch and parse `Example` protos.
Given file pattern (or list of files), will setup a queue for file names,
read `Example` proto using provided `reader`, use batch queue to create
batches of examples of size `batch_size` and parse example given `features`
specification.
All queue runners are added to the queue runners collection, and may be
started via `start_queue_runners`.
All ops are added to the default graph.
Args:
file_pattern: List of files or pattern of file paths containing
`Example` records. See `tf.gfile.Glob` for pattern rules.
batch_size: An int or scalar `Tensor` specifying the batch size to use.
features: A `dict` mapping feature keys to `FixedLenFeature` or
`VarLenFeature` values.
reader: A function or class that returns an object with
`read` method, (filename tensor) -> (example tensor).
randomize_input: Whether the input should be randomized.
num_epochs: Integer specifying the number of times to read through the
dataset. If None, cycles through the dataset forever. NOTE - If specified,
creates a variable that must be initialized, so call
tf.initialize_local_variables() as shown in the tests.
queue_capacity: Capacity for input queue.
reader_num_threads: The number of threads to read examples.
feature_queue_capacity: Capacity of the parsed features queue.
num_queue_runners: Number of queue runners to start for the feature queue,
Adding multiple queue runners for the parsed example queue helps maintain
a full queue when the subsequent computations overall are cheaper than
parsing.
parse_fn: Parsing function, takes `Example` Tensor returns parsed
representation. If `None`, no parsing is done.
name: Name of resulting op.
Returns:
Returns tuple of:
- `Tensor` of string keys.
- A dict of `Tensor` or `SparseTensor` objects for each in `features`.
Raises:
ValueError: for invalid inputs.
"""
with ops.name_scope(name, 'read_batch_features', [file_pattern]) as scope:
keys, examples = read_keyed_batch_examples(
file_pattern, batch_size, reader, randomize_input=randomize_input,
num_epochs=num_epochs, queue_capacity=queue_capacity,
num_threads=reader_num_threads, read_batch_size=batch_size,
parse_fn=parse_fn, name=scope)
# Parse the example.
feature_map = parsing_ops.parse_example(examples, features)
return queue_parsed_features(
feature_map,
keys=keys,
feature_queue_capacity=feature_queue_capacity,
num_queue_runners=num_queue_runners,
name=scope) | [
"def",
"read_keyed_batch_features",
"(",
"file_pattern",
",",
"batch_size",
",",
"features",
",",
"reader",
",",
"randomize_input",
"=",
"True",
",",
"num_epochs",
"=",
"None",
",",
"queue_capacity",
"=",
"10000",
",",
"reader_num_threads",
"=",
"1",
",",
"featu... | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/contrib/learn/python/learn/learn_io/graph_io.py#L228-L298 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_windows.py | python | Printout.GetLogicalPaperRect | (*args, **kwargs) | return _windows_.Printout_GetLogicalPaperRect(*args, **kwargs) | GetLogicalPaperRect(self) -> Rect | GetLogicalPaperRect(self) -> Rect | [
"GetLogicalPaperRect",
"(",
"self",
")",
"-",
">",
"Rect"
] | def GetLogicalPaperRect(*args, **kwargs):
"""GetLogicalPaperRect(self) -> Rect"""
return _windows_.Printout_GetLogicalPaperRect(*args, **kwargs) | [
"def",
"GetLogicalPaperRect",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_windows_",
".",
"Printout_GetLogicalPaperRect",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_windows.py#L5311-L5313 | |
SequoiaDB/SequoiaDB | 2894ed7e5bd6fe57330afc900cf76d0ff0df9f64 | tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py | python | relaxNGNewParserCtxt | (URL) | return relaxNgParserCtxt(_obj=ret) | Create an XML RelaxNGs parse context for that file/resource
expected to contain an XML RelaxNGs file. | Create an XML RelaxNGs parse context for that file/resource
expected to contain an XML RelaxNGs file. | [
"Create",
"an",
"XML",
"RelaxNGs",
"parse",
"context",
"for",
"that",
"file",
"/",
"resource",
"expected",
"to",
"contain",
"an",
"XML",
"RelaxNGs",
"file",
"."
] | def relaxNGNewParserCtxt(URL):
"""Create an XML RelaxNGs parse context for that file/resource
expected to contain an XML RelaxNGs file. """
ret = libxml2mod.xmlRelaxNGNewParserCtxt(URL)
if ret is None:raise parserError('xmlRelaxNGNewParserCtxt() failed')
return relaxNgParserCtxt(_obj=ret) | [
"def",
"relaxNGNewParserCtxt",
"(",
"URL",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlRelaxNGNewParserCtxt",
"(",
"URL",
")",
"if",
"ret",
"is",
"None",
":",
"raise",
"parserError",
"(",
"'xmlRelaxNGNewParserCtxt() failed'",
")",
"return",
"relaxNgParserCtxt",
"... | https://github.com/SequoiaDB/SequoiaDB/blob/2894ed7e5bd6fe57330afc900cf76d0ff0df9f64/tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py#L1594-L1599 | |
stan-dev/math | 5fd79f89933269a4ca4d8dd1fde2a36d53d4768c | lib/boost_1.75.0/tools/build/src/build/feature.py | python | get_values | (feature, properties) | return result | Returns all values of the given feature specified by the given property set. | Returns all values of the given feature specified by the given property set. | [
"Returns",
"all",
"values",
"of",
"the",
"given",
"feature",
"specified",
"by",
"the",
"given",
"property",
"set",
"."
] | def get_values (feature, properties):
""" Returns all values of the given feature specified by the given property set.
"""
if feature[0] != '<':
feature = '<' + feature + '>'
result = []
for p in properties:
if get_grist (p) == feature:
result.append (replace_grist (p, ''))
return result | [
"def",
"get_values",
"(",
"feature",
",",
"properties",
")",
":",
"if",
"feature",
"[",
"0",
"]",
"!=",
"'<'",
":",
"feature",
"=",
"'<'",
"+",
"feature",
"+",
"'>'",
"result",
"=",
"[",
"]",
"for",
"p",
"in",
"properties",
":",
"if",
"get_grist",
... | https://github.com/stan-dev/math/blob/5fd79f89933269a4ca4d8dd1fde2a36d53d4768c/lib/boost_1.75.0/tools/build/src/build/feature.py#L552-L562 | |
netket/netket | 0d534e54ecbf25b677ea72af6b85947979420652 | netket/driver/steady_state.py | python | SteadyState._forward_and_backward | (self) | return self._dp | Performs a number of VMC optimization steps.
Args:
n_steps (int): Number of steps to perform. | Performs a number of VMC optimization steps. | [
"Performs",
"a",
"number",
"of",
"VMC",
"optimization",
"steps",
"."
] | def _forward_and_backward(self):
"""
Performs a number of VMC optimization steps.
Args:
n_steps (int): Number of steps to perform.
"""
self.state.reset()
# Compute the local energy estimator and average Energy
self._loss_stats, self._loss_grad = self.state.expect_and_grad(self._ldag_l)
# if it's the identity it does
# self._dp = self._loss_grad
self._dp = self.preconditioner(self.state, self._loss_grad)
# If parameters are real, then take only real part of the gradient (if it's complex)
self._dp = jax.tree_multimap(
lambda x, target: (x if jnp.iscomplexobj(target) else x.real),
self._dp,
self.state.parameters,
)
return self._dp | [
"def",
"_forward_and_backward",
"(",
"self",
")",
":",
"self",
".",
"state",
".",
"reset",
"(",
")",
"# Compute the local energy estimator and average Energy",
"self",
".",
"_loss_stats",
",",
"self",
".",
"_loss_grad",
"=",
"self",
".",
"state",
".",
"expect_and_... | https://github.com/netket/netket/blob/0d534e54ecbf25b677ea72af6b85947979420652/netket/driver/steady_state.py#L109-L133 | |
BlzFans/wke | b0fa21158312e40c5fbd84682d643022b6c34a93 | cygwin/lib/python2.6/imaplib.py | python | IMAP4.proxyauth | (self, user) | return self._simple_command('PROXYAUTH', user) | Assume authentication as "user".
Allows an authorised administrator to proxy into any user's
mailbox.
(typ, [data]) = <instance>.proxyauth(user) | Assume authentication as "user". | [
"Assume",
"authentication",
"as",
"user",
"."
] | def proxyauth(self, user):
"""Assume authentication as "user".
Allows an authorised administrator to proxy into any user's
mailbox.
(typ, [data]) = <instance>.proxyauth(user)
"""
name = 'PROXYAUTH'
return self._simple_command('PROXYAUTH', user) | [
"def",
"proxyauth",
"(",
"self",
",",
"user",
")",
":",
"name",
"=",
"'PROXYAUTH'",
"return",
"self",
".",
"_simple_command",
"(",
"'PROXYAUTH'",
",",
"user",
")"
] | https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/imaplib.py#L588-L598 | |
crystax/android-platform-ndk | d86e23c826179a1c46b0576d42501ed234bf1a50 | build/instruments/build-python/sysconfig.py | python | get_paths | (scheme=_get_default_scheme(), vars=None, expand=True) | Return a mapping containing an install scheme.
``scheme`` is the install scheme name. If not provided, it will
return the default scheme for the current platform. | Return a mapping containing an install scheme. | [
"Return",
"a",
"mapping",
"containing",
"an",
"install",
"scheme",
"."
] | def get_paths(scheme=_get_default_scheme(), vars=None, expand=True):
"""Return a mapping containing an install scheme.
``scheme`` is the install scheme name. If not provided, it will
return the default scheme for the current platform.
"""
if expand:
return _expand_vars(scheme, vars)
else:
return _INSTALL_SCHEMES[scheme] | [
"def",
"get_paths",
"(",
"scheme",
"=",
"_get_default_scheme",
"(",
")",
",",
"vars",
"=",
"None",
",",
"expand",
"=",
"True",
")",
":",
"if",
"expand",
":",
"return",
"_expand_vars",
"(",
"scheme",
",",
"vars",
")",
"else",
":",
"return",
"_INSTALL_SCHE... | https://github.com/crystax/android-platform-ndk/blob/d86e23c826179a1c46b0576d42501ed234bf1a50/build/instruments/build-python/sysconfig.py#L85-L94 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py2/scipy/sparse/linalg/dsolve/linsolve.py | python | splu | (A, permc_spec=None, diag_pivot_thresh=None,
relax=None, panel_size=None, options=dict()) | return _superlu.gstrf(N, A.nnz, A.data, A.indices, A.indptr,
ilu=False, options=_options) | Compute the LU decomposition of a sparse, square matrix.
Parameters
----------
A : sparse matrix
Sparse matrix to factorize. Should be in CSR or CSC format.
permc_spec : str, optional
How to permute the columns of the matrix for sparsity preservation.
(default: 'COLAMD')
- ``NATURAL``: natural ordering.
- ``MMD_ATA``: minimum degree ordering on the structure of A^T A.
- ``MMD_AT_PLUS_A``: minimum degree ordering on the structure of A^T+A.
- ``COLAMD``: approximate minimum degree column ordering
diag_pivot_thresh : float, optional
Threshold used for a diagonal entry to be an acceptable pivot.
See SuperLU user's guide for details [1]_
relax : int, optional
Expert option for customizing the degree of relaxing supernodes.
See SuperLU user's guide for details [1]_
panel_size : int, optional
Expert option for customizing the panel size.
See SuperLU user's guide for details [1]_
options : dict, optional
Dictionary containing additional expert options to SuperLU.
See SuperLU user guide [1]_ (section 2.4 on the 'Options' argument)
for more details. For example, you can specify
``options=dict(Equil=False, IterRefine='SINGLE'))``
to turn equilibration off and perform a single iterative refinement.
Returns
-------
invA : scipy.sparse.linalg.SuperLU
Object, which has a ``solve`` method.
See also
--------
spilu : incomplete LU decomposition
Notes
-----
This function uses the SuperLU library.
References
----------
.. [1] SuperLU http://crd.lbl.gov/~xiaoye/SuperLU/
Examples
--------
>>> from scipy.sparse import csc_matrix
>>> from scipy.sparse.linalg import splu
>>> A = csc_matrix([[1., 0., 0.], [5., 0., 2.], [0., -1., 0.]], dtype=float)
>>> B = splu(A)
>>> x = np.array([1., 2., 3.], dtype=float)
>>> B.solve(x)
array([ 1. , -3. , -1.5])
>>> A.dot(B.solve(x))
array([ 1., 2., 3.])
>>> B.solve(A.dot(x))
array([ 1., 2., 3.]) | Compute the LU decomposition of a sparse, square matrix. | [
"Compute",
"the",
"LU",
"decomposition",
"of",
"a",
"sparse",
"square",
"matrix",
"."
] | def splu(A, permc_spec=None, diag_pivot_thresh=None,
relax=None, panel_size=None, options=dict()):
"""
Compute the LU decomposition of a sparse, square matrix.
Parameters
----------
A : sparse matrix
Sparse matrix to factorize. Should be in CSR or CSC format.
permc_spec : str, optional
How to permute the columns of the matrix for sparsity preservation.
(default: 'COLAMD')
- ``NATURAL``: natural ordering.
- ``MMD_ATA``: minimum degree ordering on the structure of A^T A.
- ``MMD_AT_PLUS_A``: minimum degree ordering on the structure of A^T+A.
- ``COLAMD``: approximate minimum degree column ordering
diag_pivot_thresh : float, optional
Threshold used for a diagonal entry to be an acceptable pivot.
See SuperLU user's guide for details [1]_
relax : int, optional
Expert option for customizing the degree of relaxing supernodes.
See SuperLU user's guide for details [1]_
panel_size : int, optional
Expert option for customizing the panel size.
See SuperLU user's guide for details [1]_
options : dict, optional
Dictionary containing additional expert options to SuperLU.
See SuperLU user guide [1]_ (section 2.4 on the 'Options' argument)
for more details. For example, you can specify
``options=dict(Equil=False, IterRefine='SINGLE'))``
to turn equilibration off and perform a single iterative refinement.
Returns
-------
invA : scipy.sparse.linalg.SuperLU
Object, which has a ``solve`` method.
See also
--------
spilu : incomplete LU decomposition
Notes
-----
This function uses the SuperLU library.
References
----------
.. [1] SuperLU http://crd.lbl.gov/~xiaoye/SuperLU/
Examples
--------
>>> from scipy.sparse import csc_matrix
>>> from scipy.sparse.linalg import splu
>>> A = csc_matrix([[1., 0., 0.], [5., 0., 2.], [0., -1., 0.]], dtype=float)
>>> B = splu(A)
>>> x = np.array([1., 2., 3.], dtype=float)
>>> B.solve(x)
array([ 1. , -3. , -1.5])
>>> A.dot(B.solve(x))
array([ 1., 2., 3.])
>>> B.solve(A.dot(x))
array([ 1., 2., 3.])
"""
if not isspmatrix_csc(A):
A = csc_matrix(A)
warn('splu requires CSC matrix format', SparseEfficiencyWarning)
# sum duplicates for non-canonical format
A.sum_duplicates()
A = A.asfptype() # upcast to a floating point format
M, N = A.shape
if (M != N):
raise ValueError("can only factor square matrices") # is this true?
_options = dict(DiagPivotThresh=diag_pivot_thresh, ColPerm=permc_spec,
PanelSize=panel_size, Relax=relax)
if options is not None:
_options.update(options)
return _superlu.gstrf(N, A.nnz, A.data, A.indices, A.indptr,
ilu=False, options=_options) | [
"def",
"splu",
"(",
"A",
",",
"permc_spec",
"=",
"None",
",",
"diag_pivot_thresh",
"=",
"None",
",",
"relax",
"=",
"None",
",",
"panel_size",
"=",
"None",
",",
"options",
"=",
"dict",
"(",
")",
")",
":",
"if",
"not",
"isspmatrix_csc",
"(",
"A",
")",
... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/sparse/linalg/dsolve/linsolve.py#L228-L311 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/framework/convert_to_constants.py | python | _FunctionCaller.create_edges | (self) | Creates edges related to a function caller.
Edges from a function caller to its called functions are always edges from
_inputs_ to _inputs_: a FunctionDef input is given by the caller, based on
its own inputs. | Creates edges related to a function caller. | [
"Creates",
"edges",
"related",
"to",
"a",
"function",
"caller",
"."
] | def create_edges(self):
"""Creates edges related to a function caller.
Edges from a function caller to its called functions are always edges from
_inputs_ to _inputs_: a FunctionDef input is given by the caller, based on
its own inputs.
"""
super(_FunctionCaller, self).create_edges()
for attr_name in self._function_attributes:
attr = self._node.attr[attr_name]
if attr.HasField("func"):
function = self._enclosing_graph.functions[attr.func.name]
for index in range(len(self._node.input) - self._first_function_input):
self.add_outgoing_edge(
_Edge(
_EndPoint(self, index + self._first_function_input),
_EndPoint(function, index)))
elif attr.HasField("list"):
for func in attr.list.func:
function = self._enclosing_graph.functions[func.name]
for index in range(
len(self._node.input) - self._first_function_input):
self.add_outgoing_edge(
_Edge(
_EndPoint(self, index + self._first_function_input),
_EndPoint(function, index))) | [
"def",
"create_edges",
"(",
"self",
")",
":",
"super",
"(",
"_FunctionCaller",
",",
"self",
")",
".",
"create_edges",
"(",
")",
"for",
"attr_name",
"in",
"self",
".",
"_function_attributes",
":",
"attr",
"=",
"self",
".",
"_node",
".",
"attr",
"[",
"attr... | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/framework/convert_to_constants.py#L539-L564 | ||
pytorch/xla | 93174035e8149d5d03cee446486de861f56493e1 | torch_xla/utils/utils.py | python | DataWrapper.from_tensors | (self, tensors) | Build an instance of the wrapped object given the input tensors.
The number of tensors is the same as the ones returned by the
`get_tensors()` API, and `tensors[i]` is the device copy of
`get_tensors()[i]`.
Returns:
The unwrapped instance of the object with tensors on device. | Build an instance of the wrapped object given the input tensors. | [
"Build",
"an",
"instance",
"of",
"the",
"wrapped",
"object",
"given",
"the",
"input",
"tensors",
"."
] | def from_tensors(self, tensors):
"""Build an instance of the wrapped object given the input tensors.
The number of tensors is the same as the ones returned by the
`get_tensors()` API, and `tensors[i]` is the device copy of
`get_tensors()[i]`.
Returns:
The unwrapped instance of the object with tensors on device.
"""
raise NotImplementedError('The method is missing an implementation') | [
"def",
"from_tensors",
"(",
"self",
",",
"tensors",
")",
":",
"raise",
"NotImplementedError",
"(",
"'The method is missing an implementation'",
")"
] | https://github.com/pytorch/xla/blob/93174035e8149d5d03cee446486de861f56493e1/torch_xla/utils/utils.py#L118-L128 | ||
forkineye/ESPixelStick | 22926f1c0d1131f1369fc7cad405689a095ae3cb | dist/bin/esptool/serial/rfc2217.py | python | Serial.cd | (self) | return bool(self.get_modem_state() & MODEMSTATE_MASK_CD) | Read terminal status line: Carrier Detect. | Read terminal status line: Carrier Detect. | [
"Read",
"terminal",
"status",
"line",
":",
"Carrier",
"Detect",
"."
] | def cd(self):
"""Read terminal status line: Carrier Detect."""
if not self.is_open:
raise portNotOpenError
return bool(self.get_modem_state() & MODEMSTATE_MASK_CD) | [
"def",
"cd",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_open",
":",
"raise",
"portNotOpenError",
"return",
"bool",
"(",
"self",
".",
"get_modem_state",
"(",
")",
"&",
"MODEMSTATE_MASK_CD",
")"
] | https://github.com/forkineye/ESPixelStick/blob/22926f1c0d1131f1369fc7cad405689a095ae3cb/dist/bin/esptool/serial/rfc2217.py#L714-L718 | |
CoolProp/CoolProp | 381c8535e5dec3eec27ad430ebbfff8bc9dfc008 | wrappers/Python/CoolProp/Plots/Common.py | python | IsoLine.get_update_pair | (self) | Processes the values for the isoproperty and the graph dimensions
to figure which should be used as inputs to the state update. Returns
a tuple with the indices for the update call and the property constant.
For an isobar in a Ts-diagram it returns the default order and the
correct constant for the update pair:
get_update_pair(CoolProp.iP,CoolProp.iSmass,CoolProp.iT) -> (0,1,2,CoolProp.PSmass_INPUTS)
other values require switching and swapping. | Processes the values for the isoproperty and the graph dimensions
to figure which should be used as inputs to the state update. Returns
a tuple with the indices for the update call and the property constant.
For an isobar in a Ts-diagram it returns the default order and the
correct constant for the update pair:
get_update_pair(CoolProp.iP,CoolProp.iSmass,CoolProp.iT) -> (0,1,2,CoolProp.PSmass_INPUTS)
other values require switching and swapping. | [
"Processes",
"the",
"values",
"for",
"the",
"isoproperty",
"and",
"the",
"graph",
"dimensions",
"to",
"figure",
"which",
"should",
"be",
"used",
"as",
"inputs",
"to",
"the",
"state",
"update",
".",
"Returns",
"a",
"tuple",
"with",
"the",
"indices",
"for",
... | def get_update_pair(self):
"""Processes the values for the isoproperty and the graph dimensions
to figure which should be used as inputs to the state update. Returns
a tuple with the indices for the update call and the property constant.
For an isobar in a Ts-diagram it returns the default order and the
correct constant for the update pair:
get_update_pair(CoolProp.iP,CoolProp.iSmass,CoolProp.iT) -> (0,1,2,CoolProp.PSmass_INPUTS)
other values require switching and swapping.
"""
# Figure out if x or y-dimension should be used
switch = self.XY_SWITCH[self.i_index][self.y_index * 10 + self.x_index]
if switch is None:
raise ValueError("This isoline cannot be calculated!")
elif switch is False:
pair, out1, _ = CP.generate_update_pair(self.i_index, 0.0, self.x_index, 1.0)
elif switch is True:
pair, out1, _ = CP.generate_update_pair(self.i_index, 0.0, self.y_index, 1.0)
else:
raise ValueError("Unknown error!")
if out1 == 0.0: # Correct order
swap = False
else: # Wrong order
swap = True
if not switch and not swap:
return 0, 1, 2, pair
elif switch and not swap:
return 0, 2, 1, pair
elif not switch and swap:
return 1, 0, 2, pair
elif switch and swap:
return 1, 2, 0, pair
else:
raise ValueError("Check the code, this should not happen!") | [
"def",
"get_update_pair",
"(",
"self",
")",
":",
"# Figure out if x or y-dimension should be used",
"switch",
"=",
"self",
".",
"XY_SWITCH",
"[",
"self",
".",
"i_index",
"]",
"[",
"self",
".",
"y_index",
"*",
"10",
"+",
"self",
".",
"x_index",
"]",
"if",
"sw... | https://github.com/CoolProp/CoolProp/blob/381c8535e5dec3eec27ad430ebbfff8bc9dfc008/wrappers/Python/CoolProp/Plots/Common.py#L509-L544 | ||
hfinkel/llvm-project-cxxjit | 91084ef018240bbb8e24235ff5cd8c355a9c1a1e | lldb/third_party/Python/module/pexpect-2.4/pxssh.py | python | pxssh.prompt | (self, timeout=20) | return True | This matches the shell prompt. This is little more than a short-cut
to the expect() method. This returns True if the shell prompt was
matched. This returns False if there was a timeout. Note that if you
called login() with auto_prompt_reset set to False then you should have
manually set the PROMPT attribute to a regex pattern for matching the
prompt. | This matches the shell prompt. This is little more than a short-cut
to the expect() method. This returns True if the shell prompt was
matched. This returns False if there was a timeout. Note that if you
called login() with auto_prompt_reset set to False then you should have
manually set the PROMPT attribute to a regex pattern for matching the
prompt. | [
"This",
"matches",
"the",
"shell",
"prompt",
".",
"This",
"is",
"little",
"more",
"than",
"a",
"short",
"-",
"cut",
"to",
"the",
"expect",
"()",
"method",
".",
"This",
"returns",
"True",
"if",
"the",
"shell",
"prompt",
"was",
"matched",
".",
"This",
"r... | def prompt(self, timeout=20):
"""This matches the shell prompt. This is little more than a short-cut
to the expect() method. This returns True if the shell prompt was
matched. This returns False if there was a timeout. Note that if you
called login() with auto_prompt_reset set to False then you should have
manually set the PROMPT attribute to a regex pattern for matching the
prompt. """
i = self.expect([self.PROMPT, TIMEOUT], timeout=timeout)
if i == 1:
return False
return True | [
"def",
"prompt",
"(",
"self",
",",
"timeout",
"=",
"20",
")",
":",
"i",
"=",
"self",
".",
"expect",
"(",
"[",
"self",
".",
"PROMPT",
",",
"TIMEOUT",
"]",
",",
"timeout",
"=",
"timeout",
")",
"if",
"i",
"==",
"1",
":",
"return",
"False",
"return",... | https://github.com/hfinkel/llvm-project-cxxjit/blob/91084ef018240bbb8e24235ff5cd8c355a9c1a1e/lldb/third_party/Python/module/pexpect-2.4/pxssh.py#L328-L339 | |
google/mysql-protobuf | 467cda676afaa49e762c5c9164a43f6ad31a1fbf | storage/ndb/mcc/tst/xmlrunner2.py | python | XMLTestResult.stopTestRun | (self) | Called once after all tests are executed.
See stopTest for a method called after each test. | Called once after all tests are executed. | [
"Called",
"once",
"after",
"all",
"tests",
"are",
"executed",
"."
] | def stopTestRun(self):
"""Called once after all tests are executed.
See stopTest for a method called after each test.
"""
#print 'Calling super().stopTestRun'
super(type(self), self).stopTestRun()
#print 'After super().stopTestRun'
self._ts['element'].set('errors',str(len(self.errors)))
# TODO - do we need to add unexpected successes here?
self._ts['element'].set('failures',str(len(self.failures)))
self._ts['element'].set('skipped',str(len(self.skipped)))
self._ts['element'].set('tests', str(self.testsRun))
self._ts['element'].set('time',str(time.time()-self._ts['stime']))
self._ts['element'].set('timestamp',str(time.localtime(time.time())))
self._tb.end('testsuite') | [
"def",
"stopTestRun",
"(",
"self",
")",
":",
"#print 'Calling super().stopTestRun'",
"super",
"(",
"type",
"(",
"self",
")",
",",
"self",
")",
".",
"stopTestRun",
"(",
")",
"#print 'After super().stopTestRun'",
"self",
".",
"_ts",
"[",
"'element'",
"]",
".",
"... | https://github.com/google/mysql-protobuf/blob/467cda676afaa49e762c5c9164a43f6ad31a1fbf/storage/ndb/mcc/tst/xmlrunner2.py#L94-L110 | ||
pirobot/rbx2 | 2a6544799fcf062e7b6bd5cf2981b2a84c0c7d2a | rbx2_msgs/src/rbx2_msgs/srv/_SetBatteryLevel.py | python | SetBatteryLevelRequest.serialize_numpy | (self, buff, numpy) | serialize message with numpy array types into buffer
:param buff: buffer, ``StringIO``
:param numpy: numpy python module | serialize message with numpy array types into buffer
:param buff: buffer, ``StringIO``
:param numpy: numpy python module | [
"serialize",
"message",
"with",
"numpy",
"array",
"types",
"into",
"buffer",
":",
"param",
"buff",
":",
"buffer",
"StringIO",
":",
"param",
"numpy",
":",
"numpy",
"python",
"module"
] | def serialize_numpy(self, buff, numpy):
"""
serialize message with numpy array types into buffer
:param buff: buffer, ``StringIO``
:param numpy: numpy python module
"""
try:
buff.write(_struct_f.pack(self.value))
except struct.error as se: self._check_types(se)
except TypeError as te: self._check_types(te) | [
"def",
"serialize_numpy",
"(",
"self",
",",
"buff",
",",
"numpy",
")",
":",
"try",
":",
"buff",
".",
"write",
"(",
"_struct_f",
".",
"pack",
"(",
"self",
".",
"value",
")",
")",
"except",
"struct",
".",
"error",
"as",
"se",
":",
"self",
".",
"_chec... | https://github.com/pirobot/rbx2/blob/2a6544799fcf062e7b6bd5cf2981b2a84c0c7d2a/rbx2_msgs/src/rbx2_msgs/srv/_SetBatteryLevel.py#L71-L80 | ||
yuxng/DA-RNN | 77fbb50b4272514588a10a9f90b7d5f8d46974fb | lib/datasets/shapenet_scene.py | python | shapenet_scene.depth_path_from_index | (self, index) | return depth_path | Construct an depth path from the image's "index" identifier. | Construct an depth path from the image's "index" identifier. | [
"Construct",
"an",
"depth",
"path",
"from",
"the",
"image",
"s",
"index",
"identifier",
"."
] | def depth_path_from_index(self, index):
"""
Construct an depth path from the image's "index" identifier.
"""
depth_path = os.path.join(self._data_path, index + '_depth' + self._image_ext)
assert os.path.exists(depth_path), \
'Path does not exist: {}'.format(depth_path)
return depth_path | [
"def",
"depth_path_from_index",
"(",
"self",
",",
"index",
")",
":",
"depth_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_data_path",
",",
"index",
"+",
"'_depth'",
"+",
"self",
".",
"_image_ext",
")",
"assert",
"os",
".",
"path",
"."... | https://github.com/yuxng/DA-RNN/blob/77fbb50b4272514588a10a9f90b7d5f8d46974fb/lib/datasets/shapenet_scene.py#L55-L63 | |
Ewenwan/MVision | 97b394dfa48cb21c82cd003b1a952745e413a17f | deepLearning/08_dbn.py | python | DBN.__init__ | (self, n_in=784, n_out=10, hidden_layers_sizes=[500, 500]) | :param n_in: int, the dimension of input
:param n_out: int, the dimension of output
:param hidden_layers_sizes: list or tuple, the hidden layer sizes | :param n_in: int, the dimension of input
:param n_out: int, the dimension of output
:param hidden_layers_sizes: list or tuple, the hidden layer sizes | [
":",
"param",
"n_in",
":",
"int",
"the",
"dimension",
"of",
"input",
":",
"param",
"n_out",
":",
"int",
"the",
"dimension",
"of",
"output",
":",
"param",
"hidden_layers_sizes",
":",
"list",
"or",
"tuple",
"the",
"hidden",
"layer",
"sizes"
] | def __init__(self, n_in=784, n_out=10, hidden_layers_sizes=[500, 500]):
"""
:param n_in: int, the dimension of input
:param n_out: int, the dimension of output
:param hidden_layers_sizes: list or tuple, the hidden layer sizes
"""
# Number of layers
assert len(hidden_layers_sizes) > 0
self.n_layers = len(hidden_layers_sizes)
self.layers = [] # normal sigmoid layer
self.rbm_layers = [] # RBM layer
self.params = [] # keep track of params for training
# Define the input and output
self.x = tf.placeholder(tf.float32, shape=[None, n_in])
self.y = tf.placeholder(tf.float32, shape=[None, n_out])
# Contruct the layers of DBN
for i in range(self.n_layers):
if i == 0:
layer_input = self.x
input_size = n_in
else:
layer_input = self.layers[i-1].output
input_size = hidden_layers_sizes[i-1]
# Sigmoid layer
sigmoid_layer = HiddenLayer(inpt=layer_input, n_in=input_size, n_out=hidden_layers_sizes[i],
activation=tf.nn.sigmoid)
self.layers.append(sigmoid_layer)
# Add the parameters for finetuning
self.params.extend(sigmoid_layer.params)
# Create the RBM layer
self.rbm_layers.append(RBM(inpt=layer_input, n_visiable=input_size, n_hidden=hidden_layers_sizes[i],
W=sigmoid_layer.W, hbias=sigmoid_layer.b))
# We use the LogisticRegression layer as the output layer
self.output_layer = LogisticRegression(inpt=self.layers[-1].output, n_in=hidden_layers_sizes[-1],
n_out=n_out)
self.params.extend(self.output_layer.params)
# The finetuning cost
self.cost = self.output_layer.cost(self.y)
# The accuracy
self.accuracy = self.output_layer.accuarcy(self.y) | [
"def",
"__init__",
"(",
"self",
",",
"n_in",
"=",
"784",
",",
"n_out",
"=",
"10",
",",
"hidden_layers_sizes",
"=",
"[",
"500",
",",
"500",
"]",
")",
":",
"# Number of layers",
"assert",
"len",
"(",
"hidden_layers_sizes",
")",
">",
"0",
"self",
".",
"n_... | https://github.com/Ewenwan/MVision/blob/97b394dfa48cb21c82cd003b1a952745e413a17f/deepLearning/08_dbn.py#L21-L62 | ||
LiquidPlayer/LiquidCore | 9405979363f2353ac9a71ad8ab59685dd7f919c9 | deps/node-10.15.3/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xcodeproj_file.py | python | XCObject.Comment | (self) | return self.Name() | Return a comment string for the object.
Most objects just use their name as the comment, but PBXProject uses
different values.
The returned comment is not escaped and does not have any comment marker
strings applied to it. | Return a comment string for the object. | [
"Return",
"a",
"comment",
"string",
"for",
"the",
"object",
"."
] | def Comment(self):
"""Return a comment string for the object.
Most objects just use their name as the comment, but PBXProject uses
different values.
The returned comment is not escaped and does not have any comment marker
strings applied to it.
"""
return self.Name() | [
"def",
"Comment",
"(",
"self",
")",
":",
"return",
"self",
".",
"Name",
"(",
")"
] | https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xcodeproj_file.py#L371-L381 | |
sigmaai/self-driving-golf-cart | 8d891600af3d851add27a10ae45cf3c2108bb87c | ros/src/ros_carla_bridge/carla_ros_bridge/src/carla_ros_bridge/transforms.py | python | carla_location_to_ros_vector3 | (carla_location) | return ros_translation | Convert a carla location to a ROS vector3
Considers the conversion from left-handed system (unreal) to right-handed
system (ROS)
:param carla_location: the carla location
:type carla_location: carla.Location
:return: a ROS vector3
:rtype: geometry_msgs.msg.Vector3 | Convert a carla location to a ROS vector3 | [
"Convert",
"a",
"carla",
"location",
"to",
"a",
"ROS",
"vector3"
] | def carla_location_to_ros_vector3(carla_location):
"""
Convert a carla location to a ROS vector3
Considers the conversion from left-handed system (unreal) to right-handed
system (ROS)
:param carla_location: the carla location
:type carla_location: carla.Location
:return: a ROS vector3
:rtype: geometry_msgs.msg.Vector3
"""
ros_translation = Vector3()
ros_translation.x = carla_location.x
ros_translation.y = -carla_location.y
ros_translation.z = carla_location.z
return ros_translation | [
"def",
"carla_location_to_ros_vector3",
"(",
"carla_location",
")",
":",
"ros_translation",
"=",
"Vector3",
"(",
")",
"ros_translation",
".",
"x",
"=",
"carla_location",
".",
"x",
"ros_translation",
".",
"y",
"=",
"-",
"carla_location",
".",
"y",
"ros_translation"... | https://github.com/sigmaai/self-driving-golf-cart/blob/8d891600af3d851add27a10ae45cf3c2108bb87c/ros/src/ros_carla_bridge/carla_ros_bridge/src/carla_ros_bridge/transforms.py#L39-L56 | |
microsoft/EdgeML | ef9f8a77f096acbdeb941014791f8eda1c1bc35b | pytorch/edgeml_pytorch/trainer/drocclf_trainer.py | python | cal_precision_recall | (positive_scores, far_neg_scores, close_neg_scores, fpr) | return precision, recall | Computes the precision and recall for the given false positive rate. | Computes the precision and recall for the given false positive rate. | [
"Computes",
"the",
"precision",
"and",
"recall",
"for",
"the",
"given",
"false",
"positive",
"rate",
"."
] | def cal_precision_recall(positive_scores, far_neg_scores, close_neg_scores, fpr):
"""
Computes the precision and recall for the given false positive rate.
"""
#combine the far and close negative scores
all_neg_scores = np.concatenate((far_neg_scores, close_neg_scores), axis = 0)
num_neg = all_neg_scores.shape[0]
idx = int((1-fpr) * num_neg)
#sort scores in ascending order
all_neg_scores.sort()
thresh = all_neg_scores[idx]
tp = np.sum(positive_scores > thresh)
recall = tp/positive_scores.shape[0]
fp = int(fpr * num_neg)
precision = tp/(tp+fp)
return precision, recall | [
"def",
"cal_precision_recall",
"(",
"positive_scores",
",",
"far_neg_scores",
",",
"close_neg_scores",
",",
"fpr",
")",
":",
"#combine the far and close negative scores",
"all_neg_scores",
"=",
"np",
".",
"concatenate",
"(",
"(",
"far_neg_scores",
",",
"close_neg_scores",... | https://github.com/microsoft/EdgeML/blob/ef9f8a77f096acbdeb941014791f8eda1c1bc35b/pytorch/edgeml_pytorch/trainer/drocclf_trainer.py#L10-L25 | |
idaholab/moose | 9eeebc65e098b4c30f8205fb41591fd5b61eb6ff | python/peacock/ExodusViewer/plugins/ColorbarPlugin.py | python | ColorbarPlugin.updateOptions | (self) | Update result/reader options for this widget. | Update result/reader options for this widget. | [
"Update",
"result",
"/",
"reader",
"options",
"for",
"this",
"widget",
"."
] | def updateOptions(self):
"""
Update result/reader options for this widget.
"""
self.updateResultOptions()
self.updateColorbarOptions() | [
"def",
"updateOptions",
"(",
"self",
")",
":",
"self",
".",
"updateResultOptions",
"(",
")",
"self",
".",
"updateColorbarOptions",
"(",
")"
] | https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/peacock/ExodusViewer/plugins/ColorbarPlugin.py#L171-L176 | ||
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/contrib/slim/python/slim/nets/inception_v1.py | python | inception_v1_arg_scope | (weight_decay=0.00004,
use_batch_norm=True,
batch_norm_var_collection='moving_vars') | Defines the default InceptionV1 arg scope.
Note: Althougth the original paper didn't use batch_norm we found it useful.
Args:
weight_decay: The weight decay to use for regularizing the model.
use_batch_norm: "If `True`, batch_norm is applied after each convolution.
batch_norm_var_collection: The name of the collection for the batch norm
variables.
Returns:
An `arg_scope` to use for the inception v3 model. | Defines the default InceptionV1 arg scope. | [
"Defines",
"the",
"default",
"InceptionV1",
"arg",
"scope",
"."
] | def inception_v1_arg_scope(weight_decay=0.00004,
use_batch_norm=True,
batch_norm_var_collection='moving_vars'):
"""Defines the default InceptionV1 arg scope.
Note: Althougth the original paper didn't use batch_norm we found it useful.
Args:
weight_decay: The weight decay to use for regularizing the model.
use_batch_norm: "If `True`, batch_norm is applied after each convolution.
batch_norm_var_collection: The name of the collection for the batch norm
variables.
Returns:
An `arg_scope` to use for the inception v3 model.
"""
batch_norm_params = {
# Decay for the moving averages.
'decay': 0.9997,
# epsilon to prevent 0s in variance.
'epsilon': 0.001,
# collection containing update_ops.
'updates_collections': tf.GraphKeys.UPDATE_OPS,
# collection containing the moving mean and moving variance.
'variables_collections': {
'beta': None,
'gamma': None,
'moving_mean': [batch_norm_var_collection],
'moving_variance': [batch_norm_var_collection],
}
}
if use_batch_norm:
normalizer_fn = slim.batch_norm
normalizer_params = batch_norm_params
else:
normalizer_fn = None
normalizer_params = {}
# Set weight_decay for weights in Conv and FC layers.
with slim.arg_scope([slim.conv2d, slim.fully_connected],
weights_regularizer=slim.l2_regularizer(weight_decay)):
with slim.arg_scope(
[slim.conv2d],
weights_initializer=slim.variance_scaling_initializer(),
activation_fn=tf.nn.relu,
normalizer_fn=normalizer_fn,
normalizer_params=normalizer_params) as sc:
return sc | [
"def",
"inception_v1_arg_scope",
"(",
"weight_decay",
"=",
"0.00004",
",",
"use_batch_norm",
"=",
"True",
",",
"batch_norm_var_collection",
"=",
"'moving_vars'",
")",
":",
"batch_norm_params",
"=",
"{",
"# Decay for the moving averages.",
"'decay'",
":",
"0.9997",
",",
... | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/contrib/slim/python/slim/nets/inception_v1.py#L304-L350 | ||
apple/swift-lldb | d74be846ef3e62de946df343e8c234bde93a8912 | scripts/Python/static-binding/lldb.py | python | SBCommandReturnObject.SetStatus | (self, status) | return _lldb.SBCommandReturnObject_SetStatus(self, status) | SetStatus(SBCommandReturnObject self, lldb::ReturnStatus status) | SetStatus(SBCommandReturnObject self, lldb::ReturnStatus status) | [
"SetStatus",
"(",
"SBCommandReturnObject",
"self",
"lldb",
"::",
"ReturnStatus",
"status",
")"
] | def SetStatus(self, status):
"""SetStatus(SBCommandReturnObject self, lldb::ReturnStatus status)"""
return _lldb.SBCommandReturnObject_SetStatus(self, status) | [
"def",
"SetStatus",
"(",
"self",
",",
"status",
")",
":",
"return",
"_lldb",
".",
"SBCommandReturnObject_SetStatus",
"(",
"self",
",",
"status",
")"
] | https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L2901-L2903 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/profiler/internal/flops_registry.py | python | _minimum_flops | (graph, node) | return _binary_per_element_op_flops(graph, node) | Compute flops for Minimum operation. | Compute flops for Minimum operation. | [
"Compute",
"flops",
"for",
"Minimum",
"operation",
"."
] | def _minimum_flops(graph, node):
"""Compute flops for Minimum operation."""
return _binary_per_element_op_flops(graph, node) | [
"def",
"_minimum_flops",
"(",
"graph",
",",
"node",
")",
":",
"return",
"_binary_per_element_op_flops",
"(",
"graph",
",",
"node",
")"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/profiler/internal/flops_registry.py#L174-L176 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/wheel/vendored/packaging/tags.py | python | compatible_tags | (
python_version=None, # type: Optional[PythonVersion]
interpreter=None, # type: Optional[str]
platforms=None, # type: Optional[Iterable[str]]
) | Yields the sequence of tags that are compatible with a specific version of Python.
The tags consist of:
- py*-none-<platform>
- <interpreter>-none-any # ... if `interpreter` is provided.
- py*-none-any | Yields the sequence of tags that are compatible with a specific version of Python. | [
"Yields",
"the",
"sequence",
"of",
"tags",
"that",
"are",
"compatible",
"with",
"a",
"specific",
"version",
"of",
"Python",
"."
] | def compatible_tags(
python_version=None, # type: Optional[PythonVersion]
interpreter=None, # type: Optional[str]
platforms=None, # type: Optional[Iterable[str]]
):
# type: (...) -> Iterator[Tag]
"""
Yields the sequence of tags that are compatible with a specific version of Python.
The tags consist of:
- py*-none-<platform>
- <interpreter>-none-any # ... if `interpreter` is provided.
- py*-none-any
"""
if not python_version:
python_version = sys.version_info[:2]
platforms = list(platforms or _platform_tags())
for version in _py_interpreter_range(python_version):
for platform_ in platforms:
yield Tag(version, "none", platform_)
if interpreter:
yield Tag(interpreter, "none", "any")
for version in _py_interpreter_range(python_version):
yield Tag(version, "none", "any") | [
"def",
"compatible_tags",
"(",
"python_version",
"=",
"None",
",",
"# type: Optional[PythonVersion]",
"interpreter",
"=",
"None",
",",
"# type: Optional[str]",
"platforms",
"=",
"None",
",",
"# type: Optional[Iterable[str]]",
")",
":",
"# type: (...) -> Iterator[Tag]",
"if"... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/wheel/vendored/packaging/tags.py#L349-L372 | ||
ceph/ceph | 959663007321a369c83218414a29bd9dbc8bda3a | src/python-common/ceph/deployment/translate.py | python | to_ceph_volume.run | (self) | return cmd | Generate ceph-volume commands based on the DriveGroup filters | Generate ceph-volume commands based on the DriveGroup filters | [
"Generate",
"ceph",
"-",
"volume",
"commands",
"based",
"on",
"the",
"DriveGroup",
"filters"
] | def run(self):
# type: () -> Optional[str]
""" Generate ceph-volume commands based on the DriveGroup filters """
data_devices = [x.path for x in self.selection.data_devices()]
db_devices = [x.path for x in self.selection.db_devices()]
wal_devices = [x.path for x in self.selection.wal_devices()]
journal_devices = [x.path for x in self.selection.journal_devices()]
if not data_devices:
return None
cmd = ""
if self.spec.method == 'raw':
assert self.spec.objectstore == 'bluestore'
cmd = "raw prepare --bluestore"
cmd += " --data {}".format(" ".join(data_devices))
if db_devices:
cmd += " --block.db {}".format(" ".join(db_devices))
if wal_devices:
cmd += " --block.wal {}".format(" ".join(wal_devices))
elif self.spec.objectstore == 'filestore':
cmd = "lvm batch --no-auto"
cmd += " {}".format(" ".join(data_devices))
if self.spec.journal_size:
cmd += " --journal-size {}".format(self.spec.journal_size)
if journal_devices:
cmd += " --journal-devices {}".format(
' '.join(journal_devices))
cmd += " --filestore"
elif self.spec.objectstore == 'bluestore':
cmd = "lvm batch --no-auto {}".format(" ".join(data_devices))
if db_devices:
cmd += " --db-devices {}".format(" ".join(db_devices))
if wal_devices:
cmd += " --wal-devices {}".format(" ".join(wal_devices))
if self.spec.block_wal_size:
cmd += " --block-wal-size {}".format(self.spec.block_wal_size)
if self.spec.block_db_size:
cmd += " --block-db-size {}".format(self.spec.block_db_size)
if self.spec.encrypted:
cmd += " --dmcrypt"
if self.spec.osds_per_device:
cmd += " --osds-per-device {}".format(self.spec.osds_per_device)
if self.spec.data_allocate_fraction:
cmd += " --data-allocate-fraction {}".format(self.spec.data_allocate_fraction)
if self.osd_id_claims:
cmd += " --osd-ids {}".format(" ".join(self.osd_id_claims))
if self.spec.method != 'raw':
cmd += " --yes"
cmd += " --no-systemd"
if self.preview:
cmd += " --report"
cmd += " --format json"
return cmd | [
"def",
"run",
"(",
"self",
")",
":",
"# type: () -> Optional[str]",
"data_devices",
"=",
"[",
"x",
".",
"path",
"for",
"x",
"in",
"self",
".",
"selection",
".",
"data_devices",
"(",
")",
"]",
"db_devices",
"=",
"[",
"x",
".",
"path",
"for",
"x",
"in",
... | https://github.com/ceph/ceph/blob/959663007321a369c83218414a29bd9dbc8bda3a/src/python-common/ceph/deployment/translate.py#L27-L98 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/aui.py | python | AuiMDIChildFrame.Restore | (*args, **kwargs) | return _aui.AuiMDIChildFrame_Restore(*args, **kwargs) | Restore(self) | Restore(self) | [
"Restore",
"(",
"self",
")"
] | def Restore(*args, **kwargs):
"""Restore(self)"""
return _aui.AuiMDIChildFrame_Restore(*args, **kwargs) | [
"def",
"Restore",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_aui",
".",
"AuiMDIChildFrame_Restore",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/aui.py#L1566-L1568 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/richtext.py | python | RichTextDrawingContext.HasVirtualAttributes | (*args, **kwargs) | return _richtext.RichTextDrawingContext_HasVirtualAttributes(*args, **kwargs) | HasVirtualAttributes(self, RichTextObject obj) -> bool | HasVirtualAttributes(self, RichTextObject obj) -> bool | [
"HasVirtualAttributes",
"(",
"self",
"RichTextObject",
"obj",
")",
"-",
">",
"bool"
] | def HasVirtualAttributes(*args, **kwargs):
"""HasVirtualAttributes(self, RichTextObject obj) -> bool"""
return _richtext.RichTextDrawingContext_HasVirtualAttributes(*args, **kwargs) | [
"def",
"HasVirtualAttributes",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_richtext",
".",
"RichTextDrawingContext_HasVirtualAttributes",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/richtext.py#L1090-L1092 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/maya/script/cryAlembic.py | python | prepareMaterials | (*args) | inline call for Ui | inline call for Ui | [
"inline",
"call",
"for",
"Ui"
] | def prepareMaterials(*args):
"""inline call for Ui"""
mesh, sgs = getMeshAndSGs()
sgs= renameShadingEngines(sgs)
enforcePerFaceAssignment(sgs) | [
"def",
"prepareMaterials",
"(",
"*",
"args",
")",
":",
"mesh",
",",
"sgs",
"=",
"getMeshAndSGs",
"(",
")",
"sgs",
"=",
"renameShadingEngines",
"(",
"sgs",
")",
"enforcePerFaceAssignment",
"(",
"sgs",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/maya/script/cryAlembic.py#L199-L203 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/aui/framemanager.py | python | AuiPaneInfo.Centre | (self) | return self | Sets the pane to the center position of the frame.
The centre pane is the space in the middle after all border panes (left, top,
right, bottom) are subtracted from the layout.
:note: This is the same thing as calling :meth:`~AuiPaneInfo.Direction` with ``AUI_DOCK_CENTRE`` as
parameter. | Sets the pane to the center position of the frame. | [
"Sets",
"the",
"pane",
"to",
"the",
"center",
"position",
"of",
"the",
"frame",
"."
] | def Centre(self):
"""
Sets the pane to the center position of the frame.
The centre pane is the space in the middle after all border panes (left, top,
right, bottom) are subtracted from the layout.
:note: This is the same thing as calling :meth:`~AuiPaneInfo.Direction` with ``AUI_DOCK_CENTRE`` as
parameter.
"""
self.dock_direction = AUI_DOCK_CENTRE
return self | [
"def",
"Centre",
"(",
"self",
")",
":",
"self",
".",
"dock_direction",
"=",
"AUI_DOCK_CENTRE",
"return",
"self"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/aui/framemanager.py#L971-L983 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/cookielib.py | python | request_host | (request) | return host.lower() | Return request-host, as defined by RFC 2965.
Variation from RFC: returned value is lowercased, for convenient
comparison. | Return request-host, as defined by RFC 2965. | [
"Return",
"request",
"-",
"host",
"as",
"defined",
"by",
"RFC",
"2965",
"."
] | def request_host(request):
"""Return request-host, as defined by RFC 2965.
Variation from RFC: returned value is lowercased, for convenient
comparison.
"""
url = request.get_full_url()
host = urlparse.urlparse(url)[1]
if host == "":
host = request.get_header("Host", "")
# remove port, if present
host = cut_port_re.sub("", host, 1)
return host.lower() | [
"def",
"request_host",
"(",
"request",
")",
":",
"url",
"=",
"request",
".",
"get_full_url",
"(",
")",
"host",
"=",
"urlparse",
".",
"urlparse",
"(",
"url",
")",
"[",
"1",
"]",
"if",
"host",
"==",
"\"\"",
":",
"host",
"=",
"request",
".",
"get_header... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/cookielib.py#L582-L596 | |
google/llvm-propeller | 45c226984fe8377ebfb2ad7713c680d652ba678d | clang/bindings/python/clang/cindex.py | python | TranslationUnit.__init__ | (self, ptr, index) | Create a TranslationUnit instance.
TranslationUnits should be created using one of the from_* @classmethod
functions above. __init__ is only called internally. | Create a TranslationUnit instance. | [
"Create",
"a",
"TranslationUnit",
"instance",
"."
] | def __init__(self, ptr, index):
"""Create a TranslationUnit instance.
TranslationUnits should be created using one of the from_* @classmethod
functions above. __init__ is only called internally.
"""
assert isinstance(index, Index)
self.index = index
ClangObject.__init__(self, ptr) | [
"def",
"__init__",
"(",
"self",
",",
"ptr",
",",
"index",
")",
":",
"assert",
"isinstance",
"(",
"index",
",",
"Index",
")",
"self",
".",
"index",
"=",
"index",
"ClangObject",
".",
"__init__",
"(",
"self",
",",
"ptr",
")"
] | https://github.com/google/llvm-propeller/blob/45c226984fe8377ebfb2ad7713c680d652ba678d/clang/bindings/python/clang/cindex.py#L2864-L2872 | ||
CalcProgrammer1/OpenRGB | 8156b0167a7590dd8ba561dfde524bfcacf46b5e | dependencies/mbedtls-2.24.0/scripts/abi_check.py | python | AbiChecker._get_clean_worktree_for_git_revision | (self, version) | return git_worktree_path | Make a separate worktree with version.revision checked out.
Do not modify the current worktree. | Make a separate worktree with version.revision checked out.
Do not modify the current worktree. | [
"Make",
"a",
"separate",
"worktree",
"with",
"version",
".",
"revision",
"checked",
"out",
".",
"Do",
"not",
"modify",
"the",
"current",
"worktree",
"."
] | def _get_clean_worktree_for_git_revision(self, version):
"""Make a separate worktree with version.revision checked out.
Do not modify the current worktree."""
git_worktree_path = tempfile.mkdtemp()
if version.repository:
self.log.debug(
"Checking out git worktree for revision {} from {}".format(
version.revision, version.repository
)
)
fetch_output = subprocess.check_output(
[self.git_command, "fetch",
version.repository, version.revision],
cwd=self.repo_path,
stderr=subprocess.STDOUT
)
self.log.debug(fetch_output.decode("utf-8"))
worktree_rev = "FETCH_HEAD"
else:
self.log.debug("Checking out git worktree for revision {}".format(
version.revision
))
worktree_rev = version.revision
worktree_output = subprocess.check_output(
[self.git_command, "worktree", "add", "--detach",
git_worktree_path, worktree_rev],
cwd=self.repo_path,
stderr=subprocess.STDOUT
)
self.log.debug(worktree_output.decode("utf-8"))
version.commit = subprocess.check_output(
[self.git_command, "rev-parse", "HEAD"],
cwd=git_worktree_path,
stderr=subprocess.STDOUT
).decode("ascii").rstrip()
self.log.debug("Commit is {}".format(version.commit))
return git_worktree_path | [
"def",
"_get_clean_worktree_for_git_revision",
"(",
"self",
",",
"version",
")",
":",
"git_worktree_path",
"=",
"tempfile",
".",
"mkdtemp",
"(",
")",
"if",
"version",
".",
"repository",
":",
"self",
".",
"log",
".",
"debug",
"(",
"\"Checking out git worktree for r... | https://github.com/CalcProgrammer1/OpenRGB/blob/8156b0167a7590dd8ba561dfde524bfcacf46b5e/dependencies/mbedtls-2.24.0/scripts/abi_check.py#L90-L126 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/systrace/systrace/util.py | python | run_adb_shell | (shell_args, device_serial) | return run_adb_command(adb_command) | Runs "adb shell" with the given arguments.
Args:
shell_args: array of arguments to pass to adb shell.
device_serial: if not empty, will add the appropriate command-line
parameters so that adb targets the given device.
Returns:
A tuple containing the adb output (stdout & stderr) and the return code
from adb. Will exit if adb fails to start. | Runs "adb shell" with the given arguments. | [
"Runs",
"adb",
"shell",
"with",
"the",
"given",
"arguments",
"."
] | def run_adb_shell(shell_args, device_serial):
"""Runs "adb shell" with the given arguments.
Args:
shell_args: array of arguments to pass to adb shell.
device_serial: if not empty, will add the appropriate command-line
parameters so that adb targets the given device.
Returns:
A tuple containing the adb output (stdout & stderr) and the return code
from adb. Will exit if adb fails to start.
"""
adb_command = construct_adb_shell_command(shell_args, device_serial)
return run_adb_command(adb_command) | [
"def",
"run_adb_shell",
"(",
"shell_args",
",",
"device_serial",
")",
":",
"adb_command",
"=",
"construct_adb_shell_command",
"(",
"shell_args",
",",
"device_serial",
")",
"return",
"run_adb_command",
"(",
"adb_command",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/systrace/systrace/util.py#L84-L96 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/rfc822.py | python | AddrlistClass.getrouteaddr | (self) | return adlist | Parse a route address (Return-path value).
This method just skips all the route stuff and returns the addrspec. | Parse a route address (Return-path value). | [
"Parse",
"a",
"route",
"address",
"(",
"Return",
"-",
"path",
"value",
")",
"."
] | def getrouteaddr(self):
"""Parse a route address (Return-path value).
This method just skips all the route stuff and returns the addrspec.
"""
if self.field[self.pos] != '<':
return
expectroute = 0
self.pos += 1
self.gotonext()
adlist = ""
while self.pos < len(self.field):
if expectroute:
self.getdomain()
expectroute = 0
elif self.field[self.pos] == '>':
self.pos += 1
break
elif self.field[self.pos] == '@':
self.pos += 1
expectroute = 1
elif self.field[self.pos] == ':':
self.pos += 1
else:
adlist = self.getaddrspec()
self.pos += 1
break
self.gotonext()
return adlist | [
"def",
"getrouteaddr",
"(",
"self",
")",
":",
"if",
"self",
".",
"field",
"[",
"self",
".",
"pos",
"]",
"!=",
"'<'",
":",
"return",
"expectroute",
"=",
"0",
"self",
".",
"pos",
"+=",
"1",
"self",
".",
"gotonext",
"(",
")",
"adlist",
"=",
"\"\"",
... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/rfc822.py#L610-L640 | |
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Arch/ArchRebar.py | python | makeRebar | (baseobj=None,sketch=None,diameter=None,amount=1,offset=None,name="Rebar") | return obj | makeRebar([baseobj,sketch,diameter,amount,offset,name]): adds a Reinforcement Bar object
to the given structural object, using the given sketch as profile. | makeRebar([baseobj,sketch,diameter,amount,offset,name]): adds a Reinforcement Bar object
to the given structural object, using the given sketch as profile. | [
"makeRebar",
"(",
"[",
"baseobj",
"sketch",
"diameter",
"amount",
"offset",
"name",
"]",
")",
":",
"adds",
"a",
"Reinforcement",
"Bar",
"object",
"to",
"the",
"given",
"structural",
"object",
"using",
"the",
"given",
"sketch",
"as",
"profile",
"."
] | def makeRebar(baseobj=None,sketch=None,diameter=None,amount=1,offset=None,name="Rebar"):
"""makeRebar([baseobj,sketch,diameter,amount,offset,name]): adds a Reinforcement Bar object
to the given structural object, using the given sketch as profile."""
if not FreeCAD.ActiveDocument:
FreeCAD.Console.PrintError("No active document. Aborting\n")
return
p = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Arch")
obj = FreeCAD.ActiveDocument.addObject("Part::FeaturePython","Rebar")
obj.Label = translate("Arch",name)
_Rebar(obj)
if FreeCAD.GuiUp:
_ViewProviderRebar(obj.ViewObject)
if baseobj and sketch:
if hasattr(sketch,"Support"):
if sketch.Support:
if isinstance(sketch.Support,tuple):
if sketch.Support[0] == baseobj:
sketch.Support = None
elif sketch.Support == baseobj:
sketch.Support = None
obj.Base = sketch
if FreeCAD.GuiUp:
sketch.ViewObject.hide()
obj.Host = baseobj
elif sketch and not baseobj:
# a rebar could be based on a wire without the existence of a Structure
obj.Base = sketch
if FreeCAD.GuiUp:
sketch.ViewObject.hide()
obj.Host = None
if diameter:
obj.Diameter = diameter
else:
obj.Diameter = p.GetFloat("RebarDiameter",6)
obj.Amount = amount
obj.Document.recompute()
if offset != None:
obj.OffsetStart = offset
obj.OffsetEnd = offset
else:
obj.OffsetStart = p.GetFloat("RebarOffset",30)
obj.OffsetEnd = p.GetFloat("RebarOffset",30)
obj.Mark = obj.Label
return obj | [
"def",
"makeRebar",
"(",
"baseobj",
"=",
"None",
",",
"sketch",
"=",
"None",
",",
"diameter",
"=",
"None",
",",
"amount",
"=",
"1",
",",
"offset",
"=",
"None",
",",
"name",
"=",
"\"Rebar\"",
")",
":",
"if",
"not",
"FreeCAD",
".",
"ActiveDocument",
":... | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Arch/ArchRebar.py#L49-L94 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/build/waf-1.7.13/waflib/Tools/c_preproc.py | python | c_parser.tryfind | (self, filename) | return found | Try to obtain a node from the filename based from the include paths. Will add
the node found to :py:attr:`waflib.Tools.c_preproc.c_parser.nodes` or the file name to
:py:attr:`waflib.Tools.c_preproc.c_parser.names` if no corresponding file is found. Called by
:py:attr:`waflib.Tools.c_preproc.c_parser.start`.
:param filename: header to find
:type filename: string
:return: the node if found
:rtype: :py:class:`waflib.Node.Node` | Try to obtain a node from the filename based from the include paths. Will add
the node found to :py:attr:`waflib.Tools.c_preproc.c_parser.nodes` or the file name to
:py:attr:`waflib.Tools.c_preproc.c_parser.names` if no corresponding file is found. Called by
:py:attr:`waflib.Tools.c_preproc.c_parser.start`. | [
"Try",
"to",
"obtain",
"a",
"node",
"from",
"the",
"filename",
"based",
"from",
"the",
"include",
"paths",
".",
"Will",
"add",
"the",
"node",
"found",
"to",
":",
"py",
":",
"attr",
":",
"waflib",
".",
"Tools",
".",
"c_preproc",
".",
"c_parser",
".",
... | def tryfind(self, filename):
"""
Try to obtain a node from the filename based from the include paths. Will add
the node found to :py:attr:`waflib.Tools.c_preproc.c_parser.nodes` or the file name to
:py:attr:`waflib.Tools.c_preproc.c_parser.names` if no corresponding file is found. Called by
:py:attr:`waflib.Tools.c_preproc.c_parser.start`.
:param filename: header to find
:type filename: string
:return: the node if found
:rtype: :py:class:`waflib.Node.Node`
"""
if filename.endswith('.moc'):
# we could let the qt4 module use a subclass, but then the function "scan" below must be duplicated
# in the qt4 and in the qt5 classes. So we have two lines here and it is sufficient. TODO waf 1.9
self.names.append(filename)
return None
self.curfile = filename
# for msvc it should be a for loop on the whole stack
found = self.cached_find_resource(self.currentnode_stack[-1], filename)
for n in self.nodepaths:
if found:
break
found = self.cached_find_resource(n, filename)
if found and not found in self.ban_includes:
# TODO the duplicates do not increase the no-op build times too much, but they may be worth removing
self.nodes.append(found)
self.addlines(found)
else:
if not filename in self.names:
self.names.append(filename)
return found | [
"def",
"tryfind",
"(",
"self",
",",
"filename",
")",
":",
"if",
"filename",
".",
"endswith",
"(",
"'.moc'",
")",
":",
"# we could let the qt4 module use a subclass, but then the function \"scan\" below must be duplicated",
"# in the qt4 and in the qt5 classes. So we have two lines ... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/build/waf-1.7.13/waflib/Tools/c_preproc.py#L832-L867 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/xml/dom/expatbuilder.py | python | FragmentBuilder.parseFile | (self, file) | return self.parseString(file.read()) | Parse a document fragment from a file object, returning the
fragment node. | Parse a document fragment from a file object, returning the
fragment node. | [
"Parse",
"a",
"document",
"fragment",
"from",
"a",
"file",
"object",
"returning",
"the",
"fragment",
"node",
"."
] | def parseFile(self, file):
"""Parse a document fragment from a file object, returning the
fragment node."""
return self.parseString(file.read()) | [
"def",
"parseFile",
"(",
"self",
",",
"file",
")",
":",
"return",
"self",
".",
"parseString",
"(",
"file",
".",
"read",
"(",
")",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/xml/dom/expatbuilder.py#L623-L626 | |
KratosMultiphysics/Kratos | 0000833054ed0503424eb28205d6508d9ca6cbbc | kratos/python_scripts/python_solver.py | python | PythonSolver.SolveSolutionStep | (self) | return True | This function solves the current step.
It can be called multiple times within one solution step
Returns whether the problem is converged | This function solves the current step.
It can be called multiple times within one solution step
Returns whether the problem is converged | [
"This",
"function",
"solves",
"the",
"current",
"step",
".",
"It",
"can",
"be",
"called",
"multiple",
"times",
"within",
"one",
"solution",
"step",
"Returns",
"whether",
"the",
"problem",
"is",
"converged"
] | def SolveSolutionStep(self):
"""This function solves the current step.
It can be called multiple times within one solution step
Returns whether the problem is converged
"""
return True | [
"def",
"SolveSolutionStep",
"(",
"self",
")",
":",
"return",
"True"
] | https://github.com/KratosMultiphysics/Kratos/blob/0000833054ed0503424eb28205d6508d9ca6cbbc/kratos/python_scripts/python_solver.py#L127-L132 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/decimal.py | python | Context.radix | (self) | return Decimal(10) | Just returns 10, as this is Decimal, :)
>>> ExtendedContext.radix()
Decimal('10') | Just returns 10, as this is Decimal, :) | [
"Just",
"returns",
"10",
"as",
"this",
"is",
"Decimal",
":",
")"
] | def radix(self):
"""Just returns 10, as this is Decimal, :)
>>> ExtendedContext.radix()
Decimal('10')
"""
return Decimal(10) | [
"def",
"radix",
"(",
"self",
")",
":",
"return",
"Decimal",
"(",
"10",
")"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/decimal.py#L5103-L5109 | |
NVIDIA/MDL-SDK | aa9642b2546ad7b6236b5627385d882c2ed83c5d | src/mdl/jit/generator_jit/gen_user_modules_runtime_header.py | python | eat_until | (token_set, tokens) | return eaten_tokens, [None] | eat tokens until token_kind is found and return them, handle parenthesis | eat tokens until token_kind is found and return them, handle parenthesis | [
"eat",
"tokens",
"until",
"token_kind",
"is",
"found",
"and",
"return",
"them",
"handle",
"parenthesis"
] | def eat_until(token_set, tokens):
"""eat tokens until token_kind is found and return them, handle parenthesis"""
r = 0
e = 0
g = 0
a = 0
l = len(tokens)
eaten_tokens = []
while l > 0:
tok = tokens[0]
if r == 0 and e == 0 and g == 0 and a == 0 and tok in token_set:
return eaten_tokens, tokens
if tok == '(':
r += 1
elif tok == ')':
r -= 1
elif tok == '[':
e += 1
elif tok == ']':
e -= 1
elif tok == '{':
g += 1
elif tok == '}':
g -= 1
elif tok == '[[':
a += 1
elif tok == ']]':
a -= 1
eaten_tokens.append(tokens[0])
tokens = tokens[1:]
l -= 1
# do not return empty tokens, the parser do not like that
return eaten_tokens, [None] | [
"def",
"eat_until",
"(",
"token_set",
",",
"tokens",
")",
":",
"r",
"=",
"0",
"e",
"=",
"0",
"g",
"=",
"0",
"a",
"=",
"0",
"l",
"=",
"len",
"(",
"tokens",
")",
"eaten_tokens",
"=",
"[",
"]",
"while",
"l",
">",
"0",
":",
"tok",
"=",
"tokens",
... | https://github.com/NVIDIA/MDL-SDK/blob/aa9642b2546ad7b6236b5627385d882c2ed83c5d/src/mdl/jit/generator_jit/gen_user_modules_runtime_header.py#L78-L111 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/aui.py | python | AuiPaneInfo.DockFixed | (*args, **kwargs) | return _aui.AuiPaneInfo_DockFixed(*args, **kwargs) | DockFixed(self, bool b=True) -> AuiPaneInfo | DockFixed(self, bool b=True) -> AuiPaneInfo | [
"DockFixed",
"(",
"self",
"bool",
"b",
"=",
"True",
")",
"-",
">",
"AuiPaneInfo"
] | def DockFixed(*args, **kwargs):
"""DockFixed(self, bool b=True) -> AuiPaneInfo"""
return _aui.AuiPaneInfo_DockFixed(*args, **kwargs) | [
"def",
"DockFixed",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_aui",
".",
"AuiPaneInfo_DockFixed",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/aui.py#L501-L503 | |
eventql/eventql | 7ca0dbb2e683b525620ea30dc40540a22d5eb227 | deps/3rdparty/spidermonkey/mozjs/python/psutil/psutil/__init__.py | python | Process.cpu_times | (self) | return self._proc.cpu_times() | Return a (user, system) namedtuple representing the
accumulated process time, in seconds.
This is the same as os.times() but per-process. | Return a (user, system) namedtuple representing the
accumulated process time, in seconds.
This is the same as os.times() but per-process. | [
"Return",
"a",
"(",
"user",
"system",
")",
"namedtuple",
"representing",
"the",
"accumulated",
"process",
"time",
"in",
"seconds",
".",
"This",
"is",
"the",
"same",
"as",
"os",
".",
"times",
"()",
"but",
"per",
"-",
"process",
"."
] | def cpu_times(self):
"""Return a (user, system) namedtuple representing the
accumulated process time, in seconds.
This is the same as os.times() but per-process.
"""
return self._proc.cpu_times() | [
"def",
"cpu_times",
"(",
"self",
")",
":",
"return",
"self",
".",
"_proc",
".",
"cpu_times",
"(",
")"
] | https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/python/psutil/psutil/__init__.py#L873-L878 | |
gromacs/gromacs | 7dec3a3f99993cf5687a122de3e12de31c21c399 | python_packaging/src/gmxapi/operation.py | python | SourceResource.width | (self) | Ensemble width of the managed resources. | Ensemble width of the managed resources. | [
"Ensemble",
"width",
"of",
"the",
"managed",
"resources",
"."
] | def width(self) -> int:
"""Ensemble width of the managed resources."""
... | [
"def",
"width",
"(",
"self",
")",
"->",
"int",
":",
"..."
] | https://github.com/gromacs/gromacs/blob/7dec3a3f99993cf5687a122de3e12de31c21c399/python_packaging/src/gmxapi/operation.py#L797-L799 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/distutils/fancy_getopt.py | python | wrap_text | (text, width) | return lines | wrap_text(text : string, width : int) -> [string]
Split 'text' into multiple lines of no more than 'width' characters
each, and return the list of strings that results. | wrap_text(text : string, width : int) -> [string] | [
"wrap_text",
"(",
"text",
":",
"string",
"width",
":",
"int",
")",
"-",
">",
"[",
"string",
"]"
] | def wrap_text(text, width):
"""wrap_text(text : string, width : int) -> [string]
Split 'text' into multiple lines of no more than 'width' characters
each, and return the list of strings that results.
"""
if text is None:
return []
if len(text) <= width:
return [text]
text = text.expandtabs()
text = text.translate(WS_TRANS)
chunks = re.split(r'( +|-+)', text)
chunks = [ch for ch in chunks if ch] # ' - ' results in empty strings
lines = []
while chunks:
cur_line = [] # list of chunks (to-be-joined)
cur_len = 0 # length of current line
while chunks:
l = len(chunks[0])
if cur_len + l <= width: # can squeeze (at least) this chunk in
cur_line.append(chunks[0])
del chunks[0]
cur_len = cur_len + l
else: # this line is full
# drop last chunk if all space
if cur_line and cur_line[-1][0] == ' ':
del cur_line[-1]
break
if chunks: # any chunks left to process?
# if the current line is still empty, then we had a single
# chunk that's too big too fit on a line -- so we break
# down and break it up at the line width
if cur_len == 0:
cur_line.append(chunks[0][0:width])
chunks[0] = chunks[0][width:]
# all-whitespace chunks at the end of a line can be discarded
# (and we know from the re.split above that if a chunk has
# *any* whitespace, it is *all* whitespace)
if chunks[0][0] == ' ':
del chunks[0]
# and store this line in the list-of-all-lines -- as a single
# string, of course!
lines.append(''.join(cur_line))
return lines | [
"def",
"wrap_text",
"(",
"text",
",",
"width",
")",
":",
"if",
"text",
"is",
"None",
":",
"return",
"[",
"]",
"if",
"len",
"(",
"text",
")",
"<=",
"width",
":",
"return",
"[",
"text",
"]",
"text",
"=",
"text",
".",
"expandtabs",
"(",
")",
"text",... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/distutils/fancy_getopt.py#L375-L426 | |
chipsalliance/verible | aa14e0074ff89945bf65eecfb9ef78684d996058 | verilog/tools/syntax/export_json_examples/verible_verilog_syntax.py | python | BranchNode.iter_find_all | (self, filter_: Union[CallableFilter, KeyValueFilter, None],
max_count: int = 0,
iter_: TreeIterator = LevelOrderTreeIterator,
**kwargs) | Iterate all nodes matching specified filter.
Args:
filter_: Describes what to search for. Might be:
* Callable taking Node as an argument and returning True for accepted
nodes.
* Dict mapping Node attribute names to searched value or list of
searched values.
max_count: Stop searching after finding that many matching nodes.
iter_: Tree iterator. Decides in what order nodes are visited.
Yields:
Nodes matching specified filter. | Iterate all nodes matching specified filter. | [
"Iterate",
"all",
"nodes",
"matching",
"specified",
"filter",
"."
] | def iter_find_all(self, filter_: Union[CallableFilter, KeyValueFilter, None],
max_count: int = 0,
iter_: TreeIterator = LevelOrderTreeIterator,
**kwargs) -> Iterable[Node]:
"""Iterate all nodes matching specified filter.
Args:
filter_: Describes what to search for. Might be:
* Callable taking Node as an argument and returning True for accepted
nodes.
* Dict mapping Node attribute names to searched value or list of
searched values.
max_count: Stop searching after finding that many matching nodes.
iter_: Tree iterator. Decides in what order nodes are visited.
Yields:
Nodes matching specified filter.
"""
def as_list(v):
return v if isinstance(v, list) else [v]
if filter_ and not callable(filter_):
filters = filter_
def f(node):
for attr,value in filters.items():
if not hasattr(node, attr):
return False
if getattr(node, attr) not in as_list(value):
return False
return True
filter_ = f
for node in iter_(self, filter_, **kwargs):
yield node
max_count -= 1
if max_count == 0:
break | [
"def",
"iter_find_all",
"(",
"self",
",",
"filter_",
":",
"Union",
"[",
"CallableFilter",
",",
"KeyValueFilter",
",",
"None",
"]",
",",
"max_count",
":",
"int",
"=",
"0",
",",
"iter_",
":",
"TreeIterator",
"=",
"LevelOrderTreeIterator",
",",
"*",
"*",
"kwa... | https://github.com/chipsalliance/verible/blob/aa14e0074ff89945bf65eecfb9ef78684d996058/verilog/tools/syntax/export_json_examples/verible_verilog_syntax.py#L161-L197 | ||
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Path/PathScripts/PathGui.py | python | QuantitySpinBox.attachTo | (self, obj, prop=None) | attachTo(obj, prop=None) ... use an existing editor for the given object and property | attachTo(obj, prop=None) ... use an existing editor for the given object and property | [
"attachTo",
"(",
"obj",
"prop",
"=",
"None",
")",
"...",
"use",
"an",
"existing",
"editor",
"for",
"the",
"given",
"object",
"and",
"property"
] | def attachTo(self, obj, prop=None):
"""attachTo(obj, prop=None) ... use an existing editor for the given object and property"""
PathLog.track(self.prop, prop)
self.obj = obj
self.prop = prop
if obj and prop:
attr = PathUtil.getProperty(obj, prop)
if attr is not None:
if hasattr(attr, "Value"):
self.widget.setProperty("unit", attr.getUserPreferred()[2])
self.widget.setProperty("binding", "%s.%s" % (obj.Name, prop))
self.valid = True
else:
PathLog.warning("Cannot find property {} of {}".format(prop, obj.Label))
self.valid = False
else:
self.valid = False | [
"def",
"attachTo",
"(",
"self",
",",
"obj",
",",
"prop",
"=",
"None",
")",
":",
"PathLog",
".",
"track",
"(",
"self",
".",
"prop",
",",
"prop",
")",
"self",
".",
"obj",
"=",
"obj",
"self",
".",
"prop",
"=",
"prop",
"if",
"obj",
"and",
"prop",
"... | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Path/PathScripts/PathGui.py#L127-L143 | ||
may0324/DeepCompression-caffe | 0aff6c1287bda4cfc7f378ed8a16524e1afabd8c | scripts/cpp_lint.py | python | Error | (filename, linenum, category, confidence, message) | Logs the fact we've found a lint error.
We log where the error was found, and also our confidence in the error,
that is, how certain we are this is a legitimate style regression, and
not a misidentification or a use that's sometimes justified.
False positives can be suppressed by the use of
"cpplint(category)" comments on the offending line. These are
parsed into _error_suppressions.
Args:
filename: The name of the file containing the error.
linenum: The number of the line containing the error.
category: A string used to describe the "category" this bug
falls under: "whitespace", say, or "runtime". Categories
may have a hierarchy separated by slashes: "whitespace/indent".
confidence: A number from 1-5 representing a confidence score for
the error, with 5 meaning that we are certain of the problem,
and 1 meaning that it could be a legitimate construct.
message: The error message. | Logs the fact we've found a lint error. | [
"Logs",
"the",
"fact",
"we",
"ve",
"found",
"a",
"lint",
"error",
"."
] | def Error(filename, linenum, category, confidence, message):
"""Logs the fact we've found a lint error.
We log where the error was found, and also our confidence in the error,
that is, how certain we are this is a legitimate style regression, and
not a misidentification or a use that's sometimes justified.
False positives can be suppressed by the use of
"cpplint(category)" comments on the offending line. These are
parsed into _error_suppressions.
Args:
filename: The name of the file containing the error.
linenum: The number of the line containing the error.
category: A string used to describe the "category" this bug
falls under: "whitespace", say, or "runtime". Categories
may have a hierarchy separated by slashes: "whitespace/indent".
confidence: A number from 1-5 representing a confidence score for
the error, with 5 meaning that we are certain of the problem,
and 1 meaning that it could be a legitimate construct.
message: The error message.
"""
if _ShouldPrintError(category, confidence, linenum):
_cpplint_state.IncrementErrorCount(category)
if _cpplint_state.output_format == 'vs7':
sys.stderr.write('%s(%s): %s [%s] [%d]\n' % (
filename, linenum, message, category, confidence))
elif _cpplint_state.output_format == 'eclipse':
sys.stderr.write('%s:%s: warning: %s [%s] [%d]\n' % (
filename, linenum, message, category, confidence))
else:
sys.stderr.write('%s:%s: %s [%s] [%d]\n' % (
filename, linenum, message, category, confidence)) | [
"def",
"Error",
"(",
"filename",
",",
"linenum",
",",
"category",
",",
"confidence",
",",
"message",
")",
":",
"if",
"_ShouldPrintError",
"(",
"category",
",",
"confidence",
",",
"linenum",
")",
":",
"_cpplint_state",
".",
"IncrementErrorCount",
"(",
"category... | https://github.com/may0324/DeepCompression-caffe/blob/0aff6c1287bda4cfc7f378ed8a16524e1afabd8c/scripts/cpp_lint.py#L988-L1020 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_core.py | python | Sizer.SetSizeHints | (*args, **kwargs) | return _core_.Sizer_SetSizeHints(*args, **kwargs) | SetSizeHints(self, Window window)
Tell the sizer to set (and `Fit`) the minimal size of the *window* to
match the sizer's minimal size. This is commonly done in the
constructor of the window itself if the window is resizable (as are
many dialogs under Unix and frames on probably all platforms) in order
to prevent the window from being sized smaller than the minimal size
required by the sizer. | SetSizeHints(self, Window window) | [
"SetSizeHints",
"(",
"self",
"Window",
"window",
")"
] | def SetSizeHints(*args, **kwargs):
"""
SetSizeHints(self, Window window)
Tell the sizer to set (and `Fit`) the minimal size of the *window* to
match the sizer's minimal size. This is commonly done in the
constructor of the window itself if the window is resizable (as are
many dialogs under Unix and frames on probably all platforms) in order
to prevent the window from being sized smaller than the minimal size
required by the sizer.
"""
return _core_.Sizer_SetSizeHints(*args, **kwargs) | [
"def",
"SetSizeHints",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"Sizer_SetSizeHints",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L14899-L14910 | |
qt/qt | 0a2f2382541424726168804be2c90b91381608c6 | src/3rdparty/webkit/Source/ThirdParty/gyp/pylib/gyp/MSVSSettings.py | python | _ValidateSettings | (validators, settings, stderr) | Validates that the settings are valid for MSBuild or MSVS.
We currently only validate the names of the settings, not their values.
Args:
validators: A dictionary of tools and their validators.
settings: A dictionary. The key is the tool name. The values are
themselves dictionaries of settings and their values.
stderr: The stream receiving the error messages. | Validates that the settings are valid for MSBuild or MSVS. | [
"Validates",
"that",
"the",
"settings",
"are",
"valid",
"for",
"MSBuild",
"or",
"MSVS",
"."
] | def _ValidateSettings(validators, settings, stderr):
""" Validates that the settings are valid for MSBuild or MSVS.
We currently only validate the names of the settings, not their values.
Args:
validators: A dictionary of tools and their validators.
settings: A dictionary. The key is the tool name. The values are
themselves dictionaries of settings and their values.
stderr: The stream receiving the error messages.
"""
for tool_name in settings:
if tool_name in validators:
tool_validators = validators[tool_name]
for setting, value in settings[tool_name].iteritems():
if setting in tool_validators:
try:
tool_validators[setting](value)
except ValueError:
print >> stderr, ('Warning: unrecognized value "%s" for %s/%s' %
(value, tool_name, setting))
#except TypeError: #(jeanluc)
# print ('***value "%s" for %s/%s' % (value, tool_name, setting))
else:
print >> stderr, ('Warning: unrecognized setting %s/%s' %
(tool_name, setting))
else:
print >> stderr, ('Warning: unrecognized tool %s' % tool_name) | [
"def",
"_ValidateSettings",
"(",
"validators",
",",
"settings",
",",
"stderr",
")",
":",
"for",
"tool_name",
"in",
"settings",
":",
"if",
"tool_name",
"in",
"validators",
":",
"tool_validators",
"=",
"validators",
"[",
"tool_name",
"]",
"for",
"setting",
",",
... | https://github.com/qt/qt/blob/0a2f2382541424726168804be2c90b91381608c6/src/3rdparty/webkit/Source/ThirdParty/gyp/pylib/gyp/MSVSSettings.py#L397-L424 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_windows.py | python | TopLevelWindow.SetShape | (*args, **kwargs) | return _windows_.TopLevelWindow_SetShape(*args, **kwargs) | SetShape(self, Region region) -> bool | SetShape(self, Region region) -> bool | [
"SetShape",
"(",
"self",
"Region",
"region",
")",
"-",
">",
"bool"
] | def SetShape(*args, **kwargs):
"""SetShape(self, Region region) -> bool"""
return _windows_.TopLevelWindow_SetShape(*args, **kwargs) | [
"def",
"SetShape",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_windows_",
".",
"TopLevelWindow_SetShape",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_windows.py#L465-L467 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/prompt-toolkit/py2/prompt_toolkit/key_binding/bindings/completion.py | python | _create_more_application | () | return create_prompt_application(
'--MORE--', key_bindings_registry=registry, erase_when_done=True) | Create an `Application` instance that displays the "--MORE--". | Create an `Application` instance that displays the "--MORE--". | [
"Create",
"an",
"Application",
"instance",
"that",
"displays",
"the",
"--",
"MORE",
"--",
"."
] | def _create_more_application():
"""
Create an `Application` instance that displays the "--MORE--".
"""
from prompt_toolkit.shortcuts import create_prompt_application
registry = Registry()
@registry.add_binding(' ')
@registry.add_binding('y')
@registry.add_binding('Y')
@registry.add_binding(Keys.ControlJ)
@registry.add_binding(Keys.ControlI) # Tab.
def _(event):
event.cli.set_return_value(True)
@registry.add_binding('n')
@registry.add_binding('N')
@registry.add_binding('q')
@registry.add_binding('Q')
@registry.add_binding(Keys.ControlC)
def _(event):
event.cli.set_return_value(False)
return create_prompt_application(
'--MORE--', key_bindings_registry=registry, erase_when_done=True) | [
"def",
"_create_more_application",
"(",
")",
":",
"from",
"prompt_toolkit",
".",
"shortcuts",
"import",
"create_prompt_application",
"registry",
"=",
"Registry",
"(",
")",
"@",
"registry",
".",
"add_binding",
"(",
"' '",
")",
"@",
"registry",
".",
"add_binding",
... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/prompt-toolkit/py2/prompt_toolkit/key_binding/bindings/completion.py#L137-L161 | |
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/contrib/factorization/python/ops/kmeans.py | python | KMeansClustering.transform | (self, x, batch_size=None) | return super(KMeansClustering, self).predict(
x=x, batch_size=batch_size)[KMeansClustering.ALL_SCORES] | Transforms each element in x to distances to cluster centers.
Note that this function is different from the corresponding one in sklearn.
For SQUARED_EUCLIDEAN distance metric, sklearn transform returns the
EUCLIDEAN distance, while this function returns the SQUARED_EUCLIDEAN
distance.
Args:
x: 2-D matrix or iterator.
batch_size: size to use for batching up x for querying the model.
Returns:
Array with same number of rows as x, and num_clusters columns, containing
distances to the cluster centers. | Transforms each element in x to distances to cluster centers. | [
"Transforms",
"each",
"element",
"in",
"x",
"to",
"distances",
"to",
"cluster",
"centers",
"."
] | def transform(self, x, batch_size=None):
"""Transforms each element in x to distances to cluster centers.
Note that this function is different from the corresponding one in sklearn.
For SQUARED_EUCLIDEAN distance metric, sklearn transform returns the
EUCLIDEAN distance, while this function returns the SQUARED_EUCLIDEAN
distance.
Args:
x: 2-D matrix or iterator.
batch_size: size to use for batching up x for querying the model.
Returns:
Array with same number of rows as x, and num_clusters columns, containing
distances to the cluster centers.
"""
return super(KMeansClustering, self).predict(
x=x, batch_size=batch_size)[KMeansClustering.ALL_SCORES] | [
"def",
"transform",
"(",
"self",
",",
"x",
",",
"batch_size",
"=",
"None",
")",
":",
"return",
"super",
"(",
"KMeansClustering",
",",
"self",
")",
".",
"predict",
"(",
"x",
"=",
"x",
",",
"batch_size",
"=",
"batch_size",
")",
"[",
"KMeansClustering",
"... | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/contrib/factorization/python/ops/kmeans.py#L199-L216 | |
klzgrad/naiveproxy | ed2c513637c77b18721fe428d7ed395b4d284c83 | src/third_party/boringssl/src/util/bot/go/env.py | python | find_executable | (name, goroot) | return name | Returns full path to an executable in GOROOT. | Returns full path to an executable in GOROOT. | [
"Returns",
"full",
"path",
"to",
"an",
"executable",
"in",
"GOROOT",
"."
] | def find_executable(name, goroot):
"""Returns full path to an executable in GOROOT."""
basename = name
if EXE_SFX and basename.endswith(EXE_SFX):
basename = basename[:-len(EXE_SFX)]
full_path = os.path.join(goroot, 'bin', basename + EXE_SFX)
if os.path.exists(full_path):
return full_path
return name | [
"def",
"find_executable",
"(",
"name",
",",
"goroot",
")",
":",
"basename",
"=",
"name",
"if",
"EXE_SFX",
"and",
"basename",
".",
"endswith",
"(",
"EXE_SFX",
")",
":",
"basename",
"=",
"basename",
"[",
":",
"-",
"len",
"(",
"EXE_SFX",
")",
"]",
"full_p... | https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/third_party/boringssl/src/util/bot/go/env.py#L38-L46 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/aui.py | python | AuiTabArt.GetBestTabCtrlSize | (*args, **kwargs) | return _aui.AuiTabArt_GetBestTabCtrlSize(*args, **kwargs) | GetBestTabCtrlSize(self, Window wnd, AuiNotebookPageArray pages, Size requiredBmpSize) -> int | GetBestTabCtrlSize(self, Window wnd, AuiNotebookPageArray pages, Size requiredBmpSize) -> int | [
"GetBestTabCtrlSize",
"(",
"self",
"Window",
"wnd",
"AuiNotebookPageArray",
"pages",
"Size",
"requiredBmpSize",
")",
"-",
">",
"int"
] | def GetBestTabCtrlSize(*args, **kwargs):
"""GetBestTabCtrlSize(self, Window wnd, AuiNotebookPageArray pages, Size requiredBmpSize) -> int"""
return _aui.AuiTabArt_GetBestTabCtrlSize(*args, **kwargs) | [
"def",
"GetBestTabCtrlSize",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_aui",
".",
"AuiTabArt_GetBestTabCtrlSize",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/aui.py#L2338-L2340 | |
klzgrad/naiveproxy | ed2c513637c77b18721fe428d7ed395b4d284c83 | src/base/android/jni_generator/jni_generator.py | python | InlHeaderFileGenerator.GetCalledByNativeValues | (self, called_by_native) | return {
'JAVA_CLASS_ONLY': java_class_only,
'JAVA_CLASS': EscapeClassName(java_class),
'RETURN_TYPE': return_type,
'OPTIONAL_ERROR_RETURN': optional_error_return,
'RETURN_DECLARATION': return_declaration,
'RETURN_CLAUSE': return_clause,
'FIRST_PARAM_IN_DECLARATION': first_param_in_declaration,
'PARAMS_IN_DECLARATION': params_in_declaration,
'PRE_CALL': pre_call,
'POST_CALL': post_call,
'ENV_CALL': called_by_native.env_call,
'FIRST_PARAM_IN_CALL': first_param_in_call,
'PARAMS_IN_CALL': params_in_call,
'CHECK_EXCEPTION': check_exception,
'PROFILING_LEAVING_NATIVE': profiling_leaving_native,
'JNI_NAME': jni_name,
'JNI_SIGNATURE': jni_signature,
'METHOD_ID_MEMBER_NAME': method_id_member_name,
'METHOD_ID_VAR_NAME': called_by_native.method_id_var_name,
'METHOD_ID_TYPE': 'STATIC' if called_by_native.static else 'INSTANCE',
'JAVA_NAME_FULL': java_name_full,
} | Fills in necessary values for the CalledByNative methods. | Fills in necessary values for the CalledByNative methods. | [
"Fills",
"in",
"necessary",
"values",
"for",
"the",
"CalledByNative",
"methods",
"."
] | def GetCalledByNativeValues(self, called_by_native):
"""Fills in necessary values for the CalledByNative methods."""
java_class_only = called_by_native.java_class_name or self.class_name
java_class = self.fully_qualified_class
if called_by_native.java_class_name:
java_class += '$' + called_by_native.java_class_name
if called_by_native.static or called_by_native.is_constructor:
first_param_in_declaration = ''
first_param_in_call = 'clazz'
else:
first_param_in_declaration = (
', const base::android::JavaRef<jobject>& obj')
first_param_in_call = 'obj.obj()'
params_in_declaration = self.GetCalledByNativeParamsInDeclaration(
called_by_native)
if params_in_declaration:
params_in_declaration = ', ' + params_in_declaration
params_in_call = ', '.join(self.GetArgumentsInCall(called_by_native.params))
if params_in_call:
params_in_call = ', ' + params_in_call
pre_call = ''
post_call = ''
if called_by_native.static_cast:
pre_call = 'static_cast<%s>(' % called_by_native.static_cast
post_call = ')'
check_exception = 'Unchecked'
method_id_member_name = 'call_context.method_id'
if not called_by_native.unchecked:
check_exception = 'Checked'
method_id_member_name = 'call_context.base.method_id'
return_type = JavaDataTypeToC(called_by_native.return_type)
optional_error_return = JavaReturnValueToC(called_by_native.return_type)
if optional_error_return:
optional_error_return = ', ' + optional_error_return
return_declaration = ''
return_clause = ''
if return_type != 'void':
pre_call = ' ' + pre_call
return_declaration = return_type + ' ret ='
if re.match(RE_SCOPED_JNI_TYPES, return_type):
return_type = 'base::android::ScopedJavaLocalRef<' + return_type + '>'
return_clause = 'return ' + return_type + '(env, ret);'
else:
return_clause = 'return ret;'
profiling_leaving_native = ''
if self.options.enable_profiling:
profiling_leaving_native = ' JNI_SAVE_FRAME_POINTER;\n'
jni_name = called_by_native.name
jni_return_type = called_by_native.return_type
if called_by_native.is_constructor:
jni_name = '<init>'
jni_return_type = 'void'
if called_by_native.signature:
jni_signature = called_by_native.signature
else:
jni_signature = self.jni_params.Signature(called_by_native.params,
jni_return_type)
java_name_full = java_class.replace('/', '.') + '.' + jni_name
return {
'JAVA_CLASS_ONLY': java_class_only,
'JAVA_CLASS': EscapeClassName(java_class),
'RETURN_TYPE': return_type,
'OPTIONAL_ERROR_RETURN': optional_error_return,
'RETURN_DECLARATION': return_declaration,
'RETURN_CLAUSE': return_clause,
'FIRST_PARAM_IN_DECLARATION': first_param_in_declaration,
'PARAMS_IN_DECLARATION': params_in_declaration,
'PRE_CALL': pre_call,
'POST_CALL': post_call,
'ENV_CALL': called_by_native.env_call,
'FIRST_PARAM_IN_CALL': first_param_in_call,
'PARAMS_IN_CALL': params_in_call,
'CHECK_EXCEPTION': check_exception,
'PROFILING_LEAVING_NATIVE': profiling_leaving_native,
'JNI_NAME': jni_name,
'JNI_SIGNATURE': jni_signature,
'METHOD_ID_MEMBER_NAME': method_id_member_name,
'METHOD_ID_VAR_NAME': called_by_native.method_id_var_name,
'METHOD_ID_TYPE': 'STATIC' if called_by_native.static else 'INSTANCE',
'JAVA_NAME_FULL': java_name_full,
} | [
"def",
"GetCalledByNativeValues",
"(",
"self",
",",
"called_by_native",
")",
":",
"java_class_only",
"=",
"called_by_native",
".",
"java_class_name",
"or",
"self",
".",
"class_name",
"java_class",
"=",
"self",
".",
"fully_qualified_class",
"if",
"called_by_native",
".... | https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/base/android/jni_generator/jni_generator.py#L1330-L1411 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/extern/aui/framemanager.py | python | AuiManagerEvent.CanVeto | (self) | return self.canveto_flag and self.veto_flag | Returns whether the event can be vetoed and has been vetoed. | Returns whether the event can be vetoed and has been vetoed. | [
"Returns",
"whether",
"the",
"event",
"can",
"be",
"vetoed",
"and",
"has",
"been",
"vetoed",
"."
] | def CanVeto(self):
""" Returns whether the event can be vetoed and has been vetoed. """
return self.canveto_flag and self.veto_flag | [
"def",
"CanVeto",
"(",
"self",
")",
":",
"return",
"self",
".",
"canveto_flag",
"and",
"self",
".",
"veto_flag"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/extern/aui/framemanager.py#L464-L467 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/corrections_tab_widget/background_corrections_view.py | python | BackgroundCorrectionsView._set_table_item_value_for | (self, run: str, group: str, column_index: int, value: float) | Sets the End X associated with the provided Run and Group. | Sets the End X associated with the provided Run and Group. | [
"Sets",
"the",
"End",
"X",
"associated",
"with",
"the",
"provided",
"Run",
"and",
"Group",
"."
] | def _set_table_item_value_for(self, run: str, group: str, column_index: int, value: float) -> None:
"""Sets the End X associated with the provided Run and Group."""
row_index = self._table_row_index_of(run, group)
self.correction_options_table.blockSignals(True)
self.correction_options_table.setItem(row_index, column_index, create_double_table_item(value))
self.correction_options_table.blockSignals(False) | [
"def",
"_set_table_item_value_for",
"(",
"self",
",",
"run",
":",
"str",
",",
"group",
":",
"str",
",",
"column_index",
":",
"int",
",",
"value",
":",
"float",
")",
"->",
"None",
":",
"row_index",
"=",
"self",
".",
"_table_row_index_of",
"(",
"run",
",",... | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/corrections_tab_widget/background_corrections_view.py#L365-L371 | ||
bareos/bareos | 56a10bb368b0a81e977bb51304033fe49d59efb0 | python-bareos/bareos/bsock/lowlevel.py | python | LowLevel.recv_bytes | (self, length, timeout=10) | return msg | Receive a number of bytes.
Args:
length (int): Number of bytes to receive.
timeout (float): Timeout in seconds.
Raises:
bareos.exceptions.ConnectionLostError:
If the socket connection gets lost.
socket.timeout:
If a timeout occurs on the socket connection,
meaning no data received. | Receive a number of bytes. | [
"Receive",
"a",
"number",
"of",
"bytes",
"."
] | def recv_bytes(self, length, timeout=10):
"""Receive a number of bytes.
Args:
length (int): Number of bytes to receive.
timeout (float): Timeout in seconds.
Raises:
bareos.exceptions.ConnectionLostError:
If the socket connection gets lost.
socket.timeout:
If a timeout occurs on the socket connection,
meaning no data received.
"""
self.socket.settimeout(timeout)
msg = b""
# get the message
while length > 0:
self.logger.debug("expecting {0} bytes.".format(length))
submsg = self.socket.recv(length)
if len(submsg) == 0:
errormsg = u"Failed to retrieve data. Assuming the connection is lost."
self._handleSocketError(errormsg)
raise bareos.exceptions.ConnectionLostError(errormsg)
length -= len(submsg)
msg += submsg
return msg | [
"def",
"recv_bytes",
"(",
"self",
",",
"length",
",",
"timeout",
"=",
"10",
")",
":",
"self",
".",
"socket",
".",
"settimeout",
"(",
"timeout",
")",
"msg",
"=",
"b\"\"",
"# get the message",
"while",
"length",
">",
"0",
":",
"self",
".",
"logger",
".",... | https://github.com/bareos/bareos/blob/56a10bb368b0a81e977bb51304033fe49d59efb0/python-bareos/bareos/bsock/lowlevel.py#L460-L486 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/distribute/distribution_strategy_context.py | python | has_strategy | () | return get_strategy() is not _get_default_strategy() | Return if there is a current non-default `tf.distribute.Strategy`.
```
assert not tf.distribute.has_strategy()
with strategy.scope():
assert tf.distribute.has_strategy()
```
Returns:
True if inside a `with strategy.scope():`. | Return if there is a current non-default `tf.distribute.Strategy`. | [
"Return",
"if",
"there",
"is",
"a",
"current",
"non",
"-",
"default",
"tf",
".",
"distribute",
".",
"Strategy",
"."
] | def has_strategy():
"""Return if there is a current non-default `tf.distribute.Strategy`.
```
assert not tf.distribute.has_strategy()
with strategy.scope():
assert tf.distribute.has_strategy()
```
Returns:
True if inside a `with strategy.scope():`.
"""
return get_strategy() is not _get_default_strategy() | [
"def",
"has_strategy",
"(",
")",
":",
"return",
"get_strategy",
"(",
")",
"is",
"not",
"_get_default_strategy",
"(",
")"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/distribute/distribution_strategy_context.py#L200-L212 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/numbers.py | python | Complex.__rsub__ | (self, other) | return -self + other | other - self | other - self | [
"other",
"-",
"self"
] | def __rsub__(self, other):
"""other - self"""
return -self + other | [
"def",
"__rsub__",
"(",
"self",
",",
"other",
")",
":",
"return",
"-",
"self",
"+",
"other"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/numbers.py#L96-L98 | |
microsoft/TSS.MSR | 0f2516fca2cd9929c31d5450e39301c9bde43688 | TSS.Py/src/TpmTypes.py | python | TPM2B_PUBLIC_KEY_RSA.GetUnionSelector | (self) | return TPM_ALG_ID.RSA | TpmUnion method | TpmUnion method | [
"TpmUnion",
"method"
] | def GetUnionSelector(self): # TPM_ALG_ID
""" TpmUnion method """
return TPM_ALG_ID.RSA | [
"def",
"GetUnionSelector",
"(",
"self",
")",
":",
"# TPM_ALG_ID",
"return",
"TPM_ALG_ID",
".",
"RSA"
] | https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L7143-L7145 | |
msftguy/ssh-rd | a5f3a79daeac5844edebf01916c9613563f1c390 | _3rd/boost_1_48_0/tools/build/v2/build/scanner.py | python | Scanner.pattern | (self) | Returns a pattern to use for scanning. | Returns a pattern to use for scanning. | [
"Returns",
"a",
"pattern",
"to",
"use",
"for",
"scanning",
"."
] | def pattern (self):
""" Returns a pattern to use for scanning.
"""
raise BaseException ("method must be overriden") | [
"def",
"pattern",
"(",
"self",
")",
":",
"raise",
"BaseException",
"(",
"\"method must be overriden\"",
")"
] | https://github.com/msftguy/ssh-rd/blob/a5f3a79daeac5844edebf01916c9613563f1c390/_3rd/boost_1_48_0/tools/build/v2/build/scanner.py#L91-L94 | ||
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/eager/context.py | python | _ContextSwitchStack.push | (self, is_building_function, enter_context_fn, device_stack) | Push metadata about a context switch onto the stack.
A context switch can take any one of the two forms: installing a graph as
the default graph, or entering the eager context. For each context switch,
we record whether or not the entered context is building a function.
Args:
is_building_function: (bool.) Whether the context is building a function.
enter_context_fn: (function.) A callable that executes the context switch.
For example, `graph.as_default` or `eager_mode`.
device_stack: If applicable, the device function stack for this graph.
When breaking out of graphs in init_scope, the innermost nonempty device
stack is used. Eager contexts put `None` here and the value is never
used. | Push metadata about a context switch onto the stack. | [
"Push",
"metadata",
"about",
"a",
"context",
"switch",
"onto",
"the",
"stack",
"."
] | def push(self, is_building_function, enter_context_fn, device_stack):
"""Push metadata about a context switch onto the stack.
A context switch can take any one of the two forms: installing a graph as
the default graph, or entering the eager context. For each context switch,
we record whether or not the entered context is building a function.
Args:
is_building_function: (bool.) Whether the context is building a function.
enter_context_fn: (function.) A callable that executes the context switch.
For example, `graph.as_default` or `eager_mode`.
device_stack: If applicable, the device function stack for this graph.
When breaking out of graphs in init_scope, the innermost nonempty device
stack is used. Eager contexts put `None` here and the value is never
used.
"""
self.stack.append(
ContextSwitch(is_building_function, enter_context_fn, device_stack)) | [
"def",
"push",
"(",
"self",
",",
"is_building_function",
",",
"enter_context_fn",
",",
"device_stack",
")",
":",
"self",
".",
"stack",
".",
"append",
"(",
"ContextSwitch",
"(",
"is_building_function",
",",
"enter_context_fn",
",",
"device_stack",
")",
")"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/eager/context.py#L269-L287 | ||
facebookincubator/BOLT | 88c70afe9d388ad430cc150cc158641701397f70 | lldb/examples/python/mach_o.py | python | TerminalColors.cyan | (self, fg=True) | return '' | Set the foreground or background color to cyan.
The foreground color will be set if "fg" tests True. The background color will be set if "fg" tests False. | Set the foreground or background color to cyan.
The foreground color will be set if "fg" tests True. The background color will be set if "fg" tests False. | [
"Set",
"the",
"foreground",
"or",
"background",
"color",
"to",
"cyan",
".",
"The",
"foreground",
"color",
"will",
"be",
"set",
"if",
"fg",
"tests",
"True",
".",
"The",
"background",
"color",
"will",
"be",
"set",
"if",
"fg",
"tests",
"False",
"."
] | def cyan(self, fg=True):
'''Set the foreground or background color to cyan.
The foreground color will be set if "fg" tests True. The background color will be set if "fg" tests False.'''
if self.enabled:
if fg:
return "\x1b[36m"
else:
return "\x1b[46m"
return '' | [
"def",
"cyan",
"(",
"self",
",",
"fg",
"=",
"True",
")",
":",
"if",
"self",
".",
"enabled",
":",
"if",
"fg",
":",
"return",
"\"\\x1b[36m\"",
"else",
":",
"return",
"\"\\x1b[46m\"",
"return",
"''"
] | https://github.com/facebookincubator/BOLT/blob/88c70afe9d388ad430cc150cc158641701397f70/lldb/examples/python/mach_o.py#L331-L339 | |
freeorion/freeorion | c266a40eccd3a99a17de8fe57c36ef6ba3771665 | default/python/AI/character/character_strings_module.py | python | _CharacterTableFunction.__init__ | (self, trait_class, table, post_process_func=None) | Store trait type, table and post processing function. | Store trait type, table and post processing function. | [
"Store",
"trait",
"type",
"table",
"and",
"post",
"processing",
"function",
"."
] | def __init__(self, trait_class, table, post_process_func=None):
"""Store trait type, table and post processing function."""
self.trait_class = trait_class
self.table = table
self.post_process = post_process_func | [
"def",
"__init__",
"(",
"self",
",",
"trait_class",
",",
"table",
",",
"post_process_func",
"=",
"None",
")",
":",
"self",
".",
"trait_class",
"=",
"trait_class",
"self",
".",
"table",
"=",
"table",
"self",
".",
"post_process",
"=",
"post_process_func"
] | https://github.com/freeorion/freeorion/blob/c266a40eccd3a99a17de8fe57c36ef6ba3771665/default/python/AI/character/character_strings_module.py#L39-L43 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.