repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
timothyb0912/pylogit | pylogit/bootstrap.py | Boot.calc_percentile_interval | def calc_percentile_interval(self, conf_percentage):
"""
Calculates percentile bootstrap confidence intervals for one's model.
Parameters
----------
conf_percentage : scalar in the interval (0.0, 100.0).
Denotes the confidence-level for the returned endpoints. For
... | python | def calc_percentile_interval(self, conf_percentage):
"""
Calculates percentile bootstrap confidence intervals for one's model.
Parameters
----------
conf_percentage : scalar in the interval (0.0, 100.0).
Denotes the confidence-level for the returned endpoints. For
... | [
"def",
"calc_percentile_interval",
"(",
"self",
",",
"conf_percentage",
")",
":",
"alpha",
"=",
"bc",
".",
"get_alpha_from_conf_percentage",
"(",
"conf_percentage",
")",
"single_column_names",
"=",
"[",
"'{:.3g}%'",
".",
"format",
"(",
"alpha",
"/",
"2.0",
")",
... | Calculates percentile bootstrap confidence intervals for one's model.
Parameters
----------
conf_percentage : scalar in the interval (0.0, 100.0).
Denotes the confidence-level for the returned endpoints. For
instance, to calculate a 95% confidence interval, pass `95`.
... | [
"Calculates",
"percentile",
"bootstrap",
"confidence",
"intervals",
"for",
"one",
"s",
"model",
"."
] | f83b0fd6debaa7358d87c3828428f6d4ead71357 | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/bootstrap.py#L663-L696 | train |
timothyb0912/pylogit | pylogit/bootstrap.py | Boot.calc_abc_interval | def calc_abc_interval(self,
conf_percentage,
init_vals,
epsilon=0.001,
**fit_kwargs):
"""
Calculates Approximate Bootstrap Confidence Intervals for one's model.
Parameters
----------
... | python | def calc_abc_interval(self,
conf_percentage,
init_vals,
epsilon=0.001,
**fit_kwargs):
"""
Calculates Approximate Bootstrap Confidence Intervals for one's model.
Parameters
----------
... | [
"def",
"calc_abc_interval",
"(",
"self",
",",
"conf_percentage",
",",
"init_vals",
",",
"epsilon",
"=",
"0.001",
",",
"**",
"fit_kwargs",
")",
":",
"print",
"(",
"\"Calculating Approximate Bootstrap Confidence (ABC) Intervals\"",
")",
"print",
"(",
"time",
".",
"str... | Calculates Approximate Bootstrap Confidence Intervals for one's model.
Parameters
----------
conf_percentage : scalar in the interval (0.0, 100.0).
Denotes the confidence-level for the returned endpoints. For
instance, to calculate a 95% confidence interval, pass `95`.
... | [
"Calculates",
"Approximate",
"Bootstrap",
"Confidence",
"Intervals",
"for",
"one",
"s",
"model",
"."
] | f83b0fd6debaa7358d87c3828428f6d4ead71357 | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/bootstrap.py#L737-L788 | train |
timothyb0912/pylogit | pylogit/bootstrap.py | Boot.calc_conf_intervals | def calc_conf_intervals(self,
conf_percentage,
interval_type='all',
init_vals=None,
epsilon=abc.EPSILON,
**fit_kwargs):
"""
Calculates percentile, bias-corrected an... | python | def calc_conf_intervals(self,
conf_percentage,
interval_type='all',
init_vals=None,
epsilon=abc.EPSILON,
**fit_kwargs):
"""
Calculates percentile, bias-corrected an... | [
"def",
"calc_conf_intervals",
"(",
"self",
",",
"conf_percentage",
",",
"interval_type",
"=",
"'all'",
",",
"init_vals",
"=",
"None",
",",
"epsilon",
"=",
"abc",
".",
"EPSILON",
",",
"**",
"fit_kwargs",
")",
":",
"if",
"interval_type",
"==",
"'pi'",
":",
"... | Calculates percentile, bias-corrected and accelerated, and approximate
bootstrap confidence intervals.
Parameters
----------
conf_percentage : scalar in the interval (0.0, 100.0).
Denotes the confidence-level for the returned endpoints. For
instance, to calculate... | [
"Calculates",
"percentile",
"bias",
"-",
"corrected",
"and",
"accelerated",
"and",
"approximate",
"bootstrap",
"confidence",
"intervals",
"."
] | f83b0fd6debaa7358d87c3828428f6d4ead71357 | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/bootstrap.py#L790-L879 | train |
timothyb0912/pylogit | pylogit/clog_log.py | create_calc_dh_d_alpha | def create_calc_dh_d_alpha(estimator):
"""
Return the function that can be used in the various gradient and hessian
calculations to calculate the derivative of the transformation with respect
to the outside intercept parameters.
Parameters
----------
estimator : an instance of the estimatio... | python | def create_calc_dh_d_alpha(estimator):
"""
Return the function that can be used in the various gradient and hessian
calculations to calculate the derivative of the transformation with respect
to the outside intercept parameters.
Parameters
----------
estimator : an instance of the estimatio... | [
"def",
"create_calc_dh_d_alpha",
"(",
"estimator",
")",
":",
"if",
"estimator",
".",
"intercept_ref_pos",
"is",
"not",
"None",
":",
"needed_idxs",
"=",
"range",
"(",
"estimator",
".",
"rows_to_alts",
".",
"shape",
"[",
"1",
"]",
")",
"needed_idxs",
".",
"rem... | Return the function that can be used in the various gradient and hessian
calculations to calculate the derivative of the transformation with respect
to the outside intercept parameters.
Parameters
----------
estimator : an instance of the estimation.LogitTypeEstimator class.
Should contain ... | [
"Return",
"the",
"function",
"that",
"can",
"be",
"used",
"in",
"the",
"various",
"gradient",
"and",
"hessian",
"calculations",
"to",
"calculate",
"the",
"derivative",
"of",
"the",
"transformation",
"with",
"respect",
"to",
"the",
"outside",
"intercept",
"parame... | f83b0fd6debaa7358d87c3828428f6d4ead71357 | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/clog_log.py#L374-L415 | train |
timothyb0912/pylogit | pylogit/estimation.py | calc_individual_chi_squares | def calc_individual_chi_squares(residuals,
long_probabilities,
rows_to_obs):
"""
Calculates individual chi-squared values for each choice situation in the
dataset.
Parameters
----------
residuals : 1D ndarray.
The choice ve... | python | def calc_individual_chi_squares(residuals,
long_probabilities,
rows_to_obs):
"""
Calculates individual chi-squared values for each choice situation in the
dataset.
Parameters
----------
residuals : 1D ndarray.
The choice ve... | [
"def",
"calc_individual_chi_squares",
"(",
"residuals",
",",
"long_probabilities",
",",
"rows_to_obs",
")",
":",
"chi_squared_terms",
"=",
"np",
".",
"square",
"(",
"residuals",
")",
"/",
"long_probabilities",
"return",
"rows_to_obs",
".",
"T",
".",
"dot",
"(",
... | Calculates individual chi-squared values for each choice situation in the
dataset.
Parameters
----------
residuals : 1D ndarray.
The choice vector minus the predicted probability of each alternative
for each observation.
long_probabilities : 1D ndarray.
The probability of ea... | [
"Calculates",
"individual",
"chi",
"-",
"squared",
"values",
"for",
"each",
"choice",
"situation",
"in",
"the",
"dataset",
"."
] | f83b0fd6debaa7358d87c3828428f6d4ead71357 | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/estimation.py#L424-L451 | train |
timothyb0912/pylogit | pylogit/estimation.py | calc_rho_and_rho_bar_squared | def calc_rho_and_rho_bar_squared(final_log_likelihood,
null_log_likelihood,
num_est_parameters):
"""
Calculates McFadden's rho-squared and rho-bar squared for the given model.
Parameters
----------
final_log_likelihood : float.
... | python | def calc_rho_and_rho_bar_squared(final_log_likelihood,
null_log_likelihood,
num_est_parameters):
"""
Calculates McFadden's rho-squared and rho-bar squared for the given model.
Parameters
----------
final_log_likelihood : float.
... | [
"def",
"calc_rho_and_rho_bar_squared",
"(",
"final_log_likelihood",
",",
"null_log_likelihood",
",",
"num_est_parameters",
")",
":",
"rho_squared",
"=",
"1.0",
"-",
"final_log_likelihood",
"/",
"null_log_likelihood",
"rho_bar_squared",
"=",
"1.0",
"-",
"(",
"(",
"final_... | Calculates McFadden's rho-squared and rho-bar squared for the given model.
Parameters
----------
final_log_likelihood : float.
The final log-likelihood of the model whose rho-squared and rho-bar
squared are being calculated for.
null_log_likelihood : float.
The log-likelihood of... | [
"Calculates",
"McFadden",
"s",
"rho",
"-",
"squared",
"and",
"rho",
"-",
"bar",
"squared",
"for",
"the",
"given",
"model",
"."
] | f83b0fd6debaa7358d87c3828428f6d4ead71357 | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/estimation.py#L454-L480 | train |
timothyb0912/pylogit | pylogit/estimation.py | calc_and_store_post_estimation_results | def calc_and_store_post_estimation_results(results_dict,
estimator):
"""
Calculates and stores post-estimation results that require the use of the
systematic utility transformation functions or the various derivative
functions. Note that this function is only v... | python | def calc_and_store_post_estimation_results(results_dict,
estimator):
"""
Calculates and stores post-estimation results that require the use of the
systematic utility transformation functions or the various derivative
functions. Note that this function is only v... | [
"def",
"calc_and_store_post_estimation_results",
"(",
"results_dict",
",",
"estimator",
")",
":",
"final_log_likelihood",
"=",
"-",
"1",
"*",
"results_dict",
"[",
"\"fun\"",
"]",
"results_dict",
"[",
"\"final_log_likelihood\"",
"]",
"=",
"final_log_likelihood",
"final_p... | Calculates and stores post-estimation results that require the use of the
systematic utility transformation functions or the various derivative
functions. Note that this function is only valid for logit-type models.
Parameters
----------
results_dict : dict.
This dictionary should be the di... | [
"Calculates",
"and",
"stores",
"post",
"-",
"estimation",
"results",
"that",
"require",
"the",
"use",
"of",
"the",
"systematic",
"utility",
"transformation",
"functions",
"or",
"the",
"various",
"derivative",
"functions",
".",
"Note",
"that",
"this",
"function",
... | f83b0fd6debaa7358d87c3828428f6d4ead71357 | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/estimation.py#L483-L583 | train |
timothyb0912/pylogit | pylogit/estimation.py | estimate | def estimate(init_values,
estimator,
method,
loss_tol,
gradient_tol,
maxiter,
print_results,
use_hessian=True,
just_point=False,
**kwargs):
"""
Estimate the given choice model that is defined by ... | python | def estimate(init_values,
estimator,
method,
loss_tol,
gradient_tol,
maxiter,
print_results,
use_hessian=True,
just_point=False,
**kwargs):
"""
Estimate the given choice model that is defined by ... | [
"def",
"estimate",
"(",
"init_values",
",",
"estimator",
",",
"method",
",",
"loss_tol",
",",
"gradient_tol",
",",
"maxiter",
",",
"print_results",
",",
"use_hessian",
"=",
"True",
",",
"just_point",
"=",
"False",
",",
"**",
"kwargs",
")",
":",
"if",
"not"... | Estimate the given choice model that is defined by `estimator`.
Parameters
----------
init_vals : 1D ndarray.
Should contain the initial values to start the optimization process
with.
estimator : an instance of the EstimationObj class.
method : str, optional.
Should be a val... | [
"Estimate",
"the",
"given",
"choice",
"model",
"that",
"is",
"defined",
"by",
"estimator",
"."
] | f83b0fd6debaa7358d87c3828428f6d4ead71357 | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/estimation.py#L586-L713 | train |
timothyb0912/pylogit | pylogit/estimation.py | EstimationObj.calc_neg_log_likelihood_and_neg_gradient | def calc_neg_log_likelihood_and_neg_gradient(self, params):
"""
Calculates and returns the negative of the log-likelihood and the
negative of the gradient. This function is used as the objective
function in scipy.optimize.minimize.
"""
neg_log_likelihood = -1 * self.conve... | python | def calc_neg_log_likelihood_and_neg_gradient(self, params):
"""
Calculates and returns the negative of the log-likelihood and the
negative of the gradient. This function is used as the objective
function in scipy.optimize.minimize.
"""
neg_log_likelihood = -1 * self.conve... | [
"def",
"calc_neg_log_likelihood_and_neg_gradient",
"(",
"self",
",",
"params",
")",
":",
"neg_log_likelihood",
"=",
"-",
"1",
"*",
"self",
".",
"convenience_calc_log_likelihood",
"(",
"params",
")",
"neg_gradient",
"=",
"-",
"1",
"*",
"self",
".",
"convenience_cal... | Calculates and returns the negative of the log-likelihood and the
negative of the gradient. This function is used as the objective
function in scipy.optimize.minimize. | [
"Calculates",
"and",
"returns",
"the",
"negative",
"of",
"the",
"log",
"-",
"likelihood",
"and",
"the",
"negative",
"of",
"the",
"gradient",
".",
"This",
"function",
"is",
"used",
"as",
"the",
"objective",
"function",
"in",
"scipy",
".",
"optimize",
".",
"... | f83b0fd6debaa7358d87c3828428f6d4ead71357 | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/estimation.py#L211-L223 | train |
timothyb0912/pylogit | pylogit/bootstrap_utils.py | ensure_samples_is_ndim_ndarray | def ensure_samples_is_ndim_ndarray(samples, name='bootstrap', ndim=2):
"""
Ensures that `samples` is an `ndim` numpy array. Raises a helpful
ValueError if otherwise.
"""
assert isinstance(ndim, int)
assert isinstance(name, str)
if not isinstance(samples, np.ndarray) or not (samples.ndim == n... | python | def ensure_samples_is_ndim_ndarray(samples, name='bootstrap', ndim=2):
"""
Ensures that `samples` is an `ndim` numpy array. Raises a helpful
ValueError if otherwise.
"""
assert isinstance(ndim, int)
assert isinstance(name, str)
if not isinstance(samples, np.ndarray) or not (samples.ndim == n... | [
"def",
"ensure_samples_is_ndim_ndarray",
"(",
"samples",
",",
"name",
"=",
"'bootstrap'",
",",
"ndim",
"=",
"2",
")",
":",
"assert",
"isinstance",
"(",
"ndim",
",",
"int",
")",
"assert",
"isinstance",
"(",
"name",
",",
"str",
")",
"if",
"not",
"isinstance"... | Ensures that `samples` is an `ndim` numpy array. Raises a helpful
ValueError if otherwise. | [
"Ensures",
"that",
"samples",
"is",
"an",
"ndim",
"numpy",
"array",
".",
"Raises",
"a",
"helpful",
"ValueError",
"if",
"otherwise",
"."
] | f83b0fd6debaa7358d87c3828428f6d4ead71357 | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/bootstrap_utils.py#L27-L38 | train |
timothyb0912/pylogit | pylogit/construct_estimator.py | create_estimation_obj | def create_estimation_obj(model_obj,
init_vals,
mappings=None,
ridge=None,
constrained_pos=None,
weights=None):
"""
Should return a model estimation object corresponding to the model... | python | def create_estimation_obj(model_obj,
init_vals,
mappings=None,
ridge=None,
constrained_pos=None,
weights=None):
"""
Should return a model estimation object corresponding to the model... | [
"def",
"create_estimation_obj",
"(",
"model_obj",
",",
"init_vals",
",",
"mappings",
"=",
"None",
",",
"ridge",
"=",
"None",
",",
"constrained_pos",
"=",
"None",
",",
"weights",
"=",
"None",
")",
":",
"mapping_matrices",
"=",
"model_obj",
".",
"get_mappings_fo... | Should return a model estimation object corresponding to the model type of
the `model_obj`.
Parameters
----------
model_obj : an instance or sublcass of the MNDC class.
init_vals : 1D ndarray.
The initial values to start the estimation process with. In the
following order, there sho... | [
"Should",
"return",
"a",
"model",
"estimation",
"object",
"corresponding",
"to",
"the",
"model",
"type",
"of",
"the",
"model_obj",
"."
] | f83b0fd6debaa7358d87c3828428f6d4ead71357 | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/construct_estimator.py#L54-L119 | train |
timothyb0912/pylogit | pylogit/bootstrap_abc.py | ensure_wide_weights_is_1D_or_2D_ndarray | def ensure_wide_weights_is_1D_or_2D_ndarray(wide_weights):
"""
Ensures that `wide_weights` is a 1D or 2D ndarray. Raises a helpful
ValueError if otherwise.
"""
if not isinstance(wide_weights, np.ndarray):
msg = "wide_weights MUST be a ndarray."
raise ValueError(msg)
ndim = wide_w... | python | def ensure_wide_weights_is_1D_or_2D_ndarray(wide_weights):
"""
Ensures that `wide_weights` is a 1D or 2D ndarray. Raises a helpful
ValueError if otherwise.
"""
if not isinstance(wide_weights, np.ndarray):
msg = "wide_weights MUST be a ndarray."
raise ValueError(msg)
ndim = wide_w... | [
"def",
"ensure_wide_weights_is_1D_or_2D_ndarray",
"(",
"wide_weights",
")",
":",
"if",
"not",
"isinstance",
"(",
"wide_weights",
",",
"np",
".",
"ndarray",
")",
":",
"msg",
"=",
"\"wide_weights MUST be a ndarray.\"",
"raise",
"ValueError",
"(",
"msg",
")",
"ndim",
... | Ensures that `wide_weights` is a 1D or 2D ndarray. Raises a helpful
ValueError if otherwise. | [
"Ensures",
"that",
"wide_weights",
"is",
"a",
"1D",
"or",
"2D",
"ndarray",
".",
"Raises",
"a",
"helpful",
"ValueError",
"if",
"otherwise",
"."
] | f83b0fd6debaa7358d87c3828428f6d4ead71357 | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/bootstrap_abc.py#L51-L63 | train |
timothyb0912/pylogit | pylogit/bootstrap_abc.py | check_validity_of_long_form_args | def check_validity_of_long_form_args(model_obj, wide_weights, rows_to_obs):
"""
Ensures the args to `create_long_form_weights` have expected properties.
"""
# Ensure model_obj has the necessary method for create_long_form_weights
ensure_model_obj_has_mapping_constructor(model_obj)
# Ensure wide_... | python | def check_validity_of_long_form_args(model_obj, wide_weights, rows_to_obs):
"""
Ensures the args to `create_long_form_weights` have expected properties.
"""
# Ensure model_obj has the necessary method for create_long_form_weights
ensure_model_obj_has_mapping_constructor(model_obj)
# Ensure wide_... | [
"def",
"check_validity_of_long_form_args",
"(",
"model_obj",
",",
"wide_weights",
",",
"rows_to_obs",
")",
":",
"ensure_model_obj_has_mapping_constructor",
"(",
"model_obj",
")",
"ensure_wide_weights_is_1D_or_2D_ndarray",
"(",
"wide_weights",
")",
"ensure_rows_to_obs_validity",
... | Ensures the args to `create_long_form_weights` have expected properties. | [
"Ensures",
"the",
"args",
"to",
"create_long_form_weights",
"have",
"expected",
"properties",
"."
] | f83b0fd6debaa7358d87c3828428f6d4ead71357 | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/bootstrap_abc.py#L66-L76 | train |
timothyb0912/pylogit | pylogit/bootstrap_abc.py | calc_finite_diff_terms_for_abc | def calc_finite_diff_terms_for_abc(model_obj,
mle_params,
init_vals,
epsilon,
**fit_kwargs):
"""
Calculates the terms needed for the finite difference approximations of
... | python | def calc_finite_diff_terms_for_abc(model_obj,
mle_params,
init_vals,
epsilon,
**fit_kwargs):
"""
Calculates the terms needed for the finite difference approximations of
... | [
"def",
"calc_finite_diff_terms_for_abc",
"(",
"model_obj",
",",
"mle_params",
",",
"init_vals",
",",
"epsilon",
",",
"**",
"fit_kwargs",
")",
":",
"num_obs",
"=",
"model_obj",
".",
"data",
"[",
"model_obj",
".",
"obs_id_col",
"]",
".",
"unique",
"(",
")",
".... | Calculates the terms needed for the finite difference approximations of
the empirical influence and second order empirical influence functions.
Parameters
----------
model_obj : an instance or sublcass of the MNDC class.
Should be the model object that corresponds to the model we are
co... | [
"Calculates",
"the",
"terms",
"needed",
"for",
"the",
"finite",
"difference",
"approximations",
"of",
"the",
"empirical",
"influence",
"and",
"second",
"order",
"empirical",
"influence",
"functions",
"."
] | f83b0fd6debaa7358d87c3828428f6d4ead71357 | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/bootstrap_abc.py#L123-L222 | train |
timothyb0912/pylogit | pylogit/bootstrap_abc.py | calc_abc_interval | def calc_abc_interval(model_obj,
mle_params,
init_vals,
conf_percentage,
epsilon=0.001,
**fit_kwargs):
"""
Calculate 'approximate bootstrap confidence' intervals.
Parameters
----------
mode... | python | def calc_abc_interval(model_obj,
mle_params,
init_vals,
conf_percentage,
epsilon=0.001,
**fit_kwargs):
"""
Calculate 'approximate bootstrap confidence' intervals.
Parameters
----------
mode... | [
"def",
"calc_abc_interval",
"(",
"model_obj",
",",
"mle_params",
",",
"init_vals",
",",
"conf_percentage",
",",
"epsilon",
"=",
"0.001",
",",
"**",
"fit_kwargs",
")",
":",
"check_conf_percentage_validity",
"(",
"conf_percentage",
")",
"empirical_influence",
",",
"se... | Calculate 'approximate bootstrap confidence' intervals.
Parameters
----------
model_obj : an instance or sublcass of the MNDC class.
Should be the model object that corresponds to the model we are
constructing the bootstrap confidence intervals for.
mle_params : 1D ndarray.
Shou... | [
"Calculate",
"approximate",
"bootstrap",
"confidence",
"intervals",
"."
] | f83b0fd6debaa7358d87c3828428f6d4ead71357 | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/bootstrap_abc.py#L1160-L1278 | train |
timothyb0912/pylogit | pylogit/mixed_logit.py | check_length_of_init_values | def check_length_of_init_values(design_3d, init_values):
"""
Ensures that the initial values are of the correct length, given the design
matrix that they will be dot-producted with. Raises a ValueError if that is
not the case, and provides a useful error message to users.
Parameters
----------
... | python | def check_length_of_init_values(design_3d, init_values):
"""
Ensures that the initial values are of the correct length, given the design
matrix that they will be dot-producted with. Raises a ValueError if that is
not the case, and provides a useful error message to users.
Parameters
----------
... | [
"def",
"check_length_of_init_values",
"(",
"design_3d",
",",
"init_values",
")",
":",
"if",
"init_values",
".",
"shape",
"[",
"0",
"]",
"!=",
"design_3d",
".",
"shape",
"[",
"2",
"]",
":",
"msg_1",
"=",
"\"The initial values are of the wrong dimension. \"",
"msg_2... | Ensures that the initial values are of the correct length, given the design
matrix that they will be dot-producted with. Raises a ValueError if that is
not the case, and provides a useful error message to users.
Parameters
----------
init_values : 1D ndarray.
1D numpy array of the initial v... | [
"Ensures",
"that",
"the",
"initial",
"values",
"are",
"of",
"the",
"correct",
"length",
"given",
"the",
"design",
"matrix",
"that",
"they",
"will",
"be",
"dot",
"-",
"producted",
"with",
".",
"Raises",
"a",
"ValueError",
"if",
"that",
"is",
"not",
"the",
... | f83b0fd6debaa7358d87c3828428f6d4ead71357 | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/mixed_logit.py#L106-L132 | train |
timothyb0912/pylogit | pylogit/mixed_logit.py | add_mixl_specific_results_to_estimation_res | def add_mixl_specific_results_to_estimation_res(estimator, results_dict):
"""
Stores particular items in the results dictionary that are unique to mixed
logit-type models. In particular, this function calculates and adds
`sequence_probs` and `expanded_sequence_probs` to the results dictionary.
The `... | python | def add_mixl_specific_results_to_estimation_res(estimator, results_dict):
"""
Stores particular items in the results dictionary that are unique to mixed
logit-type models. In particular, this function calculates and adds
`sequence_probs` and `expanded_sequence_probs` to the results dictionary.
The `... | [
"def",
"add_mixl_specific_results_to_estimation_res",
"(",
"estimator",
",",
"results_dict",
")",
":",
"prob_res",
"=",
"mlc",
".",
"calc_choice_sequence_probs",
"(",
"results_dict",
"[",
"\"long_probs\"",
"]",
",",
"estimator",
".",
"choice_vector",
",",
"estimator",
... | Stores particular items in the results dictionary that are unique to mixed
logit-type models. In particular, this function calculates and adds
`sequence_probs` and `expanded_sequence_probs` to the results dictionary.
The `constrained_pos` object is also stored to the results_dict.
Parameters
------... | [
"Stores",
"particular",
"items",
"in",
"the",
"results",
"dictionary",
"that",
"are",
"unique",
"to",
"mixed",
"logit",
"-",
"type",
"models",
".",
"In",
"particular",
"this",
"function",
"calculates",
"and",
"adds",
"sequence_probs",
"and",
"expanded_sequence_pro... | f83b0fd6debaa7358d87c3828428f6d4ead71357 | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/mixed_logit.py#L135-L168 | train |
timothyb0912/pylogit | pylogit/nested_logit.py | identify_degenerate_nests | def identify_degenerate_nests(nest_spec):
"""
Identify the nests within nest_spec that are degenerate, i.e. those nests
with only a single alternative within the nest.
Parameters
----------
nest_spec : OrderedDict.
Keys are strings that define the name of the nests. Values are lists
... | python | def identify_degenerate_nests(nest_spec):
"""
Identify the nests within nest_spec that are degenerate, i.e. those nests
with only a single alternative within the nest.
Parameters
----------
nest_spec : OrderedDict.
Keys are strings that define the name of the nests. Values are lists
... | [
"def",
"identify_degenerate_nests",
"(",
"nest_spec",
")",
":",
"degenerate_positions",
"=",
"[",
"]",
"for",
"pos",
",",
"key",
"in",
"enumerate",
"(",
"nest_spec",
")",
":",
"if",
"len",
"(",
"nest_spec",
"[",
"key",
"]",
")",
"==",
"1",
":",
"degenera... | Identify the nests within nest_spec that are degenerate, i.e. those nests
with only a single alternative within the nest.
Parameters
----------
nest_spec : OrderedDict.
Keys are strings that define the name of the nests. Values are lists
of alternative ids, denoting which alternatives b... | [
"Identify",
"the",
"nests",
"within",
"nest_spec",
"that",
"are",
"degenerate",
"i",
".",
"e",
".",
"those",
"nests",
"with",
"only",
"a",
"single",
"alternative",
"within",
"the",
"nest",
"."
] | f83b0fd6debaa7358d87c3828428f6d4ead71357 | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/nested_logit.py#L36-L58 | train |
timothyb0912/pylogit | pylogit/nested_logit.py | NestedEstimator.check_length_of_initial_values | def check_length_of_initial_values(self, init_values):
"""
Ensures that the initial values are of the correct length.
"""
# Figure out how many shape parameters we should have and how many
# index coefficients we should have
num_nests = self.rows_to_nests.shape[1]
... | python | def check_length_of_initial_values(self, init_values):
"""
Ensures that the initial values are of the correct length.
"""
# Figure out how many shape parameters we should have and how many
# index coefficients we should have
num_nests = self.rows_to_nests.shape[1]
... | [
"def",
"check_length_of_initial_values",
"(",
"self",
",",
"init_values",
")",
":",
"num_nests",
"=",
"self",
".",
"rows_to_nests",
".",
"shape",
"[",
"1",
"]",
"num_index_coefs",
"=",
"self",
".",
"design",
".",
"shape",
"[",
"1",
"]",
"assumed_param_dimensio... | Ensures that the initial values are of the correct length. | [
"Ensures",
"that",
"the",
"initial",
"values",
"are",
"of",
"the",
"correct",
"length",
"."
] | f83b0fd6debaa7358d87c3828428f6d4ead71357 | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/nested_logit.py#L177-L195 | train |
timothyb0912/pylogit | pylogit/nested_logit.py | NestedEstimator.convenience_split_params | def convenience_split_params(self, params, return_all_types=False):
"""
Splits parameter vector into nest parameters and index parameters.
Parameters
----------
all_params : 1D ndarray.
Should contain all of the parameters being estimated (i.e. all the
ne... | python | def convenience_split_params(self, params, return_all_types=False):
"""
Splits parameter vector into nest parameters and index parameters.
Parameters
----------
all_params : 1D ndarray.
Should contain all of the parameters being estimated (i.e. all the
ne... | [
"def",
"convenience_split_params",
"(",
"self",
",",
"params",
",",
"return_all_types",
"=",
"False",
")",
":",
"return",
"split_param_vec",
"(",
"params",
",",
"self",
".",
"rows_to_nests",
",",
"return_all_types",
"=",
"return_all_types",
")"
] | Splits parameter vector into nest parameters and index parameters.
Parameters
----------
all_params : 1D ndarray.
Should contain all of the parameters being estimated (i.e. all the
nest coefficients and all of the index coefficients). All elements
should be i... | [
"Splits",
"parameter",
"vector",
"into",
"nest",
"parameters",
"and",
"index",
"parameters",
"."
] | f83b0fd6debaa7358d87c3828428f6d4ead71357 | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/nested_logit.py#L197-L236 | train |
timothyb0912/pylogit | pylogit/choice_calcs.py | robust_outer_product | def robust_outer_product(vec_1, vec_2):
"""
Calculates a 'robust' outer product of two vectors that may or may not
contain very small values.
Parameters
----------
vec_1 : 1D ndarray
vec_2 : 1D ndarray
Returns
-------
outer_prod : 2D ndarray. The outer product of vec_1 and vec_... | python | def robust_outer_product(vec_1, vec_2):
"""
Calculates a 'robust' outer product of two vectors that may or may not
contain very small values.
Parameters
----------
vec_1 : 1D ndarray
vec_2 : 1D ndarray
Returns
-------
outer_prod : 2D ndarray. The outer product of vec_1 and vec_... | [
"def",
"robust_outer_product",
"(",
"vec_1",
",",
"vec_2",
")",
":",
"mantissa_1",
",",
"exponents_1",
"=",
"np",
".",
"frexp",
"(",
"vec_1",
")",
"mantissa_2",
",",
"exponents_2",
"=",
"np",
".",
"frexp",
"(",
"vec_2",
")",
"new_mantissas",
"=",
"mantissa... | Calculates a 'robust' outer product of two vectors that may or may not
contain very small values.
Parameters
----------
vec_1 : 1D ndarray
vec_2 : 1D ndarray
Returns
-------
outer_prod : 2D ndarray. The outer product of vec_1 and vec_2 | [
"Calculates",
"a",
"robust",
"outer",
"product",
"of",
"two",
"vectors",
"that",
"may",
"or",
"may",
"not",
"contain",
"very",
"small",
"values",
"."
] | f83b0fd6debaa7358d87c3828428f6d4ead71357 | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/choice_calcs.py#L523-L541 | train |
timothyb0912/pylogit | pylogit/bootstrap_calcs.py | calc_percentile_interval | def calc_percentile_interval(bootstrap_replicates, conf_percentage):
"""
Calculate bootstrap confidence intervals based on raw percentiles of the
bootstrap distribution of samples.
Parameters
----------
bootstrap_replicates : 2D ndarray.
Each row should correspond to a different bootstr... | python | def calc_percentile_interval(bootstrap_replicates, conf_percentage):
"""
Calculate bootstrap confidence intervals based on raw percentiles of the
bootstrap distribution of samples.
Parameters
----------
bootstrap_replicates : 2D ndarray.
Each row should correspond to a different bootstr... | [
"def",
"calc_percentile_interval",
"(",
"bootstrap_replicates",
",",
"conf_percentage",
")",
":",
"check_conf_percentage_validity",
"(",
"conf_percentage",
")",
"ensure_samples_is_ndim_ndarray",
"(",
"bootstrap_replicates",
",",
"ndim",
"=",
"2",
")",
"alpha",
"=",
"get_a... | Calculate bootstrap confidence intervals based on raw percentiles of the
bootstrap distribution of samples.
Parameters
----------
bootstrap_replicates : 2D ndarray.
Each row should correspond to a different bootstrap parameter sample.
Each column should correspond to an element of the p... | [
"Calculate",
"bootstrap",
"confidence",
"intervals",
"based",
"on",
"raw",
"percentiles",
"of",
"the",
"bootstrap",
"distribution",
"of",
"samples",
"."
] | f83b0fd6debaa7358d87c3828428f6d4ead71357 | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/bootstrap_calcs.py#L20-L83 | train |
timothyb0912/pylogit | pylogit/bootstrap_calcs.py | calc_bca_interval | def calc_bca_interval(bootstrap_replicates,
jackknife_replicates,
mle_params,
conf_percentage):
"""
Calculate 'bias-corrected and accelerated' bootstrap confidence intervals.
Parameters
----------
bootstrap_replicates : 2D ndarray.
... | python | def calc_bca_interval(bootstrap_replicates,
jackknife_replicates,
mle_params,
conf_percentage):
"""
Calculate 'bias-corrected and accelerated' bootstrap confidence intervals.
Parameters
----------
bootstrap_replicates : 2D ndarray.
... | [
"def",
"calc_bca_interval",
"(",
"bootstrap_replicates",
",",
"jackknife_replicates",
",",
"mle_params",
",",
"conf_percentage",
")",
":",
"check_conf_percentage_validity",
"(",
"conf_percentage",
")",
"ensure_samples_is_ndim_ndarray",
"(",
"bootstrap_replicates",
",",
"ndim"... | Calculate 'bias-corrected and accelerated' bootstrap confidence intervals.
Parameters
----------
bootstrap_replicates : 2D ndarray.
Each row should correspond to a different bootstrap parameter sample.
Each column should correspond to an element of the parameter vector
being estimat... | [
"Calculate",
"bias",
"-",
"corrected",
"and",
"accelerated",
"bootstrap",
"confidence",
"intervals",
"."
] | f83b0fd6debaa7358d87c3828428f6d4ead71357 | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/bootstrap_calcs.py#L254-L323 | train |
timothyb0912/pylogit | pylogit/bootstrap_mle.py | extract_default_init_vals | def extract_default_init_vals(orig_model_obj, mnl_point_series, num_params):
"""
Get the default initial values for the desired model type, based on the
point estimate of the MNL model that is 'closest' to the desired model.
Parameters
----------
orig_model_obj : an instance or sublcass of the ... | python | def extract_default_init_vals(orig_model_obj, mnl_point_series, num_params):
"""
Get the default initial values for the desired model type, based on the
point estimate of the MNL model that is 'closest' to the desired model.
Parameters
----------
orig_model_obj : an instance or sublcass of the ... | [
"def",
"extract_default_init_vals",
"(",
"orig_model_obj",
",",
"mnl_point_series",
",",
"num_params",
")",
":",
"init_vals",
"=",
"np",
".",
"zeros",
"(",
"num_params",
",",
"dtype",
"=",
"float",
")",
"no_outside_intercepts",
"=",
"orig_model_obj",
".",
"interce... | Get the default initial values for the desired model type, based on the
point estimate of the MNL model that is 'closest' to the desired model.
Parameters
----------
orig_model_obj : an instance or sublcass of the MNDC class.
Should correspond to the actual model that we want to bootstrap.
... | [
"Get",
"the",
"default",
"initial",
"values",
"for",
"the",
"desired",
"model",
"type",
"based",
"on",
"the",
"point",
"estimate",
"of",
"the",
"MNL",
"model",
"that",
"is",
"closest",
"to",
"the",
"desired",
"model",
"."
] | f83b0fd6debaa7358d87c3828428f6d4ead71357 | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/bootstrap_mle.py#L14-L75 | train |
timothyb0912/pylogit | pylogit/bootstrap_mle.py | get_model_abbrev | def get_model_abbrev(model_obj):
"""
Extract the string used to specify the model type of this model object in
`pylogit.create_chohice_model`.
Parameters
----------
model_obj : An MNDC_Model instance.
Returns
-------
str. The internal abbreviation used for the particular type of MN... | python | def get_model_abbrev(model_obj):
"""
Extract the string used to specify the model type of this model object in
`pylogit.create_chohice_model`.
Parameters
----------
model_obj : An MNDC_Model instance.
Returns
-------
str. The internal abbreviation used for the particular type of MN... | [
"def",
"get_model_abbrev",
"(",
"model_obj",
")",
":",
"model_type",
"=",
"model_obj",
".",
"model_type",
"for",
"key",
"in",
"model_type_to_display_name",
":",
"if",
"model_type_to_display_name",
"[",
"key",
"]",
"==",
"model_type",
":",
"return",
"key",
"msg",
... | Extract the string used to specify the model type of this model object in
`pylogit.create_chohice_model`.
Parameters
----------
model_obj : An MNDC_Model instance.
Returns
-------
str. The internal abbreviation used for the particular type of MNDC_Model. | [
"Extract",
"the",
"string",
"used",
"to",
"specify",
"the",
"model",
"type",
"of",
"this",
"model",
"object",
"in",
"pylogit",
".",
"create_chohice_model",
"."
] | f83b0fd6debaa7358d87c3828428f6d4ead71357 | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/bootstrap_mle.py#L78-L100 | train |
timothyb0912/pylogit | pylogit/bootstrap_mle.py | get_model_creation_kwargs | def get_model_creation_kwargs(model_obj):
"""
Get a dictionary of the keyword arguments needed to create the passed model
object using `pylogit.create_choice_model`.
Parameters
----------
model_obj : An MNDC_Model instance.
Returns
-------
model_kwargs : dict.
Contains the ... | python | def get_model_creation_kwargs(model_obj):
"""
Get a dictionary of the keyword arguments needed to create the passed model
object using `pylogit.create_choice_model`.
Parameters
----------
model_obj : An MNDC_Model instance.
Returns
-------
model_kwargs : dict.
Contains the ... | [
"def",
"get_model_creation_kwargs",
"(",
"model_obj",
")",
":",
"model_abbrev",
"=",
"get_model_abbrev",
"(",
"model_obj",
")",
"model_kwargs",
"=",
"{",
"\"model_type\"",
":",
"model_abbrev",
",",
"\"names\"",
":",
"model_obj",
".",
"name_spec",
",",
"\"intercept_n... | Get a dictionary of the keyword arguments needed to create the passed model
object using `pylogit.create_choice_model`.
Parameters
----------
model_obj : An MNDC_Model instance.
Returns
-------
model_kwargs : dict.
Contains the keyword arguments and the required values that are nee... | [
"Get",
"a",
"dictionary",
"of",
"the",
"keyword",
"arguments",
"needed",
"to",
"create",
"the",
"passed",
"model",
"object",
"using",
"pylogit",
".",
"create_choice_model",
"."
] | f83b0fd6debaa7358d87c3828428f6d4ead71357 | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/bootstrap_mle.py#L103-L133 | train |
timothyb0912/pylogit | pylogit/pylogit.py | ensure_valid_model_type | def ensure_valid_model_type(specified_type, model_type_list):
"""
Checks to make sure that `specified_type` is in `model_type_list` and
raises a helpful error if this is not the case.
Parameters
----------
specified_type : str.
Denotes the user-specified model type that is to be checked... | python | def ensure_valid_model_type(specified_type, model_type_list):
"""
Checks to make sure that `specified_type` is in `model_type_list` and
raises a helpful error if this is not the case.
Parameters
----------
specified_type : str.
Denotes the user-specified model type that is to be checked... | [
"def",
"ensure_valid_model_type",
"(",
"specified_type",
",",
"model_type_list",
")",
":",
"if",
"specified_type",
"not",
"in",
"model_type_list",
":",
"msg_1",
"=",
"\"The specified model_type was not valid.\"",
"msg_2",
"=",
"\"Valid model-types are {}\"",
".",
"format",
... | Checks to make sure that `specified_type` is in `model_type_list` and
raises a helpful error if this is not the case.
Parameters
----------
specified_type : str.
Denotes the user-specified model type that is to be checked.
model_type_list : list of strings.
Contains all of the model... | [
"Checks",
"to",
"make",
"sure",
"that",
"specified_type",
"is",
"in",
"model_type_list",
"and",
"raises",
"a",
"helpful",
"error",
"if",
"this",
"is",
"not",
"the",
"case",
"."
] | f83b0fd6debaa7358d87c3828428f6d4ead71357 | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/pylogit.py#L58-L80 | train |
timothyb0912/pylogit | pylogit/base_multinomial_cm_v2.py | ensure_valid_nums_in_specification_cols | def ensure_valid_nums_in_specification_cols(specification, dataframe):
"""
Checks whether each column in `specification` contains numeric data,
excluding positive or negative infinity and excluding NaN. Raises
ValueError if any of the columns do not meet these requirements.
Parameters
---------... | python | def ensure_valid_nums_in_specification_cols(specification, dataframe):
"""
Checks whether each column in `specification` contains numeric data,
excluding positive or negative infinity and excluding NaN. Raises
ValueError if any of the columns do not meet these requirements.
Parameters
---------... | [
"def",
"ensure_valid_nums_in_specification_cols",
"(",
"specification",
",",
"dataframe",
")",
":",
"problem_cols",
"=",
"[",
"]",
"for",
"col",
"in",
"specification",
":",
"if",
"dataframe",
"[",
"col",
"]",
".",
"dtype",
".",
"kind",
"not",
"in",
"[",
"'f'... | Checks whether each column in `specification` contains numeric data,
excluding positive or negative infinity and excluding NaN. Raises
ValueError if any of the columns do not meet these requirements.
Parameters
----------
specification : iterable of column headers in `dataframe`.
dataframe : pa... | [
"Checks",
"whether",
"each",
"column",
"in",
"specification",
"contains",
"numeric",
"data",
"excluding",
"positive",
"or",
"negative",
"infinity",
"and",
"excluding",
"NaN",
".",
"Raises",
"ValueError",
"if",
"any",
"of",
"the",
"columns",
"do",
"not",
"meet",
... | f83b0fd6debaa7358d87c3828428f6d4ead71357 | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/base_multinomial_cm_v2.py#L60-L96 | train |
timothyb0912/pylogit | pylogit/base_multinomial_cm_v2.py | check_length_of_shape_or_intercept_names | def check_length_of_shape_or_intercept_names(name_list,
num_alts,
constrained_param,
list_title):
"""
Ensures that the length of the parameter names matches the number of
pa... | python | def check_length_of_shape_or_intercept_names(name_list,
num_alts,
constrained_param,
list_title):
"""
Ensures that the length of the parameter names matches the number of
pa... | [
"def",
"check_length_of_shape_or_intercept_names",
"(",
"name_list",
",",
"num_alts",
",",
"constrained_param",
",",
"list_title",
")",
":",
"if",
"len",
"(",
"name_list",
")",
"!=",
"(",
"num_alts",
"-",
"constrained_param",
")",
":",
"msg_1",
"=",
"\"{} is of th... | Ensures that the length of the parameter names matches the number of
parameters that will be estimated. Will raise a ValueError otherwise.
Parameters
----------
name_list : list of strings.
Each element should be the name of a parameter that is to be estimated.
num_alts : int.
Shoul... | [
"Ensures",
"that",
"the",
"length",
"of",
"the",
"parameter",
"names",
"matches",
"the",
"number",
"of",
"parameters",
"that",
"will",
"be",
"estimated",
".",
"Will",
"raise",
"a",
"ValueError",
"otherwise",
"."
] | f83b0fd6debaa7358d87c3828428f6d4ead71357 | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/base_multinomial_cm_v2.py#L145-L180 | train |
timothyb0912/pylogit | pylogit/base_multinomial_cm_v2.py | check_type_of_nest_spec_keys_and_values | def check_type_of_nest_spec_keys_and_values(nest_spec):
"""
Ensures that the keys and values of `nest_spec` are strings and lists.
Raises a helpful ValueError if they are.
Parameters
----------
nest_spec : OrderedDict, or None, optional.
Keys are strings that define the name of the nest... | python | def check_type_of_nest_spec_keys_and_values(nest_spec):
"""
Ensures that the keys and values of `nest_spec` are strings and lists.
Raises a helpful ValueError if they are.
Parameters
----------
nest_spec : OrderedDict, or None, optional.
Keys are strings that define the name of the nest... | [
"def",
"check_type_of_nest_spec_keys_and_values",
"(",
"nest_spec",
")",
":",
"try",
":",
"assert",
"all",
"(",
"[",
"isinstance",
"(",
"k",
",",
"str",
")",
"for",
"k",
"in",
"nest_spec",
"]",
")",
"assert",
"all",
"(",
"[",
"isinstance",
"(",
"nest_spec"... | Ensures that the keys and values of `nest_spec` are strings and lists.
Raises a helpful ValueError if they are.
Parameters
----------
nest_spec : OrderedDict, or None, optional.
Keys are strings that define the name of the nests. Values are lists of
alternative ids, denoting which alter... | [
"Ensures",
"that",
"the",
"keys",
"and",
"values",
"of",
"nest_spec",
"are",
"strings",
"and",
"lists",
".",
"Raises",
"a",
"helpful",
"ValueError",
"if",
"they",
"are",
"."
] | f83b0fd6debaa7358d87c3828428f6d4ead71357 | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/base_multinomial_cm_v2.py#L183-L207 | train |
timothyb0912/pylogit | pylogit/base_multinomial_cm_v2.py | check_for_empty_nests_in_nest_spec | def check_for_empty_nests_in_nest_spec(nest_spec):
"""
Ensures that the values of `nest_spec` are not empty lists.
Raises a helpful ValueError if they are.
Parameters
----------
nest_spec : OrderedDict, or None, optional.
Keys are strings that define the name of the nests. Values are li... | python | def check_for_empty_nests_in_nest_spec(nest_spec):
"""
Ensures that the values of `nest_spec` are not empty lists.
Raises a helpful ValueError if they are.
Parameters
----------
nest_spec : OrderedDict, or None, optional.
Keys are strings that define the name of the nests. Values are li... | [
"def",
"check_for_empty_nests_in_nest_spec",
"(",
"nest_spec",
")",
":",
"empty_nests",
"=",
"[",
"]",
"for",
"k",
"in",
"nest_spec",
":",
"if",
"len",
"(",
"nest_spec",
"[",
"k",
"]",
")",
"==",
"0",
":",
"empty_nests",
".",
"append",
"(",
"k",
")",
"... | Ensures that the values of `nest_spec` are not empty lists.
Raises a helpful ValueError if they are.
Parameters
----------
nest_spec : OrderedDict, or None, optional.
Keys are strings that define the name of the nests. Values are lists of
alternative ids, denoting which alternatives bel... | [
"Ensures",
"that",
"the",
"values",
"of",
"nest_spec",
"are",
"not",
"empty",
"lists",
".",
"Raises",
"a",
"helpful",
"ValueError",
"if",
"they",
"are",
"."
] | f83b0fd6debaa7358d87c3828428f6d4ead71357 | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/base_multinomial_cm_v2.py#L210-L235 | train |
timothyb0912/pylogit | pylogit/base_multinomial_cm_v2.py | ensure_alt_ids_in_nest_spec_are_ints | def ensure_alt_ids_in_nest_spec_are_ints(nest_spec, list_elements):
"""
Ensures that the alternative id's in `nest_spec` are integers. Raises a
helpful ValueError if they are not.
Parameters
----------
nest_spec : OrderedDict, or None, optional.
Keys are strings that define the name of ... | python | def ensure_alt_ids_in_nest_spec_are_ints(nest_spec, list_elements):
"""
Ensures that the alternative id's in `nest_spec` are integers. Raises a
helpful ValueError if they are not.
Parameters
----------
nest_spec : OrderedDict, or None, optional.
Keys are strings that define the name of ... | [
"def",
"ensure_alt_ids_in_nest_spec_are_ints",
"(",
"nest_spec",
",",
"list_elements",
")",
":",
"try",
":",
"assert",
"all",
"(",
"[",
"isinstance",
"(",
"x",
",",
"int",
")",
"for",
"x",
"in",
"list_elements",
"]",
")",
"except",
"AssertionError",
":",
"ms... | Ensures that the alternative id's in `nest_spec` are integers. Raises a
helpful ValueError if they are not.
Parameters
----------
nest_spec : OrderedDict, or None, optional.
Keys are strings that define the name of the nests. Values are lists of
alternative ids, denoting which alternati... | [
"Ensures",
"that",
"the",
"alternative",
"id",
"s",
"in",
"nest_spec",
"are",
"integers",
".",
"Raises",
"a",
"helpful",
"ValueError",
"if",
"they",
"are",
"not",
"."
] | f83b0fd6debaa7358d87c3828428f6d4ead71357 | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/base_multinomial_cm_v2.py#L238-L264 | train |
timothyb0912/pylogit | pylogit/base_multinomial_cm_v2.py | ensure_alt_ids_are_only_in_one_nest | def ensure_alt_ids_are_only_in_one_nest(nest_spec, list_elements):
"""
Ensures that the alternative id's in `nest_spec` are only associated with
a single nest. Raises a helpful ValueError if they are not.
Parameters
----------
nest_spec : OrderedDict, or None, optional.
Keys are strings... | python | def ensure_alt_ids_are_only_in_one_nest(nest_spec, list_elements):
"""
Ensures that the alternative id's in `nest_spec` are only associated with
a single nest. Raises a helpful ValueError if they are not.
Parameters
----------
nest_spec : OrderedDict, or None, optional.
Keys are strings... | [
"def",
"ensure_alt_ids_are_only_in_one_nest",
"(",
"nest_spec",
",",
"list_elements",
")",
":",
"try",
":",
"assert",
"len",
"(",
"set",
"(",
"list_elements",
")",
")",
"==",
"len",
"(",
"list_elements",
")",
"except",
"AssertionError",
":",
"msg",
"=",
"\"Eac... | Ensures that the alternative id's in `nest_spec` are only associated with
a single nest. Raises a helpful ValueError if they are not.
Parameters
----------
nest_spec : OrderedDict, or None, optional.
Keys are strings that define the name of the nests. Values are lists of
alternative ids... | [
"Ensures",
"that",
"the",
"alternative",
"id",
"s",
"in",
"nest_spec",
"are",
"only",
"associated",
"with",
"a",
"single",
"nest",
".",
"Raises",
"a",
"helpful",
"ValueError",
"if",
"they",
"are",
"not",
"."
] | f83b0fd6debaa7358d87c3828428f6d4ead71357 | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/base_multinomial_cm_v2.py#L267-L293 | train |
timothyb0912/pylogit | pylogit/base_multinomial_cm_v2.py | ensure_all_alt_ids_have_a_nest | def ensure_all_alt_ids_have_a_nest(nest_spec, list_elements, all_ids):
"""
Ensures that the alternative id's in `nest_spec` are all associated with
a nest. Raises a helpful ValueError if they are not.
Parameters
----------
nest_spec : OrderedDict, or None, optional.
Keys are strings tha... | python | def ensure_all_alt_ids_have_a_nest(nest_spec, list_elements, all_ids):
"""
Ensures that the alternative id's in `nest_spec` are all associated with
a nest. Raises a helpful ValueError if they are not.
Parameters
----------
nest_spec : OrderedDict, or None, optional.
Keys are strings tha... | [
"def",
"ensure_all_alt_ids_have_a_nest",
"(",
"nest_spec",
",",
"list_elements",
",",
"all_ids",
")",
":",
"unaccounted_alt_ids",
"=",
"[",
"]",
"for",
"alt_id",
"in",
"all_ids",
":",
"if",
"alt_id",
"not",
"in",
"list_elements",
":",
"unaccounted_alt_ids",
".",
... | Ensures that the alternative id's in `nest_spec` are all associated with
a nest. Raises a helpful ValueError if they are not.
Parameters
----------
nest_spec : OrderedDict, or None, optional.
Keys are strings that define the name of the nests. Values are lists of
alternative ids, denoti... | [
"Ensures",
"that",
"the",
"alternative",
"id",
"s",
"in",
"nest_spec",
"are",
"all",
"associated",
"with",
"a",
"nest",
".",
"Raises",
"a",
"helpful",
"ValueError",
"if",
"they",
"are",
"not",
"."
] | f83b0fd6debaa7358d87c3828428f6d4ead71357 | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/base_multinomial_cm_v2.py#L296-L327 | train |
timothyb0912/pylogit | pylogit/base_multinomial_cm_v2.py | ensure_nest_alts_are_valid_alts | def ensure_nest_alts_are_valid_alts(nest_spec, list_elements, all_ids):
"""
Ensures that the alternative id's in `nest_spec` are all in the universal
choice set for this dataset. Raises a helpful ValueError if they are not.
Parameters
----------
nest_spec : OrderedDict, or None, optional.
... | python | def ensure_nest_alts_are_valid_alts(nest_spec, list_elements, all_ids):
"""
Ensures that the alternative id's in `nest_spec` are all in the universal
choice set for this dataset. Raises a helpful ValueError if they are not.
Parameters
----------
nest_spec : OrderedDict, or None, optional.
... | [
"def",
"ensure_nest_alts_are_valid_alts",
"(",
"nest_spec",
",",
"list_elements",
",",
"all_ids",
")",
":",
"invalid_alt_ids",
"=",
"[",
"]",
"for",
"x",
"in",
"list_elements",
":",
"if",
"x",
"not",
"in",
"all_ids",
":",
"invalid_alt_ids",
".",
"append",
"(",... | Ensures that the alternative id's in `nest_spec` are all in the universal
choice set for this dataset. Raises a helpful ValueError if they are not.
Parameters
----------
nest_spec : OrderedDict, or None, optional.
Keys are strings that define the name of the nests. Values are lists of
a... | [
"Ensures",
"that",
"the",
"alternative",
"id",
"s",
"in",
"nest_spec",
"are",
"all",
"in",
"the",
"universal",
"choice",
"set",
"for",
"this",
"dataset",
".",
"Raises",
"a",
"helpful",
"ValueError",
"if",
"they",
"are",
"not",
"."
] | f83b0fd6debaa7358d87c3828428f6d4ead71357 | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/base_multinomial_cm_v2.py#L330-L361 | train |
timothyb0912/pylogit | pylogit/base_multinomial_cm_v2.py | check_type_and_size_of_param_list | def check_type_and_size_of_param_list(param_list, expected_length):
"""
Ensure that param_list is a list with the expected length. Raises a helpful
ValueError if this is not the case.
"""
try:
assert isinstance(param_list, list)
assert len(param_list) == expected_length
except As... | python | def check_type_and_size_of_param_list(param_list, expected_length):
"""
Ensure that param_list is a list with the expected length. Raises a helpful
ValueError if this is not the case.
"""
try:
assert isinstance(param_list, list)
assert len(param_list) == expected_length
except As... | [
"def",
"check_type_and_size_of_param_list",
"(",
"param_list",
",",
"expected_length",
")",
":",
"try",
":",
"assert",
"isinstance",
"(",
"param_list",
",",
"list",
")",
"assert",
"len",
"(",
"param_list",
")",
"==",
"expected_length",
"except",
"AssertionError",
... | Ensure that param_list is a list with the expected length. Raises a helpful
ValueError if this is not the case. | [
"Ensure",
"that",
"param_list",
"is",
"a",
"list",
"with",
"the",
"expected",
"length",
".",
"Raises",
"a",
"helpful",
"ValueError",
"if",
"this",
"is",
"not",
"the",
"case",
"."
] | f83b0fd6debaa7358d87c3828428f6d4ead71357 | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/base_multinomial_cm_v2.py#L410-L422 | train |
timothyb0912/pylogit | pylogit/base_multinomial_cm_v2.py | check_type_of_param_list_elements | def check_type_of_param_list_elements(param_list):
"""
Ensures that all elements of param_list are ndarrays or None. Raises a
helpful ValueError if otherwise.
"""
try:
assert isinstance(param_list[0], np.ndarray)
assert all([(x is None or isinstance(x, np.ndarray))
... | python | def check_type_of_param_list_elements(param_list):
"""
Ensures that all elements of param_list are ndarrays or None. Raises a
helpful ValueError if otherwise.
"""
try:
assert isinstance(param_list[0], np.ndarray)
assert all([(x is None or isinstance(x, np.ndarray))
... | [
"def",
"check_type_of_param_list_elements",
"(",
"param_list",
")",
":",
"try",
":",
"assert",
"isinstance",
"(",
"param_list",
"[",
"0",
"]",
",",
"np",
".",
"ndarray",
")",
"assert",
"all",
"(",
"[",
"(",
"x",
"is",
"None",
"or",
"isinstance",
"(",
"x"... | Ensures that all elements of param_list are ndarrays or None. Raises a
helpful ValueError if otherwise. | [
"Ensures",
"that",
"all",
"elements",
"of",
"param_list",
"are",
"ndarrays",
"or",
"None",
".",
"Raises",
"a",
"helpful",
"ValueError",
"if",
"otherwise",
"."
] | f83b0fd6debaa7358d87c3828428f6d4ead71357 | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/base_multinomial_cm_v2.py#L425-L440 | train |
timothyb0912/pylogit | pylogit/base_multinomial_cm_v2.py | check_num_columns_in_param_list_arrays | def check_num_columns_in_param_list_arrays(param_list):
"""
Ensure that each array in param_list, that is not None, has the same number
of columns. Raises a helpful ValueError if otherwise.
Parameters
----------
param_list : list of ndarrays or None.
Returns
-------
None.
"""
... | python | def check_num_columns_in_param_list_arrays(param_list):
"""
Ensure that each array in param_list, that is not None, has the same number
of columns. Raises a helpful ValueError if otherwise.
Parameters
----------
param_list : list of ndarrays or None.
Returns
-------
None.
"""
... | [
"def",
"check_num_columns_in_param_list_arrays",
"(",
"param_list",
")",
":",
"try",
":",
"num_columns",
"=",
"param_list",
"[",
"0",
"]",
".",
"shape",
"[",
"1",
"]",
"assert",
"all",
"(",
"[",
"x",
"is",
"None",
"or",
"(",
"x",
".",
"shape",
"[",
"1"... | Ensure that each array in param_list, that is not None, has the same number
of columns. Raises a helpful ValueError if otherwise.
Parameters
----------
param_list : list of ndarrays or None.
Returns
-------
None. | [
"Ensure",
"that",
"each",
"array",
"in",
"param_list",
"that",
"is",
"not",
"None",
"has",
"the",
"same",
"number",
"of",
"columns",
".",
"Raises",
"a",
"helpful",
"ValueError",
"if",
"otherwise",
"."
] | f83b0fd6debaa7358d87c3828428f6d4ead71357 | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/base_multinomial_cm_v2.py#L443-L464 | train |
timothyb0912/pylogit | pylogit/base_multinomial_cm_v2.py | ensure_all_mixing_vars_are_in_the_name_dict | def ensure_all_mixing_vars_are_in_the_name_dict(mixing_vars,
name_dict,
ind_var_names):
"""
Ensures that all of the variables listed in `mixing_vars` are present in
`ind_var_names`. Raises a helpful ValueError if... | python | def ensure_all_mixing_vars_are_in_the_name_dict(mixing_vars,
name_dict,
ind_var_names):
"""
Ensures that all of the variables listed in `mixing_vars` are present in
`ind_var_names`. Raises a helpful ValueError if... | [
"def",
"ensure_all_mixing_vars_are_in_the_name_dict",
"(",
"mixing_vars",
",",
"name_dict",
",",
"ind_var_names",
")",
":",
"if",
"mixing_vars",
"is",
"None",
":",
"return",
"None",
"problem_names",
"=",
"[",
"variable_name",
"for",
"variable_name",
"in",
"mixing_vars... | Ensures that all of the variables listed in `mixing_vars` are present in
`ind_var_names`. Raises a helpful ValueError if otherwise.
Parameters
----------
mixing_vars : list of strings, or None.
Each string denotes a parameter to be treated as a random variable.
name_dict : OrderedDict or No... | [
"Ensures",
"that",
"all",
"of",
"the",
"variables",
"listed",
"in",
"mixing_vars",
"are",
"present",
"in",
"ind_var_names",
".",
"Raises",
"a",
"helpful",
"ValueError",
"if",
"otherwise",
"."
] | f83b0fd6debaa7358d87c3828428f6d4ead71357 | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/base_multinomial_cm_v2.py#L524-L574 | train |
timothyb0912/pylogit | pylogit/base_multinomial_cm_v2.py | compute_aic | def compute_aic(model_object):
"""
Compute the Akaike Information Criteria for an estimated model.
Parameters
----------
model_object : an MNDC_Model (multinomial discrete choice model) instance.
The model should have already been estimated.
`model_object.log_likelihood` should be a... | python | def compute_aic(model_object):
"""
Compute the Akaike Information Criteria for an estimated model.
Parameters
----------
model_object : an MNDC_Model (multinomial discrete choice model) instance.
The model should have already been estimated.
`model_object.log_likelihood` should be a... | [
"def",
"compute_aic",
"(",
"model_object",
")",
":",
"assert",
"isinstance",
"(",
"model_object",
".",
"params",
",",
"pd",
".",
"Series",
")",
"assert",
"isinstance",
"(",
"model_object",
".",
"log_likelihood",
",",
"Number",
")",
"return",
"-",
"2",
"*",
... | Compute the Akaike Information Criteria for an estimated model.
Parameters
----------
model_object : an MNDC_Model (multinomial discrete choice model) instance.
The model should have already been estimated.
`model_object.log_likelihood` should be a number, and
`model_object.params` ... | [
"Compute",
"the",
"Akaike",
"Information",
"Criteria",
"for",
"an",
"estimated",
"model",
"."
] | f83b0fd6debaa7358d87c3828428f6d4ead71357 | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/base_multinomial_cm_v2.py#L611-L639 | train |
timothyb0912/pylogit | pylogit/base_multinomial_cm_v2.py | compute_bic | def compute_bic(model_object):
"""
Compute the Bayesian Information Criteria for an estimated model.
Parameters
----------
model_object : an MNDC_Model (multinomial discrete choice model) instance.
The model should have already been estimated.
`model_object.log_likelihood` and `mode... | python | def compute_bic(model_object):
"""
Compute the Bayesian Information Criteria for an estimated model.
Parameters
----------
model_object : an MNDC_Model (multinomial discrete choice model) instance.
The model should have already been estimated.
`model_object.log_likelihood` and `mode... | [
"def",
"compute_bic",
"(",
"model_object",
")",
":",
"assert",
"isinstance",
"(",
"model_object",
".",
"params",
",",
"pd",
".",
"Series",
")",
"assert",
"isinstance",
"(",
"model_object",
".",
"log_likelihood",
",",
"Number",
")",
"assert",
"isinstance",
"(",... | Compute the Bayesian Information Criteria for an estimated model.
Parameters
----------
model_object : an MNDC_Model (multinomial discrete choice model) instance.
The model should have already been estimated.
`model_object.log_likelihood` and `model_object.nobs` should be a
number, ... | [
"Compute",
"the",
"Bayesian",
"Information",
"Criteria",
"for",
"an",
"estimated",
"model",
"."
] | f83b0fd6debaa7358d87c3828428f6d4ead71357 | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/base_multinomial_cm_v2.py#L642-L681 | train |
timothyb0912/pylogit | pylogit/base_multinomial_cm_v2.py | MNDC_Model._create_results_summary | def _create_results_summary(self):
"""
Create the dataframe that displays the estimation results, and store
it on the model instance.
Returns
-------
None.
"""
# Make sure we have all attributes needed to create the results summary
needed_attribut... | python | def _create_results_summary(self):
"""
Create the dataframe that displays the estimation results, and store
it on the model instance.
Returns
-------
None.
"""
# Make sure we have all attributes needed to create the results summary
needed_attribut... | [
"def",
"_create_results_summary",
"(",
"self",
")",
":",
"needed_attributes",
"=",
"[",
"\"params\"",
",",
"\"standard_errors\"",
",",
"\"tvalues\"",
",",
"\"pvalues\"",
",",
"\"robust_std_errs\"",
",",
"\"robust_t_stats\"",
",",
"\"robust_p_vals\"",
"]",
"try",
":",
... | Create the dataframe that displays the estimation results, and store
it on the model instance.
Returns
-------
None. | [
"Create",
"the",
"dataframe",
"that",
"displays",
"the",
"estimation",
"results",
"and",
"store",
"it",
"on",
"the",
"model",
"instance",
"."
] | f83b0fd6debaa7358d87c3828428f6d4ead71357 | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/base_multinomial_cm_v2.py#L995-L1029 | train |
timothyb0912/pylogit | pylogit/base_multinomial_cm_v2.py | MNDC_Model._record_values_for_fit_summary_and_statsmodels | def _record_values_for_fit_summary_and_statsmodels(self):
"""
Store the various estimation results that are used to describe how well
the estimated model fits the given dataset, and record the values that
are needed for the statsmodels estimation results table. All values are
sto... | python | def _record_values_for_fit_summary_and_statsmodels(self):
"""
Store the various estimation results that are used to describe how well
the estimated model fits the given dataset, and record the values that
are needed for the statsmodels estimation results table. All values are
sto... | [
"def",
"_record_values_for_fit_summary_and_statsmodels",
"(",
"self",
")",
":",
"needed_attributes",
"=",
"[",
"\"fitted_probs\"",
",",
"\"params\"",
",",
"\"log_likelihood\"",
",",
"\"standard_errors\"",
"]",
"try",
":",
"assert",
"all",
"(",
"[",
"hasattr",
"(",
"... | Store the various estimation results that are used to describe how well
the estimated model fits the given dataset, and record the values that
are needed for the statsmodels estimation results table. All values are
stored on the model instance.
Returns
-------
None. | [
"Store",
"the",
"various",
"estimation",
"results",
"that",
"are",
"used",
"to",
"describe",
"how",
"well",
"the",
"estimated",
"model",
"fits",
"the",
"given",
"dataset",
"and",
"record",
"the",
"values",
"that",
"are",
"needed",
"for",
"the",
"statsmodels",
... | f83b0fd6debaa7358d87c3828428f6d4ead71357 | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/base_multinomial_cm_v2.py#L1031-L1071 | train |
timothyb0912/pylogit | pylogit/base_multinomial_cm_v2.py | MNDC_Model._store_inferential_results | def _store_inferential_results(self,
value_array,
index_names,
attribute_name,
series_name=None,
column_names=None):
"""
Store th... | python | def _store_inferential_results(self,
value_array,
index_names,
attribute_name,
series_name=None,
column_names=None):
"""
Store th... | [
"def",
"_store_inferential_results",
"(",
"self",
",",
"value_array",
",",
"index_names",
",",
"attribute_name",
",",
"series_name",
"=",
"None",
",",
"column_names",
"=",
"None",
")",
":",
"if",
"len",
"(",
"value_array",
".",
"shape",
")",
"==",
"1",
":",
... | Store the estimation results that relate to statistical inference, such
as parameter estimates, standard errors, p-values, etc.
Parameters
----------
value_array : 1D or 2D ndarray.
Contains the values that are to be stored on the model instance.
index_names : list o... | [
"Store",
"the",
"estimation",
"results",
"that",
"relate",
"to",
"statistical",
"inference",
"such",
"as",
"parameter",
"estimates",
"standard",
"errors",
"p",
"-",
"values",
"etc",
"."
] | f83b0fd6debaa7358d87c3828428f6d4ead71357 | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/base_multinomial_cm_v2.py#L1117-L1164 | train |
timothyb0912/pylogit | pylogit/base_multinomial_cm_v2.py | MNDC_Model._store_generic_inference_results | def _store_generic_inference_results(self,
results_dict,
all_params,
all_names):
"""
Store the model inference values that are common to all choice models.
This includes thi... | python | def _store_generic_inference_results(self,
results_dict,
all_params,
all_names):
"""
Store the model inference values that are common to all choice models.
This includes thi... | [
"def",
"_store_generic_inference_results",
"(",
"self",
",",
"results_dict",
",",
"all_params",
",",
"all_names",
")",
":",
"self",
".",
"_store_inferential_results",
"(",
"results_dict",
"[",
"\"utility_coefs\"",
"]",
",",
"index_names",
"=",
"self",
".",
"ind_var_... | Store the model inference values that are common to all choice models.
This includes things like index coefficients, gradients, hessians,
asymptotic covariance matrices, t-values, p-values, and robust versions
of these values.
Parameters
----------
results_dict : dict.
... | [
"Store",
"the",
"model",
"inference",
"values",
"that",
"are",
"common",
"to",
"all",
"choice",
"models",
".",
"This",
"includes",
"things",
"like",
"index",
"coefficients",
"gradients",
"hessians",
"asymptotic",
"covariance",
"matrices",
"t",
"-",
"values",
"p"... | f83b0fd6debaa7358d87c3828428f6d4ead71357 | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/base_multinomial_cm_v2.py#L1166-L1275 | train |
timothyb0912/pylogit | pylogit/base_multinomial_cm_v2.py | MNDC_Model._store_optional_parameters | def _store_optional_parameters(self,
optional_params,
name_list_attr,
default_name_str,
all_names,
all_params,
... | python | def _store_optional_parameters(self,
optional_params,
name_list_attr,
default_name_str,
all_names,
all_params,
... | [
"def",
"_store_optional_parameters",
"(",
"self",
",",
"optional_params",
",",
"name_list_attr",
",",
"default_name_str",
",",
"all_names",
",",
"all_params",
",",
"param_attr_name",
",",
"series_name",
")",
":",
"num_elements",
"=",
"optional_params",
".",
"shape",
... | Extract the optional parameters from the `results_dict`, save them
to the model object, and update the list of all parameters and all
parameter names.
Parameters
----------
optional_params : 1D ndarray.
The optional parameters whose values and names should be stored.... | [
"Extract",
"the",
"optional",
"parameters",
"from",
"the",
"results_dict",
"save",
"them",
"to",
"the",
"model",
"object",
"and",
"update",
"the",
"list",
"of",
"all",
"parameters",
"and",
"all",
"parameter",
"names",
"."
] | f83b0fd6debaa7358d87c3828428f6d4ead71357 | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/base_multinomial_cm_v2.py#L1277-L1339 | train |
timothyb0912/pylogit | pylogit/base_multinomial_cm_v2.py | MNDC_Model._adjust_inferential_results_for_parameter_constraints | def _adjust_inferential_results_for_parameter_constraints(self,
constraints):
"""
Ensure that parameters that were constrained during estimation do not
have any values showed for inferential results. After all, no inference
wa... | python | def _adjust_inferential_results_for_parameter_constraints(self,
constraints):
"""
Ensure that parameters that were constrained during estimation do not
have any values showed for inferential results. After all, no inference
wa... | [
"def",
"_adjust_inferential_results_for_parameter_constraints",
"(",
"self",
",",
"constraints",
")",
":",
"if",
"constraints",
"is",
"not",
"None",
":",
"inferential_attributes",
"=",
"[",
"\"standard_errors\"",
",",
"\"tvalues\"",
",",
"\"pvalues\"",
",",
"\"robust_st... | Ensure that parameters that were constrained during estimation do not
have any values showed for inferential results. After all, no inference
was performed.
Parameters
----------
constraints : list of ints, or None.
If list, should contain the positions in the array ... | [
"Ensure",
"that",
"parameters",
"that",
"were",
"constrained",
"during",
"estimation",
"do",
"not",
"have",
"any",
"values",
"showed",
"for",
"inferential",
"results",
".",
"After",
"all",
"no",
"inference",
"was",
"performed",
"."
] | f83b0fd6debaa7358d87c3828428f6d4ead71357 | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/base_multinomial_cm_v2.py#L1341-L1375 | train |
timothyb0912/pylogit | pylogit/base_multinomial_cm_v2.py | MNDC_Model._check_result_dict_for_needed_keys | def _check_result_dict_for_needed_keys(self, results_dict):
"""
Ensure that `results_dict` has the needed keys to store all the
estimation results. Raise a helpful ValueError otherwise.
"""
missing_cols = [x for x in needed_result_keys if x not in results_dict]
if missing... | python | def _check_result_dict_for_needed_keys(self, results_dict):
"""
Ensure that `results_dict` has the needed keys to store all the
estimation results. Raise a helpful ValueError otherwise.
"""
missing_cols = [x for x in needed_result_keys if x not in results_dict]
if missing... | [
"def",
"_check_result_dict_for_needed_keys",
"(",
"self",
",",
"results_dict",
")",
":",
"missing_cols",
"=",
"[",
"x",
"for",
"x",
"in",
"needed_result_keys",
"if",
"x",
"not",
"in",
"results_dict",
"]",
"if",
"missing_cols",
"!=",
"[",
"]",
":",
"msg",
"="... | Ensure that `results_dict` has the needed keys to store all the
estimation results. Raise a helpful ValueError otherwise. | [
"Ensure",
"that",
"results_dict",
"has",
"the",
"needed",
"keys",
"to",
"store",
"all",
"the",
"estimation",
"results",
".",
"Raise",
"a",
"helpful",
"ValueError",
"otherwise",
"."
] | f83b0fd6debaa7358d87c3828428f6d4ead71357 | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/base_multinomial_cm_v2.py#L1377-L1386 | train |
timothyb0912/pylogit | pylogit/base_multinomial_cm_v2.py | MNDC_Model._add_mixing_variable_names_to_individual_vars | def _add_mixing_variable_names_to_individual_vars(self):
"""
Ensure that the model objects mixing variables are added to its list of
individual variables.
"""
assert isinstance(self.ind_var_names, list)
# Note that if one estimates a mixed logit model, then the mixing
... | python | def _add_mixing_variable_names_to_individual_vars(self):
"""
Ensure that the model objects mixing variables are added to its list of
individual variables.
"""
assert isinstance(self.ind_var_names, list)
# Note that if one estimates a mixed logit model, then the mixing
... | [
"def",
"_add_mixing_variable_names_to_individual_vars",
"(",
"self",
")",
":",
"assert",
"isinstance",
"(",
"self",
".",
"ind_var_names",
",",
"list",
")",
"already_included",
"=",
"any",
"(",
"[",
"\"Sigma \"",
"in",
"x",
"for",
"x",
"in",
"self",
".",
"ind_v... | Ensure that the model objects mixing variables are added to its list of
individual variables. | [
"Ensure",
"that",
"the",
"model",
"objects",
"mixing",
"variables",
"are",
"added",
"to",
"its",
"list",
"of",
"individual",
"variables",
"."
] | f83b0fd6debaa7358d87c3828428f6d4ead71357 | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/base_multinomial_cm_v2.py#L1388-L1405 | train |
timothyb0912/pylogit | pylogit/base_multinomial_cm_v2.py | MNDC_Model.print_summaries | def print_summaries(self):
"""
Returns None. Will print the measures of fit and the estimation results
for the model.
"""
if hasattr(self, "fit_summary") and hasattr(self, "summary"):
print("\n")
print(self.fit_summary)
print("=" * 30)
... | python | def print_summaries(self):
"""
Returns None. Will print the measures of fit and the estimation results
for the model.
"""
if hasattr(self, "fit_summary") and hasattr(self, "summary"):
print("\n")
print(self.fit_summary)
print("=" * 30)
... | [
"def",
"print_summaries",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"\"fit_summary\"",
")",
"and",
"hasattr",
"(",
"self",
",",
"\"summary\"",
")",
":",
"print",
"(",
"\"\\n\"",
")",
"print",
"(",
"self",
".",
"fit_summary",
")",
"print",... | Returns None. Will print the measures of fit and the estimation results
for the model. | [
"Returns",
"None",
".",
"Will",
"print",
"the",
"measures",
"of",
"fit",
"and",
"the",
"estimation",
"results",
"for",
"the",
"model",
"."
] | f83b0fd6debaa7358d87c3828428f6d4ead71357 | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/base_multinomial_cm_v2.py#L1556-L1572 | train |
taskcluster/json-e | jsone/prattparser.py | prefix | def prefix(*kinds):
"""Decorate a method as handling prefix tokens of the given kinds"""
def wrap(fn):
try:
fn.prefix_kinds.extend(kinds)
except AttributeError:
fn.prefix_kinds = list(kinds)
return fn
return wrap | python | def prefix(*kinds):
"""Decorate a method as handling prefix tokens of the given kinds"""
def wrap(fn):
try:
fn.prefix_kinds.extend(kinds)
except AttributeError:
fn.prefix_kinds = list(kinds)
return fn
return wrap | [
"def",
"prefix",
"(",
"*",
"kinds",
")",
":",
"def",
"wrap",
"(",
"fn",
")",
":",
"try",
":",
"fn",
".",
"prefix_kinds",
".",
"extend",
"(",
"kinds",
")",
"except",
"AttributeError",
":",
"fn",
".",
"prefix_kinds",
"=",
"list",
"(",
"kinds",
")",
"... | Decorate a method as handling prefix tokens of the given kinds | [
"Decorate",
"a",
"method",
"as",
"handling",
"prefix",
"tokens",
"of",
"the",
"given",
"kinds"
] | ac0c9fba1de3ed619f05a64dae929f6687789cbc | https://github.com/taskcluster/json-e/blob/ac0c9fba1de3ed619f05a64dae929f6687789cbc/jsone/prattparser.py#L20-L28 | train |
taskcluster/json-e | jsone/prattparser.py | infix | def infix(*kinds):
"""Decorate a method as handling infix tokens of the given kinds"""
def wrap(fn):
try:
fn.infix_kinds.extend(kinds)
except AttributeError:
fn.infix_kinds = list(kinds)
return fn
return wrap | python | def infix(*kinds):
"""Decorate a method as handling infix tokens of the given kinds"""
def wrap(fn):
try:
fn.infix_kinds.extend(kinds)
except AttributeError:
fn.infix_kinds = list(kinds)
return fn
return wrap | [
"def",
"infix",
"(",
"*",
"kinds",
")",
":",
"def",
"wrap",
"(",
"fn",
")",
":",
"try",
":",
"fn",
".",
"infix_kinds",
".",
"extend",
"(",
"kinds",
")",
"except",
"AttributeError",
":",
"fn",
".",
"infix_kinds",
"=",
"list",
"(",
"kinds",
")",
"ret... | Decorate a method as handling infix tokens of the given kinds | [
"Decorate",
"a",
"method",
"as",
"handling",
"infix",
"tokens",
"of",
"the",
"given",
"kinds"
] | ac0c9fba1de3ed619f05a64dae929f6687789cbc | https://github.com/taskcluster/json-e/blob/ac0c9fba1de3ed619f05a64dae929f6687789cbc/jsone/prattparser.py#L31-L39 | train |
taskcluster/json-e | jsone/prattparser.py | ParseContext.attempt | def attempt(self, *kinds):
"""Try to get the next token if it matches one of the kinds given,
otherwise returning None. If no kinds are given, any kind is
accepted."""
if self._error:
raise self._error
token = self.next_token
if not token:
return N... | python | def attempt(self, *kinds):
"""Try to get the next token if it matches one of the kinds given,
otherwise returning None. If no kinds are given, any kind is
accepted."""
if self._error:
raise self._error
token = self.next_token
if not token:
return N... | [
"def",
"attempt",
"(",
"self",
",",
"*",
"kinds",
")",
":",
"if",
"self",
".",
"_error",
":",
"raise",
"self",
".",
"_error",
"token",
"=",
"self",
".",
"next_token",
"if",
"not",
"token",
":",
"return",
"None",
"if",
"kinds",
"and",
"token",
".",
... | Try to get the next token if it matches one of the kinds given,
otherwise returning None. If no kinds are given, any kind is
accepted. | [
"Try",
"to",
"get",
"the",
"next",
"token",
"if",
"it",
"matches",
"one",
"of",
"the",
"kinds",
"given",
"otherwise",
"returning",
"None",
".",
"If",
"no",
"kinds",
"are",
"given",
"any",
"kind",
"is",
"accepted",
"."
] | ac0c9fba1de3ed619f05a64dae929f6687789cbc | https://github.com/taskcluster/json-e/blob/ac0c9fba1de3ed619f05a64dae929f6687789cbc/jsone/prattparser.py#L150-L162 | train |
taskcluster/json-e | jsone/prattparser.py | ParseContext.require | def require(self, *kinds):
"""Get the next token, raising an exception if it doesn't match one of
the given kinds, or the input ends. If no kinds are given, returns the
next token of any kind."""
token = self.attempt()
if not token:
raise SyntaxError('Unexpected end o... | python | def require(self, *kinds):
"""Get the next token, raising an exception if it doesn't match one of
the given kinds, or the input ends. If no kinds are given, returns the
next token of any kind."""
token = self.attempt()
if not token:
raise SyntaxError('Unexpected end o... | [
"def",
"require",
"(",
"self",
",",
"*",
"kinds",
")",
":",
"token",
"=",
"self",
".",
"attempt",
"(",
")",
"if",
"not",
"token",
":",
"raise",
"SyntaxError",
"(",
"'Unexpected end of input'",
")",
"if",
"kinds",
"and",
"token",
".",
"kind",
"not",
"in... | Get the next token, raising an exception if it doesn't match one of
the given kinds, or the input ends. If no kinds are given, returns the
next token of any kind. | [
"Get",
"the",
"next",
"token",
"raising",
"an",
"exception",
"if",
"it",
"doesn",
"t",
"match",
"one",
"of",
"the",
"given",
"kinds",
"or",
"the",
"input",
"ends",
".",
"If",
"no",
"kinds",
"are",
"given",
"returns",
"the",
"next",
"token",
"of",
"any"... | ac0c9fba1de3ed619f05a64dae929f6687789cbc | https://github.com/taskcluster/json-e/blob/ac0c9fba1de3ed619f05a64dae929f6687789cbc/jsone/prattparser.py#L164-L173 | train |
amzn/ion-python | amazon/ion/symbols.py | local_symbol_table | def local_symbol_table(imports=None, symbols=()):
"""Constructs a local symbol table.
Args:
imports (Optional[SymbolTable]): Shared symbol tables to import.
symbols (Optional[Iterable[Unicode]]): Initial local symbols to add.
Returns:
SymbolTable: A mutable local symbol table with ... | python | def local_symbol_table(imports=None, symbols=()):
"""Constructs a local symbol table.
Args:
imports (Optional[SymbolTable]): Shared symbol tables to import.
symbols (Optional[Iterable[Unicode]]): Initial local symbols to add.
Returns:
SymbolTable: A mutable local symbol table with ... | [
"def",
"local_symbol_table",
"(",
"imports",
"=",
"None",
",",
"symbols",
"=",
"(",
")",
")",
":",
"return",
"SymbolTable",
"(",
"table_type",
"=",
"LOCAL_TABLE_TYPE",
",",
"symbols",
"=",
"symbols",
",",
"imports",
"=",
"imports",
")"
] | Constructs a local symbol table.
Args:
imports (Optional[SymbolTable]): Shared symbol tables to import.
symbols (Optional[Iterable[Unicode]]): Initial local symbols to add.
Returns:
SymbolTable: A mutable local symbol table with the seeded local symbols. | [
"Constructs",
"a",
"local",
"symbol",
"table",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/symbols.py#L380-L394 | train |
amzn/ion-python | amazon/ion/symbols.py | shared_symbol_table | def shared_symbol_table(name, version, symbols, imports=None):
"""Constructs a shared symbol table.
Args:
name (unicode): The name of the shared symbol table.
version (int): The version of the shared symbol table.
symbols (Iterable[unicode]): The symbols to associate with the table.
... | python | def shared_symbol_table(name, version, symbols, imports=None):
"""Constructs a shared symbol table.
Args:
name (unicode): The name of the shared symbol table.
version (int): The version of the shared symbol table.
symbols (Iterable[unicode]): The symbols to associate with the table.
... | [
"def",
"shared_symbol_table",
"(",
"name",
",",
"version",
",",
"symbols",
",",
"imports",
"=",
"None",
")",
":",
"return",
"SymbolTable",
"(",
"table_type",
"=",
"SHARED_TABLE_TYPE",
",",
"symbols",
"=",
"symbols",
",",
"name",
"=",
"name",
",",
"version",
... | Constructs a shared symbol table.
Args:
name (unicode): The name of the shared symbol table.
version (int): The version of the shared symbol table.
symbols (Iterable[unicode]): The symbols to associate with the table.
imports (Optional[Iterable[SymbolTable]): The shared symbol table... | [
"Constructs",
"a",
"shared",
"symbol",
"table",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/symbols.py#L397-L415 | train |
amzn/ion-python | amazon/ion/symbols.py | placeholder_symbol_table | def placeholder_symbol_table(name, version, max_id):
"""Constructs a shared symbol table that consists symbols that all have no known text.
This is generally used for cases where a shared symbol table is not available by the
application.
Args:
name (unicode): The name of the shared symbol tabl... | python | def placeholder_symbol_table(name, version, max_id):
"""Constructs a shared symbol table that consists symbols that all have no known text.
This is generally used for cases where a shared symbol table is not available by the
application.
Args:
name (unicode): The name of the shared symbol tabl... | [
"def",
"placeholder_symbol_table",
"(",
"name",
",",
"version",
",",
"max_id",
")",
":",
"if",
"version",
"<=",
"0",
":",
"raise",
"ValueError",
"(",
"'Version must be grater than or equal to 1: %s'",
"%",
"version",
")",
"if",
"max_id",
"<",
"0",
":",
"raise",
... | Constructs a shared symbol table that consists symbols that all have no known text.
This is generally used for cases where a shared symbol table is not available by the
application.
Args:
name (unicode): The name of the shared symbol table.
version (int): The version of the shared symbol t... | [
"Constructs",
"a",
"shared",
"symbol",
"table",
"that",
"consists",
"symbols",
"that",
"all",
"have",
"no",
"known",
"text",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/symbols.py#L418-L443 | train |
amzn/ion-python | amazon/ion/symbols.py | substitute_symbol_table | def substitute_symbol_table(table, version, max_id):
"""Substitutes a given shared symbol table for another version.
* If the given table has **more** symbols than the requested substitute, then the generated
symbol table will be a subset of the given table.
* If the given table has **less** symbols ... | python | def substitute_symbol_table(table, version, max_id):
"""Substitutes a given shared symbol table for another version.
* If the given table has **more** symbols than the requested substitute, then the generated
symbol table will be a subset of the given table.
* If the given table has **less** symbols ... | [
"def",
"substitute_symbol_table",
"(",
"table",
",",
"version",
",",
"max_id",
")",
":",
"if",
"not",
"table",
".",
"table_type",
".",
"is_shared",
":",
"raise",
"ValueError",
"(",
"'Symbol table to substitute from must be a shared table'",
")",
"if",
"version",
"<=... | Substitutes a given shared symbol table for another version.
* If the given table has **more** symbols than the requested substitute, then the generated
symbol table will be a subset of the given table.
* If the given table has **less** symbols than the requested substitute, then the generated
symb... | [
"Substitutes",
"a",
"given",
"shared",
"symbol",
"table",
"for",
"another",
"version",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/symbols.py#L446-L484 | train |
amzn/ion-python | amazon/ion/symbols.py | SymbolTable.__add | def __add(self, token):
"""Unconditionally adds a token to the table."""
self.__symbols.append(token)
text = token.text
if text is not None and text not in self.__mapping:
self.__mapping[text] = token | python | def __add(self, token):
"""Unconditionally adds a token to the table."""
self.__symbols.append(token)
text = token.text
if text is not None and text not in self.__mapping:
self.__mapping[text] = token | [
"def",
"__add",
"(",
"self",
",",
"token",
")",
":",
"self",
".",
"__symbols",
".",
"append",
"(",
"token",
")",
"text",
"=",
"token",
".",
"text",
"if",
"text",
"is",
"not",
"None",
"and",
"text",
"not",
"in",
"self",
".",
"__mapping",
":",
"self"... | Unconditionally adds a token to the table. | [
"Unconditionally",
"adds",
"a",
"token",
"to",
"the",
"table",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/symbols.py#L213-L218 | train |
amzn/ion-python | amazon/ion/symbols.py | SymbolTable.__add_shared | def __add_shared(self, original_token):
"""Adds a token, normalizing the SID and import reference to this table."""
sid = self.__new_sid()
token = SymbolToken(original_token.text, sid, self.__import_location(sid))
self.__add(token)
return token | python | def __add_shared(self, original_token):
"""Adds a token, normalizing the SID and import reference to this table."""
sid = self.__new_sid()
token = SymbolToken(original_token.text, sid, self.__import_location(sid))
self.__add(token)
return token | [
"def",
"__add_shared",
"(",
"self",
",",
"original_token",
")",
":",
"sid",
"=",
"self",
".",
"__new_sid",
"(",
")",
"token",
"=",
"SymbolToken",
"(",
"original_token",
".",
"text",
",",
"sid",
",",
"self",
".",
"__import_location",
"(",
"sid",
")",
")",... | Adds a token, normalizing the SID and import reference to this table. | [
"Adds",
"a",
"token",
"normalizing",
"the",
"SID",
"and",
"import",
"reference",
"to",
"this",
"table",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/symbols.py#L220-L225 | train |
amzn/ion-python | amazon/ion/symbols.py | SymbolTable.__add_import | def __add_import(self, original_token):
"""Adds a token, normalizing only the SID"""
sid = self.__new_sid()
token = SymbolToken(original_token.text, sid, original_token.location)
self.__add(token)
return token | python | def __add_import(self, original_token):
"""Adds a token, normalizing only the SID"""
sid = self.__new_sid()
token = SymbolToken(original_token.text, sid, original_token.location)
self.__add(token)
return token | [
"def",
"__add_import",
"(",
"self",
",",
"original_token",
")",
":",
"sid",
"=",
"self",
".",
"__new_sid",
"(",
")",
"token",
"=",
"SymbolToken",
"(",
"original_token",
".",
"text",
",",
"sid",
",",
"original_token",
".",
"location",
")",
"self",
".",
"_... | Adds a token, normalizing only the SID | [
"Adds",
"a",
"token",
"normalizing",
"only",
"the",
"SID"
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/symbols.py#L227-L232 | train |
amzn/ion-python | amazon/ion/symbols.py | SymbolTable.__add_text | def __add_text(self, text):
"""Adds the given Unicode text as a locally defined symbol."""
if text is not None and not isinstance(text, six.text_type):
raise TypeError('Local symbol definition must be a Unicode sequence or None: %r' % text)
sid = self.__new_sid()
location = N... | python | def __add_text(self, text):
"""Adds the given Unicode text as a locally defined symbol."""
if text is not None and not isinstance(text, six.text_type):
raise TypeError('Local symbol definition must be a Unicode sequence or None: %r' % text)
sid = self.__new_sid()
location = N... | [
"def",
"__add_text",
"(",
"self",
",",
"text",
")",
":",
"if",
"text",
"is",
"not",
"None",
"and",
"not",
"isinstance",
"(",
"text",
",",
"six",
".",
"text_type",
")",
":",
"raise",
"TypeError",
"(",
"'Local symbol definition must be a Unicode sequence or None: ... | Adds the given Unicode text as a locally defined symbol. | [
"Adds",
"the",
"given",
"Unicode",
"text",
"as",
"a",
"locally",
"defined",
"symbol",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/symbols.py#L234-L244 | train |
amzn/ion-python | amazon/ion/symbols.py | SymbolTable.intern | def intern(self, text):
"""Interns the given Unicode sequence into the symbol table.
Note:
This operation is only valid on local symbol tables.
Args:
text (unicode): The target to intern.
Returns:
SymbolToken: The mapped symbol token which may alrea... | python | def intern(self, text):
"""Interns the given Unicode sequence into the symbol table.
Note:
This operation is only valid on local symbol tables.
Args:
text (unicode): The target to intern.
Returns:
SymbolToken: The mapped symbol token which may alrea... | [
"def",
"intern",
"(",
"self",
",",
"text",
")",
":",
"if",
"self",
".",
"table_type",
".",
"is_shared",
":",
"raise",
"TypeError",
"(",
"'Cannot intern on shared symbol table'",
")",
"if",
"not",
"isinstance",
"(",
"text",
",",
"six",
".",
"text_type",
")",
... | Interns the given Unicode sequence into the symbol table.
Note:
This operation is only valid on local symbol tables.
Args:
text (unicode): The target to intern.
Returns:
SymbolToken: The mapped symbol token which may already exist in the table. | [
"Interns",
"the",
"given",
"Unicode",
"sequence",
"into",
"the",
"symbol",
"table",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/symbols.py#L246-L266 | train |
amzn/ion-python | amazon/ion/symbols.py | SymbolTable.get | def get(self, key, default=None):
"""Returns a token by text or local ID, with a default.
A given text image may be associated with more than one symbol ID. This will return the first definition.
Note:
User defined symbol IDs are always one-based. Symbol zero is a special symbol ... | python | def get(self, key, default=None):
"""Returns a token by text or local ID, with a default.
A given text image may be associated with more than one symbol ID. This will return the first definition.
Note:
User defined symbol IDs are always one-based. Symbol zero is a special symbol ... | [
"def",
"get",
"(",
"self",
",",
"key",
",",
"default",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"key",
",",
"six",
".",
"text_type",
")",
":",
"return",
"self",
".",
"__mapping",
".",
"get",
"(",
"key",
",",
"None",
")",
"if",
"not",
"isin... | Returns a token by text or local ID, with a default.
A given text image may be associated with more than one symbol ID. This will return the first definition.
Note:
User defined symbol IDs are always one-based. Symbol zero is a special symbol that
always has no text.
... | [
"Returns",
"a",
"token",
"by",
"text",
"or",
"local",
"ID",
"with",
"a",
"default",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/symbols.py#L268-L297 | train |
amzn/ion-python | amazon/ion/symbols.py | SymbolTableCatalog.register | def register(self, table):
"""Adds a shared table to the catalog.
Args:
table (SymbolTable): A non-system, shared symbol table.
"""
if table.table_type.is_system:
raise ValueError('Cannot add system table to catalog')
if not table.table_type.is_shared:
... | python | def register(self, table):
"""Adds a shared table to the catalog.
Args:
table (SymbolTable): A non-system, shared symbol table.
"""
if table.table_type.is_system:
raise ValueError('Cannot add system table to catalog')
if not table.table_type.is_shared:
... | [
"def",
"register",
"(",
"self",
",",
"table",
")",
":",
"if",
"table",
".",
"table_type",
".",
"is_system",
":",
"raise",
"ValueError",
"(",
"'Cannot add system table to catalog'",
")",
"if",
"not",
"table",
".",
"table_type",
".",
"is_shared",
":",
"raise",
... | Adds a shared table to the catalog.
Args:
table (SymbolTable): A non-system, shared symbol table. | [
"Adds",
"a",
"shared",
"table",
"to",
"the",
"catalog",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/symbols.py#L499-L516 | train |
amzn/ion-python | amazon/ion/symbols.py | SymbolTableCatalog.resolve | def resolve(self, name, version, max_id):
"""Resolves the table for a given name and version.
Args:
name (unicode): The name of the table to resolve.
version (int): The version of the table to resolve.
max_id (Optional[int]): The maximum ID of the table requested.
... | python | def resolve(self, name, version, max_id):
"""Resolves the table for a given name and version.
Args:
name (unicode): The name of the table to resolve.
version (int): The version of the table to resolve.
max_id (Optional[int]): The maximum ID of the table requested.
... | [
"def",
"resolve",
"(",
"self",
",",
"name",
",",
"version",
",",
"max_id",
")",
":",
"if",
"not",
"isinstance",
"(",
"name",
",",
"six",
".",
"text_type",
")",
":",
"raise",
"TypeError",
"(",
"'Name must be a Unicode sequence: %r'",
"%",
"name",
")",
"if",... | Resolves the table for a given name and version.
Args:
name (unicode): The name of the table to resolve.
version (int): The version of the table to resolve.
max_id (Optional[int]): The maximum ID of the table requested.
May be ``None`` in which case an exact ... | [
"Resolves",
"the",
"table",
"for",
"a",
"given",
"name",
"and",
"version",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/symbols.py#L518-L564 | train |
amzn/ion-python | amazon/ion/writer_buffer.py | BufferTree.start_container | def start_container(self):
"""Add a node to the tree that represents the start of a container.
Until end_container is called, any nodes added through add_scalar_value
or start_container will be children of this new node.
"""
self.__container_lengths.append(self.current_container... | python | def start_container(self):
"""Add a node to the tree that represents the start of a container.
Until end_container is called, any nodes added through add_scalar_value
or start_container will be children of this new node.
"""
self.__container_lengths.append(self.current_container... | [
"def",
"start_container",
"(",
"self",
")",
":",
"self",
".",
"__container_lengths",
".",
"append",
"(",
"self",
".",
"current_container_length",
")",
"self",
".",
"current_container_length",
"=",
"0",
"new_container_node",
"=",
"_Node",
"(",
")",
"self",
".",
... | Add a node to the tree that represents the start of a container.
Until end_container is called, any nodes added through add_scalar_value
or start_container will be children of this new node. | [
"Add",
"a",
"node",
"to",
"the",
"tree",
"that",
"represents",
"the",
"start",
"of",
"a",
"container",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/writer_buffer.py#L91-L102 | train |
amzn/ion-python | amazon/ion/writer_buffer.py | BufferTree.end_container | def end_container(self, header_buf):
"""Add a node containing the container's header to the current subtree.
This node will be added as the leftmost leaf of the subtree that was
started by the matching call to start_container.
Args:
header_buf (bytearray): bytearray contain... | python | def end_container(self, header_buf):
"""Add a node containing the container's header to the current subtree.
This node will be added as the leftmost leaf of the subtree that was
started by the matching call to start_container.
Args:
header_buf (bytearray): bytearray contain... | [
"def",
"end_container",
"(",
"self",
",",
"header_buf",
")",
":",
"if",
"not",
"self",
".",
"__container_nodes",
":",
"raise",
"ValueError",
"(",
"\"Attempted to end container with none active.\"",
")",
"self",
".",
"__container_node",
".",
"add_leaf",
"(",
"_Node",... | Add a node containing the container's header to the current subtree.
This node will be added as the leftmost leaf of the subtree that was
started by the matching call to start_container.
Args:
header_buf (bytearray): bytearray containing the container header. | [
"Add",
"a",
"node",
"containing",
"the",
"container",
"s",
"header",
"to",
"the",
"current",
"subtree",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/writer_buffer.py#L104-L120 | train |
amzn/ion-python | amazon/ion/writer_buffer.py | BufferTree.add_scalar_value | def add_scalar_value(self, value_buf):
"""Add a node to the tree containing a scalar value.
Args:
value_buf (bytearray): bytearray containing the scalar value.
"""
self.__container_node.add_child(_Node(value_buf))
self.current_container_length += len(value_buf) | python | def add_scalar_value(self, value_buf):
"""Add a node to the tree containing a scalar value.
Args:
value_buf (bytearray): bytearray containing the scalar value.
"""
self.__container_node.add_child(_Node(value_buf))
self.current_container_length += len(value_buf) | [
"def",
"add_scalar_value",
"(",
"self",
",",
"value_buf",
")",
":",
"self",
".",
"__container_node",
".",
"add_child",
"(",
"_Node",
"(",
"value_buf",
")",
")",
"self",
".",
"current_container_length",
"+=",
"len",
"(",
"value_buf",
")"
] | Add a node to the tree containing a scalar value.
Args:
value_buf (bytearray): bytearray containing the scalar value. | [
"Add",
"a",
"node",
"to",
"the",
"tree",
"containing",
"a",
"scalar",
"value",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/writer_buffer.py#L122-L129 | train |
amzn/ion-python | amazon/ion/writer_buffer.py | BufferTree.drain | def drain(self):
"""Walk the BufferTree and reset it when finished.
Yields:
any: The current node's value.
"""
if self.__container_nodes:
raise ValueError("Attempted to drain without ending all containers.")
for buf in self.__depth_traverse(self.__root):
... | python | def drain(self):
"""Walk the BufferTree and reset it when finished.
Yields:
any: The current node's value.
"""
if self.__container_nodes:
raise ValueError("Attempted to drain without ending all containers.")
for buf in self.__depth_traverse(self.__root):
... | [
"def",
"drain",
"(",
"self",
")",
":",
"if",
"self",
".",
"__container_nodes",
":",
"raise",
"ValueError",
"(",
"\"Attempted to drain without ending all containers.\"",
")",
"for",
"buf",
"in",
"self",
".",
"__depth_traverse",
"(",
"self",
".",
"__root",
")",
":... | Walk the BufferTree and reset it when finished.
Yields:
any: The current node's value. | [
"Walk",
"the",
"BufferTree",
"and",
"reset",
"it",
"when",
"finished",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/writer_buffer.py#L131-L142 | train |
amzn/ion-python | amazon/ion/equivalence.py | ion_equals | def ion_equals(a, b, timestamps_instants_only=False):
"""Tests two objects for equivalence under the Ion data model.
There are three important cases:
* When neither operand specifies its `ion_type` or `annotations`, this method will only return True when the
values of both operands are equiva... | python | def ion_equals(a, b, timestamps_instants_only=False):
"""Tests two objects for equivalence under the Ion data model.
There are three important cases:
* When neither operand specifies its `ion_type` or `annotations`, this method will only return True when the
values of both operands are equiva... | [
"def",
"ion_equals",
"(",
"a",
",",
"b",
",",
"timestamps_instants_only",
"=",
"False",
")",
":",
"if",
"timestamps_instants_only",
":",
"return",
"_ion_equals_timestamps_instants",
"(",
"a",
",",
"b",
")",
"return",
"_ion_equals_timestamps_data_model",
"(",
"a",
... | Tests two objects for equivalence under the Ion data model.
There are three important cases:
* When neither operand specifies its `ion_type` or `annotations`, this method will only return True when the
values of both operands are equivalent under the Ion data model.
* When only one of the... | [
"Tests",
"two",
"objects",
"for",
"equivalence",
"under",
"the",
"Ion",
"data",
"model",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/equivalence.py#L35-L57 | train |
amzn/ion-python | amazon/ion/equivalence.py | _ion_equals | def _ion_equals(a, b, timestamp_comparison_func, recursive_comparison_func):
"""Compares a and b according to the description of the ion_equals method."""
for a, b in ((a, b), (b, a)): # Ensures that operand order does not matter.
if isinstance(a, _IonNature):
if isinstance(b, _IonNature):
... | python | def _ion_equals(a, b, timestamp_comparison_func, recursive_comparison_func):
"""Compares a and b according to the description of the ion_equals method."""
for a, b in ((a, b), (b, a)): # Ensures that operand order does not matter.
if isinstance(a, _IonNature):
if isinstance(b, _IonNature):
... | [
"def",
"_ion_equals",
"(",
"a",
",",
"b",
",",
"timestamp_comparison_func",
",",
"recursive_comparison_func",
")",
":",
"for",
"a",
",",
"b",
"in",
"(",
"(",
"a",
",",
"b",
")",
",",
"(",
"b",
",",
"a",
")",
")",
":",
"if",
"isinstance",
"(",
"a",
... | Compares a and b according to the description of the ion_equals method. | [
"Compares",
"a",
"and",
"b",
"according",
"to",
"the",
"description",
"of",
"the",
"ion_equals",
"method",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/equivalence.py#L68-L110 | train |
amzn/ion-python | amazon/ion/equivalence.py | _timestamps_eq | def _timestamps_eq(a, b):
"""Compares two timestamp operands for equivalence under the Ion data model."""
assert isinstance(a, datetime)
if not isinstance(b, datetime):
return False
# Local offsets must be equivalent.
if (a.tzinfo is None) ^ (b.tzinfo is None):
return False
if a.... | python | def _timestamps_eq(a, b):
"""Compares two timestamp operands for equivalence under the Ion data model."""
assert isinstance(a, datetime)
if not isinstance(b, datetime):
return False
# Local offsets must be equivalent.
if (a.tzinfo is None) ^ (b.tzinfo is None):
return False
if a.... | [
"def",
"_timestamps_eq",
"(",
"a",
",",
"b",
")",
":",
"assert",
"isinstance",
"(",
"a",
",",
"datetime",
")",
"if",
"not",
"isinstance",
"(",
"b",
",",
"datetime",
")",
":",
"return",
"False",
"if",
"(",
"a",
".",
"tzinfo",
"is",
"None",
")",
"^",... | Compares two timestamp operands for equivalence under the Ion data model. | [
"Compares",
"two",
"timestamp",
"operands",
"for",
"equivalence",
"under",
"the",
"Ion",
"data",
"model",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/equivalence.py#L161-L182 | train |
amzn/ion-python | amazon/ion/equivalence.py | _timestamp_instants_eq | def _timestamp_instants_eq(a, b):
"""Compares two timestamp operands for point-in-time equivalence only."""
assert isinstance(a, datetime)
if not isinstance(b, datetime):
return False
# datetime's __eq__ can't compare a None offset and a non-None offset. For these equivalence semantics, a None
... | python | def _timestamp_instants_eq(a, b):
"""Compares two timestamp operands for point-in-time equivalence only."""
assert isinstance(a, datetime)
if not isinstance(b, datetime):
return False
# datetime's __eq__ can't compare a None offset and a non-None offset. For these equivalence semantics, a None
... | [
"def",
"_timestamp_instants_eq",
"(",
"a",
",",
"b",
")",
":",
"assert",
"isinstance",
"(",
"a",
",",
"datetime",
")",
"if",
"not",
"isinstance",
"(",
"b",
",",
"datetime",
")",
":",
"return",
"False",
"if",
"a",
".",
"tzinfo",
"is",
"None",
":",
"a"... | Compares two timestamp operands for point-in-time equivalence only. | [
"Compares",
"two",
"timestamp",
"operands",
"for",
"point",
"-",
"in",
"-",
"time",
"equivalence",
"only",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/equivalence.py#L185-L197 | train |
amzn/ion-python | amazon/ion/reader_binary.py | _parse_var_int_components | def _parse_var_int_components(buf, signed):
"""Parses a ``VarInt`` or ``VarUInt`` field from a file-like object."""
value = 0
sign = 1
while True:
ch = buf.read(1)
if ch == '':
raise IonException('Variable integer under-run')
octet = ord(ch)
if signed:
... | python | def _parse_var_int_components(buf, signed):
"""Parses a ``VarInt`` or ``VarUInt`` field from a file-like object."""
value = 0
sign = 1
while True:
ch = buf.read(1)
if ch == '':
raise IonException('Variable integer under-run')
octet = ord(ch)
if signed:
... | [
"def",
"_parse_var_int_components",
"(",
"buf",
",",
"signed",
")",
":",
"value",
"=",
"0",
"sign",
"=",
"1",
"while",
"True",
":",
"ch",
"=",
"buf",
".",
"read",
"(",
"1",
")",
"if",
"ch",
"==",
"''",
":",
"raise",
"IonException",
"(",
"'Variable in... | Parses a ``VarInt`` or ``VarUInt`` field from a file-like object. | [
"Parses",
"a",
"VarInt",
"or",
"VarUInt",
"field",
"from",
"a",
"file",
"-",
"like",
"object",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader_binary.py#L132-L152 | train |
amzn/ion-python | amazon/ion/reader_binary.py | _parse_signed_int_components | def _parse_signed_int_components(buf):
"""Parses the remainder of a file-like object as a signed magnitude value.
Returns:
Returns a pair of the sign bit and the unsigned magnitude.
"""
sign_bit = 0
value = 0
first = True
while True:
ch = buf.read(1)
if ch == b'':
... | python | def _parse_signed_int_components(buf):
"""Parses the remainder of a file-like object as a signed magnitude value.
Returns:
Returns a pair of the sign bit and the unsigned magnitude.
"""
sign_bit = 0
value = 0
first = True
while True:
ch = buf.read(1)
if ch == b'':
... | [
"def",
"_parse_signed_int_components",
"(",
"buf",
")",
":",
"sign_bit",
"=",
"0",
"value",
"=",
"0",
"first",
"=",
"True",
"while",
"True",
":",
"ch",
"=",
"buf",
".",
"read",
"(",
"1",
")",
"if",
"ch",
"==",
"b''",
":",
"break",
"octet",
"=",
"or... | Parses the remainder of a file-like object as a signed magnitude value.
Returns:
Returns a pair of the sign bit and the unsigned magnitude. | [
"Parses",
"the",
"remainder",
"of",
"a",
"file",
"-",
"like",
"object",
"as",
"a",
"signed",
"magnitude",
"value",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader_binary.py#L160-L184 | train |
amzn/ion-python | amazon/ion/reader_binary.py | _parse_decimal | def _parse_decimal(buf):
"""Parses the remainder of a file-like object as a decimal."""
exponent = _parse_var_int(buf, signed=True)
sign_bit, coefficient = _parse_signed_int_components(buf)
if coefficient == 0:
# Handle the zero cases--especially negative zero
value = Decimal((sign_bit,... | python | def _parse_decimal(buf):
"""Parses the remainder of a file-like object as a decimal."""
exponent = _parse_var_int(buf, signed=True)
sign_bit, coefficient = _parse_signed_int_components(buf)
if coefficient == 0:
# Handle the zero cases--especially negative zero
value = Decimal((sign_bit,... | [
"def",
"_parse_decimal",
"(",
"buf",
")",
":",
"exponent",
"=",
"_parse_var_int",
"(",
"buf",
",",
"signed",
"=",
"True",
")",
"sign_bit",
",",
"coefficient",
"=",
"_parse_signed_int_components",
"(",
"buf",
")",
"if",
"coefficient",
"==",
"0",
":",
"value",... | Parses the remainder of a file-like object as a decimal. | [
"Parses",
"the",
"remainder",
"of",
"a",
"file",
"-",
"like",
"object",
"as",
"a",
"decimal",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader_binary.py#L187-L199 | train |
amzn/ion-python | amazon/ion/reader_binary.py | _create_delegate_handler | def _create_delegate_handler(delegate):
"""Creates a handler function that creates a co-routine that can yield once with the given
positional arguments to the delegate as a transition.
Args:
delegate (Coroutine): The co-routine to delegate to.
Returns:
A :class:`callable` handler that ... | python | def _create_delegate_handler(delegate):
"""Creates a handler function that creates a co-routine that can yield once with the given
positional arguments to the delegate as a transition.
Args:
delegate (Coroutine): The co-routine to delegate to.
Returns:
A :class:`callable` handler that ... | [
"def",
"_create_delegate_handler",
"(",
"delegate",
")",
":",
"@",
"coroutine",
"def",
"handler",
"(",
"*",
"args",
")",
":",
"yield",
"yield",
"delegate",
".",
"send",
"(",
"Transition",
"(",
"args",
",",
"delegate",
")",
")",
"return",
"handler"
] | Creates a handler function that creates a co-routine that can yield once with the given
positional arguments to the delegate as a transition.
Args:
delegate (Coroutine): The co-routine to delegate to.
Returns:
A :class:`callable` handler that returns a co-routine that ignores the data it r... | [
"Creates",
"a",
"handler",
"function",
"that",
"creates",
"a",
"co",
"-",
"routine",
"that",
"can",
"yield",
"once",
"with",
"the",
"given",
"positional",
"arguments",
"to",
"the",
"delegate",
"as",
"a",
"transition",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader_binary.py#L314-L330 | train |
amzn/ion-python | amazon/ion/reader_binary.py | _var_uint_field_handler | def _var_uint_field_handler(handler, ctx):
"""Handler co-routine for variable unsigned integer fields that.
Invokes the given ``handler`` function with the read field and context,
then immediately yields to the resulting co-routine.
"""
_, self = yield
queue = ctx.queue
value = 0
while ... | python | def _var_uint_field_handler(handler, ctx):
"""Handler co-routine for variable unsigned integer fields that.
Invokes the given ``handler`` function with the read field and context,
then immediately yields to the resulting co-routine.
"""
_, self = yield
queue = ctx.queue
value = 0
while ... | [
"def",
"_var_uint_field_handler",
"(",
"handler",
",",
"ctx",
")",
":",
"_",
",",
"self",
"=",
"yield",
"queue",
"=",
"ctx",
".",
"queue",
"value",
"=",
"0",
"while",
"True",
":",
"if",
"len",
"(",
"queue",
")",
"==",
"0",
":",
"yield",
"ctx",
".",... | Handler co-routine for variable unsigned integer fields that.
Invokes the given ``handler`` function with the read field and context,
then immediately yields to the resulting co-routine. | [
"Handler",
"co",
"-",
"routine",
"for",
"variable",
"unsigned",
"integer",
"fields",
"that",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader_binary.py#L398-L416 | train |
amzn/ion-python | amazon/ion/reader_binary.py | _length_scalar_handler | def _length_scalar_handler(scalar_factory, ion_type, length, ctx):
"""Handles scalars, ``scalar_factory`` is a function that returns a value or thunk."""
_, self = yield
if length == 0:
data = b''
else:
yield ctx.read_data_transition(length, self)
data = ctx.queue.read(length)
... | python | def _length_scalar_handler(scalar_factory, ion_type, length, ctx):
"""Handles scalars, ``scalar_factory`` is a function that returns a value or thunk."""
_, self = yield
if length == 0:
data = b''
else:
yield ctx.read_data_transition(length, self)
data = ctx.queue.read(length)
... | [
"def",
"_length_scalar_handler",
"(",
"scalar_factory",
",",
"ion_type",
",",
"length",
",",
"ctx",
")",
":",
"_",
",",
"self",
"=",
"yield",
"if",
"length",
"==",
"0",
":",
"data",
"=",
"b''",
"else",
":",
"yield",
"ctx",
".",
"read_data_transition",
"(... | Handles scalars, ``scalar_factory`` is a function that returns a value or thunk. | [
"Handles",
"scalars",
"scalar_factory",
"is",
"a",
"function",
"that",
"returns",
"a",
"value",
"or",
"thunk",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader_binary.py#L455-L469 | train |
amzn/ion-python | amazon/ion/reader_binary.py | _annotation_handler | def _annotation_handler(ion_type, length, ctx):
"""Handles annotations. ``ion_type`` is ignored."""
_, self = yield
self_handler = _create_delegate_handler(self)
if ctx.annotations is not None:
raise IonException('Annotation cannot be nested in annotations')
# We have to replace our conte... | python | def _annotation_handler(ion_type, length, ctx):
"""Handles annotations. ``ion_type`` is ignored."""
_, self = yield
self_handler = _create_delegate_handler(self)
if ctx.annotations is not None:
raise IonException('Annotation cannot be nested in annotations')
# We have to replace our conte... | [
"def",
"_annotation_handler",
"(",
"ion_type",
",",
"length",
",",
"ctx",
")",
":",
"_",
",",
"self",
"=",
"yield",
"self_handler",
"=",
"_create_delegate_handler",
"(",
"self",
")",
"if",
"ctx",
".",
"annotations",
"is",
"not",
"None",
":",
"raise",
"IonE... | Handles annotations. ``ion_type`` is ignored. | [
"Handles",
"annotations",
".",
"ion_type",
"is",
"ignored",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader_binary.py#L496-L526 | train |
amzn/ion-python | amazon/ion/reader_binary.py | _ordered_struct_start_handler | def _ordered_struct_start_handler(handler, ctx):
"""Handles the special case of ordered structs, specified by the type ID 0xD1.
This coroutine's only purpose is to ensure that the struct in question declares at least one field name/value pair,
as required by the spec.
"""
_, self = yield
self_h... | python | def _ordered_struct_start_handler(handler, ctx):
"""Handles the special case of ordered structs, specified by the type ID 0xD1.
This coroutine's only purpose is to ensure that the struct in question declares at least one field name/value pair,
as required by the spec.
"""
_, self = yield
self_h... | [
"def",
"_ordered_struct_start_handler",
"(",
"handler",
",",
"ctx",
")",
":",
"_",
",",
"self",
"=",
"yield",
"self_handler",
"=",
"_create_delegate_handler",
"(",
"self",
")",
"(",
"length",
",",
"_",
")",
",",
"_",
"=",
"yield",
"ctx",
".",
"immediate_tr... | Handles the special case of ordered structs, specified by the type ID 0xD1.
This coroutine's only purpose is to ensure that the struct in question declares at least one field name/value pair,
as required by the spec. | [
"Handles",
"the",
"special",
"case",
"of",
"ordered",
"structs",
"specified",
"by",
"the",
"type",
"ID",
"0xD1",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader_binary.py#L530-L544 | train |
amzn/ion-python | amazon/ion/reader_binary.py | _container_start_handler | def _container_start_handler(ion_type, length, ctx):
"""Handles container delegation."""
_, self = yield
container_ctx = ctx.derive_container_context(length)
if ctx.annotations and ctx.limit != container_ctx.limit:
# 'ctx' is the annotation wrapper context. `container_ctx` represents the wrappe... | python | def _container_start_handler(ion_type, length, ctx):
"""Handles container delegation."""
_, self = yield
container_ctx = ctx.derive_container_context(length)
if ctx.annotations and ctx.limit != container_ctx.limit:
# 'ctx' is the annotation wrapper context. `container_ctx` represents the wrappe... | [
"def",
"_container_start_handler",
"(",
"ion_type",
",",
"length",
",",
"ctx",
")",
":",
"_",
",",
"self",
"=",
"yield",
"container_ctx",
"=",
"ctx",
".",
"derive_container_context",
"(",
"length",
")",
"if",
"ctx",
".",
"annotations",
"and",
"ctx",
".",
"... | Handles container delegation. | [
"Handles",
"container",
"delegation",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader_binary.py#L548-L562 | train |
amzn/ion-python | amazon/ion/reader_binary.py | _bind_length_handlers | def _bind_length_handlers(tids, user_handler, lns):
"""Binds a set of handlers with the given factory.
Args:
tids (Sequence[int]): The Type IDs to bind to.
user_handler (Callable): A function that takes as its parameters
:class:`IonType`, ``length``, and the ``ctx`` context
... | python | def _bind_length_handlers(tids, user_handler, lns):
"""Binds a set of handlers with the given factory.
Args:
tids (Sequence[int]): The Type IDs to bind to.
user_handler (Callable): A function that takes as its parameters
:class:`IonType`, ``length``, and the ``ctx`` context
... | [
"def",
"_bind_length_handlers",
"(",
"tids",
",",
"user_handler",
",",
"lns",
")",
":",
"for",
"tid",
"in",
"tids",
":",
"for",
"ln",
"in",
"lns",
":",
"type_octet",
"=",
"_gen_type_octet",
"(",
"tid",
",",
"ln",
")",
"ion_type",
"=",
"_TID_VALUE_TYPE_TABL... | Binds a set of handlers with the given factory.
Args:
tids (Sequence[int]): The Type IDs to bind to.
user_handler (Callable): A function that takes as its parameters
:class:`IonType`, ``length``, and the ``ctx`` context
returning a co-routine.
lns (Sequence[int]): Th... | [
"Binds",
"a",
"set",
"of",
"handlers",
"with",
"the",
"given",
"factory",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader_binary.py#L777-L799 | train |
amzn/ion-python | amazon/ion/reader_binary.py | _bind_length_scalar_handlers | def _bind_length_scalar_handlers(tids, scalar_factory, lns=_NON_ZERO_LENGTH_LNS):
"""Binds a set of scalar handlers for an inclusive range of low-nibble values.
Args:
tids (Sequence[int]): The Type IDs to bind to.
scalar_factory (Callable): The factory for the scalar parsing function.
... | python | def _bind_length_scalar_handlers(tids, scalar_factory, lns=_NON_ZERO_LENGTH_LNS):
"""Binds a set of scalar handlers for an inclusive range of low-nibble values.
Args:
tids (Sequence[int]): The Type IDs to bind to.
scalar_factory (Callable): The factory for the scalar parsing function.
... | [
"def",
"_bind_length_scalar_handlers",
"(",
"tids",
",",
"scalar_factory",
",",
"lns",
"=",
"_NON_ZERO_LENGTH_LNS",
")",
":",
"handler",
"=",
"partial",
"(",
"_length_scalar_handler",
",",
"scalar_factory",
")",
"return",
"_bind_length_handlers",
"(",
"tids",
",",
"... | Binds a set of scalar handlers for an inclusive range of low-nibble values.
Args:
tids (Sequence[int]): The Type IDs to bind to.
scalar_factory (Callable): The factory for the scalar parsing function.
This function can itself return a function representing a thunk to defer the
... | [
"Binds",
"a",
"set",
"of",
"scalar",
"handlers",
"for",
"an",
"inclusive",
"range",
"of",
"low",
"-",
"nibble",
"values",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader_binary.py#L802-L813 | train |
amzn/ion-python | amazon/ion/reader_binary.py | _HandlerContext.remaining | def remaining(self):
"""Determines how many bytes are remaining in the current context."""
if self.depth == 0:
return _STREAM_REMAINING
return self.limit - self.queue.position | python | def remaining(self):
"""Determines how many bytes are remaining in the current context."""
if self.depth == 0:
return _STREAM_REMAINING
return self.limit - self.queue.position | [
"def",
"remaining",
"(",
"self",
")",
":",
"if",
"self",
".",
"depth",
"==",
"0",
":",
"return",
"_STREAM_REMAINING",
"return",
"self",
".",
"limit",
"-",
"self",
".",
"queue",
".",
"position"
] | Determines how many bytes are remaining in the current context. | [
"Determines",
"how",
"many",
"bytes",
"are",
"remaining",
"in",
"the",
"current",
"context",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader_binary.py#L229-L233 | train |
amzn/ion-python | amazon/ion/reader_binary.py | _HandlerContext.read_data_transition | def read_data_transition(self, length, whence=None,
skip=False, stream_event=ION_STREAM_INCOMPLETE_EVENT):
"""Returns an immediate event_transition to read a specified number of bytes."""
if whence is None:
whence = self.whence
return Transition(
... | python | def read_data_transition(self, length, whence=None,
skip=False, stream_event=ION_STREAM_INCOMPLETE_EVENT):
"""Returns an immediate event_transition to read a specified number of bytes."""
if whence is None:
whence = self.whence
return Transition(
... | [
"def",
"read_data_transition",
"(",
"self",
",",
"length",
",",
"whence",
"=",
"None",
",",
"skip",
"=",
"False",
",",
"stream_event",
"=",
"ION_STREAM_INCOMPLETE_EVENT",
")",
":",
"if",
"whence",
"is",
"None",
":",
"whence",
"=",
"self",
".",
"whence",
"r... | Returns an immediate event_transition to read a specified number of bytes. | [
"Returns",
"an",
"immediate",
"event_transition",
"to",
"read",
"a",
"specified",
"number",
"of",
"bytes",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader_binary.py#L235-L243 | train |
amzn/ion-python | amazon/ion/reader.py | _narrow_unichr | def _narrow_unichr(code_point):
"""Retrieves the unicode character representing any given code point, in a way that won't break on narrow builds.
This is necessary because the built-in unichr function will fail for ordinals above 0xFFFF on narrow builds (UCS2);
ordinals above 0xFFFF would require recalcula... | python | def _narrow_unichr(code_point):
"""Retrieves the unicode character representing any given code point, in a way that won't break on narrow builds.
This is necessary because the built-in unichr function will fail for ordinals above 0xFFFF on narrow builds (UCS2);
ordinals above 0xFFFF would require recalcula... | [
"def",
"_narrow_unichr",
"(",
"code_point",
")",
":",
"try",
":",
"if",
"len",
"(",
"code_point",
".",
"char",
")",
">",
"1",
":",
"return",
"code_point",
".",
"char",
"except",
"AttributeError",
":",
"pass",
"return",
"six",
".",
"unichr",
"(",
"code_po... | Retrieves the unicode character representing any given code point, in a way that won't break on narrow builds.
This is necessary because the built-in unichr function will fail for ordinals above 0xFFFF on narrow builds (UCS2);
ordinals above 0xFFFF would require recalculating and combining surrogate pairs. Thi... | [
"Retrieves",
"the",
"unicode",
"character",
"representing",
"any",
"given",
"code",
"point",
"in",
"a",
"way",
"that",
"won",
"t",
"break",
"on",
"narrow",
"builds",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader.py#L43-L59 | train |
amzn/ion-python | amazon/ion/reader.py | reader_trampoline | def reader_trampoline(start, allow_flush=False):
"""Provides the co-routine trampoline for a reader state machine.
The given co-routine is a state machine that yields :class:`Transition` and takes
a Transition of :class:`amazon.ion.core.DataEvent` and the co-routine itself.
A reader must start with a ... | python | def reader_trampoline(start, allow_flush=False):
"""Provides the co-routine trampoline for a reader state machine.
The given co-routine is a state machine that yields :class:`Transition` and takes
a Transition of :class:`amazon.ion.core.DataEvent` and the co-routine itself.
A reader must start with a ... | [
"def",
"reader_trampoline",
"(",
"start",
",",
"allow_flush",
"=",
"False",
")",
":",
"data_event",
"=",
"yield",
"if",
"data_event",
"is",
"None",
"or",
"data_event",
".",
"type",
"is",
"not",
"ReadEventType",
".",
"NEXT",
":",
"raise",
"TypeError",
"(",
... | Provides the co-routine trampoline for a reader state machine.
The given co-routine is a state machine that yields :class:`Transition` and takes
a Transition of :class:`amazon.ion.core.DataEvent` and the co-routine itself.
A reader must start with a ``ReadEventType.NEXT`` event to prime the parser. In ma... | [
"Provides",
"the",
"co",
"-",
"routine",
"trampoline",
"for",
"a",
"reader",
"state",
"machine",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader.py#L312-L369 | train |
amzn/ion-python | amazon/ion/reader.py | blocking_reader | def blocking_reader(reader, input, buffer_size=_DEFAULT_BUFFER_SIZE):
"""Provides an implementation of using the reader co-routine with a file-like object.
Args:
reader(Coroutine): A reader co-routine.
input(BaseIO): The file-like object to read from.
buffer_size(Optional[int]): The opt... | python | def blocking_reader(reader, input, buffer_size=_DEFAULT_BUFFER_SIZE):
"""Provides an implementation of using the reader co-routine with a file-like object.
Args:
reader(Coroutine): A reader co-routine.
input(BaseIO): The file-like object to read from.
buffer_size(Optional[int]): The opt... | [
"def",
"blocking_reader",
"(",
"reader",
",",
"input",
",",
"buffer_size",
"=",
"_DEFAULT_BUFFER_SIZE",
")",
":",
"ion_event",
"=",
"None",
"while",
"True",
":",
"read_event",
"=",
"(",
"yield",
"ion_event",
")",
"ion_event",
"=",
"reader",
".",
"send",
"(",... | Provides an implementation of using the reader co-routine with a file-like object.
Args:
reader(Coroutine): A reader co-routine.
input(BaseIO): The file-like object to read from.
buffer_size(Optional[int]): The optional buffer size to use. | [
"Provides",
"an",
"implementation",
"of",
"using",
"the",
"reader",
"co",
"-",
"routine",
"with",
"a",
"file",
"-",
"like",
"object",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader.py#L376-L398 | train |
amzn/ion-python | amazon/ion/reader.py | BufferQueue.read | def read(self, length, skip=False):
"""Consumes the first ``length`` bytes from the accumulator."""
if length > self.__size:
raise IndexError(
'Cannot pop %d bytes, %d bytes in buffer queue' % (length, self.__size))
self.position += length
self.__size -= lengt... | python | def read(self, length, skip=False):
"""Consumes the first ``length`` bytes from the accumulator."""
if length > self.__size:
raise IndexError(
'Cannot pop %d bytes, %d bytes in buffer queue' % (length, self.__size))
self.position += length
self.__size -= lengt... | [
"def",
"read",
"(",
"self",
",",
"length",
",",
"skip",
"=",
"False",
")",
":",
"if",
"length",
">",
"self",
".",
"__size",
":",
"raise",
"IndexError",
"(",
"'Cannot pop %d bytes, %d bytes in buffer queue'",
"%",
"(",
"length",
",",
"self",
".",
"__size",
... | Consumes the first ``length`` bytes from the accumulator. | [
"Consumes",
"the",
"first",
"length",
"bytes",
"from",
"the",
"accumulator",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader.py#L154-L199 | train |
amzn/ion-python | amazon/ion/reader.py | BufferQueue.unread | def unread(self, c):
"""Unread the given character, byte, or code point.
If this is a unicode buffer and the input is an int or byte, it will be interpreted as an ordinal representing
a unicode code point.
If this is a binary buffer, the input must be a byte or int; a unicode character... | python | def unread(self, c):
"""Unread the given character, byte, or code point.
If this is a unicode buffer and the input is an int or byte, it will be interpreted as an ordinal representing
a unicode code point.
If this is a binary buffer, the input must be a byte or int; a unicode character... | [
"def",
"unread",
"(",
"self",
",",
"c",
")",
":",
"if",
"self",
".",
"position",
"<",
"1",
":",
"raise",
"IndexError",
"(",
"'Cannot unread an empty buffer queue.'",
")",
"if",
"isinstance",
"(",
"c",
",",
"six",
".",
"text_type",
")",
":",
"if",
"not",
... | Unread the given character, byte, or code point.
If this is a unicode buffer and the input is an int or byte, it will be interpreted as an ordinal representing
a unicode code point.
If this is a binary buffer, the input must be a byte or int; a unicode character will raise an error. | [
"Unread",
"the",
"given",
"character",
"byte",
"or",
"code",
"point",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader.py#L221-L259 | train |
amzn/ion-python | amazon/ion/reader.py | BufferQueue.skip | def skip(self, length):
"""Removes ``length`` bytes and returns the number length still required to skip"""
if length >= self.__size:
skip_amount = self.__size
rem = length - skip_amount
self.__segments.clear()
self.__offset = 0
self.__size = 0... | python | def skip(self, length):
"""Removes ``length`` bytes and returns the number length still required to skip"""
if length >= self.__size:
skip_amount = self.__size
rem = length - skip_amount
self.__segments.clear()
self.__offset = 0
self.__size = 0... | [
"def",
"skip",
"(",
"self",
",",
"length",
")",
":",
"if",
"length",
">=",
"self",
".",
"__size",
":",
"skip_amount",
"=",
"self",
".",
"__size",
"rem",
"=",
"length",
"-",
"skip_amount",
"self",
".",
"__segments",
".",
"clear",
"(",
")",
"self",
"."... | Removes ``length`` bytes and returns the number length still required to skip | [
"Removes",
"length",
"bytes",
"and",
"returns",
"the",
"number",
"length",
"still",
"required",
"to",
"skip"
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader.py#L261-L273 | train |
amzn/ion-python | amazon/ion/reader_managed.py | managed_reader | def managed_reader(reader, catalog=None):
"""Managed reader wrapping another reader.
Args:
reader (Coroutine): The underlying non-blocking reader co-routine.
catalog (Optional[SymbolTableCatalog]): The catalog to use for resolving imports.
Yields:
Events from the underlying reader ... | python | def managed_reader(reader, catalog=None):
"""Managed reader wrapping another reader.
Args:
reader (Coroutine): The underlying non-blocking reader co-routine.
catalog (Optional[SymbolTableCatalog]): The catalog to use for resolving imports.
Yields:
Events from the underlying reader ... | [
"def",
"managed_reader",
"(",
"reader",
",",
"catalog",
"=",
"None",
")",
":",
"if",
"catalog",
"is",
"None",
":",
"catalog",
"=",
"SymbolTableCatalog",
"(",
")",
"ctx",
"=",
"_ManagedContext",
"(",
"catalog",
")",
"symbol_trans",
"=",
"Transition",
"(",
"... | Managed reader wrapping another reader.
Args:
reader (Coroutine): The underlying non-blocking reader co-routine.
catalog (Optional[SymbolTableCatalog]): The catalog to use for resolving imports.
Yields:
Events from the underlying reader delegating to symbol table processing as needed.
... | [
"Managed",
"reader",
"wrapping",
"another",
"reader",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader_managed.py#L261-L335 | train |
amzn/ion-python | amazon/ion/reader_text.py | _illegal_character | def _illegal_character(c, ctx, message=''):
"""Raises an IonException upon encountering the given illegal character in the given context.
Args:
c (int|None): Ordinal of the illegal character.
ctx (_HandlerContext): Context in which the illegal character was encountered.
message (Option... | python | def _illegal_character(c, ctx, message=''):
"""Raises an IonException upon encountering the given illegal character in the given context.
Args:
c (int|None): Ordinal of the illegal character.
ctx (_HandlerContext): Context in which the illegal character was encountered.
message (Option... | [
"def",
"_illegal_character",
"(",
"c",
",",
"ctx",
",",
"message",
"=",
"''",
")",
":",
"container_type",
"=",
"ctx",
".",
"container",
".",
"ion_type",
"is",
"None",
"and",
"'top-level'",
"or",
"ctx",
".",
"container",
".",
"ion_type",
".",
"name",
"val... | Raises an IonException upon encountering the given illegal character in the given context.
Args:
c (int|None): Ordinal of the illegal character.
ctx (_HandlerContext): Context in which the illegal character was encountered.
message (Optional[str]): Additional information, as necessary. | [
"Raises",
"an",
"IonException",
"upon",
"encountering",
"the",
"given",
"illegal",
"character",
"in",
"the",
"given",
"context",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader_text.py#L40-L57 | train |
amzn/ion-python | amazon/ion/reader_text.py | _defaultdict | def _defaultdict(dct, fallback=_illegal_character):
"""Wraps the given dictionary such that the given fallback function will be called when a nonexistent key is
accessed.
"""
out = defaultdict(lambda: fallback)
for k, v in six.iteritems(dct):
out[k] = v
return out | python | def _defaultdict(dct, fallback=_illegal_character):
"""Wraps the given dictionary such that the given fallback function will be called when a nonexistent key is
accessed.
"""
out = defaultdict(lambda: fallback)
for k, v in six.iteritems(dct):
out[k] = v
return out | [
"def",
"_defaultdict",
"(",
"dct",
",",
"fallback",
"=",
"_illegal_character",
")",
":",
"out",
"=",
"defaultdict",
"(",
"lambda",
":",
"fallback",
")",
"for",
"k",
",",
"v",
"in",
"six",
".",
"iteritems",
"(",
"dct",
")",
":",
"out",
"[",
"k",
"]",
... | Wraps the given dictionary such that the given fallback function will be called when a nonexistent key is
accessed. | [
"Wraps",
"the",
"given",
"dictionary",
"such",
"that",
"the",
"given",
"fallback",
"function",
"will",
"be",
"called",
"when",
"a",
"nonexistent",
"key",
"is",
"accessed",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader_text.py#L60-L67 | train |
amzn/ion-python | amazon/ion/reader_text.py | _number_negative_start_handler | def _number_negative_start_handler(c, ctx):
"""Handles numeric values that start with a negative sign. Branches to delegate co-routines according to
_NEGATIVE_TABLE.
"""
assert c == _MINUS
assert len(ctx.value) == 0
ctx.set_ion_type(IonType.INT)
ctx.value.append(c)
c, _ = yield
yield... | python | def _number_negative_start_handler(c, ctx):
"""Handles numeric values that start with a negative sign. Branches to delegate co-routines according to
_NEGATIVE_TABLE.
"""
assert c == _MINUS
assert len(ctx.value) == 0
ctx.set_ion_type(IonType.INT)
ctx.value.append(c)
c, _ = yield
yield... | [
"def",
"_number_negative_start_handler",
"(",
"c",
",",
"ctx",
")",
":",
"assert",
"c",
"==",
"_MINUS",
"assert",
"len",
"(",
"ctx",
".",
"value",
")",
"==",
"0",
"ctx",
".",
"set_ion_type",
"(",
"IonType",
".",
"INT",
")",
"ctx",
".",
"value",
".",
... | Handles numeric values that start with a negative sign. Branches to delegate co-routines according to
_NEGATIVE_TABLE. | [
"Handles",
"numeric",
"values",
"that",
"start",
"with",
"a",
"negative",
"sign",
".",
"Branches",
"to",
"delegate",
"co",
"-",
"routines",
"according",
"to",
"_NEGATIVE_TABLE",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader_text.py#L585-L594 | train |
amzn/ion-python | amazon/ion/reader_text.py | _number_zero_start_handler | def _number_zero_start_handler(c, ctx):
"""Handles numeric values that start with zero or negative zero. Branches to delegate co-routines according to
_ZERO_START_TABLE.
"""
assert c == _ZERO
assert len(ctx.value) == 0 or (len(ctx.value) == 1 and ctx.value[0] == _MINUS)
ctx.set_ion_type(IonType.... | python | def _number_zero_start_handler(c, ctx):
"""Handles numeric values that start with zero or negative zero. Branches to delegate co-routines according to
_ZERO_START_TABLE.
"""
assert c == _ZERO
assert len(ctx.value) == 0 or (len(ctx.value) == 1 and ctx.value[0] == _MINUS)
ctx.set_ion_type(IonType.... | [
"def",
"_number_zero_start_handler",
"(",
"c",
",",
"ctx",
")",
":",
"assert",
"c",
"==",
"_ZERO",
"assert",
"len",
"(",
"ctx",
".",
"value",
")",
"==",
"0",
"or",
"(",
"len",
"(",
"ctx",
".",
"value",
")",
"==",
"1",
"and",
"ctx",
".",
"value",
... | Handles numeric values that start with zero or negative zero. Branches to delegate co-routines according to
_ZERO_START_TABLE. | [
"Handles",
"numeric",
"values",
"that",
"start",
"with",
"zero",
"or",
"negative",
"zero",
".",
"Branches",
"to",
"delegate",
"co",
"-",
"routines",
"according",
"to",
"_ZERO_START_TABLE",
"."
] | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader_text.py#L598-L612 | train |
amzn/ion-python | amazon/ion/reader_text.py | _number_or_timestamp_handler | def _number_or_timestamp_handler(c, ctx):
"""Handles numeric values that start with digits 1-9. May terminate a value, in which case that value is an
int. If it does not terminate a value, it branches to delegate co-routines according to _NUMBER_OR_TIMESTAMP_TABLE.
"""
assert c in _DIGITS
ctx.set_io... | python | def _number_or_timestamp_handler(c, ctx):
"""Handles numeric values that start with digits 1-9. May terminate a value, in which case that value is an
int. If it does not terminate a value, it branches to delegate co-routines according to _NUMBER_OR_TIMESTAMP_TABLE.
"""
assert c in _DIGITS
ctx.set_io... | [
"def",
"_number_or_timestamp_handler",
"(",
"c",
",",
"ctx",
")",
":",
"assert",
"c",
"in",
"_DIGITS",
"ctx",
".",
"set_ion_type",
"(",
"IonType",
".",
"INT",
")",
"val",
"=",
"ctx",
".",
"value",
"val",
".",
"append",
"(",
"c",
")",
"c",
",",
"self"... | Handles numeric values that start with digits 1-9. May terminate a value, in which case that value is an
int. If it does not terminate a value, it branches to delegate co-routines according to _NUMBER_OR_TIMESTAMP_TABLE. | [
"Handles",
"numeric",
"values",
"that",
"start",
"with",
"digits",
"1",
"-",
"9",
".",
"May",
"terminate",
"a",
"value",
"in",
"which",
"case",
"that",
"value",
"is",
"an",
"int",
".",
"If",
"it",
"does",
"not",
"terminate",
"a",
"value",
"it",
"branch... | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader_text.py#L616-L637 | train |
amzn/ion-python | amazon/ion/reader_text.py | _number_slash_end_handler | def _number_slash_end_handler(c, ctx, event):
"""Handles numeric values that end in a forward slash. This is only legal if the slash begins a comment; thus,
this co-routine either results in an error being raised or an event being yielded.
"""
assert c == _SLASH
c, self = yield
next_ctx = ctx.de... | python | def _number_slash_end_handler(c, ctx, event):
"""Handles numeric values that end in a forward slash. This is only legal if the slash begins a comment; thus,
this co-routine either results in an error being raised or an event being yielded.
"""
assert c == _SLASH
c, self = yield
next_ctx = ctx.de... | [
"def",
"_number_slash_end_handler",
"(",
"c",
",",
"ctx",
",",
"event",
")",
":",
"assert",
"c",
"==",
"_SLASH",
"c",
",",
"self",
"=",
"yield",
"next_ctx",
"=",
"ctx",
".",
"derive_child_context",
"(",
"ctx",
".",
"whence",
")",
"comment",
"=",
"_commen... | Handles numeric values that end in a forward slash. This is only legal if the slash begins a comment; thus,
this co-routine either results in an error being raised or an event being yielded. | [
"Handles",
"numeric",
"values",
"that",
"end",
"in",
"a",
"forward",
"slash",
".",
"This",
"is",
"only",
"legal",
"if",
"the",
"slash",
"begins",
"a",
"comment",
";",
"thus",
"this",
"co",
"-",
"routine",
"either",
"results",
"in",
"an",
"error",
"being"... | 0b21fa3ba7755f55f745e4aa970d86343b82449d | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader_text.py#L641-L651 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.