repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
stbraun/fuzzing
features/steps/ft_fuzzer.py
step_impl11
def step_impl11(context, runs): """Execute multiple runs. :param runs: number of test runs to perform. :param context: test context. """ executor = context.fuzz_executor executor.run_test(runs) stats = executor.stats count = stats.cumulated_counts() assert count == runs, "VERIFY: stats available."
python
def step_impl11(context, runs): """Execute multiple runs. :param runs: number of test runs to perform. :param context: test context. """ executor = context.fuzz_executor executor.run_test(runs) stats = executor.stats count = stats.cumulated_counts() assert count == runs, "VERIFY: stats available."
[ "def", "step_impl11", "(", "context", ",", "runs", ")", ":", "executor", "=", "context", ".", "fuzz_executor", "executor", ".", "run_test", "(", "runs", ")", "stats", "=", "executor", ".", "stats", "count", "=", "stats", ".", "cumulated_counts", "(", ")", ...
Execute multiple runs. :param runs: number of test runs to perform. :param context: test context.
[ "Execute", "multiple", "runs", "." ]
train
https://github.com/stbraun/fuzzing/blob/974a64472732d4e40db919d242149bf0856fe199/features/steps/ft_fuzzer.py#L134-L144
stbraun/fuzzing
features/steps/ft_fuzzer.py
step_impl12
def step_impl12(context, runs): """Check called apps / files. :param runs: expected number of records. :param context: test context. """ executor_ = context.fuzz_executor stats = executor_.stats count = stats.cumulated_counts() assert count == runs, "VERIFY: Number of recorded runs."
python
def step_impl12(context, runs): """Check called apps / files. :param runs: expected number of records. :param context: test context. """ executor_ = context.fuzz_executor stats = executor_.stats count = stats.cumulated_counts() assert count == runs, "VERIFY: Number of recorded runs."
[ "def", "step_impl12", "(", "context", ",", "runs", ")", ":", "executor_", "=", "context", ".", "fuzz_executor", "stats", "=", "executor_", ".", "stats", "count", "=", "stats", ".", "cumulated_counts", "(", ")", "assert", "count", "==", "runs", ",", "\"VERI...
Check called apps / files. :param runs: expected number of records. :param context: test context.
[ "Check", "called", "apps", "/", "files", "." ]
train
https://github.com/stbraun/fuzzing/blob/974a64472732d4e40db919d242149bf0856fe199/features/steps/ft_fuzzer.py#L148-L157
stbraun/fuzzing
features/steps/ft_fuzzer.py
step_impl13
def step_impl13(context, runs): """Check called apps / files. :param runs: expected number of records. :param context: test context. """ executor_ = context.fuzz_executor stats = executor_.stats count = stats.cumulated_counts() assert count == runs, "VERIFY: Number of recorded runs." successful_runs = stats.cumulated_counts_for_status(Status.SUCCESS) assert successful_runs == runs
python
def step_impl13(context, runs): """Check called apps / files. :param runs: expected number of records. :param context: test context. """ executor_ = context.fuzz_executor stats = executor_.stats count = stats.cumulated_counts() assert count == runs, "VERIFY: Number of recorded runs." successful_runs = stats.cumulated_counts_for_status(Status.SUCCESS) assert successful_runs == runs
[ "def", "step_impl13", "(", "context", ",", "runs", ")", ":", "executor_", "=", "context", ".", "fuzz_executor", "stats", "=", "executor_", ".", "stats", "count", "=", "stats", ".", "cumulated_counts", "(", ")", "assert", "count", "==", "runs", ",", "\"VERI...
Check called apps / files. :param runs: expected number of records. :param context: test context.
[ "Check", "called", "apps", "/", "files", "." ]
train
https://github.com/stbraun/fuzzing/blob/974a64472732d4e40db919d242149bf0856fe199/features/steps/ft_fuzzer.py#L161-L172
stbraun/fuzzing
features/steps/ft_fuzzer.py
step_impl14
def step_impl14(context, runs): """Check called apps / files. :param runs: expected number of records. :param context: test context. """ executor_ = context.fuzz_executor stats = executor_.stats count = stats.cumulated_counts() assert count == runs, "VERIFY: Number of recorded runs." failed_runs = stats.cumulated_counts_for_status(Status.FAILED) assert failed_runs == runs
python
def step_impl14(context, runs): """Check called apps / files. :param runs: expected number of records. :param context: test context. """ executor_ = context.fuzz_executor stats = executor_.stats count = stats.cumulated_counts() assert count == runs, "VERIFY: Number of recorded runs." failed_runs = stats.cumulated_counts_for_status(Status.FAILED) assert failed_runs == runs
[ "def", "step_impl14", "(", "context", ",", "runs", ")", ":", "executor_", "=", "context", ".", "fuzz_executor", "stats", "=", "executor_", ".", "stats", "count", "=", "stats", ".", "cumulated_counts", "(", ")", "assert", "count", "==", "runs", ",", "\"VERI...
Check called apps / files. :param runs: expected number of records. :param context: test context.
[ "Check", "called", "apps", "/", "files", "." ]
train
https://github.com/stbraun/fuzzing/blob/974a64472732d4e40db919d242149bf0856fe199/features/steps/ft_fuzzer.py#L176-L187
stbraun/fuzzing
features/steps/ft_fuzzer.py
number_of_modified_bytes
def number_of_modified_bytes(buf, fuzzed_buf): """Determine the number of differing bytes. :param buf: original buffer. :param fuzzed_buf: fuzzed buffer. :return: number of different bytes. :rtype: int """ count = 0 for idx, b in enumerate(buf): if b != fuzzed_buf[idx]: count += 1 return count
python
def number_of_modified_bytes(buf, fuzzed_buf): """Determine the number of differing bytes. :param buf: original buffer. :param fuzzed_buf: fuzzed buffer. :return: number of different bytes. :rtype: int """ count = 0 for idx, b in enumerate(buf): if b != fuzzed_buf[idx]: count += 1 return count
[ "def", "number_of_modified_bytes", "(", "buf", ",", "fuzzed_buf", ")", ":", "count", "=", "0", "for", "idx", ",", "b", "in", "enumerate", "(", "buf", ")", ":", "if", "b", "!=", "fuzzed_buf", "[", "idx", "]", ":", "count", "+=", "1", "return", "count"...
Determine the number of differing bytes. :param buf: original buffer. :param fuzzed_buf: fuzzed buffer. :return: number of different bytes. :rtype: int
[ "Determine", "the", "number", "of", "differing", "bytes", "." ]
train
https://github.com/stbraun/fuzzing/blob/974a64472732d4e40db919d242149bf0856fe199/features/steps/ft_fuzzer.py#L193-L205
all-umass/graphs
graphs/construction/msg.py
flesh_out
def flesh_out(X, W, embed_dim, CC_labels, dist_mult=2.0, angle_thresh=0.2, min_shortcircuit=4, max_degree=5, verbose=False): '''Given a connected graph adj matrix (W), add edges to flesh it out.''' W = W.astype(bool) assert np.all(W == W.T), 'graph given to flesh_out must be symmetric' D = pairwise_distances(X, metric='sqeuclidean') # compute average edge lengths for each point avg_edge_length = np.empty(X.shape[0]) for i,nbr_mask in enumerate(W): avg_edge_length[i] = D[i,nbr_mask].mean() # candidate edges must satisfy edge length for at least one end point dist_thresh = dist_mult * avg_edge_length dist_mask = (D < dist_thresh) | (D < dist_thresh[:,None]) # candidate edges must connect points >= min_shortcircuit hops away hops_mask = np.isinf(dijkstra(W, unweighted=True, limit=min_shortcircuit-1)) # candidate edges must not already be connected, or in the same initial CC CC_mask = CC_labels != CC_labels[:,None] candidate_edges = ~W & dist_mask & hops_mask & CC_mask if verbose: # pragma: no cover print('before F:', candidate_edges.sum(), 'potentials') # calc subspaces subspaces, _ = cluster_subspaces(X, embed_dim, CC_labels.max()+1, CC_labels) # upper triangular avoids p,q <-> q,p repeats ii,jj = np.where(np.triu(candidate_edges)) # Get angles edge_dirs = X[ii] - X[jj] ssi = subspaces[CC_labels[ii]] ssj = subspaces[CC_labels[jj]] F = edge_cluster_angle(edge_dirs, ssi, ssj) mask = F < angle_thresh edge_ii = ii[mask] edge_jj = jj[mask] edge_order = np.argsort(F[mask]) if verbose: # pragma: no cover print('got', len(edge_ii), 'potential edges') # Prevent any one node from getting a really high degree degree = W.sum(axis=0) sorted_edges = np.column_stack((edge_ii, edge_jj))[edge_order] for e in sorted_edges: if degree[e].max() < max_degree: W[e[0],e[1]] = True W[e[1],e[0]] = True degree[e] += 1 return Graph.from_adj_matrix(np.where(W, np.sqrt(D), 0))
python
def flesh_out(X, W, embed_dim, CC_labels, dist_mult=2.0, angle_thresh=0.2, min_shortcircuit=4, max_degree=5, verbose=False): '''Given a connected graph adj matrix (W), add edges to flesh it out.''' W = W.astype(bool) assert np.all(W == W.T), 'graph given to flesh_out must be symmetric' D = pairwise_distances(X, metric='sqeuclidean') # compute average edge lengths for each point avg_edge_length = np.empty(X.shape[0]) for i,nbr_mask in enumerate(W): avg_edge_length[i] = D[i,nbr_mask].mean() # candidate edges must satisfy edge length for at least one end point dist_thresh = dist_mult * avg_edge_length dist_mask = (D < dist_thresh) | (D < dist_thresh[:,None]) # candidate edges must connect points >= min_shortcircuit hops away hops_mask = np.isinf(dijkstra(W, unweighted=True, limit=min_shortcircuit-1)) # candidate edges must not already be connected, or in the same initial CC CC_mask = CC_labels != CC_labels[:,None] candidate_edges = ~W & dist_mask & hops_mask & CC_mask if verbose: # pragma: no cover print('before F:', candidate_edges.sum(), 'potentials') # calc subspaces subspaces, _ = cluster_subspaces(X, embed_dim, CC_labels.max()+1, CC_labels) # upper triangular avoids p,q <-> q,p repeats ii,jj = np.where(np.triu(candidate_edges)) # Get angles edge_dirs = X[ii] - X[jj] ssi = subspaces[CC_labels[ii]] ssj = subspaces[CC_labels[jj]] F = edge_cluster_angle(edge_dirs, ssi, ssj) mask = F < angle_thresh edge_ii = ii[mask] edge_jj = jj[mask] edge_order = np.argsort(F[mask]) if verbose: # pragma: no cover print('got', len(edge_ii), 'potential edges') # Prevent any one node from getting a really high degree degree = W.sum(axis=0) sorted_edges = np.column_stack((edge_ii, edge_jj))[edge_order] for e in sorted_edges: if degree[e].max() < max_degree: W[e[0],e[1]] = True W[e[1],e[0]] = True degree[e] += 1 return Graph.from_adj_matrix(np.where(W, np.sqrt(D), 0))
[ "def", "flesh_out", "(", "X", ",", "W", ",", "embed_dim", ",", "CC_labels", ",", "dist_mult", "=", "2.0", ",", "angle_thresh", "=", "0.2", ",", "min_shortcircuit", "=", "4", ",", "max_degree", "=", "5", ",", "verbose", "=", "False", ")", ":", "W", "=...
Given a connected graph adj matrix (W), add edges to flesh it out.
[ "Given", "a", "connected", "graph", "adj", "matrix", "(", "W", ")", "add", "edges", "to", "flesh", "it", "out", "." ]
train
https://github.com/all-umass/graphs/blob/4fbeb025dfe33340335f34300f58dd3809228822/graphs/construction/msg.py#L45-L93
all-umass/graphs
graphs/construction/msg.py
edge_cluster_angle
def edge_cluster_angle(edge_dirs, subspaces1, subspaces2): '''edge_dirs is a (n,D) matrix of edge vectors. subspaces are (n,D,d) or (D,d) matrices of normalized orthogonal subspaces. Result is an n-length array of angles.''' QG = edge_dirs / np.linalg.norm(edge_dirs, ord=2, axis=1)[:,None] X1 = np.einsum('...ij,...i->...j', subspaces1, QG) X2 = np.einsum('...ij,...i->...j', subspaces2, QG) # TODO: check the math on this for more cases # angles = np.maximum(1-np.sum(X1**2, axis=1), 1-np.sum(X2**2, axis=1)) C1 = np.linalg.svd(X1[:,:,None], compute_uv=False) C2 = np.linalg.svd(X2[:,:,None], compute_uv=False) angles = np.maximum(1-C1**2, 1-C2**2)[:,0] angles[np.isnan(angles)] = 0.0 # nan when edge length == 0 return angles
python
def edge_cluster_angle(edge_dirs, subspaces1, subspaces2): '''edge_dirs is a (n,D) matrix of edge vectors. subspaces are (n,D,d) or (D,d) matrices of normalized orthogonal subspaces. Result is an n-length array of angles.''' QG = edge_dirs / np.linalg.norm(edge_dirs, ord=2, axis=1)[:,None] X1 = np.einsum('...ij,...i->...j', subspaces1, QG) X2 = np.einsum('...ij,...i->...j', subspaces2, QG) # TODO: check the math on this for more cases # angles = np.maximum(1-np.sum(X1**2, axis=1), 1-np.sum(X2**2, axis=1)) C1 = np.linalg.svd(X1[:,:,None], compute_uv=False) C2 = np.linalg.svd(X2[:,:,None], compute_uv=False) angles = np.maximum(1-C1**2, 1-C2**2)[:,0] angles[np.isnan(angles)] = 0.0 # nan when edge length == 0 return angles
[ "def", "edge_cluster_angle", "(", "edge_dirs", ",", "subspaces1", ",", "subspaces2", ")", ":", "QG", "=", "edge_dirs", "/", "np", ".", "linalg", ".", "norm", "(", "edge_dirs", ",", "ord", "=", "2", ",", "axis", "=", "1", ")", "[", ":", ",", "None", ...
edge_dirs is a (n,D) matrix of edge vectors. subspaces are (n,D,d) or (D,d) matrices of normalized orthogonal subspaces. Result is an n-length array of angles.
[ "edge_dirs", "is", "a", "(", "n", "D", ")", "matrix", "of", "edge", "vectors", ".", "subspaces", "are", "(", "n", "D", "d", ")", "or", "(", "D", "d", ")", "matrices", "of", "normalized", "orthogonal", "subspaces", ".", "Result", "is", "an", "n", "-...
train
https://github.com/all-umass/graphs/blob/4fbeb025dfe33340335f34300f58dd3809228822/graphs/construction/msg.py#L225-L238
jesford/cluster-lensing
clusterlensing/nfw.py
SurfaceMassDensity.sigma_nfw
def sigma_nfw(self): """Calculate NFW surface mass density profile. Generate the surface mass density profiles of each cluster halo, assuming a spherical NFW model. Optionally includes the effect of cluster miscentering offsets, if the parent object was initialized with offsets. Returns ---------- Quantity Surface mass density profiles (ndarray, in astropy.units of Msun/pc/pc). Each row corresponds to a single cluster halo. """ def _centered_sigma(self): # perfectly centered cluster case # calculate f bigF = np.zeros_like(self._x) f = np.zeros_like(self._x) numerator_arg = ((1. / self._x[self._x_small]) + np.sqrt((1. / (self._x[self._x_small]**2)) - 1.)) denominator = np.sqrt(1. - (self._x[self._x_small]**2)) bigF[self._x_small] = np.log(numerator_arg) / denominator bigF[self._x_big] = (np.arccos(1. / self._x[self._x_big]) / np.sqrt(self._x[self._x_big]**2 - 1.)) f = (1. - bigF) / (self._x**2 - 1.) f[self._x_one] = 1. / 3. if np.isnan(np.sum(f)) or np.isinf(np.sum(f)): print('\nERROR: f is not all real\n') # calculate & return centered profiles if f.ndim == 2: sigma = 2. * self._rs_dc_rcrit * f else: rs_dc_rcrit_4D = self._rs_dc_rcrit.T.reshape(1, 1, f.shape[2], f.shape[3]) sigma = 2. * rs_dc_rcrit_4D * f return sigma def _offset_sigma(self): # size of "x" arrays to integrate over numRoff = self._numRoff numTh = self._numTh numRbins = self._nbins maxsig = self._sigmaoffset.value.max() # inner/outer bin edges roff_1D = np.linspace(0., 4. * maxsig, numRoff) theta_1D = np.linspace(0., 2. * np.pi, numTh) rMpc_1D = self._rbins.value # reshape for broadcasting: (numTh,numRoff,numRbins) theta = theta_1D.reshape(numTh, 1, 1) roff = roff_1D.reshape(1, numRoff, 1) rMpc = rMpc_1D.reshape(1, 1, numRbins) r_eq13 = np.sqrt(rMpc ** 2 + roff ** 2 - 2. * rMpc * roff * np.cos(theta)) # 3D array r_eq13 -> 4D dimensionless radius (nlens) _set_dimensionless_radius(self, radii=r_eq13, integration=True) sigma = _centered_sigma(self) inner_integrand = sigma.value / (2. * np.pi) # INTEGRATE OVER theta sigma_of_RgivenRoff = simps(inner_integrand, x=theta_1D, axis=0, even='first') # theta is gone, now dimensions are: (numRoff,numRbins,nlens) sig_off_3D = self._sigmaoffset.value.reshape(1, 1, self._nlens) roff_v2 = roff_1D.reshape(numRoff, 1, 1) PofRoff = (roff_v2 / (sig_off_3D**2) * np.exp(-0.5 * (roff_v2 / sig_off_3D)**2)) dbl_integrand = sigma_of_RgivenRoff * PofRoff # INTEGRATE OVER Roff # (integration axis=0 after theta is gone). sigma_smoothed = simps(dbl_integrand, x=roff_1D, axis=0, even='first') # reset _x to correspond to input rbins (default) _set_dimensionless_radius(self) sigma_sm = np.array(sigma_smoothed.T) * units.solMass / units.pc**2 return sigma_sm if self._sigmaoffset is None: finalsigma = _centered_sigma(self) elif np.abs(self._sigmaoffset).sum() == 0: finalsigma = _centered_sigma(self) else: finalsigma = _offset_sigma(self) self._sigma_sm = finalsigma return finalsigma
python
def sigma_nfw(self): """Calculate NFW surface mass density profile. Generate the surface mass density profiles of each cluster halo, assuming a spherical NFW model. Optionally includes the effect of cluster miscentering offsets, if the parent object was initialized with offsets. Returns ---------- Quantity Surface mass density profiles (ndarray, in astropy.units of Msun/pc/pc). Each row corresponds to a single cluster halo. """ def _centered_sigma(self): # perfectly centered cluster case # calculate f bigF = np.zeros_like(self._x) f = np.zeros_like(self._x) numerator_arg = ((1. / self._x[self._x_small]) + np.sqrt((1. / (self._x[self._x_small]**2)) - 1.)) denominator = np.sqrt(1. - (self._x[self._x_small]**2)) bigF[self._x_small] = np.log(numerator_arg) / denominator bigF[self._x_big] = (np.arccos(1. / self._x[self._x_big]) / np.sqrt(self._x[self._x_big]**2 - 1.)) f = (1. - bigF) / (self._x**2 - 1.) f[self._x_one] = 1. / 3. if np.isnan(np.sum(f)) or np.isinf(np.sum(f)): print('\nERROR: f is not all real\n') # calculate & return centered profiles if f.ndim == 2: sigma = 2. * self._rs_dc_rcrit * f else: rs_dc_rcrit_4D = self._rs_dc_rcrit.T.reshape(1, 1, f.shape[2], f.shape[3]) sigma = 2. * rs_dc_rcrit_4D * f return sigma def _offset_sigma(self): # size of "x" arrays to integrate over numRoff = self._numRoff numTh = self._numTh numRbins = self._nbins maxsig = self._sigmaoffset.value.max() # inner/outer bin edges roff_1D = np.linspace(0., 4. * maxsig, numRoff) theta_1D = np.linspace(0., 2. * np.pi, numTh) rMpc_1D = self._rbins.value # reshape for broadcasting: (numTh,numRoff,numRbins) theta = theta_1D.reshape(numTh, 1, 1) roff = roff_1D.reshape(1, numRoff, 1) rMpc = rMpc_1D.reshape(1, 1, numRbins) r_eq13 = np.sqrt(rMpc ** 2 + roff ** 2 - 2. * rMpc * roff * np.cos(theta)) # 3D array r_eq13 -> 4D dimensionless radius (nlens) _set_dimensionless_radius(self, radii=r_eq13, integration=True) sigma = _centered_sigma(self) inner_integrand = sigma.value / (2. * np.pi) # INTEGRATE OVER theta sigma_of_RgivenRoff = simps(inner_integrand, x=theta_1D, axis=0, even='first') # theta is gone, now dimensions are: (numRoff,numRbins,nlens) sig_off_3D = self._sigmaoffset.value.reshape(1, 1, self._nlens) roff_v2 = roff_1D.reshape(numRoff, 1, 1) PofRoff = (roff_v2 / (sig_off_3D**2) * np.exp(-0.5 * (roff_v2 / sig_off_3D)**2)) dbl_integrand = sigma_of_RgivenRoff * PofRoff # INTEGRATE OVER Roff # (integration axis=0 after theta is gone). sigma_smoothed = simps(dbl_integrand, x=roff_1D, axis=0, even='first') # reset _x to correspond to input rbins (default) _set_dimensionless_radius(self) sigma_sm = np.array(sigma_smoothed.T) * units.solMass / units.pc**2 return sigma_sm if self._sigmaoffset is None: finalsigma = _centered_sigma(self) elif np.abs(self._sigmaoffset).sum() == 0: finalsigma = _centered_sigma(self) else: finalsigma = _offset_sigma(self) self._sigma_sm = finalsigma return finalsigma
[ "def", "sigma_nfw", "(", "self", ")", ":", "def", "_centered_sigma", "(", "self", ")", ":", "# perfectly centered cluster case", "# calculate f", "bigF", "=", "np", ".", "zeros_like", "(", "self", ".", "_x", ")", "f", "=", "np", ".", "zeros_like", "(", "se...
Calculate NFW surface mass density profile. Generate the surface mass density profiles of each cluster halo, assuming a spherical NFW model. Optionally includes the effect of cluster miscentering offsets, if the parent object was initialized with offsets. Returns ---------- Quantity Surface mass density profiles (ndarray, in astropy.units of Msun/pc/pc). Each row corresponds to a single cluster halo.
[ "Calculate", "NFW", "surface", "mass", "density", "profile", "." ]
train
https://github.com/jesford/cluster-lensing/blob/2815c1bb07d904ca91a80dae3f52090016768072/clusterlensing/nfw.py#L173-L278
jesford/cluster-lensing
clusterlensing/nfw.py
SurfaceMassDensity.deltasigma_nfw
def deltasigma_nfw(self): """Calculate NFW differential surface mass density profile. Generate the differential surface mass density profiles of each cluster halo, assuming a spherical NFW model. Optionally includes the effect of cluster miscentering offsets, if the parent object was initialized with offsets. Returns ---------- Quantity Differential surface mass density profiles (ndarray, in astropy.units of Msun/pc/pc). Each row corresponds to a single cluster halo. """ def _centered_dsigma(self): # calculate g firstpart = np.zeros_like(self._x) secondpart = np.zeros_like(self._x) g = np.zeros_like(self._x) small_1a = 4. / self._x[self._x_small]**2 small_1b = 2. / (self._x[self._x_small]**2 - 1.) small_1c = np.sqrt(1. - self._x[self._x_small]**2) firstpart[self._x_small] = (small_1a + small_1b) / small_1c big_1a = 8. / (self._x[self._x_big]**2 * np.sqrt(self._x[self._x_big]**2 - 1.)) big_1b = 4. / ((self._x[self._x_big]**2 - 1.)**1.5) firstpart[self._x_big] = big_1a + big_1b small_2a = np.sqrt((1. - self._x[self._x_small]) / (1. + self._x[self._x_small])) secondpart[self._x_small] = np.log((1. + small_2a) / (1. - small_2a)) big_2a = self._x[self._x_big] - 1. big_2b = 1. + self._x[self._x_big] secondpart[self._x_big] = np.arctan(np.sqrt(big_2a / big_2b)) both_3a = (4. / (self._x**2)) * np.log(self._x / 2.) both_3b = 2. / (self._x**2 - 1.) g = firstpart * secondpart + both_3a - both_3b g[self._x_one] = (10. / 3.) + 4. * np.log(0.5) if np.isnan(np.sum(g)) or np.isinf(np.sum(g)): print('\nERROR: g is not all real\n', g) # calculate & return centered profile deltasigma = self._rs_dc_rcrit * g return deltasigma def _offset_dsigma(self): original_rbins = self._rbins.value # if offset sigma was already calculated, use it! try: sigma_sm_rbins = self._sigma_sm except AttributeError: sigma_sm_rbins = self.sigma_nfw() innermost_sampling = 1.e-10 # stable for anything below 1e-5 inner_prec = self._numRinner r_inner = np.linspace(innermost_sampling, original_rbins.min(), endpoint=False, num=inner_prec) outer_prec = self._factorRouter * self._nbins r_outer = np.linspace(original_rbins.min(), original_rbins.max(), endpoint=False, num=outer_prec + 1)[1:] r_ext_unordered = np.hstack([r_inner, r_outer, original_rbins]) r_extended = np.sort(r_ext_unordered) # set temporary extended rbins, nbins, x, rs_dc_rcrit array self._rbins = r_extended * units.Mpc self._nbins = self._rbins.shape[0] _set_dimensionless_radius(self) # uses _rbins, _nlens rs_dc_rcrit = self._rs * self._delta_c * self._rho_crit self._rs_dc_rcrit = rs_dc_rcrit.reshape(self._nlens, 1).repeat(self._nbins, 1) sigma_sm_extended = self.sigma_nfw() mean_inside_sigma_sm = np.zeros([self._nlens, original_rbins.shape[0]]) for i, r in enumerate(original_rbins): index_of_rbin = np.where(r_extended == r)[0][0] x = r_extended[0:index_of_rbin + 1] y = sigma_sm_extended[:, 0:index_of_rbin + 1] * x integral = simps(y, x=x, axis=-1, even='first') # average of sigma_sm at r < rbin mean_inside_sigma_sm[:, i] = (2. / r**2) * integral mean_inside_sigma_sm = mean_inside_sigma_sm * (units.Msun / units.pc**2) # reset original rbins, nbins, x self._rbins = original_rbins * units.Mpc self._nbins = self._rbins.shape[0] _set_dimensionless_radius(self) rs_dc_rcrit = self._rs * self._delta_c * self._rho_crit self._rs_dc_rcrit = rs_dc_rcrit.reshape(self._nlens, 1).repeat(self._nbins, 1) self._sigma_sm = sigma_sm_rbins # reset to original sigma_sm dsigma_sm = mean_inside_sigma_sm - sigma_sm_rbins return dsigma_sm if self._sigmaoffset is None: finaldeltasigma = _centered_dsigma(self) elif np.abs(self._sigmaoffset).sum() == 0: finaldeltasigma = _centered_dsigma(self) else: finaldeltasigma = _offset_dsigma(self) return finaldeltasigma
python
def deltasigma_nfw(self): """Calculate NFW differential surface mass density profile. Generate the differential surface mass density profiles of each cluster halo, assuming a spherical NFW model. Optionally includes the effect of cluster miscentering offsets, if the parent object was initialized with offsets. Returns ---------- Quantity Differential surface mass density profiles (ndarray, in astropy.units of Msun/pc/pc). Each row corresponds to a single cluster halo. """ def _centered_dsigma(self): # calculate g firstpart = np.zeros_like(self._x) secondpart = np.zeros_like(self._x) g = np.zeros_like(self._x) small_1a = 4. / self._x[self._x_small]**2 small_1b = 2. / (self._x[self._x_small]**2 - 1.) small_1c = np.sqrt(1. - self._x[self._x_small]**2) firstpart[self._x_small] = (small_1a + small_1b) / small_1c big_1a = 8. / (self._x[self._x_big]**2 * np.sqrt(self._x[self._x_big]**2 - 1.)) big_1b = 4. / ((self._x[self._x_big]**2 - 1.)**1.5) firstpart[self._x_big] = big_1a + big_1b small_2a = np.sqrt((1. - self._x[self._x_small]) / (1. + self._x[self._x_small])) secondpart[self._x_small] = np.log((1. + small_2a) / (1. - small_2a)) big_2a = self._x[self._x_big] - 1. big_2b = 1. + self._x[self._x_big] secondpart[self._x_big] = np.arctan(np.sqrt(big_2a / big_2b)) both_3a = (4. / (self._x**2)) * np.log(self._x / 2.) both_3b = 2. / (self._x**2 - 1.) g = firstpart * secondpart + both_3a - both_3b g[self._x_one] = (10. / 3.) + 4. * np.log(0.5) if np.isnan(np.sum(g)) or np.isinf(np.sum(g)): print('\nERROR: g is not all real\n', g) # calculate & return centered profile deltasigma = self._rs_dc_rcrit * g return deltasigma def _offset_dsigma(self): original_rbins = self._rbins.value # if offset sigma was already calculated, use it! try: sigma_sm_rbins = self._sigma_sm except AttributeError: sigma_sm_rbins = self.sigma_nfw() innermost_sampling = 1.e-10 # stable for anything below 1e-5 inner_prec = self._numRinner r_inner = np.linspace(innermost_sampling, original_rbins.min(), endpoint=False, num=inner_prec) outer_prec = self._factorRouter * self._nbins r_outer = np.linspace(original_rbins.min(), original_rbins.max(), endpoint=False, num=outer_prec + 1)[1:] r_ext_unordered = np.hstack([r_inner, r_outer, original_rbins]) r_extended = np.sort(r_ext_unordered) # set temporary extended rbins, nbins, x, rs_dc_rcrit array self._rbins = r_extended * units.Mpc self._nbins = self._rbins.shape[0] _set_dimensionless_radius(self) # uses _rbins, _nlens rs_dc_rcrit = self._rs * self._delta_c * self._rho_crit self._rs_dc_rcrit = rs_dc_rcrit.reshape(self._nlens, 1).repeat(self._nbins, 1) sigma_sm_extended = self.sigma_nfw() mean_inside_sigma_sm = np.zeros([self._nlens, original_rbins.shape[0]]) for i, r in enumerate(original_rbins): index_of_rbin = np.where(r_extended == r)[0][0] x = r_extended[0:index_of_rbin + 1] y = sigma_sm_extended[:, 0:index_of_rbin + 1] * x integral = simps(y, x=x, axis=-1, even='first') # average of sigma_sm at r < rbin mean_inside_sigma_sm[:, i] = (2. / r**2) * integral mean_inside_sigma_sm = mean_inside_sigma_sm * (units.Msun / units.pc**2) # reset original rbins, nbins, x self._rbins = original_rbins * units.Mpc self._nbins = self._rbins.shape[0] _set_dimensionless_radius(self) rs_dc_rcrit = self._rs * self._delta_c * self._rho_crit self._rs_dc_rcrit = rs_dc_rcrit.reshape(self._nlens, 1).repeat(self._nbins, 1) self._sigma_sm = sigma_sm_rbins # reset to original sigma_sm dsigma_sm = mean_inside_sigma_sm - sigma_sm_rbins return dsigma_sm if self._sigmaoffset is None: finaldeltasigma = _centered_dsigma(self) elif np.abs(self._sigmaoffset).sum() == 0: finaldeltasigma = _centered_dsigma(self) else: finaldeltasigma = _offset_dsigma(self) return finaldeltasigma
[ "def", "deltasigma_nfw", "(", "self", ")", ":", "def", "_centered_dsigma", "(", "self", ")", ":", "# calculate g", "firstpart", "=", "np", ".", "zeros_like", "(", "self", ".", "_x", ")", "secondpart", "=", "np", ".", "zeros_like", "(", "self", ".", "_x",...
Calculate NFW differential surface mass density profile. Generate the differential surface mass density profiles of each cluster halo, assuming a spherical NFW model. Optionally includes the effect of cluster miscentering offsets, if the parent object was initialized with offsets. Returns ---------- Quantity Differential surface mass density profiles (ndarray, in astropy.units of Msun/pc/pc). Each row corresponds to a single cluster halo.
[ "Calculate", "NFW", "differential", "surface", "mass", "density", "profile", "." ]
train
https://github.com/jesford/cluster-lensing/blob/2815c1bb07d904ca91a80dae3f52090016768072/clusterlensing/nfw.py#L280-L401
all-umass/graphs
graphs/base/__init__.py
from_edge_pairs
def from_edge_pairs(pairs, num_vertices=None, symmetric=False, weights=None): '''Constructor for Graph objects based on edges given as pairs of vertices. pairs : integer array-like with shape (num_edges, 2) ''' if not symmetric: if weights is None: return EdgePairGraph(pairs, num_vertices=num_vertices) row, col = np.asarray(pairs).T row, weights = np.broadcast_arrays(row, weights) shape = None if num_vertices is None else (num_vertices, num_vertices) adj = ss.coo_matrix((weights, (row, col)), shape=shape) return SparseAdjacencyMatrixGraph(adj) # symmetric case G = SymmEdgePairGraph(pairs, num_vertices=num_vertices) if weights is None: return G # Convert to sparse adj graph with provided edge weights s = G.matrix('coo').astype(float) # shenanigans to assign edge weights in the right order flat_idx = np.ravel_multi_index(s.nonzero(), s.shape) r, c = np.transpose(pairs) rc_idx = np.ravel_multi_index((r,c), s.shape) cr_idx = np.ravel_multi_index((c,r), s.shape) order = np.argsort(flat_idx) flat_idx = flat_idx[order] s.data[order[np.searchsorted(flat_idx, rc_idx)]] = weights s.data[order[np.searchsorted(flat_idx, cr_idx)]] = weights return SparseAdjacencyMatrixGraph(s)
python
def from_edge_pairs(pairs, num_vertices=None, symmetric=False, weights=None): '''Constructor for Graph objects based on edges given as pairs of vertices. pairs : integer array-like with shape (num_edges, 2) ''' if not symmetric: if weights is None: return EdgePairGraph(pairs, num_vertices=num_vertices) row, col = np.asarray(pairs).T row, weights = np.broadcast_arrays(row, weights) shape = None if num_vertices is None else (num_vertices, num_vertices) adj = ss.coo_matrix((weights, (row, col)), shape=shape) return SparseAdjacencyMatrixGraph(adj) # symmetric case G = SymmEdgePairGraph(pairs, num_vertices=num_vertices) if weights is None: return G # Convert to sparse adj graph with provided edge weights s = G.matrix('coo').astype(float) # shenanigans to assign edge weights in the right order flat_idx = np.ravel_multi_index(s.nonzero(), s.shape) r, c = np.transpose(pairs) rc_idx = np.ravel_multi_index((r,c), s.shape) cr_idx = np.ravel_multi_index((c,r), s.shape) order = np.argsort(flat_idx) flat_idx = flat_idx[order] s.data[order[np.searchsorted(flat_idx, rc_idx)]] = weights s.data[order[np.searchsorted(flat_idx, cr_idx)]] = weights return SparseAdjacencyMatrixGraph(s)
[ "def", "from_edge_pairs", "(", "pairs", ",", "num_vertices", "=", "None", ",", "symmetric", "=", "False", ",", "weights", "=", "None", ")", ":", "if", "not", "symmetric", ":", "if", "weights", "is", "None", ":", "return", "EdgePairGraph", "(", "pairs", "...
Constructor for Graph objects based on edges given as pairs of vertices. pairs : integer array-like with shape (num_edges, 2)
[ "Constructor", "for", "Graph", "objects", "based", "on", "edges", "given", "as", "pairs", "of", "vertices", ".", "pairs", ":", "integer", "array", "-", "like", "with", "shape", "(", "num_edges", "2", ")" ]
train
https://github.com/all-umass/graphs/blob/4fbeb025dfe33340335f34300f58dd3809228822/graphs/base/__init__.py#L13-L40
limix/limix-core
limix_core/mean/mean_base.py
MeanBase.W
def W(self,value): """ set fixed effect design """ if value is None: value = sp.zeros((self._N, 0)) assert value.shape[0]==self._N, 'Dimension mismatch' self._K = value.shape[1] self._W = value self._notify() self.clear_cache('predict_in_sample','Yres')
python
def W(self,value): """ set fixed effect design """ if value is None: value = sp.zeros((self._N, 0)) assert value.shape[0]==self._N, 'Dimension mismatch' self._K = value.shape[1] self._W = value self._notify() self.clear_cache('predict_in_sample','Yres')
[ "def", "W", "(", "self", ",", "value", ")", ":", "if", "value", "is", "None", ":", "value", "=", "sp", ".", "zeros", "(", "(", "self", ".", "_N", ",", "0", ")", ")", "assert", "value", ".", "shape", "[", "0", "]", "==", "self", ".", "_N", "...
set fixed effect design
[ "set", "fixed", "effect", "design" ]
train
https://github.com/limix/limix-core/blob/5c590b4d351409f83ca320844b4897ce92203814/limix_core/mean/mean_base.py#L102-L109
limix/limix-core
limix_core/mean/mean_base.py
MeanBase.Wstar
def Wstar(self,value): """ set fixed effect design for predictions """ if value is None: self._use_to_predict = False else: assert value.shape[1]==self._K, 'Dimension mismatch' self._use_to_predict = True self._Wstar = value self.clear_cache('predict')
python
def Wstar(self,value): """ set fixed effect design for predictions """ if value is None: self._use_to_predict = False else: assert value.shape[1]==self._K, 'Dimension mismatch' self._use_to_predict = True self._Wstar = value self.clear_cache('predict')
[ "def", "Wstar", "(", "self", ",", "value", ")", ":", "if", "value", "is", "None", ":", "self", ".", "_use_to_predict", "=", "False", "else", ":", "assert", "value", ".", "shape", "[", "1", "]", "==", "self", ".", "_K", ",", "'Dimension mismatch'", "s...
set fixed effect design for predictions
[ "set", "fixed", "effect", "design", "for", "predictions" ]
train
https://github.com/limix/limix-core/blob/5c590b4d351409f83ca320844b4897ce92203814/limix_core/mean/mean_base.py#L112-L120
calmjs/calmjs.parse
src/calmjs/parse/handlers/obfuscation.py
obfuscate
def obfuscate( obfuscate_globals=False, shadow_funcname=False, reserved_keywords=()): """ An example, barebone name obfuscation ruleset obfuscate_globals If true, identifier names on the global scope will also be obfuscated. Default is False. shadow_funcname If True, obfuscated function names will be shadowed. Default is False. reserved_keywords A tuple of strings that should not be generated as obfuscated identifiers. """ def name_obfuscation_rules(): inst = Obfuscator( obfuscate_globals=obfuscate_globals, shadow_funcname=shadow_funcname, reserved_keywords=reserved_keywords, ) return { 'token_handler': token_handler_unobfuscate, 'deferrable_handlers': { Resolve: inst.resolve, }, 'prewalk_hooks': [ inst.prewalk_hook, ], } return name_obfuscation_rules
python
def obfuscate( obfuscate_globals=False, shadow_funcname=False, reserved_keywords=()): """ An example, barebone name obfuscation ruleset obfuscate_globals If true, identifier names on the global scope will also be obfuscated. Default is False. shadow_funcname If True, obfuscated function names will be shadowed. Default is False. reserved_keywords A tuple of strings that should not be generated as obfuscated identifiers. """ def name_obfuscation_rules(): inst = Obfuscator( obfuscate_globals=obfuscate_globals, shadow_funcname=shadow_funcname, reserved_keywords=reserved_keywords, ) return { 'token_handler': token_handler_unobfuscate, 'deferrable_handlers': { Resolve: inst.resolve, }, 'prewalk_hooks': [ inst.prewalk_hook, ], } return name_obfuscation_rules
[ "def", "obfuscate", "(", "obfuscate_globals", "=", "False", ",", "shadow_funcname", "=", "False", ",", "reserved_keywords", "=", "(", ")", ")", ":", "def", "name_obfuscation_rules", "(", ")", ":", "inst", "=", "Obfuscator", "(", "obfuscate_globals", "=", "obfu...
An example, barebone name obfuscation ruleset obfuscate_globals If true, identifier names on the global scope will also be obfuscated. Default is False. shadow_funcname If True, obfuscated function names will be shadowed. Default is False. reserved_keywords A tuple of strings that should not be generated as obfuscated identifiers.
[ "An", "example", "barebone", "name", "obfuscation", "ruleset" ]
train
https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/handlers/obfuscation.py#L528-L559
calmjs/calmjs.parse
src/calmjs/parse/handlers/obfuscation.py
Scope.declared_symbols
def declared_symbols(self): """ Return all local symbols here, and also of the parents """ return self.local_declared_symbols | ( self.parent.declared_symbols if self.parent else set())
python
def declared_symbols(self): """ Return all local symbols here, and also of the parents """ return self.local_declared_symbols | ( self.parent.declared_symbols if self.parent else set())
[ "def", "declared_symbols", "(", "self", ")", ":", "return", "self", ".", "local_declared_symbols", "|", "(", "self", ".", "parent", ".", "declared_symbols", "if", "self", ".", "parent", "else", "set", "(", ")", ")" ]
Return all local symbols here, and also of the parents
[ "Return", "all", "local", "symbols", "here", "and", "also", "of", "the", "parents" ]
train
https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/handlers/obfuscation.py#L92-L98
calmjs/calmjs.parse
src/calmjs/parse/handlers/obfuscation.py
Scope.global_symbols
def global_symbols(self): """ These are symbols that have been referenced, but not declared within this scope or any parent scopes. """ declared_symbols = self.declared_symbols return set( s for s in self.referenced_symbols if s not in declared_symbols)
python
def global_symbols(self): """ These are symbols that have been referenced, but not declared within this scope or any parent scopes. """ declared_symbols = self.declared_symbols return set( s for s in self.referenced_symbols if s not in declared_symbols)
[ "def", "global_symbols", "(", "self", ")", ":", "declared_symbols", "=", "self", ".", "declared_symbols", "return", "set", "(", "s", "for", "s", "in", "self", ".", "referenced_symbols", "if", "s", "not", "in", "declared_symbols", ")" ]
These are symbols that have been referenced, but not declared within this scope or any parent scopes.
[ "These", "are", "symbols", "that", "have", "been", "referenced", "but", "not", "declared", "within", "this", "scope", "or", "any", "parent", "scopes", "." ]
train
https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/handlers/obfuscation.py#L101-L109
calmjs/calmjs.parse
src/calmjs/parse/handlers/obfuscation.py
Scope.global_symbols_in_children
def global_symbols_in_children(self): """ This is based on all children referenced symbols that have not been declared. The intended use case is to ban the symbols from being used as remapped symbol values. """ result = set() for child in self.children: result |= ( child.global_symbols | child.global_symbols_in_children) return result
python
def global_symbols_in_children(self): """ This is based on all children referenced symbols that have not been declared. The intended use case is to ban the symbols from being used as remapped symbol values. """ result = set() for child in self.children: result |= ( child.global_symbols | child.global_symbols_in_children) return result
[ "def", "global_symbols_in_children", "(", "self", ")", ":", "result", "=", "set", "(", ")", "for", "child", "in", "self", ".", "children", ":", "result", "|=", "(", "child", ".", "global_symbols", "|", "child", ".", "global_symbols_in_children", ")", "return...
This is based on all children referenced symbols that have not been declared. The intended use case is to ban the symbols from being used as remapped symbol values.
[ "This", "is", "based", "on", "all", "children", "referenced", "symbols", "that", "have", "not", "been", "declared", "." ]
train
https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/handlers/obfuscation.py#L112-L126
calmjs/calmjs.parse
src/calmjs/parse/handlers/obfuscation.py
Scope.close
def close(self): """ Mark the scope as closed, i.e. all symbols have been declared, and no further declarations should be done. """ if self._closed: raise ValueError('scope is already marked as closed') # By letting parent know which symbols this scope has leaked, it # will let them reserve all lowest identifiers first. if self.parent: for symbol, c in self.leaked_referenced_symbols.items(): self.parent.reference(symbol, c) self._closed = True
python
def close(self): """ Mark the scope as closed, i.e. all symbols have been declared, and no further declarations should be done. """ if self._closed: raise ValueError('scope is already marked as closed') # By letting parent know which symbols this scope has leaked, it # will let them reserve all lowest identifiers first. if self.parent: for symbol, c in self.leaked_referenced_symbols.items(): self.parent.reference(symbol, c) self._closed = True
[ "def", "close", "(", "self", ")", ":", "if", "self", ".", "_closed", ":", "raise", "ValueError", "(", "'scope is already marked as closed'", ")", "# By letting parent know which symbols this scope has leaked, it", "# will let them reserve all lowest identifiers first.", "if", "...
Mark the scope as closed, i.e. all symbols have been declared, and no further declarations should be done.
[ "Mark", "the", "scope", "as", "closed", "i", ".", "e", ".", "all", "symbols", "have", "been", "declared", "and", "no", "further", "declarations", "should", "be", "done", "." ]
train
https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/handlers/obfuscation.py#L155-L170
calmjs/calmjs.parse
src/calmjs/parse/handlers/obfuscation.py
Scope._reserved_symbols
def _reserved_symbols(self): """ Helper property for the build_remap_symbols method. This property first resolves _all_ local references from parents, skipping all locally declared symbols as the goal is to generate a local mapping for them, but in a way not to shadow over any already declared symbols from parents, and also the implicit globals in all children. This is marked "private" as there are a number of computations involved, and is really meant for the build_remap_symbols to use for its standard flow. """ # In practice, and as a possible optimisation, the parent's # remapped symbols table can be merged into this instance, but # this bloats memory use and cause unspecified reservations that # may not be applicable this or any child scope. So for clarity # and purity of references made, this somewhat more involved way # is done instead. remapped_parents_symbols = { self.resolve(v) for v in self.non_local_symbols} return ( # block implicit children globals. self.global_symbols_in_children | # also not any global symbols self.global_symbols | # also all remapped parent symbols referenced here remapped_parents_symbols )
python
def _reserved_symbols(self): """ Helper property for the build_remap_symbols method. This property first resolves _all_ local references from parents, skipping all locally declared symbols as the goal is to generate a local mapping for them, but in a way not to shadow over any already declared symbols from parents, and also the implicit globals in all children. This is marked "private" as there are a number of computations involved, and is really meant for the build_remap_symbols to use for its standard flow. """ # In practice, and as a possible optimisation, the parent's # remapped symbols table can be merged into this instance, but # this bloats memory use and cause unspecified reservations that # may not be applicable this or any child scope. So for clarity # and purity of references made, this somewhat more involved way # is done instead. remapped_parents_symbols = { self.resolve(v) for v in self.non_local_symbols} return ( # block implicit children globals. self.global_symbols_in_children | # also not any global symbols self.global_symbols | # also all remapped parent symbols referenced here remapped_parents_symbols )
[ "def", "_reserved_symbols", "(", "self", ")", ":", "# In practice, and as a possible optimisation, the parent's", "# remapped symbols table can be merged into this instance, but", "# this bloats memory use and cause unspecified reservations that", "# may not be applicable this or any child scope. ...
Helper property for the build_remap_symbols method. This property first resolves _all_ local references from parents, skipping all locally declared symbols as the goal is to generate a local mapping for them, but in a way not to shadow over any already declared symbols from parents, and also the implicit globals in all children. This is marked "private" as there are a number of computations involved, and is really meant for the build_remap_symbols to use for its standard flow.
[ "Helper", "property", "for", "the", "build_remap_symbols", "method", ".", "This", "property", "first", "resolves", "_all_", "local", "references", "from", "parents", "skipping", "all", "locally", "declared", "symbols", "as", "the", "goal", "is", "to", "generate", ...
train
https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/handlers/obfuscation.py#L182-L212
calmjs/calmjs.parse
src/calmjs/parse/handlers/obfuscation.py
Scope.build_remap_symbols
def build_remap_symbols(self, name_generator, children_only=True): """ This builds the replacement table for all the defined symbols for all the children, and this scope, if the children_only argument is False. """ if not children_only: replacement = name_generator(skip=(self._reserved_symbols)) for symbol, c in reversed(sorted( self.referenced_symbols.items(), key=itemgetter(1, 0))): if symbol not in self.local_declared_symbols: continue self.remapped_symbols[symbol] = next(replacement) for child in self.children: child.build_remap_symbols(name_generator, False)
python
def build_remap_symbols(self, name_generator, children_only=True): """ This builds the replacement table for all the defined symbols for all the children, and this scope, if the children_only argument is False. """ if not children_only: replacement = name_generator(skip=(self._reserved_symbols)) for symbol, c in reversed(sorted( self.referenced_symbols.items(), key=itemgetter(1, 0))): if symbol not in self.local_declared_symbols: continue self.remapped_symbols[symbol] = next(replacement) for child in self.children: child.build_remap_symbols(name_generator, False)
[ "def", "build_remap_symbols", "(", "self", ",", "name_generator", ",", "children_only", "=", "True", ")", ":", "if", "not", "children_only", ":", "replacement", "=", "name_generator", "(", "skip", "=", "(", "self", ".", "_reserved_symbols", ")", ")", "for", ...
This builds the replacement table for all the defined symbols for all the children, and this scope, if the children_only argument is False.
[ "This", "builds", "the", "replacement", "table", "for", "all", "the", "defined", "symbols", "for", "all", "the", "children", "and", "this", "scope", "if", "the", "children_only", "argument", "is", "False", "." ]
train
https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/handlers/obfuscation.py#L214-L230
calmjs/calmjs.parse
src/calmjs/parse/handlers/obfuscation.py
Scope.nest
def nest(self, node, cls=None): """ Create a new nested scope that is within this instance, binding the provided node to it. """ if cls is None: cls = type(self) nested_scope = cls(node, self) self.children.append(nested_scope) return nested_scope
python
def nest(self, node, cls=None): """ Create a new nested scope that is within this instance, binding the provided node to it. """ if cls is None: cls = type(self) nested_scope = cls(node, self) self.children.append(nested_scope) return nested_scope
[ "def", "nest", "(", "self", ",", "node", ",", "cls", "=", "None", ")", ":", "if", "cls", "is", "None", ":", "cls", "=", "type", "(", "self", ")", "nested_scope", "=", "cls", "(", "node", ",", "self", ")", "self", ".", "children", ".", "append", ...
Create a new nested scope that is within this instance, binding the provided node to it.
[ "Create", "a", "new", "nested", "scope", "that", "is", "within", "this", "instance", "binding", "the", "provided", "node", "to", "it", "." ]
train
https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/handlers/obfuscation.py#L240-L251
calmjs/calmjs.parse
src/calmjs/parse/handlers/obfuscation.py
CatchScope.declare
def declare(self, symbol): """ Nothing gets declared here - it's the parents problem, except for the case where the symbol is the one we have here. """ if symbol != self.catch_symbol: self.parent.declare(symbol)
python
def declare(self, symbol): """ Nothing gets declared here - it's the parents problem, except for the case where the symbol is the one we have here. """ if symbol != self.catch_symbol: self.parent.declare(symbol)
[ "def", "declare", "(", "self", ",", "symbol", ")", ":", "if", "symbol", "!=", "self", ".", "catch_symbol", ":", "self", ".", "parent", ".", "declare", "(", "symbol", ")" ]
Nothing gets declared here - it's the parents problem, except for the case where the symbol is the one we have here.
[ "Nothing", "gets", "declared", "here", "-", "it", "s", "the", "parents", "problem", "except", "for", "the", "case", "where", "the", "symbol", "is", "the", "one", "we", "have", "here", "." ]
train
https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/handlers/obfuscation.py#L313-L320
calmjs/calmjs.parse
src/calmjs/parse/handlers/obfuscation.py
CatchScope.reference
def reference(self, symbol, count=1): """ However, if referenced, ensure that the counter is applied to the catch symbol. """ if symbol == self.catch_symbol: self.catch_symbol_usage += count else: self.parent.reference(symbol, count)
python
def reference(self, symbol, count=1): """ However, if referenced, ensure that the counter is applied to the catch symbol. """ if symbol == self.catch_symbol: self.catch_symbol_usage += count else: self.parent.reference(symbol, count)
[ "def", "reference", "(", "self", ",", "symbol", ",", "count", "=", "1", ")", ":", "if", "symbol", "==", "self", ".", "catch_symbol", ":", "self", ".", "catch_symbol_usage", "+=", "count", "else", ":", "self", ".", "parent", ".", "reference", "(", "symb...
However, if referenced, ensure that the counter is applied to the catch symbol.
[ "However", "if", "referenced", "ensure", "that", "the", "counter", "is", "applied", "to", "the", "catch", "symbol", "." ]
train
https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/handlers/obfuscation.py#L322-L331
calmjs/calmjs.parse
src/calmjs/parse/handlers/obfuscation.py
CatchScope.build_remap_symbols
def build_remap_symbols(self, name_generator, children_only=None): """ The children_only flag is inapplicable, but this is included as the Scope class is defined like so. Here this simply just place the catch symbol with the next replacement available. """ replacement = name_generator(skip=(self._reserved_symbols)) self.remapped_symbols[self.catch_symbol] = next(replacement) # also to continue down the children. for child in self.children: child.build_remap_symbols(name_generator, False)
python
def build_remap_symbols(self, name_generator, children_only=None): """ The children_only flag is inapplicable, but this is included as the Scope class is defined like so. Here this simply just place the catch symbol with the next replacement available. """ replacement = name_generator(skip=(self._reserved_symbols)) self.remapped_symbols[self.catch_symbol] = next(replacement) # also to continue down the children. for child in self.children: child.build_remap_symbols(name_generator, False)
[ "def", "build_remap_symbols", "(", "self", ",", "name_generator", ",", "children_only", "=", "None", ")", ":", "replacement", "=", "name_generator", "(", "skip", "=", "(", "self", ".", "_reserved_symbols", ")", ")", "self", ".", "remapped_symbols", "[", "self"...
The children_only flag is inapplicable, but this is included as the Scope class is defined like so. Here this simply just place the catch symbol with the next replacement available.
[ "The", "children_only", "flag", "is", "inapplicable", "but", "this", "is", "included", "as", "the", "Scope", "class", "is", "defined", "like", "so", "." ]
train
https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/handlers/obfuscation.py#L346-L360
calmjs/calmjs.parse
src/calmjs/parse/handlers/obfuscation.py
Obfuscator.register_reference
def register_reference(self, dispatcher, node): """ Register this identifier to the current scope, and mark it as referenced in the current scope. """ # the identifier node itself will be mapped to the current scope # for the resolve to work # This should probably WARN about the node object being already # assigned to an existing scope that isn't current_scope. self.identifiers[node] = self.current_scope self.current_scope.reference(node.value)
python
def register_reference(self, dispatcher, node): """ Register this identifier to the current scope, and mark it as referenced in the current scope. """ # the identifier node itself will be mapped to the current scope # for the resolve to work # This should probably WARN about the node object being already # assigned to an existing scope that isn't current_scope. self.identifiers[node] = self.current_scope self.current_scope.reference(node.value)
[ "def", "register_reference", "(", "self", ",", "dispatcher", ",", "node", ")", ":", "# the identifier node itself will be mapped to the current scope", "# for the resolve to work", "# This should probably WARN about the node object being already", "# assigned to an existing scope that isn'...
Register this identifier to the current scope, and mark it as referenced in the current scope.
[ "Register", "this", "identifier", "to", "the", "current", "scope", "and", "mark", "it", "as", "referenced", "in", "the", "current", "scope", "." ]
train
https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/handlers/obfuscation.py#L439-L450
calmjs/calmjs.parse
src/calmjs/parse/handlers/obfuscation.py
Obfuscator.shadow_reference
def shadow_reference(self, dispatcher, node): """ Only simply make a reference to the value in the current scope, specifically for the FuncBase type. """ # as opposed to the previous one, only add the value of the # identifier itself to the scope so that it becomes reserved. self.current_scope.reference(node.identifier.value)
python
def shadow_reference(self, dispatcher, node): """ Only simply make a reference to the value in the current scope, specifically for the FuncBase type. """ # as opposed to the previous one, only add the value of the # identifier itself to the scope so that it becomes reserved. self.current_scope.reference(node.identifier.value)
[ "def", "shadow_reference", "(", "self", ",", "dispatcher", ",", "node", ")", ":", "# as opposed to the previous one, only add the value of the", "# identifier itself to the scope so that it becomes reserved.", "self", ".", "current_scope", ".", "reference", "(", "node", ".", ...
Only simply make a reference to the value in the current scope, specifically for the FuncBase type.
[ "Only", "simply", "make", "a", "reference", "to", "the", "value", "in", "the", "current", "scope", "specifically", "for", "the", "FuncBase", "type", "." ]
train
https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/handlers/obfuscation.py#L452-L460
calmjs/calmjs.parse
src/calmjs/parse/handlers/obfuscation.py
Obfuscator.resolve
def resolve(self, dispatcher, node): """ For the given node, resolve it into the scope it was declared at, and if one was found, return its value. """ scope = self.identifiers.get(node) if not scope: return node.value return scope.resolve(node.value)
python
def resolve(self, dispatcher, node): """ For the given node, resolve it into the scope it was declared at, and if one was found, return its value. """ scope = self.identifiers.get(node) if not scope: return node.value return scope.resolve(node.value)
[ "def", "resolve", "(", "self", ",", "dispatcher", ",", "node", ")", ":", "scope", "=", "self", ".", "identifiers", ".", "get", "(", "node", ")", "if", "not", "scope", ":", "return", "node", ".", "value", "return", "scope", ".", "resolve", "(", "node"...
For the given node, resolve it into the scope it was declared at, and if one was found, return its value.
[ "For", "the", "given", "node", "resolve", "it", "into", "the", "scope", "it", "was", "declared", "at", "and", "if", "one", "was", "found", "return", "its", "value", "." ]
train
https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/handlers/obfuscation.py#L462-L471
calmjs/calmjs.parse
src/calmjs/parse/handlers/obfuscation.py
Obfuscator.walk
def walk(self, dispatcher, node): """ Walk through the node with a custom dispatcher for extraction of details that are required. """ deferrable_handlers = { Declare: self.declare, Resolve: self.register_reference, } layout_handlers = { PushScope: self.push_scope, PopScope: self.pop_scope, PushCatch: self.push_catch, # should really be different, but given that the # mechanism is within the same tree, the only difference # would be sanity check which should have been tested in # the first place in the primitives anyway. PopCatch: self.pop_scope, } if not self.shadow_funcname: layout_handlers[ResolveFuncName] = self.shadow_reference local_dispatcher = Dispatcher( definitions=dict(dispatcher), token_handler=None, layout_handlers=layout_handlers, deferrable_handlers=deferrable_handlers, ) return list(walk(local_dispatcher, node))
python
def walk(self, dispatcher, node): """ Walk through the node with a custom dispatcher for extraction of details that are required. """ deferrable_handlers = { Declare: self.declare, Resolve: self.register_reference, } layout_handlers = { PushScope: self.push_scope, PopScope: self.pop_scope, PushCatch: self.push_catch, # should really be different, but given that the # mechanism is within the same tree, the only difference # would be sanity check which should have been tested in # the first place in the primitives anyway. PopCatch: self.pop_scope, } if not self.shadow_funcname: layout_handlers[ResolveFuncName] = self.shadow_reference local_dispatcher = Dispatcher( definitions=dict(dispatcher), token_handler=None, layout_handlers=layout_handlers, deferrable_handlers=deferrable_handlers, ) return list(walk(local_dispatcher, node))
[ "def", "walk", "(", "self", ",", "dispatcher", ",", "node", ")", ":", "deferrable_handlers", "=", "{", "Declare", ":", "self", ".", "declare", ",", "Resolve", ":", "self", ".", "register_reference", ",", "}", "layout_handlers", "=", "{", "PushScope", ":", ...
Walk through the node with a custom dispatcher for extraction of details that are required.
[ "Walk", "through", "the", "node", "with", "a", "custom", "dispatcher", "for", "extraction", "of", "details", "that", "are", "required", "." ]
train
https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/handlers/obfuscation.py#L473-L503
calmjs/calmjs.parse
src/calmjs/parse/handlers/obfuscation.py
Obfuscator.finalize
def finalize(self): """ Finalize the run - build the name generator and use it to build the remap symbol tables. """ self.global_scope.close() name_generator = NameGenerator(skip=self.reserved_keywords) self.global_scope.build_remap_symbols( name_generator, children_only=not self.obfuscate_globals, )
python
def finalize(self): """ Finalize the run - build the name generator and use it to build the remap symbol tables. """ self.global_scope.close() name_generator = NameGenerator(skip=self.reserved_keywords) self.global_scope.build_remap_symbols( name_generator, children_only=not self.obfuscate_globals, )
[ "def", "finalize", "(", "self", ")", ":", "self", ".", "global_scope", ".", "close", "(", ")", "name_generator", "=", "NameGenerator", "(", "skip", "=", "self", ".", "reserved_keywords", ")", "self", ".", "global_scope", ".", "build_remap_symbols", "(", "nam...
Finalize the run - build the name generator and use it to build the remap symbol tables.
[ "Finalize", "the", "run", "-", "build", "the", "name", "generator", "and", "use", "it", "to", "build", "the", "remap", "symbol", "tables", "." ]
train
https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/handlers/obfuscation.py#L505-L516
calmjs/calmjs.parse
src/calmjs/parse/handlers/obfuscation.py
Obfuscator.prewalk_hook
def prewalk_hook(self, dispatcher, node): """ This is for the Unparser to use as a prewalk hook. """ self.walk(dispatcher, node) self.finalize() return node
python
def prewalk_hook(self, dispatcher, node): """ This is for the Unparser to use as a prewalk hook. """ self.walk(dispatcher, node) self.finalize() return node
[ "def", "prewalk_hook", "(", "self", ",", "dispatcher", ",", "node", ")", ":", "self", ".", "walk", "(", "dispatcher", ",", "node", ")", "self", ".", "finalize", "(", ")", "return", "node" ]
This is for the Unparser to use as a prewalk hook.
[ "This", "is", "for", "the", "Unparser", "to", "use", "as", "a", "prewalk", "hook", "." ]
train
https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/handlers/obfuscation.py#L518-L525
pyroscope/pyrobase
src/pyrobase/paver/housekeeping.py
clean
def clean(): "take out the trash" src_dir = easy.options.setdefault("docs", {}).get('src_dir', None) if src_dir is None: src_dir = 'src' if easy.path('src').exists() else '.' with easy.pushd(src_dir): for pkg in set(easy.options.setup.packages) | set(("tests",)): for filename in glob.glob(pkg.replace('.', os.sep) + "/*.py[oc~]"): easy.path(filename).remove()
python
def clean(): "take out the trash" src_dir = easy.options.setdefault("docs", {}).get('src_dir', None) if src_dir is None: src_dir = 'src' if easy.path('src').exists() else '.' with easy.pushd(src_dir): for pkg in set(easy.options.setup.packages) | set(("tests",)): for filename in glob.glob(pkg.replace('.', os.sep) + "/*.py[oc~]"): easy.path(filename).remove()
[ "def", "clean", "(", ")", ":", "src_dir", "=", "easy", ".", "options", ".", "setdefault", "(", "\"docs\"", ",", "{", "}", ")", ".", "get", "(", "'src_dir'", ",", "None", ")", "if", "src_dir", "is", "None", ":", "src_dir", "=", "'src'", "if", "easy"...
take out the trash
[ "take", "out", "the", "trash" ]
train
https://github.com/pyroscope/pyrobase/blob/7a2591baa492c3d8997ab4801b97c7b1f2ebc6b1/src/pyrobase/paver/housekeeping.py#L32-L41
mikekatz04/BOWIE
snr_calculator_folder/gwsnrcalc/genconutils/forminput.py
Generate._set_grid_info
def _set_grid_info(self, which, low, high, num, scale, name): """Set the grid values for x or y. Create information for the grid of x and y values. Args: which (str): `x` or `y`. low/high (float): Lowest/highest value for the axis. num (int): Number of points on axis. scale (str): Scale of the axis. Choices are 'log' or 'lin'. name (str): Name representing the axis. See GenerateContainer documentation for options for the name. unit (str): Unit for this axis quantity. See GenerateContainer documentation for options for the units. Raises: ValueError: If scale is not 'log' or 'lin'. """ setattr(self.generate_info, which + '_low', low) setattr(self.generate_info, which + '_high', high) setattr(self.generate_info, 'num_' + which, num) setattr(self.generate_info, which + 'val_name', name) if scale not in ['lin', 'log']: raise ValueError('{} scale must be lin or log.'.format(which)) setattr(self.generate_info, which + 'scale', scale) return
python
def _set_grid_info(self, which, low, high, num, scale, name): """Set the grid values for x or y. Create information for the grid of x and y values. Args: which (str): `x` or `y`. low/high (float): Lowest/highest value for the axis. num (int): Number of points on axis. scale (str): Scale of the axis. Choices are 'log' or 'lin'. name (str): Name representing the axis. See GenerateContainer documentation for options for the name. unit (str): Unit for this axis quantity. See GenerateContainer documentation for options for the units. Raises: ValueError: If scale is not 'log' or 'lin'. """ setattr(self.generate_info, which + '_low', low) setattr(self.generate_info, which + '_high', high) setattr(self.generate_info, 'num_' + which, num) setattr(self.generate_info, which + 'val_name', name) if scale not in ['lin', 'log']: raise ValueError('{} scale must be lin or log.'.format(which)) setattr(self.generate_info, which + 'scale', scale) return
[ "def", "_set_grid_info", "(", "self", ",", "which", ",", "low", ",", "high", ",", "num", ",", "scale", ",", "name", ")", ":", "setattr", "(", "self", ".", "generate_info", ",", "which", "+", "'_low'", ",", "low", ")", "setattr", "(", "self", ".", "...
Set the grid values for x or y. Create information for the grid of x and y values. Args: which (str): `x` or `y`. low/high (float): Lowest/highest value for the axis. num (int): Number of points on axis. scale (str): Scale of the axis. Choices are 'log' or 'lin'. name (str): Name representing the axis. See GenerateContainer documentation for options for the name. unit (str): Unit for this axis quantity. See GenerateContainer documentation for options for the units. Raises: ValueError: If scale is not 'log' or 'lin'.
[ "Set", "the", "grid", "values", "for", "x", "or", "y", "." ]
train
https://github.com/mikekatz04/BOWIE/blob/a941342a3536cb57c817a1643896d99a3f354a86/snr_calculator_folder/gwsnrcalc/genconutils/forminput.py#L65-L92
mikekatz04/BOWIE
snr_calculator_folder/gwsnrcalc/genconutils/forminput.py
Generate.set_y_grid_info
def set_y_grid_info(self, y_low, y_high, num_y, yscale, yval_name): """Set the grid values for y. Create information for the grid of y values. Args: num_y (int): Number of points on axis. y_low/y_high (float): Lowest/highest value for the axis. yscale (str): Scale of the axis. Choices are 'log' or 'lin'. yval_name (str): Name representing the axis. See GenerateContainer documentation for options for the name. """ self._set_grid_info('y', y_low, y_high, num_y, yscale, yval_name) return
python
def set_y_grid_info(self, y_low, y_high, num_y, yscale, yval_name): """Set the grid values for y. Create information for the grid of y values. Args: num_y (int): Number of points on axis. y_low/y_high (float): Lowest/highest value for the axis. yscale (str): Scale of the axis. Choices are 'log' or 'lin'. yval_name (str): Name representing the axis. See GenerateContainer documentation for options for the name. """ self._set_grid_info('y', y_low, y_high, num_y, yscale, yval_name) return
[ "def", "set_y_grid_info", "(", "self", ",", "y_low", ",", "y_high", ",", "num_y", ",", "yscale", ",", "yval_name", ")", ":", "self", ".", "_set_grid_info", "(", "'y'", ",", "y_low", ",", "y_high", ",", "num_y", ",", "yscale", ",", "yval_name", ")", "re...
Set the grid values for y. Create information for the grid of y values. Args: num_y (int): Number of points on axis. y_low/y_high (float): Lowest/highest value for the axis. yscale (str): Scale of the axis. Choices are 'log' or 'lin'. yval_name (str): Name representing the axis. See GenerateContainer documentation for options for the name.
[ "Set", "the", "grid", "values", "for", "y", "." ]
train
https://github.com/mikekatz04/BOWIE/blob/a941342a3536cb57c817a1643896d99a3f354a86/snr_calculator_folder/gwsnrcalc/genconutils/forminput.py#L94-L108
mikekatz04/BOWIE
snr_calculator_folder/gwsnrcalc/genconutils/forminput.py
Generate.set_x_grid_info
def set_x_grid_info(self, x_low, x_high, num_x, xscale, xval_name): """Set the grid values for x. Create information for the grid of x values. Args: num_x (int): Number of points on axis. x_low/x_high (float): Lowest/highest value for the axis. xscale (str): Scale of the axis. Choices are 'log' or 'lin'. xval_name (str): Name representing the axis. See GenerateContainer documentation for options for the name. """ self._set_grid_info('x', x_low, x_high, num_x, xscale, xval_name) return
python
def set_x_grid_info(self, x_low, x_high, num_x, xscale, xval_name): """Set the grid values for x. Create information for the grid of x values. Args: num_x (int): Number of points on axis. x_low/x_high (float): Lowest/highest value for the axis. xscale (str): Scale of the axis. Choices are 'log' or 'lin'. xval_name (str): Name representing the axis. See GenerateContainer documentation for options for the name. """ self._set_grid_info('x', x_low, x_high, num_x, xscale, xval_name) return
[ "def", "set_x_grid_info", "(", "self", ",", "x_low", ",", "x_high", ",", "num_x", ",", "xscale", ",", "xval_name", ")", ":", "self", ".", "_set_grid_info", "(", "'x'", ",", "x_low", ",", "x_high", ",", "num_x", ",", "xscale", ",", "xval_name", ")", "re...
Set the grid values for x. Create information for the grid of x values. Args: num_x (int): Number of points on axis. x_low/x_high (float): Lowest/highest value for the axis. xscale (str): Scale of the axis. Choices are 'log' or 'lin'. xval_name (str): Name representing the axis. See GenerateContainer documentation for options for the name.
[ "Set", "the", "grid", "values", "for", "x", "." ]
train
https://github.com/mikekatz04/BOWIE/blob/a941342a3536cb57c817a1643896d99a3f354a86/snr_calculator_folder/gwsnrcalc/genconutils/forminput.py#L110-L124
mikekatz04/BOWIE
snr_calculator_folder/gwsnrcalc/genconutils/forminput.py
SensitivityInput.add_noise_curve
def add_noise_curve(self, name, noise_type='ASD', is_wd_background=False): """Add a noise curve for generation. This will add a noise curve for an SNR calculation by appending to the sensitivity_curves list within the sensitivity_input dictionary. The name of the noise curve prior to the file extension will appear as its label in the final output dataset. Therefore, it is recommended prior to running the generator that file names are renamed to simple names for later reference. Args: name (str): Name of noise curve including file extension inside input_folder. noise_type (str, optional): Type of noise. Choices are `ASD`, `PSD`, or `char_strain`. Default is ASD. is_wd_background (bool, optional): If True, this sensitivity is used as the white dwarf background noise. Default is False. """ if is_wd_background: self.sensitivity_input.wd_noise = name self.sensitivity_input.wd_noise_type_in = noise_type else: if 'sensitivity_curves' not in self.sensitivity_input.__dict__: self.sensitivity_input.sensitivity_curves = [] if 'noise_type_in' not in self.sensitivity_input.__dict__: self.sensitivity_input.noise_type_in = [] self.sensitivity_input.sensitivity_curves.append(name) self.sensitivity_input.noise_type_in.append(noise_type) return
python
def add_noise_curve(self, name, noise_type='ASD', is_wd_background=False): """Add a noise curve for generation. This will add a noise curve for an SNR calculation by appending to the sensitivity_curves list within the sensitivity_input dictionary. The name of the noise curve prior to the file extension will appear as its label in the final output dataset. Therefore, it is recommended prior to running the generator that file names are renamed to simple names for later reference. Args: name (str): Name of noise curve including file extension inside input_folder. noise_type (str, optional): Type of noise. Choices are `ASD`, `PSD`, or `char_strain`. Default is ASD. is_wd_background (bool, optional): If True, this sensitivity is used as the white dwarf background noise. Default is False. """ if is_wd_background: self.sensitivity_input.wd_noise = name self.sensitivity_input.wd_noise_type_in = noise_type else: if 'sensitivity_curves' not in self.sensitivity_input.__dict__: self.sensitivity_input.sensitivity_curves = [] if 'noise_type_in' not in self.sensitivity_input.__dict__: self.sensitivity_input.noise_type_in = [] self.sensitivity_input.sensitivity_curves.append(name) self.sensitivity_input.noise_type_in.append(noise_type) return
[ "def", "add_noise_curve", "(", "self", ",", "name", ",", "noise_type", "=", "'ASD'", ",", "is_wd_background", "=", "False", ")", ":", "if", "is_wd_background", ":", "self", ".", "sensitivity_input", ".", "wd_noise", "=", "name", "self", ".", "sensitivity_input...
Add a noise curve for generation. This will add a noise curve for an SNR calculation by appending to the sensitivity_curves list within the sensitivity_input dictionary. The name of the noise curve prior to the file extension will appear as its label in the final output dataset. Therefore, it is recommended prior to running the generator that file names are renamed to simple names for later reference. Args: name (str): Name of noise curve including file extension inside input_folder. noise_type (str, optional): Type of noise. Choices are `ASD`, `PSD`, or `char_strain`. Default is ASD. is_wd_background (bool, optional): If True, this sensitivity is used as the white dwarf background noise. Default is False.
[ "Add", "a", "noise", "curve", "for", "generation", "." ]
train
https://github.com/mikekatz04/BOWIE/blob/a941342a3536cb57c817a1643896d99a3f354a86/snr_calculator_folder/gwsnrcalc/genconutils/forminput.py#L167-L198
mikekatz04/BOWIE
snr_calculator_folder/gwsnrcalc/genconutils/forminput.py
SensitivityInput.set_wd_noise
def set_wd_noise(self, wd_noise): """Add White Dwarf Background Noise This adds the White Dwarf (WD) Background noise. This can either do calculations with, without, or with and without WD noise. Args: wd_noise (bool or str, optional): Add or remove WD background noise. First option is to have only calculations with the wd_noise. For this, use `yes` or True. Second option is no WD noise. For this, use `no` or False. For both calculations with and without WD noise, use `both`. Raises: ValueError: Input value is not one of the options. """ if isinstance(wd_noise, bool): wd_noise = str(wd_noise) if wd_noise.lower() == 'yes' or wd_noise.lower() == 'true': wd_noise = 'True' elif wd_noise.lower() == 'no' or wd_noise.lower() == 'false': wd_noise = 'False' elif wd_noise.lower() == 'both': wd_noise = 'Both' else: raise ValueError('wd_noise must be yes, no, True, False, or Both.') self.sensitivity_input.add_wd_noise = wd_noise return
python
def set_wd_noise(self, wd_noise): """Add White Dwarf Background Noise This adds the White Dwarf (WD) Background noise. This can either do calculations with, without, or with and without WD noise. Args: wd_noise (bool or str, optional): Add or remove WD background noise. First option is to have only calculations with the wd_noise. For this, use `yes` or True. Second option is no WD noise. For this, use `no` or False. For both calculations with and without WD noise, use `both`. Raises: ValueError: Input value is not one of the options. """ if isinstance(wd_noise, bool): wd_noise = str(wd_noise) if wd_noise.lower() == 'yes' or wd_noise.lower() == 'true': wd_noise = 'True' elif wd_noise.lower() == 'no' or wd_noise.lower() == 'false': wd_noise = 'False' elif wd_noise.lower() == 'both': wd_noise = 'Both' else: raise ValueError('wd_noise must be yes, no, True, False, or Both.') self.sensitivity_input.add_wd_noise = wd_noise return
[ "def", "set_wd_noise", "(", "self", ",", "wd_noise", ")", ":", "if", "isinstance", "(", "wd_noise", ",", "bool", ")", ":", "wd_noise", "=", "str", "(", "wd_noise", ")", "if", "wd_noise", ".", "lower", "(", ")", "==", "'yes'", "or", "wd_noise", ".", "...
Add White Dwarf Background Noise This adds the White Dwarf (WD) Background noise. This can either do calculations with, without, or with and without WD noise. Args: wd_noise (bool or str, optional): Add or remove WD background noise. First option is to have only calculations with the wd_noise. For this, use `yes` or True. Second option is no WD noise. For this, use `no` or False. For both calculations with and without WD noise, use `both`. Raises: ValueError: Input value is not one of the options.
[ "Add", "White", "Dwarf", "Background", "Noise" ]
train
https://github.com/mikekatz04/BOWIE/blob/a941342a3536cb57c817a1643896d99a3f354a86/snr_calculator_folder/gwsnrcalc/genconutils/forminput.py#L200-L229
mikekatz04/BOWIE
snr_calculator_folder/gwsnrcalc/genconutils/forminput.py
ParallelInput.set_generation_type
def set_generation_type(self, num_processors=-1, num_splits=1000, verbose=-1): """Change generation type. Choose weather to generate the data in parallel or on a single processor. Args: num_processors (int or None, optional): Number of parallel processors to use. If ``num_processors==-1``, this will use multiprocessing module and use available cpus. If single generation is desired, num_processors is set to ``None``. Default is -1. num_splits (int, optional): Number of binaries to run during each process. Default is 1000. verbose (int, optional): Describes the notification of when parallel processes are finished. Value describes cadence of process completion notifications. If ``verbose == -1``, no notifications are given. Default is -1. """ self.parallel_input.num_processors = num_processors self.parallel_input.num_splits = num_splits self.parallel_input.verbose = verbose return
python
def set_generation_type(self, num_processors=-1, num_splits=1000, verbose=-1): """Change generation type. Choose weather to generate the data in parallel or on a single processor. Args: num_processors (int or None, optional): Number of parallel processors to use. If ``num_processors==-1``, this will use multiprocessing module and use available cpus. If single generation is desired, num_processors is set to ``None``. Default is -1. num_splits (int, optional): Number of binaries to run during each process. Default is 1000. verbose (int, optional): Describes the notification of when parallel processes are finished. Value describes cadence of process completion notifications. If ``verbose == -1``, no notifications are given. Default is -1. """ self.parallel_input.num_processors = num_processors self.parallel_input.num_splits = num_splits self.parallel_input.verbose = verbose return
[ "def", "set_generation_type", "(", "self", ",", "num_processors", "=", "-", "1", ",", "num_splits", "=", "1000", ",", "verbose", "=", "-", "1", ")", ":", "self", ".", "parallel_input", ".", "num_processors", "=", "num_processors", "self", ".", "parallel_inpu...
Change generation type. Choose weather to generate the data in parallel or on a single processor. Args: num_processors (int or None, optional): Number of parallel processors to use. If ``num_processors==-1``, this will use multiprocessing module and use available cpus. If single generation is desired, num_processors is set to ``None``. Default is -1. num_splits (int, optional): Number of binaries to run during each process. Default is 1000. verbose (int, optional): Describes the notification of when parallel processes are finished. Value describes cadence of process completion notifications. If ``verbose == -1``, no notifications are given. Default is -1.
[ "Change", "generation", "type", "." ]
train
https://github.com/mikekatz04/BOWIE/blob/a941342a3536cb57c817a1643896d99a3f354a86/snr_calculator_folder/gwsnrcalc/genconutils/forminput.py#L345-L365
mikekatz04/BOWIE
snr_calculator_folder/gwsnrcalc/genconutils/forminput.py
SNRInput.set_signal_type
def set_signal_type(self, sig_type): """Set the signal type of interest. Sets the signal type for which the SNR is calculated. This means inspiral, merger, and/or ringdown. Args: sig_type (str or list of str): Signal type desired by user. Choices are `ins`, `mrg`, `rd`, `all` for circular waveforms created with PhenomD. If eccentric waveforms are used, must be `all`. """ if isinstance(sig_type, str): sig_type = [sig_type] self.snr_input.signal_type = sig_type return
python
def set_signal_type(self, sig_type): """Set the signal type of interest. Sets the signal type for which the SNR is calculated. This means inspiral, merger, and/or ringdown. Args: sig_type (str or list of str): Signal type desired by user. Choices are `ins`, `mrg`, `rd`, `all` for circular waveforms created with PhenomD. If eccentric waveforms are used, must be `all`. """ if isinstance(sig_type, str): sig_type = [sig_type] self.snr_input.signal_type = sig_type return
[ "def", "set_signal_type", "(", "self", ",", "sig_type", ")", ":", "if", "isinstance", "(", "sig_type", ",", "str", ")", ":", "sig_type", "=", "[", "sig_type", "]", "self", ".", "snr_input", ".", "signal_type", "=", "sig_type", "return" ]
Set the signal type of interest. Sets the signal type for which the SNR is calculated. This means inspiral, merger, and/or ringdown. Args: sig_type (str or list of str): Signal type desired by user. Choices are `ins`, `mrg`, `rd`, `all` for circular waveforms created with PhenomD. If eccentric waveforms are used, must be `all`.
[ "Set", "the", "signal", "type", "of", "interest", "." ]
train
https://github.com/mikekatz04/BOWIE/blob/a941342a3536cb57c817a1643896d99a3f354a86/snr_calculator_folder/gwsnrcalc/genconutils/forminput.py#L391-L406
mikekatz04/BOWIE
snr_calculator_folder/gwsnrcalc/genconutils/forminput.py
MainContainer.return_dict
def return_dict(self): """Output dictionary for :mod:`gwsnrcalc.generate_contour_data` input. Iterates through the entire MainContainer class turning its contents into dictionary form. This dictionary becomes the input for :mod:`gwsnrcalc.generate_contour_data`. If `print_input` attribute is True, the entire dictionary will be printed prior to returning the dicitonary. Returns: - output_dict: Dicitonary for input into :mod:`gwsnrcalc.generate_contour_data`. """ output_dict = {} output_dict['general'] = self._iterate_through_class(self.general.__dict__) output_dict['generate_info'] = self._iterate_through_class(self.generate_info.__dict__) output_dict['sensitivity_input'] = (self._iterate_through_class( self.sensitivity_input.__dict__)) output_dict['snr_input'] = self._iterate_through_class(self.snr_input.__dict__) output_dict['parallel_input'] = self._iterate_through_class(self.parallel_input.__dict__) output_dict['output_info'] = self._iterate_through_class(self.output_info.__dict__) if self.print_input: print(output_dict) return output_dict
python
def return_dict(self): """Output dictionary for :mod:`gwsnrcalc.generate_contour_data` input. Iterates through the entire MainContainer class turning its contents into dictionary form. This dictionary becomes the input for :mod:`gwsnrcalc.generate_contour_data`. If `print_input` attribute is True, the entire dictionary will be printed prior to returning the dicitonary. Returns: - output_dict: Dicitonary for input into :mod:`gwsnrcalc.generate_contour_data`. """ output_dict = {} output_dict['general'] = self._iterate_through_class(self.general.__dict__) output_dict['generate_info'] = self._iterate_through_class(self.generate_info.__dict__) output_dict['sensitivity_input'] = (self._iterate_through_class( self.sensitivity_input.__dict__)) output_dict['snr_input'] = self._iterate_through_class(self.snr_input.__dict__) output_dict['parallel_input'] = self._iterate_through_class(self.parallel_input.__dict__) output_dict['output_info'] = self._iterate_through_class(self.output_info.__dict__) if self.print_input: print(output_dict) return output_dict
[ "def", "return_dict", "(", "self", ")", ":", "output_dict", "=", "{", "}", "output_dict", "[", "'general'", "]", "=", "self", ".", "_iterate_through_class", "(", "self", ".", "general", ".", "__dict__", ")", "output_dict", "[", "'generate_info'", "]", "=", ...
Output dictionary for :mod:`gwsnrcalc.generate_contour_data` input. Iterates through the entire MainContainer class turning its contents into dictionary form. This dictionary becomes the input for :mod:`gwsnrcalc.generate_contour_data`. If `print_input` attribute is True, the entire dictionary will be printed prior to returning the dicitonary. Returns: - output_dict: Dicitonary for input into :mod:`gwsnrcalc.generate_contour_data`.
[ "Output", "dictionary", "for", ":", "mod", ":", "gwsnrcalc", ".", "generate_contour_data", "input", "." ]
train
https://github.com/mikekatz04/BOWIE/blob/a941342a3536cb57c817a1643896d99a3f354a86/snr_calculator_folder/gwsnrcalc/genconutils/forminput.py#L519-L545
calmjs/calmjs.parse
src/calmjs/parse/unparsers/es5.py
pretty_print
def pretty_print(ast, indent_str=' '): """ Simple pretty print function; returns a string rendering of an input AST of an ES5 Program. arguments ast The AST to pretty print indent_str The string used for indentations. Defaults to two spaces. """ return ''.join(chunk.text for chunk in pretty_printer(indent_str)(ast))
python
def pretty_print(ast, indent_str=' '): """ Simple pretty print function; returns a string rendering of an input AST of an ES5 Program. arguments ast The AST to pretty print indent_str The string used for indentations. Defaults to two spaces. """ return ''.join(chunk.text for chunk in pretty_printer(indent_str)(ast))
[ "def", "pretty_print", "(", "ast", ",", "indent_str", "=", "' '", ")", ":", "return", "''", ".", "join", "(", "chunk", ".", "text", "for", "chunk", "in", "pretty_printer", "(", "indent_str", ")", "(", "ast", ")", ")" ]
Simple pretty print function; returns a string rendering of an input AST of an ES5 Program. arguments ast The AST to pretty print indent_str The string used for indentations. Defaults to two spaces.
[ "Simple", "pretty", "print", "function", ";", "returns", "a", "string", "rendering", "of", "an", "input", "AST", "of", "an", "ES5", "Program", "." ]
train
https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/unparsers/es5.py#L329-L342
calmjs/calmjs.parse
src/calmjs/parse/unparsers/es5.py
minify_printer
def minify_printer( obfuscate=False, obfuscate_globals=False, shadow_funcname=False, drop_semi=False): """ Construct a minimum printer. Arguments obfuscate If True, obfuscate identifiers nested in each scope with a shortened identifier name to further reduce output size. Defaults to False. obfuscate_globals Also do the same to identifiers nested on the global scope; do not enable unless the renaming of global variables in a not fully deterministic manner into something else is guaranteed to not cause problems with the generated code and other code that in the same environment that it will be executed in. Defaults to False for the reason above. drop_semi Drop semicolons whenever possible (e.g. the final semicolons of a given block). """ active_rules = [rules.minify(drop_semi=drop_semi)] if obfuscate: active_rules.append(rules.obfuscate( obfuscate_globals=obfuscate_globals, shadow_funcname=shadow_funcname, reserved_keywords=(Lexer.keywords_dict.keys()) )) return Unparser(rules=active_rules)
python
def minify_printer( obfuscate=False, obfuscate_globals=False, shadow_funcname=False, drop_semi=False): """ Construct a minimum printer. Arguments obfuscate If True, obfuscate identifiers nested in each scope with a shortened identifier name to further reduce output size. Defaults to False. obfuscate_globals Also do the same to identifiers nested on the global scope; do not enable unless the renaming of global variables in a not fully deterministic manner into something else is guaranteed to not cause problems with the generated code and other code that in the same environment that it will be executed in. Defaults to False for the reason above. drop_semi Drop semicolons whenever possible (e.g. the final semicolons of a given block). """ active_rules = [rules.minify(drop_semi=drop_semi)] if obfuscate: active_rules.append(rules.obfuscate( obfuscate_globals=obfuscate_globals, shadow_funcname=shadow_funcname, reserved_keywords=(Lexer.keywords_dict.keys()) )) return Unparser(rules=active_rules)
[ "def", "minify_printer", "(", "obfuscate", "=", "False", ",", "obfuscate_globals", "=", "False", ",", "shadow_funcname", "=", "False", ",", "drop_semi", "=", "False", ")", ":", "active_rules", "=", "[", "rules", ".", "minify", "(", "drop_semi", "=", "drop_se...
Construct a minimum printer. Arguments obfuscate If True, obfuscate identifiers nested in each scope with a shortened identifier name to further reduce output size. Defaults to False. obfuscate_globals Also do the same to identifiers nested on the global scope; do not enable unless the renaming of global variables in a not fully deterministic manner into something else is guaranteed to not cause problems with the generated code and other code that in the same environment that it will be executed in. Defaults to False for the reason above. drop_semi Drop semicolons whenever possible (e.g. the final semicolons of a given block).
[ "Construct", "a", "minimum", "printer", "." ]
train
https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/unparsers/es5.py#L345-L380
calmjs/calmjs.parse
src/calmjs/parse/unparsers/es5.py
minify_print
def minify_print( ast, obfuscate=False, obfuscate_globals=False, shadow_funcname=False, drop_semi=False): """ Simple minify print function; returns a string rendering of an input AST of an ES5 program Arguments ast The AST to minify print obfuscate If True, obfuscate identifiers nested in each scope with a shortened identifier name to further reduce output size. Defaults to False. obfuscate_globals Also do the same to identifiers nested on the global scope; do not enable unless the renaming of global variables in a not fully deterministic manner into something else is guaranteed to not cause problems with the generated code and other code that in the same environment that it will be executed in. Defaults to False for the reason above. drop_semi Drop semicolons whenever possible (e.g. the final semicolons of a given block). """ return ''.join(chunk.text for chunk in minify_printer( obfuscate, obfuscate_globals, shadow_funcname, drop_semi)(ast))
python
def minify_print( ast, obfuscate=False, obfuscate_globals=False, shadow_funcname=False, drop_semi=False): """ Simple minify print function; returns a string rendering of an input AST of an ES5 program Arguments ast The AST to minify print obfuscate If True, obfuscate identifiers nested in each scope with a shortened identifier name to further reduce output size. Defaults to False. obfuscate_globals Also do the same to identifiers nested on the global scope; do not enable unless the renaming of global variables in a not fully deterministic manner into something else is guaranteed to not cause problems with the generated code and other code that in the same environment that it will be executed in. Defaults to False for the reason above. drop_semi Drop semicolons whenever possible (e.g. the final semicolons of a given block). """ return ''.join(chunk.text for chunk in minify_printer( obfuscate, obfuscate_globals, shadow_funcname, drop_semi)(ast))
[ "def", "minify_print", "(", "ast", ",", "obfuscate", "=", "False", ",", "obfuscate_globals", "=", "False", ",", "shadow_funcname", "=", "False", ",", "drop_semi", "=", "False", ")", ":", "return", "''", ".", "join", "(", "chunk", ".", "text", "for", "chu...
Simple minify print function; returns a string rendering of an input AST of an ES5 program Arguments ast The AST to minify print obfuscate If True, obfuscate identifiers nested in each scope with a shortened identifier name to further reduce output size. Defaults to False. obfuscate_globals Also do the same to identifiers nested on the global scope; do not enable unless the renaming of global variables in a not fully deterministic manner into something else is guaranteed to not cause problems with the generated code and other code that in the same environment that it will be executed in. Defaults to False for the reason above. drop_semi Drop semicolons whenever possible (e.g. the final semicolons of a given block).
[ "Simple", "minify", "print", "function", ";", "returns", "a", "string", "rendering", "of", "an", "input", "AST", "of", "an", "ES5", "program" ]
train
https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/unparsers/es5.py#L383-L416
calmjs/calmjs.parse
src/calmjs/parse/vlq.py
encode_vlq
def encode_vlq(i): """ Encode integer `i` into a VLQ encoded string. """ # shift in the sign to least significant bit raw = (-i << 1) + 1 if i < 0 else i << 1 if raw < VLQ_MULTI_CHAR: # short-circuit simple case as it doesn't need continuation return INT_B64[raw] result = [] while raw: # assume continue result.append(raw & VLQ_BASE_MASK | VLQ_CONT) # shift out processed bits raw = raw >> VLQ_SHIFT # discontinue the last unit result[-1] &= VLQ_BASE_MASK return ''.join(INT_B64[i] for i in result)
python
def encode_vlq(i): """ Encode integer `i` into a VLQ encoded string. """ # shift in the sign to least significant bit raw = (-i << 1) + 1 if i < 0 else i << 1 if raw < VLQ_MULTI_CHAR: # short-circuit simple case as it doesn't need continuation return INT_B64[raw] result = [] while raw: # assume continue result.append(raw & VLQ_BASE_MASK | VLQ_CONT) # shift out processed bits raw = raw >> VLQ_SHIFT # discontinue the last unit result[-1] &= VLQ_BASE_MASK return ''.join(INT_B64[i] for i in result)
[ "def", "encode_vlq", "(", "i", ")", ":", "# shift in the sign to least significant bit", "raw", "=", "(", "-", "i", "<<", "1", ")", "+", "1", "if", "i", "<", "0", "else", "i", "<<", "1", "if", "raw", "<", "VLQ_MULTI_CHAR", ":", "# short-circuit simple case...
Encode integer `i` into a VLQ encoded string.
[ "Encode", "integer", "i", "into", "a", "VLQ", "encoded", "string", "." ]
train
https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/vlq.py#L64-L83
calmjs/calmjs.parse
src/calmjs/parse/vlq.py
decode_vlqs
def decode_vlqs(s): """ Decode str `s` into a list of integers. """ ints = [] i = 0 shift = 0 for c in s: raw = B64_INT[c] cont = VLQ_CONT & raw i = ((VLQ_BASE_MASK & raw) << shift) | i shift += VLQ_SHIFT if not cont: sign = -1 if 1 & i else 1 ints.append((i >> 1) * sign) i = 0 shift = 0 return tuple(ints)
python
def decode_vlqs(s): """ Decode str `s` into a list of integers. """ ints = [] i = 0 shift = 0 for c in s: raw = B64_INT[c] cont = VLQ_CONT & raw i = ((VLQ_BASE_MASK & raw) << shift) | i shift += VLQ_SHIFT if not cont: sign = -1 if 1 & i else 1 ints.append((i >> 1) * sign) i = 0 shift = 0 return tuple(ints)
[ "def", "decode_vlqs", "(", "s", ")", ":", "ints", "=", "[", "]", "i", "=", "0", "shift", "=", "0", "for", "c", "in", "s", ":", "raw", "=", "B64_INT", "[", "c", "]", "cont", "=", "VLQ_CONT", "&", "raw", "i", "=", "(", "(", "VLQ_BASE_MASK", "&"...
Decode str `s` into a list of integers.
[ "Decode", "str", "s", "into", "a", "list", "of", "integers", "." ]
train
https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/vlq.py#L90-L110
inveniosoftware/invenio-config
invenio_config/default.py
InvenioConfigDefault.init_app
def init_app(self, app): """Initialize Flask application.""" # Ensure SECRET_KEY is set. SECRET_KEY = app.config.get('SECRET_KEY') if SECRET_KEY is None: app.config['SECRET_KEY'] = 'CHANGE_ME' warnings.warn( 'Set configuration variable SECRET_KEY with random string', UserWarning)
python
def init_app(self, app): """Initialize Flask application.""" # Ensure SECRET_KEY is set. SECRET_KEY = app.config.get('SECRET_KEY') if SECRET_KEY is None: app.config['SECRET_KEY'] = 'CHANGE_ME' warnings.warn( 'Set configuration variable SECRET_KEY with random string', UserWarning)
[ "def", "init_app", "(", "self", ",", "app", ")", ":", "# Ensure SECRET_KEY is set.", "SECRET_KEY", "=", "app", ".", "config", ".", "get", "(", "'SECRET_KEY'", ")", "if", "SECRET_KEY", "is", "None", ":", "app", ".", "config", "[", "'SECRET_KEY'", "]", "=", ...
Initialize Flask application.
[ "Initialize", "Flask", "application", "." ]
train
https://github.com/inveniosoftware/invenio-config/blob/8d1e63ac045cd9c58a3399c6b58845e6daa06102/invenio_config/default.py#L27-L36
pyroscope/pyrobase
src/pyrobase/pyutil.py
require_json
def require_json(): """ Load the best available json library on demand. """ # Fails when "json" is missing and "simplejson" is not installed either try: import json # pylint: disable=F0401 return json except ImportError: try: import simplejson # pylint: disable=F0401 return simplejson except ImportError as exc: raise ImportError("""Please 'pip install "simplejson>=2.1.6"' (%s)""" % (exc,))
python
def require_json(): """ Load the best available json library on demand. """ # Fails when "json" is missing and "simplejson" is not installed either try: import json # pylint: disable=F0401 return json except ImportError: try: import simplejson # pylint: disable=F0401 return simplejson except ImportError as exc: raise ImportError("""Please 'pip install "simplejson>=2.1.6"' (%s)""" % (exc,))
[ "def", "require_json", "(", ")", ":", "# Fails when \"json\" is missing and \"simplejson\" is not installed either", "try", ":", "import", "json", "# pylint: disable=F0401", "return", "json", "except", "ImportError", ":", "try", ":", "import", "simplejson", "# pylint: disable...
Load the best available json library on demand.
[ "Load", "the", "best", "available", "json", "library", "on", "demand", "." ]
train
https://github.com/pyroscope/pyrobase/blob/7a2591baa492c3d8997ab4801b97c7b1f2ebc6b1/src/pyrobase/pyutil.py#L25-L37
ubccr/pinky
pinky/canonicalization/primes.py
Primes._findNextPrime
def _findNextPrime(self, N): """Generate the first N primes""" primes = self.primes nextPrime = primes[-1]+1 while(len(primes)<N): maximum = nextPrime * nextPrime prime = 1 for i in primes: if i > maximum: break if nextPrime % i == 0: prime = 0 break if prime: primes.append(nextPrime) nextPrime+=1
python
def _findNextPrime(self, N): """Generate the first N primes""" primes = self.primes nextPrime = primes[-1]+1 while(len(primes)<N): maximum = nextPrime * nextPrime prime = 1 for i in primes: if i > maximum: break if nextPrime % i == 0: prime = 0 break if prime: primes.append(nextPrime) nextPrime+=1
[ "def", "_findNextPrime", "(", "self", ",", "N", ")", ":", "primes", "=", "self", ".", "primes", "nextPrime", "=", "primes", "[", "-", "1", "]", "+", "1", "while", "(", "len", "(", "primes", ")", "<", "N", ")", ":", "maximum", "=", "nextPrime", "*...
Generate the first N primes
[ "Generate", "the", "first", "N", "primes" ]
train
https://github.com/ubccr/pinky/blob/e9d6e8ff72aa7f670b591e3bd3629cb879db1a93/pinky/canonicalization/primes.py#L92-L107
pyroscope/pyrobase
src/pyrobase/paver/support.py
venv_bin
def venv_bin(name=None): # pylint: disable=inconsistent-return-statements """ Get the directory for virtualenv stubs, or a full executable path if C{name} is provided. """ if not hasattr(sys, "real_prefix"): easy.error("ERROR: '%s' is not a virtualenv" % (sys.executable,)) sys.exit(1) for bindir in ("bin", "Scripts"): bindir = os.path.join(sys.prefix, bindir) if os.path.exists(bindir): if name: bin_ext = os.path.splitext(sys.executable)[1] if sys.platform == 'win32' else '' return os.path.join(bindir, name + bin_ext) else: return bindir easy.error("ERROR: Scripts directory not found in '%s'" % (sys.prefix,)) sys.exit(1)
python
def venv_bin(name=None): # pylint: disable=inconsistent-return-statements """ Get the directory for virtualenv stubs, or a full executable path if C{name} is provided. """ if not hasattr(sys, "real_prefix"): easy.error("ERROR: '%s' is not a virtualenv" % (sys.executable,)) sys.exit(1) for bindir in ("bin", "Scripts"): bindir = os.path.join(sys.prefix, bindir) if os.path.exists(bindir): if name: bin_ext = os.path.splitext(sys.executable)[1] if sys.platform == 'win32' else '' return os.path.join(bindir, name + bin_ext) else: return bindir easy.error("ERROR: Scripts directory not found in '%s'" % (sys.prefix,)) sys.exit(1)
[ "def", "venv_bin", "(", "name", "=", "None", ")", ":", "# pylint: disable=inconsistent-return-statements", "if", "not", "hasattr", "(", "sys", ",", "\"real_prefix\"", ")", ":", "easy", ".", "error", "(", "\"ERROR: '%s' is not a virtualenv\"", "%", "(", "sys", ".",...
Get the directory for virtualenv stubs, or a full executable path if C{name} is provided.
[ "Get", "the", "directory", "for", "virtualenv", "stubs", "or", "a", "full", "executable", "path", "if", "C", "{", "name", "}", "is", "provided", "." ]
train
https://github.com/pyroscope/pyrobase/blob/7a2591baa492c3d8997ab4801b97c7b1f2ebc6b1/src/pyrobase/paver/support.py#L28-L46
pyroscope/pyrobase
src/pyrobase/paver/support.py
vsh
def vsh(cmd, *args, **kw): """ Execute a command installed into the active virtualenv. """ args = '" "'.join(i.replace('"', r'\"') for i in args) easy.sh('"%s" "%s"' % (venv_bin(cmd), args))
python
def vsh(cmd, *args, **kw): """ Execute a command installed into the active virtualenv. """ args = '" "'.join(i.replace('"', r'\"') for i in args) easy.sh('"%s" "%s"' % (venv_bin(cmd), args))
[ "def", "vsh", "(", "cmd", ",", "*", "args", ",", "*", "*", "kw", ")", ":", "args", "=", "'\" \"'", ".", "join", "(", "i", ".", "replace", "(", "'\"'", ",", "r'\\\"'", ")", "for", "i", "in", "args", ")", "easy", ".", "sh", "(", "'\"%s\" \"%s\"'"...
Execute a command installed into the active virtualenv.
[ "Execute", "a", "command", "installed", "into", "the", "active", "virtualenv", "." ]
train
https://github.com/pyroscope/pyrobase/blob/7a2591baa492c3d8997ab4801b97c7b1f2ebc6b1/src/pyrobase/paver/support.py#L49-L53
pyroscope/pyrobase
src/pyrobase/paver/support.py
install_tools
def install_tools(dependencies): """ Install a required tool before using it, if it's missing. Note that C{dependencies} can be a distutils requirement, or a simple name from the C{tools} task configuration, or a (nested) list of such requirements. """ tools = getattr(easy.options, "tools", {}) for dependency in iterutil.flatten(dependencies): dependency = tools.get(dependency, dependency) try: pkg_resources.require(dependency) except pkg_resources.DistributionNotFound: vsh("pip", "install", "-q", dependency) dependency = pkg_resources.require(dependency) easy.info("Installed required tool %s" % (dependency,))
python
def install_tools(dependencies): """ Install a required tool before using it, if it's missing. Note that C{dependencies} can be a distutils requirement, or a simple name from the C{tools} task configuration, or a (nested) list of such requirements. """ tools = getattr(easy.options, "tools", {}) for dependency in iterutil.flatten(dependencies): dependency = tools.get(dependency, dependency) try: pkg_resources.require(dependency) except pkg_resources.DistributionNotFound: vsh("pip", "install", "-q", dependency) dependency = pkg_resources.require(dependency) easy.info("Installed required tool %s" % (dependency,))
[ "def", "install_tools", "(", "dependencies", ")", ":", "tools", "=", "getattr", "(", "easy", ".", "options", ",", "\"tools\"", ",", "{", "}", ")", "for", "dependency", "in", "iterutil", ".", "flatten", "(", "dependencies", ")", ":", "dependency", "=", "t...
Install a required tool before using it, if it's missing. Note that C{dependencies} can be a distutils requirement, or a simple name from the C{tools} task configuration, or a (nested) list of such requirements.
[ "Install", "a", "required", "tool", "before", "using", "it", "if", "it", "s", "missing", "." ]
train
https://github.com/pyroscope/pyrobase/blob/7a2591baa492c3d8997ab4801b97c7b1f2ebc6b1/src/pyrobase/paver/support.py#L56-L71
pyroscope/pyrobase
src/pyrobase/paver/support.py
task_requires
def task_requires(*dependencies): """ A task decorator that ensures a distutils dependency (or a list thereof) is met before that task is executed. """ def entangle(task): "Decorator wrapper." if not isinstance(task, tasks.Task): task = tasks.Task(task) def tool_task(*args, **kw): "Install requirements, then call original task." install_tools(dependencies) return task_body(*args, **kw) # Apply our wrapper to original task task_body, task.func = task.func, tool_task return task return entangle
python
def task_requires(*dependencies): """ A task decorator that ensures a distutils dependency (or a list thereof) is met before that task is executed. """ def entangle(task): "Decorator wrapper." if not isinstance(task, tasks.Task): task = tasks.Task(task) def tool_task(*args, **kw): "Install requirements, then call original task." install_tools(dependencies) return task_body(*args, **kw) # Apply our wrapper to original task task_body, task.func = task.func, tool_task return task return entangle
[ "def", "task_requires", "(", "*", "dependencies", ")", ":", "def", "entangle", "(", "task", ")", ":", "\"Decorator wrapper.\"", "if", "not", "isinstance", "(", "task", ",", "tasks", ".", "Task", ")", ":", "task", "=", "tasks", ".", "Task", "(", "task", ...
A task decorator that ensures a distutils dependency (or a list thereof) is met before that task is executed.
[ "A", "task", "decorator", "that", "ensures", "a", "distutils", "dependency", "(", "or", "a", "list", "thereof", ")", "is", "met", "before", "that", "task", "is", "executed", "." ]
train
https://github.com/pyroscope/pyrobase/blob/7a2591baa492c3d8997ab4801b97c7b1f2ebc6b1/src/pyrobase/paver/support.py#L74-L92
pyroscope/pyrobase
src/pyrobase/paver/support.py
toplevel_packages
def toplevel_packages(): """ Get package list, without sub-packages. """ packages = set(easy.options.setup.packages) for pkg in list(packages): packages -= set(p for p in packages if str(p).startswith(pkg + '.')) return list(sorted(packages))
python
def toplevel_packages(): """ Get package list, without sub-packages. """ packages = set(easy.options.setup.packages) for pkg in list(packages): packages -= set(p for p in packages if str(p).startswith(pkg + '.')) return list(sorted(packages))
[ "def", "toplevel_packages", "(", ")", ":", "packages", "=", "set", "(", "easy", ".", "options", ".", "setup", ".", "packages", ")", "for", "pkg", "in", "list", "(", "packages", ")", ":", "packages", "-=", "set", "(", "p", "for", "p", "in", "packages"...
Get package list, without sub-packages.
[ "Get", "package", "list", "without", "sub", "-", "packages", "." ]
train
https://github.com/pyroscope/pyrobase/blob/7a2591baa492c3d8997ab4801b97c7b1f2ebc6b1/src/pyrobase/paver/support.py#L95-L101
jbm950/pygame_toolbox
pygame_toolbox/graphics/__init__.py
Button.set_position
def set_position(self, position, midpoint=False, surface=None): """This method allows the button to be moved manually and keep the click on functionality. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Inputs: position - This is the x, y position of the top left corner of the button. (defining point can be changed to midpoint) midpoint - If true is passed to midpoint the button will be blitted to a surface, either automatically if a surface is passed or manually, such that the position input is the center of the button rather than the top left corner. (doc string updated ver 0.1)""" # Find the image size and midpoint of the image imagesize = self.image.get_size() imagemidp = (int(imagesize[0] * 0.5), int(imagesize[1] * 0.5)) # if a midpoint arguement is passed, set the pos to the top left pixel # such that the position passed in is in the middle of the button if midpoint: self.pos = (position[0] - imagemidp[0], position[1] - imagemidp[1]) else: self.pos = position # set the rectangle to be used for collision detection self.rect = pygame.Rect(self.pos, self.image.get_size()) # Set up the information that is needed to blit the image to the surface self.blitinfo = (self.image, self.pos) # automatically blit the button onto an input surface if surface: surface.blit(*self.blitinfo)
python
def set_position(self, position, midpoint=False, surface=None): """This method allows the button to be moved manually and keep the click on functionality. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Inputs: position - This is the x, y position of the top left corner of the button. (defining point can be changed to midpoint) midpoint - If true is passed to midpoint the button will be blitted to a surface, either automatically if a surface is passed or manually, such that the position input is the center of the button rather than the top left corner. (doc string updated ver 0.1)""" # Find the image size and midpoint of the image imagesize = self.image.get_size() imagemidp = (int(imagesize[0] * 0.5), int(imagesize[1] * 0.5)) # if a midpoint arguement is passed, set the pos to the top left pixel # such that the position passed in is in the middle of the button if midpoint: self.pos = (position[0] - imagemidp[0], position[1] - imagemidp[1]) else: self.pos = position # set the rectangle to be used for collision detection self.rect = pygame.Rect(self.pos, self.image.get_size()) # Set up the information that is needed to blit the image to the surface self.blitinfo = (self.image, self.pos) # automatically blit the button onto an input surface if surface: surface.blit(*self.blitinfo)
[ "def", "set_position", "(", "self", ",", "position", ",", "midpoint", "=", "False", ",", "surface", "=", "None", ")", ":", "# Find the image size and midpoint of the image", "imagesize", "=", "self", ".", "image", ".", "get_size", "(", ")", "imagemidp", "=", "...
This method allows the button to be moved manually and keep the click on functionality. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Inputs: position - This is the x, y position of the top left corner of the button. (defining point can be changed to midpoint) midpoint - If true is passed to midpoint the button will be blitted to a surface, either automatically if a surface is passed or manually, such that the position input is the center of the button rather than the top left corner. (doc string updated ver 0.1)
[ "This", "method", "allows", "the", "button", "to", "be", "moved", "manually", "and", "keep", "the", "click", "on", "functionality", ".", "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~", "Inputs", ":", "position", "-", "This", "is", "the", "x...
train
https://github.com/jbm950/pygame_toolbox/blob/3fe32145fc149e4dd0963c30a2b6a4dddd4fac0e/pygame_toolbox/graphics/__init__.py#L169-L203
jbm950/pygame_toolbox
pygame_toolbox/graphics/__init__.py
BaseScreen.set_offset
def set_offset(self, offset, mid=None): """This method will allow the menu to be placed anywhere in the open window instead of just the upper left corner. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Inputs: offset - This is the x,y tuple of the position that you want to move the screen to. mid - The offset will be treated as the value passed in instead of the top left pixel. 'x' (the x point in offset will be treated as the middle of the menu image) 'y' (the y point in offset will be treated as the middle of the menu image) 'c' (the offset will be treated as the center of the menu image) (doc string updated ver 0.1) """ if mid: imagesize = self.image.get_size() imagemidp = (int(imagesize[0] * 0.5), int(imagesize[1] * 0.5)) if mid == 'x': offset = (offset[0] - imagemidp[0], offset[1]) if mid == 'y': offset = (offset[0], offset[1] - imagemidp[1]) if mid == 'c': offset = (offset[0] - imagemidp[0], offset[1] - imagemidp[1]) self.pos = offset for i in self.buttonlist: i.rect[0] += offset[0] i.rect[1] += offset[1] try: for i in self.widgetlist: i.rect[0] += offset[0] i.rect[1] += offset[1] except AttributeError: pass
python
def set_offset(self, offset, mid=None): """This method will allow the menu to be placed anywhere in the open window instead of just the upper left corner. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Inputs: offset - This is the x,y tuple of the position that you want to move the screen to. mid - The offset will be treated as the value passed in instead of the top left pixel. 'x' (the x point in offset will be treated as the middle of the menu image) 'y' (the y point in offset will be treated as the middle of the menu image) 'c' (the offset will be treated as the center of the menu image) (doc string updated ver 0.1) """ if mid: imagesize = self.image.get_size() imagemidp = (int(imagesize[0] * 0.5), int(imagesize[1] * 0.5)) if mid == 'x': offset = (offset[0] - imagemidp[0], offset[1]) if mid == 'y': offset = (offset[0], offset[1] - imagemidp[1]) if mid == 'c': offset = (offset[0] - imagemidp[0], offset[1] - imagemidp[1]) self.pos = offset for i in self.buttonlist: i.rect[0] += offset[0] i.rect[1] += offset[1] try: for i in self.widgetlist: i.rect[0] += offset[0] i.rect[1] += offset[1] except AttributeError: pass
[ "def", "set_offset", "(", "self", ",", "offset", ",", "mid", "=", "None", ")", ":", "if", "mid", ":", "imagesize", "=", "self", ".", "image", ".", "get_size", "(", ")", "imagemidp", "=", "(", "int", "(", "imagesize", "[", "0", "]", "*", "0.5", ")...
This method will allow the menu to be placed anywhere in the open window instead of just the upper left corner. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Inputs: offset - This is the x,y tuple of the position that you want to move the screen to. mid - The offset will be treated as the value passed in instead of the top left pixel. 'x' (the x point in offset will be treated as the middle of the menu image) 'y' (the y point in offset will be treated as the middle of the menu image) 'c' (the offset will be treated as the center of the menu image) (doc string updated ver 0.1)
[ "This", "method", "will", "allow", "the", "menu", "to", "be", "placed", "anywhere", "in", "the", "open", "window", "instead", "of", "just", "the", "upper", "left", "corner", ".", "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~", "Inputs", ":"...
train
https://github.com/jbm950/pygame_toolbox/blob/3fe32145fc149e4dd0963c30a2b6a4dddd4fac0e/pygame_toolbox/graphics/__init__.py#L396-L439
jbm950/pygame_toolbox
pygame_toolbox/graphics/__init__.py
Menu.widget_status
def widget_status(self): """This method will return the status of all of the widgets in the widget list""" widget_status_list = [] for i in self.widgetlist: widget_status_list += [[i.name, i.status]] return widget_status_list
python
def widget_status(self): """This method will return the status of all of the widgets in the widget list""" widget_status_list = [] for i in self.widgetlist: widget_status_list += [[i.name, i.status]] return widget_status_list
[ "def", "widget_status", "(", "self", ")", ":", "widget_status_list", "=", "[", "]", "for", "i", "in", "self", ".", "widgetlist", ":", "widget_status_list", "+=", "[", "[", "i", ".", "name", ",", "i", ".", "status", "]", "]", "return", "widget_status_list...
This method will return the status of all of the widgets in the widget list
[ "This", "method", "will", "return", "the", "status", "of", "all", "of", "the", "widgets", "in", "the", "widget", "list" ]
train
https://github.com/jbm950/pygame_toolbox/blob/3fe32145fc149e4dd0963c30a2b6a4dddd4fac0e/pygame_toolbox/graphics/__init__.py#L492-L498
jbm950/pygame_toolbox
pygame_toolbox/graphics/__init__.py
Menu.update
def update(self, screen, clock): """Event handling loop for the menu""" # If a music file was passed, start playing it on repeat if self.music is not None: pygame.mixer.music.play(-1) while True: clock.tick(30) for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() # Check if any of the buttons were clicked for i in self.buttonlist: if (event.type == pygame.MOUSEBUTTONUP and i.rect.collidepoint(pygame.mouse.get_pos())): if self.music is not None: pygame.mixer.music.stop() if self.widgetlist: return [i(), self.widget_status()] else: return i() # If there is a widget list, check to see if any were clicked if self.widgetlist: for i in self.widgetlist: if (event.type == pygame.MOUSEBUTTONDOWN and i.rect.collidepoint(pygame.mouse.get_pos())): # Call the widget and give it the menu information i(self) screen.blit(self.image, self.pos) pygame.display.flip()
python
def update(self, screen, clock): """Event handling loop for the menu""" # If a music file was passed, start playing it on repeat if self.music is not None: pygame.mixer.music.play(-1) while True: clock.tick(30) for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() # Check if any of the buttons were clicked for i in self.buttonlist: if (event.type == pygame.MOUSEBUTTONUP and i.rect.collidepoint(pygame.mouse.get_pos())): if self.music is not None: pygame.mixer.music.stop() if self.widgetlist: return [i(), self.widget_status()] else: return i() # If there is a widget list, check to see if any were clicked if self.widgetlist: for i in self.widgetlist: if (event.type == pygame.MOUSEBUTTONDOWN and i.rect.collidepoint(pygame.mouse.get_pos())): # Call the widget and give it the menu information i(self) screen.blit(self.image, self.pos) pygame.display.flip()
[ "def", "update", "(", "self", ",", "screen", ",", "clock", ")", ":", "# If a music file was passed, start playing it on repeat", "if", "self", ".", "music", "is", "not", "None", ":", "pygame", ".", "mixer", ".", "music", ".", "play", "(", "-", "1", ")", "w...
Event handling loop for the menu
[ "Event", "handling", "loop", "for", "the", "menu" ]
train
https://github.com/jbm950/pygame_toolbox/blob/3fe32145fc149e4dd0963c30a2b6a4dddd4fac0e/pygame_toolbox/graphics/__init__.py#L500-L531
jbm950/pygame_toolbox
pygame_toolbox/graphics/__init__.py
Textscreens.Screens
def Screens(self, text, prog, screen, clock): """Prog = 0 for first page, 1 for middle pages, 2 for last page""" # Initialize the screen class BaseScreen.__init__(self, self.size, self.background) # Determine the mid position of the given screen size and the # y button height xmid = self.size[0]//2 # Create the header text Linesoftext(text, (xmid, 40), xmid=True, surface=self.image, fontsize=30) # Create the buttons self.buttonlist = [] if prog == 0: self.buttonlist += [self.nextbutton] elif prog == 1: self.buttonlist += [self.nextbutton] self.buttonlist += [self.backbutton] elif prog == 2: self.buttonlist += [self.lastbutton] self.buttonlist += [self.backbutton] # Draw the buttons to the screen for i in self.buttonlist: self.image.blit(*i.blitinfo) # Use the menu update method to run the screen and process button clicks return Menu.update(self, screen, clock)
python
def Screens(self, text, prog, screen, clock): """Prog = 0 for first page, 1 for middle pages, 2 for last page""" # Initialize the screen class BaseScreen.__init__(self, self.size, self.background) # Determine the mid position of the given screen size and the # y button height xmid = self.size[0]//2 # Create the header text Linesoftext(text, (xmid, 40), xmid=True, surface=self.image, fontsize=30) # Create the buttons self.buttonlist = [] if prog == 0: self.buttonlist += [self.nextbutton] elif prog == 1: self.buttonlist += [self.nextbutton] self.buttonlist += [self.backbutton] elif prog == 2: self.buttonlist += [self.lastbutton] self.buttonlist += [self.backbutton] # Draw the buttons to the screen for i in self.buttonlist: self.image.blit(*i.blitinfo) # Use the menu update method to run the screen and process button clicks return Menu.update(self, screen, clock)
[ "def", "Screens", "(", "self", ",", "text", ",", "prog", ",", "screen", ",", "clock", ")", ":", "# Initialize the screen class", "BaseScreen", ".", "__init__", "(", "self", ",", "self", ".", "size", ",", "self", ".", "background", ")", "# Determine the mid p...
Prog = 0 for first page, 1 for middle pages, 2 for last page
[ "Prog", "=", "0", "for", "first", "page", "1", "for", "middle", "pages", "2", "for", "last", "page" ]
train
https://github.com/jbm950/pygame_toolbox/blob/3fe32145fc149e4dd0963c30a2b6a4dddd4fac0e/pygame_toolbox/graphics/__init__.py#L608-L639
pedroburon/tbk
tbk/webpay/commerce.py
Commerce.create_commerce
def create_commerce(): """ Creates commerce from environment variables ``TBK_COMMERCE_ID``, ``TBK_COMMERCE_KEY`` or for testing purposes ``TBK_COMMERCE_TESTING``. """ commerce_id = os.getenv('TBK_COMMERCE_ID') commerce_key = os.getenv('TBK_COMMERCE_KEY') commerce_testing = os.getenv('TBK_COMMERCE_TESTING') == 'True' if not commerce_testing: if commerce_id is None: raise ValueError("create_commerce needs TBK_COMMERCE_ID environment variable") if commerce_key is None: raise ValueError("create_commerce needs TBK_COMMERCE_KEY environment variable") return Commerce( id=commerce_id or Commerce.TEST_COMMERCE_ID, key=commerce_key, testing=commerce_testing )
python
def create_commerce(): """ Creates commerce from environment variables ``TBK_COMMERCE_ID``, ``TBK_COMMERCE_KEY`` or for testing purposes ``TBK_COMMERCE_TESTING``. """ commerce_id = os.getenv('TBK_COMMERCE_ID') commerce_key = os.getenv('TBK_COMMERCE_KEY') commerce_testing = os.getenv('TBK_COMMERCE_TESTING') == 'True' if not commerce_testing: if commerce_id is None: raise ValueError("create_commerce needs TBK_COMMERCE_ID environment variable") if commerce_key is None: raise ValueError("create_commerce needs TBK_COMMERCE_KEY environment variable") return Commerce( id=commerce_id or Commerce.TEST_COMMERCE_ID, key=commerce_key, testing=commerce_testing )
[ "def", "create_commerce", "(", ")", ":", "commerce_id", "=", "os", ".", "getenv", "(", "'TBK_COMMERCE_ID'", ")", "commerce_key", "=", "os", ".", "getenv", "(", "'TBK_COMMERCE_KEY'", ")", "commerce_testing", "=", "os", ".", "getenv", "(", "'TBK_COMMERCE_TESTING'"...
Creates commerce from environment variables ``TBK_COMMERCE_ID``, ``TBK_COMMERCE_KEY`` or for testing purposes ``TBK_COMMERCE_TESTING``.
[ "Creates", "commerce", "from", "environment", "variables", "TBK_COMMERCE_ID", "TBK_COMMERCE_KEY", "or", "for", "testing", "purposes", "TBK_COMMERCE_TESTING", "." ]
train
https://github.com/pedroburon/tbk/blob/ecd6741e0bae06269eb4ac885c3ffcb7902ee40e/tbk/webpay/commerce.py#L98-L117
pedroburon/tbk
tbk/webpay/commerce.py
Commerce.get_config_tbk
def get_config_tbk(self, confirmation_url): ''' Returns a string with the ``TBK_CONFIG.dat``. :param confirmation_url: URL where callback is made. ''' config = ( "IDCOMERCIO = {commerce_id}\n" "MEDCOM = 1\n" "TBK_KEY_ID = 101\n" "PARAMVERIFCOM = 1\n" "URLCGICOM = {confirmation_path}\n" "SERVERCOM = {confirmation_host}\n" "PORTCOM = {confirmation_port}\n" "WHITELISTCOM = ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz 0123456789./:=&?_\n" "HOST = {confirmation_host}\n" "WPORT = {confirmation_port}\n" "URLCGITRA = /filtroUnificado/bp_revision.cgi\n" "URLCGIMEDTRA = /filtroUnificado/bp_validacion.cgi\n" "SERVERTRA = {webpay_server}\n" "PORTTRA = {webpay_port}\n" "PREFIJO_CONF_TR = HTML_\n" "HTML_TR_NORMAL = http://127.0.0.1/notify\n" ) confirmation_uri = six.moves.urllib.parse.urlparse(confirmation_url) webpay_server = "https://certificacion.webpay.cl" if self.testing else "https://webpay.transbank.cl" webpay_port = 6443 if self.testing else 443 return config.format(commerce_id=self.id, confirmation_path=confirmation_uri.path, confirmation_host=confirmation_uri.hostname, confirmation_port=confirmation_uri.port, webpay_port=webpay_port, webpay_server=webpay_server)
python
def get_config_tbk(self, confirmation_url): ''' Returns a string with the ``TBK_CONFIG.dat``. :param confirmation_url: URL where callback is made. ''' config = ( "IDCOMERCIO = {commerce_id}\n" "MEDCOM = 1\n" "TBK_KEY_ID = 101\n" "PARAMVERIFCOM = 1\n" "URLCGICOM = {confirmation_path}\n" "SERVERCOM = {confirmation_host}\n" "PORTCOM = {confirmation_port}\n" "WHITELISTCOM = ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz 0123456789./:=&?_\n" "HOST = {confirmation_host}\n" "WPORT = {confirmation_port}\n" "URLCGITRA = /filtroUnificado/bp_revision.cgi\n" "URLCGIMEDTRA = /filtroUnificado/bp_validacion.cgi\n" "SERVERTRA = {webpay_server}\n" "PORTTRA = {webpay_port}\n" "PREFIJO_CONF_TR = HTML_\n" "HTML_TR_NORMAL = http://127.0.0.1/notify\n" ) confirmation_uri = six.moves.urllib.parse.urlparse(confirmation_url) webpay_server = "https://certificacion.webpay.cl" if self.testing else "https://webpay.transbank.cl" webpay_port = 6443 if self.testing else 443 return config.format(commerce_id=self.id, confirmation_path=confirmation_uri.path, confirmation_host=confirmation_uri.hostname, confirmation_port=confirmation_uri.port, webpay_port=webpay_port, webpay_server=webpay_server)
[ "def", "get_config_tbk", "(", "self", ",", "confirmation_url", ")", ":", "config", "=", "(", "\"IDCOMERCIO = {commerce_id}\\n\"", "\"MEDCOM = 1\\n\"", "\"TBK_KEY_ID = 101\\n\"", "\"PARAMVERIFCOM = 1\\n\"", "\"URLCGICOM = {confirmation_path}\\n\"", "\"SERVERCOM = {confirmation_host}\\...
Returns a string with the ``TBK_CONFIG.dat``. :param confirmation_url: URL where callback is made.
[ "Returns", "a", "string", "with", "the", "TBK_CONFIG", ".", "dat", "." ]
train
https://github.com/pedroburon/tbk/blob/ecd6741e0bae06269eb4ac885c3ffcb7902ee40e/tbk/webpay/commerce.py#L162-L194
calmjs/calmjs.parse
src/calmjs/parse/handlers/indentation.py
indent
def indent(indent_str=None): """ An example indentation ruleset. """ def indentation_rule(): inst = Indentator(indent_str) return {'layout_handlers': { Indent: inst.layout_handler_indent, Dedent: inst.layout_handler_dedent, Newline: inst.layout_handler_newline, OptionalNewline: inst.layout_handler_newline_optional, OpenBlock: layout_handler_openbrace, CloseBlock: layout_handler_closebrace, EndStatement: layout_handler_semicolon, }} return indentation_rule
python
def indent(indent_str=None): """ An example indentation ruleset. """ def indentation_rule(): inst = Indentator(indent_str) return {'layout_handlers': { Indent: inst.layout_handler_indent, Dedent: inst.layout_handler_dedent, Newline: inst.layout_handler_newline, OptionalNewline: inst.layout_handler_newline_optional, OpenBlock: layout_handler_openbrace, CloseBlock: layout_handler_closebrace, EndStatement: layout_handler_semicolon, }} return indentation_rule
[ "def", "indent", "(", "indent_str", "=", "None", ")", ":", "def", "indentation_rule", "(", ")", ":", "inst", "=", "Indentator", "(", "indent_str", ")", "return", "{", "'layout_handlers'", ":", "{", "Indent", ":", "inst", ".", "layout_handler_indent", ",", ...
An example indentation ruleset.
[ "An", "example", "indentation", "ruleset", "." ]
train
https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/handlers/indentation.py#L84-L100
mozilla/funfactory
funfactory/middleware.py
LocaleURLMiddleware._is_lang_change
def _is_lang_change(self, request): """Return True if the lang param is present and URL isn't exempt.""" if 'lang' not in request.GET: return False return not any(request.path.endswith(url) for url in self.exempt_urls)
python
def _is_lang_change(self, request): """Return True if the lang param is present and URL isn't exempt.""" if 'lang' not in request.GET: return False return not any(request.path.endswith(url) for url in self.exempt_urls)
[ "def", "_is_lang_change", "(", "self", ",", "request", ")", ":", "if", "'lang'", "not", "in", "request", ".", "GET", ":", "return", "False", "return", "not", "any", "(", "request", ".", "path", ".", "endswith", "(", "url", ")", "for", "url", "in", "s...
Return True if the lang param is present and URL isn't exempt.
[ "Return", "True", "if", "the", "lang", "param", "is", "present", "and", "URL", "isn", "t", "exempt", "." ]
train
https://github.com/mozilla/funfactory/blob/c9bbf1c534eaa15641265bc75fa87afca52b7dd6/funfactory/middleware.py#L36-L41
chbrown/argv
argv/parsers/boolean.py
BooleanParser.add
def add(self, *matches, **kw): # kw=default=None, boolean=False '''Add an argument; this is optional, and mostly useful for setting up aliases or setting boolean=True Apparently `def add(self, *matches, default=None, boolean=False):` is invalid syntax in Python. Not only is this absolutely ridiculous, but the alternative `def add(self, default=None, boolean=False, *matches):` does not do what you would expect. This syntax works as intended in Python 3. If you provide multiple `matches` that are not dash-prefixed, only the first will be used as a positional argument. Specifying any positional arguments and then using `boolean=True` is just weird, and their will be no special consideration for boolean=True in that case for the position-enabled argument. ''' # python syntax hack default = kw.get('default', None) boolean = kw.get('boolean', False) del kw # do not use kw after this line! It's a hack; it should never have been there in the first place. positional = None names = [] for match in matches: if match.startswith('--'): names.append(match[2:]) elif match.startswith('-'): names.append(match[1:]) elif positional: # positional has already been filled names.append(match) else: # first positional: becomes canonical positional positional = match names.append(match) argument = BooleanArgument(names, default, boolean, positional) self.arguments.append(argument) # chainable return self
python
def add(self, *matches, **kw): # kw=default=None, boolean=False '''Add an argument; this is optional, and mostly useful for setting up aliases or setting boolean=True Apparently `def add(self, *matches, default=None, boolean=False):` is invalid syntax in Python. Not only is this absolutely ridiculous, but the alternative `def add(self, default=None, boolean=False, *matches):` does not do what you would expect. This syntax works as intended in Python 3. If you provide multiple `matches` that are not dash-prefixed, only the first will be used as a positional argument. Specifying any positional arguments and then using `boolean=True` is just weird, and their will be no special consideration for boolean=True in that case for the position-enabled argument. ''' # python syntax hack default = kw.get('default', None) boolean = kw.get('boolean', False) del kw # do not use kw after this line! It's a hack; it should never have been there in the first place. positional = None names = [] for match in matches: if match.startswith('--'): names.append(match[2:]) elif match.startswith('-'): names.append(match[1:]) elif positional: # positional has already been filled names.append(match) else: # first positional: becomes canonical positional positional = match names.append(match) argument = BooleanArgument(names, default, boolean, positional) self.arguments.append(argument) # chainable return self
[ "def", "add", "(", "self", ",", "*", "matches", ",", "*", "*", "kw", ")", ":", "# kw=default=None, boolean=False", "# python syntax hack", "default", "=", "kw", ".", "get", "(", "'default'", ",", "None", ")", "boolean", "=", "kw", ".", "get", "(", "'bool...
Add an argument; this is optional, and mostly useful for setting up aliases or setting boolean=True Apparently `def add(self, *matches, default=None, boolean=False):` is invalid syntax in Python. Not only is this absolutely ridiculous, but the alternative `def add(self, default=None, boolean=False, *matches):` does not do what you would expect. This syntax works as intended in Python 3. If you provide multiple `matches` that are not dash-prefixed, only the first will be used as a positional argument. Specifying any positional arguments and then using `boolean=True` is just weird, and their will be no special consideration for boolean=True in that case for the position-enabled argument.
[ "Add", "an", "argument", ";", "this", "is", "optional", "and", "mostly", "useful", "for", "setting", "up", "aliases", "or", "setting", "boolean", "=", "True" ]
train
https://github.com/chbrown/argv/blob/5e2b0424a060027c029ad9c16d90bd14a2ff53f8/argv/parsers/boolean.py#L32-L65
sobolevn/jinja2-git
jinja2_git.py
GitExtension.parse
def parse(self, parser): """Main method to render data into the template.""" lineno = next(parser.stream).lineno if parser.stream.skip_if('name:short'): parser.stream.skip(1) short = parser.parse_expression() else: short = nodes.Const(False) result = self.call_method('_commit_hash', [short], [], lineno=lineno) return nodes.Output([result], lineno=lineno)
python
def parse(self, parser): """Main method to render data into the template.""" lineno = next(parser.stream).lineno if parser.stream.skip_if('name:short'): parser.stream.skip(1) short = parser.parse_expression() else: short = nodes.Const(False) result = self.call_method('_commit_hash', [short], [], lineno=lineno) return nodes.Output([result], lineno=lineno)
[ "def", "parse", "(", "self", ",", "parser", ")", ":", "lineno", "=", "next", "(", "parser", ".", "stream", ")", ".", "lineno", "if", "parser", ".", "stream", ".", "skip_if", "(", "'name:short'", ")", ":", "parser", ".", "stream", ".", "skip", "(", ...
Main method to render data into the template.
[ "Main", "method", "to", "render", "data", "into", "the", "template", "." ]
train
https://github.com/sobolevn/jinja2-git/blob/2ef8ac30efc1d73db551aaae73b2fe214761f840/jinja2_git.py#L23-L34
pyroscope/pyrobase
src/pyrobase/iterutil.py
flatten
def flatten(nested, containers=(list, tuple)): """ Flatten a nested list by yielding its scalar items. """ for item in nested: if hasattr(item, "next") or isinstance(item, containers): for subitem in flatten(item): yield subitem else: yield item
python
def flatten(nested, containers=(list, tuple)): """ Flatten a nested list by yielding its scalar items. """ for item in nested: if hasattr(item, "next") or isinstance(item, containers): for subitem in flatten(item): yield subitem else: yield item
[ "def", "flatten", "(", "nested", ",", "containers", "=", "(", "list", ",", "tuple", ")", ")", ":", "for", "item", "in", "nested", ":", "if", "hasattr", "(", "item", ",", "\"next\"", ")", "or", "isinstance", "(", "item", ",", "containers", ")", ":", ...
Flatten a nested list by yielding its scalar items.
[ "Flatten", "a", "nested", "list", "by", "yielding", "its", "scalar", "items", "." ]
train
https://github.com/pyroscope/pyrobase/blob/7a2591baa492c3d8997ab4801b97c7b1f2ebc6b1/src/pyrobase/iterutil.py#L20-L28
mozilla/funfactory
funfactory/settings_base.py
get_template_context_processors
def get_template_context_processors(exclude=(), append=(), current={'processors': TEMPLATE_CONTEXT_PROCESSORS}): """ Returns TEMPLATE_CONTEXT_PROCESSORS without the processors listed in exclude and with the processors listed in append. The use of a mutable dict is intentional, in order to preserve the state of the TEMPLATE_CONTEXT_PROCESSORS tuple across multiple settings files. """ current['processors'] = tuple( [p for p in current['processors'] if p not in exclude] ) + tuple(append) return current['processors']
python
def get_template_context_processors(exclude=(), append=(), current={'processors': TEMPLATE_CONTEXT_PROCESSORS}): """ Returns TEMPLATE_CONTEXT_PROCESSORS without the processors listed in exclude and with the processors listed in append. The use of a mutable dict is intentional, in order to preserve the state of the TEMPLATE_CONTEXT_PROCESSORS tuple across multiple settings files. """ current['processors'] = tuple( [p for p in current['processors'] if p not in exclude] ) + tuple(append) return current['processors']
[ "def", "get_template_context_processors", "(", "exclude", "=", "(", ")", ",", "append", "=", "(", ")", ",", "current", "=", "{", "'processors'", ":", "TEMPLATE_CONTEXT_PROCESSORS", "}", ")", ":", "current", "[", "'processors'", "]", "=", "tuple", "(", "[", ...
Returns TEMPLATE_CONTEXT_PROCESSORS without the processors listed in exclude and with the processors listed in append. The use of a mutable dict is intentional, in order to preserve the state of the TEMPLATE_CONTEXT_PROCESSORS tuple across multiple settings files.
[ "Returns", "TEMPLATE_CONTEXT_PROCESSORS", "without", "the", "processors", "listed", "in", "exclude", "and", "with", "the", "processors", "listed", "in", "append", "." ]
train
https://github.com/mozilla/funfactory/blob/c9bbf1c534eaa15641265bc75fa87afca52b7dd6/funfactory/settings_base.py#L204-L218
mozilla/funfactory
funfactory/settings_base.py
get_middleware
def get_middleware(exclude=(), append=(), current={'middleware': MIDDLEWARE_CLASSES}): """ Returns MIDDLEWARE_CLASSES without the middlewares listed in exclude and with the middlewares listed in append. The use of a mutable dict is intentional, in order to preserve the state of the MIDDLEWARE_CLASSES tuple across multiple settings files. """ current['middleware'] = tuple( [m for m in current['middleware'] if m not in exclude] ) + tuple(append) return current['middleware']
python
def get_middleware(exclude=(), append=(), current={'middleware': MIDDLEWARE_CLASSES}): """ Returns MIDDLEWARE_CLASSES without the middlewares listed in exclude and with the middlewares listed in append. The use of a mutable dict is intentional, in order to preserve the state of the MIDDLEWARE_CLASSES tuple across multiple settings files. """ current['middleware'] = tuple( [m for m in current['middleware'] if m not in exclude] ) + tuple(append) return current['middleware']
[ "def", "get_middleware", "(", "exclude", "=", "(", ")", ",", "append", "=", "(", ")", ",", "current", "=", "{", "'middleware'", ":", "MIDDLEWARE_CLASSES", "}", ")", ":", "current", "[", "'middleware'", "]", "=", "tuple", "(", "[", "m", "for", "m", "i...
Returns MIDDLEWARE_CLASSES without the middlewares listed in exclude and with the middlewares listed in append. The use of a mutable dict is intentional, in order to preserve the state of the MIDDLEWARE_CLASSES tuple across multiple settings files.
[ "Returns", "MIDDLEWARE_CLASSES", "without", "the", "middlewares", "listed", "in", "exclude", "and", "with", "the", "middlewares", "listed", "in", "append", "." ]
train
https://github.com/mozilla/funfactory/blob/c9bbf1c534eaa15641265bc75fa87afca52b7dd6/funfactory/settings_base.py#L280-L293
mozilla/funfactory
funfactory/settings_base.py
get_apps
def get_apps(exclude=(), append=(), current={'apps': INSTALLED_APPS}): """ Returns INSTALLED_APPS without the apps listed in exclude and with the apps listed in append. The use of a mutable dict is intentional, in order to preserve the state of the INSTALLED_APPS tuple across multiple settings files. """ current['apps'] = tuple( [a for a in current['apps'] if a not in exclude] ) + tuple(append) return current['apps']
python
def get_apps(exclude=(), append=(), current={'apps': INSTALLED_APPS}): """ Returns INSTALLED_APPS without the apps listed in exclude and with the apps listed in append. The use of a mutable dict is intentional, in order to preserve the state of the INSTALLED_APPS tuple across multiple settings files. """ current['apps'] = tuple( [a for a in current['apps'] if a not in exclude] ) + tuple(append) return current['apps']
[ "def", "get_apps", "(", "exclude", "=", "(", ")", ",", "append", "=", "(", ")", ",", "current", "=", "{", "'apps'", ":", "INSTALLED_APPS", "}", ")", ":", "current", "[", "'apps'", "]", "=", "tuple", "(", "[", "a", "for", "a", "in", "current", "["...
Returns INSTALLED_APPS without the apps listed in exclude and with the apps listed in append. The use of a mutable dict is intentional, in order to preserve the state of the INSTALLED_APPS tuple across multiple settings files.
[ "Returns", "INSTALLED_APPS", "without", "the", "apps", "listed", "in", "exclude", "and", "with", "the", "apps", "listed", "in", "append", "." ]
train
https://github.com/mozilla/funfactory/blob/c9bbf1c534eaa15641265bc75fa87afca52b7dd6/funfactory/settings_base.py#L329-L341
limix/limix-core
limix_core/covar/cov2kronSum.py
Cov2KronSum.solve_t
def solve_t(self, Mt): """ Mt is dim_r x dim_c x d tensor """ if len(Mt.shape)==2: _Mt = Mt[:, :, sp.newaxis] else: _Mt = Mt LMt = vei_CoR_veX(_Mt, R=self.Lr(), C=self.Lc()) DLMt = self.D()[:, :, sp.newaxis] * LMt RV = vei_CoR_veX(DLMt, R=self.Lr().T, C=self.Lc().T) if len(Mt.shape)==2: RV = RV[:, :, 0] return RV
python
def solve_t(self, Mt): """ Mt is dim_r x dim_c x d tensor """ if len(Mt.shape)==2: _Mt = Mt[:, :, sp.newaxis] else: _Mt = Mt LMt = vei_CoR_veX(_Mt, R=self.Lr(), C=self.Lc()) DLMt = self.D()[:, :, sp.newaxis] * LMt RV = vei_CoR_veX(DLMt, R=self.Lr().T, C=self.Lc().T) if len(Mt.shape)==2: RV = RV[:, :, 0] return RV
[ "def", "solve_t", "(", "self", ",", "Mt", ")", ":", "if", "len", "(", "Mt", ".", "shape", ")", "==", "2", ":", "_Mt", "=", "Mt", "[", ":", ",", ":", ",", "sp", ".", "newaxis", "]", "else", ":", "_Mt", "=", "Mt", "LMt", "=", "vei_CoR_veX", "...
Mt is dim_r x dim_c x d tensor
[ "Mt", "is", "dim_r", "x", "dim_c", "x", "d", "tensor" ]
train
https://github.com/limix/limix-core/blob/5c590b4d351409f83ca320844b4897ce92203814/limix_core/covar/cov2kronSum.py#L264-L274
ubccr/pinky
pinky/fingerprints/ecfp.py
invariants
def invariants(mol): """Generate initial atom identifiers using atomic invariants""" atom_ids = {} for a in mol.atoms: components = [] components.append(a.number) components.append(len(a.oatoms)) components.append(a.hcount) components.append(a.charge) components.append(a.mass) if len(a.rings) > 0: components.append(1) atom_ids[a.index] = gen_hash(components) return atom_ids
python
def invariants(mol): """Generate initial atom identifiers using atomic invariants""" atom_ids = {} for a in mol.atoms: components = [] components.append(a.number) components.append(len(a.oatoms)) components.append(a.hcount) components.append(a.charge) components.append(a.mass) if len(a.rings) > 0: components.append(1) atom_ids[a.index] = gen_hash(components) return atom_ids
[ "def", "invariants", "(", "mol", ")", ":", "atom_ids", "=", "{", "}", "for", "a", "in", "mol", ".", "atoms", ":", "components", "=", "[", "]", "components", ".", "append", "(", "a", ".", "number", ")", "components", ".", "append", "(", "len", "(", ...
Generate initial atom identifiers using atomic invariants
[ "Generate", "initial", "atom", "identifiers", "using", "atomic", "invariants" ]
train
https://github.com/ubccr/pinky/blob/e9d6e8ff72aa7f670b591e3bd3629cb879db1a93/pinky/fingerprints/ecfp.py#L13-L28
ubccr/pinky
pinky/fingerprints/ecfp.py
ecfp
def ecfp(mol, radius=2): """Compute the Extended-Connectivity fingerprint for a molecule. :param mol: molecule object parsed from SMILES string :param radius: The number of iterations to perform. Defaults to 2 which is equivilent to ECFP4. :rtype: dictionary representing the molecular fingprint (atom identifiers and their counts). """ atom_ids = invariants(mol) fp = {} for i in atom_ids.values(): fp[i] = fp.get(i, 0) + 1 neighborhoods = [] atom_neighborhoods = [ len(mol.bonds) * bitarray('0') for a in mol.atoms] dead_atoms = len(mol.atoms) * bitarray('0') for layer in xrange(1, radius+1): round_ids = {} round_atom_neighborhoods = copy.deepcopy(atom_neighborhoods) neighborhoods_this_round = [] for a in mol.atoms: if dead_atoms[a.index]: continue nbsr = [] for b in a.bonds: round_atom_neighborhoods[a.index][b.index] = True oidx = b.xatom(a).index round_atom_neighborhoods[a.index] |= atom_neighborhoods[oidx] nbsr.append((b.bondtype, atom_ids[oidx])) nbsr = sorted(nbsr) nbsr = [item for sublist in nbsr for item in sublist] nbsr.insert(0, atom_ids[a.index]) nbsr.insert(0, layer) round_ids[a.index] = gen_hash(nbsr) neighborhoods_this_round.append( (round_atom_neighborhoods[a.index], round_ids[a.index], a.index) ) for lst in neighborhoods_this_round: if lst[0] not in neighborhoods: fp[lst[1]] = fp.get(lst[1], 0) + 1 neighborhoods.append(lst[0]) else: dead_atoms[lst[2]] = True atom_ids = round_ids atom_neighborhoods = copy.deepcopy(round_atom_neighborhoods) return fp
python
def ecfp(mol, radius=2): """Compute the Extended-Connectivity fingerprint for a molecule. :param mol: molecule object parsed from SMILES string :param radius: The number of iterations to perform. Defaults to 2 which is equivilent to ECFP4. :rtype: dictionary representing the molecular fingprint (atom identifiers and their counts). """ atom_ids = invariants(mol) fp = {} for i in atom_ids.values(): fp[i] = fp.get(i, 0) + 1 neighborhoods = [] atom_neighborhoods = [ len(mol.bonds) * bitarray('0') for a in mol.atoms] dead_atoms = len(mol.atoms) * bitarray('0') for layer in xrange(1, radius+1): round_ids = {} round_atom_neighborhoods = copy.deepcopy(atom_neighborhoods) neighborhoods_this_round = [] for a in mol.atoms: if dead_atoms[a.index]: continue nbsr = [] for b in a.bonds: round_atom_neighborhoods[a.index][b.index] = True oidx = b.xatom(a).index round_atom_neighborhoods[a.index] |= atom_neighborhoods[oidx] nbsr.append((b.bondtype, atom_ids[oidx])) nbsr = sorted(nbsr) nbsr = [item for sublist in nbsr for item in sublist] nbsr.insert(0, atom_ids[a.index]) nbsr.insert(0, layer) round_ids[a.index] = gen_hash(nbsr) neighborhoods_this_round.append( (round_atom_neighborhoods[a.index], round_ids[a.index], a.index) ) for lst in neighborhoods_this_round: if lst[0] not in neighborhoods: fp[lst[1]] = fp.get(lst[1], 0) + 1 neighborhoods.append(lst[0]) else: dead_atoms[lst[2]] = True atom_ids = round_ids atom_neighborhoods = copy.deepcopy(round_atom_neighborhoods) return fp
[ "def", "ecfp", "(", "mol", ",", "radius", "=", "2", ")", ":", "atom_ids", "=", "invariants", "(", "mol", ")", "fp", "=", "{", "}", "for", "i", "in", "atom_ids", ".", "values", "(", ")", ":", "fp", "[", "i", "]", "=", "fp", ".", "get", "(", ...
Compute the Extended-Connectivity fingerprint for a molecule. :param mol: molecule object parsed from SMILES string :param radius: The number of iterations to perform. Defaults to 2 which is equivilent to ECFP4. :rtype: dictionary representing the molecular fingprint (atom identifiers and their counts).
[ "Compute", "the", "Extended", "-", "Connectivity", "fingerprint", "for", "a", "molecule", ".", ":", "param", "mol", ":", "molecule", "object", "parsed", "from", "SMILES", "string", ":", "param", "radius", ":", "The", "number", "of", "iterations", "to", "perf...
train
https://github.com/ubccr/pinky/blob/e9d6e8ff72aa7f670b591e3bd3629cb879db1a93/pinky/fingerprints/ecfp.py#L30-L82
pyroscope/pyrobase
src/pyrobase/io/http.py
HttpPost.send
def send(self): """ Post fields and files to an HTTP server as multipart/form-data. Return the server's response. """ scheme, location, path, query, _ = urlparse.urlsplit(self.url) assert scheme in ("http", "https"), "Unsupported scheme %r" % scheme content_type, body = self._encode_multipart_formdata() handle = getattr(httplib, scheme.upper() + "Connection")(location) if self.mock_http: # Don't actually send anything, print to stdout instead handle.sock = parts.Bunch( sendall=lambda x: sys.stdout.write(fmt.to_utf8( ''.join((c if 32 <= ord(c) < 127 or ord(c) in (8, 10) else u'\u27ea%02X\u27eb' % ord(c)) for c in x) )), makefile=lambda dummy, _: StringIO.StringIO("\r\n".join(( "HTTP/1.0 204 NO CONTENT", "Content-Length: 0", "", ))), close=lambda: None, ) handle.putrequest('POST', urlparse.urlunsplit(('', '', path, query, ''))) handle.putheader('Content-Type', content_type) handle.putheader('Content-Length', str(len(body))) for key, val in self.headers.items(): handle.putheader(key, val) handle.endheaders() handle.send(body) #print handle.__dict__ return handle.getresponse()
python
def send(self): """ Post fields and files to an HTTP server as multipart/form-data. Return the server's response. """ scheme, location, path, query, _ = urlparse.urlsplit(self.url) assert scheme in ("http", "https"), "Unsupported scheme %r" % scheme content_type, body = self._encode_multipart_formdata() handle = getattr(httplib, scheme.upper() + "Connection")(location) if self.mock_http: # Don't actually send anything, print to stdout instead handle.sock = parts.Bunch( sendall=lambda x: sys.stdout.write(fmt.to_utf8( ''.join((c if 32 <= ord(c) < 127 or ord(c) in (8, 10) else u'\u27ea%02X\u27eb' % ord(c)) for c in x) )), makefile=lambda dummy, _: StringIO.StringIO("\r\n".join(( "HTTP/1.0 204 NO CONTENT", "Content-Length: 0", "", ))), close=lambda: None, ) handle.putrequest('POST', urlparse.urlunsplit(('', '', path, query, ''))) handle.putheader('Content-Type', content_type) handle.putheader('Content-Length', str(len(body))) for key, val in self.headers.items(): handle.putheader(key, val) handle.endheaders() handle.send(body) #print handle.__dict__ return handle.getresponse()
[ "def", "send", "(", "self", ")", ":", "scheme", ",", "location", ",", "path", ",", "query", ",", "_", "=", "urlparse", ".", "urlsplit", "(", "self", ".", "url", ")", "assert", "scheme", "in", "(", "\"http\"", ",", "\"https\"", ")", ",", "\"Unsupporte...
Post fields and files to an HTTP server as multipart/form-data. Return the server's response.
[ "Post", "fields", "and", "files", "to", "an", "HTTP", "server", "as", "multipart", "/", "form", "-", "data", ".", "Return", "the", "server", "s", "response", "." ]
train
https://github.com/pyroscope/pyrobase/blob/7a2591baa492c3d8997ab4801b97c7b1f2ebc6b1/src/pyrobase/io/http.py#L64-L96
pyroscope/pyrobase
src/pyrobase/io/http.py
HttpPost._encode_multipart_formdata
def _encode_multipart_formdata(self): """ Encode POST body. Return (content_type, body) ready for httplib.HTTP instance """ def get_content_type(filename): "Helper to get MIME type." return mimetypes.guess_type(filename)[0] or 'application/octet-stream' boundary = '----------ThIs_Is_tHe_b0uNdaRY_%d$' % (time.time()) logical_lines = [] for name, value in self.fields: if value is None: continue logical_lines.append('--' + boundary) if hasattr(value, "read"): filename = getattr(value, "name", str(id(value))+".dat") logical_lines.append('Content-Disposition: form-data; name="%s"; filename="%s"' % ( name, os.path.basename(filename).replace("'", '_').replace('"', '_') )) logical_lines.append('Content-Type: %s' % get_content_type(filename)) logical_lines.append('Content-Transfer-Encoding: binary') value = value.read() else: logical_lines.append('Content-Disposition: form-data; name="%s"' % name) logical_lines.append('Content-Type: text/plain; charset="UTF-8"') value = fmt.to_utf8(value) #logical_lines.append('Content-Length: %d' % len(value)) logical_lines.append('') logical_lines.append(value) logical_lines.append('--' + boundary + '--') logical_lines.append('') body = '\r\n'.join(logical_lines) content_type = 'multipart/form-data; boundary=%s' % boundary return content_type, body
python
def _encode_multipart_formdata(self): """ Encode POST body. Return (content_type, body) ready for httplib.HTTP instance """ def get_content_type(filename): "Helper to get MIME type." return mimetypes.guess_type(filename)[0] or 'application/octet-stream' boundary = '----------ThIs_Is_tHe_b0uNdaRY_%d$' % (time.time()) logical_lines = [] for name, value in self.fields: if value is None: continue logical_lines.append('--' + boundary) if hasattr(value, "read"): filename = getattr(value, "name", str(id(value))+".dat") logical_lines.append('Content-Disposition: form-data; name="%s"; filename="%s"' % ( name, os.path.basename(filename).replace("'", '_').replace('"', '_') )) logical_lines.append('Content-Type: %s' % get_content_type(filename)) logical_lines.append('Content-Transfer-Encoding: binary') value = value.read() else: logical_lines.append('Content-Disposition: form-data; name="%s"' % name) logical_lines.append('Content-Type: text/plain; charset="UTF-8"') value = fmt.to_utf8(value) #logical_lines.append('Content-Length: %d' % len(value)) logical_lines.append('') logical_lines.append(value) logical_lines.append('--' + boundary + '--') logical_lines.append('') body = '\r\n'.join(logical_lines) content_type = 'multipart/form-data; boundary=%s' % boundary return content_type, body
[ "def", "_encode_multipart_formdata", "(", "self", ")", ":", "def", "get_content_type", "(", "filename", ")", ":", "\"Helper to get MIME type.\"", "return", "mimetypes", ".", "guess_type", "(", "filename", ")", "[", "0", "]", "or", "'application/octet-stream'", "boun...
Encode POST body. Return (content_type, body) ready for httplib.HTTP instance
[ "Encode", "POST", "body", ".", "Return", "(", "content_type", "body", ")", "ready", "for", "httplib", ".", "HTTP", "instance" ]
train
https://github.com/pyroscope/pyrobase/blob/7a2591baa492c3d8997ab4801b97c7b1f2ebc6b1/src/pyrobase/io/http.py#L99-L134
all-umass/graphs
graphs/construction/spanning_tree.py
perturbed_mst
def perturbed_mst(X, num_perturbations=20, metric='euclidean', jitter=None): '''Builds a graph as the union of several MSTs on perturbed data. Reference: http://ecovision.mit.edu/~sloop/shao.pdf, page 8 jitter refers to the scale of the gaussian noise added for each perturbation. When jitter is None, it defaults to the 5th percentile interpoint distance. Note that metric cannot be 'precomputed', as multiple MSTs are computed.''' assert metric != 'precomputed' D = pairwise_distances(X, metric=metric) if jitter is None: jitter = np.percentile(D[D>0], 5) W = minimum_spanning_tree(D) W = W + W.T W.data[:] = 1.0 # binarize for i in range(num_perturbations): pX = X + np.random.normal(scale=jitter, size=X.shape) pW = minimum_spanning_tree(pairwise_distances(pX, metric=metric)) pW = pW + pW.T pW.data[:] = 1.0 W = W + pW # final graph is the average over all pertubed MSTs + the original W.data /= (num_perturbations + 1.0) return Graph.from_adj_matrix(W)
python
def perturbed_mst(X, num_perturbations=20, metric='euclidean', jitter=None): '''Builds a graph as the union of several MSTs on perturbed data. Reference: http://ecovision.mit.edu/~sloop/shao.pdf, page 8 jitter refers to the scale of the gaussian noise added for each perturbation. When jitter is None, it defaults to the 5th percentile interpoint distance. Note that metric cannot be 'precomputed', as multiple MSTs are computed.''' assert metric != 'precomputed' D = pairwise_distances(X, metric=metric) if jitter is None: jitter = np.percentile(D[D>0], 5) W = minimum_spanning_tree(D) W = W + W.T W.data[:] = 1.0 # binarize for i in range(num_perturbations): pX = X + np.random.normal(scale=jitter, size=X.shape) pW = minimum_spanning_tree(pairwise_distances(pX, metric=metric)) pW = pW + pW.T pW.data[:] = 1.0 W = W + pW # final graph is the average over all pertubed MSTs + the original W.data /= (num_perturbations + 1.0) return Graph.from_adj_matrix(W)
[ "def", "perturbed_mst", "(", "X", ",", "num_perturbations", "=", "20", ",", "metric", "=", "'euclidean'", ",", "jitter", "=", "None", ")", ":", "assert", "metric", "!=", "'precomputed'", "D", "=", "pairwise_distances", "(", "X", ",", "metric", "=", "metric...
Builds a graph as the union of several MSTs on perturbed data. Reference: http://ecovision.mit.edu/~sloop/shao.pdf, page 8 jitter refers to the scale of the gaussian noise added for each perturbation. When jitter is None, it defaults to the 5th percentile interpoint distance. Note that metric cannot be 'precomputed', as multiple MSTs are computed.
[ "Builds", "a", "graph", "as", "the", "union", "of", "several", "MSTs", "on", "perturbed", "data", ".", "Reference", ":", "http", ":", "//", "ecovision", ".", "mit", ".", "edu", "/", "~sloop", "/", "shao", ".", "pdf", "page", "8", "jitter", "refers", ...
train
https://github.com/all-umass/graphs/blob/4fbeb025dfe33340335f34300f58dd3809228822/graphs/construction/spanning_tree.py#L18-L39
all-umass/graphs
graphs/construction/spanning_tree.py
disjoint_mst
def disjoint_mst(X, num_spanning_trees=3, metric='euclidean'): '''Builds a graph as the union of several spanning trees, each time removing any edges present in previously-built trees. Reference: http://ecovision.mit.edu/~sloop/shao.pdf, page 9.''' D = pairwise_distances(X, metric=metric) if metric == 'precomputed': D = D.copy() mst = minimum_spanning_tree(D) W = mst.copy() for i in range(1, num_spanning_trees): ii,jj = mst.nonzero() D[ii,jj] = np.inf D[jj,ii] = np.inf mst = minimum_spanning_tree(D) W = W + mst # MSTs are all one-sided, so we symmetrize here return Graph.from_adj_matrix(W + W.T)
python
def disjoint_mst(X, num_spanning_trees=3, metric='euclidean'): '''Builds a graph as the union of several spanning trees, each time removing any edges present in previously-built trees. Reference: http://ecovision.mit.edu/~sloop/shao.pdf, page 9.''' D = pairwise_distances(X, metric=metric) if metric == 'precomputed': D = D.copy() mst = minimum_spanning_tree(D) W = mst.copy() for i in range(1, num_spanning_trees): ii,jj = mst.nonzero() D[ii,jj] = np.inf D[jj,ii] = np.inf mst = minimum_spanning_tree(D) W = W + mst # MSTs are all one-sided, so we symmetrize here return Graph.from_adj_matrix(W + W.T)
[ "def", "disjoint_mst", "(", "X", ",", "num_spanning_trees", "=", "3", ",", "metric", "=", "'euclidean'", ")", ":", "D", "=", "pairwise_distances", "(", "X", ",", "metric", "=", "metric", ")", "if", "metric", "==", "'precomputed'", ":", "D", "=", "D", "...
Builds a graph as the union of several spanning trees, each time removing any edges present in previously-built trees. Reference: http://ecovision.mit.edu/~sloop/shao.pdf, page 9.
[ "Builds", "a", "graph", "as", "the", "union", "of", "several", "spanning", "trees", "each", "time", "removing", "any", "edges", "present", "in", "previously", "-", "built", "trees", ".", "Reference", ":", "http", ":", "//", "ecovision", ".", "mit", ".", ...
train
https://github.com/all-umass/graphs/blob/4fbeb025dfe33340335f34300f58dd3809228822/graphs/construction/spanning_tree.py#L42-L58
all-umass/graphs
graphs/mixins/transformation.py
TransformMixin.kernelize
def kernelize(self, kernel): '''Re-weight according to a specified kernel function. kernel : str, {none, binary, rbf} none -> no reweighting binary -> all edges are given weight 1 rbf -> applies a gaussian function to edge weights ''' if kernel == 'none': return self if kernel == 'binary': if self.is_weighted(): return self._update_edges(1, copy=True) return self if kernel == 'rbf': w = self.edge_weights() r = np.exp(-w / w.std()) return self._update_edges(r, copy=True) raise ValueError('Invalid kernel type: %r' % kernel)
python
def kernelize(self, kernel): '''Re-weight according to a specified kernel function. kernel : str, {none, binary, rbf} none -> no reweighting binary -> all edges are given weight 1 rbf -> applies a gaussian function to edge weights ''' if kernel == 'none': return self if kernel == 'binary': if self.is_weighted(): return self._update_edges(1, copy=True) return self if kernel == 'rbf': w = self.edge_weights() r = np.exp(-w / w.std()) return self._update_edges(r, copy=True) raise ValueError('Invalid kernel type: %r' % kernel)
[ "def", "kernelize", "(", "self", ",", "kernel", ")", ":", "if", "kernel", "==", "'none'", ":", "return", "self", "if", "kernel", "==", "'binary'", ":", "if", "self", ".", "is_weighted", "(", ")", ":", "return", "self", ".", "_update_edges", "(", "1", ...
Re-weight according to a specified kernel function. kernel : str, {none, binary, rbf} none -> no reweighting binary -> all edges are given weight 1 rbf -> applies a gaussian function to edge weights
[ "Re", "-", "weight", "according", "to", "a", "specified", "kernel", "function", ".", "kernel", ":", "str", "{", "none", "binary", "rbf", "}", "none", "-", ">", "no", "reweighting", "binary", "-", ">", "all", "edges", "are", "given", "weight", "1", "rbf...
train
https://github.com/all-umass/graphs/blob/4fbeb025dfe33340335f34300f58dd3809228822/graphs/mixins/transformation.py#L13-L30
all-umass/graphs
graphs/mixins/transformation.py
TransformMixin.barycenter_edge_weights
def barycenter_edge_weights(self, X, copy=True, reg=1e-3): '''Re-weight such that the sum of each vertex's edge weights is 1. The resulting weighted graph is suitable for locally linear embedding. reg : amount of regularization to keep the problem well-posed ''' new_weights = [] for i, adj in enumerate(self.adj_list()): C = X[adj] - X[i] G = C.dot(C.T) trace = np.trace(G) r = reg * trace if trace > 0 else reg G.flat[::G.shape[1] + 1] += r w = solve(G, np.ones(G.shape[0]), sym_pos=True, overwrite_a=True, overwrite_b=True) w /= w.sum() new_weights.extend(w.tolist()) return self.reweight(new_weights, copy=copy)
python
def barycenter_edge_weights(self, X, copy=True, reg=1e-3): '''Re-weight such that the sum of each vertex's edge weights is 1. The resulting weighted graph is suitable for locally linear embedding. reg : amount of regularization to keep the problem well-posed ''' new_weights = [] for i, adj in enumerate(self.adj_list()): C = X[adj] - X[i] G = C.dot(C.T) trace = np.trace(G) r = reg * trace if trace > 0 else reg G.flat[::G.shape[1] + 1] += r w = solve(G, np.ones(G.shape[0]), sym_pos=True, overwrite_a=True, overwrite_b=True) w /= w.sum() new_weights.extend(w.tolist()) return self.reweight(new_weights, copy=copy)
[ "def", "barycenter_edge_weights", "(", "self", ",", "X", ",", "copy", "=", "True", ",", "reg", "=", "1e-3", ")", ":", "new_weights", "=", "[", "]", "for", "i", ",", "adj", "in", "enumerate", "(", "self", ".", "adj_list", "(", ")", ")", ":", "C", ...
Re-weight such that the sum of each vertex's edge weights is 1. The resulting weighted graph is suitable for locally linear embedding. reg : amount of regularization to keep the problem well-posed
[ "Re", "-", "weight", "such", "that", "the", "sum", "of", "each", "vertex", "s", "edge", "weights", "is", "1", ".", "The", "resulting", "weighted", "graph", "is", "suitable", "for", "locally", "linear", "embedding", ".", "reg", ":", "amount", "of", "regul...
train
https://github.com/all-umass/graphs/blob/4fbeb025dfe33340335f34300f58dd3809228822/graphs/mixins/transformation.py#L32-L48
all-umass/graphs
graphs/mixins/transformation.py
TransformMixin.connected_subgraphs
def connected_subgraphs(self, directed=True, ordered=False): '''Generates connected components as subgraphs. When ordered=True, subgraphs are ordered by number of vertices. ''' num_ccs, labels = self.connected_components(directed=directed) # check the trivial case first if num_ccs == 1: yield self raise StopIteration if ordered: # sort by descending size (num vertices) order = np.argsort(np.bincount(labels))[::-1] else: order = range(num_ccs) # don't use self.subgraph() here, because we can reuse adj adj = self.matrix('dense', 'csr', 'csc') for c in order: mask = labels == c sub_adj = adj[mask][:,mask] yield self.__class__.from_adj_matrix(sub_adj)
python
def connected_subgraphs(self, directed=True, ordered=False): '''Generates connected components as subgraphs. When ordered=True, subgraphs are ordered by number of vertices. ''' num_ccs, labels = self.connected_components(directed=directed) # check the trivial case first if num_ccs == 1: yield self raise StopIteration if ordered: # sort by descending size (num vertices) order = np.argsort(np.bincount(labels))[::-1] else: order = range(num_ccs) # don't use self.subgraph() here, because we can reuse adj adj = self.matrix('dense', 'csr', 'csc') for c in order: mask = labels == c sub_adj = adj[mask][:,mask] yield self.__class__.from_adj_matrix(sub_adj)
[ "def", "connected_subgraphs", "(", "self", ",", "directed", "=", "True", ",", "ordered", "=", "False", ")", ":", "num_ccs", ",", "labels", "=", "self", ".", "connected_components", "(", "directed", "=", "directed", ")", "# check the trivial case first", "if", ...
Generates connected components as subgraphs. When ordered=True, subgraphs are ordered by number of vertices.
[ "Generates", "connected", "components", "as", "subgraphs", ".", "When", "ordered", "=", "True", "subgraphs", "are", "ordered", "by", "number", "of", "vertices", "." ]
train
https://github.com/all-umass/graphs/blob/4fbeb025dfe33340335f34300f58dd3809228822/graphs/mixins/transformation.py#L50-L70
all-umass/graphs
graphs/mixins/transformation.py
TransformMixin.minimum_spanning_subtree
def minimum_spanning_subtree(self): '''Returns the (undirected) minimum spanning tree subgraph.''' dist = self.matrix('dense', copy=True) dist[dist==0] = np.inf np.fill_diagonal(dist, 0) mst = ssc.minimum_spanning_tree(dist) return self.__class__.from_adj_matrix(mst + mst.T)
python
def minimum_spanning_subtree(self): '''Returns the (undirected) minimum spanning tree subgraph.''' dist = self.matrix('dense', copy=True) dist[dist==0] = np.inf np.fill_diagonal(dist, 0) mst = ssc.minimum_spanning_tree(dist) return self.__class__.from_adj_matrix(mst + mst.T)
[ "def", "minimum_spanning_subtree", "(", "self", ")", ":", "dist", "=", "self", ".", "matrix", "(", "'dense'", ",", "copy", "=", "True", ")", "dist", "[", "dist", "==", "0", "]", "=", "np", ".", "inf", "np", ".", "fill_diagonal", "(", "dist", ",", "...
Returns the (undirected) minimum spanning tree subgraph.
[ "Returns", "the", "(", "undirected", ")", "minimum", "spanning", "tree", "subgraph", "." ]
train
https://github.com/all-umass/graphs/blob/4fbeb025dfe33340335f34300f58dd3809228822/graphs/mixins/transformation.py#L84-L90
all-umass/graphs
graphs/mixins/transformation.py
TransformMixin.neighborhood_subgraph
def neighborhood_subgraph(self, start_idx, radius=1, weighted=True, directed=True, return_mask=False): '''Returns a subgraph containing only vertices within a given geodesic radius of start_idx.''' adj = self.matrix('dense', 'csr', 'csc') dist = ssc.dijkstra(adj, directed=directed, indices=start_idx, unweighted=(not weighted), limit=radius) mask = np.isfinite(dist) sub_adj = adj[mask][:,mask] g = self.__class__.from_adj_matrix(sub_adj) if return_mask: return g, mask return g
python
def neighborhood_subgraph(self, start_idx, radius=1, weighted=True, directed=True, return_mask=False): '''Returns a subgraph containing only vertices within a given geodesic radius of start_idx.''' adj = self.matrix('dense', 'csr', 'csc') dist = ssc.dijkstra(adj, directed=directed, indices=start_idx, unweighted=(not weighted), limit=radius) mask = np.isfinite(dist) sub_adj = adj[mask][:,mask] g = self.__class__.from_adj_matrix(sub_adj) if return_mask: return g, mask return g
[ "def", "neighborhood_subgraph", "(", "self", ",", "start_idx", ",", "radius", "=", "1", ",", "weighted", "=", "True", ",", "directed", "=", "True", ",", "return_mask", "=", "False", ")", ":", "adj", "=", "self", ".", "matrix", "(", "'dense'", ",", "'cs...
Returns a subgraph containing only vertices within a given geodesic radius of start_idx.
[ "Returns", "a", "subgraph", "containing", "only", "vertices", "within", "a", "given", "geodesic", "radius", "of", "start_idx", "." ]
train
https://github.com/all-umass/graphs/blob/4fbeb025dfe33340335f34300f58dd3809228822/graphs/mixins/transformation.py#L92-L104
all-umass/graphs
graphs/mixins/transformation.py
TransformMixin.isograph
def isograph(self, min_weight=None): '''Remove short-circuit edges using the Isograph algorithm. min_weight : float, optional Minimum weight of edges to consider removing. Defaults to max(MST). From "Isograph: Neighbourhood Graph Construction Based On Geodesic Distance For Semi-Supervised Learning" by Ghazvininejad et al., 2011. Note: This uses the non-iterative algorithm which removes edges rather than reweighting them. ''' W = self.matrix('dense') # get candidate edges: all edges - MST edges tree = self.minimum_spanning_subtree() candidates = np.argwhere((W - tree.matrix('dense')) > 0) cand_weights = W[candidates[:,0], candidates[:,1]] # order by increasing edge weight order = np.argsort(cand_weights) cand_weights = cand_weights[order] # disregard edges shorter than a threshold if min_weight is None: min_weight = tree.edge_weights().max() idx = np.searchsorted(cand_weights, min_weight) cand_weights = cand_weights[idx:] candidates = candidates[order[idx:]] # check each candidate edge to_remove = np.zeros_like(cand_weights, dtype=bool) for i, (u,v) in enumerate(candidates): W_uv = np.where(W < cand_weights[i], W, 0) len_uv = ssc.dijkstra(W_uv, indices=u, unweighted=True, limit=2)[v] if len_uv > 2: to_remove[i] = True ii, jj = candidates[to_remove].T return self.remove_edges(ii, jj, copy=True)
python
def isograph(self, min_weight=None): '''Remove short-circuit edges using the Isograph algorithm. min_weight : float, optional Minimum weight of edges to consider removing. Defaults to max(MST). From "Isograph: Neighbourhood Graph Construction Based On Geodesic Distance For Semi-Supervised Learning" by Ghazvininejad et al., 2011. Note: This uses the non-iterative algorithm which removes edges rather than reweighting them. ''' W = self.matrix('dense') # get candidate edges: all edges - MST edges tree = self.minimum_spanning_subtree() candidates = np.argwhere((W - tree.matrix('dense')) > 0) cand_weights = W[candidates[:,0], candidates[:,1]] # order by increasing edge weight order = np.argsort(cand_weights) cand_weights = cand_weights[order] # disregard edges shorter than a threshold if min_weight is None: min_weight = tree.edge_weights().max() idx = np.searchsorted(cand_weights, min_weight) cand_weights = cand_weights[idx:] candidates = candidates[order[idx:]] # check each candidate edge to_remove = np.zeros_like(cand_weights, dtype=bool) for i, (u,v) in enumerate(candidates): W_uv = np.where(W < cand_weights[i], W, 0) len_uv = ssc.dijkstra(W_uv, indices=u, unweighted=True, limit=2)[v] if len_uv > 2: to_remove[i] = True ii, jj = candidates[to_remove].T return self.remove_edges(ii, jj, copy=True)
[ "def", "isograph", "(", "self", ",", "min_weight", "=", "None", ")", ":", "W", "=", "self", ".", "matrix", "(", "'dense'", ")", "# get candidate edges: all edges - MST edges", "tree", "=", "self", ".", "minimum_spanning_subtree", "(", ")", "candidates", "=", "...
Remove short-circuit edges using the Isograph algorithm. min_weight : float, optional Minimum weight of edges to consider removing. Defaults to max(MST). From "Isograph: Neighbourhood Graph Construction Based On Geodesic Distance For Semi-Supervised Learning" by Ghazvininejad et al., 2011. Note: This uses the non-iterative algorithm which removes edges rather than reweighting them.
[ "Remove", "short", "-", "circuit", "edges", "using", "the", "Isograph", "algorithm", "." ]
train
https://github.com/all-umass/graphs/blob/4fbeb025dfe33340335f34300f58dd3809228822/graphs/mixins/transformation.py#L106-L139
all-umass/graphs
graphs/mixins/transformation.py
TransformMixin.circle_tear
def circle_tear(self, spanning_tree='mst', cycle_len_thresh=5, spt_idx=None, copy=True): '''Circular graph tearing. spanning_tree: one of {'mst', 'spt'} cycle_len_thresh: int, length of longest allowable cycle spt_idx: int, start vertex for shortest_path_subtree, random if None From "How to project 'circular' manifolds using geodesic distances?" by Lee & Verleysen, ESANN 2004. See also: shortest_path_subtree, minimum_spanning_subtree ''' # make the initial spanning tree graph if spanning_tree == 'mst': tree = self.minimum_spanning_subtree().matrix() elif spanning_tree == 'spt': if spt_idx is None: spt_idx = np.random.choice(self.num_vertices()) tree = self.shortest_path_subtree(spt_idx, directed=False).matrix() # find edges in self but not in the tree potential_edges = np.argwhere(ss.triu(self.matrix() - tree)) # remove edges that induce large cycles ii, jj = _find_cycle_inducers(tree, potential_edges, cycle_len_thresh) return self.remove_edges(ii, jj, symmetric=True, copy=copy)
python
def circle_tear(self, spanning_tree='mst', cycle_len_thresh=5, spt_idx=None, copy=True): '''Circular graph tearing. spanning_tree: one of {'mst', 'spt'} cycle_len_thresh: int, length of longest allowable cycle spt_idx: int, start vertex for shortest_path_subtree, random if None From "How to project 'circular' manifolds using geodesic distances?" by Lee & Verleysen, ESANN 2004. See also: shortest_path_subtree, minimum_spanning_subtree ''' # make the initial spanning tree graph if spanning_tree == 'mst': tree = self.minimum_spanning_subtree().matrix() elif spanning_tree == 'spt': if spt_idx is None: spt_idx = np.random.choice(self.num_vertices()) tree = self.shortest_path_subtree(spt_idx, directed=False).matrix() # find edges in self but not in the tree potential_edges = np.argwhere(ss.triu(self.matrix() - tree)) # remove edges that induce large cycles ii, jj = _find_cycle_inducers(tree, potential_edges, cycle_len_thresh) return self.remove_edges(ii, jj, symmetric=True, copy=copy)
[ "def", "circle_tear", "(", "self", ",", "spanning_tree", "=", "'mst'", ",", "cycle_len_thresh", "=", "5", ",", "spt_idx", "=", "None", ",", "copy", "=", "True", ")", ":", "# make the initial spanning tree graph", "if", "spanning_tree", "==", "'mst'", ":", "tre...
Circular graph tearing. spanning_tree: one of {'mst', 'spt'} cycle_len_thresh: int, length of longest allowable cycle spt_idx: int, start vertex for shortest_path_subtree, random if None From "How to project 'circular' manifolds using geodesic distances?" by Lee & Verleysen, ESANN 2004. See also: shortest_path_subtree, minimum_spanning_subtree
[ "Circular", "graph", "tearing", "." ]
train
https://github.com/all-umass/graphs/blob/4fbeb025dfe33340335f34300f58dd3809228822/graphs/mixins/transformation.py#L141-L167
all-umass/graphs
graphs/mixins/transformation.py
TransformMixin.cycle_cut
def cycle_cut(self, cycle_len_thresh=12, directed=False, copy=True): '''CycleCut algorithm: removes bottleneck edges. Paper DOI: 10.1.1.225.5335 ''' symmetric = not directed adj = self.kernelize('binary').matrix('csr', 'dense', copy=True) if symmetric: adj = adj + adj.T removed_edges = [] while True: c = _atomic_cycle(adj, cycle_len_thresh, directed=directed) if c is None: break # remove edges in the cycle ii, jj = c.T adj[ii,jj] = 0 if symmetric: adj[jj,ii] = 0 removed_edges.extend(c) #XXX: if _atomic_cycle changes, may need to do this on each loop if ss.issparse(adj): adj.eliminate_zeros() # select only the necessary cuts ii, jj = _find_cycle_inducers(adj, removed_edges, cycle_len_thresh, directed=directed) # remove the bad edges return self.remove_edges(ii, jj, symmetric=symmetric, copy=copy)
python
def cycle_cut(self, cycle_len_thresh=12, directed=False, copy=True): '''CycleCut algorithm: removes bottleneck edges. Paper DOI: 10.1.1.225.5335 ''' symmetric = not directed adj = self.kernelize('binary').matrix('csr', 'dense', copy=True) if symmetric: adj = adj + adj.T removed_edges = [] while True: c = _atomic_cycle(adj, cycle_len_thresh, directed=directed) if c is None: break # remove edges in the cycle ii, jj = c.T adj[ii,jj] = 0 if symmetric: adj[jj,ii] = 0 removed_edges.extend(c) #XXX: if _atomic_cycle changes, may need to do this on each loop if ss.issparse(adj): adj.eliminate_zeros() # select only the necessary cuts ii, jj = _find_cycle_inducers(adj, removed_edges, cycle_len_thresh, directed=directed) # remove the bad edges return self.remove_edges(ii, jj, symmetric=symmetric, copy=copy)
[ "def", "cycle_cut", "(", "self", ",", "cycle_len_thresh", "=", "12", ",", "directed", "=", "False", ",", "copy", "=", "True", ")", ":", "symmetric", "=", "not", "directed", "adj", "=", "self", ".", "kernelize", "(", "'binary'", ")", ".", "matrix", "(",...
CycleCut algorithm: removes bottleneck edges. Paper DOI: 10.1.1.225.5335
[ "CycleCut", "algorithm", ":", "removes", "bottleneck", "edges", ".", "Paper", "DOI", ":", "10", ".", "1", ".", "1", ".", "225", ".", "5335" ]
train
https://github.com/all-umass/graphs/blob/4fbeb025dfe33340335f34300f58dd3809228822/graphs/mixins/transformation.py#L169-L198
stbraun/fuzzing
fuzzing/fuzzer.py
fuzz_string
def fuzz_string(seed_str, runs=100, fuzz_factor=50): """A random fuzzer for a simulated text viewer application. It takes a string as seed and generates <runs> variant of it. :param seed_str: the string to use as seed for fuzzing. :param runs: number of fuzzed variants to supply. :param fuzz_factor: degree of fuzzing = 1 / fuzz_factor. :return: list of fuzzed variants of seed_str. :rtype: [str] """ buf = bytearray(seed_str, encoding="utf8") variants = [] for _ in range(runs): fuzzed = fuzzer(buf, fuzz_factor) variants.append(''.join([chr(b) for b in fuzzed])) logger().info('Fuzzed strings: {}'.format(variants)) return variants
python
def fuzz_string(seed_str, runs=100, fuzz_factor=50): """A random fuzzer for a simulated text viewer application. It takes a string as seed and generates <runs> variant of it. :param seed_str: the string to use as seed for fuzzing. :param runs: number of fuzzed variants to supply. :param fuzz_factor: degree of fuzzing = 1 / fuzz_factor. :return: list of fuzzed variants of seed_str. :rtype: [str] """ buf = bytearray(seed_str, encoding="utf8") variants = [] for _ in range(runs): fuzzed = fuzzer(buf, fuzz_factor) variants.append(''.join([chr(b) for b in fuzzed])) logger().info('Fuzzed strings: {}'.format(variants)) return variants
[ "def", "fuzz_string", "(", "seed_str", ",", "runs", "=", "100", ",", "fuzz_factor", "=", "50", ")", ":", "buf", "=", "bytearray", "(", "seed_str", ",", "encoding", "=", "\"utf8\"", ")", "variants", "=", "[", "]", "for", "_", "in", "range", "(", "runs...
A random fuzzer for a simulated text viewer application. It takes a string as seed and generates <runs> variant of it. :param seed_str: the string to use as seed for fuzzing. :param runs: number of fuzzed variants to supply. :param fuzz_factor: degree of fuzzing = 1 / fuzz_factor. :return: list of fuzzed variants of seed_str. :rtype: [str]
[ "A", "random", "fuzzer", "for", "a", "simulated", "text", "viewer", "application", "." ]
train
https://github.com/stbraun/fuzzing/blob/974a64472732d4e40db919d242149bf0856fe199/fuzzing/fuzzer.py#L55-L72
stbraun/fuzzing
fuzzing/fuzzer.py
fuzzer
def fuzzer(buffer, fuzz_factor=101): """Fuzz given buffer. Take a buffer of bytes, create a copy, and replace some bytes with random values. Number of bytes to modify depends on fuzz_factor. This code is taken from Charlie Miller's fuzzer code. :param buffer: the data to fuzz. :type buffer: byte array :param fuzz_factor: degree of fuzzing. :type fuzz_factor: int :return: fuzzed buffer. :rtype: byte array """ buf = deepcopy(buffer) num_writes = number_of_bytes_to_modify(len(buf), fuzz_factor) for _ in range(num_writes): random_byte = random.randrange(256) random_position = random.randrange(len(buf)) buf[random_position] = random_byte return buf
python
def fuzzer(buffer, fuzz_factor=101): """Fuzz given buffer. Take a buffer of bytes, create a copy, and replace some bytes with random values. Number of bytes to modify depends on fuzz_factor. This code is taken from Charlie Miller's fuzzer code. :param buffer: the data to fuzz. :type buffer: byte array :param fuzz_factor: degree of fuzzing. :type fuzz_factor: int :return: fuzzed buffer. :rtype: byte array """ buf = deepcopy(buffer) num_writes = number_of_bytes_to_modify(len(buf), fuzz_factor) for _ in range(num_writes): random_byte = random.randrange(256) random_position = random.randrange(len(buf)) buf[random_position] = random_byte return buf
[ "def", "fuzzer", "(", "buffer", ",", "fuzz_factor", "=", "101", ")", ":", "buf", "=", "deepcopy", "(", "buffer", ")", "num_writes", "=", "number_of_bytes_to_modify", "(", "len", "(", "buf", ")", ",", "fuzz_factor", ")", "for", "_", "in", "range", "(", ...
Fuzz given buffer. Take a buffer of bytes, create a copy, and replace some bytes with random values. Number of bytes to modify depends on fuzz_factor. This code is taken from Charlie Miller's fuzzer code. :param buffer: the data to fuzz. :type buffer: byte array :param fuzz_factor: degree of fuzzing. :type fuzz_factor: int :return: fuzzed buffer. :rtype: byte array
[ "Fuzz", "given", "buffer", "." ]
train
https://github.com/stbraun/fuzzing/blob/974a64472732d4e40db919d242149bf0856fe199/fuzzing/fuzzer.py#L75-L95
stbraun/fuzzing
fuzzing/fuzzer.py
number_of_bytes_to_modify
def number_of_bytes_to_modify(buf_len, fuzz_factor): """Calculate number of bytes to modify. :param buf_len: len of data buffer to fuzz. :param fuzz_factor: degree of fuzzing. :return: number of bytes to change. """ return random.randrange(math.ceil((float(buf_len) / fuzz_factor))) + 1
python
def number_of_bytes_to_modify(buf_len, fuzz_factor): """Calculate number of bytes to modify. :param buf_len: len of data buffer to fuzz. :param fuzz_factor: degree of fuzzing. :return: number of bytes to change. """ return random.randrange(math.ceil((float(buf_len) / fuzz_factor))) + 1
[ "def", "number_of_bytes_to_modify", "(", "buf_len", ",", "fuzz_factor", ")", ":", "return", "random", ".", "randrange", "(", "math", ".", "ceil", "(", "(", "float", "(", "buf_len", ")", "/", "fuzz_factor", ")", ")", ")", "+", "1" ]
Calculate number of bytes to modify. :param buf_len: len of data buffer to fuzz. :param fuzz_factor: degree of fuzzing. :return: number of bytes to change.
[ "Calculate", "number", "of", "bytes", "to", "modify", "." ]
train
https://github.com/stbraun/fuzzing/blob/974a64472732d4e40db919d242149bf0856fe199/fuzzing/fuzzer.py#L98-L105
stbraun/fuzzing
fuzzing/fuzzer.py
FuzzExecutor._fuzz_data_file
def _fuzz_data_file(self, data_file): """Generate fuzzed variant of given file. :param data_file: path to file to fuzz. :type data_file: str :return: path to fuzzed file. :rtype: str """ buf = bytearray(open(os.path.abspath(data_file), 'rb').read()) fuzzed = fuzzer(buf, self.fuzz_factor) try: _, fuzz_output = mkstemp(prefix='fuzzed_') open(fuzz_output, 'wb').write(fuzzed) finally: pass return fuzz_output
python
def _fuzz_data_file(self, data_file): """Generate fuzzed variant of given file. :param data_file: path to file to fuzz. :type data_file: str :return: path to fuzzed file. :rtype: str """ buf = bytearray(open(os.path.abspath(data_file), 'rb').read()) fuzzed = fuzzer(buf, self.fuzz_factor) try: _, fuzz_output = mkstemp(prefix='fuzzed_') open(fuzz_output, 'wb').write(fuzzed) finally: pass return fuzz_output
[ "def", "_fuzz_data_file", "(", "self", ",", "data_file", ")", ":", "buf", "=", "bytearray", "(", "open", "(", "os", ".", "path", ".", "abspath", "(", "data_file", ")", ",", "'rb'", ")", ".", "read", "(", ")", ")", "fuzzed", "=", "fuzzer", "(", "buf...
Generate fuzzed variant of given file. :param data_file: path to file to fuzz. :type data_file: str :return: path to fuzzed file. :rtype: str
[ "Generate", "fuzzed", "variant", "of", "given", "file", "." ]
train
https://github.com/stbraun/fuzzing/blob/974a64472732d4e40db919d242149bf0856fe199/fuzzing/fuzzer.py#L254-L269
stbraun/fuzzing
fuzzing/fuzzer.py
FuzzExecutor._execute
def _execute(self, app_, file_): """Run app with file as input. :param app_: application to run. :param file_: file to run app with. :return: success True, else False :rtype: bool """ app_name = os.path.basename(app_) args = [app_] args.extend(self.args[app_]) args.append(file_) process = subprocess.Popen(args) time.sleep(1) status = {True: Status.SUCCESS, False: Status.FAILED} crashed = process.poll() result = status[crashed is None] self.stats_.add(app_name, result) if result is Status.SUCCESS: # process did not crash, so just terminate it process.terminate()
python
def _execute(self, app_, file_): """Run app with file as input. :param app_: application to run. :param file_: file to run app with. :return: success True, else False :rtype: bool """ app_name = os.path.basename(app_) args = [app_] args.extend(self.args[app_]) args.append(file_) process = subprocess.Popen(args) time.sleep(1) status = {True: Status.SUCCESS, False: Status.FAILED} crashed = process.poll() result = status[crashed is None] self.stats_.add(app_name, result) if result is Status.SUCCESS: # process did not crash, so just terminate it process.terminate()
[ "def", "_execute", "(", "self", ",", "app_", ",", "file_", ")", ":", "app_name", "=", "os", ".", "path", ".", "basename", "(", "app_", ")", "args", "=", "[", "app_", "]", "args", ".", "extend", "(", "self", ".", "args", "[", "app_", "]", ")", "...
Run app with file as input. :param app_: application to run. :param file_: file to run app with. :return: success True, else False :rtype: bool
[ "Run", "app", "with", "file", "as", "input", "." ]
train
https://github.com/stbraun/fuzzing/blob/974a64472732d4e40db919d242149bf0856fe199/fuzzing/fuzzer.py#L271-L292
stbraun/fuzzing
fuzzing/fuzzer.py
FuzzExecutor.__parse_app_list
def __parse_app_list(app_list): """Parse list of apps for arguments. :param app_list: list of apps with optional arguments. :return: list of apps and assigned argument dict. :rtype: [String], {String: [String]} """ args = {} apps = [] for app_str in app_list: parts = app_str.split("&") app_path = parts[0].strip() apps.append(app_path) if len(parts) > 1: args[app_path] = [arg.strip() for arg in parts[1].split()] else: args[app_path] = [] return apps, args
python
def __parse_app_list(app_list): """Parse list of apps for arguments. :param app_list: list of apps with optional arguments. :return: list of apps and assigned argument dict. :rtype: [String], {String: [String]} """ args = {} apps = [] for app_str in app_list: parts = app_str.split("&") app_path = parts[0].strip() apps.append(app_path) if len(parts) > 1: args[app_path] = [arg.strip() for arg in parts[1].split()] else: args[app_path] = [] return apps, args
[ "def", "__parse_app_list", "(", "app_list", ")", ":", "args", "=", "{", "}", "apps", "=", "[", "]", "for", "app_str", "in", "app_list", ":", "parts", "=", "app_str", ".", "split", "(", "\"&\"", ")", "app_path", "=", "parts", "[", "0", "]", ".", "st...
Parse list of apps for arguments. :param app_list: list of apps with optional arguments. :return: list of apps and assigned argument dict. :rtype: [String], {String: [String]}
[ "Parse", "list", "of", "apps", "for", "arguments", "." ]
train
https://github.com/stbraun/fuzzing/blob/974a64472732d4e40db919d242149bf0856fe199/fuzzing/fuzzer.py#L295-L312
wangsix/vmo
vmo/VMO/utility/distances/tonnetz.py
_make_tonnetz_matrix
def _make_tonnetz_matrix(): """Return the tonnetz projection matrix.""" pi = np.pi chroma = np.arange(12) # Define each row of the transform matrix fifth_x = r_fifth*(np.sin((7*pi/6) * chroma)) fifth_y = r_fifth*(np.cos((7*pi/6) * chroma)) minor_third_x = r_minor_thirds*(np.sin(3*pi/2 * chroma)) minor_third_y = r_minor_thirds*(np.cos(3*pi/2 * chroma)) major_third_x = r_major_thirds*(np.sin(2*pi/3 * chroma)) major_third_y = r_major_thirds*(np.cos(2*pi/3 * chroma)) # Return the tonnetz matrix return np.vstack((fifth_x, fifth_y, minor_third_x, minor_third_y, major_third_x, major_third_y))
python
def _make_tonnetz_matrix(): """Return the tonnetz projection matrix.""" pi = np.pi chroma = np.arange(12) # Define each row of the transform matrix fifth_x = r_fifth*(np.sin((7*pi/6) * chroma)) fifth_y = r_fifth*(np.cos((7*pi/6) * chroma)) minor_third_x = r_minor_thirds*(np.sin(3*pi/2 * chroma)) minor_third_y = r_minor_thirds*(np.cos(3*pi/2 * chroma)) major_third_x = r_major_thirds*(np.sin(2*pi/3 * chroma)) major_third_y = r_major_thirds*(np.cos(2*pi/3 * chroma)) # Return the tonnetz matrix return np.vstack((fifth_x, fifth_y, minor_third_x, minor_third_y, major_third_x, major_third_y))
[ "def", "_make_tonnetz_matrix", "(", ")", ":", "pi", "=", "np", ".", "pi", "chroma", "=", "np", ".", "arange", "(", "12", ")", "# Define each row of the transform matrix", "fifth_x", "=", "r_fifth", "*", "(", "np", ".", "sin", "(", "(", "7", "*", "pi", ...
Return the tonnetz projection matrix.
[ "Return", "the", "tonnetz", "projection", "matrix", "." ]
train
https://github.com/wangsix/vmo/blob/bb1cc4cf1f33f0bb49e38c91126c1be1a0cdd09d/vmo/VMO/utility/distances/tonnetz.py#L56-L72
wangsix/vmo
vmo/VMO/utility/distances/tonnetz.py
_to_tonnetz
def _to_tonnetz(chromagram): """Project a chromagram on the tonnetz. Returned value is normalized to prevent numerical instabilities. """ if np.sum(np.abs(chromagram)) == 0.: # The input is an empty chord, return zero. return np.zeros(6) _tonnetz = np.dot(__TONNETZ_MATRIX, chromagram) one_norm = np.sum(np.abs(_tonnetz)) # Non-zero value _tonnetz = _tonnetz / float(one_norm) # Normalize tonnetz vector return _tonnetz
python
def _to_tonnetz(chromagram): """Project a chromagram on the tonnetz. Returned value is normalized to prevent numerical instabilities. """ if np.sum(np.abs(chromagram)) == 0.: # The input is an empty chord, return zero. return np.zeros(6) _tonnetz = np.dot(__TONNETZ_MATRIX, chromagram) one_norm = np.sum(np.abs(_tonnetz)) # Non-zero value _tonnetz = _tonnetz / float(one_norm) # Normalize tonnetz vector return _tonnetz
[ "def", "_to_tonnetz", "(", "chromagram", ")", ":", "if", "np", ".", "sum", "(", "np", ".", "abs", "(", "chromagram", ")", ")", "==", "0.", ":", "# The input is an empty chord, return zero. ", "return", "np", ".", "zeros", "(", "6", ")", "_tonnetz", "=", ...
Project a chromagram on the tonnetz. Returned value is normalized to prevent numerical instabilities.
[ "Project", "a", "chromagram", "on", "the", "tonnetz", "." ]
train
https://github.com/wangsix/vmo/blob/bb1cc4cf1f33f0bb49e38c91126c1be1a0cdd09d/vmo/VMO/utility/distances/tonnetz.py#L78-L90
wangsix/vmo
vmo/VMO/utility/distances/tonnetz.py
distance
def distance(a, b): """Compute tonnetz-distance between two chromagrams. ---- >>> C = np.zeros(12) >>> C[0] = 1 >>> D = np.zeros(12) >>> D[2] = 1 >>> G = np.zeros(12) >>> G[7] = 1 The distance is zero on equivalent chords >>> distance(C, C) == 0 True The distance is symetric >>> distance(C, D) == distance(D, C) True >>> distance(C, D) > 0 True >>> distance(C, G) < distance(C, D) True """ [a_tonnetz, b_tonnetz] = [_to_tonnetz(x) for x in [a, b]] return np.linalg.norm(b_tonnetz - a_tonnetz)
python
def distance(a, b): """Compute tonnetz-distance between two chromagrams. ---- >>> C = np.zeros(12) >>> C[0] = 1 >>> D = np.zeros(12) >>> D[2] = 1 >>> G = np.zeros(12) >>> G[7] = 1 The distance is zero on equivalent chords >>> distance(C, C) == 0 True The distance is symetric >>> distance(C, D) == distance(D, C) True >>> distance(C, D) > 0 True >>> distance(C, G) < distance(C, D) True """ [a_tonnetz, b_tonnetz] = [_to_tonnetz(x) for x in [a, b]] return np.linalg.norm(b_tonnetz - a_tonnetz)
[ "def", "distance", "(", "a", ",", "b", ")", ":", "[", "a_tonnetz", ",", "b_tonnetz", "]", "=", "[", "_to_tonnetz", "(", "x", ")", "for", "x", "in", "[", "a", ",", "b", "]", "]", "return", "np", ".", "linalg", ".", "norm", "(", "b_tonnetz", "-",...
Compute tonnetz-distance between two chromagrams. ---- >>> C = np.zeros(12) >>> C[0] = 1 >>> D = np.zeros(12) >>> D[2] = 1 >>> G = np.zeros(12) >>> G[7] = 1 The distance is zero on equivalent chords >>> distance(C, C) == 0 True The distance is symetric >>> distance(C, D) == distance(D, C) True >>> distance(C, D) > 0 True >>> distance(C, G) < distance(C, D) True
[ "Compute", "tonnetz", "-", "distance", "between", "two", "chromagrams", ".", "----", ">>>", "C", "=", "np", ".", "zeros", "(", "12", ")", ">>>", "C", "[", "0", "]", "=", "1", ">>>", "D", "=", "np", ".", "zeros", "(", "12", ")", ">>>", "D", "[",...
train
https://github.com/wangsix/vmo/blob/bb1cc4cf1f33f0bb49e38c91126c1be1a0cdd09d/vmo/VMO/utility/distances/tonnetz.py#L93-L118
gautammishra/lyft-rides-python-sdk
examples/utils.py
fail_print
def fail_print(error): """Print an error in red text. Parameters error (HTTPError) Error object to print. """ print(COLORS.fail, error.message, COLORS.end) print(COLORS.fail, error.errors, COLORS.end)
python
def fail_print(error): """Print an error in red text. Parameters error (HTTPError) Error object to print. """ print(COLORS.fail, error.message, COLORS.end) print(COLORS.fail, error.errors, COLORS.end)
[ "def", "fail_print", "(", "error", ")", ":", "print", "(", "COLORS", ".", "fail", ",", "error", ".", "message", ",", "COLORS", ".", "end", ")", "print", "(", "COLORS", ".", "fail", ",", "error", ".", "errors", ",", "COLORS", ".", "end", ")" ]
Print an error in red text. Parameters error (HTTPError) Error object to print.
[ "Print", "an", "error", "in", "red", "text", ".", "Parameters", "error", "(", "HTTPError", ")", "Error", "object", "to", "print", "." ]
train
https://github.com/gautammishra/lyft-rides-python-sdk/blob/b6d96a0fceaf7dc3425153c418a8e25c57803431/examples/utils.py#L62-L69
gautammishra/lyft-rides-python-sdk
examples/utils.py
import_oauth2_credentials
def import_oauth2_credentials(filename=STORAGE_FILENAME): """Import OAuth 2.0 session credentials from storage file. Parameters filename (str) Name of storage file. Returns credentials (dict) All your app credentials and information imported from the configuration file. """ with open(filename, 'r') as storage_file: storage = safe_load(storage_file) # depending on OAuth 2.0 grant_type, these values may not exist client_secret = storage.get('client_secret') refresh_token = storage.get('refresh_token') credentials = { 'access_token': storage['access_token'], 'client_id': storage['client_id'], 'client_secret': client_secret, 'expires_in_seconds': storage['expires_in_seconds'], 'grant_type': storage['grant_type'], 'refresh_token': refresh_token, 'scopes': storage['scopes'], } return credentials
python
def import_oauth2_credentials(filename=STORAGE_FILENAME): """Import OAuth 2.0 session credentials from storage file. Parameters filename (str) Name of storage file. Returns credentials (dict) All your app credentials and information imported from the configuration file. """ with open(filename, 'r') as storage_file: storage = safe_load(storage_file) # depending on OAuth 2.0 grant_type, these values may not exist client_secret = storage.get('client_secret') refresh_token = storage.get('refresh_token') credentials = { 'access_token': storage['access_token'], 'client_id': storage['client_id'], 'client_secret': client_secret, 'expires_in_seconds': storage['expires_in_seconds'], 'grant_type': storage['grant_type'], 'refresh_token': refresh_token, 'scopes': storage['scopes'], } return credentials
[ "def", "import_oauth2_credentials", "(", "filename", "=", "STORAGE_FILENAME", ")", ":", "with", "open", "(", "filename", ",", "'r'", ")", "as", "storage_file", ":", "storage", "=", "safe_load", "(", "storage_file", ")", "# depending on OAuth 2.0 grant_type, these valu...
Import OAuth 2.0 session credentials from storage file. Parameters filename (str) Name of storage file. Returns credentials (dict) All your app credentials and information imported from the configuration file.
[ "Import", "OAuth", "2", ".", "0", "session", "credentials", "from", "storage", "file", ".", "Parameters", "filename", "(", "str", ")", "Name", "of", "storage", "file", ".", "Returns", "credentials", "(", "dict", ")", "All", "your", "app", "credentials", "a...
train
https://github.com/gautammishra/lyft-rides-python-sdk/blob/b6d96a0fceaf7dc3425153c418a8e25c57803431/examples/utils.py#L113-L140
gautammishra/lyft-rides-python-sdk
examples/utils.py
create_lyft_client
def create_lyft_client(credentials): """Create an LyftRidesClient from OAuth 2.0 credentials. Parameters credentials (dict) Dictionary of OAuth 2.0 credentials. Returns (LyftRidesClient) An authorized LyftRidesClient to access API resources. """ oauth2credential = OAuth2Credential( client_id=credentials.get('client_id'), access_token=credentials.get('access_token'), expires_in_seconds=credentials.get('expires_in_seconds'), scopes=credentials.get('scopes'), grant_type=credentials.get('grant_type'), client_secret=credentials.get('client_secret'), refresh_token=credentials.get('refresh_token'), ) session = Session(oauth2credential=oauth2credential) return LyftRidesClient(session)
python
def create_lyft_client(credentials): """Create an LyftRidesClient from OAuth 2.0 credentials. Parameters credentials (dict) Dictionary of OAuth 2.0 credentials. Returns (LyftRidesClient) An authorized LyftRidesClient to access API resources. """ oauth2credential = OAuth2Credential( client_id=credentials.get('client_id'), access_token=credentials.get('access_token'), expires_in_seconds=credentials.get('expires_in_seconds'), scopes=credentials.get('scopes'), grant_type=credentials.get('grant_type'), client_secret=credentials.get('client_secret'), refresh_token=credentials.get('refresh_token'), ) session = Session(oauth2credential=oauth2credential) return LyftRidesClient(session)
[ "def", "create_lyft_client", "(", "credentials", ")", ":", "oauth2credential", "=", "OAuth2Credential", "(", "client_id", "=", "credentials", ".", "get", "(", "'client_id'", ")", ",", "access_token", "=", "credentials", ".", "get", "(", "'access_token'", ")", ",...
Create an LyftRidesClient from OAuth 2.0 credentials. Parameters credentials (dict) Dictionary of OAuth 2.0 credentials. Returns (LyftRidesClient) An authorized LyftRidesClient to access API resources.
[ "Create", "an", "LyftRidesClient", "from", "OAuth", "2", ".", "0", "credentials", ".", "Parameters", "credentials", "(", "dict", ")", "Dictionary", "of", "OAuth", "2", ".", "0", "credentials", ".", "Returns", "(", "LyftRidesClient", ")", "An", "authorized", ...
train
https://github.com/gautammishra/lyft-rides-python-sdk/blob/b6d96a0fceaf7dc3425153c418a8e25c57803431/examples/utils.py#L143-L162
markfinger/python-js-host
js_host/bin.py
spawn_managed_host
def spawn_managed_host(config_file, manager, connect_on_start=True): """ Spawns a managed host, if it is not already running """ data = manager.request_host_status(config_file) is_running = data['started'] # Managed hosts run as persistent processes, so it may already be running if is_running: host_status = json.loads(data['host']['output']) logfile = data['host']['logfile'] else: data = manager.start_host(config_file) host_status = json.loads(data['output']) logfile = data['logfile'] host = JSHost( status=host_status, logfile=logfile, config_file=config_file, manager=manager ) if not is_running and settings.VERBOSITY >= verbosity.PROCESS_START: print('Started {}'.format(host.get_name())) if connect_on_start: host.connect() return host
python
def spawn_managed_host(config_file, manager, connect_on_start=True): """ Spawns a managed host, if it is not already running """ data = manager.request_host_status(config_file) is_running = data['started'] # Managed hosts run as persistent processes, so it may already be running if is_running: host_status = json.loads(data['host']['output']) logfile = data['host']['logfile'] else: data = manager.start_host(config_file) host_status = json.loads(data['output']) logfile = data['logfile'] host = JSHost( status=host_status, logfile=logfile, config_file=config_file, manager=manager ) if not is_running and settings.VERBOSITY >= verbosity.PROCESS_START: print('Started {}'.format(host.get_name())) if connect_on_start: host.connect() return host
[ "def", "spawn_managed_host", "(", "config_file", ",", "manager", ",", "connect_on_start", "=", "True", ")", ":", "data", "=", "manager", ".", "request_host_status", "(", "config_file", ")", "is_running", "=", "data", "[", "'started'", "]", "# Managed hosts run as ...
Spawns a managed host, if it is not already running
[ "Spawns", "a", "managed", "host", "if", "it", "is", "not", "already", "running" ]
train
https://github.com/markfinger/python-js-host/blob/7727138c1eae779335d55fb4d7734698225a6322/js_host/bin.py#L78-L109
mpetazzoni/tslib
tslib/__init__.py
parse_input
def parse_input(s): """Parse the given input and intelligently transform it into an absolute, non-naive, timezone-aware datetime object for the UTC timezone. The input can be specified as a millisecond-precision UTC timestamp (or delta against Epoch), with or without a terminating 'L'. Alternatively, the input can be specified as a human-readable delta string with unit-separated segments, like '24d6h4m500' (24 days, 6 hours, 4 minutes and 500ms), as long as the segments are in descending unit span order.""" if isinstance(s, six.integer_types): s = str(s) elif not isinstance(s, six.string_types): raise ValueError(s) original = s if s[-1:] == 'L': s = s[:-1] sign = {'-': -1, '=': 0, '+': 1}.get(s[0], None) if sign is not None: s = s[1:] ts = 0 for unit in _SORTED_UNITS: pos = s.find(unit[0]) if pos == 0: raise ValueError(original) elif pos > 0: # If we find a unit letter, we're dealing with an offset. Default # to positive offset if a sign wasn't specified. if sign is None: sign = 1 ts += int(s[:pos]) * __timedelta_millis(unit[1]) s = s[min(len(s), pos + 1):] if s: ts += int(s) return date_from_utc_ts(ts) if not sign else \ utc() + sign * delta(milliseconds=ts)
python
def parse_input(s): """Parse the given input and intelligently transform it into an absolute, non-naive, timezone-aware datetime object for the UTC timezone. The input can be specified as a millisecond-precision UTC timestamp (or delta against Epoch), with or without a terminating 'L'. Alternatively, the input can be specified as a human-readable delta string with unit-separated segments, like '24d6h4m500' (24 days, 6 hours, 4 minutes and 500ms), as long as the segments are in descending unit span order.""" if isinstance(s, six.integer_types): s = str(s) elif not isinstance(s, six.string_types): raise ValueError(s) original = s if s[-1:] == 'L': s = s[:-1] sign = {'-': -1, '=': 0, '+': 1}.get(s[0], None) if sign is not None: s = s[1:] ts = 0 for unit in _SORTED_UNITS: pos = s.find(unit[0]) if pos == 0: raise ValueError(original) elif pos > 0: # If we find a unit letter, we're dealing with an offset. Default # to positive offset if a sign wasn't specified. if sign is None: sign = 1 ts += int(s[:pos]) * __timedelta_millis(unit[1]) s = s[min(len(s), pos + 1):] if s: ts += int(s) return date_from_utc_ts(ts) if not sign else \ utc() + sign * delta(milliseconds=ts)
[ "def", "parse_input", "(", "s", ")", ":", "if", "isinstance", "(", "s", ",", "six", ".", "integer_types", ")", ":", "s", "=", "str", "(", "s", ")", "elif", "not", "isinstance", "(", "s", ",", "six", ".", "string_types", ")", ":", "raise", "ValueErr...
Parse the given input and intelligently transform it into an absolute, non-naive, timezone-aware datetime object for the UTC timezone. The input can be specified as a millisecond-precision UTC timestamp (or delta against Epoch), with or without a terminating 'L'. Alternatively, the input can be specified as a human-readable delta string with unit-separated segments, like '24d6h4m500' (24 days, 6 hours, 4 minutes and 500ms), as long as the segments are in descending unit span order.
[ "Parse", "the", "given", "input", "and", "intelligently", "transform", "it", "into", "an", "absolute", "non", "-", "naive", "timezone", "-", "aware", "datetime", "object", "for", "the", "UTC", "timezone", "." ]
train
https://github.com/mpetazzoni/tslib/blob/b1e15721312c82450f5a3a074d0952fbe85ff849/tslib/__init__.py#L78-L118
mpetazzoni/tslib
tslib/__init__.py
render_delta
def render_delta(d): """Render the given delta (in milliseconds) as a human-readable delta.""" s = '' if d >= 0 else '-' d = abs(d) for unit in _SORTED_UNITS: span = __timedelta_millis(unit[1]) if d >= span: count = int(d // span) s += '{0}{1}'.format(count, unit[0]) d -= count * span if d or not s: s += str(d) return s
python
def render_delta(d): """Render the given delta (in milliseconds) as a human-readable delta.""" s = '' if d >= 0 else '-' d = abs(d) for unit in _SORTED_UNITS: span = __timedelta_millis(unit[1]) if d >= span: count = int(d // span) s += '{0}{1}'.format(count, unit[0]) d -= count * span if d or not s: s += str(d) return s
[ "def", "render_delta", "(", "d", ")", ":", "s", "=", "''", "if", "d", ">=", "0", "else", "'-'", "d", "=", "abs", "(", "d", ")", "for", "unit", "in", "_SORTED_UNITS", ":", "span", "=", "__timedelta_millis", "(", "unit", "[", "1", "]", ")", "if", ...
Render the given delta (in milliseconds) as a human-readable delta.
[ "Render", "the", "given", "delta", "(", "in", "milliseconds", ")", "as", "a", "human", "-", "readable", "delta", "." ]
train
https://github.com/mpetazzoni/tslib/blob/b1e15721312c82450f5a3a074d0952fbe85ff849/tslib/__init__.py#L133-L148
mpetazzoni/tslib
tslib/__init__.py
render_date
def render_date(date, tz=pytz.utc, fmt=_FULL_OUTPUT_FORMAT): """Format the given date for output. The local time render of the given date is done using the given timezone.""" local = date.astimezone(tz) ts = __date_to_millisecond_ts(date) return fmt.format( ts=ts, utc=date.strftime(_DATE_FORMAT), millis=ts % 1000, utc_tz=date.strftime(_TZ_FORMAT), local=local.strftime(_DATE_FORMAT), local_tz=local.strftime(_TZ_FORMAT), delta=render_delta_from_now(date))
python
def render_date(date, tz=pytz.utc, fmt=_FULL_OUTPUT_FORMAT): """Format the given date for output. The local time render of the given date is done using the given timezone.""" local = date.astimezone(tz) ts = __date_to_millisecond_ts(date) return fmt.format( ts=ts, utc=date.strftime(_DATE_FORMAT), millis=ts % 1000, utc_tz=date.strftime(_TZ_FORMAT), local=local.strftime(_DATE_FORMAT), local_tz=local.strftime(_TZ_FORMAT), delta=render_delta_from_now(date))
[ "def", "render_date", "(", "date", ",", "tz", "=", "pytz", ".", "utc", ",", "fmt", "=", "_FULL_OUTPUT_FORMAT", ")", ":", "local", "=", "date", ".", "astimezone", "(", "tz", ")", "ts", "=", "__date_to_millisecond_ts", "(", "date", ")", "return", "fmt", ...
Format the given date for output. The local time render of the given date is done using the given timezone.
[ "Format", "the", "given", "date", "for", "output", ".", "The", "local", "time", "render", "of", "the", "given", "date", "is", "done", "using", "the", "given", "timezone", "." ]
train
https://github.com/mpetazzoni/tslib/blob/b1e15721312c82450f5a3a074d0952fbe85ff849/tslib/__init__.py#L151-L163
chbrown/argv
argv/parsers/descriptive.py
DescriptiveParser.parse
def parse(self, complete=True, args=None): '''Parse a list of arguments, returning a dict See BooleanParser.parse for `args`-related documentation. If `complete` is True and there are values in `args` that don't have corresponding arguments, or there are required arguments that don't have args, then raise an error. ''' opts = dict() positions = [argument.positional for argument in self.arguments if argument.positional] if args is None: import sys # skip over the program name with the [1:] slice args = sys.argv[1:] # arglist is a tuple of (is_flag, name) pairs arglist = peekable(parse_tokens(args)) for is_flag, name in arglist: if is_flag is True: argument = self.find_argument(name) # .peek will return the default argument iff there are no more entries next_is_flag, next_name = arglist.peek(default=(None, None)) # next_is_flag will be None if there are no more items, but True/False if there is a next item # if this argument looks for a subsequent (is set as boolean), and the subsequent is not a flag, consume it if argument.boolean is False and next_is_flag is False: opts[name] = next_name # finally, advance our iterator, but since we already have the next values, just discard it arglist.next() else: # if there is no next, or the next thing is a flag all the boolean=False's in the world can't save you then opts[name] = True else: # add positional argument if len(positions) > 0: # we pop the positions off from the left position = positions.pop(0) opts[position] = name else: # the rest of the args now end up as a list in '_' opts.setdefault('_', []).append(name) # propagate aliases and defaults: for argument in self.arguments: # merge provided value from aliases for name in argument.names: if name in opts: value = opts[name] # we simply break on the first match. break else: # if we iterate through all names and fine none in opts, use the default value = argument.default for name in argument.names: opts[name] = value return opts
python
def parse(self, complete=True, args=None): '''Parse a list of arguments, returning a dict See BooleanParser.parse for `args`-related documentation. If `complete` is True and there are values in `args` that don't have corresponding arguments, or there are required arguments that don't have args, then raise an error. ''' opts = dict() positions = [argument.positional for argument in self.arguments if argument.positional] if args is None: import sys # skip over the program name with the [1:] slice args = sys.argv[1:] # arglist is a tuple of (is_flag, name) pairs arglist = peekable(parse_tokens(args)) for is_flag, name in arglist: if is_flag is True: argument = self.find_argument(name) # .peek will return the default argument iff there are no more entries next_is_flag, next_name = arglist.peek(default=(None, None)) # next_is_flag will be None if there are no more items, but True/False if there is a next item # if this argument looks for a subsequent (is set as boolean), and the subsequent is not a flag, consume it if argument.boolean is False and next_is_flag is False: opts[name] = next_name # finally, advance our iterator, but since we already have the next values, just discard it arglist.next() else: # if there is no next, or the next thing is a flag all the boolean=False's in the world can't save you then opts[name] = True else: # add positional argument if len(positions) > 0: # we pop the positions off from the left position = positions.pop(0) opts[position] = name else: # the rest of the args now end up as a list in '_' opts.setdefault('_', []).append(name) # propagate aliases and defaults: for argument in self.arguments: # merge provided value from aliases for name in argument.names: if name in opts: value = opts[name] # we simply break on the first match. break else: # if we iterate through all names and fine none in opts, use the default value = argument.default for name in argument.names: opts[name] = value return opts
[ "def", "parse", "(", "self", ",", "complete", "=", "True", ",", "args", "=", "None", ")", ":", "opts", "=", "dict", "(", ")", "positions", "=", "[", "argument", ".", "positional", "for", "argument", "in", "self", ".", "arguments", "if", "argument", "...
Parse a list of arguments, returning a dict See BooleanParser.parse for `args`-related documentation. If `complete` is True and there are values in `args` that don't have corresponding arguments, or there are required arguments that don't have args, then raise an error.
[ "Parse", "a", "list", "of", "arguments", "returning", "a", "dict" ]
train
https://github.com/chbrown/argv/blob/5e2b0424a060027c029ad9c16d90bd14a2ff53f8/argv/parsers/descriptive.py#L59-L118
limix/limix-core
limix_core/covar/covar_base.py
Covariance.setRandomParams
def setRandomParams(self): """ set random hyperparameters """ params = sp.randn(self.getNumberParams()) self.setParams(params)
python
def setRandomParams(self): """ set random hyperparameters """ params = sp.randn(self.getNumberParams()) self.setParams(params)
[ "def", "setRandomParams", "(", "self", ")", ":", "params", "=", "sp", ".", "randn", "(", "self", ".", "getNumberParams", "(", ")", ")", "self", ".", "setParams", "(", "params", ")" ]
set random hyperparameters
[ "set", "random", "hyperparameters" ]
train
https://github.com/limix/limix-core/blob/5c590b4d351409f83ca320844b4897ce92203814/limix_core/covar/covar_base.py#L39-L44
limix/limix-core
limix_core/covar/covar_base.py
Covariance.perturbParams
def perturbParams(self, pertSize=1e-3): """ slightly perturbs the values of the parameters """ params = self.getParams() self.setParams(params+pertSize*sp.randn(params.shape[0]))
python
def perturbParams(self, pertSize=1e-3): """ slightly perturbs the values of the parameters """ params = self.getParams() self.setParams(params+pertSize*sp.randn(params.shape[0]))
[ "def", "perturbParams", "(", "self", ",", "pertSize", "=", "1e-3", ")", ":", "params", "=", "self", ".", "getParams", "(", ")", "self", ".", "setParams", "(", "params", "+", "pertSize", "*", "sp", ".", "randn", "(", "params", ".", "shape", "[", "0", ...
slightly perturbs the values of the parameters
[ "slightly", "perturbs", "the", "values", "of", "the", "parameters" ]
train
https://github.com/limix/limix-core/blob/5c590b4d351409f83ca320844b4897ce92203814/limix_core/covar/covar_base.py#L53-L58