INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
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 - like or sparse matrix shape ( n_samples sum_n_components ) hstack of results o... | 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 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 matrix shape ( n_samples sum_n_components ) hstack of results of transfo... | 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
-------
... |
Fit the model according to the given training data. | 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... |
Actual fitting performing the search over parameters. | 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):
... |
Fit label encoder Parameters ---------- y: ArrayRDD ( n_samples ) Target values. Returns ------- self: returns an instance of self. | 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_... |
Transform labels to normalized encoding. Parameters ---------- y: ArrayRDD [ n_samples ] Target values. Returns ------- y: ArrayRDD [ n_samples ] | 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... |
Compute the score of an estimator on a given test set. | 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 k - means clustering. | 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... |
Predict the closest cluster each sample in X belongs to. | 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
-------... |
Fit the model according to the given training data. | 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... |
Distributed method to predict class labels for samples in X. | 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.
... |
Checks if the blocks in the RDD matches the expected types. | 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 ... |
Learn a list of feature name - > indices mappings. | 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
... |
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. | 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... |
Learn empirical variances from X. | 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... |
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 k: Int Number of singular vectors... | 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 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. Parameters ---------- b... | 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... |
Fit LSI model to X and perform dimensionality reduction on X. | 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... |
Perform dimensionality reduction on X. | 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... |
Pack rdd with a specific collection constructor. | 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 of tuples as tuples of arrays or scipy. sparse matrices. | 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 >= ... |
Block an RDD | 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... |
Execute the blocking process on the given 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 : ... |
Equivalent to map compatibility purpose only. Column parameter ignored. | 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... |
Returns the shape of the data. | 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 data as numpy. array from each partition. | 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()) |
Execute the blocking process on the given 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 a transformation on a column or columns. Returns the modified DictRDD. | 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(... |
Returns zero if there are no permissions for a bit of the perm. of a file. Otherwise it returns a positive value | 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)
... |
File is only writable by root | 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... |
Command to check configuration file. Raises InvalidConfig on error | 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(... |
Parse and validate the config file. The read data is accessible as a dictionary in this instance | 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, '{}... |
Get the arguments to execute a command as a user | 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... |
Excecute command on thread | 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 remote machine using SSH | 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... |
Execute using self. data | 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... |
Check self. data. Raise InvalidConfig on error | 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... |
Execute using self. data | 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'):
... |
Get HTTP Headers to send. By default default_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 |
API 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 ... |
Return data value on self. data | 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... |
Home assistant url | 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))
... |
IFTTT Webhook url | 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... |
Return source mac address for this Scapy Packet | 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... |
Scandevice callback. Register src mac to avoid src repetition. Print device on screen. | 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... |
Print help and scan devices on screen. | 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) |
Execute this device | 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... |
Send success or error message to configured confirmation | 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()
... |
Press button. Check DEFAULT_DELAY. | 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... |
Execute a device. Used if the time between executions is greater than DEFAULT_DELAY | 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.... |
Start daemon mode | 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')) |
Sniff packages | 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)"... |
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 | 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... |
Convert an OFX Transaction to a posting | 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... |
Returns main ledger file path or raise exception if it cannot be \ found. | 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... |
This function is the final common pathway of program: | 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... |
Run the unit test suite with each support library and Python version. | 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) |
Returns the width in pixels of a string in DejaVu Sans 110pt. | 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 |
Transform README. md into a usable long description. | 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... |
Returns the width in pixels of a string in DejaVu Sans 110pt. | 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 +... |
Return a PrecalculatedTextMeasurer given a JSON stream. | 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'],
... |
Returns a reasonable default PrecalculatedTextMeasurer. | 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 ... |
Creates a github - style badge as an SVG image. | 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... |
Generate the characters support by the font at the given path. | 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... |
Generates the subset of characters that can be encoded by encodings. | 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... |
Return a mapping between each given character and its length. | 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... |
Returns a mapping between each * pair * of characters and their kerning. | 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... |
Write the data required by PrecalculatedTextMeasurer to a stream. | 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))
... |
Convolve 2d gaussian. | 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 |
Generate a gaussian kernel. | 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... |
Convert PIL image to numpy grayscale array and numpy alpha array. | 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 ... |
Main function for pyssim. | 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... |
Compute the SSIM value from the reference image to the target image. | 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 complex wavelet SSIM ( CW - SSIM ) value from the reference image to the target image. | 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... |
Computes SSIM. | 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... |
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 - to block execution and wa... | 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... |
Correctly destroy SyncObj. Stop autoTickThread close connections etc. | def destroy(self):
"""
Correctly destroy SyncObj. Stop autoTickThread, close connections, etc.
"""
if self.__conf.autoTick:
self.__destroying = True
else:
self._doDestroy() |
Waits until initialized ( binded port ). If success - just returns. If failed to initialized after conf. maxBindRetries - raise SyncObjException. | 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... |
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. | 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... |
Remove single node from cluster ( dynamic membership changes ). Async. You should wait until node successfully added before adding next node. | 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
:... |
Dumps different debug info about cluster to dict and return it | 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 default logger | 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))) |
Find the node to which a connection belongs. | 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:
... |
Create the TCP server ( but don t bind yet ) | 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 ... |
Bind the server unless it is already bound this is a read - only node or the last attempt was too recently. | 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... |
Callback for connections initiated by the other side | 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 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. | 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 the utility messages | 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... |
Check whether this node should initiate a connection to another node | 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... |
Connect to a node if necessary. | 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... |
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 first message is h... | 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 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. | 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 when a connection is terminated or considered dead. Initiates a reconnect if necessary. | 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(... |
Add a node to the network | 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.... |
Drop a node from the network | 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... |
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. | 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... |
Destroy this transport | def destroy(self):
"""
Destroy this transport
"""
self.setOnMessageReceivedCallback(None)
self.setOnNodeConnectedCallback(None)
self.setOnNodeDisconnectedCallback(None)
self.setOnReadonlyNodeConnectedCallback(None)
self.setOnReadonlyNodeDisconnectedCallba... |
Put an item into the queue. True - if item placed in queue. False - if queue is full and item can not be placed. | 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. Items should be comparable eg. tuples. True - if item placed in queue. False - if queue is full and item can not be placed. | 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... |
Extract the smallest item from queue. Return default if queue is empty. | 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) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.