_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q228100
once
train
def once(func): """Runs a thing once and once only.""" lock = threading.Lock() def new_func(*args, **kwargs): if new_func.called: return with lock: if new_func.called: return rv = func(*args, **kwargs) new_func.called = True ...
python
{ "resource": "" }
q228101
get_host
train
def get_host(request): """ A reimplementation of Django's get_host, without the SuspiciousOperation check. """ # We try three options, in order of decreasing preference. if settings.USE_X_FORWARDED_HOST and ( 'HTTP_X_FORWARDED_HOST' in request.META): host = request.META['HTTP...
python
{ "resource": "" }
q228102
install_middleware
train
def install_middleware(middleware_name, lookup_names=None): """ Install specified middleware """ if lookup_names is None: lookup_names = (middleware_name,) # default settings.MIDDLEWARE is None middleware_attr = 'MIDDLEWARE' if getattr(settings, ...
python
{ "resource": "" }
q228103
_fit_and_score
train
def _fit_and_score(est, x, y, scorer, train_index, test_index, parameters, fit_params, predict_params): """Train survival model on given data and return its score on test data""" X_train, y_train = _safe_split(est, x, y, train_index) train_params = fit_params.copy() # Training est.set_params(**para...
python
{ "resource": "" }
q228104
CoxnetSurvivalAnalysis._interpolate_coefficients
train
def _interpolate_coefficients(self, alpha): """Interpolate coefficients by calculating the weighted average of coefficient vectors corresponding to neighbors of alpha in the list of alphas constructed during training.""" exact = False coef_idx = None for i, val in enumerate(self....
python
{ "resource": "" }
q228105
CoxnetSurvivalAnalysis.predict
train
def predict(self, X, alpha=None): """The linear predictor of the model. Parameters ---------- X : array-like, shape = (n_samples, n_features) Test data of which to calculate log-likelihood from alpha : float, optional Constant that multiplies the penalty...
python
{ "resource": "" }
q228106
BaseEnsembleSelection._create_base_ensemble
train
def _create_base_ensemble(self, out, n_estimators, n_folds): """For each base estimator collect models trained on each fold""" ensemble_scores = numpy.empty((n_estimators, n_folds)) base_ensemble = numpy.empty_like(ensemble_scores, dtype=numpy.object) for model, fold, score, est in out: ...
python
{ "resource": "" }
q228107
BaseEnsembleSelection._create_cv_ensemble
train
def _create_cv_ensemble(self, base_ensemble, idx_models_included, model_names=None): """For each selected base estimator, average models trained on each fold""" fitted_models = numpy.empty(len(idx_models_included), dtype=numpy.object) for i, idx in enumerate(idx_models_included): mod...
python
{ "resource": "" }
q228108
BaseEnsembleSelection._get_base_estimators
train
def _get_base_estimators(self, X): """Takes special care of estimators using custom kernel function Parameters ---------- X : array, shape = (n_samples, n_features) Samples to pre-compute kernel matrix from. Returns ------- base_estimators : list ...
python
{ "resource": "" }
q228109
BaseEnsembleSelection._restore_base_estimators
train
def _restore_base_estimators(self, kernel_cache, out, X, cv): """Restore custom kernel functions of estimators for predictions""" train_folds = {fold: train_index for fold, (train_index, _) in enumerate(cv)} for idx, fold, _, est in out: if idx in kernel_cache: if no...
python
{ "resource": "" }
q228110
BaseEnsembleSelection._fit_and_score_ensemble
train
def _fit_and_score_ensemble(self, X, y, cv, **fit_params): """Create a cross-validated model by training a model for each fold with the same model parameters""" fit_params_steps = self._split_fit_params(fit_params) folds = list(cv.split(X, y)) # Take care of custom kernel functions ...
python
{ "resource": "" }
q228111
BaseEnsembleSelection.fit
train
def fit(self, X, y=None, **fit_params): """Fit ensemble of models Parameters ---------- X : array-like, shape = (n_samples, n_features) Training data. y : array-like, optional Target data if base estimators are supervised. Returns ------...
python
{ "resource": "" }
q228112
writearff
train
def writearff(data, filename, relation_name=None, index=True): """Write ARFF file Parameters ---------- data : :class:`pandas.DataFrame` DataFrame containing data filename : string or file-like object Path to ARFF file or file-like object. In the latter case, the handle is ...
python
{ "resource": "" }
q228113
_write_header
train
def _write_header(data, fp, relation_name, index): """Write header containing attribute names and types""" fp.write("@relation {0}\n\n".format(relation_name)) if index: data = data.reset_index() attribute_names = _sanitize_column_names(data) for column, series in data.iteritems(): ...
python
{ "resource": "" }
q228114
_sanitize_column_names
train
def _sanitize_column_names(data): """Replace illegal characters with underscore""" new_names = {} for name in data.columns: new_names[name] = _ILLEGAL_CHARACTER_PAT.sub("_", name) return new_names
python
{ "resource": "" }
q228115
_write_data
train
def _write_data(data, fp): """Write the data section""" fp.write("@data\n") def to_str(x): if pandas.isnull(x): return '?' else: return str(x) data = data.applymap(to_str) n_rows = data.shape[0] for i in range(n_rows): str_values = list(data.iloc...
python
{ "resource": "" }
q228116
Stacking.fit
train
def fit(self, X, y=None, **fit_params): """Fit base estimators. Parameters ---------- X : array-like, shape = (n_samples, n_features) Training data. y : array-like, optional Target data if base estimators are supervised. Returns ------- ...
python
{ "resource": "" }
q228117
standardize
train
def standardize(table, with_std=True): """ Perform Z-Normalization on each numeric column of the given table. Parameters ---------- table : pandas.DataFrame or numpy.ndarray Data to standardize. with_std : bool, optional, default: True If ``False`` data is only centered and not...
python
{ "resource": "" }
q228118
encode_categorical
train
def encode_categorical(table, columns=None, **kwargs): """ Encode categorical columns with `M` categories into `M-1` columns according to the one-hot scheme. Parameters ---------- table : pandas.DataFrame Table with categorical columns to encode. columns : list-like, optional, defa...
python
{ "resource": "" }
q228119
categorical_to_numeric
train
def categorical_to_numeric(table): """Encode categorical columns to numeric by converting each category to an integer value. Parameters ---------- table : pandas.DataFrame Table with categorical columns to encode. Returns ------- encoded : pandas.DataFrame Table with ca...
python
{ "resource": "" }
q228120
check_y_survival
train
def check_y_survival(y_or_event, *args, allow_all_censored=False): """Check that array correctly represents an outcome for survival analysis. Parameters ---------- y_or_event : structured array with two fields, or boolean array If a structured array, it must contain the binary event indicator ...
python
{ "resource": "" }
q228121
check_arrays_survival
train
def check_arrays_survival(X, y, **kwargs): """Check that all arrays have consistent first dimensions. Parameters ---------- X : array-like Data matrix containing feature vectors. y : structured array with two fields A structured array containing the binary event indicator a...
python
{ "resource": "" }
q228122
Surv.from_arrays
train
def from_arrays(event, time, name_event=None, name_time=None): """Create structured array. Parameters ---------- event : array-like Event indicator. A boolean array or array with values 0/1. time : array-like Observed time. name_event : str|None ...
python
{ "resource": "" }
q228123
Surv.from_dataframe
train
def from_dataframe(event, time, data): """Create structured array from data frame. Parameters ---------- event : object Identifier of column containing event indicator. time : object Identifier of column containing time. data : pandas.DataFrame ...
python
{ "resource": "" }
q228124
CoxPH.update_terminal_regions
train
def update_terminal_regions(self, tree, X, y, residual, y_pred, sample_weight, sample_mask, learning_rate=1.0, k=0): """Least squares does not need to update terminal regions. But it has to update the predictions. """ # upd...
python
{ "resource": "" }
q228125
build_from_c_and_cpp_files
train
def build_from_c_and_cpp_files(extensions): """Modify the extensions to build from the .c and .cpp files. This is useful for releases, this way cython is not required to run python setup.py install. """ for extension in extensions: sources = [] for sfile in extension.sources: ...
python
{ "resource": "" }
q228126
SurvivalCounter._count_values
train
def _count_values(self): """Return dict mapping relevance level to sample index""" indices = {yi: [i] for i, yi in enumerate(self.y) if self.status[i]} return indices
python
{ "resource": "" }
q228127
BaseSurvivalSVM._create_optimizer
train
def _create_optimizer(self, X, y, status): """Samples are ordered by relevance""" if self.optimizer is None: self.optimizer = 'avltree' times, ranks = y if self.optimizer == 'simple': optimizer = SimpleOptimizer(X, status, self.alpha, self.rank_ratio, timeit=sel...
python
{ "resource": "" }
q228128
BaseSurvivalSVM._argsort_and_resolve_ties
train
def _argsort_and_resolve_ties(time, random_state): """Like numpy.argsort, but resolves ties uniformly at random""" n_samples = len(time) order = numpy.argsort(time, kind="mergesort") i = 0 while i < n_samples - 1: inext = i + 1 while inext < n_samples and...
python
{ "resource": "" }
q228129
IPCRidge.fit
train
def fit(self, X, y): """Build an accelerated failure time 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 ...
python
{ "resource": "" }
q228130
BreslowEstimator.fit
train
def fit(self, linear_predictor, event, time): """Compute baseline cumulative hazard function. Parameters ---------- linear_predictor : array-like, shape = (n_samples,) Linear predictor of risk: `X @ coef`. event : array-like, shape = (n_samples,) Contain...
python
{ "resource": "" }
q228131
CoxPHOptimizer.nlog_likelihood
train
def nlog_likelihood(self, w): """Compute negative partial log-likelihood Parameters ---------- w : array, shape = (n_features,) Estimate of coefficients Returns ------- loss : float Average negative partial log-likelihood """ ...
python
{ "resource": "" }
q228132
CoxPHOptimizer.update
train
def update(self, w, offset=0): """Compute gradient and Hessian matrix with respect to `w`.""" time = self.time x = self.x exp_xw = numpy.exp(offset + numpy.dot(x, w)) n_samples, n_features = x.shape gradient = numpy.zeros((1, n_features), dtype=float) hessian = n...
python
{ "resource": "" }
q228133
CoxPHSurvivalAnalysis.fit
train
def fit(self, X, y): """Minimize negative partial log-likelihood for provided data. Parameters ---------- X : array-like, shape = (n_samples, n_features) Data matrix y : structured array, shape = (n_samples,) A structured array containing the binary even...
python
{ "resource": "" }
q228134
_compute_counts
train
def _compute_counts(event, time, order=None): """Count right censored and uncensored samples at each unique time point. Parameters ---------- event : array Boolean event indicator. time : array Survival time or time of censoring. order : array or None Indices to order ...
python
{ "resource": "" }
q228135
_compute_counts_truncated
train
def _compute_counts_truncated(event, time_enter, time_exit): """Compute counts for left truncated and right censored survival data. Parameters ---------- event : array Boolean event indicator. time_start : array Time when a subject entered the study. time_exit : array ...
python
{ "resource": "" }
q228136
kaplan_meier_estimator
train
def kaplan_meier_estimator(event, time_exit, time_enter=None, time_min=None): """Kaplan-Meier estimator of survival function. Parameters ---------- event : array-like, shape = (n_samples,) Contains binary event indicators. time_exit : array-like, shape = (n_samples,) Contains event...
python
{ "resource": "" }
q228137
nelson_aalen_estimator
train
def nelson_aalen_estimator(event, time): """Nelson-Aalen estimator of cumulative hazard function. Parameters ---------- event : array-like, shape = (n_samples,) Contains binary event indicators. time : array-like, shape = (n_samples,) Contains event/censoring times. Returns ...
python
{ "resource": "" }
q228138
ipc_weights
train
def ipc_weights(event, time): """Compute inverse probability of censoring weights Parameters ---------- event : array, shape = (n_samples,) Boolean event indicator. time : array, shape = (n_samples,) Time when a subject experienced an event or was censored. Returns -------...
python
{ "resource": "" }
q228139
SurvivalFunctionEstimator.fit
train
def fit(self, y): """Estimate survival distribution from training data. Parameters ---------- y : structured array, shape = (n_samples,) A structured array containing the binary event indicator as first field, and time of event or time of censoring as ...
python
{ "resource": "" }
q228140
SurvivalFunctionEstimator.predict_proba
train
def predict_proba(self, time): """Return probability of an event after given time point. :math:`\\hat{S}(t) = P(T > t)` Parameters ---------- time : array, shape = (n_samples,) Time to estimate probability at. Returns ------- prob : array, s...
python
{ "resource": "" }
q228141
CensoringDistributionEstimator.fit
train
def fit(self, y): """Estimate censoring distribution from training data. Parameters ---------- y : structured array, shape = (n_samples,) A structured array containing the binary event indicator as first field, and time of event or time of censoring as ...
python
{ "resource": "" }
q228142
CensoringDistributionEstimator.predict_ipcw
train
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...
python
{ "resource": "" }
q228143
concordance_index_censored
train
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...
python
{ "resource": "" }
q228144
concordance_index_ipcw
train
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...
python
{ "resource": "" }
q228145
_nominal_kernel
train
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
python
{ "resource": "" }
q228146
_get_continuous_and_ordinal_array
train
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...
python
{ "resource": "" }
q228147
clinical_kernel
train
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...
python
{ "resource": "" }
q228148
ClinicalKernelTransform._prepare_by_column_dtype
train
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...
python
{ "resource": "" }
q228149
ClinicalKernelTransform.fit
train
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...
python
{ "resource": "" }
q228150
ClinicalKernelTransform.transform
train
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...
python
{ "resource": "" }
q228151
_fit_stage_componentwise
train
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,...
python
{ "resource": "" }
q228152
ComponentwiseGradientBoostingSurvivalAnalysis.coef_
train
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...
python
{ "resource": "" }
q228153
GradientBoostingSurvivalAnalysis._fit_stage
train
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...
python
{ "resource": "" }
q228154
GradientBoostingSurvivalAnalysis._fit_stages
train
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...
python
{ "resource": "" }
q228155
GradientBoostingSurvivalAnalysis.fit
train
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...
python
{ "resource": "" }
q228156
GradientBoostingSurvivalAnalysis.staged_predict
train
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...
python
{ "resource": "" }
q228157
MinlipSurvivalAnalysis.fit
train
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...
python
{ "resource": "" }
q228158
MinlipSurvivalAnalysis.predict
train
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. ...
python
{ "resource": "" }
q228159
get_x_y
train
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...
python
{ "resource": "" }
q228160
load_arff_files_standardized
train
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...
python
{ "resource": "" }
q228161
load_aids
train
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 ---------...
python
{ "resource": "" }
q228162
_api_scrape
train
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...
python
{ "resource": "" }
q228163
get_player
train
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 ...
python
{ "resource": "" }
q228164
BasePokerPlayer.respond_to_ask
train
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)
python
{ "resource": "" }
q228165
BasePokerPlayer.receive_notification
train
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...
python
{ "resource": "" }
q228166
result_continuation
train
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...
python
{ "resource": "" }
q228167
result_processor
train
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
python
{ "resource": "" }
q228168
read_union
train
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...
python
{ "resource": "" }
q228169
read_data
train
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...
python
{ "resource": "" }
q228170
_iter_avro_records
train
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: ...
python
{ "resource": "" }
q228171
_iter_avro_blocks
train
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() ...
python
{ "resource": "" }
q228172
prepare_timestamp_millis
train
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...
python
{ "resource": "" }
q228173
prepare_timestamp_micros
train
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...
python
{ "resource": "" }
q228174
prepare_date
train
def prepare_date(data, schema): """Converts datetime.date to int timestamp""" if isinstance(data, datetime.date): return data.toordinal() - DAYS_SHIFT else: return data
python
{ "resource": "" }
q228175
prepare_uuid
train
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
python
{ "resource": "" }
q228176
prepare_time_millis
train
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: ...
python
{ "resource": "" }
q228177
prepare_time_micros
train
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...
python
{ "resource": "" }
q228178
prepare_bytes_decimal
train
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...
python
{ "resource": "" }
q228179
prepare_fixed_decimal
train
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_...
python
{ "resource": "" }
q228180
write_crc32
train
def write_crc32(fo, bytes): """A 4-byte, big-endian CRC32 checksum""" data = crc32(bytes) & 0xFFFFFFFF fo.write(pack('>I', data))
python
{ "resource": "" }
q228181
write_union
train
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 ...
python
{ "resource": "" }
q228182
write_data
train
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...
python
{ "resource": "" }
q228183
null_write_block
train
def null_write_block(fo, block_bytes): """Write block in "null" codec.""" write_long(fo, len(block_bytes)) fo.write(block_bytes)
python
{ "resource": "" }
q228184
deflate_write_block
train
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)
python
{ "resource": "" }
q228185
schemaless_writer
train
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...
python
{ "resource": "" }
q228186
validate_int
train
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...
python
{ "resource": "" }
q228187
validate_float
train
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...
python
{ "resource": "" }
q228188
validate_record
train
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...
python
{ "resource": "" }
q228189
validate_union
train
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...
python
{ "resource": "" }
q228190
validate_many
train
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 ...
python
{ "resource": "" }
q228191
parse_schema
train
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...
python
{ "resource": "" }
q228192
load_schema
train
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...
python
{ "resource": "" }
q228193
ToolTip.showtip
train
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...
python
{ "resource": "" }
q228194
TkApplication.run
train
def run(self): """Ejecute the main loop.""" self.toplevel.protocol("WM_DELETE_WINDOW", self.__on_window_close) self.toplevel.mainloop()
python
{ "resource": "" }
q228195
MyApplication.create_regpoly
train
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)
python
{ "resource": "" }
q228196
MyApplication.__regpoly_coords
train
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...
python
{ "resource": "" }
q228197
Builder.get_image
train
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...
python
{ "resource": "" }
q228198
Builder.import_variables
train
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...
python
{ "resource": "" }
q228199
Builder.create_variable
train
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 ...
python
{ "resource": "" }