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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_gdi.py | python | DC.LogicalToDeviceXRel | (*args, **kwargs) | return _gdi_.DC_LogicalToDeviceXRel(*args, **kwargs) | LogicalToDeviceXRel(self, int x) -> int
Converts logical X coordinate to relative device coordinate, using the
current mapping mode but ignoring the x axis orientation. Use this for
converting a width, for example. | LogicalToDeviceXRel(self, int x) -> int | [
"LogicalToDeviceXRel",
"(",
"self",
"int",
"x",
")",
"-",
">",
"int"
] | def LogicalToDeviceXRel(*args, **kwargs):
"""
LogicalToDeviceXRel(self, int x) -> int
Converts logical X coordinate to relative device coordinate, using the
current mapping mode but ignoring the x axis orientation. Use this for
converting a width, for example.
"""
return _gdi_.DC_LogicalToDeviceXRel(*args, **kwargs) | [
"def",
"LogicalToDeviceXRel",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gdi_",
".",
"DC_LogicalToDeviceXRel",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_gdi.py#L4267-L4275 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/extern/aui/auibook.py | python | AuiNotebook.OnTabMiddleUp | (self, event) | Handles the ``EVT_AUINOTEBOOK_TAB_MIDDLE_UP`` event for :class:`AuiNotebook`.
:param `event`: a :class:`AuiNotebookEvent` event to be processed. | Handles the ``EVT_AUINOTEBOOK_TAB_MIDDLE_UP`` event for :class:`AuiNotebook`. | [
"Handles",
"the",
"EVT_AUINOTEBOOK_TAB_MIDDLE_UP",
"event",
"for",
":",
"class",
":",
"AuiNotebook",
"."
] | def OnTabMiddleUp(self, event):
"""
Handles the ``EVT_AUINOTEBOOK_TAB_MIDDLE_UP`` event for :class:`AuiNotebook`.
:param `event`: a :class:`AuiNotebookEvent` event to be processed.
"""
tabs = event.GetEventObject()
if not tabs.GetEnabled(event.GetSelection()):
return
# if the AUI_NB_MIDDLE_CLICK_CLOSE is specified, middle
# click should act like a tab close action. However, first
# give the owner an opportunity to handle the middle up event
# for custom action
wnd = tabs.GetWindowFromIdx(event.GetSelection())
e = AuiNotebookEvent(wxEVT_COMMAND_AUINOTEBOOK_TAB_MIDDLE_UP, self.GetId())
e.SetSelection(self._tabs.GetIdxFromWindow(wnd))
e.SetEventObject(self)
if self.GetEventHandler().ProcessEvent(e):
return
if not e.IsAllowed():
return
# check if we are supposed to close on middle-up
if self._agwFlags & AUI_NB_MIDDLE_CLICK_CLOSE == 0:
return
# simulate the user pressing the close button on the tab
event.SetInt(AUI_BUTTON_CLOSE)
self.OnTabButton(event) | [
"def",
"OnTabMiddleUp",
"(",
"self",
",",
"event",
")",
":",
"tabs",
"=",
"event",
".",
"GetEventObject",
"(",
")",
"if",
"not",
"tabs",
".",
"GetEnabled",
"(",
"event",
".",
"GetSelection",
"(",
")",
")",
":",
"return",
"# if the AUI_NB_MIDDLE_CLICK_CLOSE i... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/extern/aui/auibook.py#L5433-L5465 | ||
cocos-creator/engine-native | 984c4c9f5838253313b44ccd429bd8fac4ec8a6a | tools/bindings-generator/clang/cindex.py | python | Cursor.enum_type | (self) | return self._enum_type | Return the integer type of an enum declaration.
Returns a Type corresponding to an integer. If the cursor is not for an
enum, this raises. | Return the integer type of an enum declaration. | [
"Return",
"the",
"integer",
"type",
"of",
"an",
"enum",
"declaration",
"."
] | def enum_type(self):
"""Return the integer type of an enum declaration.
Returns a Type corresponding to an integer. If the cursor is not for an
enum, this raises.
"""
if not hasattr(self, '_enum_type'):
assert self.kind == CursorKind.ENUM_DECL
self._enum_type = conf.lib.clang_getEnumDeclIntegerType(self)
return self._enum_type | [
"def",
"enum_type",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_enum_type'",
")",
":",
"assert",
"self",
".",
"kind",
"==",
"CursorKind",
".",
"ENUM_DECL",
"self",
".",
"_enum_type",
"=",
"conf",
".",
"lib",
".",
"clang_getEnumDec... | https://github.com/cocos-creator/engine-native/blob/984c4c9f5838253313b44ccd429bd8fac4ec8a6a/tools/bindings-generator/clang/cindex.py#L1702-L1712 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/arrays/base.py | python | ExtensionArray.shape | (self) | return (len(self),) | Return a tuple of the array dimensions. | Return a tuple of the array dimensions. | [
"Return",
"a",
"tuple",
"of",
"the",
"array",
"dimensions",
"."
] | def shape(self) -> Tuple[int, ...]:
"""
Return a tuple of the array dimensions.
"""
return (len(self),) | [
"def",
"shape",
"(",
"self",
")",
"->",
"Tuple",
"[",
"int",
",",
"...",
"]",
":",
"return",
"(",
"len",
"(",
"self",
")",
",",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/arrays/base.py#L399-L403 | |
Chia-Network/bls-signatures | a61089d653fa3653ac94452c73e97efcd461bdf2 | python-impl/hd_keys.py | python | derive_child_sk_unhardened | (parent_sk: PrivateKey, index: int) | return PrivateKey.aggregate([PrivateKey.from_bytes(h), parent_sk]) | Derives an unhardened BIP-32 child private key, from a parent private key,
at the specified index. WARNING: this key is not as secure as a hardened key. | Derives an unhardened BIP-32 child private key, from a parent private key,
at the specified index. WARNING: this key is not as secure as a hardened key. | [
"Derives",
"an",
"unhardened",
"BIP",
"-",
"32",
"child",
"private",
"key",
"from",
"a",
"parent",
"private",
"key",
"at",
"the",
"specified",
"index",
".",
"WARNING",
":",
"this",
"key",
"is",
"not",
"as",
"secure",
"as",
"a",
"hardened",
"key",
"."
] | def derive_child_sk_unhardened(parent_sk: PrivateKey, index: int) -> PrivateKey:
"""
Derives an unhardened BIP-32 child private key, from a parent private key,
at the specified index. WARNING: this key is not as secure as a hardened key.
"""
h = hash256(bytes(parent_sk.get_g1()) + index.to_bytes(4, "big"))
return PrivateKey.aggregate([PrivateKey.from_bytes(h), parent_sk]) | [
"def",
"derive_child_sk_unhardened",
"(",
"parent_sk",
":",
"PrivateKey",
",",
"index",
":",
"int",
")",
"->",
"PrivateKey",
":",
"h",
"=",
"hash256",
"(",
"bytes",
"(",
"parent_sk",
".",
"get_g1",
"(",
")",
")",
"+",
"index",
".",
"to_bytes",
"(",
"4",
... | https://github.com/Chia-Network/bls-signatures/blob/a61089d653fa3653ac94452c73e97efcd461bdf2/python-impl/hd_keys.py#L49-L55 | |
fengbingchun/NN_Test | d6305825d5273e4569ccd1eda9ffa2a9c72e18d2 | src/tiny-dnn/third_party/gemmlowp/meta/generators/gemv_1xMxK.py | python | GenerateMulCols | (emitter, result_type, lhs_add, rhs_add, aligned, cols,
leftovers) | Emits code responsible for multiplication of one horizontal lhs strip. | Emits code responsible for multiplication of one horizontal lhs strip. | [
"Emits",
"code",
"responsible",
"for",
"multiplication",
"of",
"one",
"horizontal",
"lhs",
"strip",
"."
] | def GenerateMulCols(emitter, result_type, lhs_add, rhs_add, aligned, cols,
leftovers):
"""Emits code responsible for multiplication of one horizontal lhs strip."""
emitter.EmitOpenBracket('for (int i = 0; i < col_chunks; ++i)')
emitter.EmitCall(
zip_Nx8_neon.BuildName(4, leftovers, aligned),
['rhs_chunk', 'k', 'k', 'zipped_rhs_1', 'lhs_offset', 'const_offset'])
emitter.EmitAssignIncrement('rhs_chunk', 'chunk_size')
emitter.EmitCall(
zip_Nx8_neon.BuildName(4, leftovers, aligned),
['rhs_chunk', 'k', 'k', 'zipped_rhs_2', 'lhs_offset', 'const_offset'])
emitter.EmitAssignIncrement('rhs_chunk', 'chunk_size')
emitter.EmitCall(
mul_1x8_Mx8_neon.BuildName(result_type, lhs_add, rhs_add, 8),
GetMul2Params(result_type))
emitter.EmitAssignIncrement('mul_result_chunk', 8)
emitter.EmitCloseBracket()
if cols > 4:
emitter.EmitCall(
zip_Nx8_neon.BuildName(4, leftovers, aligned),
['rhs_chunk', 'k', 'k', 'zipped_rhs_1', 'lhs_offset', 'const_offset'])
emitter.EmitAssignIncrement('rhs_chunk', 'chunk_size')
emitter.EmitCall(
zip_Nx8_neon.BuildName(cols - 4, leftovers, aligned),
['rhs_chunk', 'k', 'k', 'zipped_rhs_2', 'lhs_offset', 'const_offset'])
emitter.EmitCall(
mul_1x8_Mx8_neon.BuildName(result_type, lhs_add, rhs_add, cols),
GetMul2Params(result_type))
elif cols > 0:
emitter.EmitCall(
zip_Nx8_neon.BuildName(cols, leftovers, aligned),
['rhs_chunk', 'k', 'k', 'zipped_rhs_1', 'lhs_offset', 'const_offset'])
emitter.EmitCall(
mul_Nx8_Mx8_neon.BuildName(result_type, lhs_add, rhs_add, 1, cols),
GetMulParams(result_type)) | [
"def",
"GenerateMulCols",
"(",
"emitter",
",",
"result_type",
",",
"lhs_add",
",",
"rhs_add",
",",
"aligned",
",",
"cols",
",",
"leftovers",
")",
":",
"emitter",
".",
"EmitOpenBracket",
"(",
"'for (int i = 0; i < col_chunks; ++i)'",
")",
"emitter",
".",
"EmitCall"... | https://github.com/fengbingchun/NN_Test/blob/d6305825d5273e4569ccd1eda9ffa2a9c72e18d2/src/tiny-dnn/third_party/gemmlowp/meta/generators/gemv_1xMxK.py#L83-L124 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/idlelib/configHandler.py | python | IdleConfParser.Load | (self) | Load the configuration file from disk | Load the configuration file from disk | [
"Load",
"the",
"configuration",
"file",
"from",
"disk"
] | def Load(self):
"""
Load the configuration file from disk
"""
self.read(self.file) | [
"def",
"Load",
"(",
"self",
")",
":",
"self",
".",
"read",
"(",
"self",
".",
"file",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/idlelib/configHandler.py#L65-L69 | ||
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | gpu/command_buffer/build_gles2_cmd_buffer.py | python | SizeArgument.WriteValidationCode | (self, file, func) | overridden from Argument. | overridden from Argument. | [
"overridden",
"from",
"Argument",
"."
] | def WriteValidationCode(self, file, func):
"""overridden from Argument."""
file.Write(" if (%s < 0) {\n" % self.name)
file.Write(" SetGLError(GL_INVALID_VALUE, \"gl%s: %s < 0\");\n" %
(func.original_name, self.name))
file.Write(" return error::kNoError;\n")
file.Write(" }\n") | [
"def",
"WriteValidationCode",
"(",
"self",
",",
"file",
",",
"func",
")",
":",
"file",
".",
"Write",
"(",
"\" if (%s < 0) {\\n\"",
"%",
"self",
".",
"name",
")",
"file",
".",
"Write",
"(",
"\" SetGLError(GL_INVALID_VALUE, \\\"gl%s: %s < 0\\\");\\n\"",
"%",
"("... | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/gpu/command_buffer/build_gles2_cmd_buffer.py#L4705-L4711 | ||
ppwwyyxx/speaker-recognition | 15d7bf32ad4ba2f1543e1287b03f3f2e6791d4dd | src/gui/interface.py | python | ModelInterface.init_noise | (self, fs, signal) | init vad from environment noise | init vad from environment noise | [
"init",
"vad",
"from",
"environment",
"noise"
] | def init_noise(self, fs, signal):
"""
init vad from environment noise
"""
self.vad.init_noise(fs, signal) | [
"def",
"init_noise",
"(",
"self",
",",
"fs",
",",
"signal",
")",
":",
"self",
".",
"vad",
".",
"init_noise",
"(",
"fs",
",",
"signal",
")"
] | https://github.com/ppwwyyxx/speaker-recognition/blob/15d7bf32ad4ba2f1543e1287b03f3f2e6791d4dd/src/gui/interface.py#L37-L41 | ||
RobotLocomotion/drake | 0e18a34604c45ed65bc9018a54f7610f91cdad5b | tools/lint/buildifier.py | python | _help | (command) | return process.returncode | Perform the --help operation (display output) and return an exitcode. | Perform the --help operation (display output) and return an exitcode. | [
"Perform",
"the",
"--",
"help",
"operation",
"(",
"display",
"output",
")",
"and",
"return",
"an",
"exitcode",
"."
] | def _help(command):
"""Perform the --help operation (display output) and return an exitcode."""
process = Popen(command, stdout=PIPE, stderr=STDOUT)
stdout, _ = process.communicate()
lines = stdout.splitlines()
# Edit the first line to allow "--all" as a disjunction from "files...",
# and make one or the other required.
head = re.sub(r'\[(files\.\.\.)\]', r'<\1 | --all>', lines.pop(0))
for line in [head] + lines:
print(line)
print("")
print("=== Drake-specific additions ===")
print("")
print("If the --all flag is given, buildifier operates on every BUILD,")
print("*.BUILD, *.bazel, and *.bzl file in the tree except third_party.")
print("")
print("Without '--all', 'files...' are required; stdin cannot be used.")
return process.returncode | [
"def",
"_help",
"(",
"command",
")",
":",
"process",
"=",
"Popen",
"(",
"command",
",",
"stdout",
"=",
"PIPE",
",",
"stderr",
"=",
"STDOUT",
")",
"stdout",
",",
"_",
"=",
"process",
".",
"communicate",
"(",
")",
"lines",
"=",
"stdout",
".",
"splitlin... | https://github.com/RobotLocomotion/drake/blob/0e18a34604c45ed65bc9018a54f7610f91cdad5b/tools/lint/buildifier.py#L31-L48 | |
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | third_party/tlslite/tlslite/integration/AsyncStateMachine.py | python | AsyncStateMachine.wantsReadEvent | (self) | return None | If the state machine wants to read.
If an operation is active, this returns whether or not the
operation wants to read from the socket. If an operation is
not active, this returns None.
@rtype: bool or None
@return: If the state machine wants to read. | If the state machine wants to read. | [
"If",
"the",
"state",
"machine",
"wants",
"to",
"read",
"."
] | def wantsReadEvent(self):
"""If the state machine wants to read.
If an operation is active, this returns whether or not the
operation wants to read from the socket. If an operation is
not active, this returns None.
@rtype: bool or None
@return: If the state machine wants to read.
"""
if self.result != None:
return self.result == 0
return None | [
"def",
"wantsReadEvent",
"(",
"self",
")",
":",
"if",
"self",
".",
"result",
"!=",
"None",
":",
"return",
"self",
".",
"result",
"==",
"0",
"return",
"None"
] | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/third_party/tlslite/tlslite/integration/AsyncStateMachine.py#L64-L76 | |
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Fem/ObjectsFem.py | python | makeEquationFlow | (
doc,
base_solver=None,
name="Flow"
) | return obj | makeEquationFlow(document, [base_solver], [name]):
creates a FEM flow equation for a solver | makeEquationFlow(document, [base_solver], [name]):
creates a FEM flow equation for a solver | [
"makeEquationFlow",
"(",
"document",
"[",
"base_solver",
"]",
"[",
"name",
"]",
")",
":",
"creates",
"a",
"FEM",
"flow",
"equation",
"for",
"a",
"solver"
] | def makeEquationFlow(
doc,
base_solver=None,
name="Flow"
):
"""makeEquationFlow(document, [base_solver], [name]):
creates a FEM flow equation for a solver"""
from femsolver.elmer.equations import flow
obj = flow.create(doc, name)
if base_solver:
base_solver.addObject(obj)
return obj | [
"def",
"makeEquationFlow",
"(",
"doc",
",",
"base_solver",
"=",
"None",
",",
"name",
"=",
"\"Flow\"",
")",
":",
"from",
"femsolver",
".",
"elmer",
".",
"equations",
"import",
"flow",
"obj",
"=",
"flow",
".",
"create",
"(",
"doc",
",",
"name",
")",
"if"... | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Fem/ObjectsFem.py#L733-L744 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/scipy/optimize/_linprog.py | python | _solve_simplex | (T, n, basis, maxiter=1000, phase=2, callback=None,
tol=1.0E-12, nit0=0, bland=False) | return nit, status | Solve a linear programming problem in "standard maximization form" using
the Simplex Method.
Minimize :math:`f = c^T x`
subject to
.. math::
Ax = b
x_i >= 0
b_j >= 0
Parameters
----------
T : array_like
A 2-D array representing the simplex T corresponding to the
maximization problem. It should have the form:
[[A[0, 0], A[0, 1], ..., A[0, n_total], b[0]],
[A[1, 0], A[1, 1], ..., A[1, n_total], b[1]],
.
.
.
[A[m, 0], A[m, 1], ..., A[m, n_total], b[m]],
[c[0], c[1], ..., c[n_total], 0]]
for a Phase 2 problem, or the form:
[[A[0, 0], A[0, 1], ..., A[0, n_total], b[0]],
[A[1, 0], A[1, 1], ..., A[1, n_total], b[1]],
.
.
.
[A[m, 0], A[m, 1], ..., A[m, n_total], b[m]],
[c[0], c[1], ..., c[n_total], 0],
[c'[0], c'[1], ..., c'[n_total], 0]]
for a Phase 1 problem (a Problem in which a basic feasible solution is
sought prior to maximizing the actual objective. T is modified in
place by _solve_simplex.
n : int
The number of true variables in the problem.
basis : array
An array of the indices of the basic variables, such that basis[i]
contains the column corresponding to the basic variable for row i.
Basis is modified in place by _solve_simplex
maxiter : int
The maximum number of iterations to perform before aborting the
optimization.
phase : int
The phase of the optimization being executed. In phase 1 a basic
feasible solution is sought and the T has an additional row representing
an alternate objective function.
callback : callable, optional
If a callback function is provided, it will be called within each
iteration of the simplex algorithm. The callback must have the
signature `callback(xk, **kwargs)` where xk is the current solution
vector and kwargs is a dictionary containing the following::
"T" : The current Simplex algorithm T
"nit" : The current iteration.
"pivot" : The pivot (row, column) used for the next iteration.
"phase" : Whether the algorithm is in Phase 1 or Phase 2.
"basis" : The indices of the columns of the basic variables.
tol : float
The tolerance which determines when a solution is "close enough" to
zero in Phase 1 to be considered a basic feasible solution or close
enough to positive to to serve as an optimal solution.
nit0 : int
The initial iteration number used to keep an accurate iteration total
in a two-phase problem.
bland : bool
If True, choose pivots using Bland's rule [3]. In problems which
fail to converge due to cycling, using Bland's rule can provide
convergence at the expense of a less optimal path about the simplex.
Returns
-------
res : OptimizeResult
The optimization result represented as a ``OptimizeResult`` object.
Important attributes are: ``x`` the solution array, ``success`` a
Boolean flag indicating if the optimizer exited successfully and
``message`` which describes the cause of the termination. Possible
values for the ``status`` attribute are:
0 : Optimization terminated successfully
1 : Iteration limit reached
2 : Problem appears to be infeasible
3 : Problem appears to be unbounded
See `OptimizeResult` for a description of other attributes. | Solve a linear programming problem in "standard maximization form" using
the Simplex Method. | [
"Solve",
"a",
"linear",
"programming",
"problem",
"in",
"standard",
"maximization",
"form",
"using",
"the",
"Simplex",
"Method",
"."
] | def _solve_simplex(T, n, basis, maxiter=1000, phase=2, callback=None,
tol=1.0E-12, nit0=0, bland=False):
"""
Solve a linear programming problem in "standard maximization form" using
the Simplex Method.
Minimize :math:`f = c^T x`
subject to
.. math::
Ax = b
x_i >= 0
b_j >= 0
Parameters
----------
T : array_like
A 2-D array representing the simplex T corresponding to the
maximization problem. It should have the form:
[[A[0, 0], A[0, 1], ..., A[0, n_total], b[0]],
[A[1, 0], A[1, 1], ..., A[1, n_total], b[1]],
.
.
.
[A[m, 0], A[m, 1], ..., A[m, n_total], b[m]],
[c[0], c[1], ..., c[n_total], 0]]
for a Phase 2 problem, or the form:
[[A[0, 0], A[0, 1], ..., A[0, n_total], b[0]],
[A[1, 0], A[1, 1], ..., A[1, n_total], b[1]],
.
.
.
[A[m, 0], A[m, 1], ..., A[m, n_total], b[m]],
[c[0], c[1], ..., c[n_total], 0],
[c'[0], c'[1], ..., c'[n_total], 0]]
for a Phase 1 problem (a Problem in which a basic feasible solution is
sought prior to maximizing the actual objective. T is modified in
place by _solve_simplex.
n : int
The number of true variables in the problem.
basis : array
An array of the indices of the basic variables, such that basis[i]
contains the column corresponding to the basic variable for row i.
Basis is modified in place by _solve_simplex
maxiter : int
The maximum number of iterations to perform before aborting the
optimization.
phase : int
The phase of the optimization being executed. In phase 1 a basic
feasible solution is sought and the T has an additional row representing
an alternate objective function.
callback : callable, optional
If a callback function is provided, it will be called within each
iteration of the simplex algorithm. The callback must have the
signature `callback(xk, **kwargs)` where xk is the current solution
vector and kwargs is a dictionary containing the following::
"T" : The current Simplex algorithm T
"nit" : The current iteration.
"pivot" : The pivot (row, column) used for the next iteration.
"phase" : Whether the algorithm is in Phase 1 or Phase 2.
"basis" : The indices of the columns of the basic variables.
tol : float
The tolerance which determines when a solution is "close enough" to
zero in Phase 1 to be considered a basic feasible solution or close
enough to positive to to serve as an optimal solution.
nit0 : int
The initial iteration number used to keep an accurate iteration total
in a two-phase problem.
bland : bool
If True, choose pivots using Bland's rule [3]. In problems which
fail to converge due to cycling, using Bland's rule can provide
convergence at the expense of a less optimal path about the simplex.
Returns
-------
res : OptimizeResult
The optimization result represented as a ``OptimizeResult`` object.
Important attributes are: ``x`` the solution array, ``success`` a
Boolean flag indicating if the optimizer exited successfully and
``message`` which describes the cause of the termination. Possible
values for the ``status`` attribute are:
0 : Optimization terminated successfully
1 : Iteration limit reached
2 : Problem appears to be infeasible
3 : Problem appears to be unbounded
See `OptimizeResult` for a description of other attributes.
"""
nit = nit0
complete = False
if phase == 1:
m = T.shape[0]-2
elif phase == 2:
m = T.shape[0]-1
else:
raise ValueError("Argument 'phase' to _solve_simplex must be 1 or 2")
if phase == 2:
# Check if any artificial variables are still in the basis.
# If yes, check if any coefficients from this row and a column
# corresponding to one of the non-artificial variable is non-zero.
# If found, pivot at this term. If not, start phase 2.
# Do this for all artificial variables in the basis.
# Ref: "An Introduction to Linear Programming and Game Theory"
# by Paul R. Thie, Gerard E. Keough, 3rd Ed,
# Chapter 3.7 Redundant Systems (pag 102)
for pivrow in [row for row in range(basis.size)
if basis[row] > T.shape[1] - 2]:
non_zero_row = [col for col in range(T.shape[1] - 1)
if T[pivrow, col] != 0]
if len(non_zero_row) > 0:
pivcol = non_zero_row[0]
# variable represented by pivcol enters
# variable in basis[pivrow] leaves
basis[pivrow] = pivcol
pivval = T[pivrow][pivcol]
T[pivrow, :] = T[pivrow, :] / pivval
for irow in range(T.shape[0]):
if irow != pivrow:
T[irow, :] = T[irow, :] - T[pivrow, :]*T[irow, pivcol]
nit += 1
if len(basis[:m]) == 0:
solution = np.zeros(T.shape[1] - 1, dtype=np.float64)
else:
solution = np.zeros(max(T.shape[1] - 1, max(basis[:m]) + 1),
dtype=np.float64)
while not complete:
# Find the pivot column
pivcol_found, pivcol = _pivot_col(T, tol, bland)
if not pivcol_found:
pivcol = np.nan
pivrow = np.nan
status = 0
complete = True
else:
# Find the pivot row
pivrow_found, pivrow = _pivot_row(T, pivcol, phase, tol)
if not pivrow_found:
status = 3
complete = True
if callback is not None:
solution[:] = 0
solution[basis[:m]] = T[:m, -1]
callback(solution[:n], **{"tableau": T,
"phase":phase,
"nit":nit,
"pivot":(pivrow, pivcol),
"basis":basis,
"complete": complete and phase == 2})
if not complete:
if nit >= maxiter:
# Iteration limit exceeded
status = 1
complete = True
else:
# variable represented by pivcol enters
# variable in basis[pivrow] leaves
basis[pivrow] = pivcol
pivval = T[pivrow][pivcol]
T[pivrow, :] = T[pivrow, :] / pivval
for irow in range(T.shape[0]):
if irow != pivrow:
T[irow, :] = T[irow, :] - T[pivrow, :]*T[irow, pivcol]
nit += 1
return nit, status | [
"def",
"_solve_simplex",
"(",
"T",
",",
"n",
",",
"basis",
",",
"maxiter",
"=",
"1000",
",",
"phase",
"=",
"2",
",",
"callback",
"=",
"None",
",",
"tol",
"=",
"1.0E-12",
",",
"nit0",
"=",
"0",
",",
"bland",
"=",
"False",
")",
":",
"nit",
"=",
"... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/optimize/_linprog.py#L212-L388 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_windows.py | python | FindReplaceDialog.GetData | (*args, **kwargs) | return _windows_.FindReplaceDialog_GetData(*args, **kwargs) | GetData(self) -> FindReplaceData
Get the FindReplaceData object used by this dialog. | GetData(self) -> FindReplaceData | [
"GetData",
"(",
"self",
")",
"-",
">",
"FindReplaceData"
] | def GetData(*args, **kwargs):
"""
GetData(self) -> FindReplaceData
Get the FindReplaceData object used by this dialog.
"""
return _windows_.FindReplaceDialog_GetData(*args, **kwargs) | [
"def",
"GetData",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_windows_",
".",
"FindReplaceDialog_GetData",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_windows.py#L3972-L3978 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_misc.py | python | VideoMode.IsOk | (*args, **kwargs) | return _misc_.VideoMode_IsOk(*args, **kwargs) | IsOk(self) -> bool
returns true if the object has been initialized | IsOk(self) -> bool | [
"IsOk",
"(",
"self",
")",
"-",
">",
"bool"
] | def IsOk(*args, **kwargs):
"""
IsOk(self) -> bool
returns true if the object has been initialized
"""
return _misc_.VideoMode_IsOk(*args, **kwargs) | [
"def",
"IsOk",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"VideoMode_IsOk",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_misc.py#L6050-L6056 | |
arangodb/arangodb | 0d658689c7d1b721b314fa3ca27d38303e1570c8 | 3rdParty/V8/v7.9.317/third_party/jinja2/compiler.py | python | CodeGenerator.visit_Include | (self, node, frame) | Handles includes. | Handles includes. | [
"Handles",
"includes",
"."
] | def visit_Include(self, node, frame):
"""Handles includes."""
if node.ignore_missing:
self.writeline('try:')
self.indent()
func_name = 'get_or_select_template'
if isinstance(node.template, nodes.Const):
if isinstance(node.template.value, string_types):
func_name = 'get_template'
elif isinstance(node.template.value, (tuple, list)):
func_name = 'select_template'
elif isinstance(node.template, (nodes.Tuple, nodes.List)):
func_name = 'select_template'
self.writeline('template = environment.%s(' % func_name, node)
self.visit(node.template, frame)
self.write(', %r)' % self.name)
if node.ignore_missing:
self.outdent()
self.writeline('except TemplateNotFound:')
self.indent()
self.writeline('pass')
self.outdent()
self.writeline('else:')
self.indent()
skip_event_yield = False
if node.with_context:
loop = self.environment.is_async and 'async for' or 'for'
self.writeline('%s event in template.root_render_func('
'template.new_context(context.get_all(), True, '
'%s)):' % (loop, self.dump_local_context(frame)))
elif self.environment.is_async:
self.writeline('for event in (await '
'template._get_default_module_async())'
'._body_stream:')
else:
if supports_yield_from:
self.writeline('yield from template._get_default_module()'
'._body_stream')
skip_event_yield = True
else:
self.writeline('for event in template._get_default_module()'
'._body_stream:')
if not skip_event_yield:
self.indent()
self.simple_write('event', frame)
self.outdent()
if node.ignore_missing:
self.outdent() | [
"def",
"visit_Include",
"(",
"self",
",",
"node",
",",
"frame",
")",
":",
"if",
"node",
".",
"ignore_missing",
":",
"self",
".",
"writeline",
"(",
"'try:'",
")",
"self",
".",
"indent",
"(",
")",
"func_name",
"=",
"'get_or_select_template'",
"if",
"isinstan... | https://github.com/arangodb/arangodb/blob/0d658689c7d1b721b314fa3ca27d38303e1570c8/3rdParty/V8/v7.9.317/third_party/jinja2/compiler.py#L890-L942 | ||
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/python/framework/tensor_shape.py | python | TensorShape.merge_with | (self, other) | Returns a `TensorShape` combining the information in `self` and `other`.
The dimensions in `self` and `other` are merged elementwise,
according to the rules defined for `Dimension.merge_with()`.
Args:
other: Another `TensorShape`.
Returns:
A `TensorShape` containing the combined information of `self` and
`other`.
Raises:
ValueError: If `self` and `other` are not compatible. | Returns a `TensorShape` combining the information in `self` and `other`. | [
"Returns",
"a",
"TensorShape",
"combining",
"the",
"information",
"in",
"self",
"and",
"other",
"."
] | def merge_with(self, other):
"""Returns a `TensorShape` combining the information in `self` and `other`.
The dimensions in `self` and `other` are merged elementwise,
according to the rules defined for `Dimension.merge_with()`.
Args:
other: Another `TensorShape`.
Returns:
A `TensorShape` containing the combined information of `self` and
`other`.
Raises:
ValueError: If `self` and `other` are not compatible.
"""
other = as_shape(other)
if self._dims is None:
return other
else:
try:
self.assert_same_rank(other)
new_dims = []
for i, dim in enumerate(self._dims):
new_dims.append(dim.merge_with(other[i]))
return TensorShape(new_dims)
except ValueError:
raise ValueError("Shapes %s and %s are not compatible" %
(self, other)) | [
"def",
"merge_with",
"(",
"self",
",",
"other",
")",
":",
"other",
"=",
"as_shape",
"(",
"other",
")",
"if",
"self",
".",
"_dims",
"is",
"None",
":",
"return",
"other",
"else",
":",
"try",
":",
"self",
".",
"assert_same_rank",
"(",
"other",
")",
"new... | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/python/framework/tensor_shape.py#L542-L570 | ||
google/earthenterprise | 0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9 | earth_enterprise/src/server/wsgi/serve/publish/publish_manager_helper.py | python | PublishManagerHelper.IsDefaultDatabase | (self, publish_context_id) | return False | Checks whether the passed-in database is the default database or not. When
upgrading from older releases such as 5.1.2, the publish_context_table may
not have an entry for a published database, so we have to perform two
queries: one to get the list of databases and one to check if each database
is the default. It would simplify things somewhat to move the ec_default_db
field to the target_table database so that we can get all the data we want
with a single query. However, this would make the upgrade code more
complicated because we would have to manage 3 schemas: one from before we
added ec_default_db and two with the ec_default_db in different places.
This method seems to be the simplest overall option even though it requires
multiple queries. | Checks whether the passed-in database is the default database or not. When
upgrading from older releases such as 5.1.2, the publish_context_table may
not have an entry for a published database, so we have to perform two
queries: one to get the list of databases and one to check if each database
is the default. It would simplify things somewhat to move the ec_default_db
field to the target_table database so that we can get all the data we want
with a single query. However, this would make the upgrade code more
complicated because we would have to manage 3 schemas: one from before we
added ec_default_db and two with the ec_default_db in different places.
This method seems to be the simplest overall option even though it requires
multiple queries. | [
"Checks",
"whether",
"the",
"passed",
"-",
"in",
"database",
"is",
"the",
"default",
"database",
"or",
"not",
".",
"When",
"upgrading",
"from",
"older",
"releases",
"such",
"as",
"5",
".",
"1",
".",
"2",
"the",
"publish_context_table",
"may",
"not",
"have"... | def IsDefaultDatabase(self, publish_context_id):
"""
Checks whether the passed-in database is the default database or not. When
upgrading from older releases such as 5.1.2, the publish_context_table may
not have an entry for a published database, so we have to perform two
queries: one to get the list of databases and one to check if each database
is the default. It would simplify things somewhat to move the ec_default_db
field to the target_table database so that we can get all the data we want
with a single query. However, this would make the upgrade code more
complicated because we would have to manage 3 schemas: one from before we
added ec_default_db and two with the ec_default_db in different places.
This method seems to be the simplest overall option even though it requires
multiple queries.
"""
if publish_context_id != 0: # Ensure the publish_context_id is valid
query_string = ("""
SELECT publish_context_table.ec_default_db
FROM publish_context_table
WHERE publish_context_table.publish_context_id = %s AND
publish_context_table.ec_default_db = TRUE
""")
results = self.DbQuery(query_string, (publish_context_id,))
if results:
return True
return False | [
"def",
"IsDefaultDatabase",
"(",
"self",
",",
"publish_context_id",
")",
":",
"if",
"publish_context_id",
"!=",
"0",
":",
"# Ensure the publish_context_id is valid",
"query_string",
"=",
"(",
"\"\"\"\n SELECT publish_context_table.ec_default_db\n FROM publish_cont... | https://github.com/google/earthenterprise/blob/0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9/earth_enterprise/src/server/wsgi/serve/publish/publish_manager_helper.py#L152-L176 | |
KhronosGroup/SPIRV-Tools | 940127a77d3ad795a4a1422fbeaad50c9f19f2ea | utils/generate_registry_tables.py | python | mkdir_p | (directory) | Make the directory, and all its ancestors as required. Any of the
directories are allowed to already exist.
This is compatible with Python down to 3.0. | Make the directory, and all its ancestors as required. Any of the
directories are allowed to already exist.
This is compatible with Python down to 3.0. | [
"Make",
"the",
"directory",
"and",
"all",
"its",
"ancestors",
"as",
"required",
".",
"Any",
"of",
"the",
"directories",
"are",
"allowed",
"to",
"already",
"exist",
".",
"This",
"is",
"compatible",
"with",
"Python",
"down",
"to",
"3",
".",
"0",
"."
] | def mkdir_p(directory):
"""Make the directory, and all its ancestors as required. Any of the
directories are allowed to already exist.
This is compatible with Python down to 3.0.
"""
if directory == "":
# We're being asked to make the current directory.
return
try:
os.makedirs(directory)
except OSError as e:
if e.errno == errno.EEXIST and os.path.isdir(directory):
pass
else:
raise | [
"def",
"mkdir_p",
"(",
"directory",
")",
":",
"if",
"directory",
"==",
"\"\"",
":",
"# We're being asked to make the current directory.",
"return",
"try",
":",
"os",
".",
"makedirs",
"(",
"directory",
")",
"except",
"OSError",
"as",
"e",
":",
"if",
"e",
".",
... | https://github.com/KhronosGroup/SPIRV-Tools/blob/940127a77d3ad795a4a1422fbeaad50c9f19f2ea/utils/generate_registry_tables.py#L22-L38 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/core/setup.py | python | is_npy_no_smp | () | return 'NPY_NOSMP' in os.environ | Return True if the NPY_NO_SMP symbol must be defined in public
header (when SMP support cannot be reliably enabled). | Return True if the NPY_NO_SMP symbol must be defined in public
header (when SMP support cannot be reliably enabled). | [
"Return",
"True",
"if",
"the",
"NPY_NO_SMP",
"symbol",
"must",
"be",
"defined",
"in",
"public",
"header",
"(",
"when",
"SMP",
"support",
"cannot",
"be",
"reliably",
"enabled",
")",
"."
] | def is_npy_no_smp():
"""Return True if the NPY_NO_SMP symbol must be defined in public
header (when SMP support cannot be reliably enabled)."""
# Perhaps a fancier check is in order here.
# so that threads are only enabled if there
# are actually multiple CPUS? -- but
# threaded code can be nice even on a single
# CPU so that long-calculating code doesn't
# block.
return 'NPY_NOSMP' in os.environ | [
"def",
"is_npy_no_smp",
"(",
")",
":",
"# Perhaps a fancier check is in order here.",
"# so that threads are only enabled if there",
"# are actually multiple CPUS? -- but",
"# threaded code can be nice even on a single",
"# CPU so that long-calculating code doesn't",
"# block.",
"return",... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/core/setup.py#L83-L92 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/dtypes/common.py | python | is_interval_dtype | (arr_or_dtype) | return IntervalDtype.is_dtype(arr_or_dtype) | Check whether an array-like or dtype is of the Interval dtype.
Parameters
----------
arr_or_dtype : array-like
The array-like or dtype to check.
Returns
-------
boolean
Whether or not the array-like or dtype is of the Interval dtype.
Examples
--------
>>> is_interval_dtype(object)
False
>>> is_interval_dtype(IntervalDtype())
True
>>> is_interval_dtype([1, 2, 3])
False
>>>
>>> interval = pd.Interval(1, 2, closed="right")
>>> is_interval_dtype(interval)
False
>>> is_interval_dtype(pd.IntervalIndex([interval]))
True | Check whether an array-like or dtype is of the Interval dtype. | [
"Check",
"whether",
"an",
"array",
"-",
"like",
"or",
"dtype",
"is",
"of",
"the",
"Interval",
"dtype",
"."
] | def is_interval_dtype(arr_or_dtype) -> bool:
"""
Check whether an array-like or dtype is of the Interval dtype.
Parameters
----------
arr_or_dtype : array-like
The array-like or dtype to check.
Returns
-------
boolean
Whether or not the array-like or dtype is of the Interval dtype.
Examples
--------
>>> is_interval_dtype(object)
False
>>> is_interval_dtype(IntervalDtype())
True
>>> is_interval_dtype([1, 2, 3])
False
>>>
>>> interval = pd.Interval(1, 2, closed="right")
>>> is_interval_dtype(interval)
False
>>> is_interval_dtype(pd.IntervalIndex([interval]))
True
"""
# TODO: Consider making Interval an instance of IntervalDtype
if arr_or_dtype is None:
return False
return IntervalDtype.is_dtype(arr_or_dtype) | [
"def",
"is_interval_dtype",
"(",
"arr_or_dtype",
")",
"->",
"bool",
":",
"# TODO: Consider making Interval an instance of IntervalDtype",
"if",
"arr_or_dtype",
"is",
"None",
":",
"return",
"False",
"return",
"IntervalDtype",
".",
"is_dtype",
"(",
"arr_or_dtype",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/dtypes/common.py#L506-L539 | |
intel/caffe | 3f494b442ee3f9d17a07b09ecbd5fa2bbda00836 | examples/rfcn/lib/roi_data_layer/layer.py | python | RoIDataLayer.reshape | (self, bottom, top) | Reshaping happens during the call to forward. | Reshaping happens during the call to forward. | [
"Reshaping",
"happens",
"during",
"the",
"call",
"to",
"forward",
"."
] | def reshape(self, bottom, top):
"""Reshaping happens during the call to forward."""
pass | [
"def",
"reshape",
"(",
"self",
",",
"bottom",
",",
"top",
")",
":",
"pass"
] | https://github.com/intel/caffe/blob/3f494b442ee3f9d17a07b09ecbd5fa2bbda00836/examples/rfcn/lib/roi_data_layer/layer.py#L162-L164 | ||
falkTX/Carla | 74a1ae82c90db85f20550ddcdc8a927b8fb7e414 | source/modules/lilv/lilv-0.24.0/bindings/python/lilv.py | python | Instance.get_handle | (self) | return self.instance[0].lv2_handle | Get the LV2_Handle of the plugin instance.
Normally hosts should not need to access the LV2_Handle directly,
use the lilv_instance_* functions. | Get the LV2_Handle of the plugin instance. | [
"Get",
"the",
"LV2_Handle",
"of",
"the",
"plugin",
"instance",
"."
] | def get_handle(self):
"""Get the LV2_Handle of the plugin instance.
Normally hosts should not need to access the LV2_Handle directly,
use the lilv_instance_* functions.
"""
return self.instance[0].lv2_handle | [
"def",
"get_handle",
"(",
"self",
")",
":",
"return",
"self",
".",
"instance",
"[",
"0",
"]",
".",
"lv2_handle"
] | https://github.com/falkTX/Carla/blob/74a1ae82c90db85f20550ddcdc8a927b8fb7e414/source/modules/lilv/lilv-0.24.0/bindings/python/lilv.py#L1264-L1270 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/contrib/data/python/ops/readers.py | python | read_batch_features | (file_pattern,
batch_size,
features,
reader,
reader_args=None,
randomize_input=True,
num_epochs=None,
capacity=10000) | return result | Reads batches of Examples.
Example:
```
serialized_examples = [
features {
feature { key: "age" value { int64_list { value: [ 0 ] } } }
feature { key: "gender" value { bytes_list { value: [ "f" ] } } }
feature { key: "kws" value { bytes_list { value: [ "code", "art" ] } } }
},
features {
feature { key: "age" value { int64_list { value: [] } } }
feature { key: "gender" value { bytes_list { value: [ "f" ] } } }
feature { key: "kws" value { bytes_list { value: [ "sports" ] } } }
}
]
```
We can use arguments:
```
features: {
"age": FixedLenFeature([], dtype=tf.int64, default_value=-1),
"gender": FixedLenFeature([], dtype=tf.string),
"kws": VarLenFeature(dtype=tf.string),
}
```
And the expected output is:
```python
{
"age": [[0], [-1]],
"gender": [["f"], ["f"]],
"kws": SparseTensor(
indices=[[0, 0], [0, 1], [1, 0]],
values=["code", "art", "sports"]
dense_shape=[2, 2]),
}
```
Args:
file_pattern: List of files or patterns of file paths containing
`Example` records. See `tf.gfile.Glob` for pattern rules.
batch_size: An int representing the number of consecutive elements of this
dataset to combine in a single batch.
features: A `dict` mapping feature keys to `FixedLenFeature` or
`VarLenFeature` values. See `tf.parse_example`.
reader: A function or class that can be called with a `filenames` tensor
and (optional) `reader_args` and returns a `Dataset` of serialized
Examples.
reader_args: Additional arguments to pass to the reader class.
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.
capacity: Capacity of the ShuffleDataset. A large capacity ensures better
shuffling but would increase memory usage and startup time.
Returns:
A dict from keys in features to Tensor or SparseTensor objects. | Reads batches of Examples. | [
"Reads",
"batches",
"of",
"Examples",
"."
] | def read_batch_features(file_pattern,
batch_size,
features,
reader,
reader_args=None,
randomize_input=True,
num_epochs=None,
capacity=10000):
"""Reads batches of Examples.
Example:
```
serialized_examples = [
features {
feature { key: "age" value { int64_list { value: [ 0 ] } } }
feature { key: "gender" value { bytes_list { value: [ "f" ] } } }
feature { key: "kws" value { bytes_list { value: [ "code", "art" ] } } }
},
features {
feature { key: "age" value { int64_list { value: [] } } }
feature { key: "gender" value { bytes_list { value: [ "f" ] } } }
feature { key: "kws" value { bytes_list { value: [ "sports" ] } } }
}
]
```
We can use arguments:
```
features: {
"age": FixedLenFeature([], dtype=tf.int64, default_value=-1),
"gender": FixedLenFeature([], dtype=tf.string),
"kws": VarLenFeature(dtype=tf.string),
}
```
And the expected output is:
```python
{
"age": [[0], [-1]],
"gender": [["f"], ["f"]],
"kws": SparseTensor(
indices=[[0, 0], [0, 1], [1, 0]],
values=["code", "art", "sports"]
dense_shape=[2, 2]),
}
```
Args:
file_pattern: List of files or patterns of file paths containing
`Example` records. See `tf.gfile.Glob` for pattern rules.
batch_size: An int representing the number of consecutive elements of this
dataset to combine in a single batch.
features: A `dict` mapping feature keys to `FixedLenFeature` or
`VarLenFeature` values. See `tf.parse_example`.
reader: A function or class that can be called with a `filenames` tensor
and (optional) `reader_args` and returns a `Dataset` of serialized
Examples.
reader_args: Additional arguments to pass to the reader class.
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.
capacity: Capacity of the ShuffleDataset. A large capacity ensures better
shuffling but would increase memory usage and startup time.
Returns:
A dict from keys in features to Tensor or SparseTensor objects.
"""
filenames = _get_file_names(file_pattern, randomize_input)
if reader_args:
dataset = reader(filenames, *reader_args)
else:
dataset = reader(filenames)
if dataset.output_types == (dtypes.string, dtypes.string):
dataset = dataset.map(lambda unused_k, v: v)
elif dataset.output_types != dtypes.string:
raise TypeError("`reader` must be a dataset of `tf.string` values, "
"or `(tf.string, tf.string)` key-value pairs.")
if num_epochs != 1:
dataset = dataset.repeat(num_epochs)
if randomize_input:
dataset = dataset.shuffle(capacity)
dataset = dataset.batch(batch_size)
dataset = dataset.map(lambda x: _parse_example(x, features))
iterator = dataset.make_one_shot_iterator()
outputs = iterator.get_next()
index = 0
result = {}
for key in sorted(features.keys()):
feature = features[key]
if isinstance(feature, parsing_ops.FixedLenFeature):
result[key] = outputs[index]
index += 1
else:
result[key] = sparse_tensor_lib.SparseTensor(
indices=outputs[index],
values=outputs[index + 1],
dense_shape=outputs[index + 2])
index += 3
return result | [
"def",
"read_batch_features",
"(",
"file_pattern",
",",
"batch_size",
",",
"features",
",",
"reader",
",",
"reader_args",
"=",
"None",
",",
"randomize_input",
"=",
"True",
",",
"num_epochs",
"=",
"None",
",",
"capacity",
"=",
"10000",
")",
":",
"filenames",
... | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/data/python/ops/readers.py#L101-L202 | |
cms-sw/cmssw | fd9de012d503d3405420bcbeec0ec879baa57cf2 | Utilities/RelMon/python/utils_v2.py | python | check_disk_for_space | (work_path, size_needed) | Checks afs file system for space. | Checks afs file system for space. | [
"Checks",
"afs",
"file",
"system",
"for",
"space",
"."
] | def check_disk_for_space(work_path, size_needed):
'''Checks afs file system for space.'''
pass | [
"def",
"check_disk_for_space",
"(",
"work_path",
",",
"size_needed",
")",
":",
"pass"
] | https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/Utilities/RelMon/python/utils_v2.py#L462-L464 | ||
intel/libxcam | f0909548fce2245dc5e95922a51f709ec05b98f4 | modules/dnn/feathernet/main.py | python | accuracy | (output, target, topk=(1,)) | return res | Computes the precision@k for the specified values of k | Computes the precision | [
"Computes",
"the",
"precision"
] | def accuracy(output, target, topk=(1,)):
"""Computes the precision@k for the specified values of k"""
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.eq(target.view(1, -1).expand_as(pred))
res = []
for k in topk:
correct_k = correct[:k].view(-1).float().sum(0, keepdim=True)
res.append(correct_k.mul_(100.0 / batch_size))
return res | [
"def",
"accuracy",
"(",
"output",
",",
"target",
",",
"topk",
"=",
"(",
"1",
",",
")",
")",
":",
"maxk",
"=",
"max",
"(",
"topk",
")",
"batch_size",
"=",
"target",
".",
"size",
"(",
"0",
")",
"_",
",",
"pred",
"=",
"output",
".",
"topk",
"(",
... | https://github.com/intel/libxcam/blob/f0909548fce2245dc5e95922a51f709ec05b98f4/modules/dnn/feathernet/main.py#L424-L437 | |
MhLiao/TextBoxes_plusplus | 39d4898de1504c53a2ed3d67966a57b3595836d0 | python/caffe/draw.py | python | draw_net_to_file | (caffe_net, filename, rankdir='LR', phase=None) | Draws a caffe net, and saves it to file using the format given as the
file extension. Use '.raw' to output raw text that you can manually feed
to graphviz to draw graphs.
Parameters
----------
caffe_net : a caffe.proto.caffe_pb2.NetParameter protocol buffer.
filename : string
The path to a file where the networks visualization will be stored.
rankdir : {'LR', 'TB', 'BT'}
Direction of graph layout.
phase : {caffe_pb2.Phase.TRAIN, caffe_pb2.Phase.TEST, None} optional
Include layers from this network phase. If None, include all layers.
(the default is None) | Draws a caffe net, and saves it to file using the format given as the
file extension. Use '.raw' to output raw text that you can manually feed
to graphviz to draw graphs. | [
"Draws",
"a",
"caffe",
"net",
"and",
"saves",
"it",
"to",
"file",
"using",
"the",
"format",
"given",
"as",
"the",
"file",
"extension",
".",
"Use",
".",
"raw",
"to",
"output",
"raw",
"text",
"that",
"you",
"can",
"manually",
"feed",
"to",
"graphviz",
"t... | def draw_net_to_file(caffe_net, filename, rankdir='LR', phase=None):
"""Draws a caffe net, and saves it to file using the format given as the
file extension. Use '.raw' to output raw text that you can manually feed
to graphviz to draw graphs.
Parameters
----------
caffe_net : a caffe.proto.caffe_pb2.NetParameter protocol buffer.
filename : string
The path to a file where the networks visualization will be stored.
rankdir : {'LR', 'TB', 'BT'}
Direction of graph layout.
phase : {caffe_pb2.Phase.TRAIN, caffe_pb2.Phase.TEST, None} optional
Include layers from this network phase. If None, include all layers.
(the default is None)
"""
ext = filename[filename.rfind('.')+1:]
with open(filename, 'wb') as fid:
fid.write(draw_net(caffe_net, rankdir, ext, phase)) | [
"def",
"draw_net_to_file",
"(",
"caffe_net",
",",
"filename",
",",
"rankdir",
"=",
"'LR'",
",",
"phase",
"=",
"None",
")",
":",
"ext",
"=",
"filename",
"[",
"filename",
".",
"rfind",
"(",
"'.'",
")",
"+",
"1",
":",
"]",
"with",
"open",
"(",
"filename... | https://github.com/MhLiao/TextBoxes_plusplus/blob/39d4898de1504c53a2ed3d67966a57b3595836d0/python/caffe/draw.py#L226-L244 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/ed_cmdbar.py | python | PopupListBase.SetSelection | (self, index) | Set the selection in the list by index
@param index: zero based index to set selection by | Set the selection in the list by index
@param index: zero based index to set selection by | [
"Set",
"the",
"selection",
"in",
"the",
"list",
"by",
"index",
"@param",
"index",
":",
"zero",
"based",
"index",
"to",
"set",
"selection",
"by"
] | def SetSelection(self, index):
"""Set the selection in the list by index
@param index: zero based index to set selection by
"""
self._list.SetSelection(index) | [
"def",
"SetSelection",
"(",
"self",
",",
"index",
")",
":",
"self",
".",
"_list",
".",
"SetSelection",
"(",
"index",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/ed_cmdbar.py#L1096-L1101 | ||
hpi-xnor/BMXNet-v2 | af2b1859eafc5c721b1397cef02f946aaf2ce20d | tools/caffe_converter/convert_mean.py | python | convert_mean | (binaryproto_fname, output=None) | return nd | Convert caffe mean
Parameters
----------
binaryproto_fname : str
Filename of the mean
output : str, optional
Save the mean into mxnet's format
Returns
-------
NDArray
Mean in ndarray | Convert caffe mean | [
"Convert",
"caffe",
"mean"
] | def convert_mean(binaryproto_fname, output=None):
"""Convert caffe mean
Parameters
----------
binaryproto_fname : str
Filename of the mean
output : str, optional
Save the mean into mxnet's format
Returns
-------
NDArray
Mean in ndarray
"""
mean_blob = caffe_parser.caffe_pb2.BlobProto()
with open(binaryproto_fname, 'rb') as f:
mean_blob.ParseFromString(f.read())
img_mean_np = np.array(mean_blob.data)
img_mean_np = img_mean_np.reshape(
mean_blob.channels, mean_blob.height, mean_blob.width
)
# swap channels from Caffe BGR to RGB
img_mean_np[[0, 2], :, :] = img_mean_np[[2, 0], :, :]
nd = mx.nd.array(img_mean_np)
if output is not None:
mx.nd.save(output, {"mean_image": nd})
return nd | [
"def",
"convert_mean",
"(",
"binaryproto_fname",
",",
"output",
"=",
"None",
")",
":",
"mean_blob",
"=",
"caffe_parser",
".",
"caffe_pb2",
".",
"BlobProto",
"(",
")",
"with",
"open",
"(",
"binaryproto_fname",
",",
"'rb'",
")",
"as",
"f",
":",
"mean_blob",
... | https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/tools/caffe_converter/convert_mean.py#L25-L53 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/xrc.py | python | XmlProperty.GetValue | (*args, **kwargs) | return _xrc.XmlProperty_GetValue(*args, **kwargs) | GetValue(self) -> String | GetValue(self) -> String | [
"GetValue",
"(",
"self",
")",
"-",
">",
"String"
] | def GetValue(*args, **kwargs):
"""GetValue(self) -> String"""
return _xrc.XmlProperty_GetValue(*args, **kwargs) | [
"def",
"GetValue",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_xrc",
".",
"XmlProperty_GetValue",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/xrc.py#L320-L322 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/propgrid.py | python | PropertyGrid.ClearActionTriggers | (*args, **kwargs) | return _propgrid.PropertyGrid_ClearActionTriggers(*args, **kwargs) | ClearActionTriggers(self, int action) | ClearActionTriggers(self, int action) | [
"ClearActionTriggers",
"(",
"self",
"int",
"action",
")"
] | def ClearActionTriggers(*args, **kwargs):
"""ClearActionTriggers(self, int action)"""
return _propgrid.PropertyGrid_ClearActionTriggers(*args, **kwargs) | [
"def",
"ClearActionTriggers",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_propgrid",
".",
"PropertyGrid_ClearActionTriggers",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/propgrid.py#L2003-L2005 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/numbers.py | python | Integral.__rand__ | (self, other) | other & self | other & self | [
"other",
"&",
"self"
] | def __rand__(self, other):
"""other & self"""
raise NotImplementedError | [
"def",
"__rand__",
"(",
"self",
",",
"other",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/numbers.py#L346-L348 | ||
CRYTEK/CRYENGINE | 232227c59a220cbbd311576f0fbeba7bb53b2a8c | Code/Tools/waf-1.7.13/waflib/extras/review.py | python | ReviewContext.refresh_review_set | (self) | Obtain the old review set and the new review set, and import the new set. | Obtain the old review set and the new review set, and import the new set. | [
"Obtain",
"the",
"old",
"review",
"set",
"and",
"the",
"new",
"review",
"set",
"and",
"import",
"the",
"new",
"set",
"."
] | def refresh_review_set(self):
"""
Obtain the old review set and the new review set, and import the new set.
"""
global old_review_set, new_review_set
old_review_set = self.load_review_set()
new_review_set = self.update_review_set(old_review_set)
self.import_review_set(new_review_set) | [
"def",
"refresh_review_set",
"(",
"self",
")",
":",
"global",
"old_review_set",
",",
"new_review_set",
"old_review_set",
"=",
"self",
".",
"load_review_set",
"(",
")",
"new_review_set",
"=",
"self",
".",
"update_review_set",
"(",
"old_review_set",
")",
"self",
"."... | https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Code/Tools/waf-1.7.13/waflib/extras/review.py#L180-L187 | ||
smartdevicelink/sdl_core | 68f082169e0a40fccd9eb0db3c83911c28870f07 | tools/InterfaceGenerator/MsgVersionGenerate.py | python | prepare_data_for_storage | (major_version, minor_version, patch_version, minimum_major_version, minimum_minor_version, minimum_patch_version) | return data_to_file | Prepares data to store to file. | Prepares data to store to file. | [
"Prepares",
"data",
"to",
"store",
"to",
"file",
"."
] | def prepare_data_for_storage(major_version, minor_version, patch_version, minimum_major_version, minimum_minor_version, minimum_patch_version):
"""Prepares data to store to file.
"""
temp = Template(
u'''/*Copyright (c) 2019, SmartDeviceLink Consortium, Inc.\n'''
u'''All rights reserved.\n'''
u'''Redistribution and use in source and binary forms, with or without\n'''
u'''modification, are permitted provided that the following conditions are met:\n'''
u'''Redistributions of source code must retain the above copyright notice, this\n'''
u'''list of conditions and the following disclaimer.\n'''
u'''Redistributions in binary form must reproduce the above copyright notice,\n'''
u'''this list of conditions and the following\n'''
u'''disclaimer in the documentation and/or other materials provided with the\n'''
u'''distribution.\n'''
u'''Neither the name of the SmartDeviceLink Consortium, Inc. nor the names of its\n'''
u'''contributors may be used to endorse or promote products derived from this\n'''
u'''software without specific prior written permission.\n'''
u'''THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n'''
u'''AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n'''
u'''IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n'''
u'''ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n'''
u'''LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n'''
u'''CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n'''
u'''SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n'''
u'''INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n'''
u'''CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n'''
u'''ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n'''
u'''POSSIBILITY OF SUCH DAMAGE.\n'''
u'''*/\n'''
u'''#ifndef GENERATED_MSG_VERSION_H\n'''
u'''#define GENERATED_MSG_VERSION_H\n\n'''
u'''#include <cstdint>\n\n'''
u'''namespace application_manager {\n\n'''
u'''const uint16_t major_version = $m_version;\n'''
u'''const uint16_t minor_version = $min_version;\n'''
u'''const uint16_t patch_version = $p_version;\n'''
u'''const uint16_t minimum_major_version = $min_major_version;\n'''
u'''const uint16_t minimum_minor_version = $min_minor_version;\n'''
u'''const uint16_t minimum_patch_version = $min_patch_version;\n'''
u'''} // namespace application_manager\n'''
u'''#endif // GENERATED_MSG_VERSION_H''')
data_to_file = temp.substitute(m_version = major_version, min_version = minor_version, p_version = patch_version,
min_major_version = minimum_major_version, min_minor_version = minimum_minor_version, min_patch_version = minimum_patch_version)
return data_to_file | [
"def",
"prepare_data_for_storage",
"(",
"major_version",
",",
"minor_version",
",",
"patch_version",
",",
"minimum_major_version",
",",
"minimum_minor_version",
",",
"minimum_patch_version",
")",
":",
"temp",
"=",
"Template",
"(",
"u'''/*Copyright (c) 2019, SmartDeviceLink Co... | https://github.com/smartdevicelink/sdl_core/blob/68f082169e0a40fccd9eb0db3c83911c28870f07/tools/InterfaceGenerator/MsgVersionGenerate.py#L70-L113 | |
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | current/tools/gyp/pylib/gyp/MSVSVersion.py | python | _ConvertToCygpath | (path) | return path | Convert to cygwin path if we are using cygwin. | Convert to cygwin path if we are using cygwin. | [
"Convert",
"to",
"cygwin",
"path",
"if",
"we",
"are",
"using",
"cygwin",
"."
] | def _ConvertToCygpath(path):
"""Convert to cygwin path if we are using cygwin."""
if sys.platform == 'cygwin':
p = subprocess.Popen(['cygpath', path], stdout=subprocess.PIPE)
path = p.communicate()[0].strip()
if PY3:
path = path.decode('utf-8')
return path | [
"def",
"_ConvertToCygpath",
"(",
"path",
")",
":",
"if",
"sys",
".",
"platform",
"==",
"'cygwin'",
":",
"p",
"=",
"subprocess",
".",
"Popen",
"(",
"[",
"'cygpath'",
",",
"path",
"]",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
")",
"path",
"=",
"p... | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/current/tools/gyp/pylib/gyp/MSVSVersion.py#L387-L394 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/traitlets/py2/traitlets/config/configurable.py | python | SingletonConfigurable.initialized | (cls) | return hasattr(cls, "_instance") and cls._instance is not None | Has an instance been created? | Has an instance been created? | [
"Has",
"an",
"instance",
"been",
"created?"
] | def initialized(cls):
"""Has an instance been created?"""
return hasattr(cls, "_instance") and cls._instance is not None | [
"def",
"initialized",
"(",
"cls",
")",
":",
"return",
"hasattr",
"(",
"cls",
",",
"\"_instance\"",
")",
"and",
"cls",
".",
"_instance",
"is",
"not",
"None"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/traitlets/py2/traitlets/config/configurable.py#L427-L429 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/window/rolling.py | python | _Window._get_window_indexer | (self, window: int) | return FixedWindowIndexer(window_size=window) | Return an indexer class that will compute the window start and end bounds | Return an indexer class that will compute the window start and end bounds | [
"Return",
"an",
"indexer",
"class",
"that",
"will",
"compute",
"the",
"window",
"start",
"and",
"end",
"bounds"
] | def _get_window_indexer(self, window: int) -> BaseIndexer:
"""
Return an indexer class that will compute the window start and end bounds
"""
if isinstance(self.window, BaseIndexer):
return self.window
if self.is_freq_type:
return VariableWindowIndexer(index_array=self._on.asi8, window_size=window)
return FixedWindowIndexer(window_size=window) | [
"def",
"_get_window_indexer",
"(",
"self",
",",
"window",
":",
"int",
")",
"->",
"BaseIndexer",
":",
"if",
"isinstance",
"(",
"self",
".",
"window",
",",
"BaseIndexer",
")",
":",
"return",
"self",
".",
"window",
"if",
"self",
".",
"is_freq_type",
":",
"r... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/window/rolling.py#L399-L407 | |
seqan/seqan | f5f658343c366c9c3d44ba358ffc9317e78a09ed | util/py_lib/seqan/paths.py | python | pathToInclude | (location) | return os.path.join(repositoryRoot(), location, 'include') | Return path to the include dir in the given location/repository. | Return path to the include dir in the given location/repository. | [
"Return",
"path",
"to",
"the",
"include",
"dir",
"in",
"the",
"given",
"location",
"/",
"repository",
"."
] | def pathToInclude(location):
"""Return path to the include dir in the given location/repository."""
return os.path.join(repositoryRoot(), location, 'include') | [
"def",
"pathToInclude",
"(",
"location",
")",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"repositoryRoot",
"(",
")",
",",
"location",
",",
"'include'",
")"
] | https://github.com/seqan/seqan/blob/f5f658343c366c9c3d44ba358ffc9317e78a09ed/util/py_lib/seqan/paths.py#L38-L40 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/propgrid.py | python | PGProperty.OnCustomPaint | (*args, **kwargs) | return _propgrid.PGProperty_OnCustomPaint(*args, **kwargs) | OnCustomPaint(self, DC dc, Rect rect, PGPaintData paintdata) | OnCustomPaint(self, DC dc, Rect rect, PGPaintData paintdata) | [
"OnCustomPaint",
"(",
"self",
"DC",
"dc",
"Rect",
"rect",
"PGPaintData",
"paintdata",
")"
] | def OnCustomPaint(*args, **kwargs):
"""OnCustomPaint(self, DC dc, Rect rect, PGPaintData paintdata)"""
return _propgrid.PGProperty_OnCustomPaint(*args, **kwargs) | [
"def",
"OnCustomPaint",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_propgrid",
".",
"PGProperty_OnCustomPaint",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/propgrid.py#L401-L403 | |
vnpy/vnpy | f50f2535ed39dd33272e0985ed40c7078e4c19f6 | vnpy/trader/engine.py | python | MainEngine.get_all_gateway_names | (self) | return list(self.gateways.keys()) | Get all names of gatewasy added in main engine. | Get all names of gatewasy added in main engine. | [
"Get",
"all",
"names",
"of",
"gatewasy",
"added",
"in",
"main",
"engine",
"."
] | def get_all_gateway_names(self) -> List[str]:
"""
Get all names of gatewasy added in main engine.
"""
return list(self.gateways.keys()) | [
"def",
"get_all_gateway_names",
"(",
"self",
")",
"->",
"List",
"[",
"str",
"]",
":",
"return",
"list",
"(",
"self",
".",
"gateways",
".",
"keys",
"(",
")",
")"
] | https://github.com/vnpy/vnpy/blob/f50f2535ed39dd33272e0985ed40c7078e4c19f6/vnpy/trader/engine.py#L145-L149 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_misc.py | python | PyDataObjectSimple.__init__ | (self, *args, **kwargs) | __init__(self, DataFormat format=FormatInvalid) -> PyDataObjectSimple
wx.PyDataObjectSimple is a version of `wx.DataObjectSimple` that is
Python-aware and knows how to reflect calls to its C++ virtual methods
to methods in the Python derived class. You should derive from this
class and overload `GetDataSize`, `GetDataHere` and `SetData` when you
need to create your own simple single-format type of `wx.DataObject`. | __init__(self, DataFormat format=FormatInvalid) -> PyDataObjectSimple | [
"__init__",
"(",
"self",
"DataFormat",
"format",
"=",
"FormatInvalid",
")",
"-",
">",
"PyDataObjectSimple"
] | def __init__(self, *args, **kwargs):
"""
__init__(self, DataFormat format=FormatInvalid) -> PyDataObjectSimple
wx.PyDataObjectSimple is a version of `wx.DataObjectSimple` that is
Python-aware and knows how to reflect calls to its C++ virtual methods
to methods in the Python derived class. You should derive from this
class and overload `GetDataSize`, `GetDataHere` and `SetData` when you
need to create your own simple single-format type of `wx.DataObject`.
"""
_misc_.PyDataObjectSimple_swiginit(self,_misc_.new_PyDataObjectSimple(*args, **kwargs))
PyDataObjectSimple._setCallbackInfo(self, self, PyDataObjectSimple) | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_misc_",
".",
"PyDataObjectSimple_swiginit",
"(",
"self",
",",
"_misc_",
".",
"new_PyDataObjectSimple",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")",
"PyDataObje... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_misc.py#L5078-L5090 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/py/dispatcher.py | python | disconnect | (receiver, signal=Any, sender=Any, weak=True) | Disconnect receiver from sender for signal.
Disconnecting is not required. The use of disconnect is the same as for
connect, only in reverse. Think of it as undoing a previous connection. | Disconnect receiver from sender for signal.
Disconnecting is not required. The use of disconnect is the same as for
connect, only in reverse. Think of it as undoing a previous connection. | [
"Disconnect",
"receiver",
"from",
"sender",
"for",
"signal",
".",
"Disconnecting",
"is",
"not",
"required",
".",
"The",
"use",
"of",
"disconnect",
"is",
"the",
"same",
"as",
"for",
"connect",
"only",
"in",
"reverse",
".",
"Think",
"of",
"it",
"as",
"undoin... | def disconnect(receiver, signal=Any, sender=Any, weak=True):
"""Disconnect receiver from sender for signal.
Disconnecting is not required. The use of disconnect is the same as for
connect, only in reverse. Think of it as undoing a previous connection."""
if signal is None:
raise DispatcherError, 'signal cannot be None'
if weak:
receiver = safeRef(receiver)
senderkey = id(sender)
try:
receivers = connections[senderkey][signal]
except KeyError:
raise DispatcherError, \
'No receivers for signal %r from sender %s' % (signal, sender)
try:
receivers.remove(receiver)
except ValueError:
raise DispatcherError, \
'No connection to receiver %s for signal %r from sender %s' % \
(receiver, signal, sender)
_cleanupConnections(senderkey, signal) | [
"def",
"disconnect",
"(",
"receiver",
",",
"signal",
"=",
"Any",
",",
"sender",
"=",
"Any",
",",
"weak",
"=",
"True",
")",
":",
"if",
"signal",
"is",
"None",
":",
"raise",
"DispatcherError",
",",
"'signal cannot be None'",
"if",
"weak",
":",
"receiver",
... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/py/dispatcher.py#L79-L100 | ||
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | scripts/SANS/sans/common/file_information.py | python | get_geometry_information_isis_added_nexus | (file_name) | return height, width, thickness, shape | Gets geometry information from the sample folder in an added nexus file
:param file_name: the file name
:return: height, width, thickness, shape | Gets geometry information from the sample folder in an added nexus file | [
"Gets",
"geometry",
"information",
"from",
"the",
"sample",
"folder",
"in",
"an",
"added",
"nexus",
"file"
] | def get_geometry_information_isis_added_nexus(file_name):
"""
Gets geometry information from the sample folder in an added nexus file
:param file_name: the file name
:return: height, width, thickness, shape
"""
with h5.File(file_name, 'r') as h5_file:
# Open first entry
keys = list(h5_file.keys())
top_level = h5_file[keys[0]]
sample = top_level[SAMPLE]
height = float(sample[GEOM_HEIGHT][0])
width = float(sample[GEOM_WIDTH][0])
thickness = float(sample[GEOM_THICKNESS][0])
shape_id = int(sample[GEOM_ID][0])
shape = convert_to_shape(shape_id)
return height, width, thickness, shape | [
"def",
"get_geometry_information_isis_added_nexus",
"(",
"file_name",
")",
":",
"with",
"h5",
".",
"File",
"(",
"file_name",
",",
"'r'",
")",
"as",
"h5_file",
":",
"# Open first entry",
"keys",
"=",
"list",
"(",
"h5_file",
".",
"keys",
"(",
")",
")",
"top_le... | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/SANS/sans/common/file_information.py#L560-L577 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/distro.py | python | LinuxDistribution._parse_os_release_content | (lines) | return props | Parse the lines of an os-release file.
Parameters:
* lines: Iterable through the lines in the os-release file.
Each line must be a unicode string or a UTF-8 encoded byte
string.
Returns:
A dictionary containing all information items. | [] | def _parse_os_release_content(lines):
"""
Parse the lines of an os-release file.
Parameters:
* lines: Iterable through the lines in the os-release file.
Each line must be a unicode string or a UTF-8 encoded byte
string.
Returns:
A dictionary containing all information items.
"""
props = {}
lexer = shlex.shlex(lines, posix=True)
lexer.whitespace_split = True
# The shlex module defines its `wordchars` variable using literals,
# making it dependent on the encoding of the Python source file.
# In Python 2.6 and 2.7, the shlex source file is encoded in
# 'iso-8859-1', and the `wordchars` variable is defined as a byte
# string. This causes a UnicodeDecodeError to be raised when the
# parsed content is a unicode object. The following fix resolves that
# (... but it should be fixed in shlex...):
if sys.version_info[0] == 2 and isinstance(lexer.wordchars, bytes):
lexer.wordchars = lexer.wordchars.decode('iso-8859-1')
tokens = list(lexer)
for token in tokens:
# At this point, all shell-like parsing has been done (i.e.
# comments processed, quotes and backslash escape sequences
# processed, multi-line values assembled, trailing newlines
# stripped, etc.), so the tokens are now either:
# * variable assignments: var=value
# * commands or their arguments (not allowed in os-release)
if '=' in token:
k, v = token.split('=', 1)
props[k.lower()] = v
else:
# Ignore any tokens that are not variable assignments
pass
if 'version_codename' in props:
# os-release added a version_codename field. Use that in
# preference to anything else Note that some distros purposefully
# do not have code names. They should be setting
# version_codename=""
props['codename'] = props['version_codename']
elif 'ubuntu_codename' in props:
# Same as above but a non-standard field name used on older Ubuntus
props['codename'] = props['ubuntu_codename']
elif 'version' in props:
# If there is no version_codename, parse it from the version
codename = re.search(r'(\(\D+\))|,(\s+)?\D+', props['version'])
if codename:
codename = codename.group()
codename = codename.strip('()')
codename = codename.strip(',')
codename = codename.strip()
# codename appears within paranthese.
props['codename'] = codename
return props | [
"def",
"_parse_os_release_content",
"(",
"lines",
")",
":",
"props",
"=",
"{",
"}",
"lexer",
"=",
"shlex",
".",
"shlex",
"(",
"lines",
",",
"posix",
"=",
"True",
")",
"lexer",
".",
"whitespace_split",
"=",
"True",
"# The shlex module defines its `wordchars` vari... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/distro.py#L1873-L1997 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py2/scipy/stats/_distn_infrastructure.py | python | rv_continuous.nnlf | (self, theta, x) | return self._nnlf(x, *args) + n_log_scale | Return negative loglikelihood function.
Notes
-----
This is ``-sum(log pdf(x, theta), axis=0)`` where `theta` are the
parameters (including loc and scale). | Return negative loglikelihood function. | [
"Return",
"negative",
"loglikelihood",
"function",
"."
] | def nnlf(self, theta, x):
'''Return negative loglikelihood function.
Notes
-----
This is ``-sum(log pdf(x, theta), axis=0)`` where `theta` are the
parameters (including loc and scale).
'''
loc, scale, args = self._unpack_loc_scale(theta)
if not self._argcheck(*args) or scale <= 0:
return inf
x = asarray((x-loc) / scale)
n_log_scale = len(x) * log(scale)
if np.any(~self._support_mask(x)):
return inf
return self._nnlf(x, *args) + n_log_scale | [
"def",
"nnlf",
"(",
"self",
",",
"theta",
",",
"x",
")",
":",
"loc",
",",
"scale",
",",
"args",
"=",
"self",
".",
"_unpack_loc_scale",
"(",
"theta",
")",
"if",
"not",
"self",
".",
"_argcheck",
"(",
"*",
"args",
")",
"or",
"scale",
"<=",
"0",
":",... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/stats/_distn_infrastructure.py#L1990-L2005 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Tools/gdb/libpython.py | python | Frame.is_other_python_frame | (self) | return False | Is this frame worth displaying in python backtraces?
Examples:
- waiting on the GIL
- garbage-collecting
- within a CFunction
If it is, return a descriptive string
For other frames, return False | Is this frame worth displaying in python backtraces?
Examples:
- waiting on the GIL
- garbage-collecting
- within a CFunction
If it is, return a descriptive string
For other frames, return False | [
"Is",
"this",
"frame",
"worth",
"displaying",
"in",
"python",
"backtraces?",
"Examples",
":",
"-",
"waiting",
"on",
"the",
"GIL",
"-",
"garbage",
"-",
"collecting",
"-",
"within",
"a",
"CFunction",
"If",
"it",
"is",
"return",
"a",
"descriptive",
"string",
... | def is_other_python_frame(self):
'''Is this frame worth displaying in python backtraces?
Examples:
- waiting on the GIL
- garbage-collecting
- within a CFunction
If it is, return a descriptive string
For other frames, return False
'''
if self.is_waiting_for_gil():
return 'Waiting for the GIL'
if self.is_gc_collect():
return 'Garbage-collecting'
# Detect invocations of PyCFunction instances:
frame = self._gdbframe
caller = frame.name()
if not caller:
return False
if caller == 'PyCFunction_Call':
arg_name = 'func'
# Within that frame:
# "func" is the local containing the PyObject* of the
# PyCFunctionObject instance
# "f" is the same value, but cast to (PyCFunctionObject*)
# "self" is the (PyObject*) of the 'self'
try:
# Use the prettyprinter for the func:
func = frame.read_var(arg_name)
return str(func)
except ValueError:
return ('PyCFunction invocation (unable to read %s: '
'missing debuginfos?)' % arg_name)
except RuntimeError:
return 'PyCFunction invocation (unable to read %s)' % arg_name
if caller == 'wrapper_call':
arg_name = 'wp'
try:
func = frame.read_var(arg_name)
return str(func)
except ValueError:
return ('<wrapper_call invocation (unable to read %s: '
'missing debuginfos?)>' % arg_name)
except RuntimeError:
return '<wrapper_call invocation (unable to read %s)>' % arg_name
# This frame isn't worth reporting:
return False | [
"def",
"is_other_python_frame",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_waiting_for_gil",
"(",
")",
":",
"return",
"'Waiting for the GIL'",
"if",
"self",
".",
"is_gc_collect",
"(",
")",
":",
"return",
"'Garbage-collecting'",
"# Detect invocations of PyCFunction ... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Tools/gdb/libpython.py#L1359-L1409 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/roc/hsadrv/devicearray.py | python | DeviceNDArray.is_c_contiguous | (self) | return self._dummy.is_c_contig | Return true if the array is C-contiguous. | Return true if the array is C-contiguous. | [
"Return",
"true",
"if",
"the",
"array",
"is",
"C",
"-",
"contiguous",
"."
] | def is_c_contiguous(self):
'''
Return true if the array is C-contiguous.
'''
return self._dummy.is_c_contig | [
"def",
"is_c_contiguous",
"(",
"self",
")",
":",
"return",
"self",
".",
"_dummy",
".",
"is_c_contig"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/roc/hsadrv/devicearray.py#L262-L266 | |
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/models/embedding/word2vec_optimized.py | python | Word2Vec.train | (self) | Train the model. | Train the model. | [
"Train",
"the",
"model",
"."
] | def train(self):
"""Train the model."""
opts = self._options
initial_epoch, initial_words = self._session.run([self._epoch, self._words])
workers = []
for _ in xrange(opts.concurrent_steps):
t = threading.Thread(target=self._train_thread_body)
t.start()
workers.append(t)
last_words, last_time = initial_words, time.time()
while True:
time.sleep(5) # Reports our progress once a while.
(epoch, step, words,
lr) = self._session.run([self._epoch, self.step, self._words, self._lr])
now = time.time()
last_words, last_time, rate = words, now, (words - last_words) / (
now - last_time)
print("Epoch %4d Step %8d: lr = %5.3f words/sec = %8.0f\r" % (epoch, step,
lr, rate),
end="")
sys.stdout.flush()
if epoch != initial_epoch:
break
for t in workers:
t.join() | [
"def",
"train",
"(",
"self",
")",
":",
"opts",
"=",
"self",
".",
"_options",
"initial_epoch",
",",
"initial_words",
"=",
"self",
".",
"_session",
".",
"run",
"(",
"[",
"self",
".",
"_epoch",
",",
"self",
".",
"_words",
"]",
")",
"workers",
"=",
"[",
... | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/models/embedding/word2vec_optimized.py#L310-L338 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/build/waf-1.7.13/waflib/extras/run_m_script.py | python | apply_run_m_script | (tg) | Task generator customising the options etc. to call Matlab in batch
mode for running a m-script. | Task generator customising the options etc. to call Matlab in batch
mode for running a m-script. | [
"Task",
"generator",
"customising",
"the",
"options",
"etc",
".",
"to",
"call",
"Matlab",
"in",
"batch",
"mode",
"for",
"running",
"a",
"m",
"-",
"script",
"."
] | def apply_run_m_script(tg):
"""Task generator customising the options etc. to call Matlab in batch
mode for running a m-script.
"""
# Convert sources and targets to nodes
src_node = tg.path.find_resource(tg.source)
tgt_nodes = [tg.path.find_or_declare(t) for t in tg.to_list(tg.target)]
tsk = tg.create_task('run_m_script', src=src_node, tgt=tgt_nodes)
tsk.cwd = src_node.parent.abspath()
tsk.env.MSCRIPTTRUNK = os.path.splitext(src_node.name)[0]
tsk.env.LOGFILEPATH = os.path.join(tg.bld.bldnode.abspath(), '%s_%d.log' % (tsk.env.MSCRIPTTRUNK, tg.idx))
# dependencies (if the attribute 'deps' changes, trigger a recompilation)
for x in tg.to_list(getattr(tg, 'deps', [])):
node = tg.path.find_resource(x)
if not node:
tg.bld.fatal('Could not find dependency %r for running %r' % (x, src_node.nice_path()))
tsk.dep_nodes.append(node)
Logs.debug('deps: found dependencies %r for running %r' % (tsk.dep_nodes, src_node.nice_path()))
# Bypass the execution of process_source by setting the source to an empty list
tg.source = [] | [
"def",
"apply_run_m_script",
"(",
"tg",
")",
":",
"# Convert sources and targets to nodes ",
"src_node",
"=",
"tg",
".",
"path",
".",
"find_resource",
"(",
"tg",
".",
"source",
")",
"tgt_nodes",
"=",
"[",
"tg",
".",
"path",
".",
"find_or_declare",
"(",
"t",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/build/waf-1.7.13/waflib/extras/run_m_script.py#L66-L89 | ||
google-ar/WebARonTango | e86965d2cbc652156b480e0fcf77c716745578cd | chromium/src/gpu/command_buffer/build_gles2_cmd_buffer.py | python | DataHandler.WriteGetDataSizeCode | (self, func, f) | Overrriden from TypeHandler. | Overrriden from TypeHandler. | [
"Overrriden",
"from",
"TypeHandler",
"."
] | def WriteGetDataSizeCode(self, func, f):
"""Overrriden from TypeHandler."""
# TODO: Move this data to _FUNCTION_INFO?
name = func.name
if name.endswith("Immediate"):
name = name[0:-9]
if name == 'BufferData' or name == 'BufferSubData':
f.write(" uint32_t data_size = size;\n")
elif name == 'TexImage2D' or name == 'TexSubImage2D':
code = """ uint32_t data_size;
if (!GLES2Util::ComputeImageDataSize(
width, height, format, type, unpack_alignment_, &data_size)) {
return error::kOutOfBounds;
}
"""
f.write(code)
else:
f.write(
"// uint32_t data_size = 0; // WARNING: compute correct size.\n") | [
"def",
"WriteGetDataSizeCode",
"(",
"self",
",",
"func",
",",
"f",
")",
":",
"# TODO: Move this data to _FUNCTION_INFO?",
"name",
"=",
"func",
".",
"name",
"if",
"name",
".",
"endswith",
"(",
"\"Immediate\"",
")",
":",
"name",
"=",
"name",
"[",
"0",
":",
"... | https://github.com/google-ar/WebARonTango/blob/e86965d2cbc652156b480e0fcf77c716745578cd/chromium/src/gpu/command_buffer/build_gles2_cmd_buffer.py#L5748-L5766 | ||
moflow/moflow | 2dfb27c799c90c6caf1477508eca3eec616ef7d2 | bap/libtracewrap/libtrace/protobuf/python/google/protobuf/internal/cpp_message.py | python | _AddMessageMethods | (message_descriptor, cls) | Adds the methods to a protocol message class. | Adds the methods to a protocol message class. | [
"Adds",
"the",
"methods",
"to",
"a",
"protocol",
"message",
"class",
"."
] | def _AddMessageMethods(message_descriptor, cls):
"""Adds the methods to a protocol message class."""
if message_descriptor.is_extendable:
def ClearExtension(self, extension):
self.Extensions.ClearExtension(extension)
def HasExtension(self, extension):
return self.Extensions.HasExtension(extension)
def HasField(self, field_name):
return self._cmsg.HasField(field_name)
def ClearField(self, field_name):
child_cmessage = None
if field_name in self._composite_fields:
child_field = self._composite_fields[field_name]
del self._composite_fields[field_name]
child_cdescriptor = self.__descriptors[field_name]
# TODO(anuraag): Support clearing repeated message fields as well.
if (child_cdescriptor.label != _LABEL_REPEATED and
child_cdescriptor.cpp_type == _CPPTYPE_MESSAGE):
child_field._owner = None
child_cmessage = child_field._cmsg
if child_cmessage is not None:
self._cmsg.ClearField(field_name, child_cmessage)
else:
self._cmsg.ClearField(field_name)
def Clear(self):
cmessages_to_release = []
for field_name, child_field in self._composite_fields.iteritems():
child_cdescriptor = self.__descriptors[field_name]
# TODO(anuraag): Support clearing repeated message fields as well.
if (child_cdescriptor.label != _LABEL_REPEATED and
child_cdescriptor.cpp_type == _CPPTYPE_MESSAGE):
child_field._owner = None
cmessages_to_release.append((child_cdescriptor, child_field._cmsg))
self._composite_fields.clear()
self._cmsg.Clear(cmessages_to_release)
def IsInitialized(self, errors=None):
if self._cmsg.IsInitialized():
return True
if errors is not None:
errors.extend(self.FindInitializationErrors());
return False
def SerializeToString(self):
if not self.IsInitialized():
raise message.EncodeError(
'Message %s is missing required fields: %s' % (
self._cmsg.full_name, ','.join(self.FindInitializationErrors())))
return self._cmsg.SerializeToString()
def SerializePartialToString(self):
return self._cmsg.SerializePartialToString()
def ParseFromString(self, serialized):
self.Clear()
self.MergeFromString(serialized)
def MergeFromString(self, serialized):
byte_size = self._cmsg.MergeFromString(serialized)
if byte_size < 0:
raise message.DecodeError('Unable to merge from string.')
return byte_size
def MergeFrom(self, msg):
if not isinstance(msg, cls):
raise TypeError(
"Parameter to MergeFrom() must be instance of same class: "
"expected %s got %s." % (cls.__name__, type(msg).__name__))
self._cmsg.MergeFrom(msg._cmsg)
def CopyFrom(self, msg):
self._cmsg.CopyFrom(msg._cmsg)
def ByteSize(self):
return self._cmsg.ByteSize()
def SetInParent(self):
return self._cmsg.SetInParent()
def ListFields(self):
all_fields = []
field_list = self._cmsg.ListFields()
fields_by_name = cls.DESCRIPTOR.fields_by_name
for is_extension, field_name in field_list:
if is_extension:
extension = cls._extensions_by_name[field_name]
all_fields.append((extension, self.Extensions[extension]))
else:
field_descriptor = fields_by_name[field_name]
all_fields.append(
(field_descriptor, getattr(self, field_name)))
all_fields.sort(key=lambda item: item[0].number)
return all_fields
def FindInitializationErrors(self):
return self._cmsg.FindInitializationErrors()
def __str__(self):
return self._cmsg.DebugString()
def __eq__(self, other):
if self is other:
return True
if not isinstance(other, self.__class__):
return False
return self.ListFields() == other.ListFields()
def __ne__(self, other):
return not self == other
def __hash__(self):
raise TypeError('unhashable object')
def __unicode__(self):
# Lazy import to prevent circular import when text_format imports this file.
from google.protobuf import text_format
return text_format.MessageToString(self, as_utf8=True).decode('utf-8')
# Attach the local methods to the message class.
for key, value in locals().copy().iteritems():
if key not in ('key', 'value', '__builtins__', '__name__', '__doc__'):
setattr(cls, key, value)
# Static methods:
def RegisterExtension(extension_handle):
extension_handle.containing_type = cls.DESCRIPTOR
cls._extensions_by_name[extension_handle.full_name] = extension_handle
if _IsMessageSetExtension(extension_handle):
# MessageSet extension. Also register under type name.
cls._extensions_by_name[
extension_handle.message_type.full_name] = extension_handle
cls.RegisterExtension = staticmethod(RegisterExtension)
def FromString(string):
msg = cls()
msg.MergeFromString(string)
return msg
cls.FromString = staticmethod(FromString) | [
"def",
"_AddMessageMethods",
"(",
"message_descriptor",
",",
"cls",
")",
":",
"if",
"message_descriptor",
".",
"is_extendable",
":",
"def",
"ClearExtension",
"(",
"self",
",",
"extension",
")",
":",
"self",
".",
"Extensions",
".",
"ClearExtension",
"(",
"extensi... | https://github.com/moflow/moflow/blob/2dfb27c799c90c6caf1477508eca3eec616ef7d2/bap/libtracewrap/libtrace/protobuf/python/google/protobuf/internal/cpp_message.py#L508-L654 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/arrays/datetimes.py | python | DatetimeArray.to_pydatetime | (self) | return tslib.ints_to_pydatetime(self.asi8, tz=self.tz) | Return Datetime Array/Index as object ndarray of datetime.datetime
objects.
Returns
-------
datetimes : ndarray | Return Datetime Array/Index as object ndarray of datetime.datetime
objects. | [
"Return",
"Datetime",
"Array",
"/",
"Index",
"as",
"object",
"ndarray",
"of",
"datetime",
".",
"datetime",
"objects",
"."
] | def to_pydatetime(self):
"""
Return Datetime Array/Index as object ndarray of datetime.datetime
objects.
Returns
-------
datetimes : ndarray
"""
return tslib.ints_to_pydatetime(self.asi8, tz=self.tz) | [
"def",
"to_pydatetime",
"(",
"self",
")",
":",
"return",
"tslib",
".",
"ints_to_pydatetime",
"(",
"self",
".",
"asi8",
",",
"tz",
"=",
"self",
".",
"tz",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/arrays/datetimes.py#L995-L1004 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py3/sklearn/preprocessing/_data.py | python | QuantileTransformer.fit | (self, X, y=None) | return self | Compute the quantiles used for transforming.
Parameters
----------
X : ndarray or sparse matrix, shape (n_samples, n_features)
The data used to scale along the features axis. If a sparse
matrix is provided, it will be converted into a sparse
``csc_matrix``. Additionally, the sparse matrix needs to be
nonnegative if `ignore_implicit_zeros` is False.
Returns
-------
self : object | Compute the quantiles used for transforming. | [
"Compute",
"the",
"quantiles",
"used",
"for",
"transforming",
"."
] | def fit(self, X, y=None):
"""Compute the quantiles used for transforming.
Parameters
----------
X : ndarray or sparse matrix, shape (n_samples, n_features)
The data used to scale along the features axis. If a sparse
matrix is provided, it will be converted into a sparse
``csc_matrix``. Additionally, the sparse matrix needs to be
nonnegative if `ignore_implicit_zeros` is False.
Returns
-------
self : object
"""
if self.n_quantiles <= 0:
raise ValueError("Invalid value for 'n_quantiles': %d. "
"The number of quantiles must be at least one."
% self.n_quantiles)
if self.subsample <= 0:
raise ValueError("Invalid value for 'subsample': %d. "
"The number of subsamples must be at least one."
% self.subsample)
if self.n_quantiles > self.subsample:
raise ValueError("The number of quantiles cannot be greater than"
" the number of samples used. Got {} quantiles"
" and {} samples.".format(self.n_quantiles,
self.subsample))
X = self._check_inputs(X, copy=False)
n_samples = X.shape[0]
if self.n_quantiles > n_samples:
warnings.warn("n_quantiles (%s) is greater than the total number "
"of samples (%s). n_quantiles is set to "
"n_samples."
% (self.n_quantiles, n_samples))
self.n_quantiles_ = max(1, min(self.n_quantiles, n_samples))
rng = check_random_state(self.random_state)
# Create the quantiles of reference
self.references_ = np.linspace(0, 1, self.n_quantiles_,
endpoint=True)
if sparse.issparse(X):
self._sparse_fit(X, rng)
else:
self._dense_fit(X, rng)
return self | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
"=",
"None",
")",
":",
"if",
"self",
".",
"n_quantiles",
"<=",
"0",
":",
"raise",
"ValueError",
"(",
"\"Invalid value for 'n_quantiles': %d. \"",
"\"The number of quantiles must be at least one.\"",
"%",
"self",
".",
... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/preprocessing/_data.py#L2319-L2370 | |
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Draft/draftguitools/gui_mirror.py | python | Mirror.GetResources | (self) | return {'Pixmap': 'Draft_Mirror',
'Accel': "M, I",
'MenuText': QT_TRANSLATE_NOOP("Draft_Mirror", "Mirror"),
'ToolTip': QT_TRANSLATE_NOOP("Draft_Mirror", "Mirrors the selected objects along a line defined by two points.")} | Set icon, menu and tooltip. | Set icon, menu and tooltip. | [
"Set",
"icon",
"menu",
"and",
"tooltip",
"."
] | def GetResources(self):
"""Set icon, menu and tooltip."""
return {'Pixmap': 'Draft_Mirror',
'Accel': "M, I",
'MenuText': QT_TRANSLATE_NOOP("Draft_Mirror", "Mirror"),
'ToolTip': QT_TRANSLATE_NOOP("Draft_Mirror", "Mirrors the selected objects along a line defined by two points.")} | [
"def",
"GetResources",
"(",
"self",
")",
":",
"return",
"{",
"'Pixmap'",
":",
"'Draft_Mirror'",
",",
"'Accel'",
":",
"\"M, I\"",
",",
"'MenuText'",
":",
"QT_TRANSLATE_NOOP",
"(",
"\"Draft_Mirror\"",
",",
"\"Mirror\"",
")",
",",
"'ToolTip'",
":",
"QT_TRANSLATE_NO... | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Draft/draftguitools/gui_mirror.py#L58-L64 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/build/waf-1.7.13/lmbrwaflib/project_settings.py | python | get_bootstrap_remote_ip | (self) | return remote_ip | :param self:
:return: remote_ip set in bootstrap.cfg | :param self:
:return: remote_ip set in bootstrap.cfg | [
":",
"param",
"self",
":",
":",
"return",
":",
"remote_ip",
"set",
"in",
"bootstrap",
".",
"cfg"
] | def get_bootstrap_remote_ip(self):
"""
:param self:
:return: remote_ip set in bootstrap.cfg
"""
project_folder_node = getattr(self, 'srcnode', self.path)
bootstrap_cfg = project_folder_node.make_node('bootstrap.cfg')
bootstrap_contents = bootstrap_cfg.read()
remote_ip = '127.0.0.1'
try:
remote_ip = re.search('^\s*remote_ip\s*=\s*((\d+[.]*)*)', bootstrap_contents, re.MULTILINE).group(1)
except:
pass
return remote_ip | [
"def",
"get_bootstrap_remote_ip",
"(",
"self",
")",
":",
"project_folder_node",
"=",
"getattr",
"(",
"self",
",",
"'srcnode'",
",",
"self",
".",
"path",
")",
"bootstrap_cfg",
"=",
"project_folder_node",
".",
"make_node",
"(",
"'bootstrap.cfg'",
")",
"bootstrap_con... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/build/waf-1.7.13/lmbrwaflib/project_settings.py#L657-L670 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/dashboard/dashboard/add_point.py | python | _GetSupplementalColumns | (row) | return columns | Gets a dict of supplemental columns.
If any columns are invalid, a warning is logged and they just aren't included,
but no exception is raised.
Individual rows may specify up to _MAX_NUM_COLUMNS extra data, revision,
and annotation columns. These columns must follow formatting rules for
their type. Invalid columns are dropped with an error log, but the valid
data will still be graphed.
Args:
row: A dict, possibly with the key "supplemental_columns", the value of
which should be a dict.
Returns:
A dict of valid supplemental columns. | Gets a dict of supplemental columns. | [
"Gets",
"a",
"dict",
"of",
"supplemental",
"columns",
"."
] | def _GetSupplementalColumns(row):
"""Gets a dict of supplemental columns.
If any columns are invalid, a warning is logged and they just aren't included,
but no exception is raised.
Individual rows may specify up to _MAX_NUM_COLUMNS extra data, revision,
and annotation columns. These columns must follow formatting rules for
their type. Invalid columns are dropped with an error log, but the valid
data will still be graphed.
Args:
row: A dict, possibly with the key "supplemental_columns", the value of
which should be a dict.
Returns:
A dict of valid supplemental columns.
"""
columns = {}
for (name, value) in row.get('supplemental_columns', {}).iteritems():
# Don't allow too many columns
if len(columns) == _MAX_NUM_COLUMNS:
logging.warn('Too many columns, some being dropped.')
break
value = _CheckSupplementalColumn(name, value)
if value:
columns[name] = value
return columns | [
"def",
"_GetSupplementalColumns",
"(",
"row",
")",
":",
"columns",
"=",
"{",
"}",
"for",
"(",
"name",
",",
"value",
")",
"in",
"row",
".",
"get",
"(",
"'supplemental_columns'",
",",
"{",
"}",
")",
".",
"iteritems",
"(",
")",
":",
"# Don't allow too many ... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/dashboard/dashboard/add_point.py#L751-L778 | |
Constellation/iv | 64c3a9c7c517063f29d90d449180ea8f6f4d946f | tools/cpplint.py | python | _IncludeState.CanonicalizeAlphabeticalOrder | (self, header_path) | return header_path.replace('-inl.h', '.h').replace('-', '_').lower() | Returns a path canonicalized for alphabetical comparison.
- replaces "-" with "_" so they both cmp the same.
- removes '-inl' since we don't require them to be after the main header.
- lowercase everything, just in case.
Args:
header_path: Path to be canonicalized.
Returns:
Canonicalized path. | Returns a path canonicalized for alphabetical comparison. | [
"Returns",
"a",
"path",
"canonicalized",
"for",
"alphabetical",
"comparison",
"."
] | def CanonicalizeAlphabeticalOrder(self, header_path):
"""Returns a path canonicalized for alphabetical comparison.
- replaces "-" with "_" so they both cmp the same.
- removes '-inl' since we don't require them to be after the main header.
- lowercase everything, just in case.
Args:
header_path: Path to be canonicalized.
Returns:
Canonicalized path.
"""
return header_path.replace('-inl.h', '.h').replace('-', '_').lower() | [
"def",
"CanonicalizeAlphabeticalOrder",
"(",
"self",
",",
"header_path",
")",
":",
"return",
"header_path",
".",
"replace",
"(",
"'-inl.h'",
",",
"'.h'",
")",
".",
"replace",
"(",
"'-'",
",",
"'_'",
")",
".",
"lower",
"(",
")"
] | https://github.com/Constellation/iv/blob/64c3a9c7c517063f29d90d449180ea8f6f4d946f/tools/cpplint.py#L585-L598 | |
protocolbuffers/protobuf | b5ab0b7a18b7336c60130f4ddb2d97c51792f896 | python/mox.py | python | IgnoreArg.equals | (self, unused_rhs) | return True | Ignores arguments and returns True.
Args:
unused_rhs: any python object
Returns:
always returns True | Ignores arguments and returns True. | [
"Ignores",
"arguments",
"and",
"returns",
"True",
"."
] | def equals(self, unused_rhs):
"""Ignores arguments and returns True.
Args:
unused_rhs: any python object
Returns:
always returns True
"""
return True | [
"def",
"equals",
"(",
"self",
",",
"unused_rhs",
")",
":",
"return",
"True"
] | https://github.com/protocolbuffers/protobuf/blob/b5ab0b7a18b7336c60130f4ddb2d97c51792f896/python/mox.py#L1166-L1176 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_misc.py | python | ConfigBase.RenameGroup | (*args, **kwargs) | return _misc_.ConfigBase_RenameGroup(*args, **kwargs) | RenameGroup(self, String oldName, String newName) -> bool
Rename a group. Returns False on failure (probably because the new
name is already taken by an existing entry) | RenameGroup(self, String oldName, String newName) -> bool | [
"RenameGroup",
"(",
"self",
"String",
"oldName",
"String",
"newName",
")",
"-",
">",
"bool"
] | def RenameGroup(*args, **kwargs):
"""
RenameGroup(self, String oldName, String newName) -> bool
Rename a group. Returns False on failure (probably because the new
name is already taken by an existing entry)
"""
return _misc_.ConfigBase_RenameGroup(*args, **kwargs) | [
"def",
"RenameGroup",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"ConfigBase_RenameGroup",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_misc.py#L3336-L3343 | |
hpi-xnor/BMXNet | ed0b201da6667887222b8e4b5f997c4f6b61943d | python/mxnet/symbol/symbol.py | python | Symbol.list_auxiliary_states | (self) | return [py_str(sarr[i]) for i in range(size.value)] | Lists all the auxiliary states in the symbol.
Example
-------
>>> a = mx.sym.var('a')
>>> b = mx.sym.var('b')
>>> c = a + b
>>> c.list_auxiliary_states()
[]
Example of auxiliary states in `BatchNorm`.
>>> data = mx.symbol.Variable('data')
>>> weight = mx.sym.Variable(name='fc1_weight')
>>> fc1 = mx.symbol.FullyConnected(data = data, weight=weight, name='fc1', num_hidden=128)
>>> fc2 = mx.symbol.BatchNorm(fc1, name='batchnorm0')
>>> fc2.list_auxiliary_states()
['batchnorm0_moving_mean', 'batchnorm0_moving_var']
Returns
-------
aux_states : list of str
List of the auxiliary states in input symbol.
Notes
-----
Auxiliary states are special states of symbols that do not correspond to an argument,
and are not updated by gradient descent. Common examples of auxiliary states
include the `moving_mean` and `moving_variance` in `BatchNorm`.
Most operators do not have auxiliary states. | Lists all the auxiliary states in the symbol. | [
"Lists",
"all",
"the",
"auxiliary",
"states",
"in",
"the",
"symbol",
"."
] | def list_auxiliary_states(self):
"""Lists all the auxiliary states in the symbol.
Example
-------
>>> a = mx.sym.var('a')
>>> b = mx.sym.var('b')
>>> c = a + b
>>> c.list_auxiliary_states()
[]
Example of auxiliary states in `BatchNorm`.
>>> data = mx.symbol.Variable('data')
>>> weight = mx.sym.Variable(name='fc1_weight')
>>> fc1 = mx.symbol.FullyConnected(data = data, weight=weight, name='fc1', num_hidden=128)
>>> fc2 = mx.symbol.BatchNorm(fc1, name='batchnorm0')
>>> fc2.list_auxiliary_states()
['batchnorm0_moving_mean', 'batchnorm0_moving_var']
Returns
-------
aux_states : list of str
List of the auxiliary states in input symbol.
Notes
-----
Auxiliary states are special states of symbols that do not correspond to an argument,
and are not updated by gradient descent. Common examples of auxiliary states
include the `moving_mean` and `moving_variance` in `BatchNorm`.
Most operators do not have auxiliary states.
"""
size = ctypes.c_uint()
sarr = ctypes.POINTER(ctypes.c_char_p)()
check_call(_LIB.MXSymbolListAuxiliaryStates(
self.handle, ctypes.byref(size), ctypes.byref(sarr)))
return [py_str(sarr[i]) for i in range(size.value)] | [
"def",
"list_auxiliary_states",
"(",
"self",
")",
":",
"size",
"=",
"ctypes",
".",
"c_uint",
"(",
")",
"sarr",
"=",
"ctypes",
".",
"POINTER",
"(",
"ctypes",
".",
"c_char_p",
")",
"(",
")",
"check_call",
"(",
"_LIB",
".",
"MXSymbolListAuxiliaryStates",
"(",... | https://github.com/hpi-xnor/BMXNet/blob/ed0b201da6667887222b8e4b5f997c4f6b61943d/python/mxnet/symbol/symbol.py#L748-L784 | |
yrnkrn/zapcc | c6a8aa30006d997eff0d60fd37b0e62b8aa0ea50 | tools/clang/bindings/python/clang/cindex.py | python | Cursor.exception_specification_kind | (self) | return self._exception_specification_kind | Retrieve the exception specification kind, which is one of the values
from the ExceptionSpecificationKind enumeration. | Retrieve the exception specification kind, which is one of the values
from the ExceptionSpecificationKind enumeration. | [
"Retrieve",
"the",
"exception",
"specification",
"kind",
"which",
"is",
"one",
"of",
"the",
"values",
"from",
"the",
"ExceptionSpecificationKind",
"enumeration",
"."
] | def exception_specification_kind(self):
'''
Retrieve the exception specification kind, which is one of the values
from the ExceptionSpecificationKind enumeration.
'''
if not hasattr(self, '_exception_specification_kind'):
exc_kind = conf.lib.clang_getCursorExceptionSpecificationType(self)
self._exception_specification_kind = ExceptionSpecificationKind.from_id(exc_kind)
return self._exception_specification_kind | [
"def",
"exception_specification_kind",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_exception_specification_kind'",
")",
":",
"exc_kind",
"=",
"conf",
".",
"lib",
".",
"clang_getCursorExceptionSpecificationType",
"(",
"self",
")",
"self",
".... | https://github.com/yrnkrn/zapcc/blob/c6a8aa30006d997eff0d60fd37b0e62b8aa0ea50/tools/clang/bindings/python/clang/cindex.py#L1652-L1661 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py2/scipy/sparse/linalg/_expm_multiply.py | python | LazyOperatorNormInfo.__init__ | (self, A, A_1_norm=None, ell=2, scale=1) | Provide the operator and some norm-related information.
Parameters
----------
A : linear operator
The operator of interest.
A_1_norm : float, optional
The exact 1-norm of A.
ell : int, optional
A technical parameter controlling norm estimation quality.
scale : int, optional
If specified, return the norms of scale*A instead of A. | Provide the operator and some norm-related information. | [
"Provide",
"the",
"operator",
"and",
"some",
"norm",
"-",
"related",
"information",
"."
] | def __init__(self, A, A_1_norm=None, ell=2, scale=1):
"""
Provide the operator and some norm-related information.
Parameters
----------
A : linear operator
The operator of interest.
A_1_norm : float, optional
The exact 1-norm of A.
ell : int, optional
A technical parameter controlling norm estimation quality.
scale : int, optional
If specified, return the norms of scale*A instead of A.
"""
self._A = A
self._A_1_norm = A_1_norm
self._ell = ell
self._d = {}
self._scale = scale | [
"def",
"__init__",
"(",
"self",
",",
"A",
",",
"A_1_norm",
"=",
"None",
",",
"ell",
"=",
"2",
",",
"scale",
"=",
"1",
")",
":",
"self",
".",
"_A",
"=",
"A",
"self",
".",
"_A_1_norm",
"=",
"A_1_norm",
"self",
".",
"_ell",
"=",
"ell",
"self",
"."... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/sparse/linalg/_expm_multiply.py#L316-L336 | ||
msracver/Deep-Image-Analogy | 632b9287b42552e32dad64922967c8c9ec7fc4d3 | python/caffe/io.py | python | Transformer.set_raw_scale | (self, in_, scale) | Set the scale of raw features s.t. the input blob = input * scale.
While Python represents images in [0, 1], certain Caffe models
like CaffeNet and AlexNet represent images in [0, 255] so the raw_scale
of these models must be 255.
Parameters
----------
in_ : which input to assign this scale factor
scale : scale coefficient | Set the scale of raw features s.t. the input blob = input * scale.
While Python represents images in [0, 1], certain Caffe models
like CaffeNet and AlexNet represent images in [0, 255] so the raw_scale
of these models must be 255. | [
"Set",
"the",
"scale",
"of",
"raw",
"features",
"s",
".",
"t",
".",
"the",
"input",
"blob",
"=",
"input",
"*",
"scale",
".",
"While",
"Python",
"represents",
"images",
"in",
"[",
"0",
"1",
"]",
"certain",
"Caffe",
"models",
"like",
"CaffeNet",
"and",
... | def set_raw_scale(self, in_, scale):
"""
Set the scale of raw features s.t. the input blob = input * scale.
While Python represents images in [0, 1], certain Caffe models
like CaffeNet and AlexNet represent images in [0, 255] so the raw_scale
of these models must be 255.
Parameters
----------
in_ : which input to assign this scale factor
scale : scale coefficient
"""
self.__check_input(in_)
self.raw_scale[in_] = scale | [
"def",
"set_raw_scale",
"(",
"self",
",",
"in_",
",",
"scale",
")",
":",
"self",
".",
"__check_input",
"(",
"in_",
")",
"self",
".",
"raw_scale",
"[",
"in_",
"]",
"=",
"scale"
] | https://github.com/msracver/Deep-Image-Analogy/blob/632b9287b42552e32dad64922967c8c9ec7fc4d3/python/caffe/io.py#L221-L234 | ||
scribusproject/scribus | 41ec7c775a060912cf251682a8b1437f753f80f4 | scribus/plugins/scriptplugin_py2x/scripts/color2csv.py | python | main_wrapper | (argv) | The main_wrapper() function disables redrawing, sets a sensible generic
status bar message, and optionally sets up the progress bar. It then runs
the main() function. Once everything finishes it cleans up after the main()
function, making sure everything is sane before the script terminates. | The main_wrapper() function disables redrawing, sets a sensible generic
status bar message, and optionally sets up the progress bar. It then runs
the main() function. Once everything finishes it cleans up after the main()
function, making sure everything is sane before the script terminates. | [
"The",
"main_wrapper",
"()",
"function",
"disables",
"redrawing",
"sets",
"a",
"sensible",
"generic",
"status",
"bar",
"message",
"and",
"optionally",
"sets",
"up",
"the",
"progress",
"bar",
".",
"It",
"then",
"runs",
"the",
"main",
"()",
"function",
".",
"O... | def main_wrapper(argv):
"""The main_wrapper() function disables redrawing, sets a sensible generic
status bar message, and optionally sets up the progress bar. It then runs
the main() function. Once everything finishes it cleans up after the main()
function, making sure everything is sane before the script terminates."""
try:
#scribus.statusMessage("Running script...")
#scribus.progressReset()
main(argv)
finally:
# Exit neatly even if the script terminated with an exception,
# so we leave the progress bar and status bar blank and make sure
# drawing is enabled.
if scribus.haveDoc():
scribus.setRedraw(True)
scribus.statusMessage("")
scribus.progressReset() | [
"def",
"main_wrapper",
"(",
"argv",
")",
":",
"try",
":",
"#scribus.statusMessage(\"Running script...\")",
"#scribus.progressReset()",
"main",
"(",
"argv",
")",
"finally",
":",
"# Exit neatly even if the script terminated with an exception,",
"# so we leave the progress bar and sta... | https://github.com/scribusproject/scribus/blob/41ec7c775a060912cf251682a8b1437f753f80f4/scribus/plugins/scriptplugin_py2x/scripts/color2csv.py#L138-L154 | ||
geemaple/leetcode | 68bc5032e1ee52c22ef2f2e608053484c487af54 | leetcode/407.trapping-rain-water-ii.py | python | Solution.trapRainWater | (self, heightMap) | return result | :type heightMap: List[List[int]]
:rtype: int | :type heightMap: List[List[int]]
:rtype: int | [
":",
"type",
"heightMap",
":",
"List",
"[",
"List",
"[",
"int",
"]]",
":",
"rtype",
":",
"int"
] | def trapRainWater(self, heightMap):
"""
:type heightMap: List[List[int]]
:rtype: int
"""
if heightMap is None or len(heightMap) < 3 or len(heightMap[0]) < 3:
return 0
row = len(heightMap)
col = len(heightMap[0])
self.initialize(heightMap, row, col)
result = 0
while len(self.borders) > 0:
border_height, x, y = heapq.heappop(self.borders)
for d in self.directions:
new_x = x + d[0]
new_y = y + d[1]
if (self.in_boundary(new_x, new_y, heightMap) and (new_x, new_y) not in self.visited):
new_height = heightMap[new_x][new_y]
result += max(0, border_height - new_height)
self.add(max(new_height, border_height), new_x, new_y, col)
return result | [
"def",
"trapRainWater",
"(",
"self",
",",
"heightMap",
")",
":",
"if",
"heightMap",
"is",
"None",
"or",
"len",
"(",
"heightMap",
")",
"<",
"3",
"or",
"len",
"(",
"heightMap",
"[",
"0",
"]",
")",
"<",
"3",
":",
"return",
"0",
"row",
"=",
"len",
"(... | https://github.com/geemaple/leetcode/blob/68bc5032e1ee52c22ef2f2e608053484c487af54/leetcode/407.trapping-rain-water-ii.py#L10-L34 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/closure_linter/closure_linter/statetracker.py | python | DocComment.ordered_params | (self) | return params | Gives the list of parameter names as a list of strings. | Gives the list of parameter names as a list of strings. | [
"Gives",
"the",
"list",
"of",
"parameter",
"names",
"as",
"a",
"list",
"of",
"strings",
"."
] | def ordered_params(self):
"""Gives the list of parameter names as a list of strings."""
params = []
for flag in self.__flags:
if flag.flag_type == 'param' and flag.name:
params.append(flag.name)
return params | [
"def",
"ordered_params",
"(",
"self",
")",
":",
"params",
"=",
"[",
"]",
"for",
"flag",
"in",
"self",
".",
"__flags",
":",
"if",
"flag",
".",
"flag_type",
"==",
"'param'",
"and",
"flag",
".",
"name",
":",
"params",
".",
"append",
"(",
"flag",
".",
... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/closure_linter/closure_linter/statetracker.py#L329-L335 | |
arangodb/arangodb | 0d658689c7d1b721b314fa3ca27d38303e1570c8 | 3rdParty/V8/gyp/buildtime_helpers/mac_tool.py | python | MacTool._GetSubstitutions | (self, bundle_identifier, app_identifier_prefix) | return {
'CFBundleIdentifier': bundle_identifier,
'AppIdentifierPrefix': app_identifier_prefix,
} | Constructs a dictionary of variable substitutions for Entitlements.plist.
Args:
bundle_identifier: string, value of CFBundleIdentifier from Info.plist
app_identifier_prefix: string, value for AppIdentifierPrefix
Returns:
Dictionary of substitutions to apply when generating Entitlements.plist. | Constructs a dictionary of variable substitutions for Entitlements.plist. | [
"Constructs",
"a",
"dictionary",
"of",
"variable",
"substitutions",
"for",
"Entitlements",
".",
"plist",
"."
] | def _GetSubstitutions(self, bundle_identifier, app_identifier_prefix):
"""Constructs a dictionary of variable substitutions for Entitlements.plist.
Args:
bundle_identifier: string, value of CFBundleIdentifier from Info.plist
app_identifier_prefix: string, value for AppIdentifierPrefix
Returns:
Dictionary of substitutions to apply when generating Entitlements.plist.
"""
return {
'CFBundleIdentifier': bundle_identifier,
'AppIdentifierPrefix': app_identifier_prefix,
} | [
"def",
"_GetSubstitutions",
"(",
"self",
",",
"bundle_identifier",
",",
"app_identifier_prefix",
")",
":",
"return",
"{",
"'CFBundleIdentifier'",
":",
"bundle_identifier",
",",
"'AppIdentifierPrefix'",
":",
"app_identifier_prefix",
",",
"}"
] | https://github.com/arangodb/arangodb/blob/0d658689c7d1b721b314fa3ca27d38303e1570c8/3rdParty/V8/gyp/buildtime_helpers/mac_tool.py#L569-L582 | |
PixarAnimationStudios/USD | faed18ce62c8736b02413635b584a2f637156bad | pxr/usdImaging/usdviewq/selectionDataModel.py | python | Blocker.__exit__ | (self, *args) | Exit the 'blocked' state. | Exit the 'blocked' state. | [
"Exit",
"the",
"blocked",
"state",
"."
] | def __exit__(self, *args):
"""Exit the 'blocked' state."""
self._count -= 1
if not self.blocked():
self._exitCallback() | [
"def",
"__exit__",
"(",
"self",
",",
"*",
"args",
")",
":",
"self",
".",
"_count",
"-=",
"1",
"if",
"not",
"self",
".",
"blocked",
"(",
")",
":",
"self",
".",
"_exitCallback",
"(",
")"
] | https://github.com/PixarAnimationStudios/USD/blob/faed18ce62c8736b02413635b584a2f637156bad/pxr/usdImaging/usdviewq/selectionDataModel.py#L59-L65 | ||
kamyu104/LeetCode-Solutions | 77605708a927ea3b85aee5a479db733938c7c211 | Python/lfu-cache.py | python | LFUCache2.put | (self, key, value) | :type key: int
:type value: int
:rtype: void | :type key: int
:type value: int
:rtype: void | [
":",
"type",
"key",
":",
"int",
":",
"type",
"value",
":",
"int",
":",
"rtype",
":",
"void"
] | def put(self, key, value):
"""
:type key: int
:type value: int
:rtype: void
"""
if self.__capa <= 0:
return
if key not in self.__key_to_node and self.__size == self.__capa:
del self.__key_to_node[self.__freq_to_nodes[self.__min_freq].head.key]
self.__freq_to_nodes[self.__min_freq].delete(self.__freq_to_nodes[self.__min_freq].head)
if not self.__freq_to_nodes[self.__min_freq].head:
del self.__freq_to_nodes[self.__min_freq]
self.__size -= 1
self.__update(key, value) | [
"def",
"put",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"if",
"self",
".",
"__capa",
"<=",
"0",
":",
"return",
"if",
"key",
"not",
"in",
"self",
".",
"__key_to_node",
"and",
"self",
".",
"__size",
"==",
"self",
".",
"__capa",
":",
"del",
"... | https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/lfu-cache.py#L128-L143 | ||
neoml-lib/neoml | a0d370fba05269a1b2258cef126f77bbd2054a3e | NeoML/Python/neoml/DifferentialEvolution.py | python | DifferentialEvolution.population | (self) | return self.internal.get_population() | Gets the resulting population.
:return: the population on the current step.
:rtype: *array-like of shape {population, vector_length}* | Gets the resulting population. | [
"Gets",
"the",
"resulting",
"population",
"."
] | def population(self):
"""Gets the resulting population.
:return: the population on the current step.
:rtype: *array-like of shape {population, vector_length}*
"""
return self.internal.get_population() | [
"def",
"population",
"(",
"self",
")",
":",
"return",
"self",
".",
"internal",
".",
"get_population",
"(",
")"
] | https://github.com/neoml-lib/neoml/blob/a0d370fba05269a1b2258cef126f77bbd2054a3e/NeoML/Python/neoml/DifferentialEvolution.py#L295-L301 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/platform.py | python | win32_ver | (release='',version='',csd='',ptype='') | return release,version,csd,ptype | Get additional version information from the Windows Registry
and return a tuple (version,csd,ptype) referring to version
number, CSD level (service pack), and OS type (multi/single
processor).
As a hint: ptype returns 'Uniprocessor Free' on single
processor NT machines and 'Multiprocessor Free' on multi
processor machines. The 'Free' refers to the OS version being
free of debugging code. It could also state 'Checked' which
means the OS version uses debugging code, i.e. code that
checks arguments, ranges, etc. (Thomas Heller).
Note: this function works best with Mark Hammond's win32
package installed, but also on Python 2.3 and later. It
obviously only runs on Win32 compatible platforms. | Get additional version information from the Windows Registry
and return a tuple (version,csd,ptype) referring to version
number, CSD level (service pack), and OS type (multi/single
processor). | [
"Get",
"additional",
"version",
"information",
"from",
"the",
"Windows",
"Registry",
"and",
"return",
"a",
"tuple",
"(",
"version",
"csd",
"ptype",
")",
"referring",
"to",
"version",
"number",
"CSD",
"level",
"(",
"service",
"pack",
")",
"and",
"OS",
"type",... | def win32_ver(release='',version='',csd='',ptype=''):
""" Get additional version information from the Windows Registry
and return a tuple (version,csd,ptype) referring to version
number, CSD level (service pack), and OS type (multi/single
processor).
As a hint: ptype returns 'Uniprocessor Free' on single
processor NT machines and 'Multiprocessor Free' on multi
processor machines. The 'Free' refers to the OS version being
free of debugging code. It could also state 'Checked' which
means the OS version uses debugging code, i.e. code that
checks arguments, ranges, etc. (Thomas Heller).
Note: this function works best with Mark Hammond's win32
package installed, but also on Python 2.3 and later. It
obviously only runs on Win32 compatible platforms.
"""
# XXX Is there any way to find out the processor type on WinXX ?
# XXX Is win32 available on Windows CE ?
#
# Adapted from code posted by Karl Putland to comp.lang.python.
#
# The mappings between reg. values and release names can be found
# here: http://msdn.microsoft.com/library/en-us/sysinfo/base/osversioninfo_str.asp
# Import the needed APIs
try:
import win32api
from win32api import RegQueryValueEx, RegOpenKeyEx, \
RegCloseKey, GetVersionEx
from win32con import HKEY_LOCAL_MACHINE, VER_PLATFORM_WIN32_NT, \
VER_PLATFORM_WIN32_WINDOWS, VER_NT_WORKSTATION
except ImportError:
# Emulate the win32api module using Python APIs
try:
sys.getwindowsversion
except AttributeError:
# No emulation possible, so return the defaults...
return release,version,csd,ptype
else:
# Emulation using _winreg (added in Python 2.0) and
# sys.getwindowsversion() (added in Python 2.3)
import _winreg
GetVersionEx = sys.getwindowsversion
RegQueryValueEx = _winreg.QueryValueEx
RegOpenKeyEx = _winreg.OpenKeyEx
RegCloseKey = _winreg.CloseKey
HKEY_LOCAL_MACHINE = _winreg.HKEY_LOCAL_MACHINE
VER_PLATFORM_WIN32_WINDOWS = 1
VER_PLATFORM_WIN32_NT = 2
VER_NT_WORKSTATION = 1
VER_NT_SERVER = 3
REG_SZ = 1
# Find out the registry key and some general version infos
winver = GetVersionEx()
maj,min,buildno,plat,csd = winver
version = '%i.%i.%i' % (maj,min,buildno & 0xFFFF)
if hasattr(winver, "service_pack"):
if winver.service_pack != "":
csd = 'SP%s' % winver.service_pack_major
else:
if csd[:13] == 'Service Pack ':
csd = 'SP' + csd[13:]
if plat == VER_PLATFORM_WIN32_WINDOWS:
regkey = 'SOFTWARE\\Microsoft\\Windows\\CurrentVersion'
# Try to guess the release name
if maj == 4:
if min == 0:
release = '95'
elif min == 10:
release = '98'
elif min == 90:
release = 'Me'
else:
release = 'postMe'
elif maj == 5:
release = '2000'
elif plat == VER_PLATFORM_WIN32_NT:
regkey = 'SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion'
if maj <= 4:
release = 'NT'
elif maj == 5:
if min == 0:
release = '2000'
elif min == 1:
release = 'XP'
elif min == 2:
release = '2003Server'
else:
release = 'post2003'
elif maj == 6:
if hasattr(winver, "product_type"):
product_type = winver.product_type
else:
product_type = VER_NT_WORKSTATION
# Without an OSVERSIONINFOEX capable sys.getwindowsversion(),
# or help from the registry, we cannot properly identify
# non-workstation versions.
try:
key = RegOpenKeyEx(HKEY_LOCAL_MACHINE, regkey)
name, type = RegQueryValueEx(key, "ProductName")
# Discard any type that isn't REG_SZ
if type == REG_SZ and name.find("Server") != -1:
product_type = VER_NT_SERVER
except WindowsError:
# Use default of VER_NT_WORKSTATION
pass
if min == 0:
if product_type == VER_NT_WORKSTATION:
release = 'Vista'
else:
release = '2008Server'
elif min == 1:
if product_type == VER_NT_WORKSTATION:
release = '7'
else:
release = '2008ServerR2'
elif min == 2:
if product_type == VER_NT_WORKSTATION:
release = '8'
else:
release = '2012Server'
else:
release = 'post2012Server'
else:
if not release:
# E.g. Win3.1 with win32s
release = '%i.%i' % (maj,min)
return release,version,csd,ptype
# Open the registry key
try:
keyCurVer = RegOpenKeyEx(HKEY_LOCAL_MACHINE, regkey)
# Get a value to make sure the key exists...
RegQueryValueEx(keyCurVer, 'SystemRoot')
except:
return release,version,csd,ptype
# Parse values
#subversion = _win32_getvalue(keyCurVer,
# 'SubVersionNumber',
# ('',1))[0]
#if subversion:
# release = release + subversion # 95a, 95b, etc.
build = _win32_getvalue(keyCurVer,
'CurrentBuildNumber',
('',1))[0]
ptype = _win32_getvalue(keyCurVer,
'CurrentType',
(ptype,1))[0]
# Normalize version
version = _norm_version(version,build)
# Close key
RegCloseKey(keyCurVer)
return release,version,csd,ptype | [
"def",
"win32_ver",
"(",
"release",
"=",
"''",
",",
"version",
"=",
"''",
",",
"csd",
"=",
"''",
",",
"ptype",
"=",
"''",
")",
":",
"# XXX Is there any way to find out the processor type on WinXX ?",
"# XXX Is win32 available on Windows CE ?",
"#",
"# Adapted from code ... | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/platform.py#L553-L716 | |
microsoft/CNTK | e9396480025b9ca457d26b6f33dd07c474c6aa04 | bindings/python/cntk/ops/functions.py | python | Function.__getattr__ | (self, name) | return getattr(outputs[0], name) | Access a member inside this object.
Members of ``Function`` can be accessed directly.
In addition, members of the Function's output, if only one, are accessed here.
Lastly, this also gives access to Functions and Variables inside this Function's
graph by their user-specified name, e.g. ``model.embed.E``, as long as those names are not also
member names of Function or Variable. | Access a member inside this object.
Members of ``Function`` can be accessed directly.
In addition, members of the Function's output, if only one, are accessed here.
Lastly, this also gives access to Functions and Variables inside this Function's
graph by their user-specified name, e.g. ``model.embed.E``, as long as those names are not also
member names of Function or Variable. | [
"Access",
"a",
"member",
"inside",
"this",
"object",
".",
"Members",
"of",
"Function",
"can",
"be",
"accessed",
"directly",
".",
"In",
"addition",
"members",
"of",
"the",
"Function",
"s",
"output",
"if",
"only",
"one",
"are",
"accessed",
"here",
".",
"Last... | def __getattr__(self, name):
'''
Access a member inside this object.
Members of ``Function`` can be accessed directly.
In addition, members of the Function's output, if only one, are accessed here.
Lastly, this also gives access to Functions and Variables inside this Function's
graph by their user-specified name, e.g. ``model.embed.E``, as long as those names are not also
member names of Function or Variable.
'''
# If name is not a member of Function or Variable, first look for
# a user-named item in the graph.
# (Known member names cannot be overridden by user-named items,
# to ensure that the API functions.)
if not hasattr(Variable, name) and not hasattr(Function, name) \
and not name.startswith('_') and name not in ['outputs', 'output', 'this']:
# lookup of a named object inside the graph
# When 'self' is a BlockFunction (e.g. a named layer), then we only search in there,
# while when 'self' is a regular node (e.g. a named output using Label),
# we search the composite, which may return multiple hits with the same name.
# In case of multiple matches, we fail.
# BUGBUG: That is a problem if, e.g., someone used a layer (=BlockFunction) twice
# and then looks it up by name, as that will fail although both instances are identical.
from cntk.logging.graph import find_by_name
root = self.block_root if self.is_block else self
item = typemap(find_by_name)(root, name, depth=1)
if item:
return item
# If something is not found in Function, look it up in its output
# variable, if it has only one.
if name.startswith('_') or name in ['outputs', 'output', 'this']:
# These should not be looked up in self's output.
# 'outputs' and 'output' are required to fetch the attribute for
# in the Variable.
# 'this' is required for Swig and needs to be thrown if the
# object is created the first time.
raise AttributeError("neither Function nor its output variable"
" has '%s'"%name)
# access an API member of 'output', such as .shape()
outputs = self.__getattribute__('outputs')
if len(outputs) != 1:
raise AttributeError("Function does not have '%s' and it cannot "
"be looked up in its outputs because it does not have "
"exactly one"%name)
return getattr(outputs[0], name) | [
"def",
"__getattr__",
"(",
"self",
",",
"name",
")",
":",
"# If name is not a member of Function or Variable, first look for",
"# a user-named item in the graph.",
"# (Known member names cannot be overridden by user-named items,",
"# to ensure that the API functions.)",
"if",
"not",
"has... | https://github.com/microsoft/CNTK/blob/e9396480025b9ca457d26b6f33dd07c474c6aa04/bindings/python/cntk/ops/functions.py#L478-L524 | |
kushview/Element | 1cc16380caa2ab79461246ba758b9de1f46db2a5 | waflib/extras/ticgt.py | python | c_hook | (self, node) | Bind the c file extension to the creation of a :py:class:`waflib.Tools.c.c` instance | Bind the c file extension to the creation of a :py:class:`waflib.Tools.c.c` instance | [
"Bind",
"the",
"c",
"file",
"extension",
"to",
"the",
"creation",
"of",
"a",
":",
"py",
":",
"class",
":",
"waflib",
".",
"Tools",
".",
"c",
".",
"c",
"instance"
] | def c_hook(self, node):
"Bind the c file extension to the creation of a :py:class:`waflib.Tools.c.c` instance"
if self.env.CC_NAME == 'ticc':
return create_compiled_task(self, 'ti_c', node)
else:
return self.create_compiled_task('c', node) | [
"def",
"c_hook",
"(",
"self",
",",
"node",
")",
":",
"if",
"self",
".",
"env",
".",
"CC_NAME",
"==",
"'ticc'",
":",
"return",
"create_compiled_task",
"(",
"self",
",",
"'ti_c'",
",",
"node",
")",
"else",
":",
"return",
"self",
".",
"create_compiled_task"... | https://github.com/kushview/Element/blob/1cc16380caa2ab79461246ba758b9de1f46db2a5/waflib/extras/ticgt.py#L218-L223 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/fastparquet/writer.py | python | find_max_part | (row_groups) | Find the highest integer matching "**part.*.parquet" in referenced paths. | Find the highest integer matching "**part.*.parquet" in referenced paths. | [
"Find",
"the",
"highest",
"integer",
"matching",
"**",
"part",
".",
"*",
".",
"parquet",
"in",
"referenced",
"paths",
"."
] | def find_max_part(row_groups):
"""
Find the highest integer matching "**part.*.parquet" in referenced paths.
"""
paths = [c.file_path or "" for rg in row_groups for c in rg.columns]
s = re.compile(r'.*part.(?P<i>[\d]+).parquet$')
matches = [s.match(path) for path in paths]
nums = [int(match.groupdict()['i']) for match in matches if match]
if nums:
return max(nums) + 1
else:
return 0 | [
"def",
"find_max_part",
"(",
"row_groups",
")",
":",
"paths",
"=",
"[",
"c",
".",
"file_path",
"or",
"\"\"",
"for",
"rg",
"in",
"row_groups",
"for",
"c",
"in",
"rg",
".",
"columns",
"]",
"s",
"=",
"re",
".",
"compile",
"(",
"r'.*part.(?P<i>[\\d]+).parque... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/fastparquet/writer.py#L924-L935 | ||
CoolProp/CoolProp | 381c8535e5dec3eec27ad430ebbfff8bc9dfc008 | dev/scripts/ECS_fitter.py | python | viscosity_dilute | (fluid, T, e_k, sigma) | return eta_star | T in [K], e_K in [K], sigma in [nm]
viscosity returned is in [Pa-s] | T in [K], e_K in [K], sigma in [nm]
viscosity returned is in [Pa-s] | [
"T",
"in",
"[",
"K",
"]",
"e_K",
"in",
"[",
"K",
"]",
"sigma",
"in",
"[",
"nm",
"]",
"viscosity",
"returned",
"is",
"in",
"[",
"Pa",
"-",
"s",
"]"
] | def viscosity_dilute(fluid, T, e_k, sigma):
"""
T in [K], e_K in [K], sigma in [nm]
viscosity returned is in [Pa-s]
"""
Tstar = T / e_k
molemass = CoolProp.CoolProp.PropsSI(fluid, 'molemass') * 1000
# From Neufeld, 1972, Journal of Chemical Physics - checked coefficients
OMEGA_2_2 = 1.16145 * pow(Tstar, -0.14874) + 0.52487 * exp(-0.77320 * Tstar) + 2.16178 * exp(-2.43787 * Tstar)
# Using the leading constant from McLinden, 2000 since the leading term from Huber 2003 gives crazy values
eta_star = 26.692e-3 * sqrt(molemass * T) / (pow(sigma, 2) * OMEGA_2_2) / 1e6
return eta_star | [
"def",
"viscosity_dilute",
"(",
"fluid",
",",
"T",
",",
"e_k",
",",
"sigma",
")",
":",
"Tstar",
"=",
"T",
"/",
"e_k",
"molemass",
"=",
"CoolProp",
".",
"CoolProp",
".",
"PropsSI",
"(",
"fluid",
",",
"'molemass'",
")",
"*",
"1000",
"# From Neufeld, 1972, ... | https://github.com/CoolProp/CoolProp/blob/381c8535e5dec3eec27ad430ebbfff8bc9dfc008/dev/scripts/ECS_fitter.py#L11-L23 | |
lmb-freiburg/flownet2 | b92e198b56b0e52e1ba0a5a98dc0e39fa5ae70cc | scripts/cpp_lint.py | python | FileInfo.IsSource | (self) | return self.Extension()[1:] in ('c', 'cc', 'cpp', 'cxx') | File has a source file extension. | File has a source file extension. | [
"File",
"has",
"a",
"source",
"file",
"extension",
"."
] | def IsSource(self):
"""File has a source file extension."""
return self.Extension()[1:] in ('c', 'cc', 'cpp', 'cxx') | [
"def",
"IsSource",
"(",
"self",
")",
":",
"return",
"self",
".",
"Extension",
"(",
")",
"[",
"1",
":",
"]",
"in",
"(",
"'c'",
",",
"'cc'",
",",
"'cpp'",
",",
"'cxx'",
")"
] | https://github.com/lmb-freiburg/flownet2/blob/b92e198b56b0e52e1ba0a5a98dc0e39fa5ae70cc/scripts/cpp_lint.py#L956-L958 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/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/osx_carbon/richtext.py#L2076-L2078 | |
shedskin/shedskin | ae88dbca7b1d9671cd8be448cb0b497122758936 | examples/mm/code.py | python | Code.compare | (self,code) | return Code(resultPegs) | Black pegs first: correct colour in correct position | Black pegs first: correct colour in correct position | [
"Black",
"pegs",
"first",
":",
"correct",
"colour",
"in",
"correct",
"position"
] | def compare(self,code):
resultPegs = []
secretUsed = []
guessUsed = []
count = 0
codeLength = len(self.__pegList)
for i in range(codeLength):
secretUsed.append(False)
guessUsed.append(False)
"""
Black pegs first: correct colour in correct position
"""
for i in range(codeLength):
if (self.__pegList[i].equals(code.getPegs()[i])):
secretUsed[i] = True
guessUsed[i] = True
resultPegs.append(peg.Peg(colour.Colours.black))
count += 1
"""
White pegs: trickier
White pegs are for pegs of the correct colour, but in the wrong
place. Each peg should only be evaluated once, hence the "used"
lists.
Condition below is a shortcut- if there were 3 blacks pegs
then the remaining peg can't be a correct colour (think about it)
"""
if (count < codeLength-1):
for i in range(codeLength):
if (guessUsed[i]):
continue
for j in range(codeLength):
if (i != j and not secretUsed[j] \
and not guessUsed[i] \
and self.__pegList[j].equals(code.getPegs()[i])):
resultPegs.append(peg.Peg(colour.Colours.white))
secretUsed[j] = True
guessUsed[i] = True
return Code(resultPegs) | [
"def",
"compare",
"(",
"self",
",",
"code",
")",
":",
"resultPegs",
"=",
"[",
"]",
"secretUsed",
"=",
"[",
"]",
"guessUsed",
"=",
"[",
"]",
"count",
"=",
"0",
"codeLength",
"=",
"len",
"(",
"self",
".",
"__pegList",
")",
"for",
"i",
"in",
"range",
... | https://github.com/shedskin/shedskin/blob/ae88dbca7b1d9671cd8be448cb0b497122758936/examples/mm/code.py#L40-L84 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/idlelib/HyperParser.py | python | HyperParser.__init__ | (self, editwin, index) | To initialize, analyze the surroundings of the given index. | To initialize, analyze the surroundings of the given index. | [
"To",
"initialize",
"analyze",
"the",
"surroundings",
"of",
"the",
"given",
"index",
"."
] | def __init__(self, editwin, index):
"To initialize, analyze the surroundings of the given index."
self.editwin = editwin
self.text = text = editwin.text
parser = PyParse.Parser(editwin.indentwidth, editwin.tabwidth)
def index2line(index):
return int(float(index))
lno = index2line(text.index(index))
if not editwin.context_use_ps1:
for context in editwin.num_context_lines:
startat = max(lno - context, 1)
startatindex = repr(startat) + ".0"
stopatindex = "%d.end" % lno
# We add the newline because PyParse requires a newline
# at end. We add a space so that index won't be at end
# of line, so that its status will be the same as the
# char before it, if should.
parser.set_str(text.get(startatindex, stopatindex)+' \n')
bod = parser.find_good_parse_start(
editwin._build_char_in_string_func(startatindex))
if bod is not None or startat == 1:
break
parser.set_lo(bod or 0)
else:
r = text.tag_prevrange("console", index)
if r:
startatindex = r[1]
else:
startatindex = "1.0"
stopatindex = "%d.end" % lno
# We add the newline because PyParse requires it. We add a
# space so that index won't be at end of line, so that its
# status will be the same as the char before it, if should.
parser.set_str(text.get(startatindex, stopatindex)+' \n')
parser.set_lo(0)
# We want what the parser has, minus the last newline and space.
self.rawtext = parser.str[:-2]
# Parser.str apparently preserves the statement we are in, so
# that stopatindex can be used to synchronize the string with
# the text box indices.
self.stopatindex = stopatindex
self.bracketing = parser.get_last_stmt_bracketing()
# find which pairs of bracketing are openers. These always
# correspond to a character of rawtext.
self.isopener = [i>0 and self.bracketing[i][1] >
self.bracketing[i-1][1]
for i in range(len(self.bracketing))]
self.set_index(index) | [
"def",
"__init__",
"(",
"self",
",",
"editwin",
",",
"index",
")",
":",
"self",
".",
"editwin",
"=",
"editwin",
"self",
".",
"text",
"=",
"text",
"=",
"editwin",
".",
"text",
"parser",
"=",
"PyParse",
".",
"Parser",
"(",
"editwin",
".",
"indentwidth",
... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/idlelib/HyperParser.py#L14-L67 | ||
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | third_party/closure_linter/closure_linter/javascriptlintrules.py | python | JavaScriptLintRules.GetLongLineExceptions | (self) | return [
re.compile('goog\.require\(.+\);?\s*$'),
re.compile('goog\.provide\(.+\);?\s*$')
] | Gets a list of regexps for lines which can be longer than the limit. | Gets a list of regexps for lines which can be longer than the limit. | [
"Gets",
"a",
"list",
"of",
"regexps",
"for",
"lines",
"which",
"can",
"be",
"longer",
"than",
"the",
"limit",
"."
] | def GetLongLineExceptions(self):
"""Gets a list of regexps for lines which can be longer than the limit."""
return [
re.compile('goog\.require\(.+\);?\s*$'),
re.compile('goog\.provide\(.+\);?\s*$')
] | [
"def",
"GetLongLineExceptions",
"(",
"self",
")",
":",
"return",
"[",
"re",
".",
"compile",
"(",
"'goog\\.require\\(.+\\);?\\s*$'",
")",
",",
"re",
".",
"compile",
"(",
"'goog\\.provide\\(.+\\);?\\s*$'",
")",
"]"
] | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/third_party/closure_linter/closure_linter/javascriptlintrules.py#L533-L538 | |
scylladb/seastar | 0cdd2329beb1cc4c0af8828598c26114397ffa9c | scripts/perftune.py | python | DiskPerfTuner.__get_io_scheduler | (self, dev_node) | return next((scheduler for scheduler in self.__io_schedulers if scheduler in supported_schedulers), None) | Return a supported scheduler that is also present in the required schedulers list (__io_schedulers).
If there isn't such a supported scheduler - return None. | Return a supported scheduler that is also present in the required schedulers list (__io_schedulers). | [
"Return",
"a",
"supported",
"scheduler",
"that",
"is",
"also",
"present",
"in",
"the",
"required",
"schedulers",
"list",
"(",
"__io_schedulers",
")",
"."
] | def __get_io_scheduler(self, dev_node):
"""
Return a supported scheduler that is also present in the required schedulers list (__io_schedulers).
If there isn't such a supported scheduler - return None.
"""
feature_file, feature_node = self.__get_feature_file(dev_node, lambda p : os.path.join(p, 'queue', 'scheduler'))
lines = readlines(feature_file)
if not lines:
return None
# Supported schedulers appear in the config file as a single line as follows:
#
# sched1 [sched2] sched3
#
# ...with one or more schedulers where currently selected scheduler is the one in brackets.
#
# Return the scheduler with the highest priority among those that are supported for the current device.
supported_schedulers = frozenset([scheduler.lstrip("[").rstrip("]").rstrip("\n") for scheduler in lines[0].split(" ")])
return next((scheduler for scheduler in self.__io_schedulers if scheduler in supported_schedulers), None) | [
"def",
"__get_io_scheduler",
"(",
"self",
",",
"dev_node",
")",
":",
"feature_file",
",",
"feature_node",
"=",
"self",
".",
"__get_feature_file",
"(",
"dev_node",
",",
"lambda",
"p",
":",
"os",
".",
"path",
".",
"join",
"(",
"p",
",",
"'queue'",
",",
"'s... | https://github.com/scylladb/seastar/blob/0cdd2329beb1cc4c0af8828598c26114397ffa9c/scripts/perftune.py#L1254-L1274 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/cffi/api.py | python | FFI.cast | (self, cdecl, source) | return self._backend.cast(cdecl, source) | Similar to a C cast: returns an instance of the named C
type initialized with the given 'source'. The source is
casted between integers or pointers of any type. | Similar to a C cast: returns an instance of the named C
type initialized with the given 'source'. The source is
casted between integers or pointers of any type. | [
"Similar",
"to",
"a",
"C",
"cast",
":",
"returns",
"an",
"instance",
"of",
"the",
"named",
"C",
"type",
"initialized",
"with",
"the",
"given",
"source",
".",
"The",
"source",
"is",
"casted",
"between",
"integers",
"or",
"pointers",
"of",
"any",
"type",
"... | def cast(self, cdecl, source):
"""Similar to a C cast: returns an instance of the named C
type initialized with the given 'source'. The source is
casted between integers or pointers of any type.
"""
if isinstance(cdecl, basestring):
cdecl = self._typeof(cdecl)
return self._backend.cast(cdecl, source) | [
"def",
"cast",
"(",
"self",
",",
"cdecl",
",",
"source",
")",
":",
"if",
"isinstance",
"(",
"cdecl",
",",
"basestring",
")",
":",
"cdecl",
"=",
"self",
".",
"_typeof",
"(",
"cdecl",
")",
"return",
"self",
".",
"_backend",
".",
"cast",
"(",
"cdecl",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/cffi/api.py#L293-L300 | |
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/python2_version/klampt/math/optimize.py | python | OptimizationProblemBuilder.unbind | (self,**kwargs) | return res | Binds the variables specified by the keyword arguments | Binds the variables specified by the keyword arguments | [
"Binds",
"the",
"variables",
"specified",
"by",
"the",
"keyword",
"arguments"
] | def unbind(self,**kwargs):
"""Binds the variables specified by the keyword arguments"""
for (k,v) in kwargs:
self.context.variableDict[k].unbind()
return res | [
"def",
"unbind",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"(",
"k",
",",
"v",
")",
"in",
"kwargs",
":",
"self",
".",
"context",
".",
"variableDict",
"[",
"k",
"]",
".",
"unbind",
"(",
")",
"return",
"res"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/math/optimize.py#L860-L864 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/AzCodeGenerator/bin/osx/az_code_gen/clang_cpp.py | python | extract_parameters | (string_data) | Extract and return the parameters contained in parenthesis
of a parametrized JSON entry in a string.
For example:
"Token(Parameter)" would return "Parameter"
Note: The incoming string must be validated by is_parametrized_token
@param string_data - The incoming string to extract parameters from
@return A string containing the parameter string of the input token | Extract and return the parameters contained in parenthesis
of a parametrized JSON entry in a string.
For example:
"Token(Parameter)" would return "Parameter"
Note: The incoming string must be validated by is_parametrized_token | [
"Extract",
"and",
"return",
"the",
"parameters",
"contained",
"in",
"parenthesis",
"of",
"a",
"parametrized",
"JSON",
"entry",
"in",
"a",
"string",
".",
"For",
"example",
":",
"Token",
"(",
"Parameter",
")",
"would",
"return",
"Parameter",
"Note",
":",
"The"... | def extract_parameters(string_data):
"""Extract and return the parameters contained in parenthesis
of a parametrized JSON entry in a string.
For example:
"Token(Parameter)" would return "Parameter"
Note: The incoming string must be validated by is_parametrized_token
@param string_data - The incoming string to extract parameters from
@return A string containing the parameter string of the input token
"""
parenthesis_depth = 0
open_index = 0
close_index = 0
index = 0
string_checker = string_detector(string_data)
for c in string_data:
in_string = next(string_checker)
# Handle Parenthesis
if not in_string and c == '(':
parenthesis_depth += 1
if parenthesis_depth == 1:
open_index = index + 1
if not in_string and c == ')':
parenthesis_depth -= 1
if parenthesis_depth == 0:
close_index = index
# increment our index
index += 1
if open_index > close_index:
return "null"
else:
return string_data[open_index:close_index] | [
"def",
"extract_parameters",
"(",
"string_data",
")",
":",
"parenthesis_depth",
"=",
"0",
"open_index",
"=",
"0",
"close_index",
"=",
"0",
"index",
"=",
"0",
"string_checker",
"=",
"string_detector",
"(",
"string_data",
")",
"for",
"c",
"in",
"string_data",
":... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AzCodeGenerator/bin/osx/az_code_gen/clang_cpp.py#L506-L541 | ||
netease-youdao/hex | d7b8773dae8dde63f3807cef1d48c017077db727 | tools/git_util.py | python | get_changed_files | (path=".") | return [] | Retrieves the list of changed files. | Retrieves the list of changed files. | [
"Retrieves",
"the",
"list",
"of",
"changed",
"files",
"."
] | def get_changed_files(path="."):
""" Retrieves the list of changed files. """
# not implemented
return [] | [
"def",
"get_changed_files",
"(",
"path",
"=",
"\".\"",
")",
":",
"# not implemented",
"return",
"[",
"]"
] | https://github.com/netease-youdao/hex/blob/d7b8773dae8dde63f3807cef1d48c017077db727/tools/git_util.py#L21-L24 | |
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/python/debug/cli/command_parser.py | python | parse_readable_time_str | (time_str) | return int(parse_positive_float(time_str)) | Parses a time string in the format N, Nus, Nms, Ns.
Args:
time_str: (`str`) string consisting of an integer time value optionally
followed by 'us', 'ms', or 's' suffix. If suffix is not specified,
value is assumed to be in microseconds. (e.g. 100us, 8ms, 5s, 100).
Returns:
Microseconds value. | Parses a time string in the format N, Nus, Nms, Ns. | [
"Parses",
"a",
"time",
"string",
"in",
"the",
"format",
"N",
"Nus",
"Nms",
"Ns",
"."
] | def parse_readable_time_str(time_str):
"""Parses a time string in the format N, Nus, Nms, Ns.
Args:
time_str: (`str`) string consisting of an integer time value optionally
followed by 'us', 'ms', or 's' suffix. If suffix is not specified,
value is assumed to be in microseconds. (e.g. 100us, 8ms, 5s, 100).
Returns:
Microseconds value.
"""
def parse_positive_float(value_str):
value = float(value_str)
if value < 0:
raise ValueError(
"Invalid time %s. Time value must be positive." % value_str)
return value
time_str = time_str.strip()
if time_str.endswith("us"):
return int(parse_positive_float(time_str[:-2]))
elif time_str.endswith("ms"):
return int(parse_positive_float(time_str[:-2]) * 1e3)
elif time_str.endswith("s"):
return int(parse_positive_float(time_str[:-1]) * 1e6)
return int(parse_positive_float(time_str)) | [
"def",
"parse_readable_time_str",
"(",
"time_str",
")",
":",
"def",
"parse_positive_float",
"(",
"value_str",
")",
":",
"value",
"=",
"float",
"(",
"value_str",
")",
"if",
"value",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"Invalid time %s. Time value must be p... | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/debug/cli/command_parser.py#L442-L467 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_misc.py | python | DateSpan.GetYears | (*args, **kwargs) | return _misc_.DateSpan_GetYears(*args, **kwargs) | GetYears(self) -> int | GetYears(self) -> int | [
"GetYears",
"(",
"self",
")",
"-",
">",
"int"
] | def GetYears(*args, **kwargs):
"""GetYears(self) -> int"""
return _misc_.DateSpan_GetYears(*args, **kwargs) | [
"def",
"GetYears",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"DateSpan_GetYears",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_misc.py#L4669-L4671 | |
trailofbits/llvm-sanitizer-tutorial | d29dfeec7f51fbf234fd0080f28f2b30cd0b6e99 | llvm/tools/clang/bindings/python/clang/cindex.py | python | BaseEnumeration.name | (self) | return self._name_map[self] | Get the enumeration name of this cursor kind. | Get the enumeration name of this cursor kind. | [
"Get",
"the",
"enumeration",
"name",
"of",
"this",
"cursor",
"kind",
"."
] | def name(self):
"""Get the enumeration name of this cursor kind."""
if self._name_map is None:
self._name_map = {}
for key, value in self.__class__.__dict__.items():
if isinstance(value, self.__class__):
self._name_map[value] = key
return self._name_map[self] | [
"def",
"name",
"(",
"self",
")",
":",
"if",
"self",
".",
"_name_map",
"is",
"None",
":",
"self",
".",
"_name_map",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"self",
".",
"__class__",
".",
"__dict__",
".",
"items",
"(",
")",
":",
"if",
"isi... | https://github.com/trailofbits/llvm-sanitizer-tutorial/blob/d29dfeec7f51fbf234fd0080f28f2b30cd0b6e99/llvm/tools/clang/bindings/python/clang/cindex.py#L639-L646 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_controls.py | python | FileCtrl.GetFilenames | (*args, **kwargs) | return _controls_.FileCtrl_GetFilenames(*args, **kwargs) | GetFilenames(self) -> wxArrayString | GetFilenames(self) -> wxArrayString | [
"GetFilenames",
"(",
"self",
")",
"-",
">",
"wxArrayString"
] | def GetFilenames(*args, **kwargs):
"""GetFilenames(self) -> wxArrayString"""
return _controls_.FileCtrl_GetFilenames(*args, **kwargs) | [
"def",
"GetFilenames",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"FileCtrl_GetFilenames",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_controls.py#L7608-L7610 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/logging/handlers.py | python | BaseRotatingHandler.rotate | (self, source, dest) | When rotating, rotate the current log.
The default implementation calls the 'rotator' attribute of the
handler, if it's callable, passing the source and dest arguments to
it. If the attribute isn't callable (the default is None), the source
is simply renamed to the destination.
:param source: The source filename. This is normally the base
filename, e.g. 'test.log'
:param dest: The destination filename. This is normally
what the source is rotated to, e.g. 'test.log.1'. | When rotating, rotate the current log. | [
"When",
"rotating",
"rotate",
"the",
"current",
"log",
"."
] | def rotate(self, source, dest):
"""
When rotating, rotate the current log.
The default implementation calls the 'rotator' attribute of the
handler, if it's callable, passing the source and dest arguments to
it. If the attribute isn't callable (the default is None), the source
is simply renamed to the destination.
:param source: The source filename. This is normally the base
filename, e.g. 'test.log'
:param dest: The destination filename. This is normally
what the source is rotated to, e.g. 'test.log.1'.
"""
if not callable(self.rotator):
# Issue 18940: A file may not have been created if delay is True.
if os.path.exists(source):
os.rename(source, dest)
else:
self.rotator(source, dest) | [
"def",
"rotate",
"(",
"self",
",",
"source",
",",
"dest",
")",
":",
"if",
"not",
"callable",
"(",
"self",
".",
"rotator",
")",
":",
"# Issue 18940: A file may not have been created if delay is True.",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"source",
")",... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/logging/handlers.py#L94-L113 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/cython/Cython/Debugger/libpython.py | python | PyFrameObjectPtr.iter_globals | (self) | return pyop_globals.iteritems() | Yield a sequence of (name,value) pairs of PyObjectPtr instances, for
the global variables of this frame | Yield a sequence of (name,value) pairs of PyObjectPtr instances, for
the global variables of this frame | [
"Yield",
"a",
"sequence",
"of",
"(",
"name",
"value",
")",
"pairs",
"of",
"PyObjectPtr",
"instances",
"for",
"the",
"global",
"variables",
"of",
"this",
"frame"
] | def iter_globals(self):
'''
Yield a sequence of (name,value) pairs of PyObjectPtr instances, for
the global variables of this frame
'''
if self.is_optimized_out():
return ()
pyop_globals = self.pyop_field('f_globals')
return pyop_globals.iteritems() | [
"def",
"iter_globals",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_optimized_out",
"(",
")",
":",
"return",
"(",
")",
"pyop_globals",
"=",
"self",
".",
"pyop_field",
"(",
"'f_globals'",
")",
"return",
"pyop_globals",
".",
"iteritems",
"(",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/cython/Cython/Debugger/libpython.py#L878-L887 | |
rodeofx/OpenWalter | 6116fbe3f04f1146c854afbfbdbe944feaee647e | walter/maya/scripts/walterPanel/mergeExpressions.py | python | MergeExpressions.__call__ | (self) | return self.diff(self.firstLen, self.secondLen) | Compare saved strings and return the expression that matches both
strings.
:returns: The expression that matches both strings.
:rtype: string | Compare saved strings and return the expression that matches both
strings. | [
"Compare",
"saved",
"strings",
"and",
"return",
"the",
"expression",
"that",
"matches",
"both",
"strings",
"."
] | def __call__(self):
"""
Compare saved strings and return the expression that matches both
strings.
:returns: The expression that matches both strings.
:rtype: string
"""
return self.diff(self.firstLen, self.secondLen) | [
"def",
"__call__",
"(",
"self",
")",
":",
"return",
"self",
".",
"diff",
"(",
"self",
".",
"firstLen",
",",
"self",
".",
"secondLen",
")"
] | https://github.com/rodeofx/OpenWalter/blob/6116fbe3f04f1146c854afbfbdbe944feaee647e/walter/maya/scripts/walterPanel/mergeExpressions.py#L67-L75 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/keras/saving/saved_model/load.py | python | _restore_layer_unconditional_losses | (layer) | Restore unconditional losses from SavedModel. | Restore unconditional losses from SavedModel. | [
"Restore",
"unconditional",
"losses",
"from",
"SavedModel",
"."
] | def _restore_layer_unconditional_losses(layer):
"""Restore unconditional losses from SavedModel."""
if hasattr(_get_keras_attr(layer), 'layer_regularization_losses'):
losses = getattr(_get_keras_attr(layer), 'layer_regularization_losses', [])
else:
# Some earlier SavedModels may not have layer_regularization_losses
# serialized separately. Fall back to using the regularization_losses
# list if it does not exist.
losses = layer._serialized_attributes.get('regularization_losses', []) # pylint: disable=protected-access
for loss in losses:
layer.add_loss(loss) | [
"def",
"_restore_layer_unconditional_losses",
"(",
"layer",
")",
":",
"if",
"hasattr",
"(",
"_get_keras_attr",
"(",
"layer",
")",
",",
"'layer_regularization_losses'",
")",
":",
"losses",
"=",
"getattr",
"(",
"_get_keras_attr",
"(",
"layer",
")",
",",
"'layer_regu... | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/keras/saving/saved_model/load.py#L921-L931 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/html.py | python | PreHtmlHelpFrame | (*args, **kwargs) | return val | PreHtmlHelpFrame(HtmlHelpData data=None) -> HtmlHelpFrame | PreHtmlHelpFrame(HtmlHelpData data=None) -> HtmlHelpFrame | [
"PreHtmlHelpFrame",
"(",
"HtmlHelpData",
"data",
"=",
"None",
")",
"-",
">",
"HtmlHelpFrame"
] | def PreHtmlHelpFrame(*args, **kwargs):
"""PreHtmlHelpFrame(HtmlHelpData data=None) -> HtmlHelpFrame"""
val = _html.new_PreHtmlHelpFrame(*args, **kwargs)
self._setOORInfo(self)
return val | [
"def",
"PreHtmlHelpFrame",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"val",
"=",
"_html",
".",
"new_PreHtmlHelpFrame",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"_setOORInfo",
"(",
"self",
")",
"return",
"val"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/html.py#L1803-L1807 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/gslib/command.py | python | ShutDownGsutil | () | Shut down all processes in consumer pools in preparation for exiting. | Shut down all processes in consumer pools in preparation for exiting. | [
"Shut",
"down",
"all",
"processes",
"in",
"consumer",
"pools",
"in",
"preparation",
"for",
"exiting",
"."
] | def ShutDownGsutil():
"""Shut down all processes in consumer pools in preparation for exiting."""
for q in queues:
try:
q.cancel_join_thread()
except: # pylint: disable=bare-except
pass
for consumer_pool in consumer_pools:
consumer_pool.ShutDown() | [
"def",
"ShutDownGsutil",
"(",
")",
":",
"for",
"q",
"in",
"queues",
":",
"try",
":",
"q",
".",
"cancel_join_thread",
"(",
")",
"except",
":",
"# pylint: disable=bare-except",
"pass",
"for",
"consumer_pool",
"in",
"consumer_pools",
":",
"consumer_pool",
".",
"S... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/gslib/command.py#L1818-L1826 | ||
swift/swift | 12d031cf8177fdec0137f9aa7e2912fa23c4416b | 3rdParty/SCons/scons-3.0.1/engine/SCons/compat/__init__.py | python | rename_module | (new, old) | Attempts to import the old module and load it under the new name.
Used for purely cosmetic name changes in Python 3.x. | Attempts to import the old module and load it under the new name.
Used for purely cosmetic name changes in Python 3.x. | [
"Attempts",
"to",
"import",
"the",
"old",
"module",
"and",
"load",
"it",
"under",
"the",
"new",
"name",
".",
"Used",
"for",
"purely",
"cosmetic",
"name",
"changes",
"in",
"Python",
"3",
".",
"x",
"."
] | def rename_module(new, old):
"""
Attempts to import the old module and load it under the new name.
Used for purely cosmetic name changes in Python 3.x.
"""
try:
sys.modules[new] = imp.load_module(old, *imp.find_module(old))
return True
except ImportError:
return False | [
"def",
"rename_module",
"(",
"new",
",",
"old",
")",
":",
"try",
":",
"sys",
".",
"modules",
"[",
"new",
"]",
"=",
"imp",
".",
"load_module",
"(",
"old",
",",
"*",
"imp",
".",
"find_module",
"(",
"old",
")",
")",
"return",
"True",
"except",
"Import... | https://github.com/swift/swift/blob/12d031cf8177fdec0137f9aa7e2912fa23c4416b/3rdParty/SCons/scons-3.0.1/engine/SCons/compat/__init__.py#L78-L87 | ||
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/python/ops/rnn_cell.py | python | BasicLSTMCell.__init__ | (self, num_units, forget_bias=1.0, input_size=None,
state_is_tuple=True, activation=tanh) | Initialize the basic LSTM cell.
Args:
num_units: int, The number of units in the LSTM cell.
forget_bias: float, The bias added to forget gates (see above).
input_size: Deprecated and unused.
state_is_tuple: If True, accepted and returned states are 2-tuples of
the `c_state` and `m_state`. If False, they are concatenated
along the column axis. The latter behavior will soon be deprecated.
activation: Activation function of the inner states. | Initialize the basic LSTM cell. | [
"Initialize",
"the",
"basic",
"LSTM",
"cell",
"."
] | def __init__(self, num_units, forget_bias=1.0, input_size=None,
state_is_tuple=True, activation=tanh):
"""Initialize the basic LSTM cell.
Args:
num_units: int, The number of units in the LSTM cell.
forget_bias: float, The bias added to forget gates (see above).
input_size: Deprecated and unused.
state_is_tuple: If True, accepted and returned states are 2-tuples of
the `c_state` and `m_state`. If False, they are concatenated
along the column axis. The latter behavior will soon be deprecated.
activation: Activation function of the inner states.
"""
if not state_is_tuple:
logging.warn("%s: Using a concatenated state is slower and will soon be "
"deprecated. Use state_is_tuple=True.", self)
if input_size is not None:
logging.warn("%s: The input_size parameter is deprecated.", self)
self._num_units = num_units
self._forget_bias = forget_bias
self._state_is_tuple = state_is_tuple
self._activation = activation | [
"def",
"__init__",
"(",
"self",
",",
"num_units",
",",
"forget_bias",
"=",
"1.0",
",",
"input_size",
"=",
"None",
",",
"state_is_tuple",
"=",
"True",
",",
"activation",
"=",
"tanh",
")",
":",
"if",
"not",
"state_is_tuple",
":",
"logging",
".",
"warn",
"(... | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/ops/rnn_cell.py#L271-L292 | ||
meritlabs/merit | 49dc96043f882b982175fb66934e2bf1e6b1920c | contrib/devtools/security-check.py | python | check_ELF_RELRO | (executable) | return have_gnu_relro and have_bindnow | Check for read-only relocations.
GNU_RELRO program header must exist
Dynamic section must have BIND_NOW flag | Check for read-only relocations.
GNU_RELRO program header must exist
Dynamic section must have BIND_NOW flag | [
"Check",
"for",
"read",
"-",
"only",
"relocations",
".",
"GNU_RELRO",
"program",
"header",
"must",
"exist",
"Dynamic",
"section",
"must",
"have",
"BIND_NOW",
"flag"
] | def check_ELF_RELRO(executable):
'''
Check for read-only relocations.
GNU_RELRO program header must exist
Dynamic section must have BIND_NOW flag
'''
have_gnu_relro = False
for (typ, flags) in get_ELF_program_headers(executable):
# Note: not checking flags == 'R': here as linkers set the permission differently
# This does not affect security: the permission flags of the GNU_RELRO program header are ignored, the PT_LOAD header determines the effective permissions.
# However, the dynamic linker need to write to this area so these are RW.
# Glibc itself takes care of mprotecting this area R after relocations are finished.
# See also http://permalink.gmane.org/gmane.comp.gnu.binutils/71347
if typ == b'GNU_RELRO':
have_gnu_relro = True
have_bindnow = False
p = subprocess.Popen([READELF_CMD, '-d', '-W', executable], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
(stdout, stderr) = p.communicate()
if p.returncode:
raise IOError('Error opening file')
for line in stdout.split(b'\n'):
tokens = line.split()
if len(tokens)>1 and tokens[1] == b'(BIND_NOW)' or (len(tokens)>2 and tokens[1] == b'(FLAGS)' and b'BIND_NOW' in tokens[2]):
have_bindnow = True
return have_gnu_relro and have_bindnow | [
"def",
"check_ELF_RELRO",
"(",
"executable",
")",
":",
"have_gnu_relro",
"=",
"False",
"for",
"(",
"typ",
",",
"flags",
")",
"in",
"get_ELF_program_headers",
"(",
"executable",
")",
":",
"# Note: not checking flags == 'R': here as linkers set the permission differently",
... | https://github.com/meritlabs/merit/blob/49dc96043f882b982175fb66934e2bf1e6b1920c/contrib/devtools/security-check.py#L78-L103 | |
xiaohaoChen/rrc_detection | 4f2b110cd122da7f55e8533275a9b4809a88785a | scripts/cpp_lint.py | python | _CppLintState.SetCountingStyle | (self, counting_style) | Sets the module's counting options. | Sets the module's counting options. | [
"Sets",
"the",
"module",
"s",
"counting",
"options",
"."
] | def SetCountingStyle(self, counting_style):
"""Sets the module's counting options."""
self.counting = counting_style | [
"def",
"SetCountingStyle",
"(",
"self",
",",
"counting_style",
")",
":",
"self",
".",
"counting",
"=",
"counting_style"
] | https://github.com/xiaohaoChen/rrc_detection/blob/4f2b110cd122da7f55e8533275a9b4809a88785a/scripts/cpp_lint.py#L713-L715 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py3/sklearn/neural_network/_multilayer_perceptron.py | python | MLPClassifier.predict_log_proba | (self, X) | return np.log(y_prob, out=y_prob) | Return the log of probability estimates.
Parameters
----------
X : ndarray of shape (n_samples, n_features)
The input data.
Returns
-------
log_y_prob : ndarray of shape (n_samples, n_classes)
The predicted log-probability of the sample for each class
in the model, where classes are ordered as they are in
`self.classes_`. Equivalent to log(predict_proba(X)) | Return the log of probability estimates. | [
"Return",
"the",
"log",
"of",
"probability",
"estimates",
"."
] | def predict_log_proba(self, X):
"""Return the log of probability estimates.
Parameters
----------
X : ndarray of shape (n_samples, n_features)
The input data.
Returns
-------
log_y_prob : ndarray of shape (n_samples, n_classes)
The predicted log-probability of the sample for each class
in the model, where classes are ordered as they are in
`self.classes_`. Equivalent to log(predict_proba(X))
"""
y_prob = self.predict_proba(X)
return np.log(y_prob, out=y_prob) | [
"def",
"predict_log_proba",
"(",
"self",
",",
"X",
")",
":",
"y_prob",
"=",
"self",
".",
"predict_proba",
"(",
"X",
")",
"return",
"np",
".",
"log",
"(",
"y_prob",
",",
"out",
"=",
"y_prob",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/neural_network/_multilayer_perceptron.py#L1039-L1055 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.