signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
def to_affine(self):
X, Y, Z = self.x, self.y, self.inverse(self.z)<EOL>return ((X * Z ** <NUM_LIT:2>) % P, (Y * Z ** <NUM_LIT:3>) % P)<EOL>
Converts this point to an affine representation. Returns: AffinePoint: The affine reprsentation.
f11841:c2:m6
def __mul__(self, other):
r0 = AffinePoint(<NUM_LIT:0>, <NUM_LIT:0>, True)<EOL>r = [r0, self]<EOL>for i in reversed(range(other.bit_length())):<EOL><INDENT>di = (other >> i) & <NUM_LIT><EOL>r[(di + <NUM_LIT:1>) % <NUM_LIT:2>] = r[<NUM_LIT:0>] + r[<NUM_LIT:1>]<EOL>r[di] = r[di].double()<EOL><DEDENT>return r[<NUM_LIT:0>]<EOL>
Implements the scalar multiplication via the Montgomery ladder tech- nique.
f11841:c3:m4
def double(self):
X1, Y1, a, P = self.X, self.Y, self.a, self.P<EOL>if self.infinity:<EOL><INDENT>return self<EOL><DEDENT>S = ((<NUM_LIT:3> * X1 ** <NUM_LIT:2> + a) * self.inverse(<NUM_LIT:2> * Y1)) % P<EOL>X2 = (S ** <NUM_LIT:2> - (<NUM_LIT:2> * X1)) % P<EOL>Y2 = (S * (X1 - X2) - Y1) % P<EOL>return AffinePoint(X2, Y2)<EOL>
Doubles this point. Returns: AffinePoint: The point corresponding to `2 * self`.
f11841:c3:m8
def slope(self, other):
X1, Y1, X2, Y2 = self.X, self.Y, other.X, other.Y<EOL>Y3 = Y1 - Y2<EOL>X3 = X1 - X2<EOL>return (Y3 * self.inverse(X3)) % self.P<EOL>
Determines the slope between this point and another point. Args: other (AffinePoint): The second point. Returns: int: Slope between self and other.
f11841:c3:m9
def to_jacobian(self):
if not self:<EOL><INDENT>return JacobianPoint(X=<NUM_LIT:0>, Y=<NUM_LIT:0>, Z=<NUM_LIT:0>)<EOL><DEDENT>return JacobianPoint(X=self.X, Y=self.Y, Z=<NUM_LIT:1>)<EOL>
Converts this point to a Jacobian representation. Returns: JacobianPoint: The Jacobian representation.
f11841:c3:m10
@classmethod<EOL><INDENT>def make_controller(cls, config, session, left_menu_items=None):<DEDENT>
m = config.model<EOL>Controller = config.defaultCrudRestController<EOL>class ModelController(Controller):<EOL><INDENT>model = m<EOL>table = config.table_type(session)<EOL>table_filler = config.table_filler_type(session)<EOL>new_form = config.new_form_type(session)<EOL>new_filler = config.new_filler_...
New CRUD controllers using the admin configuration can be created using this.
f11846:c0:m4
@classmethod<EOL><INDENT>def by_email_address(cls, email):<DEDENT>
return DBSession.query(cls).filter(cls.email_address==email).first()<EOL>
A class method that can be used to search users based on their email addresses since it is unique.
f11854:c2:m2
@classmethod<EOL><INDENT>def by_user_name(cls, username):<DEDENT>
return DBSession.query(cls).filter(cls.user_name==username).first()<EOL>
A class method that permits to search users based on their user_name attribute.
f11854:c2:m3
def _set_password(self, password):
<EOL>
encrypts password on the fly using the encryption algo defined in the configuration
f11854:c2:m4
def _get_password(self):
return self._password<EOL>
returns password
f11854:c2:m5
def _encrypt_password(self, algorithm, password):
hashed_password = password<EOL>if isinstance(password, unicode):<EOL><INDENT>password_8bit = password.encode('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>password_8bit = password<EOL><DEDENT>salt = sha1()<EOL>salt.update(os.urandom(<NUM_LIT>))<EOL>hash = sha1()<EOL>hash.update(password_8bit + salt.hexdigest())<EOL>hashed...
Hash the given password with the specified algorithm. Valid values for algorithm are 'md5' and 'sha1'. All other algorithm values will be essentially a no-op.
f11854:c2:m6
def validate_password(self, password):
hashed_pass = sha1()<EOL>hashed_pass.update(password + self.password[:<NUM_LIT>])<EOL>return self.password[<NUM_LIT>:] == hashed_pass.hexdigest()<EOL>
Check the password against existing credentials. this method _MUST_ return a boolean. @param password: the password that was provided by the user to try and authenticate. This is the clear text version that we will need to match against the (possibly) encrypted one in the database. ...
f11854:c2:m7
def make_app(controller_klass=None, environ=None):
if environ is None:<EOL><INDENT>environ = {}<EOL><DEDENT>environ['<STR_LIT>'] = {}<EOL>environ['<STR_LIT>']['<STR_LIT:action>'] = "<STR_LIT>"<EOL>if controller_klass is None:<EOL><INDENT>controller_klass = TGController<EOL><DEDENT>app = ControllerWrap(controller_klass)<EOL>app = SetupCacheGlobal(app, environ, setup_cac...
Creates a `TestApp` instance.
f11856:m2
def cmdscale_fast(D, ndim):
tasklogger.log_debug("<STR_LIT>".format(<EOL>type(D).__name__, D.shape))<EOL>D = D**<NUM_LIT:2><EOL>D = D - D.mean(axis=<NUM_LIT:0>)[None, :]<EOL>D = D - D.mean(axis=<NUM_LIT:1>)[:, None]<EOL>pca = PCA(n_components=ndim, svd_solver='<STR_LIT>')<EOL>Y = pca.fit_transform(D)<EOL>return Y<EOL>
Fast CMDS using random SVD Parameters ---------- D : array-like, input data [n_samples, n_dimensions] ndim : int, number of dimensions in which to embed `D` Returns ------- Y : array-like, embedded data [n_sample, ndim]
f11864:m0
def embed_MDS(X, ndim=<NUM_LIT:2>, how='<STR_LIT>', distance_metric='<STR_LIT>',<EOL>n_jobs=<NUM_LIT:1>, seed=None, verbose=<NUM_LIT:0>):
if how not in ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>".format(how))<EOL><DEDENT>X_dist = squareform(pdist(X, distance_metric))<EOL>Y = cmdscale_fast(X_dist, ndim)<EOL>if how in ['<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>tasklogger.log_debug("<STR_LIT...
Performs classic, metric, and non-metric MDS Metric MDS is initialized using classic MDS, non-metric MDS is initialized using metric MDS. Parameters ---------- X: ndarray [n_samples, n_samples] 2 dimensional input data array with n_samples embed_MDS does not check for matrix square...
f11864:m1
def _get_plot_data(data, ndim=None):
out = data<EOL>if isinstance(data, PHATE):<EOL><INDENT>out = data.transform()<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>if isinstance(data, anndata.AnnData):<EOL><INDENT>try:<EOL><INDENT>out = data.obsm['<STR_LIT>']<EOL><DEDENT>except KeyError:<EOL><INDENT>raise RuntimeError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL><...
Get plot data out of an input object Parameters ---------- data : array-like, `phate.PHATE` or `scanpy.AnnData` ndim : int, optional (default: None) Minimum number of dimensions
f11866:m0
def scatter(x, y, z=None,<EOL>c=None, cmap=None, s=None, discrete=None,<EOL>ax=None, legend=None, figsize=None,<EOL>xticks=False,<EOL>yticks=False,<EOL>zticks=False,<EOL>xticklabels=True,<EOL>yticklabels=True,<EOL>zticklabels=True,<EOL>label_prefix="<STR_LIT>",<EOL>xlabel=None,<EOL>ylabel=None,<EOL>zlabel=None,<EOL>tit...
warnings.warn("<STR_LIT>"<EOL>"<STR_LIT>",<EOL>FutureWarning)<EOL>return scprep.plot.scatter(x=x, y=y, z=z,<EOL>c=c, cmap=cmap, s=s, discrete=discrete,<EOL>ax=ax, legend=legend, figsize=figsize,<EOL>xticks=xticks,<EOL>yticks=yticks,<EOL>zticks=zticks,<EOL>xticklabels=xticklabels,<EOL>yticklabels=yticklabels,<EOL>ztickl...
Create a scatter plot Builds upon `matplotlib.pyplot.scatter` with nice defaults and handles categorical colors / legends better. For easy access, use `scatter2d` or `scatter3d`. Parameters ---------- x : list-like data for x axis y : list-like data for y axis z : list-...
f11866:m1
def scatter2d(data, **kwargs):
warnings.warn("<STR_LIT>"<EOL>"<STR_LIT>",<EOL>FutureWarning)<EOL>data = _get_plot_data(data, ndim=<NUM_LIT:2>)<EOL>return scprep.plot.scatter2d(data, **kwargs)<EOL>
Create a 2D scatter plot Builds upon `matplotlib.pyplot.scatter` with nice defaults and handles categorical colors / legends better. Parameters ---------- data : array-like, shape=[n_samples, n_features] Input data. Only the first two components will be used. c : list-like or None, opt...
f11866:m2
def scatter3d(data, **kwargs):
warnings.warn("<STR_LIT>"<EOL>"<STR_LIT>",<EOL>FutureWarning)<EOL>data = _get_plot_data(data, ndim=<NUM_LIT:3>)<EOL>return scprep.plot.scatter3d(data, **kwargs)<EOL>
Create a 3D scatter plot Builds upon `matplotlib.pyplot.scatter` with nice defaults and handles categorical colors / legends better. Parameters ---------- data : array-like, shape=[n_samples, n_features] to be the value of the figure. Only used if filename is not None. Input data. ...
f11866:m3
def rotate_scatter3d(data,<EOL>filename=None,<EOL>elev=<NUM_LIT:30>,<EOL>rotation_speed=<NUM_LIT:30>,<EOL>fps=<NUM_LIT:10>,<EOL>ax=None,<EOL>figsize=None,<EOL>dpi=None,<EOL>ipython_html="<STR_LIT>",<EOL>**kwargs):
warnings.warn("<STR_LIT>"<EOL>"<STR_LIT>",<EOL>FutureWarning)<EOL>return scprep.plot.rotate_scatter3d(data,<EOL>filename=filename,<EOL>elev=elev,<EOL>rotation_speed=rotation_speed,<EOL>fps=fps,<EOL>ax=ax,<EOL>figsize=figsize,<EOL>dpi=dpi,<EOL>ipython_html=ipython_html,<EOL>**kwargs)<EOL>
Create a rotating 3D scatter plot Builds upon `matplotlib.pyplot.scatter` with nice defaults and handles categorical colors / legends better. Parameters ---------- data : array-like, `phate.PHATE` or `scanpy.AnnData` Input data. Only the first three dimensions are used. filename : str,...
f11866:m4
def compute_von_neumann_entropy(data, t_max=<NUM_LIT:100>):
_, eigenvalues, _ = svd(data)<EOL>entropy = []<EOL>eigenvalues_t = np.copy(eigenvalues)<EOL>for _ in range(t_max):<EOL><INDENT>prob = eigenvalues_t / np.sum(eigenvalues_t)<EOL>prob = prob + np.finfo(float).eps<EOL>entropy.append(-np.sum(prob * np.log(prob)))<EOL>eigenvalues_t = eigenvalues_t * eigenvalues<EOL><DEDENT>e...
Determines the Von Neumann entropy of data at varying matrix powers. The user should select a value of t around the "knee" of the entropy curve. Parameters ---------- t_max : int, default: 100 Maximum value of t to test Returns ------- entropy : array, shape=[t_max] The entropy of the diffusion affinities for...
f11867:m0
def find_knee_point(y, x=None):
try:<EOL><INDENT>y.shape<EOL><DEDENT>except AttributeError:<EOL><INDENT>y = np.array(y)<EOL><DEDENT>if len(y) < <NUM_LIT:3>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>elif len(y.shape) > <NUM_LIT:1>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if x is None:<EOL><INDENT>x = np.arange(len(y))<EOL><D...
Returns the x-location of a (single) knee of curve y=f(x) Parameters ---------- y : array, shape=[n] data for which to find the knee point x : array, optional, shape=[n], default=np.arange(len(y)) indices of the data points of y, if these are not in order and evenly spaced Returns ------- knee_point : i...
f11867:m1
def check_positive(**params):
for p in params:<EOL><INDENT>if not isinstance(params[p], numbers.Number) or params[p] <= <NUM_LIT:0>:<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>".format(p, params[p]))<EOL><DEDENT><DEDENT>
Check that parameters are positive as expected Raises ------ ValueError : unacceptable choice of parameters
f11869:m0
def check_int(**params):
for p in params:<EOL><INDENT>if not isinstance(params[p], numbers.Integral):<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>".format(p, params[p]))<EOL><DEDENT><DEDENT>
Check that parameters are integers as expected Raises ------ ValueError : unacceptable choice of parameters
f11869:m1
def check_if_not(x, *checks, **params):
for p in params:<EOL><INDENT>if params[p] is not x and params[p] != x:<EOL><INDENT>[check(**{p: params[p]}) for check in checks]<EOL><DEDENT><DEDENT>
Run checks only if parameters are not equal to a specified value Parameters ---------- x : excepted value Checks not run if parameters equal x checks : function Unnamed arguments, check functions to be run params : object Named arguments, parameters to be checked Rai...
f11869:m2
def check_in(choices, **params):
for p in params:<EOL><INDENT>if params[p] not in choices:<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>".format(<EOL>p, params[p], choices))<EOL><DEDENT><DEDENT>
Checks parameters are in a list of allowed parameters Parameters ---------- choices : array-like, accepted values params : object Named arguments, parameters to be checked Raises ------ ValueError : unacceptable choice of parameters
f11869:m3
def check_between(v_min, v_max, **params):
for p in params:<EOL><INDENT>if params[p] < v_min or params[p] > v_max:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>".format(p, v_min, v_max, params[p]))<EOL><DEDENT><DEDENT>
Checks parameters are in a specified range Parameters ---------- v_min : float, minimum allowed value (inclusive) v_max : float, maximum allowed value (inclusive) params : object Named arguments, parameters to be checked Raises ------ ValueError : unacceptable choice of para...
f11869:m4
def matrix_is_equivalent(X, Y):
return X is Y or (isinstance(X, Y.__class__) and X.shape == Y.shape and<EOL>np.sum((X != Y).sum()) == <NUM_LIT:0>)<EOL>
Checks matrix equivalence with numpy, scipy and pandas
f11869:m5
def in_ipynb():
__VALID_NOTEBOOKS = ["<STR_LIT>",<EOL>"<STR_LIT>"]<EOL>try:<EOL><INDENT>return str(type(get_ipython())) in __VALID_NOTEBOOKS<EOL><DEDENT>except NameError:<EOL><INDENT>return False<EOL><DEDENT>
Check if we are running in a Jupyter Notebook Credit to https://stackoverflow.com/a/24937408/3996580
f11869:m6
@property<EOL><INDENT>def diff_op(self):<DEDENT>
if self.graph is not None:<EOL><INDENT>if isinstance(self.graph, graphtools.graphs.LandmarkGraph):<EOL><INDENT>diff_op = self.graph.landmark_op<EOL><DEDENT>else:<EOL><INDENT>diff_op = self.graph.diff_op<EOL><DEDENT>if sparse.issparse(diff_op):<EOL><INDENT>diff_op = diff_op.toarray()<EOL><DEDENT>return diff_op<EOL><DEDE...
The diffusion operator calculated from the data
f11870:c0:m1
def _check_params(self):
utils.check_positive(n_components=self.n_components,<EOL>k=self.knn)<EOL>utils.check_int(n_components=self.n_components,<EOL>k=self.knn,<EOL>n_jobs=self.n_jobs)<EOL>utils.check_between(<NUM_LIT:0>, <NUM_LIT:1>, gamma=self.gamma)<EOL>utils.check_if_not(None, utils.check_positive, a=self.decay)<EOL>utils.check_if_not(Non...
Check PHATE parameters This allows us to fail early - otherwise certain unacceptable parameter choices, such as mds='mmds', would only fail after minutes of runtime. Raises ------ ValueError : unacceptable choice of parameters
f11870:c0:m2
def set_params(self, **params):
reset_kernel = False<EOL>reset_potential = False<EOL>reset_embedding = False<EOL>if '<STR_LIT>' in params andparams['<STR_LIT>'] != self.n_components:<EOL><INDENT>self.n_components = params['<STR_LIT>']<EOL>reset_embedding = True<EOL>del params['<STR_LIT>']<EOL><DEDENT>if '<STR_LIT>' in params and params['<STR_LIT>'] !...
Set the parameters on this estimator. Any parameters not given as named arguments will be left at their current value. Parameters ---------- n_components : int, optional, default: 2 number of dimensions in which the data will be embedded knn : int, optiona...
f11870:c0:m7
def reset_mds(self, **kwargs):
warnings.warn("<STR_LIT>"<EOL>"<STR_LIT>",<EOL>FutureWarning)<EOL>self.set_params(**kwargs)<EOL>
Deprecated. Reset parameters related to multidimensional scaling Parameters ---------- n_components : int, optional, default: None If given, sets number of dimensions in which the data will be embedded mds : string, optional, default: None choose from ['classic', 'metric', 'nonmetric'] If given, sets ...
f11870:c0:m8
def reset_potential(self, **kwargs):
warnings.warn("<STR_LIT>"<EOL>"<STR_LIT>",<EOL>FutureWarning)<EOL>self.set_params(**kwargs)<EOL>
Deprecated. Reset parameters related to the diffusion potential Parameters ---------- t : int or 'auto', optional, default: None Power to which the diffusion operator is powered If given, sets the level of diffusion potential_method : string, optional, default: None choose from ['log', 'sqrt'] If give...
f11870:c0:m9
def fit(self, X):
X, n_pca, precomputed, update_graph = self._parse_input(X)<EOL>if precomputed is None:<EOL><INDENT>tasklogger.log_info(<EOL>"<STR_LIT>".format(<EOL>X.shape[<NUM_LIT:0>], X.shape[<NUM_LIT:1>]))<EOL><DEDENT>else:<EOL><INDENT>tasklogger.log_info(<EOL>"<STR_LIT>".format(<EOL>precomputed, X.shape[<NUM_LIT:0>]))<EOL><DEDENT>...
Computes the diffusion operator Parameters ---------- X : array, shape=[n_samples, n_features] input data with `n_samples` samples and `n_dimensions` dimensions. Accepted data types: `numpy.ndarray`, `scipy.sparse.spmatrix`, `pd.DataFrame`, `anndata.AnnData`....
f11870:c0:m12
def transform(self, X=None, t_max=<NUM_LIT:100>, plot_optimal_t=False, ax=None):
if self.graph is None:<EOL><INDENT>raise NotFittedError("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>elif X is not None and not utils.matrix_is_equivalent(X, self.X):<EOL><INDENT>warnings.warn("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>",<EOL>RuntimeWarning)<EOL>if isinstance(self.graph, graphtools.graphs.Tr...
Computes the position of the cells in the embedding space Parameters ---------- X : array, optional, shape=[n_samples, n_features] input data with `n_samples` samples and `n_dimensions` dimensions. Not required, since PHATE does not currently embed cells not ...
f11870:c0:m13
def fit_transform(self, X, **kwargs):
tasklogger.log_start('<STR_LIT>')<EOL>self.fit(X)<EOL>embedding = self.transform(**kwargs)<EOL>tasklogger.log_complete('<STR_LIT>')<EOL>return embedding<EOL>
Computes the diffusion operator and the position of the cells in the embedding space Parameters ---------- X : array, shape=[n_samples, n_features] input data with `n_samples` samples and `n_dimensions` dimensions. Accepted data types: `numpy.ndarray`, ...
f11870:c0:m14
def calculate_potential(self, t=None,<EOL>t_max=<NUM_LIT:100>, plot_optimal_t=False, ax=None):
if t is None:<EOL><INDENT>t = self.t<EOL><DEDENT>if self.diff_potential is None:<EOL><INDENT>if t == '<STR_LIT>':<EOL><INDENT>t = self.optimal_t(t_max=t_max, plot=plot_optimal_t, ax=ax)<EOL><DEDENT>else:<EOL><INDENT>t = self.t<EOL><DEDENT>tasklogger.log_start("<STR_LIT>")<EOL>diff_op_t = np.linalg.matrix_power(self.dif...
Calculates the diffusion potential Parameters ---------- t : int power to which the diffusion operator is powered sets the level of diffusion t_max : int, default: 100 Maximum value of `t` to test plot_optimal_t : boolean, default: False ...
f11870:c0:m15
def von_neumann_entropy(self, t_max=<NUM_LIT:100>):
t = np.arange(t_max)<EOL>return t, vne.compute_von_neumann_entropy(self.diff_op, t_max=t_max)<EOL>
Calculate Von Neumann Entropy Determines the Von Neumann entropy of the diffusion affinities at varying levels of `t`. The user should select a value of `t` around the "knee" of the entropy curve. We require that 'fit' stores the value of `PHATE.diff_op` in order to calculate t...
f11870:c0:m16
def optimal_t(self, t_max=<NUM_LIT:100>, plot=False, ax=None):
tasklogger.log_start("<STR_LIT>")<EOL>t, h = self.von_neumann_entropy(t_max=t_max)<EOL>t_opt = vne.find_knee_point(y=h, x=t)<EOL>tasklogger.log_info("<STR_LIT>".format(t_opt))<EOL>tasklogger.log_complete("<STR_LIT>")<EOL>if plot:<EOL><INDENT>if ax is None:<EOL><INDENT>fig, ax = plt.subplots()<EOL>show = True<EOL><DEDEN...
Find the optimal value of t Selects the optimal value of t based on the knee point of the Von Neumann Entropy of the diffusion operator. Parameters ---------- t_max : int, default: 100 Maximum value of t to test plot : boolean, default: False If...
f11870:c0:m17
def kmeans(phate_op, k=<NUM_LIT:8>, random_state=None):
if phate_op.graph is not None:<EOL><INDENT>diff_potential = phate_op.calculate_potential()<EOL>if isinstance(phate_op.graph, graphtools.graphs.LandmarkGraph):<EOL><INDENT>diff_potential = phate_op.graph.interpolate(diff_potential)<EOL><DEDENT>return cluster.KMeans(k, random_state=random_state).fit_predict(diff_potentia...
KMeans on the PHATE potential Clustering on the PHATE operator as introduced in Moon et al. This is similar to spectral clustering. Parameters ---------- phate_op : phate.PHATE Fitted PHATE operator k : int, optional (default: 8) Number of clusters random_state : int or No...
f11872:m0
@staticmethod<EOL><INDENT>def get_constraints(model):<DEDENT>
with connection.cursor() as cursor:<EOL><INDENT>return connection.introspection.get_constraints(cursor, model._meta.db_table)<EOL><DEDENT>
Get the indexes on the table using a new cursor.
f11883:c1:m1
def validate_partial_unique(self):
<EOL>unique_idxs = [idx for idx in self._meta.indexes if isinstance(idx, PartialIndex) and idx.unique]<EOL>if unique_idxs:<EOL><INDENT>model_fields = set(f.name for f in self._meta.get_fields(include_parents=True, include_hidden=True))<EOL>for idx in unique_idxs:<EOL><INDENT>where = idx.where<EOL>if not isinstance(wher...
Check partial unique constraints on the model and raise ValidationError if any failed. We want to check if another instance already exists with the fields mentioned in idx.fields, but only if idx.where matches. But can't just check for the fields in idx.fields - idx.where may refer to other fields on t...
f11891:c1:m1
def set_name_with_model(self, model):
table_name = model._meta.db_table<EOL>column_names = [model._meta.get_field(field_name).column for field_name, order in self.fields_orders]<EOL>column_names_with_order = [<EOL>(('<STR_LIT>' if order else '<STR_LIT:%s>') % column_name)<EOL>for column_name, (field_name, order) in zip(column_names, self.fields_orders)<EOL...
Sets an unique generated name for the index. PartialIndex would like to only override "hash_data = ...", but the entire method must be duplicated for that.
f11892:c0:m6
def q_mentioned_fields(q, model):
query = Query(model)<EOL>where = query._add_q(q, used_aliases=set(), allow_joins=False)[<NUM_LIT:0>]<EOL>return list(sorted(set(expression_mentioned_fields(where))))<EOL>
Returns list of field names mentioned in Q object. Q(a__isnull=True, b=F('c')) -> ['a', 'b', 'c']
f11893:m3
def __eq__(self, other):
if self.__class__ != other.__class__:<EOL><INDENT>return False<EOL><DEDENT>if (self.connector, self.negated) == (other.connector, other.negated):<EOL><INDENT>return self.children == other.children<EOL><DEDENT>return False<EOL>
Copied from Django 2.0 django.utils.tree.Node.__eq__()
f11893:c1:m0
def deconstruct(self):
path = '<STR_LIT>' % (self.__class__.__module__, self.__class__.__name__)<EOL>if path.startswith('<STR_LIT>'):<EOL><INDENT>path = path.replace('<STR_LIT>', '<STR_LIT>')<EOL><DEDENT>args, kwargs = (), {}<EOL>if len(self.children) == <NUM_LIT:1> and not isinstance(self.children[<NUM_LIT:0>], Q):<EOL><INDENT>child = self....
Copied from Django 2.0 django.db.models.query_utils.Q.deconstruct()
f11893:c1:m1
def func_():
function
f11896:m4
@classmethod<EOL><INDENT>def classmethod_(cls):<DEDENT>
function decorated by @classmethod
f11896:c0:m0
@decorator_<EOL><INDENT>def decorated_method_(self):<DEDENT>
decorated method
f11896:c0:m1
def method_(self):
method
f11896:c0:m2
@property<EOL><INDENT>def property_(self):<DEDENT>
property
f11896:c0:m3
def fullqualname_py3(obj):
if type(obj).__name__ == '<STR_LIT>':<EOL><INDENT>return _fullqualname_builtin_py3(obj)<EOL><DEDENT>elif type(obj).__name__ == '<STR_LIT>':<EOL><INDENT>return _fullqualname_function_py3(obj)<EOL><DEDENT>elif type(obj).__name__ in ['<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>']:<EOL><INDENT>return obj.__objclass__.__module_...
Fully qualified name for objects in Python 3.
f11897:m0
def _fullqualname_builtin_py3(obj):
if obj.__module__ is not None:<EOL><INDENT>module = obj.__module__<EOL><DEDENT>else:<EOL><INDENT>if inspect.isclass(obj.__self__):<EOL><INDENT>module = obj.__self__.__module__<EOL><DEDENT>else:<EOL><INDENT>module = obj.__self__.__class__.__module__<EOL><DEDENT><DEDENT>return module + '<STR_LIT:.>' + obj.__qualname__<EO...
Fully qualified name for 'builtin_function_or_method' objects in Python 3.
f11897:m1
def _fullqualname_function_py3(obj):
if hasattr(obj, "<STR_LIT>"):<EOL><INDENT>qualname = obj.__wrapped__.__qualname__<EOL><DEDENT>else:<EOL><INDENT>qualname = obj.__qualname__<EOL><DEDENT>return obj.__module__ + '<STR_LIT:.>' + qualname<EOL>
Fully qualified name for 'function' objects in Python 3.
f11897:m2
def _fullqualname_method_py3(obj):
if inspect.isclass(obj.__self__):<EOL><INDENT>cls = obj.__self__.__qualname__<EOL><DEDENT>else:<EOL><INDENT>cls = obj.__self__.__class__.__qualname__<EOL><DEDENT>return obj.__self__.__module__ + '<STR_LIT:.>' + cls + '<STR_LIT:.>' + obj.__name__<EOL>
Fully qualified name for 'method' objects in Python 3.
f11897:m3
def fullqualname_py2(obj):
if type(obj).__name__ == '<STR_LIT>':<EOL><INDENT>return _fullqualname_builtin_py2(obj)<EOL><DEDENT>elif type(obj).__name__ == '<STR_LIT>':<EOL><INDENT>return obj.__module__ + '<STR_LIT:.>' + obj.__name__<EOL><DEDENT>elif type(obj).__name__ in ['<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>']:<EOL><INDENT>return (obj.__objcl...
Fully qualified name for objects in Python 2.
f11897:m4
def _fullqualname_builtin_py2(obj):
if obj.__self__ is None:<EOL><INDENT>module = obj.__module__<EOL>qualname = obj.__name__<EOL><DEDENT>else:<EOL><INDENT>if inspect.isclass(obj.__self__):<EOL><INDENT>cls = obj.__self__<EOL><DEDENT>else:<EOL><INDENT>cls = obj.__self__.__class__<EOL><DEDENT>module = cls.__module__<EOL>qualname = cls.__name__ + '<STR_LIT:....
Fully qualified name for 'builtin_function_or_method' objects in Python 2.
f11897:m5
def _fullqualname_method_py2(obj):
if obj.__self__ is None:<EOL><INDENT>module = obj.im_class.__module__<EOL>cls = obj.im_class.__name__<EOL><DEDENT>else:<EOL><INDENT>if inspect.isclass(obj.__self__):<EOL><INDENT>module = obj.__self__.__module__<EOL>cls = obj.__self__.__name__<EOL><DEDENT>else:<EOL><INDENT>module = obj.__self__.__class__.__module__<EOL>...
Fully qualified name for 'instancemethod' objects in Python 2.
f11897:m6
def create_switch(type, settings, pin):
switch = None<EOL>if type == "<STR_LIT:A>":<EOL><INDENT>group, device = settings.split("<STR_LIT:U+002C>")<EOL>switch = pi_switch.RCSwitchA(group, device)<EOL><DEDENT>elif type == "<STR_LIT:B>":<EOL><INDENT>addr, channel = settings.split("<STR_LIT:U+002C>")<EOL>addr = int(addr)<EOL>channel = int(channel)<EOL>switch = p...
Create a switch. Args: type: (str): type of the switch [A,B,C,D] settings (str): a comma separted list pin (int): wiringPi pin Returns: switch
f11904:m0
def toggle(switch, command):
if command in ["<STR_LIT>"]:<EOL><INDENT>switch.switchOn()<EOL><DEDENT>if command in ["<STR_LIT>"]:<EOL><INDENT>switch.switchOff()<EOL><DEDENT>
Toggles a switch on or off. Args: switch (switch): a switch command (str): "on" or "off"
f11904:m1
def normalizeCountry(country_str, target="<STR_LIT>", title_case=False):
iso2 = "<STR_LIT>"<EOL>iso3 = "<STR_LIT>"<EOL>raw = "<STR_LIT>"<EOL>if country_str is None:<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>if len(country_str) == <NUM_LIT:2>:<EOL><INDENT>cc = countrycode(country_str.upper(), origin=iso2, target=target)<EOL>if not cc:<EOL><INDENT>cc = countrycode(country_str, origin=raw, ta...
Return a normalized name/code for country in ``country_str``. The input can be a code or name, the ``target`` determines output value. 3 character ISO code is the default (iso3c), 'country_name', and 'iso2c' are common also. See ``countrycode.countrycode`` for details and other options. Raises ``ValueEr...
f11914:m2
def mostCommonItem(lst):
<EOL>lst = [l for l in lst if l]<EOL>if lst:<EOL><INDENT>return max(set(lst), key=lst.count)<EOL><DEDENT>else:<EOL><INDENT>return None<EOL><DEDENT>
Choose the most common item from the list, or the first item if all items are unique.
f11914:m4
def safeDbUrl(db_url):
url = urlparse(db_url)<EOL>return db_url.replace(url.password, "<STR_LIT>") if url.password else db_url<EOL>
Obfuscates password from a database URL.
f11914:m5
def __init__(self, arg_parser):
super().__init__(arg_parser, cache_files=True, track_images=True)<EOL>eyed3.main.setFileScannerOpts(<EOL>arg_parser, paths_metavar="<STR_LIT>",<EOL>paths_help="<STR_LIT>"<EOL>"<STR_LIT>")<EOL>arg_parser.add_argument(<EOL>"<STR_LIT>", action="<STR_LIT:store_true>", dest="<STR_LIT>",<EOL>help="<STR_LIT>")<EOL>arg_parser....
Constructor
f11919:c0:m0
def syncImage(img, current, session):
def _img_str(i):<EOL><INDENT>return "<STR_LIT>" % (i.type, i.description)<EOL><DEDENT>for db_img in current.images:<EOL><INDENT>img_info = (img.type, img.md5, img.size)<EOL>db_img_info = (db_img.type, db_img.md5, db_img.size)<EOL>if db_img_info == img_info:<EOL><INDENT>img = None<EOL>break<EOL><DEDENT>elif (db_img.type...
Add or updated the Image.
f11922:m1
def _run(self):
all_procs = []<EOL>MishMashProc("<STR_LIT:info>", config=self.args.config).start().join(check=True)<EOL>sync = MishMashProc("<STR_LIT>", "<STR_LIT>", "<STR_LIT>", config=self.args.config)if self.args.config.getboolean("<STR_LIT>", "<STR_LIT>", fallback=True) else None<EOL>web = MishMashProc("<STR_LIT>", config=self.arg...
main
f11923:c2:m0
def run_migrations_offline():
url = config.get_main_option("<STR_LIT>")<EOL>context.configure(<EOL>url=url, target_metadata=target_metadata, literal_binds=True)<EOL>with context.begin_transaction():<EOL><INDENT>context.run_migrations()<EOL><DEDENT>
Run migrations in 'offline' mode. This configures the context with just a URL and not an Engine, though an Engine is acceptable here as well. By skipping the Engine creation we don't even need a DBAPI to be available. Calls to context.execute() here emit the given string to the script output.
f11928:m0
def run_migrations_online():
connectable = engine_from_config(<EOL>config.get_section(config.config_ini_section),<EOL>prefix='<STR_LIT>',<EOL>poolclass=pool.NullPool)<EOL>with connectable.connect() as connection:<EOL><INDENT>context.configure(<EOL>connection=connection,<EOL>target_metadata=target_metadata,<EOL>render_as_batch=True, <EOL>)<EOL>wi...
Run migrations in 'online' mode. In this scenario we need to create an Engine and associate a connection with the context.
f11928:m1
def search(session, query):
flat_query = "<STR_LIT>".join(query.split())<EOL>artists = session.query(Artist).filter(<EOL>or_(Artist.name.ilike(f"<STR_LIT>"),<EOL>Artist.name.ilike(f"<STR_LIT>"))<EOL>).all()<EOL>albums = session.query(Album).filter(<EOL>Album.title.ilike(f"<STR_LIT>")).all()<EOL>tracks = session.query(Track).filter(<EOL>Track.titl...
Naive search of the database for `query`. :return: A dict with keys 'artists', 'albums', and 'tracks'. Each containing a list of the respective ORM type.
f11931:m3
@event.listens_for(Engine, "<STR_LIT>")<EOL>def set_sqlite_pragma(dbapi_connection, connection_record):
import sqlite3<EOL>if dbapi_connection.__class__ is sqlite3.Connection:<EOL><INDENT>cursor = dbapi_connection.cursor()<EOL>cursor.execute("<STR_LIT>")<EOL>cursor.close()<EOL><DEDENT>
Allows foreign keys to work in sqlite.
f11937:m1
def __repr__(self):
attrs = []<EOL>for key in self.__dict__:<EOL><INDENT>if not key.startswith('<STR_LIT:_>'):<EOL><INDENT>attrs.append((key, getattr(self, key)))<EOL><DEDENT><DEDENT>return self.__class__.__name__ + '<STR_LIT:(>' +'<STR_LIT:U+002CU+0020>'.join(x[<NUM_LIT:0>] + '<STR_LIT:=>' + repr(x[<NUM_LIT:1>]) for x in attrs) + '<STR_L...
Dump the object state and return it as a strings.
f11937:c0:m1
def __init__(self, **kwargs):
if "<STR_LIT>" in kwargs:<EOL><INDENT>self.update(kwargs["<STR_LIT>"])<EOL>del kwargs["<STR_LIT>"]<EOL><DEDENT>super(Track, self).__init__(**kwargs)<EOL>
Along with the column args a ``audio_file`` keyword may be passed for this class to use for initialization.
f11937:c5:m0
@classmethod<EOL><INDENT>def iterall(Class, session, names=None):<DEDENT>
names = set(names if names else [])<EOL>for lib in session.query(Class).filter(Class.id > NULL_LIB_ID).all():<EOL><INDENT>if not names or (lib.name in names):<EOL><INDENT>yield lib<EOL><DEDENT><DEDENT>
Iterate over all Library rows found in `session`. :param names: Optional sequence of names to filter on.
f11937:c8:m2
@contextlib.contextmanager<EOL>def capture_logger(name):
import logging<EOL>logger = logging.getLogger(name)<EOL>try:<EOL><INDENT>import StringIO<EOL>stream = StringIO.StringIO()<EOL><DEDENT>except ImportError:<EOL><INDENT>from io import StringIO<EOL>stream = StringIO()<EOL><DEDENT>handler = logging.StreamHandler(stream)<EOL>logger.addHandler(handler)<EOL>try:<EOL><INDENT>yi...
Context manager to capture a logger output with a StringIO stream.
f11942:m0
def bumpversion(self, part, commit=True, tag=False, message=None,<EOL>allow_dirty=False):
import bumpversion<EOL>args = (<EOL>(['<STR_LIT>'] if self.verbose > <NUM_LIT:1> else []) +<EOL>(['<STR_LIT>'] if allow_dirty else []) +<EOL>(['<STR_LIT>'] if commit else ['<STR_LIT>']) +<EOL>(['<STR_LIT>'] if tag else ['<STR_LIT>']) +<EOL>(['<STR_LIT>', message] if message is not None else []) +<EOL>['<STR_LIT>', part...
Run bumpversion.main() with the specified arguments, and return the new computed version string.
f11942:c0:m2
@staticmethod<EOL><INDENT>def edit_release_notes():<DEDENT>
from tempfile import mkstemp<EOL>import os<EOL>import shlex<EOL>import subprocess<EOL>text_editor = shlex.split(os.environ.get('<STR_LIT>', '<STR_LIT>'))<EOL>fd, tmp = mkstemp(prefix='<STR_LIT>')<EOL>try:<EOL><INDENT>os.close(fd)<EOL>with open(tmp, '<STR_LIT:w>') as f:<EOL><INDENT>f.write("<STR_LIT>"<EOL>"<STR_LIT>")<E...
Use the default text $EDITOR to write release notes. If $EDITOR is not set, use 'nano'.
f11942:c1:m2
def buildMutator(items, axes=None, bias=None):
from mutatorMath.objects.bender import Bender<EOL>items = [(Location(loc),obj) for loc, obj in items]<EOL>m = Mutator()<EOL>if axes is not None:<EOL><INDENT>bender = Bender(axes)<EOL>m.setBender(bender)<EOL><DEDENT>else:<EOL><INDENT>bender = noBend<EOL><DEDENT>items = sorted(items)<EOL>if not bias:<EOL><INDENT>bias = b...
Build a mutator with the (location, obj) pairs in items. Determine the bias based on the given locations.
f11943:m1
def getLimits(locations, current, sortResults=True, verbose=False):
limit = {}<EOL>for l in locations:<EOL><INDENT>a, b = current.common(l)<EOL>if a is None:<EOL><INDENT>continue<EOL><DEDENT>for name, value in b.items():<EOL><INDENT>f = a[name]<EOL>if name not in limit:<EOL><INDENT>limit[name] = {}<EOL>limit[name]['<STR_LIT:<>'] = {}<EOL>limit[name]['<STR_LIT:=>'] = {}<EOL>limit[name][...
Find the projections for each delta in the list of locations, relative to the current location. Return only the dimensions that are relevant for current.
f11943:m2
def setNeutral(self, aMathObject, deltaName="<STR_LIT>"):
self._neutral = aMathObject<EOL>self.addDelta(Location(), aMathObject-aMathObject, deltaName, punch=False, axisOnly=True)<EOL>
Set the neutral object.
f11943:c0:m4
def getNeutral(self):
return self._neutral<EOL>
Get the neutral object.
f11943:c0:m5
def addDelta(self, location, aMathObject, deltaName = None, punch=False, axisOnly=True):
<EOL>if punch:<EOL><INDENT>r = self.getInstance(location, axisOnly=axisOnly)<EOL>if r is not None:<EOL><INDENT>self[location.asTuple()] = aMathObject-r, deltaName<EOL><DEDENT>else:<EOL><INDENT>raise MutatorError("<STR_LIT>")<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self[location.asTuple()] = aMathObject, deltaName<EOL><DE...
Add a delta at this location. * location: a Location object * mathObject: a math-sensitive object * deltaName: optional string/token * punch: * True: add the difference with the instance value at that location and the delta * ...
f11943:c0:m6
def getAxisNames(self):
s = {}<EOL>for l, x in self.items():<EOL><INDENT>s.update(dict.fromkeys([k for k, v in l], None))<EOL><DEDENT>return set(s.keys())<EOL>
Collect a set of axis names from all deltas.
f11943:c0:m7
def _collectAxisPoints(self):
for l, (value, deltaName) in self.items():<EOL><INDENT>location = Location(l)<EOL>name = location.isOnAxis()<EOL>if name is not None and name is not False:<EOL><INDENT>if name not in self._axes:<EOL><INDENT>self._axes[name] = []<EOL><DEDENT>if l not in self._axes[name]:<EOL><INDENT>self._axes[name].append(l)<EOL><DEDEN...
Return a dictionary with all on-axis locations.
f11943:c0:m8
def _collectOffAxisPoints(self):
offAxis = {}<EOL>for l, (value, deltaName) in self.items():<EOL><INDENT>location = Location(l)<EOL>name = location.isOnAxis()<EOL>if name is None or name is False:<EOL><INDENT>offAxis[l] = <NUM_LIT:1><EOL><DEDENT><DEDENT>return list(offAxis.keys())<EOL>
Return a dictionary with all off-axis locations.
f11943:c0:m9
def collectLocations(self):
pts = []<EOL>for l, (value, deltaName) in self.items():<EOL><INDENT>pts.append(Location(l))<EOL><DEDENT>return pts<EOL>
Return a dictionary with all objects.
f11943:c0:m10
def _allLocations(self):
l = []<EOL>for locationTuple in self.keys():<EOL><INDENT>l.append(Location(locationTuple))<EOL><DEDENT>return l<EOL>
Return a list of all locations of all objects.
f11943:c0:m11
def getInstance(self, aLocation, axisOnly=False, getFactors=False):
self._collectAxisPoints()<EOL>factors = self.getFactors(aLocation, axisOnly)<EOL>total = None<EOL>for f, item, name in factors:<EOL><INDENT>if total is None:<EOL><INDENT>total = f * item<EOL>continue<EOL><DEDENT>total += f * item<EOL><DEDENT>if total is None:<EOL><INDENT>total = <NUM_LIT:0> * self._neutral<EOL><DEDENT>...
Calculate the delta at aLocation. * aLocation: a Location object, expected to be in bent space * axisOnly: * True: calculate an instance only with the on-axis masters. * False: calculate an instance with on-axis and off-axis masters. * getFa...
f11943:c0:m12
def makeInstance(self, aLocation, bend=True):
if bend:<EOL><INDENT>aLocation = self._bender(Location(aLocation))<EOL><DEDENT>if not aLocation.isAmbivalent():<EOL><INDENT>instanceObject = self.getInstance(aLocation-self._bias)<EOL><DEDENT>else:<EOL><INDENT>locX, locY = aLocation.split()<EOL>instanceObject = self.getInstance(locX-self._bias)*(<NUM_LIT:1>,<NUM_LIT:0>...
Calculate an instance with the right bias and add the neutral. aLocation: expected to be in input space
f11943:c0:m13
def getFactors(self, aLocation, axisOnly=False, allFactors=False):
deltas = []<EOL>aLocation.expand(self.getAxisNames())<EOL>limits = getLimits(self._allLocations(), aLocation)<EOL>for deltaLocationTuple, (mathItem, deltaName) in sorted(self.items()):<EOL><INDENT>deltaLocation = Location(deltaLocationTuple)<EOL>deltaLocation.expand( self.getAxisNames())<EOL>factor = self._accumulateFa...
Return a list of all factors and math items at aLocation. factor, mathItem, deltaName all = True: include factors that are zero or near-zero
f11943:c0:m14
def _accumulateFactors(self, aLocation, deltaLocation, limits, axisOnly):
relative = []<EOL>deltaAxis = deltaLocation.isOnAxis()<EOL>if deltaAxis is None:<EOL><INDENT>relative.append(<NUM_LIT:1>)<EOL><DEDENT>elif deltaAxis:<EOL><INDENT>deltasOnSameAxis = self._axes.get(deltaAxis, [])<EOL>d = ((deltaAxis, <NUM_LIT:0>),)<EOL>if d not in deltasOnSameAxis:<EOL><INDENT>deltasOnSameAxis.append(d)<...
Calculate the factors of deltaLocation towards aLocation,
f11943:c0:m15
def _calcOnAxisFactor(self, aLocation, deltaAxis, deltasOnSameAxis, deltaLocation):
if deltaAxis == "<STR_LIT>":<EOL><INDENT>f = <NUM_LIT:0><EOL>v = <NUM_LIT:0><EOL><DEDENT>else:<EOL><INDENT>f = aLocation[deltaAxis]<EOL>v = deltaLocation[deltaAxis]<EOL><DEDENT>i = []<EOL>iv = {}<EOL>for value in deltasOnSameAxis:<EOL><INDENT>iv[Location(value)[deltaAxis]]=<NUM_LIT:1><EOL><DEDENT>i = sorted(iv.keys())<...
Calculate the on-axis factors.
f11943:c0:m16
def _calcOffAxisFactor(self, aLocation, deltaLocation, limits):
relative = []<EOL>for dim in limits.keys():<EOL><INDENT>f = aLocation[dim]<EOL>v = deltaLocation[dim]<EOL>mB, M, mA = limits[dim]<EOL>r = <NUM_LIT:0><EOL>if mA is not None and v > mA:<EOL><INDENT>relative.append(<NUM_LIT:0>)<EOL>continue<EOL><DEDENT>elif mB is not None and v < mB:<EOL><INDENT>relative.append(<NUM_LIT:0...
Calculate the off-axis factors.
f11943:c0:m17
def sortLocations(locations):
onAxis = []<EOL>onAxisValues = {}<EOL>offAxis = []<EOL>offAxis_projecting = []<EOL>offAxis_wild = []<EOL>for l in locations:<EOL><INDENT>if l.isOrigin():<EOL><INDENT>continue<EOL><DEDENT>if l.isOnAxis():<EOL><INDENT>onAxis.append(l)<EOL>for axis in l.keys():<EOL><INDENT>if axis not in onAxisValues:<EOL><INDENT>onAxisVa...
Sort the locations by ranking: 1. all on-axis points 2. all off-axis points which project onto on-axis points these would be involved in master to master interpolations necessary for patching. Projecting off-axis masters have at least one coordin...
f11945:m1
def biasFromLocations(locs, preferOrigin=True):
dims = {}<EOL>locs.sort()<EOL>for l in locs:<EOL><INDENT>for d in l.keys():<EOL><INDENT>if not d in dims:<EOL><INDENT>dims[d] = []<EOL><DEDENT>v = l[d]<EOL>if type(v)==tuple:<EOL><INDENT>dims[d].append(v[<NUM_LIT:0>])<EOL>dims[d].append(v[<NUM_LIT:1>])<EOL><DEDENT>else:<EOL><INDENT>dims[d].append(v)<EOL><DEDENT><DEDENT...
Find the vector that translates the whole system to the origin.
f11945:m2
def mostCommon(L):
<EOL>SL = sorted((x, i) for i, x in enumerate(L))<EOL>groups = itertools.groupby(SL, key=operator.itemgetter(<NUM_LIT:0>))<EOL>def _auxfun(g):<EOL><INDENT>item, iterable = g<EOL>count = <NUM_LIT:0><EOL>min_index = len(L)<EOL>for _, where in iterable:<EOL><INDENT>count += <NUM_LIT:1><EOL>min_index = min(min_index, where...
# http://stackoverflow.com/questions/1518522/python-most-common-element-in-a-list >>> mostCommon([1, 2, 2, 3]) 2 >>> mostCommon([1, 2, 3]) 1 >>> mostCommon([-1, 2, 3]) -1 >>> mostCommon([-1, -2, -3]) -1 >>> mostCommon([-1, -2, -3, -1]) -1 >>> mostCommon([-1, -1, -2, -2]) -1 >>> mostCommon([0, 0.125, 0.275, 1]) 0 >>>...
f11945:m3
def expand(self, axisNames):
for k in axisNames:<EOL><INDENT>if k not in self:<EOL><INDENT>self[k] = <NUM_LIT:0><EOL><DEDENT><DEDENT>
Expand the location with zero values for all axes in axisNames that aren't filled in the current location. :: >>> l = Location(pop=1) >>> l.expand(['snap', 'crackle']) >>> print(l) <Location crackle:0, pop:1, snap:0 >
f11945:c0:m2
def copy(self):
new = self.__class__()<EOL>new.update(self)<EOL>return new<EOL>
Return a copy of this location. :: >>> l = Location(pop=1, snap=0) >>> l.copy() <Location pop:1, snap:0 >
f11945:c0:m3
def fromTuple(self, locationTuple):
for key, value in locationTuple:<EOL><INDENT>try:<EOL><INDENT>self[key] = float(value)<EOL><DEDENT>except TypeError:<EOL><INDENT>self[key] = tuple([float(v) for v in value])<EOL><DEDENT><DEDENT>
Read the coordinates from a tuple. :: >>> t = (('pop', 1), ('snap', -100)) >>> l = Location() >>> l.fromTuple(t) >>> print(l) <Location pop:1, snap:-100 >
f11945:c0:m4
def asTuple(self):
t = []<EOL>k = sorted(self.keys())<EOL>for key in k:<EOL><INDENT>t.append((key, self[key]))<EOL><DEDENT>return tuple(t)<EOL>
Return the location as a tuple. Sort the dimension names alphabetically. :: >>> l = Location(pop=1, snap=-100) >>> l.asTuple() (('pop', 1), ('snap', -100))
f11945:c0:m5