INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Return inverse probability of censoring weights at given time points.
:math:`\\omega_i = \\delta_i / \\hat{G}(y_i)`
Parameters
----------
y : structured array, shape = (n_samples,)
A structured array containing the binary event indicator
as first field, and time... | def predict_ipcw(self, y):
"""Return inverse probability of censoring weights at given time points.
:math:`\\omega_i = \\delta_i / \\hat{G}(y_i)`
Parameters
----------
y : structured array, shape = (n_samples,)
A structured array containing the binary event indicato... |
Concordance index for right-censored data
The concordance index is defined as the proportion of all comparable pairs
in which the predictions and outcomes are concordant.
Samples are comparable if for at least one of them an event occurred.
If the estimated risk is larger for the sample with a higher ... | def concordance_index_censored(event_indicator, event_time, estimate, tied_tol=1e-8):
"""Concordance index for right-censored data
The concordance index is defined as the proportion of all comparable pairs
in which the predictions and outcomes are concordant.
Samples are comparable if for at least one... |
Concordance index for right-censored data based on inverse probability of censoring weights.
This is an alternative to the estimator in :func:`concordance_index_censored`
that does not depend on the distribution of censoring times in the test data.
Therefore, the estimate is unbiased and consistent for a p... | def concordance_index_ipcw(survival_train, survival_test, estimate, tau=None, tied_tol=1e-8):
"""Concordance index for right-censored data based on inverse probability of censoring weights.
This is an alternative to the estimator in :func:`concordance_index_censored`
that does not depend on the distributio... |
Estimator of cumulative/dynamic AUC for right-censored time-to-event data.
The receiver operating characteristic (ROC) curve and the area under the
ROC curve (AUC) can be extended to survival data by defining
sensitivity (true positive rate) and specificity (true negative rate)
as time-dependent measur... | def cumulative_dynamic_auc(survival_train, survival_test, estimate, times, tied_tol=1e-8):
"""Estimator of cumulative/dynamic AUC for right-censored time-to-event data.
The receiver operating characteristic (ROC) curve and the area under the
ROC curve (AUC) can be extended to survival data by defining
... |
Number of features that match exactly | def _nominal_kernel(x, y, out):
"""Number of features that match exactly"""
for i in range(x.shape[0]):
for j in range(y.shape[0]):
out[i, j] += (x[i, :] == y[j, :]).sum()
return out |
Convert array from continuous and ordered categorical columns | def _get_continuous_and_ordinal_array(x):
"""Convert array from continuous and ordered categorical columns"""
nominal_columns = x.select_dtypes(include=['object', 'category']).columns
ordinal_columns = pandas.Index([v for v in nominal_columns if x[v].cat.ordered])
continuous_columns = x.select_dtypes(in... |
Computes clinical kernel
The clinical kernel distinguishes between continuous
ordinal,and nominal variables.
Parameters
----------
x : pandas.DataFrame, shape = (n_samples_x, n_features)
Training data
y : pandas.DataFrame, shape = (n_samples_y, n_features)
Testing data
Re... | def clinical_kernel(x, y=None):
"""Computes clinical kernel
The clinical kernel distinguishes between continuous
ordinal,and nominal variables.
Parameters
----------
x : pandas.DataFrame, shape = (n_samples_x, n_features)
Training data
y : pandas.DataFrame, shape = (n_samples_y, n... |
Get distance functions for each column's dtype | def _prepare_by_column_dtype(self, X):
"""Get distance functions for each column's dtype"""
if not isinstance(X, pandas.DataFrame):
raise TypeError('X must be a pandas DataFrame')
numeric_columns = []
nominal_columns = []
numeric_ranges = []
fit_data = numpy... |
Determine transformation parameters from data in X.
Subsequent calls to `transform(Y)` compute the pairwise
distance to `X`.
Parameters of the clinical kernel are only updated
if `fit_once` is `False`, otherwise you have to
explicitly call `prepare()` once.
Parameters
... | def fit(self, X, y=None, **kwargs):
"""Determine transformation parameters from data in X.
Subsequent calls to `transform(Y)` compute the pairwise
distance to `X`.
Parameters of the clinical kernel are only updated
if `fit_once` is `False`, otherwise you have to
explicit... |
r"""Compute all pairwise distances between `self.X_fit_` and `Y`.
Parameters
----------
y : array-like, shape = (n_samples_y, n_features)
Returns
-------
kernel : ndarray, shape = (n_samples_y, n_samples_X_fit\_)
Kernel matrix. Values are normalized to lie w... | def transform(self, Y):
r"""Compute all pairwise distances between `self.X_fit_` and `Y`.
Parameters
----------
y : array-like, shape = (n_samples_y, n_features)
Returns
-------
kernel : ndarray, shape = (n_samples_y, n_samples_X_fit\_)
Kernel matrix... |
Function to use with :func:`sklearn.metrics.pairwise.pairwise_kernels`
Parameters
----------
X : array, shape = (n_features,)
Y : array, shape = (n_features,)
Returns
-------
similarity : float
Similarities are normalized to be within [0, 1] | def pairwise_kernel(self, X, Y):
"""Function to use with :func:`sklearn.metrics.pairwise.pairwise_kernels`
Parameters
----------
X : array, shape = (n_features,)
Y : array, shape = (n_features,)
Returns
-------
similarity : float
Similaritie... |
Fit estimator.
Parameters
----------
X : array-like, shape = (n_samples, n_features)
Data matrix
y : structured array, shape = (n_samples,)
A structured array containing the binary event indicator
as first field, and time of event or time of censorin... | def fit(self, X, y, sample_weight=None):
"""Fit estimator.
Parameters
----------
X : array-like, shape = (n_samples, n_features)
Data matrix
y : structured array, shape = (n_samples,)
A structured array containing the binary event indicator
a... |
Check validity of parameters and raise ValueError if not valid. | def _check_params(self):
"""Check validity of parameters and raise ValueError if not valid. """
if self.n_estimators <= 0:
raise ValueError("n_estimators must be greater than 0 but "
"was %r" % self.n_estimators)
if not 0.0 < self.subsample <= 1.0:
... |
Fit component-wise weighted least squares model | def _fit_stage_componentwise(X, residuals, sample_weight, **fit_params):
"""Fit component-wise weighted least squares model"""
n_features = X.shape[1]
base_learners = []
error = numpy.empty(n_features)
for component in range(n_features):
learner = ComponentwiseLeastSquares(component).fit(X,... |
Predict risk scores.
Parameters
----------
X : array-like, shape = (n_samples, n_features)
Data matrix.
Returns
-------
risk_score : array, shape = (n_samples,)
Predicted risk scores. | def predict(self, X):
"""Predict risk scores.
Parameters
----------
X : array-like, shape = (n_samples, n_features)
Data matrix.
Returns
-------
risk_score : array, shape = (n_samples,)
Predicted risk scores.
"""
check_is_... |
Return the aggregated coefficients.
Returns
-------
coef_ : ndarray, shape = (n_features + 1,)
Coefficients of features. The first element denotes the intercept. | def coef_(self):
"""Return the aggregated coefficients.
Returns
-------
coef_ : ndarray, shape = (n_features + 1,)
Coefficients of features. The first element denotes the intercept.
"""
coef = numpy.zeros(self.n_features_ + 1, dtype=float)
for estima... |
Check validity of parameters and raise ValueError if not valid. | def _check_params(self):
"""Check validity of parameters and raise ValueError if not valid. """
self.n_estimators = int(self.n_estimators)
if self.n_estimators <= 0:
raise ValueError("n_estimators must be greater than 0 but "
"was %r" % self.n_estimators)... |
Fit another stage of ``n_classes_`` trees to the boosting model. | def _fit_stage(self, i, X, y, y_pred, sample_weight, sample_mask,
random_state, scale, X_idx_sorted, X_csc=None, X_csr=None):
"""Fit another stage of ``n_classes_`` trees to the boosting model. """
assert sample_mask.dtype == numpy.bool
loss = self.loss_
# whether to... |
Iteratively fits the stages.
For each stage it computes the progress (OOB, train score)
and delegates to ``_fit_stage``.
Returns the number of stages fit; might differ from ``n_estimators``
due to early stopping. | def _fit_stages(self, X, y, y_pred, sample_weight, random_state,
begin_at_stage=0, monitor=None, X_idx_sorted=None):
"""Iteratively fits the stages.
For each stage it computes the progress (OOB, train score)
and delegates to ``_fit_stage``.
Returns the number of stag... |
Fit the gradient boosting model.
Parameters
----------
X : array-like, shape = (n_samples, n_features)
Data matrix
y : structured array, shape = (n_samples,)
A structured array containing the binary event indicator
as first field, and time of event o... | def fit(self, X, y, sample_weight=None, monitor=None):
"""Fit the gradient boosting model.
Parameters
----------
X : array-like, shape = (n_samples, n_features)
Data matrix
y : structured array, shape = (n_samples,)
A structured array containing the bina... |
Predict risk scores.
Parameters
----------
X : array-like, shape = (n_samples, n_features)
The input samples.
Returns
-------
y : ndarray, shape = (n_samples,)
The risk scores. | def predict(self, X):
"""Predict risk scores.
Parameters
----------
X : array-like, shape = (n_samples, n_features)
The input samples.
Returns
-------
y : ndarray, shape = (n_samples,)
The risk scores.
"""
check_is_fitted(... |
Predict hazard at each stage for X.
This method allows monitoring (i.e. determine error on testing set)
after each stage.
Parameters
----------
X : array-like, shape = (n_samples, n_features)
The input samples.
Returns
-------
y : generator ... | def staged_predict(self, X):
"""Predict hazard at each stage for X.
This method allows monitoring (i.e. determine error on testing set)
after each stage.
Parameters
----------
X : array-like, shape = (n_samples, n_features)
The input samples.
Return... |
Build a MINLIP survival model from training data.
Parameters
----------
X : array-like, shape = (n_samples, n_features)
Data matrix.
y : structured array, shape = (n_samples,)
A structured array containing the binary event indicator
as first field, a... | def fit(self, X, y):
"""Build a MINLIP survival model from training data.
Parameters
----------
X : array-like, shape = (n_samples, n_features)
Data matrix.
y : structured array, shape = (n_samples,)
A structured array containing the binary event indicat... |
Predict risk score of experiencing an event.
Higher scores indicate shorter survival (high risk),
lower scores longer survival (low risk).
Parameters
----------
X : array-like, shape = (n_samples, n_features)
The input samples.
Returns
-------
... | def predict(self, X):
"""Predict risk score of experiencing an event.
Higher scores indicate shorter survival (high risk),
lower scores longer survival (low risk).
Parameters
----------
X : array-like, shape = (n_samples, n_features)
The input samples.
... |
Split data frame into features and labels.
Parameters
----------
data_frame : pandas.DataFrame, shape = (n_samples, n_columns)
A data frame.
attr_labels : sequence of str or None
A list of one or more columns that are considered the label.
If `survival` is `True`, then attr_lab... | def get_x_y(data_frame, attr_labels, pos_label=None, survival=True):
"""Split data frame into features and labels.
Parameters
----------
data_frame : pandas.DataFrame, shape = (n_samples, n_columns)
A data frame.
attr_labels : sequence of str or None
A list of one or more columns t... |
Load dataset in ARFF format.
Parameters
----------
path_training : str
Path to ARFF file containing data.
attr_labels : sequence of str
Names of attributes denoting dependent variables.
If ``survival`` is set, it must be a sequence with two items:
the name of the event ... | def load_arff_files_standardized(path_training, attr_labels, pos_label=None, path_testing=None, survival=True,
standardize_numeric=True, to_numeric=True):
"""Load dataset in ARFF format.
Parameters
----------
path_training : str
Path to ARFF file containing data... |
Load and return the AIDS Clinical Trial dataset
The dataset has 1,151 samples and 11 features.
The dataset has 2 endpoints:
1. AIDS defining event, which occurred for 96 patients (8.3%)
2. Death, which occurred for 26 patients (2.3%)
Parameters
----------
endpoint : aids|death
The... | def load_aids(endpoint="aids"):
"""Load and return the AIDS Clinical Trial dataset
The dataset has 1,151 samples and 11 features.
The dataset has 2 endpoints:
1. AIDS defining event, which occurred for 96 patients (8.3%)
2. Death, which occurred for 26 patients (2.3%)
Parameters
---------... |
Convert categorical columns to numeric values.
Parameters
----------
X : pandas.DataFrame
Data to encode.
y :
Ignored. For compatibility with TransformerMixin.
fit_params :
Ignored. For compatibility with TransformerMixin.
Returns
... | def fit_transform(self, X, y=None, **fit_params):
"""Convert categorical columns to numeric values.
Parameters
----------
X : pandas.DataFrame
Data to encode.
y :
Ignored. For compatibility with TransformerMixin.
fit_params :
Ignored. ... |
Convert categorical columns to numeric values.
Parameters
----------
X : pandas.DataFrame
Data to encode.
Returns
-------
Xt : pandas.DataFrame
Encoded data. | def transform(self, X):
"""Convert categorical columns to numeric values.
Parameters
----------
X : pandas.DataFrame
Data to encode.
Returns
-------
Xt : pandas.DataFrame
Encoded data.
"""
check_is_fitted(self, "encoded_co... |
Internal method to streamline the getting of data from the json
Args:
json_inp (json): json input from our caller
ndx (int): index where the data is located in the api
Returns:
If pandas is present:
DataFrame (pandas.DataFrame): data set from ndx within the
API'... | def _api_scrape(json_inp, ndx):
"""
Internal method to streamline the getting of data from the json
Args:
json_inp (json): json input from our caller
ndx (int): index where the data is located in the api
Returns:
If pandas is present:
DataFrame (pandas.DataFrame): d... |
Internal method to streamline our requests / json getting
Args:
endpoint (str): endpoint to be called from the API
params (dict): parameters to be passed to the API
Raises:
HTTPError: if requests hits a status code != 200
Returns:
json (json): json object for selected API ... | def _get_json(endpoint, params, referer='scores'):
"""
Internal method to streamline our requests / json getting
Args:
endpoint (str): endpoint to be called from the API
params (dict): parameters to be passed to the API
Raises:
HTTPError: if requests hits a status code != 200
... |
Calls our PlayerList class to get a full list of players and then returns
just an id if specified or the full row of player information
Args:
:first_name: First name of the player
:last_name: Last name of the player
(this is None if the player only has first name [Nene])
:only_c... | def get_player(first_name,
last_name=None,
season=constants.CURRENT_SEASON,
only_current=0,
just_id=True):
"""
Calls our PlayerList class to get a full list of players and then returns
just an id if specified or the full row of player information
... |
Called from Dealer when ask message received from RoundManager | def respond_to_ask(self, message):
"""Called from Dealer when ask message received from RoundManager"""
valid_actions, hole_card, round_state = self.__parse_ask_message(message)
return self.declare_action(valid_actions, hole_card, round_state) |
Called from Dealer when notification received from RoundManager | def receive_notification(self, message):
"""Called from Dealer when notification received from RoundManager"""
msg_type = message["message_type"]
if msg_type == "game_start_message":
info = self.__parse_game_start_message(message)
self.receive_game_start_message(info)
elif msg_type == "rou... |
A preliminary result processor we'll chain on to the original task
This will get executed wherever the source task was executed, in this
case one of the threads in the ThreadPoolExecutor | async def result_continuation(task):
"""A preliminary result processor we'll chain on to the original task
This will get executed wherever the source task was executed, in this
case one of the threads in the ThreadPoolExecutor"""
await asyncio.sleep(0.1)
num, res = task.result()
return num... |
An async result aggregator that combines all the results
This gets executed in unsync.loop and unsync.thread | async def result_processor(tasks):
"""An async result aggregator that combines all the results
This gets executed in unsync.loop and unsync.thread"""
output = {}
for task in tasks:
num, res = await task
output[num] = res
return output |
based on https://github.com/apache/avro/pull/82/ | def _read_decimal(data, size, writer_schema):
"""
based on https://github.com/apache/avro/pull/82/
"""
scale = writer_schema.get('scale', 0)
precision = writer_schema['precision']
datum_byte = str2ints(data)
unscaled_datum = 0
msb = fstint(data)
leftmost_bit = (msb >> 7) & 1
if... |
int and long values are written using variable-length, zig-zag
coding. | def read_long(fo, writer_schema=None, reader_schema=None):
"""int and long values are written using variable-length, zig-zag
coding."""
c = fo.read(1)
# We do EOF checking only here, since most reader start here
if not c:
raise StopIteration
b = ord(c)
n = b & 0x7F
shift = 7
... |
Bytes are encoded as a long followed by that many bytes of data. | def read_bytes(fo, writer_schema=None, reader_schema=None):
"""Bytes are encoded as a long followed by that many bytes of data."""
size = read_long(fo)
return fo.read(size) |
An enum is encoded by a int, representing the zero-based position of the
symbol in the schema. | def read_enum(fo, writer_schema, reader_schema=None):
"""An enum is encoded by a int, representing the zero-based position of the
symbol in the schema.
"""
index = read_long(fo)
symbol = writer_schema['symbols'][index]
if reader_schema and symbol not in reader_schema['symbols']:
default ... |
Arrays are encoded as a series of blocks.
Each block consists of a long count value, followed by that many array
items. A block with count zero indicates the end of the array. Each item
is encoded per the array's item schema.
If a block's count is negative, then the count is followed immediately by ... | def read_array(fo, writer_schema, reader_schema=None):
"""Arrays are encoded as a series of blocks.
Each block consists of a long count value, followed by that many array
items. A block with count zero indicates the end of the array. Each item
is encoded per the array's item schema.
If a block's... |
Maps are encoded as a series of blocks.
Each block consists of a long count value, followed by that many key/value
pairs. A block with count zero indicates the end of the map. Each item is
encoded per the map's value schema.
If a block's count is negative, then the count is followed immediately by a... | def read_map(fo, writer_schema, reader_schema=None):
"""Maps are encoded as a series of blocks.
Each block consists of a long count value, followed by that many key/value
pairs. A block with count zero indicates the end of the map. Each item is
encoded per the map's value schema.
If a block's co... |
A union is encoded by first writing a long value indicating the
zero-based position within the union of the schema of its value.
The value is then encoded per the indicated schema within the union. | def read_union(fo, writer_schema, reader_schema=None):
"""A union is encoded by first writing a long value indicating the
zero-based position within the union of the schema of its value.
The value is then encoded per the indicated schema within the union.
"""
# schema resolution
index = read_lo... |
A record is encoded by encoding the values of its fields in the order
that they are declared. In other words, a record is encoded as just the
concatenation of the encodings of its fields. Field values are encoded per
their schema.
Schema Resolution:
* the ordering of fields may be different: fiel... | def read_record(fo, writer_schema, reader_schema=None):
"""A record is encoded by encoding the values of its fields in the order
that they are declared. In other words, a record is encoded as just the
concatenation of the encodings of its fields. Field values are encoded per
their schema.
Schema R... |
Read data from file object according to schema. | def read_data(fo, writer_schema, reader_schema=None):
"""Read data from file object according to schema."""
record_type = extract_record_type(writer_schema)
logical_type = extract_logical_type(writer_schema)
if reader_schema and record_type in AVRO_TYPES:
# If the schemas are the same, set the... |
Return iterator over avro records. | def _iter_avro_records(fo, header, codec, writer_schema, reader_schema):
"""Return iterator over avro records."""
sync_marker = header['sync']
read_block = BLOCK_READERS.get(codec)
if not read_block:
raise ValueError('Unrecognized codec: %r' % codec)
block_count = 0
while True:
... |
Return iterator over avro blocks. | def _iter_avro_blocks(fo, header, codec, writer_schema, reader_schema):
"""Return iterator over avro blocks."""
sync_marker = header['sync']
read_block = BLOCK_READERS.get(codec)
if not read_block:
raise ValueError('Unrecognized codec: %r' % codec)
while True:
offset = fo.tell()
... |
Reads a single record writen using the
:meth:`~fastavro._write_py.schemaless_writer`
Parameters
----------
fo: file-like
Input stream
writer_schema: dict
Schema used when calling schemaless_writer
reader_schema: dict, optional
If the schema has changed since being writte... | def schemaless_reader(fo, writer_schema, reader_schema=None):
"""Reads a single record writen using the
:meth:`~fastavro._write_py.schemaless_writer`
Parameters
----------
fo: file-like
Input stream
writer_schema: dict
Schema used when calling schemaless_writer
reader_schema... |
Converts datetime.datetime to int timestamp with microseconds | def prepare_timestamp_micros(data, schema):
"""Converts datetime.datetime to int timestamp with microseconds"""
if isinstance(data, datetime.datetime):
if data.tzinfo is not None:
delta = (data - epoch)
return int(delta.total_seconds() * MCS_PER_SECOND)
t = int(time.mktim... |
Return True if path (or buffer) points to an Avro file.
Parameters
----------
path_or_buffer: path to file or file-like object
Path to file | def is_avro(path_or_buffer):
"""Return True if path (or buffer) points to an Avro file.
Parameters
----------
path_or_buffer: path to file or file-like object
Path to file
"""
if is_str(path_or_buffer):
fp = open(path_or_buffer, 'rb')
close = True
else:
fp = ... |
Converts datetime.date to int timestamp | def prepare_date(data, schema):
"""Converts datetime.date to int timestamp"""
if isinstance(data, datetime.date):
return data.toordinal() - DAYS_SHIFT
else:
return data |
Converts uuid.UUID to
string formatted UUID xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx | def prepare_uuid(data, schema):
"""Converts uuid.UUID to
string formatted UUID xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
"""
if isinstance(data, uuid.UUID):
return str(data)
else:
return data |
Converts datetime.datetime object to int timestamp with milliseconds | def prepare_timestamp_millis(data, schema):
"""Converts datetime.datetime object to int timestamp with milliseconds
"""
if isinstance(data, datetime.datetime):
if data.tzinfo is not None:
delta = (data - epoch)
return int(delta.total_seconds() * MLS_PER_SECOND)
t = in... |
Convert datetime.time to int timestamp with milliseconds | def prepare_time_millis(data, schema):
"""Convert datetime.time to int timestamp with milliseconds"""
if isinstance(data, datetime.time):
return int(
data.hour * MLS_PER_HOUR + data.minute * MLS_PER_MINUTE
+ data.second * MLS_PER_SECOND + int(data.microsecond / 1000))
else:
... |
Convert datetime.time to int timestamp with microseconds | def prepare_time_micros(data, schema):
"""Convert datetime.time to int timestamp with microseconds"""
if isinstance(data, datetime.time):
return long(data.hour * MCS_PER_HOUR + data.minute * MCS_PER_MINUTE
+ data.second * MCS_PER_SECOND + data.microsecond)
else:
return da... |
Convert decimal.Decimal to bytes | def prepare_bytes_decimal(data, schema):
"""Convert decimal.Decimal to bytes"""
if not isinstance(data, decimal.Decimal):
return data
scale = schema.get('scale', 0)
# based on https://github.com/apache/avro/pull/82/
sign, digits, exp = data.as_tuple()
if -exp > scale:
raise Va... |
Converts decimal.Decimal to fixed length bytes array | def prepare_fixed_decimal(data, schema):
"""Converts decimal.Decimal to fixed length bytes array"""
if not isinstance(data, decimal.Decimal):
return data
scale = schema.get('scale', 0)
size = schema['size']
# based on https://github.com/apache/avro/pull/82/
sign, digits, exp = data.as_... |
int and long values are written using variable-length, zig-zag coding. | def write_int(fo, datum, schema=None):
"""int and long values are written using variable-length, zig-zag coding.
"""
datum = (datum << 1) ^ (datum >> 63)
while (datum & ~0x7F) != 0:
fo.write(pack('B', (datum & 0x7f) | 0x80))
datum >>= 7
fo.write(pack('B', datum)) |
Bytes are encoded as a long followed by that many bytes of data. | def write_bytes(fo, datum, schema=None):
"""Bytes are encoded as a long followed by that many bytes of data."""
write_long(fo, len(datum))
fo.write(datum) |
A 4-byte, big-endian CRC32 checksum | def write_crc32(fo, bytes):
"""A 4-byte, big-endian CRC32 checksum"""
data = crc32(bytes) & 0xFFFFFFFF
fo.write(pack('>I', data)) |
An enum is encoded by a int, representing the zero-based position of
the symbol in the schema. | def write_enum(fo, datum, schema):
"""An enum is encoded by a int, representing the zero-based position of
the symbol in the schema."""
index = schema['symbols'].index(datum)
write_int(fo, index) |
Arrays are encoded as a series of blocks.
Each block consists of a long count value, followed by that many array
items. A block with count zero indicates the end of the array. Each item
is encoded per the array's item schema.
If a block's count is negative, then the count is followed immediately by ... | def write_array(fo, datum, schema):
"""Arrays are encoded as a series of blocks.
Each block consists of a long count value, followed by that many array
items. A block with count zero indicates the end of the array. Each item
is encoded per the array's item schema.
If a block's count is negative,... |
Maps are encoded as a series of blocks.
Each block consists of a long count value, followed by that many key/value
pairs. A block with count zero indicates the end of the map. Each item is
encoded per the map's value schema.
If a block's count is negative, then the count is followed immediately by a... | def write_map(fo, datum, schema):
"""Maps are encoded as a series of blocks.
Each block consists of a long count value, followed by that many key/value
pairs. A block with count zero indicates the end of the map. Each item is
encoded per the map's value schema.
If a block's count is negative, th... |
A union is encoded by first writing a long value indicating the
zero-based position within the union of the schema of its value. The value
is then encoded per the indicated schema within the union. | def write_union(fo, datum, schema):
"""A union is encoded by first writing a long value indicating the
zero-based position within the union of the schema of its value. The value
is then encoded per the indicated schema within the union."""
if isinstance(datum, tuple):
(name, datum) = datum
... |
A record is encoded by encoding the values of its fields in the order
that they are declared. In other words, a record is encoded as just the
concatenation of the encodings of its fields. Field values are encoded per
their schema. | def write_record(fo, datum, schema):
"""A record is encoded by encoding the values of its fields in the order
that they are declared. In other words, a record is encoded as just the
concatenation of the encodings of its fields. Field values are encoded per
their schema."""
for field in schema['fiel... |
Write a datum of data to output stream.
Paramaters
----------
fo: file-like
Output file
datum: object
Data to write
schema: dict
Schemda to use | def write_data(fo, datum, schema):
"""Write a datum of data to output stream.
Paramaters
----------
fo: file-like
Output file
datum: object
Data to write
schema: dict
Schemda to use
"""
record_type = extract_record_type(schema)
logical_type = extract_logical... |
Write block in "null" codec. | def null_write_block(fo, block_bytes):
"""Write block in "null" codec."""
write_long(fo, len(block_bytes))
fo.write(block_bytes) |
Write block in "deflate" codec. | def deflate_write_block(fo, block_bytes):
"""Write block in "deflate" codec."""
# The first two characters and last character are zlib
# wrappers around deflate data.
data = compress(block_bytes)[2:-1]
write_long(fo, len(data))
fo.write(data) |
Write records to fo (stream) according to schema
Parameters
----------
fo: file-like
Output stream
records: iterable
Records to write. This is commonly a list of the dictionary
representation of the records, but it can be any iterable
codec: string, optional
Compress... | def writer(fo,
schema,
records,
codec='null',
sync_interval=1000 * SYNC_SIZE,
metadata=None,
validator=None,
sync_marker=None):
"""Write records to fo (stream) according to schema
Parameters
----------
fo: file-like
Ou... |
Write a single record without the schema or header information
Parameters
----------
fo: file-like
Output file
schema: dict
Schema
record: dict
Record to write
Example::
parsed_schema = fastavro.parse_schema(schema)
with open('file.avro', 'rb') as fp:
... | def schemaless_writer(fo, schema, record):
"""Write a single record without the schema or header information
Parameters
----------
fo: file-like
Output file
schema: dict
Schema
record: dict
Record to write
Example::
parsed_schema = fastavro.parse_schema(sc... |
A decorator that defines __unicode__ and __str__ methods under Python 2.
Under Python 3 it does nothing.
To support Python 2 and 3 with a single code base, define a __str__ method
returning text and apply this decorator to the class. | def python_2_unicode_compatible(klass):
"""
A decorator that defines __unicode__ and __str__ methods under Python 2.
Under Python 3 it does nothing.
To support Python 2 and 3 with a single code base, define a __str__ method
returning text and apply this decorator to the class.
"""
if sys.ver... |
Check that the data value is a non floating
point number with size less that Int32.
Also support for logicalType timestamp validation with datetime.
Int32 = -2147483648<=datum<=2147483647
conditional python types
(int, long, numbers.Integral,
datetime.time, datetime.datetime, datetime.date)
... | def validate_int(datum, **kwargs):
"""
Check that the data value is a non floating
point number with size less that Int32.
Also support for logicalType timestamp validation with datetime.
Int32 = -2147483648<=datum<=2147483647
conditional python types
(int, long, numbers.Integral,
date... |
Check that the data value is a non floating
point number with size less that long64.
* Also support for logicalType timestamp validation with datetime.
Int64 = -9223372036854775808 <= datum <= 9223372036854775807
conditional python types
(int, long, numbers.Integral,
datetime.time, datetime.da... | def validate_long(datum, **kwargs):
"""
Check that the data value is a non floating
point number with size less that long64.
* Also support for logicalType timestamp validation with datetime.
Int64 = -9223372036854775808 <= datum <= 9223372036854775807
conditional python types
(int, long, ... |
Check that the data value is a floating
point number or double precision.
conditional python types
(int, long, float, numbers.Real)
Parameters
----------
datum: Any
Data being validated
kwargs: Any
Unused kwargs | def validate_float(datum, **kwargs):
"""
Check that the data value is a floating
point number or double precision.
conditional python types
(int, long, float, numbers.Real)
Parameters
----------
datum: Any
Data being validated
kwargs: Any
Unused kwargs
"""
r... |
Check that the data value is fixed width bytes,
matching the schema['size'] exactly!
Parameters
----------
datum: Any
Data being validated
schema: dict
Schema
kwargs: Any
Unused kwargs | def validate_fixed(datum, schema, **kwargs):
"""
Check that the data value is fixed width bytes,
matching the schema['size'] exactly!
Parameters
----------
datum: Any
Data being validated
schema: dict
Schema
kwargs: Any
Unused kwargs
"""
return (
... |
Check that the data list values all match schema['items'].
Parameters
----------
datum: Any
Data being validated
schema: dict
Schema
parent_ns: str
parent namespace
raise_errors: bool
If true, raises ValidationError on invalid data | def validate_array(datum, schema, parent_ns=None, raise_errors=True):
"""
Check that the data list values all match schema['items'].
Parameters
----------
datum: Any
Data being validated
schema: dict
Schema
parent_ns: str
parent namespace
raise_errors: bool
... |
Check that the data is a Map(k,v)
matching values to schema['values'] type.
Parameters
----------
datum: Any
Data being validated
schema: dict
Schema
parent_ns: str
parent namespace
raise_errors: bool
If true, raises ValidationError on invalid data | def validate_map(datum, schema, parent_ns=None, raise_errors=True):
"""
Check that the data is a Map(k,v)
matching values to schema['values'] type.
Parameters
----------
datum: Any
Data being validated
schema: dict
Schema
parent_ns: str
parent namespace
raise... |
Check that the data is a Mapping type with all schema defined fields
validated as True.
Parameters
----------
datum: Any
Data being validated
schema: dict
Schema
parent_ns: str
parent namespace
raise_errors: bool
If true, raises ValidationError on invalid dat... | def validate_record(datum, schema, parent_ns=None, raise_errors=True):
"""
Check that the data is a Mapping type with all schema defined fields
validated as True.
Parameters
----------
datum: Any
Data being validated
schema: dict
Schema
parent_ns: str
parent name... |
Check that the data is a list type with possible options to
validate as True.
Parameters
----------
datum: Any
Data being validated
schema: dict
Schema
parent_ns: str
parent namespace
raise_errors: bool
If true, raises ValidationError on invalid data | def validate_union(datum, schema, parent_ns=None, raise_errors=True):
"""
Check that the data is a list type with possible options to
validate as True.
Parameters
----------
datum: Any
Data being validated
schema: dict
Schema
parent_ns: str
parent namespace
r... |
Determine if a python datum is an instance of a schema.
Parameters
----------
datum: Any
Data being validated
schema: dict
Schema
field: str, optional
Record field being validated
raise_errors: bool, optional
If true, errors are raised for invalid data. If false,... | def validate(datum, schema, field=None, raise_errors=True):
"""
Determine if a python datum is an instance of a schema.
Parameters
----------
datum: Any
Data being validated
schema: dict
Schema
field: str, optional
Record field being validated
raise_errors: bool,... |
Validate a list of data!
Parameters
----------
records: iterable
List of records to validate
schema: dict
Schema
raise_errors: bool, optional
If true, errors are raised for invalid data. If false, a simple
True (valid) or False (invalid) result is returned
Exam... | def validate_many(records, schema, raise_errors=True):
"""
Validate a list of data!
Parameters
----------
records: iterable
List of records to validate
schema: dict
Schema
raise_errors: bool, optional
If true, errors are raised for invalid data. If false, a simple
... |
Returns a parsed avro schema
It is not necessary to call parse_schema but doing so and saving the parsed
schema for use later will make future operations faster as the schema will
not need to be reparsed.
Parameters
----------
schema: dict
Input schema
_write_hint: bool
Int... | def parse_schema(schema, _write_hint=True, _force=False):
"""Returns a parsed avro schema
It is not necessary to call parse_schema but doing so and saving the parsed
schema for use later will make future operations faster as the schema will
not need to be reparsed.
Parameters
----------
sc... |
Returns a schema loaded from the file at `schema_path`.
Will recursively load referenced schemas assuming they can be found in
files in the same directory and named with the convention
`<type_name>.avsc`. | def load_schema(schema_path):
'''
Returns a schema loaded from the file at `schema_path`.
Will recursively load referenced schemas assuming they can be found in
files in the same directory and named with the convention
`<type_name>.avsc`.
'''
with open(schema_path) as fd:
schema = j... |
Display text in tooltip window | def showtip(self, text):
"Display text in tooltip window"
self.text = text
if self.tipwindow or not self.text:
return
x, y, cx, cy = self.widget.bbox("insert")
x = x + self.widget.winfo_rootx() + 27
y = y + cy + self.widget.winfo_rooty() +27
self.tipwi... |
Ejecute the main loop. | def run(self):
"""Ejecute the main loop."""
self.toplevel.protocol("WM_DELETE_WINDOW", self.__on_window_close)
self.toplevel.mainloop() |
Hide and show scrollbar as needed.
Code from Joe English (JE) at http://wiki.tcl.tk/950 | def _autoscroll(sbar, first, last):
"""Hide and show scrollbar as needed.
Code from Joe English (JE) at http://wiki.tcl.tk/950"""
first, last = float(first), float(last)
if first <= 0 and last >= 1:
sbar.grid_remove()
else:
sbar.grid()
sbar.set(first, last) |
Create a regular polygon | def create_regpoly(self, x0, y0, x1, y1, sides=0, start=90, extent=360, **kw):
"""Create a regular polygon"""
coords = self.__regpoly_coords(x0, y0, x1, y1, sides, start, extent)
return self.canvas.create_polygon(*coords, **kw) |
Create the coordinates of the regular polygon specified | def __regpoly_coords(self, x0, y0, x1, y1, sides, start, extent):
"""Create the coordinates of the regular polygon specified"""
coords = []
if extent == 0:
return coords
xm = (x0 + x1) / 2.
ym = (y0 + y1) / 2.
rx = xm - x0
ry = ym - y0
n = s... |
Deletes unused grid row/cols | def remove_unused_grid_rc(self):
"""Deletes unused grid row/cols"""
if 'columns' in self['layout']:
ckeys = tuple(self['layout']['columns'].keys())
for key in ckeys:
value = int(key)
if value > self.max_col:
del self['layout'][... |
Return tk image corresponding to name which is taken form path. | def get_image(self, path):
"""Return tk image corresponding to name which is taken form path."""
image = ''
name = os.path.basename(path)
if not StockImage.is_registered(name):
ipath = self.__find_image(path)
if ipath is not None:
StockImage.regist... |
Helper method to avoid call get_variable for every variable. | def import_variables(self, container, varnames=None):
"""Helper method to avoid call get_variable for every variable."""
if varnames is None:
for keyword in self.tkvariables:
setattr(container, keyword, self.tkvariables[keyword])
else:
for keyword in varna... |
Create a tk variable.
If the variable was created previously return that instance. | def create_variable(self, varname, vtype=None):
"""Create a tk variable.
If the variable was created previously return that instance.
"""
var_types = ('string', 'int', 'boolean', 'double')
vname = varname
var = None
type_from_name = 'string' # default type
... |
Load ui definition from file. | def add_from_file(self, fpath):
"""Load ui definition from file."""
if self.tree is None:
base, name = os.path.split(fpath)
self.add_resource_path(base)
self.tree = tree = ET.parse(fpath)
self.root = tree.getroot()
self.objects = {}
els... |
Load ui definition from string. | def add_from_string(self, strdata):
"""Load ui definition from string."""
if self.tree is None:
self.tree = tree = ET.ElementTree(ET.fromstring(strdata))
self.root = tree.getroot()
self.objects = {}
else:
# TODO: append to current tree
... |
Load ui definition from xml.etree.Element node. | def add_from_xmlnode(self, element):
"""Load ui definition from xml.etree.Element node."""
if self.tree is None:
root = ET.Element('interface')
root.append(element)
self.tree = tree = ET.ElementTree(root)
self.root = tree.getroot()
self.objects... |
Find and create the widget named name.
Use master as parent. If widget was already created, return
that instance. | def get_object(self, name, master=None):
"""Find and create the widget named name.
Use master as parent. If widget was already created, return
that instance."""
widget = None
if name in self.objects:
widget = self.objects[name].widget
else:
xpath =... |
Builds a widget from xml element using master as parent. | def _realize(self, master, element):
"""Builds a widget from xml element using master as parent."""
data = data_xmlnode_to_dict(element, self.translator)
cname = data['class']
uniqueid = data['id']
if cname not in CLASS_MAP:
self._import_class(cname)
if cna... |
Connect callbacks specified in callbacks_bag with callbacks
defined in the ui definition.
Return a list with the name of the callbacks not connected. | def connect_callbacks(self, callbacks_bag):
"""Connect callbacks specified in callbacks_bag with callbacks
defined in the ui definition.
Return a list with the name of the callbacks not connected.
"""
notconnected = []
for wname, builderobj in self.objects.items():
... |
Comienza con el proceso de seleccion. | def _start_selecting(self, event):
"""Comienza con el proceso de seleccion."""
self._selecting = True
canvas = self._canvas
x = canvas.canvasx(event.x)
y = canvas.canvasy(event.y)
self._sstart = (x, y)
if not self._sobject:
self._sobject = canvas.creat... |
Continua con el proceso de seleccion.
Crea o redimensiona el cuadro de seleccion de acuerdo con
la posicion del raton. | def _keep_selecting(self, event):
"""Continua con el proceso de seleccion.
Crea o redimensiona el cuadro de seleccion de acuerdo con
la posicion del raton."""
canvas = self._canvas
x = canvas.canvasx(event.x)
y = canvas.canvasy(event.y)
canvas.coords(self._sobject... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.