partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
test
SparkFeatureUnion.fit_transform
TODO: rewrite docstring Fit all transformers using X, transform the data and concatenate results. Parameters ---------- X : array-like or sparse matrix, shape (n_samples, n_features) Input data to be transformed. Returns ------- X_t : array-lik...
splearn/pipeline.py
def fit_transform(self, Z, **fit_params): """TODO: rewrite docstring Fit all transformers using X, transform the data and concatenate results. Parameters ---------- X : array-like or sparse matrix, shape (n_samples, n_features) Input data to be transformed. ...
def fit_transform(self, Z, **fit_params): """TODO: rewrite docstring Fit all transformers using X, transform the data and concatenate results. Parameters ---------- X : array-like or sparse matrix, shape (n_samples, n_features) Input data to be transformed. ...
[ "TODO", ":", "rewrite", "docstring", "Fit", "all", "transformers", "using", "X", "transform", "the", "data", "and", "concatenate", "results", ".", "Parameters", "----------", "X", ":", "array", "-", "like", "or", "sparse", "matrix", "shape", "(", "n_samples", ...
lensacom/sparkit-learn
python
https://github.com/lensacom/sparkit-learn/blob/0498502107c1f7dcf33cda0cdb6f5ba4b42524b7/splearn/pipeline.py#L248-L262
[ "def", "fit_transform", "(", "self", ",", "Z", ",", "*", "*", "fit_params", ")", ":", "return", "self", ".", "fit", "(", "Z", ",", "*", "*", "fit_params", ")", ".", "transform", "(", "Z", ")" ]
0498502107c1f7dcf33cda0cdb6f5ba4b42524b7
test
SparkFeatureUnion.transform
TODO: rewrite docstring Transform X separately by each transformer, concatenate results. Parameters ---------- X : array-like or sparse matrix, shape (n_samples, n_features) Input data to be transformed. Returns ------- X_t : array-like or sparse matri...
splearn/pipeline.py
def transform(self, Z): """TODO: rewrite docstring Transform X separately by each transformer, concatenate results. Parameters ---------- X : array-like or sparse matrix, shape (n_samples, n_features) Input data to be transformed. Returns ------- ...
def transform(self, Z): """TODO: rewrite docstring Transform X separately by each transformer, concatenate results. Parameters ---------- X : array-like or sparse matrix, shape (n_samples, n_features) Input data to be transformed. Returns ------- ...
[ "TODO", ":", "rewrite", "docstring", "Transform", "X", "separately", "by", "each", "transformer", "concatenate", "results", ".", "Parameters", "----------", "X", ":", "array", "-", "like", "or", "sparse", "matrix", "shape", "(", "n_samples", "n_features", ")", ...
lensacom/sparkit-learn
python
https://github.com/lensacom/sparkit-learn/blob/0498502107c1f7dcf33cda0cdb6f5ba4b42524b7/splearn/pipeline.py#L264-L298
[ "def", "transform", "(", "self", ",", "Z", ")", ":", "if", "isinstance", "(", "Z", ",", "DictRDD", ")", ":", "X", "=", "Z", "[", ":", ",", "'X'", "]", "else", ":", "X", "=", "Z", "Zs", "=", "[", "_transform_one", "(", "trans", ",", "name", ",...
0498502107c1f7dcf33cda0cdb6f5ba4b42524b7
test
SparkRandomForestClassifier.fit
Fit the model according to the given training data. Parameters ---------- Z : DictRDD containing (X, y) pairs X - Training vector y - Target labels classes : iterable The set of available classes Returns ------- self : object ...
splearn/ensemble/__init__.py
def fit(self, Z, classes=None): """Fit the model according to the given training data. Parameters ---------- Z : DictRDD containing (X, y) pairs X - Training vector y - Target labels classes : iterable The set of available classes Ret...
def fit(self, Z, classes=None): """Fit the model according to the given training data. Parameters ---------- Z : DictRDD containing (X, y) pairs X - Training vector y - Target labels classes : iterable The set of available classes Ret...
[ "Fit", "the", "model", "according", "to", "the", "given", "training", "data", "." ]
lensacom/sparkit-learn
python
https://github.com/lensacom/sparkit-learn/blob/0498502107c1f7dcf33cda0cdb6f5ba4b42524b7/splearn/ensemble/__init__.py#L122-L150
[ "def", "fit", "(", "self", ",", "Z", ",", "classes", "=", "None", ")", ":", "check_rdd", "(", "Z", ",", "{", "'X'", ":", "(", "sp", ".", "spmatrix", ",", "np", ".", "ndarray", ")", "}", ")", "mapper", "=", "lambda", "X_y", ":", "super", "(", ...
0498502107c1f7dcf33cda0cdb6f5ba4b42524b7
test
SparkGridSearchCV._fit
Actual fitting, performing the search over parameters.
splearn/grid_search.py
def _fit(self, Z, parameter_iterable): """Actual fitting, performing the search over parameters.""" self.scorer_ = check_scoring(self.estimator, scoring=self.scoring) cv = self.cv cv = _check_cv(cv, Z) if self.verbose > 0: if isinstance(parameter_iterable, Sized): ...
def _fit(self, Z, parameter_iterable): """Actual fitting, performing the search over parameters.""" self.scorer_ = check_scoring(self.estimator, scoring=self.scoring) cv = self.cv cv = _check_cv(cv, Z) if self.verbose > 0: if isinstance(parameter_iterable, Sized): ...
[ "Actual", "fitting", "performing", "the", "search", "over", "parameters", "." ]
lensacom/sparkit-learn
python
https://github.com/lensacom/sparkit-learn/blob/0498502107c1f7dcf33cda0cdb6f5ba4b42524b7/splearn/grid_search.py#L17-L90
[ "def", "_fit", "(", "self", ",", "Z", ",", "parameter_iterable", ")", ":", "self", ".", "scorer_", "=", "check_scoring", "(", "self", ".", "estimator", ",", "scoring", "=", "self", ".", "scoring", ")", "cv", "=", "self", ".", "cv", "cv", "=", "_check...
0498502107c1f7dcf33cda0cdb6f5ba4b42524b7
test
SparkLabelEncoder.fit
Fit label encoder Parameters ---------- y : ArrayRDD (n_samples,) Target values. Returns ------- self : returns an instance of self.
splearn/preprocessing/label.py
def fit(self, y): """Fit label encoder Parameters ---------- y : ArrayRDD (n_samples,) Target values. Returns ------- self : returns an instance of self. """ def mapper(y): y = column_or_1d(y, warn=True) _check_...
def fit(self, y): """Fit label encoder Parameters ---------- y : ArrayRDD (n_samples,) Target values. Returns ------- self : returns an instance of self. """ def mapper(y): y = column_or_1d(y, warn=True) _check_...
[ "Fit", "label", "encoder", "Parameters", "----------", "y", ":", "ArrayRDD", "(", "n_samples", ")", "Target", "values", ".", "Returns", "-------", "self", ":", "returns", "an", "instance", "of", "self", "." ]
lensacom/sparkit-learn
python
https://github.com/lensacom/sparkit-learn/blob/0498502107c1f7dcf33cda0cdb6f5ba4b42524b7/splearn/preprocessing/label.py#L49-L70
[ "def", "fit", "(", "self", ",", "y", ")", ":", "def", "mapper", "(", "y", ")", ":", "y", "=", "column_or_1d", "(", "y", ",", "warn", "=", "True", ")", "_check_numpy_unicode_bug", "(", "y", ")", "return", "np", ".", "unique", "(", "y", ")", "def",...
0498502107c1f7dcf33cda0cdb6f5ba4b42524b7
test
SparkLabelEncoder.transform
Transform labels to normalized encoding. Parameters ---------- y : ArrayRDD [n_samples] Target values. Returns ------- y : ArrayRDD [n_samples]
splearn/preprocessing/label.py
def transform(self, y): """Transform labels to normalized encoding. Parameters ---------- y : ArrayRDD [n_samples] Target values. Returns ------- y : ArrayRDD [n_samples] """ mapper = super(SparkLabelEncoder, self).transform map...
def transform(self, y): """Transform labels to normalized encoding. Parameters ---------- y : ArrayRDD [n_samples] Target values. Returns ------- y : ArrayRDD [n_samples] """ mapper = super(SparkLabelEncoder, self).transform map...
[ "Transform", "labels", "to", "normalized", "encoding", ".", "Parameters", "----------", "y", ":", "ArrayRDD", "[", "n_samples", "]", "Target", "values", ".", "Returns", "-------", "y", ":", "ArrayRDD", "[", "n_samples", "]" ]
lensacom/sparkit-learn
python
https://github.com/lensacom/sparkit-learn/blob/0498502107c1f7dcf33cda0cdb6f5ba4b42524b7/splearn/preprocessing/label.py#L84-L96
[ "def", "transform", "(", "self", ",", "y", ")", ":", "mapper", "=", "super", "(", "SparkLabelEncoder", ",", "self", ")", ".", "transform", "mapper", "=", "self", ".", "broadcast", "(", "mapper", ",", "y", ".", "context", ")", "return", "y", ".", "tra...
0498502107c1f7dcf33cda0cdb6f5ba4b42524b7
test
_score
Compute the score of an estimator on a given test set.
splearn/cross_validation.py
def _score(estimator, Z_test, scorer): """Compute the score of an estimator on a given test set.""" score = scorer(estimator, Z_test) if not isinstance(score, numbers.Number): raise ValueError("scoring must return a number, got %s (%s) instead." % (str(score), type(score))) ...
def _score(estimator, Z_test, scorer): """Compute the score of an estimator on a given test set.""" score = scorer(estimator, Z_test) if not isinstance(score, numbers.Number): raise ValueError("scoring must return a number, got %s (%s) instead." % (str(score), type(score))) ...
[ "Compute", "the", "score", "of", "an", "estimator", "on", "a", "given", "test", "set", "." ]
lensacom/sparkit-learn
python
https://github.com/lensacom/sparkit-learn/blob/0498502107c1f7dcf33cda0cdb6f5ba4b42524b7/splearn/cross_validation.py#L29-L35
[ "def", "_score", "(", "estimator", ",", "Z_test", ",", "scorer", ")", ":", "score", "=", "scorer", "(", "estimator", ",", "Z_test", ")", "if", "not", "isinstance", "(", "score", ",", "numbers", ".", "Number", ")", ":", "raise", "ValueError", "(", "\"sc...
0498502107c1f7dcf33cda0cdb6f5ba4b42524b7
test
SparkKMeans.fit
Compute k-means clustering. Parameters ---------- Z : ArrayRDD or DictRDD containing array-like or sparse matrix Train data. Returns ------- self
splearn/cluster/k_means_.py
def fit(self, Z): """Compute k-means clustering. Parameters ---------- Z : ArrayRDD or DictRDD containing array-like or sparse matrix Train data. Returns ------- self """ X = Z[:, 'X'] if isinstance(Z, DictRDD) else Z check_rd...
def fit(self, Z): """Compute k-means clustering. Parameters ---------- Z : ArrayRDD or DictRDD containing array-like or sparse matrix Train data. Returns ------- self """ X = Z[:, 'X'] if isinstance(Z, DictRDD) else Z check_rd...
[ "Compute", "k", "-", "means", "clustering", "." ]
lensacom/sparkit-learn
python
https://github.com/lensacom/sparkit-learn/blob/0498502107c1f7dcf33cda0cdb6f5ba4b42524b7/splearn/cluster/k_means_.py#L74-L98
[ "def", "fit", "(", "self", ",", "Z", ")", ":", "X", "=", "Z", "[", ":", ",", "'X'", "]", "if", "isinstance", "(", "Z", ",", "DictRDD", ")", "else", "Z", "check_rdd", "(", "X", ",", "(", "np", ".", "ndarray", ",", "sp", ".", "spmatrix", ")", ...
0498502107c1f7dcf33cda0cdb6f5ba4b42524b7
test
SparkKMeans.predict
Predict the closest cluster each sample in X belongs to. In the vector quantization literature, `cluster_centers_` is called the code book and each value returned by `predict` is the index of the closest code in the code book. Parameters ---------- X : ArrayRDD containi...
splearn/cluster/k_means_.py
def predict(self, X): """Predict the closest cluster each sample in X belongs to. In the vector quantization literature, `cluster_centers_` is called the code book and each value returned by `predict` is the index of the closest code in the code book. Parameters -------...
def predict(self, X): """Predict the closest cluster each sample in X belongs to. In the vector quantization literature, `cluster_centers_` is called the code book and each value returned by `predict` is the index of the closest code in the code book. Parameters -------...
[ "Predict", "the", "closest", "cluster", "each", "sample", "in", "X", "belongs", "to", "." ]
lensacom/sparkit-learn
python
https://github.com/lensacom/sparkit-learn/blob/0498502107c1f7dcf33cda0cdb6f5ba4b42524b7/splearn/cluster/k_means_.py#L100-L125
[ "def", "predict", "(", "self", ",", "X", ")", ":", "check_rdd", "(", "X", ",", "(", "np", ".", "ndarray", ",", "sp", ".", "spmatrix", ")", ")", "if", "hasattr", "(", "self", ",", "'_mllib_model'", ")", ":", "if", "isinstance", "(", "X", ",", "Arr...
0498502107c1f7dcf33cda0cdb6f5ba4b42524b7
test
SparkSGDClassifier.fit
Fit the model according to the given training data. Parameters ---------- Z : DictRDD containing (X, y) pairs X - Training vector y - Target labels classes : iterable The set of available classes Returns ------- self : object ...
splearn/linear_model/stochastic_gradient.py
def fit(self, Z, classes=None): """Fit the model according to the given training data. Parameters ---------- Z : DictRDD containing (X, y) pairs X - Training vector y - Target labels classes : iterable The set of available classes Ret...
def fit(self, Z, classes=None): """Fit the model according to the given training data. Parameters ---------- Z : DictRDD containing (X, y) pairs X - Training vector y - Target labels classes : iterable The set of available classes Ret...
[ "Fit", "the", "model", "according", "to", "the", "given", "training", "data", "." ]
lensacom/sparkit-learn
python
https://github.com/lensacom/sparkit-learn/blob/0498502107c1f7dcf33cda0cdb6f5ba4b42524b7/splearn/linear_model/stochastic_gradient.py#L154-L172
[ "def", "fit", "(", "self", ",", "Z", ",", "classes", "=", "None", ")", ":", "check_rdd", "(", "Z", ",", "{", "'X'", ":", "(", "sp", ".", "spmatrix", ",", "np", ".", "ndarray", ")", "}", ")", "self", ".", "_classes_", "=", "np", ".", "unique", ...
0498502107c1f7dcf33cda0cdb6f5ba4b42524b7
test
SparkSGDClassifier.predict
Distributed method to predict class labels for samples in X. Parameters ---------- X : ArrayRDD containing {array-like, sparse matrix} Samples. Returns ------- C : ArrayRDD Predicted class label per sample.
splearn/linear_model/stochastic_gradient.py
def predict(self, X): """Distributed method to predict class labels for samples in X. Parameters ---------- X : ArrayRDD containing {array-like, sparse matrix} Samples. Returns ------- C : ArrayRDD Predicted class label per sample. ...
def predict(self, X): """Distributed method to predict class labels for samples in X. Parameters ---------- X : ArrayRDD containing {array-like, sparse matrix} Samples. Returns ------- C : ArrayRDD Predicted class label per sample. ...
[ "Distributed", "method", "to", "predict", "class", "labels", "for", "samples", "in", "X", "." ]
lensacom/sparkit-learn
python
https://github.com/lensacom/sparkit-learn/blob/0498502107c1f7dcf33cda0cdb6f5ba4b42524b7/splearn/linear_model/stochastic_gradient.py#L174-L188
[ "def", "predict", "(", "self", ",", "X", ")", ":", "check_rdd", "(", "X", ",", "(", "sp", ".", "spmatrix", ",", "np", ".", "ndarray", ")", ")", "return", "self", ".", "_spark_predict", "(", "SparkSGDClassifier", ",", "X", ")" ]
0498502107c1f7dcf33cda0cdb6f5ba4b42524b7
test
check_rdd_dtype
Checks if the blocks in the RDD matches the expected types. Parameters: ----------- rdd: splearn.BlockRDD The RDD to check expected_dtype: {type, list of types, tuple of types, dict of types} Expected type(s). If the RDD is a DictRDD the parameter type is restricted to dict. ...
splearn/utils/validation.py
def check_rdd_dtype(rdd, expected_dtype): """Checks if the blocks in the RDD matches the expected types. Parameters: ----------- rdd: splearn.BlockRDD The RDD to check expected_dtype: {type, list of types, tuple of types, dict of types} Expected type(s). If the RDD is a DictRDD the ...
def check_rdd_dtype(rdd, expected_dtype): """Checks if the blocks in the RDD matches the expected types. Parameters: ----------- rdd: splearn.BlockRDD The RDD to check expected_dtype: {type, list of types, tuple of types, dict of types} Expected type(s). If the RDD is a DictRDD the ...
[ "Checks", "if", "the", "blocks", "in", "the", "RDD", "matches", "the", "expected", "types", "." ]
lensacom/sparkit-learn
python
https://github.com/lensacom/sparkit-learn/blob/0498502107c1f7dcf33cda0cdb6f5ba4b42524b7/splearn/utils/validation.py#L4-L39
[ "def", "check_rdd_dtype", "(", "rdd", ",", "expected_dtype", ")", ":", "if", "not", "isinstance", "(", "rdd", ",", "BlockRDD", ")", ":", "raise", "TypeError", "(", "\"Expected {0} for parameter rdd, got {1}.\"", ".", "format", "(", "BlockRDD", ",", "type", "(", ...
0498502107c1f7dcf33cda0cdb6f5ba4b42524b7
test
SparkDictVectorizer.fit
Learn a list of feature name -> indices mappings. Parameters ---------- Z : DictRDD with column 'X' Dict(s) or Mapping(s) from feature names (arbitrary Python objects) to feature values (strings or convertible to dtype). Returns ------- self
splearn/feature_extraction/dict_vectorizer.py
def fit(self, Z): """Learn a list of feature name -> indices mappings. Parameters ---------- Z : DictRDD with column 'X' Dict(s) or Mapping(s) from feature names (arbitrary Python objects) to feature values (strings or convertible to dtype). Returns ...
def fit(self, Z): """Learn a list of feature name -> indices mappings. Parameters ---------- Z : DictRDD with column 'X' Dict(s) or Mapping(s) from feature names (arbitrary Python objects) to feature values (strings or convertible to dtype). Returns ...
[ "Learn", "a", "list", "of", "feature", "name", "-", ">", "indices", "mappings", "." ]
lensacom/sparkit-learn
python
https://github.com/lensacom/sparkit-learn/blob/0498502107c1f7dcf33cda0cdb6f5ba4b42524b7/splearn/feature_extraction/dict_vectorizer.py#L76-L124
[ "def", "fit", "(", "self", ",", "Z", ")", ":", "X", "=", "Z", "[", ":", ",", "'X'", "]", "if", "isinstance", "(", "Z", ",", "DictRDD", ")", "else", "Z", "\"\"\"Create vocabulary\n \"\"\"", "class", "SetAccum", "(", "AccumulatorParam", ")", ":", ...
0498502107c1f7dcf33cda0cdb6f5ba4b42524b7
test
SparkDictVectorizer.transform
Transform ArrayRDD's (or DictRDD's 'X' column's) feature->value dicts to array or sparse matrix. Named features not encountered during fit or fit_transform will be silently ignored. Parameters ---------- Z : ArrayRDD or DictRDD with column 'X' containing Mapping or ...
splearn/feature_extraction/dict_vectorizer.py
def transform(self, Z): """Transform ArrayRDD's (or DictRDD's 'X' column's) feature->value dicts to array or sparse matrix. Named features not encountered during fit or fit_transform will be silently ignored. Parameters ---------- Z : ArrayRDD or DictRDD with col...
def transform(self, Z): """Transform ArrayRDD's (or DictRDD's 'X' column's) feature->value dicts to array or sparse matrix. Named features not encountered during fit or fit_transform will be silently ignored. Parameters ---------- Z : ArrayRDD or DictRDD with col...
[ "Transform", "ArrayRDD", "s", "(", "or", "DictRDD", "s", "X", "column", "s", ")", "feature", "-", ">", "value", "dicts", "to", "array", "or", "sparse", "matrix", ".", "Named", "features", "not", "encountered", "during", "fit", "or", "fit_transform", "will"...
lensacom/sparkit-learn
python
https://github.com/lensacom/sparkit-learn/blob/0498502107c1f7dcf33cda0cdb6f5ba4b42524b7/splearn/feature_extraction/dict_vectorizer.py#L126-L147
[ "def", "transform", "(", "self", ",", "Z", ")", ":", "mapper", "=", "self", ".", "broadcast", "(", "super", "(", "SparkDictVectorizer", ",", "self", ")", ".", "transform", ",", "Z", ".", "context", ")", "dtype", "=", "sp", ".", "spmatrix", "if", "sel...
0498502107c1f7dcf33cda0cdb6f5ba4b42524b7
test
SparkVarianceThreshold.fit
Learn empirical variances from X. Parameters ---------- X : {array-like, sparse matrix}, shape (n_samples, n_features) Sample vectors from which to compute variances. y : any Ignored. This parameter exists only for compatibility with sklearn.pipeline...
splearn/feature_selection/variance_threshold.py
def fit(self, Z): """Learn empirical variances from X. Parameters ---------- X : {array-like, sparse matrix}, shape (n_samples, n_features) Sample vectors from which to compute variances. y : any Ignored. This parameter exists only for compatibility with...
def fit(self, Z): """Learn empirical variances from X. Parameters ---------- X : {array-like, sparse matrix}, shape (n_samples, n_features) Sample vectors from which to compute variances. y : any Ignored. This parameter exists only for compatibility with...
[ "Learn", "empirical", "variances", "from", "X", "." ]
lensacom/sparkit-learn
python
https://github.com/lensacom/sparkit-learn/blob/0498502107c1f7dcf33cda0cdb6f5ba4b42524b7/splearn/feature_selection/variance_threshold.py#L46-L93
[ "def", "fit", "(", "self", ",", "Z", ")", ":", "X", "=", "Z", "[", ":", ",", "'X'", "]", "if", "isinstance", "(", "Z", ",", "DictRDD", ")", "else", "Z", "check_rdd", "(", "X", ",", "(", "np", ".", "ndarray", ",", "sp", ".", "spmatrix", ")", ...
0498502107c1f7dcf33cda0cdb6f5ba4b42524b7
test
svd
Calculate the SVD of a blocked RDD directly, returning only the leading k singular vectors. Assumes n rows and d columns, efficient when n >> d Must be able to fit d^2 within the memory of a single machine. Parameters ---------- blocked_rdd : RDD RDD with data points in numpy array blocks ...
splearn/decomposition/truncated_svd.py
def svd(blocked_rdd, k): """ Calculate the SVD of a blocked RDD directly, returning only the leading k singular vectors. Assumes n rows and d columns, efficient when n >> d Must be able to fit d^2 within the memory of a single machine. Parameters ---------- blocked_rdd : RDD RDD with...
def svd(blocked_rdd, k): """ Calculate the SVD of a blocked RDD directly, returning only the leading k singular vectors. Assumes n rows and d columns, efficient when n >> d Must be able to fit d^2 within the memory of a single machine. Parameters ---------- blocked_rdd : RDD RDD with...
[ "Calculate", "the", "SVD", "of", "a", "blocked", "RDD", "directly", "returning", "only", "the", "leading", "k", "singular", "vectors", ".", "Assumes", "n", "rows", "and", "d", "columns", "efficient", "when", "n", ">>", "d", "Must", "be", "able", "to", "f...
lensacom/sparkit-learn
python
https://github.com/lensacom/sparkit-learn/blob/0498502107c1f7dcf33cda0cdb6f5ba4b42524b7/splearn/decomposition/truncated_svd.py#L15-L52
[ "def", "svd", "(", "blocked_rdd", ",", "k", ")", ":", "# compute the covariance matrix (without mean subtraction)", "# TODO use one func for this (with mean subtraction as an option?)", "c", "=", "blocked_rdd", ".", "map", "(", "lambda", "x", ":", "(", "x", ".", "T", "....
0498502107c1f7dcf33cda0cdb6f5ba4b42524b7
test
svd_em
Calculate the SVD of a blocked RDD using an expectation maximization algorithm (from Roweis, NIPS, 1997) that avoids explicitly computing the covariance matrix, returning only the leading k singular vectors. Assumes n rows and d columns, does not require d^2 to fit into memory on a single machine. P...
splearn/decomposition/truncated_svd.py
def svd_em(blocked_rdd, k, maxiter=20, tol=1e-6, compute_u=True, seed=None): """ Calculate the SVD of a blocked RDD using an expectation maximization algorithm (from Roweis, NIPS, 1997) that avoids explicitly computing the covariance matrix, returning only the leading k singular vectors. Assumes n r...
def svd_em(blocked_rdd, k, maxiter=20, tol=1e-6, compute_u=True, seed=None): """ Calculate the SVD of a blocked RDD using an expectation maximization algorithm (from Roweis, NIPS, 1997) that avoids explicitly computing the covariance matrix, returning only the leading k singular vectors. Assumes n r...
[ "Calculate", "the", "SVD", "of", "a", "blocked", "RDD", "using", "an", "expectation", "maximization", "algorithm", "(", "from", "Roweis", "NIPS", "1997", ")", "that", "avoids", "explicitly", "computing", "the", "covariance", "matrix", "returning", "only", "the",...
lensacom/sparkit-learn
python
https://github.com/lensacom/sparkit-learn/blob/0498502107c1f7dcf33cda0cdb6f5ba4b42524b7/splearn/decomposition/truncated_svd.py#L55-L170
[ "def", "svd_em", "(", "blocked_rdd", ",", "k", ",", "maxiter", "=", "20", ",", "tol", "=", "1e-6", ",", "compute_u", "=", "True", ",", "seed", "=", "None", ")", ":", "n", ",", "m", "=", "blocked_rdd", ".", "shape", "[", ":", "2", "]", "sc", "="...
0498502107c1f7dcf33cda0cdb6f5ba4b42524b7
test
SparkTruncatedSVD.fit_transform
Fit LSI model to X and perform dimensionality reduction on X. Parameters ---------- X : {array-like, sparse matrix}, shape (n_samples, n_features) Training data. Returns ------- X_new : array, shape (n_samples, n_components) Reduced version of X....
splearn/decomposition/truncated_svd.py
def fit_transform(self, Z): """Fit LSI model to X and perform dimensionality reduction on X. Parameters ---------- X : {array-like, sparse matrix}, shape (n_samples, n_features) Training data. Returns ------- X_new : array, shape (n_samples, n_compon...
def fit_transform(self, Z): """Fit LSI model to X and perform dimensionality reduction on X. Parameters ---------- X : {array-like, sparse matrix}, shape (n_samples, n_features) Training data. Returns ------- X_new : array, shape (n_samples, n_compon...
[ "Fit", "LSI", "model", "to", "X", "and", "perform", "dimensionality", "reduction", "on", "X", "." ]
lensacom/sparkit-learn
python
https://github.com/lensacom/sparkit-learn/blob/0498502107c1f7dcf33cda0cdb6f5ba4b42524b7/splearn/decomposition/truncated_svd.py#L283-L308
[ "def", "fit_transform", "(", "self", ",", "Z", ")", ":", "X", "=", "Z", "[", ":", ",", "'X'", "]", "if", "isinstance", "(", "Z", ",", "DictRDD", ")", "else", "Z", "check_rdd", "(", "X", ",", "(", "sp", ".", "spmatrix", ",", "np", ".", "ndarray"...
0498502107c1f7dcf33cda0cdb6f5ba4b42524b7
test
SparkTruncatedSVD.transform
Perform dimensionality reduction on X. Parameters ---------- X : {array-like, sparse matrix}, shape (n_samples, n_features) New data. Returns ------- X_new : array, shape (n_samples, n_components) Reduced version of X. This will always be a dense...
splearn/decomposition/truncated_svd.py
def transform(self, Z): """Perform dimensionality reduction on X. Parameters ---------- X : {array-like, sparse matrix}, shape (n_samples, n_features) New data. Returns ------- X_new : array, shape (n_samples, n_components) Reduced versio...
def transform(self, Z): """Perform dimensionality reduction on X. Parameters ---------- X : {array-like, sparse matrix}, shape (n_samples, n_features) New data. Returns ------- X_new : array, shape (n_samples, n_components) Reduced versio...
[ "Perform", "dimensionality", "reduction", "on", "X", "." ]
lensacom/sparkit-learn
python
https://github.com/lensacom/sparkit-learn/blob/0498502107c1f7dcf33cda0cdb6f5ba4b42524b7/splearn/decomposition/truncated_svd.py#L310-L328
[ "def", "transform", "(", "self", ",", "Z", ")", ":", "X", "=", "Z", "[", ":", ",", "'X'", "]", "if", "isinstance", "(", "Z", ",", "DictRDD", ")", "else", "Z", "check_rdd", "(", "X", ",", "(", "sp", ".", "spmatrix", ",", "np", ".", "ndarray", ...
0498502107c1f7dcf33cda0cdb6f5ba4b42524b7
test
_block_collection
Pack rdd with a specific collection constructor.
splearn/rdd.py
def _block_collection(iterator, dtype, bsize=-1): """Pack rdd with a specific collection constructor.""" i = 0 accumulated = [] for a in iterator: if (bsize > 0) and (i >= bsize): yield _pack_accumulated(accumulated, dtype) accumulated = [] i = 0 accum...
def _block_collection(iterator, dtype, bsize=-1): """Pack rdd with a specific collection constructor.""" i = 0 accumulated = [] for a in iterator: if (bsize > 0) and (i >= bsize): yield _pack_accumulated(accumulated, dtype) accumulated = [] i = 0 accum...
[ "Pack", "rdd", "with", "a", "specific", "collection", "constructor", "." ]
lensacom/sparkit-learn
python
https://github.com/lensacom/sparkit-learn/blob/0498502107c1f7dcf33cda0cdb6f5ba4b42524b7/splearn/rdd.py#L35-L47
[ "def", "_block_collection", "(", "iterator", ",", "dtype", ",", "bsize", "=", "-", "1", ")", ":", "i", "=", "0", "accumulated", "=", "[", "]", "for", "a", "in", "iterator", ":", "if", "(", "bsize", ">", "0", ")", "and", "(", "i", ">=", "bsize", ...
0498502107c1f7dcf33cda0cdb6f5ba4b42524b7
test
_block_tuple
Pack rdd of tuples as tuples of arrays or scipy.sparse matrices.
splearn/rdd.py
def _block_tuple(iterator, dtypes, bsize=-1): """Pack rdd of tuples as tuples of arrays or scipy.sparse matrices.""" i = 0 blocked_tuple = None for tuple_i in iterator: if blocked_tuple is None: blocked_tuple = tuple([] for _ in range(len(tuple_i))) if (bsize > 0) and (i >= ...
def _block_tuple(iterator, dtypes, bsize=-1): """Pack rdd of tuples as tuples of arrays or scipy.sparse matrices.""" i = 0 blocked_tuple = None for tuple_i in iterator: if blocked_tuple is None: blocked_tuple = tuple([] for _ in range(len(tuple_i))) if (bsize > 0) and (i >= ...
[ "Pack", "rdd", "of", "tuples", "as", "tuples", "of", "arrays", "or", "scipy", ".", "sparse", "matrices", "." ]
lensacom/sparkit-learn
python
https://github.com/lensacom/sparkit-learn/blob/0498502107c1f7dcf33cda0cdb6f5ba4b42524b7/splearn/rdd.py#L50-L69
[ "def", "_block_tuple", "(", "iterator", ",", "dtypes", ",", "bsize", "=", "-", "1", ")", ":", "i", "=", "0", "blocked_tuple", "=", "None", "for", "tuple_i", "in", "iterator", ":", "if", "blocked_tuple", "is", "None", ":", "blocked_tuple", "=", "tuple", ...
0498502107c1f7dcf33cda0cdb6f5ba4b42524b7
test
block
Block an RDD Parameters ---------- rdd : RDD RDD of data points to block into either numpy arrays, scipy sparse matrices, or pandas data frames. Type of data point will be automatically inferred and blocked accordingly. bsize : int, optional, default None Size ...
splearn/rdd.py
def block(rdd, bsize=-1, dtype=None): """Block an RDD Parameters ---------- rdd : RDD RDD of data points to block into either numpy arrays, scipy sparse matrices, or pandas data frames. Type of data point will be automatically inferred and blocked accordingly. bsiz...
def block(rdd, bsize=-1, dtype=None): """Block an RDD Parameters ---------- rdd : RDD RDD of data points to block into either numpy arrays, scipy sparse matrices, or pandas data frames. Type of data point will be automatically inferred and blocked accordingly. bsiz...
[ "Block", "an", "RDD" ]
lensacom/sparkit-learn
python
https://github.com/lensacom/sparkit-learn/blob/0498502107c1f7dcf33cda0cdb6f5ba4b42524b7/splearn/rdd.py#L72-L111
[ "def", "block", "(", "rdd", ",", "bsize", "=", "-", "1", ",", "dtype", "=", "None", ")", ":", "try", ":", "entry", "=", "rdd", ".", "first", "(", ")", "except", "IndexError", ":", "# empty RDD: do not block", "return", "rdd", "# do different kinds of block...
0498502107c1f7dcf33cda0cdb6f5ba4b42524b7
test
BlockRDD._block
Execute the blocking process on the given rdd. Parameters ---------- rdd : pyspark.rdd.RDD Distributed data to block bsize : int or None The desired size of the blocks Returns ------- rdd : pyspark.rdd.RDD Blocked rdd.
splearn/rdd.py
def _block(self, rdd, bsize, dtype): """Execute the blocking process on the given rdd. Parameters ---------- rdd : pyspark.rdd.RDD Distributed data to block bsize : int or None The desired size of the blocks Returns ------- rdd : ...
def _block(self, rdd, bsize, dtype): """Execute the blocking process on the given rdd. Parameters ---------- rdd : pyspark.rdd.RDD Distributed data to block bsize : int or None The desired size of the blocks Returns ------- rdd : ...
[ "Execute", "the", "blocking", "process", "on", "the", "given", "rdd", "." ]
lensacom/sparkit-learn
python
https://github.com/lensacom/sparkit-learn/blob/0498502107c1f7dcf33cda0cdb6f5ba4b42524b7/splearn/rdd.py#L132-L148
[ "def", "_block", "(", "self", ",", "rdd", ",", "bsize", ",", "dtype", ")", ":", "return", "rdd", ".", "mapPartitions", "(", "lambda", "x", ":", "_block_collection", "(", "x", ",", "dtype", ",", "bsize", ")", ")" ]
0498502107c1f7dcf33cda0cdb6f5ba4b42524b7
test
BlockRDD.transform
Equivalent to map, compatibility purpose only. Column parameter ignored.
splearn/rdd.py
def transform(self, fn, dtype=None, *args, **kwargs): """Equivalent to map, compatibility purpose only. Column parameter ignored. """ rdd = self._rdd.map(fn) if dtype is None: return self.__class__(rdd, noblock=True, **self.get_params()) if dtype is np.ndarra...
def transform(self, fn, dtype=None, *args, **kwargs): """Equivalent to map, compatibility purpose only. Column parameter ignored. """ rdd = self._rdd.map(fn) if dtype is None: return self.__class__(rdd, noblock=True, **self.get_params()) if dtype is np.ndarra...
[ "Equivalent", "to", "map", "compatibility", "purpose", "only", ".", "Column", "parameter", "ignored", "." ]
lensacom/sparkit-learn
python
https://github.com/lensacom/sparkit-learn/blob/0498502107c1f7dcf33cda0cdb6f5ba4b42524b7/splearn/rdd.py#L257-L270
[ "def", "transform", "(", "self", ",", "fn", ",", "dtype", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "rdd", "=", "self", ".", "_rdd", ".", "map", "(", "fn", ")", "if", "dtype", "is", "None", ":", "return", "self", ".", ...
0498502107c1f7dcf33cda0cdb6f5ba4b42524b7
test
ArrayLikeRDDMixin.shape
Returns the shape of the data.
splearn/rdd.py
def shape(self): """Returns the shape of the data.""" # TODO cache first = self.first().shape shape = self._rdd.map(lambda x: x.shape[0]).sum() return (shape,) + first[1:]
def shape(self): """Returns the shape of the data.""" # TODO cache first = self.first().shape shape = self._rdd.map(lambda x: x.shape[0]).sum() return (shape,) + first[1:]
[ "Returns", "the", "shape", "of", "the", "data", "." ]
lensacom/sparkit-learn
python
https://github.com/lensacom/sparkit-learn/blob/0498502107c1f7dcf33cda0cdb6f5ba4b42524b7/splearn/rdd.py#L303-L308
[ "def", "shape", "(", "self", ")", ":", "# TODO cache", "first", "=", "self", ".", "first", "(", ")", ".", "shape", "shape", "=", "self", ".", "_rdd", ".", "map", "(", "lambda", "x", ":", "x", ".", "shape", "[", "0", "]", ")", ".", "sum", "(", ...
0498502107c1f7dcf33cda0cdb6f5ba4b42524b7
test
SparseRDD.toarray
Returns the data as numpy.array from each partition.
splearn/rdd.py
def toarray(self): """Returns the data as numpy.array from each partition.""" rdd = self._rdd.map(lambda x: x.toarray()) return np.concatenate(rdd.collect())
def toarray(self): """Returns the data as numpy.array from each partition.""" rdd = self._rdd.map(lambda x: x.toarray()) return np.concatenate(rdd.collect())
[ "Returns", "the", "data", "as", "numpy", ".", "array", "from", "each", "partition", "." ]
lensacom/sparkit-learn
python
https://github.com/lensacom/sparkit-learn/blob/0498502107c1f7dcf33cda0cdb6f5ba4b42524b7/splearn/rdd.py#L491-L494
[ "def", "toarray", "(", "self", ")", ":", "rdd", "=", "self", ".", "_rdd", ".", "map", "(", "lambda", "x", ":", "x", ".", "toarray", "(", ")", ")", "return", "np", ".", "concatenate", "(", "rdd", ".", "collect", "(", ")", ")" ]
0498502107c1f7dcf33cda0cdb6f5ba4b42524b7
test
DictRDD._block
Execute the blocking process on the given rdd. Parameters ---------- rdd : pyspark.rdd.RDD Distributed data to block bsize : int or None The desired size of the blocks Returns ------- rdd : pyspark.rdd.RDD Blocked rdd.
splearn/rdd.py
def _block(self, rdd, bsize, dtype): """Execute the blocking process on the given rdd. Parameters ---------- rdd : pyspark.rdd.RDD Distributed data to block bsize : int or None The desired size of the blocks Returns ------- rdd : ...
def _block(self, rdd, bsize, dtype): """Execute the blocking process on the given rdd. Parameters ---------- rdd : pyspark.rdd.RDD Distributed data to block bsize : int or None The desired size of the blocks Returns ------- rdd : ...
[ "Execute", "the", "blocking", "process", "on", "the", "given", "rdd", "." ]
lensacom/sparkit-learn
python
https://github.com/lensacom/sparkit-learn/blob/0498502107c1f7dcf33cda0cdb6f5ba4b42524b7/splearn/rdd.py#L625-L640
[ "def", "_block", "(", "self", ",", "rdd", ",", "bsize", ",", "dtype", ")", ":", "return", "rdd", ".", "mapPartitions", "(", "lambda", "x", ":", "_block_tuple", "(", "x", ",", "dtype", ",", "bsize", ")", ")" ]
0498502107c1f7dcf33cda0cdb6f5ba4b42524b7
test
DictRDD.transform
Execute a transformation on a column or columns. Returns the modified DictRDD. Parameters ---------- f : function The function to execute on the columns. column : {str, list or None} The column(s) to transform. If None is specified the method is ...
splearn/rdd.py
def transform(self, fn, column=None, dtype=None): """Execute a transformation on a column or columns. Returns the modified DictRDD. Parameters ---------- f : function The function to execute on the columns. column : {str, list or None} The column(...
def transform(self, fn, column=None, dtype=None): """Execute a transformation on a column or columns. Returns the modified DictRDD. Parameters ---------- f : function The function to execute on the columns. column : {str, list or None} The column(...
[ "Execute", "a", "transformation", "on", "a", "column", "or", "columns", ".", "Returns", "the", "modified", "DictRDD", "." ]
lensacom/sparkit-learn
python
https://github.com/lensacom/sparkit-learn/blob/0498502107c1f7dcf33cda0cdb6f5ba4b42524b7/splearn/rdd.py#L716-L768
[ "def", "transform", "(", "self", ",", "fn", ",", "column", "=", "None", ",", "dtype", "=", "None", ")", ":", "dtypes", "=", "self", ".", "dtype", "if", "column", "is", "None", ":", "indices", "=", "list", "(", "range", "(", "len", "(", "self", "....
0498502107c1f7dcf33cda0cdb6f5ba4b42524b7
test
bitperm
Returns zero if there are no permissions for a bit of the perm. of a file. Otherwise it returns a positive value :param os.stat_result s: os.stat(file) object :param str perm: R (Read) or W (Write) or X (eXecute) :param str pos: USR (USeR) or GRP (GRouP) or OTH (OTHer) :return: mask value :rtype: i...
amazon_dash/config.py
def bitperm(s, perm, pos): """Returns zero if there are no permissions for a bit of the perm. of a file. Otherwise it returns a positive value :param os.stat_result s: os.stat(file) object :param str perm: R (Read) or W (Write) or X (eXecute) :param str pos: USR (USeR) or GRP (GRouP) or OTH (OTHer) ...
def bitperm(s, perm, pos): """Returns zero if there are no permissions for a bit of the perm. of a file. Otherwise it returns a positive value :param os.stat_result s: os.stat(file) object :param str perm: R (Read) or W (Write) or X (eXecute) :param str pos: USR (USeR) or GRP (GRouP) or OTH (OTHer) ...
[ "Returns", "zero", "if", "there", "are", "no", "permissions", "for", "a", "bit", "of", "the", "perm", ".", "of", "a", "file", ".", "Otherwise", "it", "returns", "a", "positive", "value" ]
Nekmo/amazon-dash
python
https://github.com/Nekmo/amazon-dash/blob/0e2bdc24ff8ea32cecb2f5f54f5cc1c0f99c197b/amazon_dash/config.py#L159-L172
[ "def", "bitperm", "(", "s", ",", "perm", ",", "pos", ")", ":", "perm", "=", "perm", ".", "upper", "(", ")", "pos", "=", "pos", ".", "upper", "(", ")", "assert", "perm", "in", "[", "'R'", ",", "'W'", ",", "'X'", "]", "assert", "pos", "in", "["...
0e2bdc24ff8ea32cecb2f5f54f5cc1c0f99c197b
test
only_root_write
File is only writable by root :param str path: Path to file :return: True if only root can write :rtype: bool
amazon_dash/config.py
def only_root_write(path): """File is only writable by root :param str path: Path to file :return: True if only root can write :rtype: bool """ s = os.stat(path) for ug, bp in [(s.st_uid, bitperm(s, 'w', 'usr')), (s.st_gid, bitperm(s, 'w', 'grp'))]: # User id (is not root) and bit p...
def only_root_write(path): """File is only writable by root :param str path: Path to file :return: True if only root can write :rtype: bool """ s = os.stat(path) for ug, bp in [(s.st_uid, bitperm(s, 'w', 'usr')), (s.st_gid, bitperm(s, 'w', 'grp'))]: # User id (is not root) and bit p...
[ "File", "is", "only", "writable", "by", "root" ]
Nekmo/amazon-dash
python
https://github.com/Nekmo/amazon-dash/blob/0e2bdc24ff8ea32cecb2f5f54f5cc1c0f99c197b/amazon_dash/config.py#L185-L199
[ "def", "only_root_write", "(", "path", ")", ":", "s", "=", "os", ".", "stat", "(", "path", ")", "for", "ug", ",", "bp", "in", "[", "(", "s", ".", "st_uid", ",", "bitperm", "(", "s", ",", "'w'", ",", "'usr'", ")", ")", ",", "(", "s", ".", "s...
0e2bdc24ff8ea32cecb2f5f54f5cc1c0f99c197b
test
check_config
Command to check configuration file. Raises InvalidConfig on error :param str file: path to config file :param printfn: print function for success message :return: None
amazon_dash/config.py
def check_config(file, printfn=print): """Command to check configuration file. Raises InvalidConfig on error :param str file: path to config file :param printfn: print function for success message :return: None """ Config(file).read() printfn('The configuration file "{}" is correct'.format(...
def check_config(file, printfn=print): """Command to check configuration file. Raises InvalidConfig on error :param str file: path to config file :param printfn: print function for success message :return: None """ Config(file).read() printfn('The configuration file "{}" is correct'.format(...
[ "Command", "to", "check", "configuration", "file", ".", "Raises", "InvalidConfig", "on", "error" ]
Nekmo/amazon-dash
python
https://github.com/Nekmo/amazon-dash/blob/0e2bdc24ff8ea32cecb2f5f54f5cc1c0f99c197b/amazon_dash/config.py#L243-L251
[ "def", "check_config", "(", "file", ",", "printfn", "=", "print", ")", ":", "Config", "(", "file", ")", ".", "read", "(", ")", "printfn", "(", "'The configuration file \"{}\" is correct'", ".", "format", "(", "file", ")", ")" ]
0e2bdc24ff8ea32cecb2f5f54f5cc1c0f99c197b
test
Config.read
Parse and validate the config file. The read data is accessible as a dictionary in this instance :return: None
amazon_dash/config.py
def read(self): """Parse and validate the config file. The read data is accessible as a dictionary in this instance :return: None """ try: data = load(open(self.file), Loader) except (UnicodeDecodeError, YAMLError) as e: raise InvalidConfig(self.file, '{}...
def read(self): """Parse and validate the config file. The read data is accessible as a dictionary in this instance :return: None """ try: data = load(open(self.file), Loader) except (UnicodeDecodeError, YAMLError) as e: raise InvalidConfig(self.file, '{}...
[ "Parse", "and", "validate", "the", "config", "file", ".", "The", "read", "data", "is", "accessible", "as", "a", "dictionary", "in", "this", "instance" ]
Nekmo/amazon-dash
python
https://github.com/Nekmo/amazon-dash/blob/0e2bdc24ff8ea32cecb2f5f54f5cc1c0f99c197b/amazon_dash/config.py#L227-L240
[ "def", "read", "(", "self", ")", ":", "try", ":", "data", "=", "load", "(", "open", "(", "self", ".", "file", ")", ",", "Loader", ")", "except", "(", "UnicodeDecodeError", ",", "YAMLError", ")", "as", "e", ":", "raise", "InvalidConfig", "(", "self", ...
0e2bdc24ff8ea32cecb2f5f54f5cc1c0f99c197b
test
run_as_cmd
Get the arguments to execute a command as a user :param str cmd: command to execute :param user: User for use :param shell: Bash, zsh, etc. :return: arguments :rtype: list
amazon_dash/execute.py
def run_as_cmd(cmd, user, shell='bash'): """Get the arguments to execute a command as a user :param str cmd: command to execute :param user: User for use :param shell: Bash, zsh, etc. :return: arguments :rtype: list """ to_execute = get_shell(shell) + [EXECUTE_SHELL_PARAM, cmd] if u...
def run_as_cmd(cmd, user, shell='bash'): """Get the arguments to execute a command as a user :param str cmd: command to execute :param user: User for use :param shell: Bash, zsh, etc. :return: arguments :rtype: list """ to_execute = get_shell(shell) + [EXECUTE_SHELL_PARAM, cmd] if u...
[ "Get", "the", "arguments", "to", "execute", "a", "command", "as", "a", "user" ]
Nekmo/amazon-dash
python
https://github.com/Nekmo/amazon-dash/blob/0e2bdc24ff8ea32cecb2f5f54f5cc1c0f99c197b/amazon_dash/execute.py#L39-L51
[ "def", "run_as_cmd", "(", "cmd", ",", "user", ",", "shell", "=", "'bash'", ")", ":", "to_execute", "=", "get_shell", "(", "shell", ")", "+", "[", "EXECUTE_SHELL_PARAM", ",", "cmd", "]", "if", "user", "==", "'root'", ":", "return", "to_execute", "return",...
0e2bdc24ff8ea32cecb2f5f54f5cc1c0f99c197b
test
execute_cmd
Excecute command on thread :param cmd: Command to execute :param cwd: current working directory :return: None
amazon_dash/execute.py
def execute_cmd(cmd, cwd=None, timeout=5): """Excecute command on thread :param cmd: Command to execute :param cwd: current working directory :return: None """ p = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) try: p.wait(timeout=timeout) except ...
def execute_cmd(cmd, cwd=None, timeout=5): """Excecute command on thread :param cmd: Command to execute :param cwd: current working directory :return: None """ p = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) try: p.wait(timeout=timeout) except ...
[ "Excecute", "command", "on", "thread" ]
Nekmo/amazon-dash
python
https://github.com/Nekmo/amazon-dash/blob/0e2bdc24ff8ea32cecb2f5f54f5cc1c0f99c197b/amazon_dash/execute.py#L54-L75
[ "def", "execute_cmd", "(", "cmd", ",", "cwd", "=", "None", ",", "timeout", "=", "5", ")", ":", "p", "=", "subprocess", ".", "Popen", "(", "cmd", ",", "cwd", "=", "cwd", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess"...
0e2bdc24ff8ea32cecb2f5f54f5cc1c0f99c197b
test
execute_over_ssh
Excecute command on remote machine using SSH :param cmd: Command to execute :param ssh: Server to connect. Port is optional :param cwd: current working directory :return: None
amazon_dash/execute.py
def execute_over_ssh(cmd, ssh, cwd=None, shell='bash'): """Excecute command on remote machine using SSH :param cmd: Command to execute :param ssh: Server to connect. Port is optional :param cwd: current working directory :return: None """ port = None parts = ssh.split(':', 1) if len...
def execute_over_ssh(cmd, ssh, cwd=None, shell='bash'): """Excecute command on remote machine using SSH :param cmd: Command to execute :param ssh: Server to connect. Port is optional :param cwd: current working directory :return: None """ port = None parts = ssh.split(':', 1) if len...
[ "Excecute", "command", "on", "remote", "machine", "using", "SSH" ]
Nekmo/amazon-dash
python
https://github.com/Nekmo/amazon-dash/blob/0e2bdc24ff8ea32cecb2f5f54f5cc1c0f99c197b/amazon_dash/execute.py#L78-L97
[ "def", "execute_over_ssh", "(", "cmd", ",", "ssh", ",", "cwd", "=", "None", ",", "shell", "=", "'bash'", ")", ":", "port", "=", "None", "parts", "=", "ssh", ".", "split", "(", "':'", ",", "1", ")", "if", "len", "(", "parts", ")", ">", "1", "and...
0e2bdc24ff8ea32cecb2f5f54f5cc1c0f99c197b
test
ExecuteCmd.execute
Execute using self.data :param bool root_allowed: Allow execute as root commands :return:
amazon_dash/execute.py
def execute(self, root_allowed=False): """Execute using self.data :param bool root_allowed: Allow execute as root commands :return: """ if self.user == ROOT_USER and not root_allowed and not self.data.get('ssh'): raise SecurityException('For security, execute command...
def execute(self, root_allowed=False): """Execute using self.data :param bool root_allowed: Allow execute as root commands :return: """ if self.user == ROOT_USER and not root_allowed and not self.data.get('ssh'): raise SecurityException('For security, execute command...
[ "Execute", "using", "self", ".", "data" ]
Nekmo/amazon-dash
python
https://github.com/Nekmo/amazon-dash/blob/0e2bdc24ff8ea32cecb2f5f54f5cc1c0f99c197b/amazon_dash/execute.py#L151-L172
[ "def", "execute", "(", "self", ",", "root_allowed", "=", "False", ")", ":", "if", "self", ".", "user", "==", "ROOT_USER", "and", "not", "root_allowed", "and", "not", "self", ".", "data", ".", "get", "(", "'ssh'", ")", ":", "raise", "SecurityException", ...
0e2bdc24ff8ea32cecb2f5f54f5cc1c0f99c197b
test
ExecuteUrl.validate
Check self.data. Raise InvalidConfig on error :return: None
amazon_dash/execute.py
def validate(self): """Check self.data. Raise InvalidConfig on error :return: None """ if (self.data.get('content-type') or self.data.get('body')) and \ self.data.get('method', '').lower() not in CONTENT_TYPE_METHODS: raise InvalidConfig( extr...
def validate(self): """Check self.data. Raise InvalidConfig on error :return: None """ if (self.data.get('content-type') or self.data.get('body')) and \ self.data.get('method', '').lower() not in CONTENT_TYPE_METHODS: raise InvalidConfig( extr...
[ "Check", "self", ".", "data", ".", "Raise", "InvalidConfig", "on", "error" ]
Nekmo/amazon-dash
python
https://github.com/Nekmo/amazon-dash/blob/0e2bdc24ff8ea32cecb2f5f54f5cc1c0f99c197b/amazon_dash/execute.py#L179-L199
[ "def", "validate", "(", "self", ")", ":", "if", "(", "self", ".", "data", ".", "get", "(", "'content-type'", ")", "or", "self", ".", "data", ".", "get", "(", "'body'", ")", ")", "and", "self", ".", "data", ".", "get", "(", "'method'", ",", "''", ...
0e2bdc24ff8ea32cecb2f5f54f5cc1c0f99c197b
test
ExecuteUrl.execute
Execute using self.data :param bool root_allowed: Only used for ExecuteCmd :return:
amazon_dash/execute.py
def execute(self, root_allowed=False): """Execute using self.data :param bool root_allowed: Only used for ExecuteCmd :return: """ kwargs = {'stream': True, 'timeout': 15, 'headers': self.data.get('headers', {})} if self.data.get('content-type'): ...
def execute(self, root_allowed=False): """Execute using self.data :param bool root_allowed: Only used for ExecuteCmd :return: """ kwargs = {'stream': True, 'timeout': 15, 'headers': self.data.get('headers', {})} if self.data.get('content-type'): ...
[ "Execute", "using", "self", ".", "data" ]
Nekmo/amazon-dash
python
https://github.com/Nekmo/amazon-dash/blob/0e2bdc24ff8ea32cecb2f5f54f5cc1c0f99c197b/amazon_dash/execute.py#L201-L226
[ "def", "execute", "(", "self", ",", "root_allowed", "=", "False", ")", ":", "kwargs", "=", "{", "'stream'", ":", "True", ",", "'timeout'", ":", "15", ",", "'headers'", ":", "self", ".", "data", ".", "get", "(", "'headers'", ",", "{", "}", ")", "}",...
0e2bdc24ff8ea32cecb2f5f54f5cc1c0f99c197b
test
ExecuteUrlServiceBase.get_headers
Get HTTP Headers to send. By default default_headers :return: HTTP Headers :rtype: dict
amazon_dash/execute.py
def get_headers(self): """Get HTTP Headers to send. By default default_headers :return: HTTP Headers :rtype: dict """ headers = copy.copy(self.default_headers or {}) headers.update(self.data.get('headers') or {}) return headers
def get_headers(self): """Get HTTP Headers to send. By default default_headers :return: HTTP Headers :rtype: dict """ headers = copy.copy(self.default_headers or {}) headers.update(self.data.get('headers') or {}) return headers
[ "Get", "HTTP", "Headers", "to", "send", ".", "By", "default", "default_headers" ]
Nekmo/amazon-dash
python
https://github.com/Nekmo/amazon-dash/blob/0e2bdc24ff8ea32cecb2f5f54f5cc1c0f99c197b/amazon_dash/execute.py#L275-L283
[ "def", "get_headers", "(", "self", ")", ":", "headers", "=", "copy", ".", "copy", "(", "self", ".", "default_headers", "or", "{", "}", ")", "headers", ".", "update", "(", "self", ".", "data", ".", "get", "(", "'headers'", ")", "or", "{", "}", ")", ...
0e2bdc24ff8ea32cecb2f5f54f5cc1c0f99c197b
test
ExecuteOwnApiBase.get_url
API url :return: url :rtype: str
amazon_dash/execute.py
def get_url(self): """API url :return: url :rtype: str """ url = self.data[self.execute_name] parsed = urlparse(url) if not parsed.scheme: url = '{}://{}'.format(self.default_protocol, url) if not url.split(':')[-1].isalnum(): url ...
def get_url(self): """API url :return: url :rtype: str """ url = self.data[self.execute_name] parsed = urlparse(url) if not parsed.scheme: url = '{}://{}'.format(self.default_protocol, url) if not url.split(':')[-1].isalnum(): url ...
[ "API", "url" ]
Nekmo/amazon-dash
python
https://github.com/Nekmo/amazon-dash/blob/0e2bdc24ff8ea32cecb2f5f54f5cc1c0f99c197b/amazon_dash/execute.py#L300-L312
[ "def", "get_url", "(", "self", ")", ":", "url", "=", "self", ".", "data", "[", "self", ".", "execute_name", "]", "parsed", "=", "urlparse", "(", "url", ")", "if", "not", "parsed", ".", "scheme", ":", "url", "=", "'{}://{}'", ".", "format", "(", "se...
0e2bdc24ff8ea32cecb2f5f54f5cc1c0f99c197b
test
ExecuteOwnApiBase.get_body
Return "data" value on self.data :return: data to send :rtype: str
amazon_dash/execute.py
def get_body(self): """Return "data" value on self.data :return: data to send :rtype: str """ if self.default_body: return self.default_body data = self.data.get('data') if isinstance(data, dict): return json.dumps(data) return dat...
def get_body(self): """Return "data" value on self.data :return: data to send :rtype: str """ if self.default_body: return self.default_body data = self.data.get('data') if isinstance(data, dict): return json.dumps(data) return dat...
[ "Return", "data", "value", "on", "self", ".", "data" ]
Nekmo/amazon-dash
python
https://github.com/Nekmo/amazon-dash/blob/0e2bdc24ff8ea32cecb2f5f54f5cc1c0f99c197b/amazon_dash/execute.py#L314-L325
[ "def", "get_body", "(", "self", ")", ":", "if", "self", ".", "default_body", ":", "return", "self", ".", "default_body", "data", "=", "self", ".", "data", ".", "get", "(", "'data'", ")", "if", "isinstance", "(", "data", ",", "dict", ")", ":", "return...
0e2bdc24ff8ea32cecb2f5f54f5cc1c0f99c197b
test
ExecuteHomeAssistant.get_url
Home assistant url :return: url :rtype: str
amazon_dash/execute.py
def get_url(self): """Home assistant url :return: url :rtype: str """ url = super(ExecuteHomeAssistant, self).get_url() if not self.data.get('event'): raise InvalidConfig(extra_body='Event option is required for HomeAsistant on {} device.'.format(self.name)) ...
def get_url(self): """Home assistant url :return: url :rtype: str """ url = super(ExecuteHomeAssistant, self).get_url() if not self.data.get('event'): raise InvalidConfig(extra_body='Event option is required for HomeAsistant on {} device.'.format(self.name)) ...
[ "Home", "assistant", "url" ]
Nekmo/amazon-dash
python
https://github.com/Nekmo/amazon-dash/blob/0e2bdc24ff8ea32cecb2f5f54f5cc1c0f99c197b/amazon_dash/execute.py#L336-L346
[ "def", "get_url", "(", "self", ")", ":", "url", "=", "super", "(", "ExecuteHomeAssistant", ",", "self", ")", ".", "get_url", "(", ")", "if", "not", "self", ".", "data", ".", "get", "(", "'event'", ")", ":", "raise", "InvalidConfig", "(", "extra_body", ...
0e2bdc24ff8ea32cecb2f5f54f5cc1c0f99c197b
test
ExecuteIFTTT.get_url
IFTTT Webhook url :return: url :rtype: str
amazon_dash/execute.py
def get_url(self): """IFTTT Webhook url :return: url :rtype: str """ if not self.data[self.execute_name]: raise InvalidConfig(extra_body='Value for IFTTT is required on {} device. Get your key here: ' 'https://ifttt.com/serv...
def get_url(self): """IFTTT Webhook url :return: url :rtype: str """ if not self.data[self.execute_name]: raise InvalidConfig(extra_body='Value for IFTTT is required on {} device. Get your key here: ' 'https://ifttt.com/serv...
[ "IFTTT", "Webhook", "url" ]
Nekmo/amazon-dash
python
https://github.com/Nekmo/amazon-dash/blob/0e2bdc24ff8ea32cecb2f5f54f5cc1c0f99c197b/amazon_dash/execute.py#L392-L406
[ "def", "get_url", "(", "self", ")", ":", "if", "not", "self", ".", "data", "[", "self", ".", "execute_name", "]", ":", "raise", "InvalidConfig", "(", "extra_body", "=", "'Value for IFTTT is required on {} device. Get your key here: '", "'https://ifttt.com/services/maker...
0e2bdc24ff8ea32cecb2f5f54f5cc1c0f99c197b
test
pkt_text
Return source mac address for this Scapy Packet :param scapy.packet.Packet pkt: Scapy Packet :return: Mac address. Include (Amazon Device) for these devices :rtype: str
amazon_dash/discovery.py
def pkt_text(pkt): """Return source mac address for this Scapy Packet :param scapy.packet.Packet pkt: Scapy Packet :return: Mac address. Include (Amazon Device) for these devices :rtype: str """ if pkt.src.upper() in BANNED_DEVICES: body = '' elif pkt.src.upper()[:8] in AMAZON_DEVIC...
def pkt_text(pkt): """Return source mac address for this Scapy Packet :param scapy.packet.Packet pkt: Scapy Packet :return: Mac address. Include (Amazon Device) for these devices :rtype: str """ if pkt.src.upper() in BANNED_DEVICES: body = '' elif pkt.src.upper()[:8] in AMAZON_DEVIC...
[ "Return", "source", "mac", "address", "for", "this", "Scapy", "Packet" ]
Nekmo/amazon-dash
python
https://github.com/Nekmo/amazon-dash/blob/0e2bdc24ff8ea32cecb2f5f54f5cc1c0f99c197b/amazon_dash/discovery.py#L62-L75
[ "def", "pkt_text", "(", "pkt", ")", ":", "if", "pkt", ".", "src", ".", "upper", "(", ")", "in", "BANNED_DEVICES", ":", "body", "=", "''", "elif", "pkt", ".", "src", ".", "upper", "(", ")", "[", ":", "8", "]", "in", "AMAZON_DEVICES", ":", "body", ...
0e2bdc24ff8ea32cecb2f5f54f5cc1c0f99c197b
test
discovery_print
Scandevice callback. Register src mac to avoid src repetition. Print device on screen. :param scapy.packet.Packet pkt: Scapy Packet :return: None
amazon_dash/discovery.py
def discovery_print(pkt): """Scandevice callback. Register src mac to avoid src repetition. Print device on screen. :param scapy.packet.Packet pkt: Scapy Packet :return: None """ if pkt.src in mac_id_list: return mac_id_list.append(pkt.src) text = pkt_text(pkt) click.secho(t...
def discovery_print(pkt): """Scandevice callback. Register src mac to avoid src repetition. Print device on screen. :param scapy.packet.Packet pkt: Scapy Packet :return: None """ if pkt.src in mac_id_list: return mac_id_list.append(pkt.src) text = pkt_text(pkt) click.secho(t...
[ "Scandevice", "callback", ".", "Register", "src", "mac", "to", "avoid", "src", "repetition", ".", "Print", "device", "on", "screen", "." ]
Nekmo/amazon-dash
python
https://github.com/Nekmo/amazon-dash/blob/0e2bdc24ff8ea32cecb2f5f54f5cc1c0f99c197b/amazon_dash/discovery.py#L78-L89
[ "def", "discovery_print", "(", "pkt", ")", ":", "if", "pkt", ".", "src", "in", "mac_id_list", ":", "return", "mac_id_list", ".", "append", "(", "pkt", ".", "src", ")", "text", "=", "pkt_text", "(", "pkt", ")", "click", ".", "secho", "(", "text", ",",...
0e2bdc24ff8ea32cecb2f5f54f5cc1c0f99c197b
test
discover
Print help and scan devices on screen. :return: None
amazon_dash/discovery.py
def discover(interface=None): """Print help and scan devices on screen. :return: None """ click.secho(HELP, fg='yellow') scan_devices(discovery_print, lfilter=lambda d: d.src not in mac_id_list, iface=interface)
def discover(interface=None): """Print help and scan devices on screen. :return: None """ click.secho(HELP, fg='yellow') scan_devices(discovery_print, lfilter=lambda d: d.src not in mac_id_list, iface=interface)
[ "Print", "help", "and", "scan", "devices", "on", "screen", "." ]
Nekmo/amazon-dash
python
https://github.com/Nekmo/amazon-dash/blob/0e2bdc24ff8ea32cecb2f5f54f5cc1c0f99c197b/amazon_dash/discovery.py#L92-L98
[ "def", "discover", "(", "interface", "=", "None", ")", ":", "click", ".", "secho", "(", "HELP", ",", "fg", "=", "'yellow'", ")", "scan_devices", "(", "discovery_print", ",", "lfilter", "=", "lambda", "d", ":", "d", ".", "src", "not", "in", "mac_id_list...
0e2bdc24ff8ea32cecb2f5f54f5cc1c0f99c197b
test
Device.execute
Execute this device :param bool root_allowed: Only used for ExecuteCmd :return: None
amazon_dash/listener.py
def execute(self, root_allowed=False): """Execute this device :param bool root_allowed: Only used for ExecuteCmd :return: None """ logger.debug('%s device executed (mac %s)', self.name, self.src) if not self.execute_instance: msg = '%s: There is not execution...
def execute(self, root_allowed=False): """Execute this device :param bool root_allowed: Only used for ExecuteCmd :return: None """ logger.debug('%s device executed (mac %s)', self.name, self.src) if not self.execute_instance: msg = '%s: There is not execution...
[ "Execute", "this", "device" ]
Nekmo/amazon-dash
python
https://github.com/Nekmo/amazon-dash/blob/0e2bdc24ff8ea32cecb2f5f54f5cc1c0f99c197b/amazon_dash/listener.py#L71-L93
[ "def", "execute", "(", "self", ",", "root_allowed", "=", "False", ")", ":", "logger", ".", "debug", "(", "'%s device executed (mac %s)'", ",", "self", ".", "name", ",", "self", ".", "src", ")", "if", "not", "self", ".", "execute_instance", ":", "msg", "=...
0e2bdc24ff8ea32cecb2f5f54f5cc1c0f99c197b
test
Device.send_confirmation
Send success or error message to configured confirmation :param str message: Body message to send :param bool success: Device executed successfully to personalize message :return: None
amazon_dash/listener.py
def send_confirmation(self, message, success=True): """Send success or error message to configured confirmation :param str message: Body message to send :param bool success: Device executed successfully to personalize message :return: None """ message = message.strip() ...
def send_confirmation(self, message, success=True): """Send success or error message to configured confirmation :param str message: Body message to send :param bool success: Device executed successfully to personalize message :return: None """ message = message.strip() ...
[ "Send", "success", "or", "error", "message", "to", "configured", "confirmation" ]
Nekmo/amazon-dash
python
https://github.com/Nekmo/amazon-dash/blob/0e2bdc24ff8ea32cecb2f5f54f5cc1c0f99c197b/amazon_dash/listener.py#L95-L108
[ "def", "send_confirmation", "(", "self", ",", "message", ",", "success", "=", "True", ")", ":", "message", "=", "message", ".", "strip", "(", ")", "if", "not", "self", ".", "confirmation", ":", "return", "try", ":", "self", ".", "confirmation", ".", "s...
0e2bdc24ff8ea32cecb2f5f54f5cc1c0f99c197b
test
Listener.on_push
Press button. Check DEFAULT_DELAY. :param scapy.packet.Packet device: Scapy packet :return: None
amazon_dash/listener.py
def on_push(self, device): """Press button. Check DEFAULT_DELAY. :param scapy.packet.Packet device: Scapy packet :return: None """ src = device.src.lower() if last_execution[src] + self.settings.get('delay', DEFAULT_DELAY) > time.time(): return last_e...
def on_push(self, device): """Press button. Check DEFAULT_DELAY. :param scapy.packet.Packet device: Scapy packet :return: None """ src = device.src.lower() if last_execution[src] + self.settings.get('delay', DEFAULT_DELAY) > time.time(): return last_e...
[ "Press", "button", ".", "Check", "DEFAULT_DELAY", "." ]
Nekmo/amazon-dash
python
https://github.com/Nekmo/amazon-dash/blob/0e2bdc24ff8ea32cecb2f5f54f5cc1c0f99c197b/amazon_dash/listener.py#L128-L138
[ "def", "on_push", "(", "self", ",", "device", ")", ":", "src", "=", "device", ".", "src", ".", "lower", "(", ")", "if", "last_execution", "[", "src", "]", "+", "self", ".", "settings", ".", "get", "(", "'delay'", ",", "DEFAULT_DELAY", ")", ">", "ti...
0e2bdc24ff8ea32cecb2f5f54f5cc1c0f99c197b
test
Listener.execute
Execute a device. Used if the time between executions is greater than DEFAULT_DELAY :param scapy.packet.Packet device: Scapy packet :return: None
amazon_dash/listener.py
def execute(self, device): """Execute a device. Used if the time between executions is greater than DEFAULT_DELAY :param scapy.packet.Packet device: Scapy packet :return: None """ src = device.src.lower() device = self.devices[src] threading.Thread(target=device....
def execute(self, device): """Execute a device. Used if the time between executions is greater than DEFAULT_DELAY :param scapy.packet.Packet device: Scapy packet :return: None """ src = device.src.lower() device = self.devices[src] threading.Thread(target=device....
[ "Execute", "a", "device", ".", "Used", "if", "the", "time", "between", "executions", "is", "greater", "than", "DEFAULT_DELAY" ]
Nekmo/amazon-dash
python
https://github.com/Nekmo/amazon-dash/blob/0e2bdc24ff8ea32cecb2f5f54f5cc1c0f99c197b/amazon_dash/listener.py#L140-L150
[ "def", "execute", "(", "self", ",", "device", ")", ":", "src", "=", "device", ".", "src", ".", "lower", "(", ")", "device", "=", "self", ".", "devices", "[", "src", "]", "threading", ".", "Thread", "(", "target", "=", "device", ".", "execute", ",",...
0e2bdc24ff8ea32cecb2f5f54f5cc1c0f99c197b
test
Listener.run
Start daemon mode :param bool root_allowed: Only used for ExecuteCmd :return: loop
amazon_dash/listener.py
def run(self, root_allowed=False): """Start daemon mode :param bool root_allowed: Only used for ExecuteCmd :return: loop """ self.root_allowed = root_allowed scan_devices(self.on_push, lambda d: d.src.lower() in self.devices, self.settings.get('interface'))
def run(self, root_allowed=False): """Start daemon mode :param bool root_allowed: Only used for ExecuteCmd :return: loop """ self.root_allowed = root_allowed scan_devices(self.on_push, lambda d: d.src.lower() in self.devices, self.settings.get('interface'))
[ "Start", "daemon", "mode" ]
Nekmo/amazon-dash
python
https://github.com/Nekmo/amazon-dash/blob/0e2bdc24ff8ea32cecb2f5f54f5cc1c0f99c197b/amazon_dash/listener.py#L152-L159
[ "def", "run", "(", "self", ",", "root_allowed", "=", "False", ")", ":", "self", ".", "root_allowed", "=", "root_allowed", "scan_devices", "(", "self", ".", "on_push", ",", "lambda", "d", ":", "d", ".", "src", ".", "lower", "(", ")", "in", "self", "."...
0e2bdc24ff8ea32cecb2f5f54f5cc1c0f99c197b
test
scan_devices
Sniff packages :param fn: callback on packet :param lfilter: filter packages :return: loop
amazon_dash/scan.py
def scan_devices(fn, lfilter, iface=None): """Sniff packages :param fn: callback on packet :param lfilter: filter packages :return: loop """ try: sniff(prn=fn, store=0, # filter="udp", filter="arp or (udp and src port 68 and dst port 67 and src host 0.0.0.0)"...
def scan_devices(fn, lfilter, iface=None): """Sniff packages :param fn: callback on packet :param lfilter: filter packages :return: loop """ try: sniff(prn=fn, store=0, # filter="udp", filter="arp or (udp and src port 68 and dst port 67 and src host 0.0.0.0)"...
[ "Sniff", "packages" ]
Nekmo/amazon-dash
python
https://github.com/Nekmo/amazon-dash/blob/0e2bdc24ff8ea32cecb2f5f54f5cc1c0f99c197b/amazon_dash/scan.py#L16-L29
[ "def", "scan_devices", "(", "fn", ",", "lfilter", ",", "iface", "=", "None", ")", ":", "try", ":", "sniff", "(", "prn", "=", "fn", ",", "store", "=", "0", ",", "# filter=\"udp\",", "filter", "=", "\"arp or (udp and src port 68 and dst port 67 and src host 0.0.0....
0e2bdc24ff8ea32cecb2f5f54f5cc1c0f99c197b
test
open_url
Loads a web page in the current browser session. :param absolgenerateute_or_relative_url: an absolute url to web page in case of config.base_url is not specified, otherwise - relative url correspondingly :Usage: open_url('http://mydomain.com/subpage1') open_url('http://mydomain....
selene/browser.py
def open_url(absolute_or_relative_url): """ Loads a web page in the current browser session. :param absolgenerateute_or_relative_url: an absolute url to web page in case of config.base_url is not specified, otherwise - relative url correspondingly :Usage: open_url('http://mydoma...
def open_url(absolute_or_relative_url): """ Loads a web page in the current browser session. :param absolgenerateute_or_relative_url: an absolute url to web page in case of config.base_url is not specified, otherwise - relative url correspondingly :Usage: open_url('http://mydoma...
[ "Loads", "a", "web", "page", "in", "the", "current", "browser", "session", ".", ":", "param", "absolgenerateute_or_relative_url", ":", "an", "absolute", "url", "to", "web", "page", "in", "case", "of", "config", ".", "base_url", "is", "not", "specified", "oth...
yashaka/selene
python
https://github.com/yashaka/selene/blob/123d6142047c3f0a9f0a67da6be0b916e630fd6a/selene/browser.py#L38-L55
[ "def", "open_url", "(", "absolute_or_relative_url", ")", ":", "# todo: refactor next line when app_host is removed", "base_url", "=", "selene", ".", "config", ".", "app_host", "if", "selene", ".", "config", ".", "app_host", "else", "selene", ".", "config", ".", "bas...
123d6142047c3f0a9f0a67da6be0b916e630fd6a
test
OfxConverter.convert
Convert an OFX Transaction to a posting
ledgerautosync/converter.py
def convert(self, txn): """ Convert an OFX Transaction to a posting """ ofxid = self.mk_ofxid(txn.id) metadata = {} posting_metadata = {"ofxid": ofxid} if isinstance(txn, OfxTransaction): posting = Posting(self.name, Amo...
def convert(self, txn): """ Convert an OFX Transaction to a posting """ ofxid = self.mk_ofxid(txn.id) metadata = {} posting_metadata = {"ofxid": ofxid} if isinstance(txn, OfxTransaction): posting = Posting(self.name, Amo...
[ "Convert", "an", "OFX", "Transaction", "to", "a", "posting" ]
egh/ledger-autosync
python
https://github.com/egh/ledger-autosync/blob/7a303f3a693261d10f677c01fb08f35c105a1e1b/ledgerautosync/converter.py#L403-L507
[ "def", "convert", "(", "self", ",", "txn", ")", ":", "ofxid", "=", "self", ".", "mk_ofxid", "(", "txn", ".", "id", ")", "metadata", "=", "{", "}", "posting_metadata", "=", "{", "\"ofxid\"", ":", "ofxid", "}", "if", "isinstance", "(", "txn", ",", "O...
7a303f3a693261d10f677c01fb08f35c105a1e1b
test
find_ledger_file
Returns main ledger file path or raise exception if it cannot be \ found.
ledgerautosync/cli.py
def find_ledger_file(ledgerrcpath=None): """Returns main ledger file path or raise exception if it cannot be \ found.""" if ledgerrcpath is None: ledgerrcpath = os.path.abspath(os.path.expanduser("~/.ledgerrc")) if "LEDGER_FILE" in os.environ: return os.path.abspath(os.path.expanduser(os.env...
def find_ledger_file(ledgerrcpath=None): """Returns main ledger file path or raise exception if it cannot be \ found.""" if ledgerrcpath is None: ledgerrcpath = os.path.abspath(os.path.expanduser("~/.ledgerrc")) if "LEDGER_FILE" in os.environ: return os.path.abspath(os.path.expanduser(os.env...
[ "Returns", "main", "ledger", "file", "path", "or", "raise", "exception", "if", "it", "cannot", "be", "\\", "found", "." ]
egh/ledger-autosync
python
https://github.com/egh/ledger-autosync/blob/7a303f3a693261d10f677c01fb08f35c105a1e1b/ledgerautosync/cli.py#L40-L55
[ "def", "find_ledger_file", "(", "ledgerrcpath", "=", "None", ")", ":", "if", "ledgerrcpath", "is", "None", ":", "ledgerrcpath", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "expanduser", "(", "\"~/.ledgerrc\"", ")", ")", "if", "\"...
7a303f3a693261d10f677c01fb08f35c105a1e1b
test
print_results
This function is the final common pathway of program: Print initial balance if requested; Print transactions surviving de-duplication filter; Print balance assertions if requested; Print commodity prices obtained from position statements
ledgerautosync/cli.py
def print_results(converter, ofx, ledger, txns, args): """ This function is the final common pathway of program: Print initial balance if requested; Print transactions surviving de-duplication filter; Print balance assertions if requested; Print commodity prices obtained from position statement...
def print_results(converter, ofx, ledger, txns, args): """ This function is the final common pathway of program: Print initial balance if requested; Print transactions surviving de-duplication filter; Print balance assertions if requested; Print commodity prices obtained from position statement...
[ "This", "function", "is", "the", "final", "common", "pathway", "of", "program", ":" ]
egh/ledger-autosync
python
https://github.com/egh/ledger-autosync/blob/7a303f3a693261d10f677c01fb08f35c105a1e1b/ledgerautosync/cli.py#L58-L84
[ "def", "print_results", "(", "converter", ",", "ofx", ",", "ledger", ",", "txns", ",", "args", ")", ":", "if", "args", ".", "initial", ":", "if", "(", "not", "(", "ledger", ".", "check_transaction_by_id", "(", "\"ofxid\"", ",", "converter", ".", "mk_ofxi...
7a303f3a693261d10f677c01fb08f35c105a1e1b
test
compatibility
Run the unit test suite with each support library and Python version.
noxfile.py
def compatibility(session, install): """Run the unit test suite with each support library and Python version.""" session.install('-e', '.[dev]') session.install(install) _run_tests(session)
def compatibility(session, install): """Run the unit test suite with each support library and Python version.""" session.install('-e', '.[dev]') session.install(install) _run_tests(session)
[ "Run", "the", "unit", "test", "suite", "with", "each", "support", "library", "and", "Python", "version", "." ]
google/pybadges
python
https://github.com/google/pybadges/blob/d42c8080adb21b81123ac9540c53127ed2fa1edc/noxfile.py#L50-L55
[ "def", "compatibility", "(", "session", ",", "install", ")", ":", "session", ".", "install", "(", "'-e'", ",", "'.[dev]'", ")", "session", ".", "install", "(", "install", ")", "_run_tests", "(", "session", ")" ]
d42c8080adb21b81123ac9540c53127ed2fa1edc
test
PilMeasurer.text_width
Returns the width, in pixels, of a string in DejaVu Sans 110pt.
pybadges/pil_text_measurer.py
def text_width(self, text: str) -> float: """Returns the width, in pixels, of a string in DejaVu Sans 110pt.""" width, _ = self._font.getsize(text) return width
def text_width(self, text: str) -> float: """Returns the width, in pixels, of a string in DejaVu Sans 110pt.""" width, _ = self._font.getsize(text) return width
[ "Returns", "the", "width", "in", "pixels", "of", "a", "string", "in", "DejaVu", "Sans", "110pt", "." ]
google/pybadges
python
https://github.com/google/pybadges/blob/d42c8080adb21b81123ac9540c53127ed2fa1edc/pybadges/pil_text_measurer.py#L37-L40
[ "def", "text_width", "(", "self", ",", "text", ":", "str", ")", "->", "float", ":", "width", ",", "_", "=", "self", ".", "_font", ".", "getsize", "(", "text", ")", "return", "width" ]
d42c8080adb21b81123ac9540c53127ed2fa1edc
test
get_long_description
Transform README.md into a usable long description. Replaces relative references to svg images to absolute https references.
setup.py
def get_long_description(): """Transform README.md into a usable long description. Replaces relative references to svg images to absolute https references. """ with open('README.md') as f: read_me = f.read() def replace_relative_with_absolute(match): svg_path = match.group(0)[1:-1...
def get_long_description(): """Transform README.md into a usable long description. Replaces relative references to svg images to absolute https references. """ with open('README.md') as f: read_me = f.read() def replace_relative_with_absolute(match): svg_path = match.group(0)[1:-1...
[ "Transform", "README", ".", "md", "into", "a", "usable", "long", "description", "." ]
google/pybadges
python
https://github.com/google/pybadges/blob/d42c8080adb21b81123ac9540c53127ed2fa1edc/setup.py#L23-L39
[ "def", "get_long_description", "(", ")", ":", "with", "open", "(", "'README.md'", ")", "as", "f", ":", "read_me", "=", "f", ".", "read", "(", ")", "def", "replace_relative_with_absolute", "(", "match", ")", ":", "svg_path", "=", "match", ".", "group", "(...
d42c8080adb21b81123ac9540c53127ed2fa1edc
test
PrecalculatedTextMeasurer.text_width
Returns the width, in pixels, of a string in DejaVu Sans 110pt.
pybadges/precalculated_text_measurer.py
def text_width(self, text: str) -> float: """Returns the width, in pixels, of a string in DejaVu Sans 110pt.""" width = 0 for index, c in enumerate(text): width += self._char_to_width.get(c, self._default_character_width) width -= self._pair_to_kern.get(text[index:index +...
def text_width(self, text: str) -> float: """Returns the width, in pixels, of a string in DejaVu Sans 110pt.""" width = 0 for index, c in enumerate(text): width += self._char_to_width.get(c, self._default_character_width) width -= self._pair_to_kern.get(text[index:index +...
[ "Returns", "the", "width", "in", "pixels", "of", "a", "string", "in", "DejaVu", "Sans", "110pt", "." ]
google/pybadges
python
https://github.com/google/pybadges/blob/d42c8080adb21b81123ac9540c53127ed2fa1edc/pybadges/precalculated_text_measurer.py#L52-L59
[ "def", "text_width", "(", "self", ",", "text", ":", "str", ")", "->", "float", ":", "width", "=", "0", "for", "index", ",", "c", "in", "enumerate", "(", "text", ")", ":", "width", "+=", "self", ".", "_char_to_width", ".", "get", "(", "c", ",", "s...
d42c8080adb21b81123ac9540c53127ed2fa1edc
test
PrecalculatedTextMeasurer.from_json
Return a PrecalculatedTextMeasurer given a JSON stream. See precalculate_text.py for details on the required format.
pybadges/precalculated_text_measurer.py
def from_json(f: TextIO) -> 'PrecalculatedTextMeasurer': """Return a PrecalculatedTextMeasurer given a JSON stream. See precalculate_text.py for details on the required format. """ o = json.load(f) return PrecalculatedTextMeasurer(o['mean-character-length'], ...
def from_json(f: TextIO) -> 'PrecalculatedTextMeasurer': """Return a PrecalculatedTextMeasurer given a JSON stream. See precalculate_text.py for details on the required format. """ o = json.load(f) return PrecalculatedTextMeasurer(o['mean-character-length'], ...
[ "Return", "a", "PrecalculatedTextMeasurer", "given", "a", "JSON", "stream", "." ]
google/pybadges
python
https://github.com/google/pybadges/blob/d42c8080adb21b81123ac9540c53127ed2fa1edc/pybadges/precalculated_text_measurer.py#L62-L70
[ "def", "from_json", "(", "f", ":", "TextIO", ")", "->", "'PrecalculatedTextMeasurer'", ":", "o", "=", "json", ".", "load", "(", "f", ")", "return", "PrecalculatedTextMeasurer", "(", "o", "[", "'mean-character-length'", "]", ",", "o", "[", "'character-lengths'"...
d42c8080adb21b81123ac9540c53127ed2fa1edc
test
PrecalculatedTextMeasurer.default
Returns a reasonable default PrecalculatedTextMeasurer.
pybadges/precalculated_text_measurer.py
def default(cls) -> 'PrecalculatedTextMeasurer': """Returns a reasonable default PrecalculatedTextMeasurer.""" if cls._default_cache is not None: return cls._default_cache if pkg_resources.resource_exists(__name__, 'default-widths.json.xz'): import lzma with ...
def default(cls) -> 'PrecalculatedTextMeasurer': """Returns a reasonable default PrecalculatedTextMeasurer.""" if cls._default_cache is not None: return cls._default_cache if pkg_resources.resource_exists(__name__, 'default-widths.json.xz'): import lzma with ...
[ "Returns", "a", "reasonable", "default", "PrecalculatedTextMeasurer", "." ]
google/pybadges
python
https://github.com/google/pybadges/blob/d42c8080adb21b81123ac9540c53127ed2fa1edc/pybadges/precalculated_text_measurer.py#L73-L93
[ "def", "default", "(", "cls", ")", "->", "'PrecalculatedTextMeasurer'", ":", "if", "cls", ".", "_default_cache", "is", "not", "None", ":", "return", "cls", ".", "_default_cache", "if", "pkg_resources", ".", "resource_exists", "(", "__name__", ",", "'default-widt...
d42c8080adb21b81123ac9540c53127ed2fa1edc
test
badge
Creates a github-style badge as an SVG image. >>> badge(left_text='coverage', right_text='23%', right_color='red') '<svg...</svg>' >>> badge(left_text='build', right_text='green', right_color='green', ... whole_link="http://www.example.com/") '<svg...</svg>' Args: left_text: The ...
pybadges/__init__.py
def badge(left_text: str, right_text: str, left_link: Optional[str] = None, right_link: Optional[str] = None, whole_link: Optional[str] = None, logo: Optional[str] = None, left_color: str = '#555', right_color: str = '#007ec6', measurer: Optional[text_measurer.TextMeasurer] = Non...
def badge(left_text: str, right_text: str, left_link: Optional[str] = None, right_link: Optional[str] = None, whole_link: Optional[str] = None, logo: Optional[str] = None, left_color: str = '#555', right_color: str = '#007ec6', measurer: Optional[text_measurer.TextMeasurer] = Non...
[ "Creates", "a", "github", "-", "style", "badge", "as", "an", "SVG", "image", "." ]
google/pybadges
python
https://github.com/google/pybadges/blob/d42c8080adb21b81123ac9540c53127ed2fa1edc/pybadges/__init__.py#L115-L188
[ "def", "badge", "(", "left_text", ":", "str", ",", "right_text", ":", "str", ",", "left_link", ":", "Optional", "[", "str", "]", "=", "None", ",", "right_link", ":", "Optional", "[", "str", "]", "=", "None", ",", "whole_link", ":", "Optional", "[", "...
d42c8080adb21b81123ac9540c53127ed2fa1edc
test
generate_supported_characters
Generate the characters support by the font at the given path.
pybadges/precalculate_text.py
def generate_supported_characters(deja_vu_sans_path: str) -> Iterable[str]: """Generate the characters support by the font at the given path.""" font = ttLib.TTFont(deja_vu_sans_path) for cmap in font['cmap'].tables: if cmap.isUnicode(): for code in cmap.cmap: yield chr(c...
def generate_supported_characters(deja_vu_sans_path: str) -> Iterable[str]: """Generate the characters support by the font at the given path.""" font = ttLib.TTFont(deja_vu_sans_path) for cmap in font['cmap'].tables: if cmap.isUnicode(): for code in cmap.cmap: yield chr(c...
[ "Generate", "the", "characters", "support", "by", "the", "font", "at", "the", "given", "path", "." ]
google/pybadges
python
https://github.com/google/pybadges/blob/d42c8080adb21b81123ac9540c53127ed2fa1edc/pybadges/precalculate_text.py#L57-L63
[ "def", "generate_supported_characters", "(", "deja_vu_sans_path", ":", "str", ")", "->", "Iterable", "[", "str", "]", ":", "font", "=", "ttLib", ".", "TTFont", "(", "deja_vu_sans_path", ")", "for", "cmap", "in", "font", "[", "'cmap'", "]", ".", "tables", "...
d42c8080adb21b81123ac9540c53127ed2fa1edc
test
generate_encodeable_characters
Generates the subset of 'characters' that can be encoded by 'encodings'. Args: characters: The characters to check for encodeability e.g. 'abcd'. encodings: The encodings to check against e.g. ['cp1252', 'iso-8859-5']. Returns: The subset of 'characters' that can be encoded using one o...
pybadges/precalculate_text.py
def generate_encodeable_characters(characters: Iterable[str], encodings: Iterable[str]) -> Iterable[str]: """Generates the subset of 'characters' that can be encoded by 'encodings'. Args: characters: The characters to check for encodeability e.g. 'abcd'. encod...
def generate_encodeable_characters(characters: Iterable[str], encodings: Iterable[str]) -> Iterable[str]: """Generates the subset of 'characters' that can be encoded by 'encodings'. Args: characters: The characters to check for encodeability e.g. 'abcd'. encod...
[ "Generates", "the", "subset", "of", "characters", "that", "can", "be", "encoded", "by", "encodings", "." ]
google/pybadges
python
https://github.com/google/pybadges/blob/d42c8080adb21b81123ac9540c53127ed2fa1edc/pybadges/precalculate_text.py#L66-L84
[ "def", "generate_encodeable_characters", "(", "characters", ":", "Iterable", "[", "str", "]", ",", "encodings", ":", "Iterable", "[", "str", "]", ")", "->", "Iterable", "[", "str", "]", ":", "for", "c", "in", "characters", ":", "for", "encoding", "in", "...
d42c8080adb21b81123ac9540c53127ed2fa1edc
test
calculate_character_to_length_mapping
Return a mapping between each given character and its length. Args: measurer: The TextMeasurer used to measure the width of the text in pixels. characters: The characters to measure e.g. "ml". Returns: A mapping from the given characters to their length in pixels, as ...
pybadges/precalculate_text.py
def calculate_character_to_length_mapping( measurer: text_measurer.TextMeasurer, characters: Iterable[str]) -> Mapping[str, float]: """Return a mapping between each given character and its length. Args: measurer: The TextMeasurer used to measure the width of the text in pixe...
def calculate_character_to_length_mapping( measurer: text_measurer.TextMeasurer, characters: Iterable[str]) -> Mapping[str, float]: """Return a mapping between each given character and its length. Args: measurer: The TextMeasurer used to measure the width of the text in pixe...
[ "Return", "a", "mapping", "between", "each", "given", "character", "and", "its", "length", "." ]
google/pybadges
python
https://github.com/google/pybadges/blob/d42c8080adb21b81123ac9540c53127ed2fa1edc/pybadges/precalculate_text.py#L87-L105
[ "def", "calculate_character_to_length_mapping", "(", "measurer", ":", "text_measurer", ".", "TextMeasurer", ",", "characters", ":", "Iterable", "[", "str", "]", ")", "->", "Mapping", "[", "str", ",", "float", "]", ":", "char_to_length", "=", "{", "}", "for", ...
d42c8080adb21b81123ac9540c53127ed2fa1edc
test
calculate_pair_to_kern_mapping
Returns a mapping between each *pair* of characters and their kerning. Args: measurer: The TextMeasurer used to measure the width of each pair of characters. char_to_length: A mapping between characters and their length in pixels. Must contain every character in 'characters'...
pybadges/precalculate_text.py
def calculate_pair_to_kern_mapping( measurer: text_measurer.TextMeasurer, char_to_length: Mapping[str, float], characters: Iterable[str]) -> Mapping[str, float]: """Returns a mapping between each *pair* of characters and their kerning. Args: measurer: The TextMeasurer used to me...
def calculate_pair_to_kern_mapping( measurer: text_measurer.TextMeasurer, char_to_length: Mapping[str, float], characters: Iterable[str]) -> Mapping[str, float]: """Returns a mapping between each *pair* of characters and their kerning. Args: measurer: The TextMeasurer used to me...
[ "Returns", "a", "mapping", "between", "each", "*", "pair", "*", "of", "characters", "and", "their", "kerning", "." ]
google/pybadges
python
https://github.com/google/pybadges/blob/d42c8080adb21b81123ac9540c53127ed2fa1edc/pybadges/precalculate_text.py#L108-L139
[ "def", "calculate_pair_to_kern_mapping", "(", "measurer", ":", "text_measurer", ".", "TextMeasurer", ",", "char_to_length", ":", "Mapping", "[", "str", ",", "float", "]", ",", "characters", ":", "Iterable", "[", "str", "]", ")", "->", "Mapping", "[", "str", ...
d42c8080adb21b81123ac9540c53127ed2fa1edc
test
write_json
Write the data required by PrecalculatedTextMeasurer to a stream.
pybadges/precalculate_text.py
def write_json(f: TextIO, deja_vu_sans_path: str, measurer: text_measurer.TextMeasurer, encodings: Iterable[str]) -> None: """Write the data required by PrecalculatedTextMeasurer to a stream.""" supported_characters = list( generate_supported_characters(deja_vu_sans_path)) ...
def write_json(f: TextIO, deja_vu_sans_path: str, measurer: text_measurer.TextMeasurer, encodings: Iterable[str]) -> None: """Write the data required by PrecalculatedTextMeasurer to a stream.""" supported_characters = list( generate_supported_characters(deja_vu_sans_path)) ...
[ "Write", "the", "data", "required", "by", "PrecalculatedTextMeasurer", "to", "a", "stream", "." ]
google/pybadges
python
https://github.com/google/pybadges/blob/d42c8080adb21b81123ac9540c53127ed2fa1edc/pybadges/precalculate_text.py#L142-L159
[ "def", "write_json", "(", "f", ":", "TextIO", ",", "deja_vu_sans_path", ":", "str", ",", "measurer", ":", "text_measurer", ".", "TextMeasurer", ",", "encodings", ":", "Iterable", "[", "str", "]", ")", "->", "None", ":", "supported_characters", "=", "list", ...
d42c8080adb21b81123ac9540c53127ed2fa1edc
test
convolve_gaussian_2d
Convolve 2d gaussian.
ssim/utils.py
def convolve_gaussian_2d(image, gaussian_kernel_1d): """Convolve 2d gaussian.""" result = scipy.ndimage.filters.correlate1d( image, gaussian_kernel_1d, axis=0) result = scipy.ndimage.filters.correlate1d( result, gaussian_kernel_1d, axis=1) return result
def convolve_gaussian_2d(image, gaussian_kernel_1d): """Convolve 2d gaussian.""" result = scipy.ndimage.filters.correlate1d( image, gaussian_kernel_1d, axis=0) result = scipy.ndimage.filters.correlate1d( result, gaussian_kernel_1d, axis=1) return result
[ "Convolve", "2d", "gaussian", "." ]
jterrace/pyssim
python
https://github.com/jterrace/pyssim/blob/ff9bd90c3eb7525013ad46babf66b7cc78391e89/ssim/utils.py#L11-L17
[ "def", "convolve_gaussian_2d", "(", "image", ",", "gaussian_kernel_1d", ")", ":", "result", "=", "scipy", ".", "ndimage", ".", "filters", ".", "correlate1d", "(", "image", ",", "gaussian_kernel_1d", ",", "axis", "=", "0", ")", "result", "=", "scipy", ".", ...
ff9bd90c3eb7525013ad46babf66b7cc78391e89
test
get_gaussian_kernel
Generate a gaussian kernel.
ssim/utils.py
def get_gaussian_kernel(gaussian_kernel_width=11, gaussian_kernel_sigma=1.5): """Generate a gaussian kernel.""" # 1D Gaussian kernel definition gaussian_kernel_1d = numpy.ndarray((gaussian_kernel_width)) norm_mu = int(gaussian_kernel_width / 2) # Fill Gaussian kernel for i in range(gaussian_ker...
def get_gaussian_kernel(gaussian_kernel_width=11, gaussian_kernel_sigma=1.5): """Generate a gaussian kernel.""" # 1D Gaussian kernel definition gaussian_kernel_1d = numpy.ndarray((gaussian_kernel_width)) norm_mu = int(gaussian_kernel_width / 2) # Fill Gaussian kernel for i in range(gaussian_ker...
[ "Generate", "a", "gaussian", "kernel", "." ]
jterrace/pyssim
python
https://github.com/jterrace/pyssim/blob/ff9bd90c3eb7525013ad46babf66b7cc78391e89/ssim/utils.py#L19-L29
[ "def", "get_gaussian_kernel", "(", "gaussian_kernel_width", "=", "11", ",", "gaussian_kernel_sigma", "=", "1.5", ")", ":", "# 1D Gaussian kernel definition", "gaussian_kernel_1d", "=", "numpy", ".", "ndarray", "(", "(", "gaussian_kernel_width", ")", ")", "norm_mu", "=...
ff9bd90c3eb7525013ad46babf66b7cc78391e89
test
to_grayscale
Convert PIL image to numpy grayscale array and numpy alpha array. Args: img (PIL.Image): PIL Image object. Returns: (gray, alpha): both numpy arrays.
ssim/utils.py
def to_grayscale(img): """Convert PIL image to numpy grayscale array and numpy alpha array. Args: img (PIL.Image): PIL Image object. Returns: (gray, alpha): both numpy arrays. """ gray = numpy.asarray(ImageOps.grayscale(img)).astype(numpy.float) imbands = img.getbands() alpha ...
def to_grayscale(img): """Convert PIL image to numpy grayscale array and numpy alpha array. Args: img (PIL.Image): PIL Image object. Returns: (gray, alpha): both numpy arrays. """ gray = numpy.asarray(ImageOps.grayscale(img)).astype(numpy.float) imbands = img.getbands() alpha ...
[ "Convert", "PIL", "image", "to", "numpy", "grayscale", "array", "and", "numpy", "alpha", "array", "." ]
jterrace/pyssim
python
https://github.com/jterrace/pyssim/blob/ff9bd90c3eb7525013ad46babf66b7cc78391e89/ssim/utils.py#L31-L47
[ "def", "to_grayscale", "(", "img", ")", ":", "gray", "=", "numpy", ".", "asarray", "(", "ImageOps", ".", "grayscale", "(", "img", ")", ")", ".", "astype", "(", "numpy", ".", "float", ")", "imbands", "=", "img", ".", "getbands", "(", ")", "alpha", "...
ff9bd90c3eb7525013ad46babf66b7cc78391e89
test
main
Main function for pyssim.
ssim/ssimlib.py
def main(): """Main function for pyssim.""" description = '\n'.join([ 'Compares an image with a list of images using the SSIM metric.', ' Example:', ' pyssim test-images/test1-1.png "test-images/*"' ]) parser = argparse.ArgumentParser( prog='pyssim', formatter_class...
def main(): """Main function for pyssim.""" description = '\n'.join([ 'Compares an image with a list of images using the SSIM metric.', ' Example:', ' pyssim test-images/test1-1.png "test-images/*"' ]) parser = argparse.ArgumentParser( prog='pyssim', formatter_class...
[ "Main", "function", "for", "pyssim", "." ]
jterrace/pyssim
python
https://github.com/jterrace/pyssim/blob/ff9bd90c3eb7525013ad46babf66b7cc78391e89/ssim/ssimlib.py#L193-L246
[ "def", "main", "(", ")", ":", "description", "=", "'\\n'", ".", "join", "(", "[", "'Compares an image with a list of images using the SSIM metric.'", ",", "' Example:'", ",", "' pyssim test-images/test1-1.png \"test-images/*\"'", "]", ")", "parser", "=", "argparse", "...
ff9bd90c3eb7525013ad46babf66b7cc78391e89
test
SSIM.ssim_value
Compute the SSIM value from the reference image to the target image. Args: target (str or PIL.Image): Input image to compare the reference image to. This may be a PIL Image object or, to save time, an SSIMImage object (e.g. the img member of another SSIM object). Returns:...
ssim/ssimlib.py
def ssim_value(self, target): """Compute the SSIM value from the reference image to the target image. Args: target (str or PIL.Image): Input image to compare the reference image to. This may be a PIL Image object or, to save time, an SSIMImage object (e.g. the img member o...
def ssim_value(self, target): """Compute the SSIM value from the reference image to the target image. Args: target (str or PIL.Image): Input image to compare the reference image to. This may be a PIL Image object or, to save time, an SSIMImage object (e.g. the img member o...
[ "Compute", "the", "SSIM", "value", "from", "the", "reference", "image", "to", "the", "target", "image", "." ]
jterrace/pyssim
python
https://github.com/jterrace/pyssim/blob/ff9bd90c3eb7525013ad46babf66b7cc78391e89/ssim/ssimlib.py#L109-L145
[ "def", "ssim_value", "(", "self", ",", "target", ")", ":", "# Performance boost if handed a compatible SSIMImage object.", "if", "not", "isinstance", "(", "target", ",", "SSIMImage", ")", "or", "not", "np", ".", "array_equal", "(", "self", ".", "gaussian_kernel_1d",...
ff9bd90c3eb7525013ad46babf66b7cc78391e89
test
SSIM.cw_ssim_value
Compute the complex wavelet SSIM (CW-SSIM) value from the reference image to the target image. Args: target (str or PIL.Image): Input image to compare the reference image to. This may be a PIL Image object or, to save time, an SSIMImage object (e.g. the img member of anoth...
ssim/ssimlib.py
def cw_ssim_value(self, target, width=30): """Compute the complex wavelet SSIM (CW-SSIM) value from the reference image to the target image. Args: target (str or PIL.Image): Input image to compare the reference image to. This may be a PIL Image object or, to save time, an SS...
def cw_ssim_value(self, target, width=30): """Compute the complex wavelet SSIM (CW-SSIM) value from the reference image to the target image. Args: target (str or PIL.Image): Input image to compare the reference image to. This may be a PIL Image object or, to save time, an SS...
[ "Compute", "the", "complex", "wavelet", "SSIM", "(", "CW", "-", "SSIM", ")", "value", "from", "the", "reference", "image", "to", "the", "target", "image", "." ]
jterrace/pyssim
python
https://github.com/jterrace/pyssim/blob/ff9bd90c3eb7525013ad46babf66b7cc78391e89/ssim/ssimlib.py#L147-L191
[ "def", "cw_ssim_value", "(", "self", ",", "target", ",", "width", "=", "30", ")", ":", "if", "not", "isinstance", "(", "target", ",", "SSIMImage", ")", ":", "target", "=", "SSIMImage", "(", "target", ",", "size", "=", "self", ".", "img", ".", "size",...
ff9bd90c3eb7525013ad46babf66b7cc78391e89
test
compute_ssim
Computes SSIM. Args: im1: First PIL Image object to compare. im2: Second PIL Image object to compare. Returns: SSIM float value.
ssim/__init__.py
def compute_ssim(image1, image2, gaussian_kernel_sigma=1.5, gaussian_kernel_width=11): """Computes SSIM. Args: im1: First PIL Image object to compare. im2: Second PIL Image object to compare. Returns: SSIM float value. """ gaussian_kernel_1d = get_gaussian_kernel...
def compute_ssim(image1, image2, gaussian_kernel_sigma=1.5, gaussian_kernel_width=11): """Computes SSIM. Args: im1: First PIL Image object to compare. im2: Second PIL Image object to compare. Returns: SSIM float value. """ gaussian_kernel_1d = get_gaussian_kernel...
[ "Computes", "SSIM", "." ]
jterrace/pyssim
python
https://github.com/jterrace/pyssim/blob/ff9bd90c3eb7525013ad46babf66b7cc78391e89/ssim/__init__.py#L10-L23
[ "def", "compute_ssim", "(", "image1", ",", "image2", ",", "gaussian_kernel_sigma", "=", "1.5", ",", "gaussian_kernel_width", "=", "11", ")", ":", "gaussian_kernel_1d", "=", "get_gaussian_kernel", "(", "gaussian_kernel_width", ",", "gaussian_kernel_sigma", ")", "return...
ff9bd90c3eb7525013ad46babf66b7cc78391e89
test
replicated
Replicated decorator. Use it to mark your class members that modifies a class state. Function will be called asynchronously. Function accepts flowing additional parameters (optional): 'callback': callback(result, failReason), failReason - `FAIL_REASON <#pysyncobj.FAIL_REASON>`_. 'sync': True - t...
pysyncobj/syncobj.py
def replicated(*decArgs, **decKwargs): """Replicated decorator. Use it to mark your class members that modifies a class state. Function will be called asynchronously. Function accepts flowing additional parameters (optional): 'callback': callback(result, failReason), failReason - `FAIL_REASON <#pysy...
def replicated(*decArgs, **decKwargs): """Replicated decorator. Use it to mark your class members that modifies a class state. Function will be called asynchronously. Function accepts flowing additional parameters (optional): 'callback': callback(result, failReason), failReason - `FAIL_REASON <#pysy...
[ "Replicated", "decorator", ".", "Use", "it", "to", "mark", "your", "class", "members", "that", "modifies", "a", "class", "state", ".", "Function", "will", "be", "called", "asynchronously", ".", "Function", "accepts", "flowing", "additional", "parameters", "(", ...
bakwc/PySyncObj
python
https://github.com/bakwc/PySyncObj/blob/be3b0aaa932d5156f5df140c23c962430f51b7b8/pysyncobj/syncobj.py#L1298-L1373
[ "def", "replicated", "(", "*", "decArgs", ",", "*", "*", "decKwargs", ")", ":", "def", "replicatedImpl", "(", "func", ")", ":", "def", "newFunc", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "kwargs", ".", "pop", "(", "...
be3b0aaa932d5156f5df140c23c962430f51b7b8
test
SyncObj.destroy
Correctly destroy SyncObj. Stop autoTickThread, close connections, etc.
pysyncobj/syncobj.py
def destroy(self): """ Correctly destroy SyncObj. Stop autoTickThread, close connections, etc. """ if self.__conf.autoTick: self.__destroying = True else: self._doDestroy()
def destroy(self): """ Correctly destroy SyncObj. Stop autoTickThread, close connections, etc. """ if self.__conf.autoTick: self.__destroying = True else: self._doDestroy()
[ "Correctly", "destroy", "SyncObj", ".", "Stop", "autoTickThread", "close", "connections", "etc", "." ]
bakwc/PySyncObj
python
https://github.com/bakwc/PySyncObj/blob/be3b0aaa932d5156f5df140c23c962430f51b7b8/pysyncobj/syncobj.py#L274-L281
[ "def", "destroy", "(", "self", ")", ":", "if", "self", ".", "__conf", ".", "autoTick", ":", "self", ".", "__destroying", "=", "True", "else", ":", "self", ".", "_doDestroy", "(", ")" ]
be3b0aaa932d5156f5df140c23c962430f51b7b8
test
SyncObj.waitBinded
Waits until initialized (binded port). If success - just returns. If failed to initialized after conf.maxBindRetries - raise SyncObjException.
pysyncobj/syncobj.py
def waitBinded(self): """ Waits until initialized (binded port). If success - just returns. If failed to initialized after conf.maxBindRetries - raise SyncObjException. """ try: self.__transport.waitReady() except TransportNotReadyError: ra...
def waitBinded(self): """ Waits until initialized (binded port). If success - just returns. If failed to initialized after conf.maxBindRetries - raise SyncObjException. """ try: self.__transport.waitReady() except TransportNotReadyError: ra...
[ "Waits", "until", "initialized", "(", "binded", "port", ")", ".", "If", "success", "-", "just", "returns", ".", "If", "failed", "to", "initialized", "after", "conf", ".", "maxBindRetries", "-", "raise", "SyncObjException", "." ]
bakwc/PySyncObj
python
https://github.com/bakwc/PySyncObj/blob/be3b0aaa932d5156f5df140c23c962430f51b7b8/pysyncobj/syncobj.py#L291-L302
[ "def", "waitBinded", "(", "self", ")", ":", "try", ":", "self", ".", "__transport", ".", "waitReady", "(", ")", "except", "TransportNotReadyError", ":", "raise", "SyncObjException", "(", "'BindError'", ")", "if", "not", "self", ".", "__transport", ".", "read...
be3b0aaa932d5156f5df140c23c962430f51b7b8
test
SyncObj.setCodeVersion
Switch to a new code version on all cluster nodes. You should ensure that cluster nodes are updated, otherwise they won't be able to apply commands. :param newVersion: new code version :type int :param callback: will be called on cussess or fail :type callback: function(...
pysyncobj/syncobj.py
def setCodeVersion(self, newVersion, callback = None): """Switch to a new code version on all cluster nodes. You should ensure that cluster nodes are updated, otherwise they won't be able to apply commands. :param newVersion: new code version :type int :param callback: w...
def setCodeVersion(self, newVersion, callback = None): """Switch to a new code version on all cluster nodes. You should ensure that cluster nodes are updated, otherwise they won't be able to apply commands. :param newVersion: new code version :type int :param callback: w...
[ "Switch", "to", "a", "new", "code", "version", "on", "all", "cluster", "nodes", ".", "You", "should", "ensure", "that", "cluster", "nodes", "are", "updated", "otherwise", "they", "won", "t", "be", "able", "to", "apply", "commands", "." ]
bakwc/PySyncObj
python
https://github.com/bakwc/PySyncObj/blob/be3b0aaa932d5156f5df140c23c962430f51b7b8/pysyncobj/syncobj.py#L316-L331
[ "def", "setCodeVersion", "(", "self", ",", "newVersion", ",", "callback", "=", "None", ")", ":", "assert", "isinstance", "(", "newVersion", ",", "int", ")", "if", "newVersion", ">", "self", ".", "__selfCodeVersion", ":", "raise", "Exception", "(", "'wrong ve...
be3b0aaa932d5156f5df140c23c962430f51b7b8
test
SyncObj.removeNodeFromCluster
Remove single node from cluster (dynamic membership changes). Async. You should wait until node successfully added before adding next node. :param node: node object or 'nodeHost:nodePort' :type node: Node | str :param callback: will be called on success or fail :type cal...
pysyncobj/syncobj.py
def removeNodeFromCluster(self, node, callback = None): """Remove single node from cluster (dynamic membership changes). Async. You should wait until node successfully added before adding next node. :param node: node object or 'nodeHost:nodePort' :type node: Node | str :...
def removeNodeFromCluster(self, node, callback = None): """Remove single node from cluster (dynamic membership changes). Async. You should wait until node successfully added before adding next node. :param node: node object or 'nodeHost:nodePort' :type node: Node | str :...
[ "Remove", "single", "node", "from", "cluster", "(", "dynamic", "membership", "changes", ")", ".", "Async", ".", "You", "should", "wait", "until", "node", "successfully", "added", "before", "adding", "next", "node", "." ]
bakwc/PySyncObj
python
https://github.com/bakwc/PySyncObj/blob/be3b0aaa932d5156f5df140c23c962430f51b7b8/pysyncobj/syncobj.py#L349-L363
[ "def", "removeNodeFromCluster", "(", "self", ",", "node", ",", "callback", "=", "None", ")", ":", "if", "not", "self", ".", "__conf", ".", "dynamicMembershipChange", ":", "raise", "Exception", "(", "'dynamicMembershipChange is disabled'", ")", "if", "not", "isin...
be3b0aaa932d5156f5df140c23c962430f51b7b8
test
SyncObj.getStatus
Dumps different debug info about cluster to dict and return it
pysyncobj/syncobj.py
def getStatus(self): """Dumps different debug info about cluster to dict and return it""" status = {} status['version'] = VERSION status['revision'] = REVISION status['self'] = self.__selfNode status['state'] = self.__raftState status['leader'] = self.__raftLeade...
def getStatus(self): """Dumps different debug info about cluster to dict and return it""" status = {} status['version'] = VERSION status['revision'] = REVISION status['self'] = self.__selfNode status['state'] = self.__raftState status['leader'] = self.__raftLeade...
[ "Dumps", "different", "debug", "info", "about", "cluster", "to", "dict", "and", "return", "it" ]
bakwc/PySyncObj
python
https://github.com/bakwc/PySyncObj/blob/be3b0aaa932d5156f5df140c23c962430f51b7b8/pysyncobj/syncobj.py#L630-L659
[ "def", "getStatus", "(", "self", ")", ":", "status", "=", "{", "}", "status", "[", "'version'", "]", "=", "VERSION", "status", "[", "'revision'", "]", "=", "REVISION", "status", "[", "'self'", "]", "=", "self", ".", "__selfNode", "status", "[", "'state...
be3b0aaa932d5156f5df140c23c962430f51b7b8
test
SyncObj.printStatus
Dumps different debug info about cluster to default logger
pysyncobj/syncobj.py
def printStatus(self): """Dumps different debug info about cluster to default logger""" status = self.getStatus() for k, v in iteritems(status): logging.info('%s: %s' % (str(k), str(v)))
def printStatus(self): """Dumps different debug info about cluster to default logger""" status = self.getStatus() for k, v in iteritems(status): logging.info('%s: %s' % (str(k), str(v)))
[ "Dumps", "different", "debug", "info", "about", "cluster", "to", "default", "logger" ]
bakwc/PySyncObj
python
https://github.com/bakwc/PySyncObj/blob/be3b0aaa932d5156f5df140c23c962430f51b7b8/pysyncobj/syncobj.py#L664-L668
[ "def", "printStatus", "(", "self", ")", ":", "status", "=", "self", ".", "getStatus", "(", ")", "for", "k", ",", "v", "in", "iteritems", "(", "status", ")", ":", "logging", ".", "info", "(", "'%s: %s'", "%", "(", "str", "(", "k", ")", ",", "str",...
be3b0aaa932d5156f5df140c23c962430f51b7b8
test
TCPTransport._connToNode
Find the node to which a connection belongs. :param conn: connection object :type conn: TcpConnection :returns corresponding node or None if the node cannot be found :rtype Node or None
pysyncobj/transport.py
def _connToNode(self, conn): """ Find the node to which a connection belongs. :param conn: connection object :type conn: TcpConnection :returns corresponding node or None if the node cannot be found :rtype Node or None """ for node in self._connections: ...
def _connToNode(self, conn): """ Find the node to which a connection belongs. :param conn: connection object :type conn: TcpConnection :returns corresponding node or None if the node cannot be found :rtype Node or None """ for node in self._connections: ...
[ "Find", "the", "node", "to", "which", "a", "connection", "belongs", "." ]
bakwc/PySyncObj
python
https://github.com/bakwc/PySyncObj/blob/be3b0aaa932d5156f5df140c23c962430f51b7b8/pysyncobj/transport.py#L211-L224
[ "def", "_connToNode", "(", "self", ",", "conn", ")", ":", "for", "node", "in", "self", ".", "_connections", ":", "if", "self", ".", "_connections", "[", "node", "]", "is", "conn", ":", "return", "node", "return", "None" ]
be3b0aaa932d5156f5df140c23c962430f51b7b8
test
TCPTransport._createServer
Create the TCP server (but don't bind yet)
pysyncobj/transport.py
def _createServer(self): """ Create the TCP server (but don't bind yet) """ conf = self._syncObj.conf bindAddr = conf.bindAddress or getattr(self._selfNode, 'address') if not bindAddr: raise RuntimeError('Unable to determine bind address') host, port ...
def _createServer(self): """ Create the TCP server (but don't bind yet) """ conf = self._syncObj.conf bindAddr = conf.bindAddress or getattr(self._selfNode, 'address') if not bindAddr: raise RuntimeError('Unable to determine bind address') host, port ...
[ "Create", "the", "TCP", "server", "(", "but", "don", "t", "bind", "yet", ")" ]
bakwc/PySyncObj
python
https://github.com/bakwc/PySyncObj/blob/be3b0aaa932d5156f5df140c23c962430f51b7b8/pysyncobj/transport.py#L239-L253
[ "def", "_createServer", "(", "self", ")", ":", "conf", "=", "self", ".", "_syncObj", ".", "conf", "bindAddr", "=", "conf", ".", "bindAddress", "or", "getattr", "(", "self", ".", "_selfNode", ",", "'address'", ")", "if", "not", "bindAddr", ":", "raise", ...
be3b0aaa932d5156f5df140c23c962430f51b7b8
test
TCPTransport._maybeBind
Bind the server unless it is already bound, this is a read-only node, or the last attempt was too recently. :raises TransportNotReadyError if the bind attempt fails
pysyncobj/transport.py
def _maybeBind(self): """ Bind the server unless it is already bound, this is a read-only node, or the last attempt was too recently. :raises TransportNotReadyError if the bind attempt fails """ if self._ready or self._selfIsReadonlyNode or time.time() < self._lastBindAttemptTi...
def _maybeBind(self): """ Bind the server unless it is already bound, this is a read-only node, or the last attempt was too recently. :raises TransportNotReadyError if the bind attempt fails """ if self._ready or self._selfIsReadonlyNode or time.time() < self._lastBindAttemptTi...
[ "Bind", "the", "server", "unless", "it", "is", "already", "bound", "this", "is", "a", "read", "-", "only", "node", "or", "the", "last", "attempt", "was", "too", "recently", "." ]
bakwc/PySyncObj
python
https://github.com/bakwc/PySyncObj/blob/be3b0aaa932d5156f5df140c23c962430f51b7b8/pysyncobj/transport.py#L255-L274
[ "def", "_maybeBind", "(", "self", ")", ":", "if", "self", ".", "_ready", "or", "self", ".", "_selfIsReadonlyNode", "or", "time", ".", "time", "(", ")", "<", "self", ".", "_lastBindAttemptTime", "+", "self", ".", "_syncObj", ".", "conf", ".", "bindRetryTi...
be3b0aaa932d5156f5df140c23c962430f51b7b8
test
TCPTransport._onNewIncomingConnection
Callback for connections initiated by the other side :param conn: connection object :type conn: TcpConnection
pysyncobj/transport.py
def _onNewIncomingConnection(self, conn): """ Callback for connections initiated by the other side :param conn: connection object :type conn: TcpConnection """ self._unknownConnections.add(conn) encryptor = self._syncObj.encryptor if encryptor: ...
def _onNewIncomingConnection(self, conn): """ Callback for connections initiated by the other side :param conn: connection object :type conn: TcpConnection """ self._unknownConnections.add(conn) encryptor = self._syncObj.encryptor if encryptor: ...
[ "Callback", "for", "connections", "initiated", "by", "the", "other", "side" ]
bakwc/PySyncObj
python
https://github.com/bakwc/PySyncObj/blob/be3b0aaa932d5156f5df140c23c962430f51b7b8/pysyncobj/transport.py#L287-L300
[ "def", "_onNewIncomingConnection", "(", "self", ",", "conn", ")", ":", "self", ".", "_unknownConnections", ".", "add", "(", "conn", ")", "encryptor", "=", "self", ".", "_syncObj", ".", "encryptor", "if", "encryptor", ":", "conn", ".", "encryptor", "=", "en...
be3b0aaa932d5156f5df140c23c962430f51b7b8
test
TCPTransport._onIncomingMessageReceived
Callback for initial messages on incoming connections. Handles encryption, utility messages, and association of the connection with a Node. Once this initial setup is done, the relevant connected callback is executed, and further messages are deferred to the onMessageReceived callback. :param conn: con...
pysyncobj/transport.py
def _onIncomingMessageReceived(self, conn, message): """ Callback for initial messages on incoming connections. Handles encryption, utility messages, and association of the connection with a Node. Once this initial setup is done, the relevant connected callback is executed, and further messages ...
def _onIncomingMessageReceived(self, conn, message): """ Callback for initial messages on incoming connections. Handles encryption, utility messages, and association of the connection with a Node. Once this initial setup is done, the relevant connected callback is executed, and further messages ...
[ "Callback", "for", "initial", "messages", "on", "incoming", "connections", ".", "Handles", "encryption", "utility", "messages", "and", "association", "of", "the", "connection", "with", "a", "Node", ".", "Once", "this", "initial", "setup", "is", "done", "the", ...
bakwc/PySyncObj
python
https://github.com/bakwc/PySyncObj/blob/be3b0aaa932d5156f5df140c23c962430f51b7b8/pysyncobj/transport.py#L302-L365
[ "def", "_onIncomingMessageReceived", "(", "self", ",", "conn", ",", "message", ")", ":", "if", "self", ".", "_syncObj", ".", "encryptor", "and", "not", "conn", ".", "sendRandKey", ":", "conn", ".", "sendRandKey", "=", "message", "conn", ".", "recvRandKey", ...
be3b0aaa932d5156f5df140c23c962430f51b7b8
test
TCPTransport._utilityCallback
Callback for the utility messages :param res: result of the command :param err: error code (one of pysyncobj.config.FAIL_REASON) :param conn: utility connection :param cmd: command :param arg: command arguments
pysyncobj/transport.py
def _utilityCallback(self, res, err, conn, cmd, arg): """ Callback for the utility messages :param res: result of the command :param err: error code (one of pysyncobj.config.FAIL_REASON) :param conn: utility connection :param cmd: command :param arg: command argu...
def _utilityCallback(self, res, err, conn, cmd, arg): """ Callback for the utility messages :param res: result of the command :param err: error code (one of pysyncobj.config.FAIL_REASON) :param conn: utility connection :param cmd: command :param arg: command argu...
[ "Callback", "for", "the", "utility", "messages" ]
bakwc/PySyncObj
python
https://github.com/bakwc/PySyncObj/blob/be3b0aaa932d5156f5df140c23c962430f51b7b8/pysyncobj/transport.py#L367-L381
[ "def", "_utilityCallback", "(", "self", ",", "res", ",", "err", ",", "conn", ",", "cmd", ",", "arg", ")", ":", "cmdResult", "=", "'FAIL'", "if", "err", "==", "FAIL_REASON", ".", "SUCCESS", ":", "cmdResult", "=", "'SUCCESS'", "conn", ".", "send", "(", ...
be3b0aaa932d5156f5df140c23c962430f51b7b8
test
TCPTransport._shouldConnect
Check whether this node should initiate a connection to another node :param node: the other node :type node: Node
pysyncobj/transport.py
def _shouldConnect(self, node): """ Check whether this node should initiate a connection to another node :param node: the other node :type node: Node """ return isinstance(node, TCPNode) and node not in self._preventConnectNodes and (self._selfIsReadonlyNode or self._se...
def _shouldConnect(self, node): """ Check whether this node should initiate a connection to another node :param node: the other node :type node: Node """ return isinstance(node, TCPNode) and node not in self._preventConnectNodes and (self._selfIsReadonlyNode or self._se...
[ "Check", "whether", "this", "node", "should", "initiate", "a", "connection", "to", "another", "node" ]
bakwc/PySyncObj
python
https://github.com/bakwc/PySyncObj/blob/be3b0aaa932d5156f5df140c23c962430f51b7b8/pysyncobj/transport.py#L383-L391
[ "def", "_shouldConnect", "(", "self", ",", "node", ")", ":", "return", "isinstance", "(", "node", ",", "TCPNode", ")", "and", "node", "not", "in", "self", ".", "_preventConnectNodes", "and", "(", "self", ".", "_selfIsReadonlyNode", "or", "self", ".", "_sel...
be3b0aaa932d5156f5df140c23c962430f51b7b8
test
TCPTransport._connectIfNecessarySingle
Connect to a node if necessary. :param node: node to connect to :type node: Node
pysyncobj/transport.py
def _connectIfNecessarySingle(self, node): """ Connect to a node if necessary. :param node: node to connect to :type node: Node """ if node in self._connections and self._connections[node].state != CONNECTION_STATE.DISCONNECTED: return True if not se...
def _connectIfNecessarySingle(self, node): """ Connect to a node if necessary. :param node: node to connect to :type node: Node """ if node in self._connections and self._connections[node].state != CONNECTION_STATE.DISCONNECTED: return True if not se...
[ "Connect", "to", "a", "node", "if", "necessary", "." ]
bakwc/PySyncObj
python
https://github.com/bakwc/PySyncObj/blob/be3b0aaa932d5156f5df140c23c962430f51b7b8/pysyncobj/transport.py#L393-L409
[ "def", "_connectIfNecessarySingle", "(", "self", ",", "node", ")", ":", "if", "node", "in", "self", ".", "_connections", "and", "self", ".", "_connections", "[", "node", "]", ".", "state", "!=", "CONNECTION_STATE", ".", "DISCONNECTED", ":", "return", "True",...
be3b0aaa932d5156f5df140c23c962430f51b7b8
test
TCPTransport._onOutgoingConnected
Callback for when a new connection from this to another node is established. Handles encryption and informs the other node which node this is. If encryption is disabled, this triggers the onNodeConnected callback and messages are deferred to the onMessageReceived callback. If encryption is enabled, the ...
pysyncobj/transport.py
def _onOutgoingConnected(self, conn): """ Callback for when a new connection from this to another node is established. Handles encryption and informs the other node which node this is. If encryption is disabled, this triggers the onNodeConnected callback and messages are deferred to the onMessag...
def _onOutgoingConnected(self, conn): """ Callback for when a new connection from this to another node is established. Handles encryption and informs the other node which node this is. If encryption is disabled, this triggers the onNodeConnected callback and messages are deferred to the onMessag...
[ "Callback", "for", "when", "a", "new", "connection", "from", "this", "to", "another", "node", "is", "established", ".", "Handles", "encryption", "and", "informs", "the", "other", "node", "which", "node", "this", "is", ".", "If", "encryption", "is", "disabled...
bakwc/PySyncObj
python
https://github.com/bakwc/PySyncObj/blob/be3b0aaa932d5156f5df140c23c962430f51b7b8/pysyncobj/transport.py#L419-L439
[ "def", "_onOutgoingConnected", "(", "self", ",", "conn", ")", ":", "if", "self", ".", "_syncObj", ".", "encryptor", ":", "conn", ".", "setOnMessageReceivedCallback", "(", "functools", ".", "partial", "(", "self", ".", "_onOutgoingMessageReceived", ",", "conn", ...
be3b0aaa932d5156f5df140c23c962430f51b7b8
test
TCPTransport._onOutgoingMessageReceived
Callback for receiving a message on a new outgoing connection. Used only if encryption is enabled to exchange the random keys. Once the key exchange is done, this triggers the onNodeConnected callback, and further messages are deferred to the onMessageReceived callback. :param conn: connection object ...
pysyncobj/transport.py
def _onOutgoingMessageReceived(self, conn, message): """ Callback for receiving a message on a new outgoing connection. Used only if encryption is enabled to exchange the random keys. Once the key exchange is done, this triggers the onNodeConnected callback, and further messages are deferred to ...
def _onOutgoingMessageReceived(self, conn, message): """ Callback for receiving a message on a new outgoing connection. Used only if encryption is enabled to exchange the random keys. Once the key exchange is done, this triggers the onNodeConnected callback, and further messages are deferred to ...
[ "Callback", "for", "receiving", "a", "message", "on", "a", "new", "outgoing", "connection", ".", "Used", "only", "if", "encryption", "is", "enabled", "to", "exchange", "the", "random", "keys", ".", "Once", "the", "key", "exchange", "is", "done", "this", "t...
bakwc/PySyncObj
python
https://github.com/bakwc/PySyncObj/blob/be3b0aaa932d5156f5df140c23c962430f51b7b8/pysyncobj/transport.py#L441-L458
[ "def", "_onOutgoingMessageReceived", "(", "self", ",", "conn", ",", "message", ")", ":", "if", "not", "conn", ".", "sendRandKey", ":", "conn", ".", "sendRandKey", "=", "message", "conn", ".", "send", "(", "self", ".", "_selfNode", ".", "address", ")", "n...
be3b0aaa932d5156f5df140c23c962430f51b7b8
test
TCPTransport._onDisconnected
Callback for when a connection is terminated or considered dead. Initiates a reconnect if necessary. :param conn: connection object :type conn: TcpConnection
pysyncobj/transport.py
def _onDisconnected(self, conn): """ Callback for when a connection is terminated or considered dead. Initiates a reconnect if necessary. :param conn: connection object :type conn: TcpConnection """ self._unknownConnections.discard(conn) node = self._connToNode(...
def _onDisconnected(self, conn): """ Callback for when a connection is terminated or considered dead. Initiates a reconnect if necessary. :param conn: connection object :type conn: TcpConnection """ self._unknownConnections.discard(conn) node = self._connToNode(...
[ "Callback", "for", "when", "a", "connection", "is", "terminated", "or", "considered", "dead", ".", "Initiates", "a", "reconnect", "if", "necessary", "." ]
bakwc/PySyncObj
python
https://github.com/bakwc/PySyncObj/blob/be3b0aaa932d5156f5df140c23c962430f51b7b8/pysyncobj/transport.py#L460-L476
[ "def", "_onDisconnected", "(", "self", ",", "conn", ")", ":", "self", ".", "_unknownConnections", ".", "discard", "(", "conn", ")", "node", "=", "self", ".", "_connToNode", "(", "conn", ")", "if", "node", "is", "not", "None", ":", "if", "node", "in", ...
be3b0aaa932d5156f5df140c23c962430f51b7b8
test
TCPTransport.addNode
Add a node to the network :param node: node to add :type node: TCPNode
pysyncobj/transport.py
def addNode(self, node): """ Add a node to the network :param node: node to add :type node: TCPNode """ self._nodes.add(node) self._nodeAddrToNode[node.address] = node if self._shouldConnect(node): conn = TcpConnection(poller = self._syncObj....
def addNode(self, node): """ Add a node to the network :param node: node to add :type node: TCPNode """ self._nodes.add(node) self._nodeAddrToNode[node.address] = node if self._shouldConnect(node): conn = TcpConnection(poller = self._syncObj....
[ "Add", "a", "node", "to", "the", "network" ]
bakwc/PySyncObj
python
https://github.com/bakwc/PySyncObj/blob/be3b0aaa932d5156f5df140c23c962430f51b7b8/pysyncobj/transport.py#L490-L509
[ "def", "addNode", "(", "self", ",", "node", ")", ":", "self", ".", "_nodes", ".", "add", "(", "node", ")", "self", ".", "_nodeAddrToNode", "[", "node", ".", "address", "]", "=", "node", "if", "self", ".", "_shouldConnect", "(", "node", ")", ":", "c...
be3b0aaa932d5156f5df140c23c962430f51b7b8
test
TCPTransport.dropNode
Drop a node from the network :param node: node to drop :type node: Node
pysyncobj/transport.py
def dropNode(self, node): """ Drop a node from the network :param node: node to drop :type node: Node """ conn = self._connections.pop(node, None) if conn is not None: # Calling conn.disconnect() immediately triggers the onDisconnected callback if th...
def dropNode(self, node): """ Drop a node from the network :param node: node to drop :type node: Node """ conn = self._connections.pop(node, None) if conn is not None: # Calling conn.disconnect() immediately triggers the onDisconnected callback if th...
[ "Drop", "a", "node", "from", "the", "network" ]
bakwc/PySyncObj
python
https://github.com/bakwc/PySyncObj/blob/be3b0aaa932d5156f5df140c23c962430f51b7b8/pysyncobj/transport.py#L511-L530
[ "def", "dropNode", "(", "self", ",", "node", ")", ":", "conn", "=", "self", ".", "_connections", ".", "pop", "(", "node", ",", "None", ")", "if", "conn", "is", "not", "None", ":", "# Calling conn.disconnect() immediately triggers the onDisconnected callback if the...
be3b0aaa932d5156f5df140c23c962430f51b7b8
test
TCPTransport.send
Send a message to a node. Returns False if the connection appears to be dead either before or after actually trying to send the message. :param node: target node :type node: Node :param message: message :param message: any :returns success :rtype bool
pysyncobj/transport.py
def send(self, node, message): """ Send a message to a node. Returns False if the connection appears to be dead either before or after actually trying to send the message. :param node: target node :type node: Node :param message: message :param message: any :retu...
def send(self, node, message): """ Send a message to a node. Returns False if the connection appears to be dead either before or after actually trying to send the message. :param node: target node :type node: Node :param message: message :param message: any :retu...
[ "Send", "a", "message", "to", "a", "node", ".", "Returns", "False", "if", "the", "connection", "appears", "to", "be", "dead", "either", "before", "or", "after", "actually", "trying", "to", "send", "the", "message", "." ]
bakwc/PySyncObj
python
https://github.com/bakwc/PySyncObj/blob/be3b0aaa932d5156f5df140c23c962430f51b7b8/pysyncobj/transport.py#L532-L549
[ "def", "send", "(", "self", ",", "node", ",", "message", ")", ":", "if", "node", "not", "in", "self", ".", "_connections", "or", "self", ".", "_connections", "[", "node", "]", ".", "state", "!=", "CONNECTION_STATE", ".", "CONNECTED", ":", "return", "Fa...
be3b0aaa932d5156f5df140c23c962430f51b7b8
test
TCPTransport.destroy
Destroy this transport
pysyncobj/transport.py
def destroy(self): """ Destroy this transport """ self.setOnMessageReceivedCallback(None) self.setOnNodeConnectedCallback(None) self.setOnNodeDisconnectedCallback(None) self.setOnReadonlyNodeConnectedCallback(None) self.setOnReadonlyNodeDisconnectedCallba...
def destroy(self): """ Destroy this transport """ self.setOnMessageReceivedCallback(None) self.setOnNodeConnectedCallback(None) self.setOnNodeDisconnectedCallback(None) self.setOnReadonlyNodeConnectedCallback(None) self.setOnReadonlyNodeDisconnectedCallba...
[ "Destroy", "this", "transport" ]
bakwc/PySyncObj
python
https://github.com/bakwc/PySyncObj/blob/be3b0aaa932d5156f5df140c23c962430f51b7b8/pysyncobj/transport.py#L551-L567
[ "def", "destroy", "(", "self", ")", ":", "self", ".", "setOnMessageReceivedCallback", "(", "None", ")", "self", ".", "setOnNodeConnectedCallback", "(", "None", ")", "self", ".", "setOnNodeDisconnectedCallback", "(", "None", ")", "self", ".", "setOnReadonlyNodeConn...
be3b0aaa932d5156f5df140c23c962430f51b7b8
test
ReplQueue.put
Put an item into the queue. True - if item placed in queue. False - if queue is full and item can not be placed.
pysyncobj/batteries.py
def put(self, item): """Put an item into the queue. True - if item placed in queue. False - if queue is full and item can not be placed.""" if self.__maxsize and len(self.__data) >= self.__maxsize: return False self.__data.append(item) return True
def put(self, item): """Put an item into the queue. True - if item placed in queue. False - if queue is full and item can not be placed.""" if self.__maxsize and len(self.__data) >= self.__maxsize: return False self.__data.append(item) return True
[ "Put", "an", "item", "into", "the", "queue", ".", "True", "-", "if", "item", "placed", "in", "queue", ".", "False", "-", "if", "queue", "is", "full", "and", "item", "can", "not", "be", "placed", "." ]
bakwc/PySyncObj
python
https://github.com/bakwc/PySyncObj/blob/be3b0aaa932d5156f5df140c23c962430f51b7b8/pysyncobj/batteries.py#L330-L337
[ "def", "put", "(", "self", ",", "item", ")", ":", "if", "self", ".", "__maxsize", "and", "len", "(", "self", ".", "__data", ")", ">=", "self", ".", "__maxsize", ":", "return", "False", "self", ".", "__data", ".", "append", "(", "item", ")", "return...
be3b0aaa932d5156f5df140c23c962430f51b7b8
test
ReplPriorityQueue.put
Put an item into the queue. Items should be comparable, eg. tuples. True - if item placed in queue. False - if queue is full and item can not be placed.
pysyncobj/batteries.py
def put(self, item): """Put an item into the queue. Items should be comparable, eg. tuples. True - if item placed in queue. False - if queue is full and item can not be placed.""" if self.__maxsize and len(self.__data) >= self.__maxsize: return False heapq.heappush(se...
def put(self, item): """Put an item into the queue. Items should be comparable, eg. tuples. True - if item placed in queue. False - if queue is full and item can not be placed.""" if self.__maxsize and len(self.__data) >= self.__maxsize: return False heapq.heappush(se...
[ "Put", "an", "item", "into", "the", "queue", ".", "Items", "should", "be", "comparable", "eg", ".", "tuples", ".", "True", "-", "if", "item", "placed", "in", "queue", ".", "False", "-", "if", "queue", "is", "full", "and", "item", "can", "not", "be", ...
bakwc/PySyncObj
python
https://github.com/bakwc/PySyncObj/blob/be3b0aaa932d5156f5df140c23c962430f51b7b8/pysyncobj/batteries.py#L379-L386
[ "def", "put", "(", "self", ",", "item", ")", ":", "if", "self", ".", "__maxsize", "and", "len", "(", "self", ".", "__data", ")", ">=", "self", ".", "__maxsize", ":", "return", "False", "heapq", ".", "heappush", "(", "self", ".", "__data", ",", "ite...
be3b0aaa932d5156f5df140c23c962430f51b7b8
test
ReplPriorityQueue.get
Extract the smallest item from queue. Return default if queue is empty.
pysyncobj/batteries.py
def get(self, default=None): """Extract the smallest item from queue. Return default if queue is empty.""" if not self.__data: return default return heapq.heappop(self.__data)
def get(self, default=None): """Extract the smallest item from queue. Return default if queue is empty.""" if not self.__data: return default return heapq.heappop(self.__data)
[ "Extract", "the", "smallest", "item", "from", "queue", ".", "Return", "default", "if", "queue", "is", "empty", "." ]
bakwc/PySyncObj
python
https://github.com/bakwc/PySyncObj/blob/be3b0aaa932d5156f5df140c23c962430f51b7b8/pysyncobj/batteries.py#L389-L394
[ "def", "get", "(", "self", ",", "default", "=", "None", ")", ":", "if", "not", "self", ".", "__data", ":", "return", "default", "return", "heapq", ".", "heappop", "(", "self", ".", "__data", ")" ]
be3b0aaa932d5156f5df140c23c962430f51b7b8