code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
A, x, b = make_system(A, x, b, formats=['csr'])
sweep = slice(None)
(row_start, row_stop, row_step) = sweep.indices(A.shape[0])
temp = np.zeros_like(x)
# Dinv for A*A.H
Dinv = get_diagonal(A, norm_eq=2, inv=True)
# Create uniform type, convert possibly complex scalars to length 1 ar... | def jacobi_ne(A, x, b, iterations=1, omega=1.0) | Perform Jacobi iterations on the linear system A A.H x = A.H b.
Also known as Cimmino relaxation
Parameters
----------
A : csr_matrix
Sparse NxN matrix
x : ndarray
Approximate solution (length N)
b : ndarray
Right-hand side (length N)
iterations : int
Number... | 6.114159 | 6.510365 | 0.939142 |
A, x, b = make_system(A, x, b, formats=['csr'])
# Dinv for A*A.H
if Dinv is None:
Dinv = np.ravel(get_diagonal(A, norm_eq=2, inv=True))
if sweep == 'forward':
row_start, row_stop, row_step = 0, len(x), 1
elif sweep == 'backward':
row_start, row_stop, row_step = len(x)-... | def gauss_seidel_ne(A, x, b, iterations=1, sweep='forward', omega=1.0,
Dinv=None) | Perform Gauss-Seidel iterations on the linear system A A.H x = b.
Also known as Kaczmarz relaxation
Parameters
----------
A : csr_matrix
Sparse NxN matrix
x : ndarray
Approximate solution (length N)
b : ndarray
Right-hand side (length N)
iterations : int
Num... | 2.485411 | 2.649138 | 0.938196 |
A, x, b = make_system(A, x, b, formats=['csc'])
# Dinv for A.H*A
if Dinv is None:
Dinv = np.ravel(get_diagonal(A, norm_eq=1, inv=True))
if sweep == 'forward':
col_start, col_stop, col_step = 0, len(x), 1
elif sweep == 'backward':
col_start, col_stop, col_step = len(x)-... | def gauss_seidel_nr(A, x, b, iterations=1, sweep='forward', omega=1.0,
Dinv=None) | Perform Gauss-Seidel iterations on the linear system A.H A x = A.H b.
Parameters
----------
A : csr_matrix
Sparse NxN matrix
x : ndarray
Approximate solution (length N)
b : ndarray
Right-hand side (length N)
iterations : int
Number of iterations to perform
sw... | 2.605257 | 2.798225 | 0.931039 |
# Check if A has a pre-existing set of Schwarz parameters
if hasattr(A, 'schwarz_parameters'):
if subdomain is not None and subdomain_ptr is not None:
# check that the existing parameters correspond to the same
# subdomains
if np.array(A.schwarz_parameters[0] == ... | def schwarz_parameters(A, subdomain=None, subdomain_ptr=None,
inv_subblock=None, inv_subblock_ptr=None) | Set Schwarz parameters.
Helper function for setting up Schwarz relaxation. This function avoids
recomputing the subdomains and block inverses manytimes, e.g., it avoids a
costly double computation when setting up pre and post smoothing with
Schwarz.
Parameters
----------
A {csr_matrix}
... | 2.925457 | 2.887217 | 1.013245 |
cycle = str(cycle).upper()
nnz = [level.A.nnz for level in self.levels]
def V(level):
if len(self.levels) == 1:
return nnz[0]
elif level == len(self.levels) - 2:
return 2 * nnz[level] + nnz[level + 1]
else:
... | def cycle_complexity(self, cycle='V') | Cycle complexity of V, W, AMLI, and F(1,1) cycle with simple relaxation.
Cycle complexity is an approximate measure of the number of
floating point operations (FLOPs) required to perform a single
multigrid cycle relative to the cost a single smoothing operation.
Parameters
----... | 1.926405 | 1.773029 | 1.086505 |
return sum([level.A.nnz for level in self.levels]) /\
float(self.levels[0].A.nnz) | def operator_complexity(self) | Operator complexity of this multigrid hierarchy.
Defined as:
Number of nonzeros in the matrix on all levels /
Number of nonzeros in the matrix on the finest level | 9.265436 | 6.003919 | 1.543231 |
return sum([level.A.shape[0] for level in self.levels]) /\
float(self.levels[0].A.shape[0]) | def grid_complexity(self) | Grid complexity of this multigrid hierarchy.
Defined as:
Number of unknowns on all levels /
Number of unknowns on the finest level | 6.612605 | 5.444808 | 1.214479 |
from scipy.sparse.linalg import LinearOperator
shape = self.levels[0].A.shape
dtype = self.levels[0].A.dtype
def matvec(b):
return self.solve(b, maxiter=1, cycle=cycle, tol=1e-12)
return LinearOperator(shape, matvec, dtype=dtype) | def aspreconditioner(self, cycle='V') | Create a preconditioner using this multigrid cycle.
Parameters
----------
cycle : {'V','W','F','AMLI'}
Type of multigrid cycle to perform in each iteration.
Returns
-------
precond : LinearOperator
Preconditioner suitable for the iterative solver... | 3.673719 | 4.687424 | 0.783739 |
A = self.levels[lvl].A
self.levels[lvl].presmoother(A, x, b)
residual = b - A * x
coarse_b = self.levels[lvl].R * residual
coarse_x = np.zeros_like(coarse_b)
if lvl == len(self.levels) - 2:
coarse_x[:] = self.coarse_solver(self.levels[-1].A, coars... | def __solve(self, lvl, x, b, cycle) | Multigrid cycling.
Parameters
----------
lvl : int
Solve problem on level `lvl`
x : numpy array
Initial guess `x` and return correction
b : numpy array
Right-hand side for Ax=b
cycle : {'V','W','F','AMLI'}
Recursively calle... | 2.962482 | 2.773053 | 1.068311 |
G = asgraph(G)
N = G.shape[0]
mis = np.empty(N, dtype='intc')
mis[:] = -1
if k is None:
if algo == 'serial':
fn = amg_core.maximal_independent_set_serial
fn(N, G.indptr, G.indices, -1, 1, 0, mis)
elif algo == 'parallel':
fn = amg_core.maxima... | def maximal_independent_set(G, algo='serial', k=None) | Compute a maximal independent vertex set for a graph.
Parameters
----------
G : sparse matrix
Symmetric matrix, preferably in sparse CSR or CSC format
The nonzeros of G represent the edges of an undirected graph.
algo : {'serial', 'parallel'}
Algorithm used to compute the MIS
... | 2.418303 | 2.382103 | 1.015197 |
G = asgraph(G)
N = G.shape[0]
coloring = np.empty(N, dtype='intc')
if method == 'MIS':
fn = amg_core.vertex_coloring_mis
fn(N, G.indptr, G.indices, coloring)
elif method == 'JP':
fn = amg_core.vertex_coloring_jones_plassmann
fn(N, G.indptr, G.indices, coloring,... | def vertex_coloring(G, method='MIS') | Compute a vertex coloring of a graph.
Parameters
----------
G : sparse matrix
Symmetric matrix, preferably in sparse CSR or CSC format
The nonzeros of G represent the edges of an undirected graph.
method : string
Algorithm used to compute the vertex coloring:
* 'MIS... | 2.739932 | 2.261163 | 1.211736 |
G = asgraph(G)
N = G.shape[0]
if maxiter is not None and maxiter < 0:
raise ValueError('maxiter must be positive')
if G.dtype == complex:
raise ValueError('Bellman-Ford algorithm only defined for real\
weights')
seeds = np.asarray(seeds, dtype='intc')... | def bellman_ford(G, seeds, maxiter=None) | Bellman-Ford iteration.
Parameters
----------
G : sparse matrix
Returns
-------
distances : array
nearest_seed : array
References
----------
CLR | 3.010553 | 2.866933 | 1.050095 |
G = asgraph(G)
N = G.shape[0]
if G.dtype.kind == 'c':
# complex dtype
G = np.abs(G)
# interpret seeds argument
if np.isscalar(seeds):
seeds = np.random.permutation(N)[:seeds]
seeds = seeds.astype('intc')
else:
seeds = np.array(seeds, dtype='intc')
... | def lloyd_cluster(G, seeds, maxiter=10) | Perform Lloyd clustering on graph with weighted edges.
Parameters
----------
G : csr_matrix, csc_matrix
A sparse NxN matrix where each nonzero entry G[i,j] is the distance
between nodes i and j.
seeds : int array
If seeds is an integer, then its value determines the number of
... | 2.645669 | 2.363295 | 1.119483 |
G = asgraph(G)
N = G.shape[0]
order = np.empty(N, G.indptr.dtype)
level = np.empty(N, G.indptr.dtype)
level[:] = -1
BFS = amg_core.breadth_first_search
BFS(G.indptr, G.indices, int(seed), order, level)
return order, level | def breadth_first_search(G, seed) | Breadth First search of a graph.
Parameters
----------
G : csr_matrix, csc_matrix
A sparse NxN matrix where each nonzero entry G[i,j] is the distance
between nodes i and j.
seed : int
Index of the seed location
Returns
-------
order : int array
Breadth first... | 4.009982 | 4.381859 | 0.915132 |
G = asgraph(G)
N = G.shape[0]
components = np.empty(N, G.indptr.dtype)
fn = amg_core.connected_components
fn(N, G.indptr, G.indices, components)
return components | def connected_components(G) | Compute the connected components of a graph.
The connected components of a graph G, which is represented by a
symmetric sparse matrix, are labeled with the integers 0,1,..(K-1) where
K is the number of components.
Parameters
----------
G : symmetric matrix, preferably in sparse CSR or CSC form... | 4.709032 | 6.088264 | 0.773461 |
n = A.shape[0]
root, order, level = pseudo_peripheral_node(A)
Perm = sparse.identity(n, format='csr')
p = level.argsort()
Perm = Perm[p, :]
return Perm * A * Perm.T | def symmetric_rcm(A) | Symmetric Reverse Cutthill-McKee.
Parameters
----------
A : sparse matrix
Sparse matrix
Returns
-------
B : sparse matrix
Permuted matrix with reordering
Notes
-----
Get a pseudo-peripheral node, then call BFS
Examples
--------
>>> from pyamg import ga... | 7.90971 | 5.810686 | 1.361235 |
from pyamg.graph import breadth_first_search
n = A.shape[0]
valence = np.diff(A.indptr)
# select an initial node x, set delta = 0
x = int(np.random.rand() * n)
delta = 0
while True:
# do a level-set traversal from x
order, level = breadth_first_search(A, x)
#... | def pseudo_peripheral_node(A) | Find a pseudo peripheral node.
Parameters
----------
A : sparse matrix
Sparse matrix
Returns
-------
x : int
Locaiton of the node
order : array
BFS ordering
level : array
BFS levels
Notes
-----
Algorithm in Saad | 4.319782 | 3.948699 | 1.093976 |
A = ml.levels[0].A
b = A * sp.rand(A.shape[0], 1)
residuals = []
if accel is None:
ml.solve(b, residuals=residuals, **kwargs)
else:
def callback(x):
residuals.append(norm(np.ravel(b) - np.ravel(A*x)))
M = ml.aspreconditioner(cycle=kwargs.get('cycle', 'V'))
... | def profile_solver(ml, accel=None, **kwargs) | Profile a particular multilevel object.
Parameters
----------
ml : multilevel
Fully constructed multilevel object
accel : function pointer
Pointer to a valid Krylov solver (e.g. gmres, cg)
Returns
-------
residuals : array
Array of residuals for each iteration
... | 4.00344 | 4.651523 | 0.860673 |
if isspmatrix(A):
return A.diagonal()
else:
if(np.ndim(A) != 1):
raise ValueError('input diagonal array expected to be 1d')
return csr_matrix((np.asarray(A), np.arange(len(A)),
np.arange(len(A)+1)), (len(A), len(A))) | def diag_sparse(A) | Return a diagonal.
If A is a sparse matrix (e.g. csr_matrix or csc_matrix)
- return the diagonal of A as an array
Otherwise
- return a csr_matrix with A on the diagonal
Parameters
----------
A : sparse matrix or 1d array
General sparse matrix or array of diagonal entries
... | 3.505005 | 3.870257 | 0.905626 |
v = np.ravel(v)
M, N = A.shape
if not isspmatrix(A):
raise ValueError('scale rows needs a sparse matrix')
if M != len(v):
raise ValueError('scale vector has incompatible shape')
if copy:
A = A.copy()
A.data = np.asarray(A.data, dtype=upcast(A.dtype, v.dtype))... | def scale_rows(A, v, copy=True) | Scale the sparse rows of a matrix.
Parameters
----------
A : sparse matrix
Sparse matrix with M rows
v : array_like
Array of M scales
copy : {True,False}
- If copy=True, then the matrix is copied to a new and different return
matrix (e.g. B=scale_rows(A,v))
... | 2.599241 | 3.070634 | 0.846484 |
v = np.ravel(v)
M, N = A.shape
if not isspmatrix(A):
raise ValueError('scale columns needs a sparse matrix')
if N != len(v):
raise ValueError('scale vector has incompatible shape')
if copy:
A = A.copy()
A.data = np.asarray(A.data, dtype=upcast(A.dtype, v.dtyp... | def scale_columns(A, v, copy=True) | Scale the sparse columns of a matrix.
Parameters
----------
A : sparse matrix
Sparse matrix with N rows
v : array_like
Array of N scales
copy : {True,False}
- If copy=True, then the matrix is copied to a new and different return
matrix (e.g. B=scale_columns(A,v))
... | 2.599377 | 3.018754 | 0.861076 |
if isspmatrix_csr(A) or isspmatrix_csc(A) or isspmatrix_bsr(A):
if A.shape[0] != A.shape[1]:
raise ValueError('expected square matrix')
D = diag_sparse(A)
mask = (D != 0)
if A.dtype != complex:
D_sqrt = np.sqrt(abs(D))
else:
# We can... | def symmetric_rescaling(A, copy=True) | Scale the matrix symmetrically.
A = D^{-1/2} A D^{-1/2}
where D=diag(A).
The left multiplication is accomplished through scale_rows and the right
multiplication is done through scale columns.
Parameters
----------
A : sparse matrix
Sparse matrix with N rows
copy : {True,F... | 2.806417 | 2.721491 | 1.031206 |
# rescale A
[D_sqrt, D_sqrt_inv, A] = symmetric_rescaling(A, copy=False)
# scale candidates
for i in range(B.shape[1]):
B[:, i] = np.ravel(B[:, i])*np.ravel(D_sqrt)
if hasattr(A, 'symmetry'):
if A.symmetry == 'nonsymmetric':
if BH is None:
raise Valu... | def symmetric_rescaling_sa(A, B, BH=None) | Scale the matrix symmetrically.
A = D^{-1/2} A D^{-1/2}
where D=diag(A). The left multiplication is accomplished through
scale_rows and the right multiplication is done through scale columns.
The candidates B and BH are scaled accordingly::
B = D^{1/2} B
BH = D^{1/2} BH
Par... | 3.339621 | 3.42918 | 0.973883 |
varlist = to_type(upcast_type, varlist)
for i in range(len(varlist)):
if np.isscalar(varlist[i]):
varlist[i] = np.array([varlist[i]])
return varlist | def type_prep(upcast_type, varlist) | Upcast variables to a type.
Loop over all elements of varlist and convert them to upcasttype
The only difference with pyamg.util.utils.to_type(...), is that scalars
are wrapped into (1,0) arrays. This is desirable when passing
the numpy complex data type to C routines and complex scalars aren't
ha... | 2.466162 | 3.575888 | 0.689664 |
# convert_type = type(np.array([0], upcast_type)[0])
for i in range(len(varlist)):
# convert scalars to complex
if np.isscalar(varlist[i]):
varlist[i] = np.array([varlist[i]], upcast_type)[0]
else:
# convert sparse and dense mats to complex
try:... | def to_type(upcast_type, varlist) | Loop over all elements of varlist and convert them to upcasttype.
Parameters
----------
upcast_type : data type
e.g. complex, float64 or complex128
varlist : list
list may contain arrays, mat's, sparse matrices, or scalars
the elements may be float, int or complex
Returns
... | 3.169989 | 3.582437 | 0.884869 |
# if not isspmatrix(A):
if not (isspmatrix_csr(A) or isspmatrix_csc(A) or isspmatrix_bsr(A)):
warn('Implicit conversion to sparse matrix')
A = csr_matrix(A)
# critical to sort the indices of A
A.sort_indices()
if norm_eq == 1:
# This transpose involves almost no work, u... | def get_diagonal(A, norm_eq=False, inv=False) | Return the diagonal or inverse of diagonal for A, (A.H A) or (A A.H).
Parameters
----------
A : {dense or sparse matrix}
e.g. array, matrix, csr_matrix, ...
norm_eq : {0, 1, 2}
0 ==> D = diag(A)
1 ==> D = diag(A.H A)
2 ==> D = diag(A A.H)
inv : {True, False}
... | 3.53531 | 3.715309 | 0.951552 |
if not isspmatrix(A):
raise TypeError('Expected sparse matrix')
if A.shape[0] != A.shape[1]:
raise ValueError("Expected square matrix")
if sp.mod(A.shape[0], blocksize) != 0:
raise ValueError("blocksize and A.shape must be compatible")
# If the block diagonal of A already e... | def get_block_diag(A, blocksize, inv_flag=True) | Return the block diagonal of A, in array form.
Parameters
----------
A : csr_matrix
assumed to be square
blocksize : int
square block size for the diagonal
inv_flag : bool
if True, return the inverse of the block diagonal
Returns
-------
block_diag : array
... | 2.577073 | 2.66388 | 0.967413 |
if blocksize == 1:
return A
elif sp.mod(A.shape[0], blocksize) != 0:
raise ValueError("Incompatible blocksize")
A = A.tobsr(blocksize=(blocksize, blocksize))
A.sort_indices()
subI = (np.ones(A.indices.shape), A.indices, A.indptr)
shape = (int(A.shape[0]/A.blocksize[0]),
... | def amalgamate(A, blocksize) | Amalgamate matrix A.
Parameters
----------
A : csr_matrix
Matrix to amalgamate
blocksize : int
blocksize to use while amalgamating
Returns
-------
A_amal : csr_matrix
Amalgamated matrix A, first, convert A to BSR with square blocksize
and then return a CSR ... | 3.27873 | 3.585194 | 0.91452 |
data = np.ones((A.indices.shape[0], RowsPerBlock, ColsPerBlock))
blockI = (data, A.indices, A.indptr)
shape = (RowsPerBlock*A.shape[0], ColsPerBlock*A.shape[1])
return bsr_matrix(blockI, shape=shape) | def UnAmal(A, RowsPerBlock, ColsPerBlock) | Unamalgamate a CSR A with blocks of 1's.
This operation is equivalent to
replacing each entry of A with ones(RowsPerBlock, ColsPerBlock), i.e., this
is equivalent to setting all of A's nonzeros to 1 and then doing a
Kronecker product between A and ones(RowsPerBlock, ColsPerBlock).
Parameters
-... | 3.181842 | 3.917473 | 0.812218 |
table_str = '\n'
# sometimes, the table will be passed in as (title, table)
if isinstance(table, tuple):
title = table[0]
table = table[1]
# Calculate each column's width
colwidths = []
for i in range(len(table)):
# extend colwidths for row i
for k in range... | def print_table(table, title='', delim='|', centering='center', col_padding=2,
header=True, headerchar='-') | Print a table from a list of lists representing the rows of a table.
Parameters
----------
table : list
list of lists, e.g. a table with 3 columns and 2 rows could be
[ ['0,0', '0,1', '0,2'], ['1,0', '1,1', '1,2'] ]
title : string
Printed centered above the table
delim : str... | 2.560843 | 2.730898 | 0.937729 |
from pyamg import relaxation
from scipy.sparse.linalg.interface import LinearOperator
import pyamg.multilevel
def unpack_arg(v):
if isinstance(v, tuple):
return v[0], v[1]
else:
return v, {}
# setup variables
accepted_methods = ['gauss_seidel', 'blo... | def relaxation_as_linear_operator(method, A, b) | Create a linear operator that applies a relaxation method for the given right-hand-side.
Parameters
----------
methods : {tuple or string}
Relaxation descriptor: Each tuple must be of the form ('method','opts')
where 'method' is the name of a supported smoother, e.g., gauss_seidel,
... | 4.213129 | 4.379918 | 0.96192 |
if not isspmatrix_bsr(C) and not isspmatrix_csr(C):
raise TypeError('Expected bsr_matrix or csr_matrix for C')
if C.shape[1] != B.shape[0]:
raise TypeError('Expected matching dimensions such that C*B')
# Problem parameters
if isspmatrix_bsr(C):
ColsPerBlock = C.blocksize[1]... | def compute_BtBinv(B, C) | Create block inverses.
Helper function that creates inv(B_i.T B_i) for each block row i in C,
where B_i is B restricted to the sparsity pattern of block row i.
Parameters
----------
B : {array}
(M,k) array, typically near-nullspace modes for coarse grid, i.e., B_c.
C : {csr_matrix, bsr... | 4.06827 | 4.049902 | 1.004535 |
r
# Find the diagonally dominant rows in A.
A_abs = A.copy()
A_abs.data = np.abs(A_abs.data)
D_abs = get_diagonal(A_abs, norm_eq=0, inv=False)
diag_dom_rows = (D_abs > (theta*(A_abs*np.ones((A_abs.shape[0],),
dtype=A_abs) - D_abs)))
# Accou... | def eliminate_diag_dom_nodes(A, C, theta=1.02) | r"""Eliminate diagonally dominance.
Helper function that eliminates diagonally dominant rows and cols from A
in the separate matrix C. This is useful because it eliminates nodes in C
which we don't want coarsened. These eliminated nodes in C just become
the rows and columns of the identity.
Para... | 3.741065 | 3.610042 | 1.036294 |
if not isspmatrix_csr(S):
raise TypeError('expected csr_matrix')
if S.shape[0] != S.shape[1]:
raise ValueError('expected square matrix, shape=%s' % (S.shape,))
S = coo_matrix(S)
mask = S.row != S.col
S.row = S.row[mask]
S.col = S.col[mask]
S.data = S.data[mask]
re... | def remove_diagonal(S) | Remove the diagonal of the matrix S.
Parameters
----------
S : csr_matrix
Square matrix
Returns
-------
S : csr_matrix
Strength matrix with the diagonal removed
Notes
-----
This is needed by all the splitting routines which operate on matrix graphs
with an assu... | 2.166274 | 2.890501 | 0.749446 |
if not isspmatrix_csr(S):
raise TypeError('expected csr_matrix')
# Scale S by the largest magnitude entry in each row
largest_row_entry = np.zeros((S.shape[0],), dtype=S.dtype)
pyamg.amg_core.maximum_row_value(S.shape[0], largest_row_entry,
S.indptr, S.... | def scale_rows_by_largest_entry(S) | Scale each row in S by it's largest in magnitude entry.
Parameters
----------
S : csr_matrix
Returns
-------
S : csr_matrix
Each row has been scaled by it's largest in magnitude entry
Examples
--------
>>> from pyamg.gallery import poisson
>>> from pyamg.util.utils imp... | 3.042825 | 3.55086 | 0.856926 |
if isinstance(to_levelize, tuple):
if to_levelize[0] == 'predefined':
to_levelize = [to_levelize]
max_levels = 2
max_coarse = 0
else:
to_levelize = [to_levelize for i in range(max_levels-1)]
elif isinstance(to_levelize, str):
if to_le... | def levelize_strength_or_aggregation(to_levelize, max_levels, max_coarse) | Turn parameter into a list per level.
Helper function to preprocess the strength and aggregation parameters
passed to smoothed_aggregation_solver and rootnode_solver.
Parameters
----------
to_levelize : {string, tuple, list}
Parameter to preprocess, i.e., levelize and convert to a level-by... | 2.766921 | 2.828598 | 0.978195 |
if isinstance(to_levelize, tuple) or isinstance(to_levelize, str):
to_levelize = [to_levelize for i in range(max_levels)]
elif isinstance(to_levelize, list):
if len(to_levelize) < max_levels:
mlz = max_levels - len(to_levelize)
toext = [to_levelize[-1] for i in range... | def levelize_smooth_or_improve_candidates(to_levelize, max_levels) | Turn parameter in to a list per level.
Helper function to preprocess the smooth and improve_candidates
parameters passed to smoothed_aggregation_solver and rootnode_solver.
Parameters
----------
to_levelize : {string, tuple, list}
Parameter to preprocess, i.e., levelize and convert to a le... | 2.235112 | 2.358583 | 0.94765 |
if not isspmatrix(A):
raise ValueError("Sparse matrix input needed")
if isspmatrix_bsr(A):
blocksize = A.blocksize
Aformat = A.format
if (theta < 0) or (theta >= 1.0):
raise ValueError("theta must be in [0,1)")
# Apply drop-tolerance to each column of A, which is most ... | def filter_matrix_columns(A, theta) | Filter each column of A with tol.
i.e., drop all entries in column k where
abs(A[i,k]) < tol max( abs(A[:,k]) )
Parameters
----------
A : sparse_matrix
theta : float
In range [0,1) and defines drop-tolerance used to filter the columns
of A
Returns
-------
A_fi... | 3.541747 | 3.445539 | 1.027922 |
if not isspmatrix(A):
raise ValueError("Sparse matrix input needed")
if isspmatrix_bsr(A):
blocksize = A.blocksize
Aformat = A.format
A = A.tocsr()
if (theta < 0) or (theta >= 1.0):
raise ValueError("theta must be in [0,1)")
# Apply drop-tolerance to each row of A.... | def filter_matrix_rows(A, theta) | Filter each row of A with tol.
i.e., drop all entries in row k where
abs(A[i,k]) < tol max( abs(A[:,k]) )
Parameters
----------
A : sparse_matrix
theta : float
In range [0,1) and defines drop-tolerance used to filter the row of A
Returns
-------
A_filter : sparse_matr... | 3.22081 | 3.146634 | 1.023573 |
if not isspmatrix(A):
raise ValueError("Sparse matrix input needed")
if isspmatrix_bsr(A):
blocksize = A.blocksize
if isspmatrix_csr(A):
A = A.copy() # don't modify A in-place
Aformat = A.format
A = A.tocsr()
nz_per_row = int(nz_per_row)
# Truncate rows of A,... | def truncate_rows(A, nz_per_row) | Truncate the rows of A by keeping only the largest in magnitude entries in each row.
Parameters
----------
A : sparse_matrix
nz_per_row : int
Determines how many entries in each row to keep
Returns
-------
A : sparse_matrix
Each row has been truncated to at most nz_per_row... | 3.0361 | 3.365232 | 0.902196 |
@functools.wraps(function)
def wrapper(self, *args, **kwargs):
if not self.access_token():
raise MissingAccessTokenError
return function(self, *args, **kwargs)
return wrapper | def require_auth(function) | A decorator that wraps the passed in function and raises exception
if access token is missing | 2.265151 | 2.167509 | 1.045048 |
@functools.wraps(function)
def wrapper(self, *args, **kwargs):
if self.randomize:
self.randomize_headers()
return function(self, *args, **kwargs)
return wrapper | def randomizable(function) | A decorator which randomizes requests if needed | 2.207891 | 1.883316 | 1.172342 |
r = self._session.get(API_URL + "/logins/me")
r.raise_for_status()
return r.json() | def get_profile(self) | Get my own profile | 5.87077 | 4.688266 | 1.252226 |
params = {
'year': str(starting_year),
'listing_id': str(listing_id),
'_format': 'with_conditions',
'count': str(calendar_months),
'month': str(starting_month)
}
r = self._session.get(API_URL + "/calendar_months", params=param... | def get_calendar(self, listing_id, starting_month=datetime.datetime.now().month, starting_year=datetime.datetime.now().year, calendar_months=12) | Get availability calendar for a given listing | 3.123988 | 3.028315 | 1.031593 |
params = {
'_order': 'language_country',
'listing_id': str(listing_id),
'_offset': str(offset),
'role': 'all',
'_limit': str(limit),
'_format': 'for_mobile_client',
}
print(self._session.headers)
r = self.... | def get_reviews(self, listing_id, offset=0, limit=20) | Get reviews for a given listing | 4.313791 | 4.255585 | 1.013677 |
params = {
'_format': 'host_calendar_detailed'
}
starting_date_str = starting_date.strftime("%Y-%m-%d")
ending_date_str = (
starting_date + datetime.timedelta(days=30)).strftime("%Y-%m-%d")
r = self._session.get(API_URL + "/calendars/{}/{}/{}".f... | def get_listing_calendar(self, listing_id, starting_date=datetime.datetime.now(), calendar_months=6) | Get host availability calendar for a given listing | 2.977846 | 2.727091 | 1.09195 |
params = {
'is_guided_search': 'true',
'version': '1.3.9',
'section_offset': '0',
'items_offset': str(offset),
'adults': '0',
'screen_size': 'small',
'source': 'explore_tabs',
'items_per_grid': str(items_per... | def get_homes(self, query=None, gps_lat=None, gps_lng=None, offset=0, items_per_grid=8) | Search listings with
* Query (e.g. query="Lisbon, Portugal") or
* Location (e.g. gps_lat=55.6123352&gps_lng=37.7117917) | 3.511722 | 3.411924 | 1.02925 |
'''
Note:
If the shellcode starts with '66' controls, it needs to be changed to add [BITS 32] or
[BITS 64] to the start.
To use:
convert()
'''
code = code.replace(' ', '')
lines = []
for l in code.splitlines(False):
lines.app... | def convert(self, code) | Note:
If the shellcode starts with '66' controls, it needs to be changed to add [BITS 32] or
[BITS 64] to the start.
To use:
convert("""
55
53
50
BDE97F071E
FFD5
BDD67B071E
FFD5
5D
... | 8.868506 | 2.658297 | 3.336161 |
'''
:return list(tuple(method_name, docstring, parameters, completion_type))
method_name: str
docstring: str
parameters: str -- i.e.: "(a, b)"
completion_type is an int
See: _pydev_bundle._pydev_imports_tipper for TYPE_ constants
'''
if frame is None:
return []
# No... | def generate_completions(frame, act_tok) | :return list(tuple(method_name, docstring, parameters, completion_type))
method_name: str
docstring: str
parameters: str -- i.e.: "(a, b)"
completion_type is an int
See: _pydev_bundle._pydev_imports_tipper for TYPE_ constants | 5.750112 | 3.559192 | 1.615567 |
'''
Extracts the token a qualifier from the text given the line/colum
(see test_extract_token_and_qualifier for examples).
:param unicode text:
:param int line: 0-based
:param int column: 0-based
'''
# Note: not using the tokenize module because text should be unicode and
# line/col... | def extract_token_and_qualifier(text, line=0, column=0) | Extracts the token a qualifier from the text given the line/colum
(see test_extract_token_and_qualifier for examples).
:param unicode text:
:param int line: 0-based
:param int column: 0-based | 3.061688 | 2.485926 | 1.231609 |
if self.use_main_ns:
# In pydev this option should never be used
raise RuntimeError('Namespace must be provided!')
self.namespace = __main__.__dict__ # @UndefinedVariable
if "." in text:
return self.attr_matches(text)
else:
r... | def complete(self, text) | Return the next possible completion for 'text'.
This is called successively with state == 0, 1, 2, ... until it
returns None. The completion should begin with 'text'. | 10.669305 | 11.48894 | 0.928659 |
def get_item(obj, attr):
return obj[attr]
a = {}
for dict_with_comps in [__builtin__.__dict__, self.namespace, self.global_namespace]: # @UndefinedVariable
a.update(dict_with_comps)
filter = _StartsWithFilter(text)
return dir2(a, a.keys(), g... | def global_matches(self, text) | Compute matches when text is a simple name.
Return a list of all keywords, built-in functions and names currently
defined in self.namespace or self.global_namespace that match. | 9.751831 | 8.102592 | 1.203545 |
import re
# Another option, seems to work great. Catches things like ''.<tab>
m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text) # @UndefinedVariable
if not m:
return []
expr, attr = m.group(1, 3)
try:
obj = eval(expr, self.namespace)
... | def attr_matches(self, text) | Compute matches when text contains a dot.
Assuming the text is of the form NAME.NAME....[NAME], and is
evaluatable in self.namespace or self.global_namespace, it will be
evaluated and its attributes (as revealed by dir()) are used as
possible completions. (For class instances, class me... | 6.728119 | 5.362571 | 1.254644 |
'''
:param dict fmt:
Format expected by the DAP (keys: 'hex': bool, 'rawString': bool)
'''
safe_repr = SafeRepr()
if fmt is not None:
safe_repr.convert_to_hex = fmt.get('hex', False)
safe_repr.raw_value = fmt.get('rawString', False)
ty... | def get_var_data(self, fmt=None) | :param dict fmt:
Format expected by the DAP (keys: 'hex': bool, 'rawString': bool) | 4.6532 | 3.586666 | 1.297361 |
'''
:param thread_id:
The thread id to be used for this frame.
:param frame:
The topmost frame which is suspended at the given thread.
:param frame_id_to_lineno:
If available, the line number for the frame will be gotten from this dict,
o... | def track(self, thread_id, frame, frame_id_to_lineno, frame_custom_thread_id=None) | :param thread_id:
The thread id to be used for this frame.
:param frame:
The topmost frame which is suspended at the given thread.
:param frame_id_to_lineno:
If available, the line number for the frame will be gotten from this dict,
otherwise frame.f_lin... | 3.914327 | 2.290846 | 1.708682 |
'''
We can't evaluate variable references values on any thread, only in the suspended
thread (the main reason for this is that in UI frameworks inspecting a UI object
from a different thread can potentially crash the application).
:param int variable_reference:
The v... | def get_thread_id_for_variable_reference(self, variable_reference) | We can't evaluate variable references values on any thread, only in the suspended
thread (the main reason for this is that in UI frameworks inspecting a UI object
from a different thread can potentially crash the application).
:param int variable_reference:
The variable reference (c... | 7.912347 | 1.584166 | 4.994644 |
'''
:raises KeyError
'''
frames_tracker = self._get_tracker_for_variable_reference(variable_reference)
if frames_tracker is None:
raise KeyError()
return frames_tracker.get_variable(variable_reference) | def get_variable(self, variable_reference) | :raises KeyError | 4.573453 | 3.963077 | 1.154016 |
matplotlib = sys.modules['matplotlib']
# WARNING: this assumes matplotlib 1.1 or newer!!
backend = matplotlib.rcParams['backend']
# In this case, we need to find what the appropriate gui selection call
# should be for IPython, so we can activate inputhook accordingly
gui = backend2gui.get(b... | def find_gui_and_backend() | Return the gui and mpl backend. | 12.112193 | 11.305665 | 1.071338 |
matplotlib = sys.modules['matplotlib']
from matplotlib.rcsetup import interactive_bk, non_interactive_bk # @UnresolvedImport
if backend in interactive_bk:
return True
elif backend in non_interactive_bk:
return False
else:
return matplotlib.is_interactive() | def is_interactive_backend(backend) | Check if backend is interactive | 3.59159 | 3.372241 | 1.065046 |
matplotlib = sys.modules['matplotlib']
def patched_use(*args, **kwargs):
matplotlib.real_use(*args, **kwargs)
gui, backend = find_gui_and_backend()
enable_gui_function(gui)
matplotlib.real_use = matplotlib.use
matplotlib.use = patched_use | def patch_use(enable_gui_function) | Patch matplotlib function 'use' | 3.644461 | 3.432866 | 1.061638 |
matplotlib = sys.modules['matplotlib']
def patched_is_interactive():
return matplotlib.rcParams['interactive']
matplotlib.real_is_interactive = matplotlib.is_interactive
matplotlib.is_interactive = patched_is_interactive | def patch_is_interactive() | Patch matplotlib function 'use' | 3.746402 | 3.174348 | 1.180212 |
matplotlib = sys.modules['matplotlib']
gui, backend = find_gui_and_backend()
is_interactive = is_interactive_backend(backend)
if is_interactive:
enable_gui_function(gui)
if not matplotlib.is_interactive():
sys.stdout.write("Backend %s is interactive backend. Turning inte... | def activate_matplotlib(enable_gui_function) | Set interactive to True for interactive backends.
enable_gui_function - Function which enables gui, should be run in the main thread. | 2.833866 | 2.858743 | 0.991298 |
# don't wrap twice
if hasattr(func, 'called'):
return func
def wrapper(*args, **kw):
wrapper.called = False
out = func(*args, **kw)
wrapper.called = True
return out
wrapper.called = False
wrapper.__doc__ = func.__doc__
return wrapper | def flag_calls(func) | Wrap a function to detect and flag when it gets called.
This is a decorator which takes a function and wraps it in a function with
a 'called' attribute. wrapper.called is initialized to False.
The wrapper.called attribute is set to False right before each call to the
wrapped function, so if the call f... | 2.854527 | 2.705409 | 1.055118 |
'''
Checks whether the file can be read by the coverage module. This is especially
needed for .pyx files and .py files with syntax errors.
'''
import os
is_valid = False
if os.path.isfile(path) and not os.path.splitext(path)[1] == '.pyx':
try:
with open(path, 'rb') as f:... | def is_valid_py_file(path) | Checks whether the file can be read by the coverage module. This is especially
needed for .pyx files and .py files with syntax errors. | 3.624357 | 1.927202 | 1.880632 |
pid = self.get_pid()
system = self.debug.system
if system.has_process(pid):
process = system.get_process(pid)
else:
# XXX HACK
# The process object was missing for some reason, so make a new one.
process = Process(pid)
... | def get_process(self) | @see: L{get_pid}
@rtype: L{Process}
@return: Process where the event occured. | 5.835752 | 6.076789 | 0.960335 |
tid = self.get_tid()
process = self.get_process()
if process.has_thread(tid):
thread = process.get_thread(tid)
else:
# XXX HACK
# The thread object was missing for some reason, so make a new one.
thread = Thread(tid)
... | def get_thread(self) | @see: L{get_tid}
@rtype: L{Thread}
@return: Thread where the event occured. | 4.40941 | 4.45682 | 0.989362 |
return bool( self.raw.u.Exception.ExceptionRecord.ExceptionFlags & \
win32.EXCEPTION_NONCONTINUABLE ) | def is_noncontinuable(self) | @see: U{http://msdn.microsoft.com/en-us/library/aa363082(VS.85).aspx}
@rtype: bool
@return: C{True} if the exception is noncontinuable,
C{False} otherwise.
Attempting to continue a noncontinuable exception results in an
EXCEPTION_NONCONTINUABLE_EXCEPTION exception ... | 26.469658 | 13.450535 | 1.967926 |
if index < 0 or index > win32.EXCEPTION_MAXIMUM_PARAMETERS:
raise IndexError("Array index out of range: %s" % repr(index))
info = self.raw.u.Exception.ExceptionRecord.ExceptionInformation
value = info[index]
if value is None:
value = 0
return valu... | def get_exception_information(self, index) | @type index: int
@param index: Index into the exception information block.
@rtype: int
@return: Exception information DWORD. | 5.544718 | 5.073977 | 1.092776 |
if self.get_exception_code() not in (win32.EXCEPTION_ACCESS_VIOLATION,
win32.EXCEPTION_IN_PAGE_ERROR, win32.EXCEPTION_GUARD_PAGE):
msg = "This method is not meaningful for %s."
raise NotImplementedError(msg % self.get_exception_name())
return self.get... | def get_fault_type(self) | @rtype: int
@return: Access violation type.
Should be one of the following constants:
- L{win32.EXCEPTION_READ_FAULT}
- L{win32.EXCEPTION_WRITE_FAULT}
- L{win32.EXCEPTION_EXECUTE_FAULT}
@note: This method is only meaningful for access violation excep... | 4.764897 | 3.040203 | 1.567296 |
if self.get_exception_code() != win32.EXCEPTION_IN_PAGE_ERROR:
msg = "This method is only meaningful "\
"for in-page memory error exceptions."
raise NotImplementedError(msg)
return self.get_exception_information(2) | def get_ntstatus_code(self) | @rtype: int
@return: NTSTATUS status code that caused the exception.
@note: This method is only meaningful for in-page memory error
exceptions.
@raise NotImplementedError: Not an in-page memory error. | 10.102329 | 4.159399 | 2.428796 |
# The first EXCEPTION_RECORD is contained in EXCEPTION_DEBUG_INFO.
# The remaining EXCEPTION_RECORD structures are linked by pointers.
nested = list()
record = self.raw.u.Exception
while True:
record = record.ExceptionRecord
if not record:
... | def get_raw_exception_record_list(self) | Traverses the exception record linked list and builds a Python list.
Nested exception records are received for nested exceptions. This
happens when an exception is raised in the debugee while trying to
handle a previous exception.
@rtype: list( L{win32.EXCEPTION_RECORD} )
@ret... | 10.197886 | 8.064758 | 1.2645 |
# The list always begins with ourselves.
# Just put a reference to "self" as the first element,
# and start looping from the second exception record.
nested = [ self ]
raw = self.raw
dwDebugEventCode = raw.dwDebugEventCode
dwProcessId = raw.dwProcess... | def get_nested_exceptions(self) | Traverses the exception record linked list and builds a Python list.
Nested exception records are received for nested exceptions. This
happens when an exception is raised in the debugee while trying to
handle a previous exception.
@rtype: list( L{ExceptionEvent} )
@return:
... | 4.43859 | 4.058439 | 1.093669 |
eventClass = cls.eventClasses.get(raw.dwDebugEventCode, cls.baseEvent)
return eventClass(debug, raw) | def get(cls, debug, raw) | @type debug: L{Debug}
@param debug: Debug object that received the event.
@type raw: L{DEBUG_EVENT}
@param raw: Raw DEBUG_EVENT structure as used by the Win32 API.
@rtype: L{Event}
@returns: An Event object or one of it's subclasses,
depending on the event type. | 8.849003 | 6.087083 | 1.453735 |
result = []
if self.__apiHooks:
path = event.get_module().get_filename()
if path:
lib_name = PathOperations.pathname_to_filename(path).lower()
for hook_lib, hook_api_list in compat.iteritems(self.__apiHooks):
if hook_li... | def __get_hooks_for_dll(self, event) | Get the requested API hooks for the current DLL.
Used by L{__hook_dll} and L{__unhook_dll}. | 4.93206 | 4.450525 | 1.108197 |
debug = event.debug
pid = event.get_pid()
for hook_api_stub in self.__get_hooks_for_dll(event):
hook_api_stub.hook(debug, pid) | def __hook_dll(self, event) | Hook the requested API calls (in self.apiHooks).
This method is called automatically whenever a DLL is loaded. | 6.983165 | 7.037913 | 0.992221 |
debug = event.debug
pid = event.get_pid()
for hook_api_stub in self.__get_hooks_for_dll(event):
hook_api_stub.unhook(debug, pid) | def __unhook_dll(self, event) | Unhook the requested API calls (in self.apiHooks).
This method is called automatically whenever a DLL is unloaded. | 6.457569 | 6.391737 | 1.010299 |
eventCode = event.get_event_code()
pid = event.get_pid()
handler = self.forward.get(pid, None)
if handler is None:
handler = self.cls(*self.argv, **self.argd)
if eventCode != win32.EXIT_PROCESS_DEBUG_EVENT:
self.forward[pid] = handler
... | def event(self, event) | Forwards events to the corresponding instance of your event handler
for this process.
If you subclass L{EventSift} and reimplement this method, no event
will be forwarded at all unless you call the superclass implementation.
If your filtering is based on the event type, there's a much ... | 3.924202 | 4.257034 | 0.921816 |
if eventHandler is not None and not callable(eventHandler):
raise TypeError("Event handler must be a callable object")
try:
wrong_type = issubclass(eventHandler, EventHandler)
except TypeError:
wrong_type = False
if wrong_type:
cla... | def set_event_handler(self, eventHandler) | Set the event handler.
@warn: This is normally not needed. Use with care!
@type eventHandler: L{EventHandler}
@param eventHandler: New event handler object, or C{None}.
@rtype: L{EventHandler}
@return: Previous event handler object, or C{None}.
@raise TypeError: The... | 3.384156 | 3.474753 | 0.973927 |
eventCode = event.get_event_code()
method = getattr(eventHandler, 'event', fallback)
if eventCode == win32.EXCEPTION_DEBUG_EVENT:
method = getattr(eventHandler, 'exception', method)
method = getattr(eventHandler, event.eventMethod, method)
return method | def get_handler_method(eventHandler, event, fallback=None) | Retrieves the appropriate callback method from an L{EventHandler}
instance for the given L{Event} object.
@type eventHandler: L{EventHandler}
@param eventHandler:
Event handler object whose methods we are examining.
@type event: L{Event}
@param event: Debugging ev... | 4.929862 | 5.507479 | 0.895121 |
returnValue = None
bCallHandler = True
pre_handler = None
post_handler = None
eventCode = event.get_event_code()
# Get the pre and post notification methods for exceptions.
# If not found, the following steps take care of that.
if eventCode ... | def dispatch(self, event) | Sends event notifications to the L{Debug} object and
the L{EventHandler} object provided by the user.
The L{Debug} object will forward the notifications to it's contained
snapshot objects (L{System}, L{Process}, L{Thread} and L{Module}) when
appropriate.
@warning: This method i... | 2.73363 | 2.821996 | 0.968687 |
for skip_path in config['skip']:
if posixpath.abspath(posixpath.join(path, filename)) == posixpath.abspath(skip_path.replace('\\', '/')):
return True
position = os.path.split(filename)
while position[1]:
if position[1] in config['skip']:
return True
posi... | def should_skip(filename, config, path='/') | Returns True if the file should be skipped based on the passed in settings. | 2.588725 | 2.558114 | 1.011966 |
'''formats an argument to be shown
'''
s = str(arg)
dot = s.rfind('.')
if dot >= 0:
s = s[dot + 1:]
s = s.replace(';', '')
s = s.replace('[]', 'Array')
if len(s) > 0:
c = s[0].lower()
s = c + s[1:]
return s | def format_arg(arg) | formats an argument to be shown | 3.706898 | 3.738062 | 0.991663 |
'''
Runs a function as a pydevd daemon thread (without any tracing in place).
'''
t = PyDBDaemonThread(target_and_args=(func, args, kwargs))
t.name = '%s (pydevd daemon thread)' % (func.__name__,)
t.start()
return t | def run_as_pydevd_daemon_thread(func, *args, **kwargs) | Runs a function as a pydevd daemon thread (without any tracing in place). | 5.186083 | 3.383881 | 1.532584 |
''' binds to a port, waits for the debugger to connect '''
s = socket(AF_INET, SOCK_STREAM)
s.settimeout(None)
try:
from socket import SO_REUSEPORT
s.setsockopt(SOL_SOCKET, SO_REUSEPORT, 1)
except ImportError:
s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
s.bind(('', port))... | def start_server(port) | binds to a port, waits for the debugger to connect | 3.139899 | 2.971517 | 1.056665 |
''' connects to a host/port '''
pydev_log.info("Connecting to %s:%s", host, port)
s = socket(AF_INET, SOCK_STREAM)
# Set TCP keepalive on an open socket.
# It activates after 1 second (TCP_KEEPIDLE,) of idleness,
# then sends a keepalive ping once every 3 seconds (TCP_KEEPINTVL),
# and... | def start_client(host, port) | connects to a host/port | 2.54094 | 2.552558 | 0.995448 |
'''
:param VariablesRequest request:
'''
arguments = request.arguments # : :type arguments: VariablesArguments
variables_reference = arguments.variablesReference
fmt = arguments.format
if hasattr(fmt, 'to_dict'):
fmt = fmt.to_dict()
variables = []
try:
variable ... | def internal_get_variable_json(py_db, request) | :param VariablesRequest request: | 5.569073 | 5.160079 | 1.079261 |
''' Changes the value of a variable '''
try:
frame = dbg.find_frame(thread_id, frame_id)
if frame is not None:
result = pydevd_vars.change_attr_expression(frame, attr, value, dbg)
else:
result = None
xml = "<xml>"
xml += pydevd_xml.var_to_xml(resul... | def internal_change_variable(dbg, seq, thread_id, frame_id, scope, attr, value) | Changes the value of a variable | 3.642255 | 3.73935 | 0.974034 |
'''
The pydevd_vars.change_attr_expression(thread_id, frame_id, attr, value, dbg) can only
deal with changing at a frame level, so, currently changing the contents of something
in a different scope is currently not supported.
TODO: make the resolvers structure resolve the name and change accordingl... | def internal_change_variable_json(py_db, request) | The pydevd_vars.change_attr_expression(thread_id, frame_id, attr, value, dbg) can only
deal with changing at a frame level, so, currently changing the contents of something
in a different scope is currently not supported.
TODO: make the resolvers structure resolve the name and change accordingly -- for ins... | 5.144481 | 2.909221 | 1.768336 |
''' Converts request into python variable '''
try:
frame = dbg.find_frame(thread_id, frame_id)
if frame is not None:
hidden_ns = pydevconsole.get_ipython_hidden_vars()
xml = "<xml>"
xml += pydevd_xml.frame_vars_to_xml(frame.f_locals, hidden_ns)
del... | def internal_get_frame(dbg, seq, thread_id, frame_id) | Converts request into python variable | 3.7826 | 3.565037 | 1.061027 |
''' gets the valid line numbers for use with set next statement '''
try:
frame = dbg.find_frame(thread_id, frame_id)
if frame is not None:
code = frame.f_code
xml = "<xml>"
if hasattr(code, 'co_lnotab'):
lineno = code.co_firstlineno
... | def internal_get_next_statement_targets(dbg, seq, thread_id, frame_id) | gets the valid line numbers for use with set next statement | 2.608552 | 2.397619 | 1.087976 |
'''
:param EvaluateRequest request:
'''
# : :type arguments: EvaluateArguments
arguments = request.arguments
expression = arguments.expression
frame_id = arguments.frameId
context = arguments.context
fmt = arguments.format
if hasattr(fmt, 'to_dict'):
fmt = fmt.to_dict()
... | def internal_evaluate_expression_json(py_db, request, thread_id) | :param EvaluateRequest request: | 3.659287 | 3.571719 | 1.024517 |
''' gets the value of a variable '''
try:
frame = dbg.find_frame(thread_id, frame_id)
if frame is not None:
result = pydevd_vars.evaluate_expression(dbg, frame, expression, is_exec)
if attr_to_set_result != "":
pydevd_vars.change_attr_expression(frame, att... | def internal_evaluate_expression(dbg, seq, thread_id, frame_id, expression, is_exec, trim_if_too_big, attr_to_set_result) | gets the value of a variable | 2.912277 | 2.860282 | 1.018179 |
'''
Note that if the column is >= 0, the act_tok is considered text and the actual
activation token/qualifier is computed in this command.
'''
try:
remove_path = None
try:
qualifier = u''
if column >= 0:
token_and_qualifier = extract_token_and_... | def internal_get_completions(dbg, seq, thread_id, frame_id, act_tok, line=-1, column=-1) | Note that if the column is >= 0, the act_tok is considered text and the actual
activation token/qualifier is computed in this command. | 3.631991 | 3.018991 | 1.203048 |
''' Fetch the variable description stub from the debug console
'''
try:
frame = dbg.find_frame(thread_id, frame_id)
description = pydevd_console.get_description(frame, thread_id, frame_id, expression)
description = pydevd_xml.make_valid_xml_value(quote(description, '/>_= \t'))
... | def internal_get_description(dbg, seq, thread_id, frame_id, expression) | Fetch the variable description stub from the debug console | 4.436935 | 4.015064 | 1.105072 |
'''
:return ExceptionInfoResponse
'''
thread = pydevd_find_thread_by_id(thread_id)
additional_info = set_additional_thread_info(thread)
topmost_frame = additional_info.get_topmost_frame(thread)
frames = []
exc_type = None
exc_desc = None
if topmost_frame is not None:
fra... | def build_exception_info_response(dbg, thread_id, request_seq, set_additional_thread_info, iter_visible_frames_info, max_frames) | :return ExceptionInfoResponse | 3.106526 | 3.104973 | 1.0005 |
''' Fetch exception details
'''
try:
response = build_exception_info_response(dbg, thread_id, request.seq, set_additional_thread_info, iter_visible_frames_info, max_frames)
except:
exc = get_exception_traceback_str()
response = pydevd_base_schema.build_response(request, kwargs={
... | def internal_get_exception_details_json(dbg, request, thread_id, max_frames, set_additional_thread_info=None, iter_visible_frames_info=None) | Fetch exception details | 5.503833 | 5.636117 | 0.976529 |
''' just loop and write responses '''
try:
while True:
try:
try:
cmd = self.cmdQueue.get(1, 0.1)
except _queue.Empty:
if self.killReceived:
try:
... | def _on_run(self) | just loop and write responses | 8.817436 | 7.890079 | 1.117535 |
'''By default, it must be in the same thread to be executed
'''
return self.thread_id == thread_id or self.thread_id.endswith('|' + thread_id) | def can_be_executed_by(self, thread_id) | By default, it must be in the same thread to be executed | 7.048354 | 4.146218 | 1.699948 |
''' Converts request into python variable '''
try:
xml = StringIO.StringIO()
xml.write("<xml>")
_typeName, val_dict = pydevd_vars.resolve_compound_variable_fields(
dbg, self.thread_id, self.frame_id, self.scope, self.attributes)
if val_dict... | def do_it(self, dbg) | Converts request into python variable | 5.299749 | 5.038902 | 1.051767 |
''' Create an XML for console output, error and more (true/false)
<xml>
<output message=output_message></output>
<error message=error_message></error>
<more>true/false</more>
</xml>
'''
try:
frame = dbg.find_frame(self.thread_id, se... | def do_it(self, dbg) | Create an XML for console output, error and more (true/false)
<xml>
<output message=output_message></output>
<error message=error_message></error>
<more>true/false</more>
</xml> | 4.104992 | 2.948045 | 1.392445 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.