code
stringlengths
52
7.75k
docs
stringlengths
1
5.85k
def committor_forward(self, a, b): r u = np.zeros(self.dim) g = np.zeros(self.dim - 1) g[0] = 1.0 g[1:] = np.cumprod(self.q[1:-1] / self.p[1:-1]) """If a and b are equal the event T_b<T_a is impossible for any starting state x so that the committor is ...
r"""Forward committor for birth-and-death-chain. The forward committor is the probability to hit state b before hitting state a starting in state x, u_x=P_x(T_b<T_a) T_i is the first arrival time of the chain to state i, T_i = inf( t>0 | X_t=i ) Parameters ...
def flux(self, a, b): r # if b<=a: # raise ValueError("State index b has to be strictly larger than state index a") qminus = self.committor_backward(a, b) qplus = self.committor_forward(a, b) P = self.transition_matrix() pi = self.stationary_distribution() ...
r"""The flux network for the reaction from A=[0,...,a] => B=[b,...,M]. Parameters ---------- a : int State index b : int State index Returns ------- flux : (M, M) ndarray Matrix of flux values between pairs of states.
def netflux(self, a, b): r flux = self.flux(a, b) netflux = flux - np.transpose(flux) ind = (netflux < 0.0) netflux[ind] = 0.0 return netflux
r"""The netflux network for the reaction from A=[0,...,a] => B=[b,...,M]. Parameters ---------- a : int State index b : int State index Returns ------- netflux : (M, M) ndarray Matrix of flux values between pairs of st...
def totalflux(self, a, b): r flux = self.flux(a, b) A = list(range(a + 1)) notA = list(range(a + 1, flux.shape[0])) F = flux[A, :][:, notA].sum() return F
r"""The tiotal flux for the reaction A=[0,...,a] => B=[b,...,M]. Parameters ---------- a : int State index b : int State index Returns ------- F : float The total flux between reactant and product
def transition_matrix_non_reversible(C): if not scipy.sparse.issparse(C): C = scipy.sparse.csr_matrix(C) rowsum = C.tocsr().sum(axis=1) # catch div by zero if np.min(rowsum) == 0.0: raise ValueError("matrix C contains rows with sum zero.") rowsum = np.array(1. / rowsum).flatten(...
implementation of transition_matrix
def correct_transition_matrix(T, reversible=None): r row_sums = T.sum(axis=1).A1 max_sum = np.max(row_sums) if max_sum == 0.0: max_sum = 1.0 return (T + scipy.sparse.diags(-row_sums+max_sum, 0)) / max_sum
r"""Normalize transition matrix Fixes a the row normalization of a transition matrix. To be used with the reversible estimators to fix an almost coverged transition matrix. Parameters ---------- T : (M, M) ndarray matrix to correct reversible : boolean for future use R...
def transition_matrix_reversible_pisym(C, return_statdist=False, **kwargs): r # nonreversible estimate T_nonrev = transition_matrix_non_reversible(C) from msmtools.analysis import stationary_distribution pi = stationary_distribution(T_nonrev) # correlation matrix X = scipy.sparse.diags(pi).d...
r""" Estimates reversible transition matrix as follows: ..:math: p_{ij} = c_{ij} / c_i where c_i = sum_j c_{ij} \pi_j = \sum_j \pi_i p_{ij} x_{ij} = \pi_i p_{ij} + \pi_j p_{ji} p^{rev}_{ij} = x_{ij} / x_i where x_i = sum_j x_{ij} In words: takes the nonreversible transition...
def expectation(P, obs): r pi = statdist(P) return np.dot(pi, obs)
r"""Equilibrium expectation of given observable. Parameters ---------- P : (M, M) ndarray Transition matrix obs : (M,) ndarray Observable, represented as vector on state space Returns ------- x : float Expectation value
def correlation(P, obs1, obs2=None, times=[1], k=None): r M = P.shape[0] T = np.asarray(times).max() if T < M: return correlation_matvec(P, obs1, obs2=obs2, times=times) else: return correlation_decomp(P, obs1, obs2=obs2, times=times, k=k)
r"""Time-correlation for equilibrium experiment. Parameters ---------- P : (M, M) ndarray Transition matrix obs1 : (M,) ndarray Observable, represented as vector on state space obs2 : (M,) ndarray (optional) Second observable, for cross-correlations times : list of int (...
def correlation_decomp(P, obs1, obs2=None, times=[1], k=None): r if obs2 is None: obs2 = obs1 R, D, L = rdl_decomposition(P, k=k) """Stationary vector""" mu = L[0, :] """Extract eigenvalues""" ev = np.diagonal(D) """Amplitudes""" amplitudes = np.dot(mu * obs1, R) * np.dot(L, ...
r"""Time-correlation for equilibrium experiment - via decomposition. Parameters ---------- P : (M, M) ndarray Transition matrix obs1 : (M,) ndarray Observable, represented as vector on state space obs2 : (M,) ndarray (optional) Second observable, for cross-correlations t...
def log_likelihood(C, T): C = C.tocsr() T = T.tocsr() ind = scipy.nonzero(C) relT = np.array(T[ind])[0, :] relT = np.log(relT) relC = np.array(C[ind])[0, :] return relT.dot(relC)
implementation of likelihood of C given T
def upload_file(token, channel_name, file_name): slack = Slacker(token) slack.files.upload(file_name, channels=channel_name)
upload file to a channel
def args_priority(args, environ): ''' priority of token 1) as argumment: -t 2) as environ variable priority of as_user 1) as argument: -a 2) as environ variable ''' arg_token = args.token arg_as_user = args.as_user slack_token_var_name = 'SLACK_TOKE...
priority of token 1) as argumment: -t 2) as environ variable priority of as_user 1) as argument: -a 2) as environ variable
def set_up(): global _context if _context is not None: raise AssertionError( 'This function must only be called ' 'once in an application lifetime') platform.set_up() vm = platform.create_vm() vm.set_up() _context = vm.create_context() _context.set_up()...
Set ups the V8 machinery:\ platform, VM and context. This function is not thread-safe,\ it must be called from a place\ where is guaranteed it will be\ called once and only once.\ Probably within the main-thread\ at import time.
def run(self): if self.verbose: self.selftest() self.count = 0 if self.verbose: logging.info('initial value of the objective function is %f' % self.function(self.initial)) theta0 = self.initial theta, f, d = fmin_l_bfgs_b(...
Run the minimization. Returns ------- K : (N,N) ndarray the optimal rate matrix
def get_forwarders(resolv="resolv.conf"): ns = [] if os.path.exists(resolv): for l in open(resolv): if l.startswith("nameserver"): address = l.strip().split(" ", 2)[1] # forwarding to ourselves would be bad if not address.startswith("127")...
Find the forwarders in /etc/resolv.conf, default to 8.8.8.8 and 8.8.4.4
def format_code(source, preferred_quote="'"): try: return _format_code(source, preferred_quote) except (tokenize.TokenError, IndentationError): return source
Return source code with quotes unified.
def _format_code(source, preferred_quote): if not source: return source modified_tokens = [] sio = io.StringIO(source) for (token_type, token_string, start, end, line) in tokenize.generate_tokens(sio.readline): if token_type == tokenize.STRING:...
Return source code with quotes unified.
def unify_quotes(token_string, preferred_quote): bad_quote = {'"': "'", "'": '"'}[preferred_quote] allowed_starts = { '': bad_quote, 'f': 'f' + bad_quote, 'b': 'b' + bad_quote } if not any(token_string.startswith(start) for start in allowed_...
Return string with quotes changed to preferred_quote if possible.
def open_with_encoding(filename, encoding, mode='r'): return io.open(filename, mode=mode, encoding=encoding, newline='')
Return opened file with a specific encoding.
def detect_encoding(filename): try: with open(filename, 'rb') as input_file: from lib2to3.pgen2 import tokenize as lib2to3_tokenize encoding = lib2to3_tokenize.detect_encoding(input_file.readline)[0] # Check for correctness of encoding. with open_with_en...
Return file encoding.
def format_file(filename, args, standard_out): encoding = detect_encoding(filename) with open_with_encoding(filename, encoding=encoding) as input_file: source = input_file.read() formatted_source = format_code( source, preferred_quote=args.quote) if source != fo...
Run format_code() on a file. Returns `True` if any changes are needed and they are not being done in-place.
def _main(argv, standard_out, standard_error): import argparse parser = argparse.ArgumentParser(description=__doc__, prog='unify') parser.add_argument('-i', '--in-place', action='store_true', help='make changes to files instead of printing diffs') parser.add_argument('-c', '...
Run quotes unifying on files. Returns `1` if any quoting changes are still needed, otherwise `None`.
def main(): # pragma: no cover try: # Exit on broken pipe. signal.signal(signal.SIGPIPE, signal.SIG_DFL) except AttributeError: # SIGPIPE is not available on Windows. pass try: return _main(sys.argv, standard_out=sys.stdout, ...
Main entry point.
def bootstrap_counts(dtrajs, lagtime, corrlength=None): r dtrajs = _ensure_dtraj_list(dtrajs) return dense.bootstrapping.bootstrap_counts(dtrajs, lagtime, corrlength=corrlength)
r"""Generates a randomly resampled count matrix given the input coordinates. Parameters ---------- dtrajs : array-like or array-like of array-like single or multiple discrete trajectories. Every trajectory is assumed to be a statistically independent realization. Note that this is often not...
def connected_sets(C, directed=True): r if isdense(C): return sparse.connectivity.connected_sets(csr_matrix(C), directed=directed) else: return sparse.connectivity.connected_sets(C, directed=directed)
r"""Compute connected sets of microstates. Connected components for a directed graph with edge-weights given by the count matrix. Parameters ---------- C : scipy.sparse matrix Count matrix specifying edge weights. directed : bool, optional Whether to compute connected components...
def largest_connected_set(C, directed=True): r if isdense(C): return sparse.connectivity.largest_connected_set(csr_matrix(C), directed=directed) else: return sparse.connectivity.largest_connected_set(C, directed=directed)
r"""Largest connected component for a directed graph with edge-weights given by the count matrix. Parameters ---------- C : scipy.sparse matrix Count matrix specifying edge weights. directed : bool, optional Whether to compute connected components for a directed or undirected...
def largest_connected_submatrix(C, directed=True, lcc=None): r if isdense(C): return sparse.connectivity.largest_connected_submatrix(csr_matrix(C), directed=directed, lcc=lcc).toarray() else: return sparse.connectivity.largest_connected_submatrix(C, directed=directed, lcc=lcc)
r"""Compute the count matrix on the largest connected set. Parameters ---------- C : scipy.sparse matrix Count matrix specifying edge weights. directed : bool, optional Whether to compute connected components for a directed or undirected graph. Default is True lcc : (M,) ndarr...
def is_connected(C, directed=True): if isdense(C): return sparse.connectivity.is_connected(csr_matrix(C), directed=directed) else: return sparse.connectivity.is_connected(C, directed=directed)
Check connectivity of the given matrix. Parameters ---------- C : scipy.sparse matrix Count matrix specifying edge weights. directed : bool, optional Whether to compute connected components for a directed or undirected graph. Default is True. Returns ------- is_connec...
def prior_neighbor(C, alpha=0.001): r if isdense(C): B = sparse.prior.prior_neighbor(csr_matrix(C), alpha=alpha) return B.toarray() else: return sparse.prior.prior_neighbor(C, alpha=alpha)
r"""Neighbor prior for the given count matrix. Parameters ---------- C : (M, M) ndarray or scipy.sparse matrix Count matrix alpha : float (optional) Value of prior counts Returns ------- B : (M, M) ndarray or scipy.sparse matrix Prior count matrix Notes ---...
def prior_const(C, alpha=0.001): r if isdense(C): return sparse.prior.prior_const(C, alpha=alpha) else: warnings.warn("Prior will be a dense matrix for sparse input") return sparse.prior.prior_const(C, alpha=alpha)
r"""Constant prior for given count matrix. Parameters ---------- C : (M, M) ndarray or scipy.sparse matrix Count matrix alpha : float (optional) Value of prior counts Returns ------- B : (M, M) ndarray Prior count matrix Notes ----- The prior is defined...
def prior_rev(C, alpha=-1.0): r if isdense(C): return sparse.prior.prior_rev(C, alpha=alpha) else: warnings.warn("Prior will be a dense matrix for sparse input") return sparse.prior.prior_rev(C, alpha=alpha)
r"""Prior counts for sampling of reversible transition matrices. Prior is defined as b_ij= alpha if i<=j b_ij=0 else Parameters ---------- C : (M, M) ndarray or scipy.sparse matrix Count matrix alpha : float (optional) Value of prior counts Returns ---...
def tmatrix_cov(C, k=None): r if issparse(C): warnings.warn("Covariance matrix will be dense for sparse input") C = C.toarray() return dense.covariance.tmatrix_cov(C, row=k)
r"""Covariance tensor for non-reversible transition matrix posterior. Parameters ---------- C : (M, M) ndarray or scipy.sparse matrix Count matrix k : int (optional) Return only covariance matrix for entires in the k-th row of the transition matrix Returns ------- c...
def error_perturbation(C, S): r if issparse(C): warnings.warn("Error-perturbation will be dense for sparse input") C = C.toarray() return dense.covariance.error_perturbation(C, S)
r"""Error perturbation for given sensitivity matrix. Parameters ---------- C : (M, M) ndarray Count matrix S : (M, M) ndarray or (K, M, M) ndarray Sensitivity matrix (for scalar observable) or sensitivity tensor for vector observable Returns ------- X : float or (K,...
def hitting_probability(P, target): if hasattr(target, "__len__"): target = np.array(target) else: target = np.array([target]) # target size n = np.shape(P)[0] # nontarget nontarget = np.array(list(set(range(n)) - set(target)), dtype=int) # stable states stable = np....
Computes the hitting probabilities for all states to the target states. The hitting probability of state i to set A is defined as the minimal, non-negative solution of: .. math:: h_i^A &= 1 \:\:\:\: i\in A \\ h_i^A &= \sum_j p_{ij} h_i^A \:\:\:\: i \notin A Retur...
def remove_negative_entries(A): r A = A.tocoo() data = A.data row = A.row col = A.col """Positive entries""" pos = data > 0.0 datap = data[pos] rowp = row[pos] colp = col[pos] Aplus = coo_matrix((datap, (rowp, colp)), shape=A.shape) return Aplus
r"""Remove all negative entries from sparse matrix. Aplus=max(0, A) Parameters ---------- A : (M, M) scipy.sparse matrix Input matrix Returns ------- Aplus : (M, M) scipy.sparse matrix Input matrix with negative entries set to zero.
def flux_matrix(T, pi, qminus, qplus, netflux=True): r D1 = diags((pi * qminus,), (0,)) D2 = diags((qplus,), (0,)) flux = D1.dot(T.dot(D2)) """Remove self-fluxes""" flux = flux - diags(flux.diagonal(), 0) """Return net or gross flux""" if netflux: return to_netflux(flux) e...
r"""Compute the flux. Parameters ---------- T : (M, M) scipy.sparse matrix Transition matrix pi : (M,) ndarray Stationary distribution corresponding to T qminus : (M,) ndarray Backward comittor qplus : (M,) ndarray Forward committor netflux : boolean ...
def to_netflux(flux): r netflux = flux - flux.T """Set negative entries to zero""" netflux = remove_negative_entries(netflux) return netflux
r"""Compute the netflux. f_ij^{+}=max{0, f_ij-f_ji} for all pairs i,j Parameters ---------- flux : (M, M) scipy.sparse matrix Matrix of flux values between pairs of states. Returns ------- netflux : (M, M) scipy.sparse matrix Matrix of netflux values between pairs of s...
def coarsegrain(F, sets): r nnew = len(sets) Fin = F.tocsr() Fc = csr_matrix((nnew, nnew)) for i in range(0, nnew - 1): for j in range(i, nnew): I = list(sets[i]) J = list(sets[j]) Fc[i, j] = (Fin[I, :][:, J]).sum() Fc[j, i] = (Fin[J, :][:, I])...
r"""Coarse-grains the flux to the given sets $fc_{i,j} = \sum_{i \in I,j \in J} f_{i,j}$ Note that if you coarse-grain a net flux, it does not necessarily have a net flux property anymore. If want to make sure you get a netflux, use to_netflux(coarsegrain(F,sets)). Parameters ---------- F ...
def total_flux(flux, A): r X = set(np.arange(flux.shape[0])) # total state space A = set(A) notA = X.difference(A) """Extract rows corresponding to A""" W = flux.tocsr() W = W[list(A), :] """Extract columns corresonding to X\A""" W = W.tocsc() W = W[:, list(notA)] F = W.su...
r"""Compute the total flux between reactant and product. Parameters ---------- flux : (M, M) scipy.sparse matrix Matrix of flux values between pairs of states. A : array_like List of integer state labels for set A (reactant) Returns ------- F : float The total flux ...
def eigenvalue_sensitivity(T, k): eValues, rightEigenvectors = numpy.linalg.eig(T) leftEigenvectors = numpy.linalg.inv(rightEigenvectors) perm = numpy.argsort(eValues)[::-1] rightEigenvectors = rightEigenvectors[:, perm] leftEigenvectors = leftEigenvectors[perm] sensitivity = numpy.oute...
calculate the sensitivity matrix for eigenvalue k given transition matrix T. Parameters ---------- T : numpy.ndarray shape = (n, n) Transition matrix k : int eigenvalue index for eigenvalues order descending Returns ------- x : ndarray, shape=(n, n) Sensitivity matri...
def timescale_sensitivity(T, k): eValues, rightEigenvectors = numpy.linalg.eig(T) leftEigenvectors = numpy.linalg.inv(rightEigenvectors) perm = numpy.argsort(eValues)[::-1] eValues = eValues[perm] rightEigenvectors = rightEigenvectors[:, perm] leftEigenvectors = leftEigenvectors[perm] ...
calculate the sensitivity matrix for timescale k given transition matrix T. Parameters ---------- T : numpy.ndarray shape = (n, n) Transition matrix k : int timescale index for timescales of descending order (k = 0 for the infinite one) Returns ------- x : ndarray, shape=(n,...
def stationary_distribution_sensitivity(T, j): r n = len(T) lEV = numpy.ones(n) rEV = stationary_distribution(T) eVal = 1.0 T = numpy.transpose(T) vecA = numpy.zeros(n) vecA[j] = 1.0 matA = T - eVal * numpy.identity(n) # normalize s.t. sum is one using rEV which is constant ...
r"""Calculate the sensitivity matrix for entry j the stationary distribution vector given transition matrix T. Parameters ---------- T : numpy.ndarray shape = (n, n) Transition matrix j : int entry of stationary distribution for which the sensitivity is to be computed Returns ...
def mfpt_sensitivity(T, target, j): n = len(T) matA = T - numpy.diag(numpy.ones((n))) matA[target] *= 0 matA[target, target] = 1.0 tVec = -1. * numpy.ones(n) tVec[target] = 0 mfpt = numpy.linalg.solve(matA, tVec) aVec = numpy.zeros(n) aVec[j] = 1.0 phiVec = numpy.linalg...
calculate the sensitivity matrix for entry j of the mean first passage time (MFPT) given transition matrix T. Parameters ---------- T : numpy.ndarray shape = (n, n) Transition matrix target : int target state to which the MFPT is computed j : int entry of the mfpt vector for ...
def expectation_sensitivity(T, a): r M = T.shape[0] S = numpy.zeros((M, M)) for i in range(M): S += a[i] * stationary_distribution_sensitivity(T, i) return S
r"""Sensitivity of expectation value of observable A=(a_i). Parameters ---------- T : (M, M) ndarray Transition matrix a : (M,) ndarray Observable, a[i] is the value of the observable at state i. Returns ------- S : (M, M) ndarray Sensitivity matrix of the expectati...
def expected_counts(p0, T, n): r M = T.shape[0] if n <= M: return ec_matrix_vector(p0, T, n) else: return ec_geometric_series(p0, T, n)
r"""Compute expected transition counts for Markov chain after n steps. Expected counts are computed according to ..math:: E[C_{ij}^{(n)}]=\sum_{k=0}^{n-1} (p_0^T T^{k})_{i} p_{ij} For N<=M, the sum is computed via successive summation of the following matrix vector products, p_1^t=p_0^t T,...,p_n...
def expected_counts_stationary(T, n, mu=None): r if n <= 0: EC = np.zeros(T.shape) return EC else: if mu is None: mu = stationary_distribution(T) EC = n * mu[:, np.newaxis] * T return EC
r"""Expected transition counts for Markov chain in equilibrium. Since mu is stationary for T we have .. math:: E(C^{(N)})=N diag(mu)*T. Parameters ---------- T : (M, M) ndarray Transition matrix. n : int Number of steps for chain. mu : (M,) ndarray (optional) ...
def geometric_series(q, n): q = np.asarray(q) if n < 0: raise ValueError('Finite geometric series is only defined for n>=0.') else: """q is scalar""" if q.ndim == 0: if q == 1: s = (n + 1) * 1.0 return s else: ...
Compute finite geometric series. \frac{1-q^{n+1}}{1-q} q \neq 1 \sum_{k=0}^{n} q^{k}= n+1 q = 1 Parameters ---------- q : array-like The common ratio of the geometric series. n : int The num...
def ec_matrix_vector(p0, T, n): r if (n <= 0): EC = np.zeros(T.shape) return EC else: """Probability vector after (k=0) propagations""" p_k = 1.0 * p0 """Sum of vectors after (k=0) propagations""" p_sum = 1.0 * p_k for k in range(n - 1): ""...
r"""Compute expected transition counts for Markov chain after n steps. Expected counts are computed according to ..math:: E[C_{ij}^{(n)}]=\sum_{k=0}^{n-1} (p_0^t T^{k})_{i} p_{ij} The sum is computed via successive summation of the following matrix vector products, p_1^t=p_0^t T,...,p_n^t=P_{n-1}...
def ec_geometric_series(p0, T, n): r if (n <= 0): EC = np.zeros(T.shape) return EC else: R, D, L = rdl_decomposition(T) w = np.diagonal(D) L = np.transpose(L) D_sum = np.diag(geometric_series(w, n - 1)) T_sum = np.dot(np.dot(R, D_sum), np.conjugate(np...
r"""Compute expected transition counts for Markov chain after n steps. Expected counts are computed according to ..math:: E[C_{ij}^{(n)}]=\sum_{k=0}^{n-1} (p_0^t T^{k})_{i} p_{ij} The sum is computed using the eigenvalue decomposition of T and applying the expression for a finite geometric series...
def solve_mle_rev(C, tol=1e-10, maxiter=100, show_progress=False, full_output=False, return_statdist=True, **kwargs): M = C.shape[0] """Initial guess for primal-point""" z0 = np.zeros(2*M) z0[0:M] = 1.0 """Inequality constraints""" # G = np.zeros((M, 2*M)) # G[np.ara...
Number of states
def blueprint_name_to_url(name): if name[-1:] == ".": name = name[:-1] name = str(name).replace(".", "/") return name
remove the last . in the string it it ends with a . for the url structure must follow the flask routing format it should be /model/method instead of /model/method/
def home(request): "Simple homepage view." context = {} if request.user.is_authenticated(): try: access = request.user.accountaccess_set.all()[0] except IndexError: access = None else: client = access.api_client context['info'] = client...
Simple homepage view.
def forwards(self, orm): "Write your forwards methods here." # Note: Don't use "from appname.models import ModelName". # Use orm.ModelName to refer to models in this application, # and orm['appname.ModelName'] for models in other applications. from account_keeping.models import ...
Write your forwards methods here.
def get_client(provider, token=''): "Return the API client for the given provider." cls = OAuth2Client if provider.request_token_url: cls = OAuthClient return cls(provider, tokenf get_client(provider, token=''): "Return the API client for the given provider." cls = OAuth2Client if pr...
Return the API client for the given provider.
def get_profile_info(self, raw_token, profile_info_params={}): "Fetch user profile information." try: response = self.request('get', self.provider.profile_url, token=raw_token, params=profile_info_params) response.raise_for_status() except RequestException as e: ...
Fetch user profile information.
def get_access_token(self, request, callback=None): "Fetch access token from callback request." raw_token = request.session.get(self.session_key, None) verifier = request.GET.get('oauth_verifier', None) if raw_token is not None and verifier is not None: data = {'oauth_verifie...
Fetch access token from callback request.
def get_redirect_args(self, request, callback): "Get request parameters for redirect url." callback = force_text(request.build_absolute_uri(callback)) raw_token = self.get_request_token(request, callback) token, secret = self.parse_raw_token(raw_token) if token is not None and se...
Get request parameters for redirect url.
def parse_raw_token(self, raw_token): "Parse token and secret from raw token response." if raw_token is None: return (None, None) qs = parse_qs(raw_token) token = qs.get('oauth_token', [None])[0] secret = qs.get('oauth_token_secret', [None])[0] return (token, ...
Parse token and secret from raw token response.
def request(self, method, url, **kwargs): "Build remote url request. Constructs necessary auth." user_token = kwargs.pop('token', self.token) token, secret = self.parse_raw_token(user_token) callback = kwargs.pop('oauth_callback', None) verifier = kwargs.get('data', {}).pop('oaut...
Build remote url request. Constructs necessary auth.
def check_application_state(self, request, callback): "Check optional state parameter." stored = request.session.get(self.session_key, None) returned = request.GET.get('state', None) check = False if stored is not None: if returned is not None: check =...
Check optional state parameter.
def get_redirect_args(self, request, callback): "Get request parameters for redirect url." callback = request.build_absolute_uri(callback) args = { 'client_id': self.provider.consumer_key, 'redirect_uri': callback, 'response_type': 'code', } st...
Get request parameters for redirect url.
def parse_raw_token(self, raw_token): "Parse token and secret from raw token response." if raw_token is None: return (None, None) # Load as json first then parse as query string try: token_data = json.loads(raw_token) except ValueError: qs = pa...
Parse token and secret from raw token response.
def request(self, method, url, **kwargs): "Build remote url request. Constructs necessary auth." user_token = kwargs.pop('token', self.token) token, _ = self.parse_raw_token(user_token) if token is not None: params = kwargs.get('params', {}) params['access_token']...
Build remote url request. Constructs necessary auth.
def _stripped_codes(codes): return tuple([ code.strip() for code in codes.split(',') if code.strip() ])
Return a tuple of stripped codes split by ','.
def regex(self): if not self._compiled_regex: self._compiled_regex = re.compile(self.raw) return self._compiled_regex
Return compiled regex.
def marker(self): if not self._marker: assert markers, 'Package packaging is needed for environment markers' self._marker = markers.Marker(self.raw) return self._marker
Return environment marker.
def regex_match_any(self, line, codes=None): for selector in self.regex_selectors: for match in selector.regex.finditer(line): if codes and match.lastindex: # Currently the group name must be 'codes' try: disabl...
Match any regex.
def match(self, filename, line, codes): if self.regex_match_any(line, codes): if self._vary_codes: self.codes = tuple([codes[-1]]) return True
Match rule and set attribute codes.
def file_match_any(self, filename): if filename.startswith('.' + os.sep): filename = filename[len(os.sep) + 1:] if os.sep != '/': filename = filename.replace(os.sep, '/') for selector in self.file_selectors: if (selector.pattern.endswith('/') and ...
Match any filename.
def codes_match_any(self, codes): for selector in self.code_selectors: if selector.code in codes: return True return False
Match any code.
def match(self, filename, line, codes): if ((not self.file_selectors or self.file_match_any(filename)) and (not self.environment_marker_selector or self.environment_marker_evaluate()) and (not self.code_selectors or self.codes_match_any(codes))): ...
Match rule.
def authenticate(self, provider=None, identifier=None): "Fetch user for a given provider by id." provider_q = Q(provider__name=provider) if isinstance(provider, Provider): provider_q = Q(provider=provider) try: access = AccountAccess.objects.filter( ...
Fetch user for a given provider by id.
def __extract_modules(self, loader, name, is_pkg): mod = loader.find_module(name).load_module(name) """ find the attribute method on each module """ if hasattr(mod, '__method__'): """ register to the blueprint if method attribute found """ module_router = Modu...
if module found load module and save all attributes in the module found
def get_client(self, provider): "Get instance of the OAuth client for this provider." if self.client_class is not None: return self.client_class(provider) return get_client(providerf get_client(self, provider): "Get instance of the OAuth client for this provider." if ...
Get instance of the OAuth client for this provider.
def get_redirect_url(self, **kwargs): "Build redirect url for a given provider." name = kwargs.get('provider', '') try: provider = Provider.objects.get(name=name) except Provider.DoesNotExist: raise Http404('Unknown OAuth provider.') else: if n...
Build redirect url for a given provider.
def get_or_create_user(self, provider, access, info): "Create a shell auth.User." digest = hashlib.sha1(smart_bytes(access)).digest() # Base 64 encode to get below 30 characters # Removed padding characters username = force_text(base64.urlsafe_b64encode(digest)).replace('=', '') ...
Create a shell auth.User.
def get_user_id(self, provider, info): "Return unique identifier from the profile info." id_key = self.provider_id or 'id' result = info try: for key in id_key.split('.'): result = result[key] return result except KeyError: retu...
Return unique identifier from the profile info.
def handle_existing_user(self, provider, user, access, info): "Login user and redirect." login(self.request, user) return redirect(self.get_login_redirect(provider, user, access)f handle_existing_user(self, provider, user, access, info): "Login user and redirect." login(self.requ...
Login user and redirect.
def handle_new_user(self, provider, access, info): "Create a shell auth.User and redirect." user = self.get_or_create_user(provider, access, info) access.user = user AccountAccess.objects.filter(pk=access.pk).update(user=user) user = authenticate(provider=access.provider, identif...
Create a shell auth.User and redirect.
async def discover_nupnp(websession): async with websession.get(URL_NUPNP) as res: return [Bridge(item['internalipaddress'], websession=websession) for item in (await res.json())]
Discover bridges via NUPNP.
def get_months_of_year(year): current_year = now().year if year == current_year: return now().month if year > current_year: return 1 if year < current_year: return 12
Returns the number of months that have already passed in the given year. This is useful for calculating averages on the year view. For past years, we should divide by 12, but for the current year, we should divide by the current month.
def colorgamut(self): try: light_spec = self.controlcapabilities gtup = tuple([XYPoint(*x) for x in light_spec['colorgamut']]) color_gamut = GamutType(*gtup) except KeyError: color_gamut = None return color_gamut
The color gamut information of the light.
def get_totals_by_payee(self, account, start_date=None, end_date=None): qs = Transaction.objects.filter(account=account, parent__isnull=True) qs = qs.values('payee').annotate(models.Sum('value_gross')) qs = qs.order_by('payee__name') return qs
Returns transaction totals grouped by Payee.
def get_without_invoice(self): qs = Transaction.objects.filter( children__isnull=True, invoice__isnull=True) return qs
Returns transactions that don't have an invoice. We filter out transactions that have children, because those transactions never have invoices - their children are the ones that would each have one invoice.
def _get_enabled(): providers = Provider.objects.all() return [p for p in providers if p.enabled()]
Wrapped function for filtering enabled providers.
def available_providers(request): "Adds the list of enabled providers to the context." if APPENGINE: # Note: AppEngine inequality queries are limited to one property. # See https://developers.google.com/appengine/docs/python/datastore/queries#Python_Restrictions_on_queries # Users have a...
Adds the list of enabled providers to the context.
def run(command, **kw): # Windows low-level subprocess API wants str for current working # directory. if sys.platform == 'win32': _cwd = kw.get('cwd', None) if _cwd is not None: kw['cwd'] = _cwd.decode() try: # In Python 3, iterating over bytes yield integers, so...
Run `command`, catch any exception, and return lines of output.
def find_repositories_with_locate(path): command = [b'locate', b'-0'] for dotdir in DOTDIRS: # Escaping the slash (using '\/' rather than '/') is an # important signal to locate(1) that these glob patterns are # supposed to match the full path, so that things like # '.hgigno...
Use locate to return a sequence of (directory, dotdir) pairs.
def find_repositories_by_walking_without_following_symlinks(path): repos = [] for dirpath, dirnames, filenames in os.walk(path, followlinks=False): for dotdir in set(dirnames) & DOTDIRS: repos.append((dirpath, dotdir)) return repos
Walk a tree and return a sequence of (directory, dotdir) pairs.
def find_repositories_by_walking_and_following_symlinks(path): repos = [] # This is for detecting symlink loops and escaping them. This is similar to # http://stackoverflow.com/questions/36977259/avoiding-infinite-recursion-with-os-walk/36977656#36977656 def inode(path): stats = os.stat(pa...
Walk a tree and return a sequence of (directory, dotdir) pairs.
def status_mercurial(path, ignore_set, options): lines = run(['hg', '--config', 'extensions.color=!', 'st'], cwd=path) subrepos = () return [b' ' + l for l in lines if not l.startswith(b'?')], subrepos
Run hg status. Returns a 2-element tuple: * Text lines describing the status of the repository. * Empty sequence of subrepos, since hg does not support them.
def status_git(path, ignore_set, options): # Check whether current branch is dirty: lines = [l for l in run(('git', 'status', '-s', '-b'), cwd=path) if (options.untracked or not l.startswith(b'?')) and not l.startswith(b'##')] # Check all branches for unpushed commits: li...
Run git status. Returns a 2-element tuple: * Text lines describing the status of the repository. * List of subrepository paths, relative to the repository itself.
def status_subversion(path, ignore_set, options): subrepos = () if path in ignore_set: return None, subrepos keepers = [] for line in run(['svn', 'st', '-v'], cwd=path): if not line.strip(): continue if line.startswith(b'Performing') or line[0] in b'X?': ...
Run svn status. Returns a 2-element tuple: * Text lines describing the status of the repository. * Empty sequence of subrepos, since svn does not support them.
def scan(repos, options): ignore_set = set() repos = repos[::-1] # Create a queue we can push and pop from while repos: directory, dotdir = repos.pop() ignore_this = any(pat in directory for pat in options.ignore_patterns) if ignore_this: if options.verbose: ...
Given a repository list [(path, vcsname), ...], scan each of them.
def get_reporter_state(): # Stack # 1. get_reporter_state (i.e. this function) # 2. putty_ignore_code # 3. QueueReport.error or pep8.StandardReport.error for flake8 -j 1 # 4. pep8.Checker.check_ast or check_physical or check_logical # locals contains `tree` (ast) for check_ast frame ...
Get pep8 reporter state from stack.
def putty_ignore_code(options, code): reporter, line_number, offset, text, check = get_reporter_state() try: line = reporter.lines[line_number - 1] except IndexError: line = '' options.ignore = options._orig_ignore options.select = options._orig_select for rule in options....
Implement pep8 'ignore_code' hook.
def add_options(cls, parser): parser.add_option( '--putty-select', metavar='errors', default='', help='putty select list', ) parser.add_option( '--putty-ignore', metavar='errors', default='', help='putty ignore list', ) par...
Add options for command line and config file.
def parse_options(cls, options): if (not options.putty_select and not options.putty_ignore and not options.putty_auto_ignore): return options._orig_select = options.select options._orig_ignore = options.ignore options.putty_select = Parser(options.p...
Parse options and activate `ignore_code` handler.
def _raise_on_error(data): if isinstance(data, list): data = data[0] if isinstance(data, dict) and 'error' in data: raise_error(data['error'])
Check response for error message.