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
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
SheffieldML/GPyOpt
GPyOpt/acquisitions/EI.py
AcquisitionEI._compute_acq
def _compute_acq(self, x): """ Computes the Expected Improvement per unit of cost """ m, s = self.model.predict(x) fmin = self.model.get_fmin() phi, Phi, u = get_quantiles(self.jitter, fmin, m, s) f_acqu = s * (u * Phi + phi) return f_acqu
python
def _compute_acq(self, x): """ Computes the Expected Improvement per unit of cost """ m, s = self.model.predict(x) fmin = self.model.get_fmin() phi, Phi, u = get_quantiles(self.jitter, fmin, m, s) f_acqu = s * (u * Phi + phi) return f_acqu
[ "def", "_compute_acq", "(", "self", ",", "x", ")", ":", "m", ",", "s", "=", "self", ".", "model", ".", "predict", "(", "x", ")", "fmin", "=", "self", ".", "model", ".", "get_fmin", "(", ")", "phi", ",", "Phi", ",", "u", "=", "get_quantiles", "(...
Computes the Expected Improvement per unit of cost
[ "Computes", "the", "Expected", "Improvement", "per", "unit", "of", "cost" ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/acquisitions/EI.py#L32-L40
train
223,100
SheffieldML/GPyOpt
GPyOpt/interface/config_parser.py
update_config
def update_config(config_new, config_default): ''' Updates the loaded method configuration with default values. ''' if any([isinstance(v, dict) for v in list(config_new.values())]): for k,v in list(config_new.items()): if isinstance(v,dict) and k in config_default: update_config(config_new[k],config_default[k]) else: config_default[k] = v else: config_default.update(config_new) return config_default
python
def update_config(config_new, config_default): ''' Updates the loaded method configuration with default values. ''' if any([isinstance(v, dict) for v in list(config_new.values())]): for k,v in list(config_new.items()): if isinstance(v,dict) and k in config_default: update_config(config_new[k],config_default[k]) else: config_default[k] = v else: config_default.update(config_new) return config_default
[ "def", "update_config", "(", "config_new", ",", "config_default", ")", ":", "if", "any", "(", "[", "isinstance", "(", "v", ",", "dict", ")", "for", "v", "in", "list", "(", "config_new", ".", "values", "(", ")", ")", "]", ")", ":", "for", "k", ",", ...
Updates the loaded method configuration with default values.
[ "Updates", "the", "loaded", "method", "configuration", "with", "default", "values", "." ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/interface/config_parser.py#L62-L75
train
223,101
SheffieldML/GPyOpt
GPyOpt/interface/config_parser.py
parser
def parser(input_file_path='config.json'): ''' Parser for the .json file containing the configuration of the method. ''' # --- Read .json file try: with open(input_file_path, 'r') as config_file: config_new = json.load(config_file) config_file.close() except: raise Exception('Config file "'+input_file_path+'" not loaded properly. Please check it an try again.') import copy options = update_config(config_new, copy.deepcopy(default_config)) return options
python
def parser(input_file_path='config.json'): ''' Parser for the .json file containing the configuration of the method. ''' # --- Read .json file try: with open(input_file_path, 'r') as config_file: config_new = json.load(config_file) config_file.close() except: raise Exception('Config file "'+input_file_path+'" not loaded properly. Please check it an try again.') import copy options = update_config(config_new, copy.deepcopy(default_config)) return options
[ "def", "parser", "(", "input_file_path", "=", "'config.json'", ")", ":", "# --- Read .json file", "try", ":", "with", "open", "(", "input_file_path", ",", "'r'", ")", "as", "config_file", ":", "config_new", "=", "json", ".", "load", "(", "config_file", ")", ...
Parser for the .json file containing the configuration of the method.
[ "Parser", "for", "the", ".", "json", "file", "containing", "the", "configuration", "of", "the", "method", "." ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/interface/config_parser.py#L78-L94
train
223,102
SheffieldML/GPyOpt
GPyOpt/util/mcmc_sampler.py
AffineInvariantEnsembleSampler.get_samples
def get_samples(self, n_samples, log_p_function, burn_in_steps=50): """ Generates samples. Parameters: n_samples - number of samples to generate log_p_function - a function that returns log density for a specific sample burn_in_steps - number of burn-in steps for sampling Returns a tuple of two array: (samples, log_p_function values for samples) """ restarts = initial_design('random', self.space, n_samples) sampler = emcee.EnsembleSampler(n_samples, self.space.input_dim(), log_p_function) samples, samples_log, _ = sampler.run_mcmc(restarts, burn_in_steps) # make sure we have an array of shape (n samples, space input dim) if len(samples.shape) == 1: samples = samples.reshape(-1, 1) samples_log = samples_log.reshape(-1, 1) return samples, samples_log
python
def get_samples(self, n_samples, log_p_function, burn_in_steps=50): """ Generates samples. Parameters: n_samples - number of samples to generate log_p_function - a function that returns log density for a specific sample burn_in_steps - number of burn-in steps for sampling Returns a tuple of two array: (samples, log_p_function values for samples) """ restarts = initial_design('random', self.space, n_samples) sampler = emcee.EnsembleSampler(n_samples, self.space.input_dim(), log_p_function) samples, samples_log, _ = sampler.run_mcmc(restarts, burn_in_steps) # make sure we have an array of shape (n samples, space input dim) if len(samples.shape) == 1: samples = samples.reshape(-1, 1) samples_log = samples_log.reshape(-1, 1) return samples, samples_log
[ "def", "get_samples", "(", "self", ",", "n_samples", ",", "log_p_function", ",", "burn_in_steps", "=", "50", ")", ":", "restarts", "=", "initial_design", "(", "'random'", ",", "self", ".", "space", ",", "n_samples", ")", "sampler", "=", "emcee", ".", "Ense...
Generates samples. Parameters: n_samples - number of samples to generate log_p_function - a function that returns log density for a specific sample burn_in_steps - number of burn-in steps for sampling Returns a tuple of two array: (samples, log_p_function values for samples)
[ "Generates", "samples", "." ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/util/mcmc_sampler.py#L39-L59
train
223,103
SheffieldML/GPyOpt
GPyOpt/core/bo.py
BO.suggest_next_locations
def suggest_next_locations(self, context = None, pending_X = None, ignored_X = None): """ Run a single optimization step and return the next locations to evaluate the objective. Number of suggested locations equals to batch_size. :param context: fixes specified variables to a particular context (values) for the optimization run (default, None). :param pending_X: matrix of input configurations that are in a pending state (i.e., do not have an evaluation yet) (default, None). :param ignored_X: matrix of input configurations that the user black-lists, i.e., those configurations will not be suggested again (default, None). """ self.model_parameters_iterations = None self.num_acquisitions = 0 self.context = context self._update_model(self.normalization_type) suggested_locations = self._compute_next_evaluations(pending_zipped_X = pending_X, ignored_zipped_X = ignored_X) return suggested_locations
python
def suggest_next_locations(self, context = None, pending_X = None, ignored_X = None): """ Run a single optimization step and return the next locations to evaluate the objective. Number of suggested locations equals to batch_size. :param context: fixes specified variables to a particular context (values) for the optimization run (default, None). :param pending_X: matrix of input configurations that are in a pending state (i.e., do not have an evaluation yet) (default, None). :param ignored_X: matrix of input configurations that the user black-lists, i.e., those configurations will not be suggested again (default, None). """ self.model_parameters_iterations = None self.num_acquisitions = 0 self.context = context self._update_model(self.normalization_type) suggested_locations = self._compute_next_evaluations(pending_zipped_X = pending_X, ignored_zipped_X = ignored_X) return suggested_locations
[ "def", "suggest_next_locations", "(", "self", ",", "context", "=", "None", ",", "pending_X", "=", "None", ",", "ignored_X", "=", "None", ")", ":", "self", ".", "model_parameters_iterations", "=", "None", "self", ".", "num_acquisitions", "=", "0", "self", "."...
Run a single optimization step and return the next locations to evaluate the objective. Number of suggested locations equals to batch_size. :param context: fixes specified variables to a particular context (values) for the optimization run (default, None). :param pending_X: matrix of input configurations that are in a pending state (i.e., do not have an evaluation yet) (default, None). :param ignored_X: matrix of input configurations that the user black-lists, i.e., those configurations will not be suggested again (default, None).
[ "Run", "a", "single", "optimization", "step", "and", "return", "the", "next", "locations", "to", "evaluate", "the", "objective", ".", "Number", "of", "suggested", "locations", "equals", "to", "batch_size", "." ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/core/bo.py#L55-L71
train
223,104
SheffieldML/GPyOpt
GPyOpt/core/bo.py
BO._print_convergence
def _print_convergence(self): """ Prints the reason why the optimization stopped. """ if self.verbosity: if (self.num_acquisitions == self.max_iter) and (not self.initial_iter): print(' ** Maximum number of iterations reached **') return 1 elif (self._distance_last_evaluations() < self.eps) and (not self.initial_iter): print(' ** Two equal location selected **') return 1 elif (self.max_time < self.cum_time) and not (self.initial_iter): print(' ** Evaluation time reached **') return 0 if self.initial_iter: print('** GPyOpt Bayesian Optimization class initialized successfully **') self.initial_iter = False
python
def _print_convergence(self): """ Prints the reason why the optimization stopped. """ if self.verbosity: if (self.num_acquisitions == self.max_iter) and (not self.initial_iter): print(' ** Maximum number of iterations reached **') return 1 elif (self._distance_last_evaluations() < self.eps) and (not self.initial_iter): print(' ** Two equal location selected **') return 1 elif (self.max_time < self.cum_time) and not (self.initial_iter): print(' ** Evaluation time reached **') return 0 if self.initial_iter: print('** GPyOpt Bayesian Optimization class initialized successfully **') self.initial_iter = False
[ "def", "_print_convergence", "(", "self", ")", ":", "if", "self", ".", "verbosity", ":", "if", "(", "self", ".", "num_acquisitions", "==", "self", ".", "max_iter", ")", "and", "(", "not", "self", ".", "initial_iter", ")", ":", "print", "(", "' ** Maxim...
Prints the reason why the optimization stopped.
[ "Prints", "the", "reason", "why", "the", "optimization", "stopped", "." ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/core/bo.py#L172-L190
train
223,105
SheffieldML/GPyOpt
GPyOpt/core/bo.py
BO.evaluate_objective
def evaluate_objective(self): """ Evaluates the objective """ self.Y_new, cost_new = self.objective.evaluate(self.suggested_sample) self.cost.update_cost_model(self.suggested_sample, cost_new) self.Y = np.vstack((self.Y,self.Y_new))
python
def evaluate_objective(self): """ Evaluates the objective """ self.Y_new, cost_new = self.objective.evaluate(self.suggested_sample) self.cost.update_cost_model(self.suggested_sample, cost_new) self.Y = np.vstack((self.Y,self.Y_new))
[ "def", "evaluate_objective", "(", "self", ")", ":", "self", ".", "Y_new", ",", "cost_new", "=", "self", ".", "objective", ".", "evaluate", "(", "self", ".", "suggested_sample", ")", "self", ".", "cost", ".", "update_cost_model", "(", "self", ".", "suggeste...
Evaluates the objective
[ "Evaluates", "the", "objective" ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/core/bo.py#L193-L199
train
223,106
SheffieldML/GPyOpt
GPyOpt/core/bo.py
BO._compute_results
def _compute_results(self): """ Computes the optimum and its value. """ self.Y_best = best_value(self.Y) self.x_opt = self.X[np.argmin(self.Y),:] self.fx_opt = np.min(self.Y)
python
def _compute_results(self): """ Computes the optimum and its value. """ self.Y_best = best_value(self.Y) self.x_opt = self.X[np.argmin(self.Y),:] self.fx_opt = np.min(self.Y)
[ "def", "_compute_results", "(", "self", ")", ":", "self", ".", "Y_best", "=", "best_value", "(", "self", ".", "Y", ")", "self", ".", "x_opt", "=", "self", ".", "X", "[", "np", ".", "argmin", "(", "self", ".", "Y", ")", ",", ":", "]", "self", "....
Computes the optimum and its value.
[ "Computes", "the", "optimum", "and", "its", "value", "." ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/core/bo.py#L201-L207
train
223,107
SheffieldML/GPyOpt
GPyOpt/core/bo.py
BO._distance_last_evaluations
def _distance_last_evaluations(self): """ Computes the distance between the last two evaluations. """ if self.X.shape[0] < 2: # less than 2 evaluations return np.inf return np.sqrt(np.sum((self.X[-1, :] - self.X[-2, :]) ** 2))
python
def _distance_last_evaluations(self): """ Computes the distance between the last two evaluations. """ if self.X.shape[0] < 2: # less than 2 evaluations return np.inf return np.sqrt(np.sum((self.X[-1, :] - self.X[-2, :]) ** 2))
[ "def", "_distance_last_evaluations", "(", "self", ")", ":", "if", "self", ".", "X", ".", "shape", "[", "0", "]", "<", "2", ":", "# less than 2 evaluations", "return", "np", ".", "inf", "return", "np", ".", "sqrt", "(", "np", ".", "sum", "(", "(", "se...
Computes the distance between the last two evaluations.
[ "Computes", "the", "distance", "between", "the", "last", "two", "evaluations", "." ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/core/bo.py#L209-L216
train
223,108
SheffieldML/GPyOpt
GPyOpt/core/bo.py
BO.save_evaluations
def save_evaluations(self, evaluations_file = None): """ Saves evaluations at each iteration of the optimization :param evaluations_file: name of the file in which the results are saved. """ iterations = np.array(range(1, self.Y.shape[0] + 1))[:, None] results = np.hstack((iterations, self.Y, self.X)) header = ['Iteration', 'Y'] + ['var_' + str(k) for k in range(1, self.X.shape[1] + 1)] data = [header] + results.tolist() self._write_csv(evaluations_file, data)
python
def save_evaluations(self, evaluations_file = None): """ Saves evaluations at each iteration of the optimization :param evaluations_file: name of the file in which the results are saved. """ iterations = np.array(range(1, self.Y.shape[0] + 1))[:, None] results = np.hstack((iterations, self.Y, self.X)) header = ['Iteration', 'Y'] + ['var_' + str(k) for k in range(1, self.X.shape[1] + 1)] data = [header] + results.tolist() self._write_csv(evaluations_file, data)
[ "def", "save_evaluations", "(", "self", ",", "evaluations_file", "=", "None", ")", ":", "iterations", "=", "np", ".", "array", "(", "range", "(", "1", ",", "self", ".", "Y", ".", "shape", "[", "0", "]", "+", "1", ")", ")", "[", ":", ",", "None", ...
Saves evaluations at each iteration of the optimization :param evaluations_file: name of the file in which the results are saved.
[ "Saves", "evaluations", "at", "each", "iteration", "of", "the", "optimization" ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/core/bo.py#L367-L378
train
223,109
SheffieldML/GPyOpt
GPyOpt/core/bo.py
BO.save_models
def save_models(self, models_file): """ Saves model parameters at each iteration of the optimization :param models_file: name of the file or a file buffer, in which the results are saved. """ if self.model_parameters_iterations is None: raise ValueError("No iterations have been carried out yet and hence no iterations of the BO can be saved") iterations = np.array(range(1,self.model_parameters_iterations.shape[0]+1))[:,None] results = np.hstack((iterations,self.model_parameters_iterations)) header = ['Iteration'] + self.model.get_model_parameters_names() data = [header] + results.tolist() self._write_csv(models_file, data)
python
def save_models(self, models_file): """ Saves model parameters at each iteration of the optimization :param models_file: name of the file or a file buffer, in which the results are saved. """ if self.model_parameters_iterations is None: raise ValueError("No iterations have been carried out yet and hence no iterations of the BO can be saved") iterations = np.array(range(1,self.model_parameters_iterations.shape[0]+1))[:,None] results = np.hstack((iterations,self.model_parameters_iterations)) header = ['Iteration'] + self.model.get_model_parameters_names() data = [header] + results.tolist() self._write_csv(models_file, data)
[ "def", "save_models", "(", "self", ",", "models_file", ")", ":", "if", "self", ".", "model_parameters_iterations", "is", "None", ":", "raise", "ValueError", "(", "\"No iterations have been carried out yet and hence no iterations of the BO can be saved\"", ")", "iterations", ...
Saves model parameters at each iteration of the optimization :param models_file: name of the file or a file buffer, in which the results are saved.
[ "Saves", "model", "parameters", "at", "each", "iteration", "of", "the", "optimization" ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/core/bo.py#L380-L394
train
223,110
SheffieldML/GPyOpt
GPyOpt/methods/bayesian_optimization.py
BayesianOptimization._init_design_chooser
def _init_design_chooser(self): """ Initializes the choice of X and Y based on the selected initial design and number of points selected. """ # If objective function was not provided, we require some initial sample data if self.f is None and (self.X is None or self.Y is None): raise InvalidConfigError("Initial data for both X and Y is required when objective function is not provided") # Case 1: if self.X is None: self.X = initial_design(self.initial_design_type, self.space, self.initial_design_numdata) self.Y, _ = self.objective.evaluate(self.X) # Case 2 elif self.X is not None and self.Y is None: self.Y, _ = self.objective.evaluate(self.X)
python
def _init_design_chooser(self): """ Initializes the choice of X and Y based on the selected initial design and number of points selected. """ # If objective function was not provided, we require some initial sample data if self.f is None and (self.X is None or self.Y is None): raise InvalidConfigError("Initial data for both X and Y is required when objective function is not provided") # Case 1: if self.X is None: self.X = initial_design(self.initial_design_type, self.space, self.initial_design_numdata) self.Y, _ = self.objective.evaluate(self.X) # Case 2 elif self.X is not None and self.Y is None: self.Y, _ = self.objective.evaluate(self.X)
[ "def", "_init_design_chooser", "(", "self", ")", ":", "# If objective function was not provided, we require some initial sample data", "if", "self", ".", "f", "is", "None", "and", "(", "self", ".", "X", "is", "None", "or", "self", ".", "Y", "is", "None", ")", ":...
Initializes the choice of X and Y based on the selected initial design and number of points selected.
[ "Initializes", "the", "choice", "of", "X", "and", "Y", "based", "on", "the", "selected", "initial", "design", "and", "number", "of", "points", "selected", "." ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/methods/bayesian_optimization.py#L183-L198
train
223,111
coleifer/huey
huey/api.py
crontab
def crontab(minute='*', hour='*', day='*', month='*', day_of_week='*'): """ Convert a "crontab"-style set of parameters into a test function that will return True when the given datetime matches the parameters set forth in the crontab. For day-of-week, 0=Sunday and 6=Saturday. Acceptable inputs: * = every distinct value */n = run every "n" times, i.e. hours='*/4' == 0, 4, 8, 12, 16, 20 m-n = run every time m..n m,n = run on m and n """ validation = ( ('m', month, range(1, 13)), ('d', day, range(1, 32)), ('w', day_of_week, range(8)), # 0-6, but also 7 for Sunday. ('H', hour, range(24)), ('M', minute, range(60)) ) cron_settings = [] for (date_str, value, acceptable) in validation: settings = set([]) if isinstance(value, int): value = str(value) for piece in value.split(','): if piece == '*': settings.update(acceptable) continue if piece.isdigit(): piece = int(piece) if piece not in acceptable: raise ValueError('%d is not a valid input' % piece) elif date_str == 'w': piece %= 7 settings.add(piece) else: dash_match = dash_re.match(piece) if dash_match: lhs, rhs = map(int, dash_match.groups()) if lhs not in acceptable or rhs not in acceptable: raise ValueError('%s is not a valid input' % piece) elif date_str == 'w': lhs %= 7 rhs %= 7 settings.update(range(lhs, rhs + 1)) continue # Handle stuff like */3, */6. every_match = every_re.match(piece) if every_match: if date_str == 'w': raise ValueError('Cannot perform this kind of matching' ' on day-of-week.') interval = int(every_match.groups()[0]) settings.update(acceptable[::interval]) cron_settings.append(sorted(list(settings))) def validate_date(timestamp): _, m, d, H, M, _, w, _, _ = timestamp.timetuple() # fix the weekday to be sunday=0 w = (w + 1) % 7 for (date_piece, selection) in zip((m, d, w, H, M), cron_settings): if date_piece not in selection: return False return True return validate_date
python
def crontab(minute='*', hour='*', day='*', month='*', day_of_week='*'): """ Convert a "crontab"-style set of parameters into a test function that will return True when the given datetime matches the parameters set forth in the crontab. For day-of-week, 0=Sunday and 6=Saturday. Acceptable inputs: * = every distinct value */n = run every "n" times, i.e. hours='*/4' == 0, 4, 8, 12, 16, 20 m-n = run every time m..n m,n = run on m and n """ validation = ( ('m', month, range(1, 13)), ('d', day, range(1, 32)), ('w', day_of_week, range(8)), # 0-6, but also 7 for Sunday. ('H', hour, range(24)), ('M', minute, range(60)) ) cron_settings = [] for (date_str, value, acceptable) in validation: settings = set([]) if isinstance(value, int): value = str(value) for piece in value.split(','): if piece == '*': settings.update(acceptable) continue if piece.isdigit(): piece = int(piece) if piece not in acceptable: raise ValueError('%d is not a valid input' % piece) elif date_str == 'w': piece %= 7 settings.add(piece) else: dash_match = dash_re.match(piece) if dash_match: lhs, rhs = map(int, dash_match.groups()) if lhs not in acceptable or rhs not in acceptable: raise ValueError('%s is not a valid input' % piece) elif date_str == 'w': lhs %= 7 rhs %= 7 settings.update(range(lhs, rhs + 1)) continue # Handle stuff like */3, */6. every_match = every_re.match(piece) if every_match: if date_str == 'w': raise ValueError('Cannot perform this kind of matching' ' on day-of-week.') interval = int(every_match.groups()[0]) settings.update(acceptable[::interval]) cron_settings.append(sorted(list(settings))) def validate_date(timestamp): _, m, d, H, M, _, w, _, _ = timestamp.timetuple() # fix the weekday to be sunday=0 w = (w + 1) % 7 for (date_piece, selection) in zip((m, d, w, H, M), cron_settings): if date_piece not in selection: return False return True return validate_date
[ "def", "crontab", "(", "minute", "=", "'*'", ",", "hour", "=", "'*'", ",", "day", "=", "'*'", ",", "month", "=", "'*'", ",", "day_of_week", "=", "'*'", ")", ":", "validation", "=", "(", "(", "'m'", ",", "month", ",", "range", "(", "1", ",", "13...
Convert a "crontab"-style set of parameters into a test function that will return True when the given datetime matches the parameters set forth in the crontab. For day-of-week, 0=Sunday and 6=Saturday. Acceptable inputs: * = every distinct value */n = run every "n" times, i.e. hours='*/4' == 0, 4, 8, 12, 16, 20 m-n = run every time m..n m,n = run on m and n
[ "Convert", "a", "crontab", "-", "style", "set", "of", "parameters", "into", "a", "test", "function", "that", "will", "return", "True", "when", "the", "given", "datetime", "matches", "the", "parameters", "set", "forth", "in", "the", "crontab", "." ]
416e8da1ca18442c08431a91bce373de7d2d200f
https://github.com/coleifer/huey/blob/416e8da1ca18442c08431a91bce373de7d2d200f/huey/api.py#L913-L990
train
223,112
coleifer/huey
huey/storage.py
BaseStorage.put_if_empty
def put_if_empty(self, key, value): """ Atomically write data only if the key is not already set. :param bytes key: Key to check/set. :param bytes value: Arbitrary data. :return: Boolean whether key/value was set. """ if self.has_data_for_key(key): return False self.put_data(key, value) return True
python
def put_if_empty(self, key, value): """ Atomically write data only if the key is not already set. :param bytes key: Key to check/set. :param bytes value: Arbitrary data. :return: Boolean whether key/value was set. """ if self.has_data_for_key(key): return False self.put_data(key, value) return True
[ "def", "put_if_empty", "(", "self", ",", "key", ",", "value", ")", ":", "if", "self", ".", "has_data_for_key", "(", "key", ")", ":", "return", "False", "self", ".", "put_data", "(", "key", ",", "value", ")", "return", "True" ]
Atomically write data only if the key is not already set. :param bytes key: Key to check/set. :param bytes value: Arbitrary data. :return: Boolean whether key/value was set.
[ "Atomically", "write", "data", "only", "if", "the", "key", "is", "not", "already", "set", "." ]
416e8da1ca18442c08431a91bce373de7d2d200f
https://github.com/coleifer/huey/blob/416e8da1ca18442c08431a91bce373de7d2d200f/huey/storage.py#L190-L201
train
223,113
coleifer/huey
huey/utils.py
make_naive
def make_naive(dt): """ Makes an aware datetime.datetime naive in local time zone. """ tt = dt.utctimetuple() ts = calendar.timegm(tt) local_tt = time.localtime(ts) return datetime.datetime(*local_tt[:6])
python
def make_naive(dt): """ Makes an aware datetime.datetime naive in local time zone. """ tt = dt.utctimetuple() ts = calendar.timegm(tt) local_tt = time.localtime(ts) return datetime.datetime(*local_tt[:6])
[ "def", "make_naive", "(", "dt", ")", ":", "tt", "=", "dt", ".", "utctimetuple", "(", ")", "ts", "=", "calendar", ".", "timegm", "(", "tt", ")", "local_tt", "=", "time", ".", "localtime", "(", "ts", ")", "return", "datetime", ".", "datetime", "(", "...
Makes an aware datetime.datetime naive in local time zone.
[ "Makes", "an", "aware", "datetime", ".", "datetime", "naive", "in", "local", "time", "zone", "." ]
416e8da1ca18442c08431a91bce373de7d2d200f
https://github.com/coleifer/huey/blob/416e8da1ca18442c08431a91bce373de7d2d200f/huey/utils.py#L48-L55
train
223,114
coleifer/huey
huey/consumer.py
BaseProcess.sleep_for_interval
def sleep_for_interval(self, start_ts, nseconds): """ Sleep for a given interval with respect to the start timestamp. So, if the start timestamp is 1337 and nseconds is 10, the method will actually sleep for nseconds - (current_timestamp - start_timestamp). So if the current timestamp is 1340, we'll only sleep for 7 seconds (the goal being to sleep until 1347, or 1337 + 10). """ sleep_time = nseconds - (time.time() - start_ts) if sleep_time <= 0: return self._logger.debug('Sleeping for %s', sleep_time) # Recompute time to sleep to improve accuracy in case the process was # pre-empted by the kernel while logging. sleep_time = nseconds - (time.time() - start_ts) if sleep_time > 0: time.sleep(sleep_time)
python
def sleep_for_interval(self, start_ts, nseconds): """ Sleep for a given interval with respect to the start timestamp. So, if the start timestamp is 1337 and nseconds is 10, the method will actually sleep for nseconds - (current_timestamp - start_timestamp). So if the current timestamp is 1340, we'll only sleep for 7 seconds (the goal being to sleep until 1347, or 1337 + 10). """ sleep_time = nseconds - (time.time() - start_ts) if sleep_time <= 0: return self._logger.debug('Sleeping for %s', sleep_time) # Recompute time to sleep to improve accuracy in case the process was # pre-empted by the kernel while logging. sleep_time = nseconds - (time.time() - start_ts) if sleep_time > 0: time.sleep(sleep_time)
[ "def", "sleep_for_interval", "(", "self", ",", "start_ts", ",", "nseconds", ")", ":", "sleep_time", "=", "nseconds", "-", "(", "time", ".", "time", "(", ")", "-", "start_ts", ")", "if", "sleep_time", "<=", "0", ":", "return", "self", ".", "_logger", "....
Sleep for a given interval with respect to the start timestamp. So, if the start timestamp is 1337 and nseconds is 10, the method will actually sleep for nseconds - (current_timestamp - start_timestamp). So if the current timestamp is 1340, we'll only sleep for 7 seconds (the goal being to sleep until 1347, or 1337 + 10).
[ "Sleep", "for", "a", "given", "interval", "with", "respect", "to", "the", "start", "timestamp", "." ]
416e8da1ca18442c08431a91bce373de7d2d200f
https://github.com/coleifer/huey/blob/416e8da1ca18442c08431a91bce373de7d2d200f/huey/consumer.py#L39-L56
train
223,115
coleifer/huey
huey/consumer.py
Consumer.start
def start(self): """ Start all consumer processes and register signal handlers. """ if self.huey.immediate: raise ConfigurationError( 'Consumer cannot be run with Huey instances where immediate ' 'is enabled. Please check your configuration and ensure that ' '"huey.immediate = False".') # Log startup message. self._logger.info('Huey consumer started with %s %s, PID %s at %s', self.workers, self.worker_type, os.getpid(), self.huey._get_timestamp()) self._logger.info('Scheduler runs every %s second(s).', self.scheduler_interval) self._logger.info('Periodic tasks are %s.', 'enabled' if self.periodic else 'disabled') self._set_signal_handlers() msg = ['The following commands are available:'] for command in self.huey._registry._registry: msg.append('+ %s' % command) self._logger.info('\n'.join(msg)) # We'll temporarily ignore SIGINT and SIGHUP (so that it is inherited # by the child-processes). Once the child processes are created, we # restore the handler. original_sigint_handler = signal.signal(signal.SIGINT, signal.SIG_IGN) if hasattr(signal, 'SIGHUP'): original_sighup_handler = signal.signal(signal.SIGHUP, signal.SIG_IGN) self.scheduler.start() for _, worker_process in self.worker_threads: worker_process.start() signal.signal(signal.SIGINT, original_sigint_handler) if hasattr(signal, 'SIGHUP'): signal.signal(signal.SIGHUP, original_sighup_handler)
python
def start(self): """ Start all consumer processes and register signal handlers. """ if self.huey.immediate: raise ConfigurationError( 'Consumer cannot be run with Huey instances where immediate ' 'is enabled. Please check your configuration and ensure that ' '"huey.immediate = False".') # Log startup message. self._logger.info('Huey consumer started with %s %s, PID %s at %s', self.workers, self.worker_type, os.getpid(), self.huey._get_timestamp()) self._logger.info('Scheduler runs every %s second(s).', self.scheduler_interval) self._logger.info('Periodic tasks are %s.', 'enabled' if self.periodic else 'disabled') self._set_signal_handlers() msg = ['The following commands are available:'] for command in self.huey._registry._registry: msg.append('+ %s' % command) self._logger.info('\n'.join(msg)) # We'll temporarily ignore SIGINT and SIGHUP (so that it is inherited # by the child-processes). Once the child processes are created, we # restore the handler. original_sigint_handler = signal.signal(signal.SIGINT, signal.SIG_IGN) if hasattr(signal, 'SIGHUP'): original_sighup_handler = signal.signal(signal.SIGHUP, signal.SIG_IGN) self.scheduler.start() for _, worker_process in self.worker_threads: worker_process.start() signal.signal(signal.SIGINT, original_sigint_handler) if hasattr(signal, 'SIGHUP'): signal.signal(signal.SIGHUP, original_sighup_handler)
[ "def", "start", "(", "self", ")", ":", "if", "self", ".", "huey", ".", "immediate", ":", "raise", "ConfigurationError", "(", "'Consumer cannot be run with Huey instances where immediate '", "'is enabled. Please check your configuration and ensure that '", "'\"huey.immediate = Fal...
Start all consumer processes and register signal handlers.
[ "Start", "all", "consumer", "processes", "and", "register", "signal", "handlers", "." ]
416e8da1ca18442c08431a91bce373de7d2d200f
https://github.com/coleifer/huey/blob/416e8da1ca18442c08431a91bce373de7d2d200f/huey/consumer.py#L344-L383
train
223,116
coleifer/huey
huey/consumer.py
Consumer.stop
def stop(self, graceful=False): """ Set the stop-flag. If `graceful=True`, this method blocks until the workers to finish executing any tasks they might be currently working on. """ self.stop_flag.set() if graceful: self._logger.info('Shutting down gracefully...') try: for _, worker_process in self.worker_threads: worker_process.join() except KeyboardInterrupt: self._logger.info('Received request to shut down now.') else: self._logger.info('All workers have stopped.') else: self._logger.info('Shutting down')
python
def stop(self, graceful=False): """ Set the stop-flag. If `graceful=True`, this method blocks until the workers to finish executing any tasks they might be currently working on. """ self.stop_flag.set() if graceful: self._logger.info('Shutting down gracefully...') try: for _, worker_process in self.worker_threads: worker_process.join() except KeyboardInterrupt: self._logger.info('Received request to shut down now.') else: self._logger.info('All workers have stopped.') else: self._logger.info('Shutting down')
[ "def", "stop", "(", "self", ",", "graceful", "=", "False", ")", ":", "self", ".", "stop_flag", ".", "set", "(", ")", "if", "graceful", ":", "self", ".", "_logger", ".", "info", "(", "'Shutting down gracefully...'", ")", "try", ":", "for", "_", ",", "...
Set the stop-flag. If `graceful=True`, this method blocks until the workers to finish executing any tasks they might be currently working on.
[ "Set", "the", "stop", "-", "flag", "." ]
416e8da1ca18442c08431a91bce373de7d2d200f
https://github.com/coleifer/huey/blob/416e8da1ca18442c08431a91bce373de7d2d200f/huey/consumer.py#L385-L403
train
223,117
coleifer/huey
huey/consumer.py
Consumer.run
def run(self): """ Run the consumer. """ self.start() timeout = self._stop_flag_timeout health_check_ts = time.time() while True: try: self.stop_flag.wait(timeout=timeout) except KeyboardInterrupt: self._logger.info('Received SIGINT') self.stop(graceful=True) except: self._logger.exception('Error in consumer.') self.stop() else: if self._received_signal: self.stop(graceful=self._graceful) if self.stop_flag.is_set(): break if self._health_check: now = time.time() if now >= health_check_ts + self._health_check_interval: health_check_ts = now self.check_worker_health() if self._restart: self._logger.info('Consumer will restart.') python = sys.executable os.execl(python, python, *sys.argv) else: self._logger.info('Consumer exiting.')
python
def run(self): """ Run the consumer. """ self.start() timeout = self._stop_flag_timeout health_check_ts = time.time() while True: try: self.stop_flag.wait(timeout=timeout) except KeyboardInterrupt: self._logger.info('Received SIGINT') self.stop(graceful=True) except: self._logger.exception('Error in consumer.') self.stop() else: if self._received_signal: self.stop(graceful=self._graceful) if self.stop_flag.is_set(): break if self._health_check: now = time.time() if now >= health_check_ts + self._health_check_interval: health_check_ts = now self.check_worker_health() if self._restart: self._logger.info('Consumer will restart.') python = sys.executable os.execl(python, python, *sys.argv) else: self._logger.info('Consumer exiting.')
[ "def", "run", "(", "self", ")", ":", "self", ".", "start", "(", ")", "timeout", "=", "self", ".", "_stop_flag_timeout", "health_check_ts", "=", "time", ".", "time", "(", ")", "while", "True", ":", "try", ":", "self", ".", "stop_flag", ".", "wait", "(...
Run the consumer.
[ "Run", "the", "consumer", "." ]
416e8da1ca18442c08431a91bce373de7d2d200f
https://github.com/coleifer/huey/blob/416e8da1ca18442c08431a91bce373de7d2d200f/huey/consumer.py#L405-L440
train
223,118
coleifer/huey
huey/consumer.py
Consumer.check_worker_health
def check_worker_health(self): """ Check the health of the worker processes. Workers that have died will be replaced with new workers. """ self._logger.debug('Checking worker health.') workers = [] restart_occurred = False for i, (worker, worker_t) in enumerate(self.worker_threads): if not self.environment.is_alive(worker_t): self._logger.warning('Worker %d died, restarting.', i + 1) worker = self._create_worker() worker_t = self._create_process(worker, 'Worker-%d' % (i + 1)) worker_t.start() restart_occurred = True workers.append((worker, worker_t)) if restart_occurred: self.worker_threads = workers else: self._logger.debug('Workers are up and running.') if not self.environment.is_alive(self.scheduler): self._logger.warning('Scheduler died, restarting.') scheduler = self._create_scheduler() self.scheduler = self._create_process(scheduler, 'Scheduler') self.scheduler.start() else: self._logger.debug('Scheduler is up and running.') return not restart_occurred
python
def check_worker_health(self): """ Check the health of the worker processes. Workers that have died will be replaced with new workers. """ self._logger.debug('Checking worker health.') workers = [] restart_occurred = False for i, (worker, worker_t) in enumerate(self.worker_threads): if not self.environment.is_alive(worker_t): self._logger.warning('Worker %d died, restarting.', i + 1) worker = self._create_worker() worker_t = self._create_process(worker, 'Worker-%d' % (i + 1)) worker_t.start() restart_occurred = True workers.append((worker, worker_t)) if restart_occurred: self.worker_threads = workers else: self._logger.debug('Workers are up and running.') if not self.environment.is_alive(self.scheduler): self._logger.warning('Scheduler died, restarting.') scheduler = self._create_scheduler() self.scheduler = self._create_process(scheduler, 'Scheduler') self.scheduler.start() else: self._logger.debug('Scheduler is up and running.') return not restart_occurred
[ "def", "check_worker_health", "(", "self", ")", ":", "self", ".", "_logger", ".", "debug", "(", "'Checking worker health.'", ")", "workers", "=", "[", "]", "restart_occurred", "=", "False", "for", "i", ",", "(", "worker", ",", "worker_t", ")", "in", "enume...
Check the health of the worker processes. Workers that have died will be replaced with new workers.
[ "Check", "the", "health", "of", "the", "worker", "processes", ".", "Workers", "that", "have", "died", "will", "be", "replaced", "with", "new", "workers", "." ]
416e8da1ca18442c08431a91bce373de7d2d200f
https://github.com/coleifer/huey/blob/416e8da1ca18442c08431a91bce373de7d2d200f/huey/consumer.py#L442-L472
train
223,119
coleifer/huey
huey/contrib/djhuey/__init__.py
close_db
def close_db(fn): """Decorator to be used with tasks that may operate on the database.""" @wraps(fn) def inner(*args, **kwargs): try: return fn(*args, **kwargs) finally: if not HUEY.immediate: close_old_connections() return inner
python
def close_db(fn): """Decorator to be used with tasks that may operate on the database.""" @wraps(fn) def inner(*args, **kwargs): try: return fn(*args, **kwargs) finally: if not HUEY.immediate: close_old_connections() return inner
[ "def", "close_db", "(", "fn", ")", ":", "@", "wraps", "(", "fn", ")", "def", "inner", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "return", "fn", "(", "*", "args", ",", "*", "*", "kwargs", ")", "finally", ":", "if", "not"...
Decorator to be used with tasks that may operate on the database.
[ "Decorator", "to", "be", "used", "with", "tasks", "that", "may", "operate", "on", "the", "database", "." ]
416e8da1ca18442c08431a91bce373de7d2d200f
https://github.com/coleifer/huey/blob/416e8da1ca18442c08431a91bce373de7d2d200f/huey/contrib/djhuey/__init__.py#L123-L132
train
223,120
johnwheeler/flask-ask
samples/purchase/model.py
Product.list
def list(self): """ return list of purchasable and not entitled products""" mylist = [] for prod in self.product_list: if self.purchasable(prod) and not self.entitled(prod): mylist.append(prod) return mylist
python
def list(self): """ return list of purchasable and not entitled products""" mylist = [] for prod in self.product_list: if self.purchasable(prod) and not self.entitled(prod): mylist.append(prod) return mylist
[ "def", "list", "(", "self", ")", ":", "mylist", "=", "[", "]", "for", "prod", "in", "self", ".", "product_list", ":", "if", "self", ".", "purchasable", "(", "prod", ")", "and", "not", "self", ".", "entitled", "(", "prod", ")", ":", "mylist", ".", ...
return list of purchasable and not entitled products
[ "return", "list", "of", "purchasable", "and", "not", "entitled", "products" ]
fe407646ae404a8c90b363c86d5c4c201b6a5580
https://github.com/johnwheeler/flask-ask/blob/fe407646ae404a8c90b363c86d5c4c201b6a5580/samples/purchase/model.py#L51-L57
train
223,121
johnwheeler/flask-ask
samples/tidepooler/tidepooler.py
_find_tide_info
def _find_tide_info(predictions): """ Algorithm to find the 2 high tides for the day, the first of which is smaller and occurs mid-day, the second of which is larger and typically in the evening. """ last_prediction = None first_high_tide = None second_high_tide = None low_tide = None first_tide_done = False for prediction in predictions: if last_prediction is None: last_prediction = prediction continue if last_prediction['v'] < prediction['v']: if not first_tide_done: first_high_tide = prediction else: second_high_tide = prediction else: # we're decreasing if not first_tide_done and first_high_tide is not None: first_tide_done = True elif second_high_tide is not None: break # we're decreasing after having found the 2nd tide. We're done. if first_tide_done: low_tide = prediction last_prediction = prediction fmt = '%Y-%m-%d %H:%M' parse = datetime.datetime.strptime tideinfo = TideInfo() tideinfo.first_high_tide_time = parse(first_high_tide['t'], fmt) tideinfo.first_high_tide_height = float(first_high_tide['v']) tideinfo.second_high_tide_time = parse(second_high_tide['t'], fmt) tideinfo.second_high_tide_height = float(second_high_tide['v']) tideinfo.low_tide_time = parse(low_tide['t'], fmt) tideinfo.low_tide_height = float(low_tide['v']) return tideinfo
python
def _find_tide_info(predictions): """ Algorithm to find the 2 high tides for the day, the first of which is smaller and occurs mid-day, the second of which is larger and typically in the evening. """ last_prediction = None first_high_tide = None second_high_tide = None low_tide = None first_tide_done = False for prediction in predictions: if last_prediction is None: last_prediction = prediction continue if last_prediction['v'] < prediction['v']: if not first_tide_done: first_high_tide = prediction else: second_high_tide = prediction else: # we're decreasing if not first_tide_done and first_high_tide is not None: first_tide_done = True elif second_high_tide is not None: break # we're decreasing after having found the 2nd tide. We're done. if first_tide_done: low_tide = prediction last_prediction = prediction fmt = '%Y-%m-%d %H:%M' parse = datetime.datetime.strptime tideinfo = TideInfo() tideinfo.first_high_tide_time = parse(first_high_tide['t'], fmt) tideinfo.first_high_tide_height = float(first_high_tide['v']) tideinfo.second_high_tide_time = parse(second_high_tide['t'], fmt) tideinfo.second_high_tide_height = float(second_high_tide['v']) tideinfo.low_tide_time = parse(low_tide['t'], fmt) tideinfo.low_tide_height = float(low_tide['v']) return tideinfo
[ "def", "_find_tide_info", "(", "predictions", ")", ":", "last_prediction", "=", "None", "first_high_tide", "=", "None", "second_high_tide", "=", "None", "low_tide", "=", "None", "first_tide_done", "=", "False", "for", "prediction", "in", "predictions", ":", "if", ...
Algorithm to find the 2 high tides for the day, the first of which is smaller and occurs mid-day, the second of which is larger and typically in the evening.
[ "Algorithm", "to", "find", "the", "2", "high", "tides", "for", "the", "day", "the", "first", "of", "which", "is", "smaller", "and", "occurs", "mid", "-", "day", "the", "second", "of", "which", "is", "larger", "and", "typically", "in", "the", "evening", ...
fe407646ae404a8c90b363c86d5c4c201b6a5580
https://github.com/johnwheeler/flask-ask/blob/fe407646ae404a8c90b363c86d5c4c201b6a5580/samples/tidepooler/tidepooler.py#L252-L290
train
223,122
johnwheeler/flask-ask
flask_ask/models.py
audio.enqueue
def enqueue(self, stream_url, offset=0, opaque_token=None): """Adds stream to the queue. Does not impact the currently playing stream.""" directive = self._play_directive('ENQUEUE') audio_item = self._audio_item(stream_url=stream_url, offset=offset, push_buffer=False, opaque_token=opaque_token) audio_item['stream']['expectedPreviousToken'] = current_stream.token directive['audioItem'] = audio_item self._response['directives'].append(directive) return self
python
def enqueue(self, stream_url, offset=0, opaque_token=None): """Adds stream to the queue. Does not impact the currently playing stream.""" directive = self._play_directive('ENQUEUE') audio_item = self._audio_item(stream_url=stream_url, offset=offset, push_buffer=False, opaque_token=opaque_token) audio_item['stream']['expectedPreviousToken'] = current_stream.token directive['audioItem'] = audio_item self._response['directives'].append(directive) return self
[ "def", "enqueue", "(", "self", ",", "stream_url", ",", "offset", "=", "0", ",", "opaque_token", "=", "None", ")", ":", "directive", "=", "self", ".", "_play_directive", "(", "'ENQUEUE'", ")", "audio_item", "=", "self", ".", "_audio_item", "(", "stream_url"...
Adds stream to the queue. Does not impact the currently playing stream.
[ "Adds", "stream", "to", "the", "queue", ".", "Does", "not", "impact", "the", "currently", "playing", "stream", "." ]
fe407646ae404a8c90b363c86d5c4c201b6a5580
https://github.com/johnwheeler/flask-ask/blob/fe407646ae404a8c90b363c86d5c4c201b6a5580/flask_ask/models.py#L364-L375
train
223,123
johnwheeler/flask-ask
flask_ask/models.py
audio.play_next
def play_next(self, stream_url=None, offset=0, opaque_token=None): """Replace all streams in the queue but does not impact the currently playing stream.""" directive = self._play_directive('REPLACE_ENQUEUED') directive['audioItem'] = self._audio_item(stream_url=stream_url, offset=offset, opaque_token=opaque_token) self._response['directives'].append(directive) return self
python
def play_next(self, stream_url=None, offset=0, opaque_token=None): """Replace all streams in the queue but does not impact the currently playing stream.""" directive = self._play_directive('REPLACE_ENQUEUED') directive['audioItem'] = self._audio_item(stream_url=stream_url, offset=offset, opaque_token=opaque_token) self._response['directives'].append(directive) return self
[ "def", "play_next", "(", "self", ",", "stream_url", "=", "None", ",", "offset", "=", "0", ",", "opaque_token", "=", "None", ")", ":", "directive", "=", "self", ".", "_play_directive", "(", "'REPLACE_ENQUEUED'", ")", "directive", "[", "'audioItem'", "]", "=...
Replace all streams in the queue but does not impact the currently playing stream.
[ "Replace", "all", "streams", "in", "the", "queue", "but", "does", "not", "impact", "the", "currently", "playing", "stream", "." ]
fe407646ae404a8c90b363c86d5c4c201b6a5580
https://github.com/johnwheeler/flask-ask/blob/fe407646ae404a8c90b363c86d5c4c201b6a5580/flask_ask/models.py#L377-L383
train
223,124
johnwheeler/flask-ask
flask_ask/models.py
audio.resume
def resume(self): """Sends Play Directive to resume playback at the paused offset""" directive = self._play_directive('REPLACE_ALL') directive['audioItem'] = self._audio_item() self._response['directives'].append(directive) return self
python
def resume(self): """Sends Play Directive to resume playback at the paused offset""" directive = self._play_directive('REPLACE_ALL') directive['audioItem'] = self._audio_item() self._response['directives'].append(directive) return self
[ "def", "resume", "(", "self", ")", ":", "directive", "=", "self", ".", "_play_directive", "(", "'REPLACE_ALL'", ")", "directive", "[", "'audioItem'", "]", "=", "self", ".", "_audio_item", "(", ")", "self", ".", "_response", "[", "'directives'", "]", ".", ...
Sends Play Directive to resume playback at the paused offset
[ "Sends", "Play", "Directive", "to", "resume", "playback", "at", "the", "paused", "offset" ]
fe407646ae404a8c90b363c86d5c4c201b6a5580
https://github.com/johnwheeler/flask-ask/blob/fe407646ae404a8c90b363c86d5c4c201b6a5580/flask_ask/models.py#L385-L390
train
223,125
johnwheeler/flask-ask
flask_ask/models.py
audio._audio_item
def _audio_item(self, stream_url=None, offset=0, push_buffer=True, opaque_token=None): """Builds an AudioPlayer Directive's audioItem and updates current_stream""" audio_item = {'stream': {}} stream = audio_item['stream'] # existing stream if not stream_url: # stream.update(current_stream.__dict__) stream['url'] = current_stream.url stream['token'] = current_stream.token stream['offsetInMilliseconds'] = current_stream.offsetInMilliseconds # new stream else: stream['url'] = stream_url stream['token'] = opaque_token or str(uuid.uuid4()) stream['offsetInMilliseconds'] = offset if push_buffer: # prevents enqueued streams from becoming current_stream push_stream(stream_cache, context['System']['user']['userId'], stream) return audio_item
python
def _audio_item(self, stream_url=None, offset=0, push_buffer=True, opaque_token=None): """Builds an AudioPlayer Directive's audioItem and updates current_stream""" audio_item = {'stream': {}} stream = audio_item['stream'] # existing stream if not stream_url: # stream.update(current_stream.__dict__) stream['url'] = current_stream.url stream['token'] = current_stream.token stream['offsetInMilliseconds'] = current_stream.offsetInMilliseconds # new stream else: stream['url'] = stream_url stream['token'] = opaque_token or str(uuid.uuid4()) stream['offsetInMilliseconds'] = offset if push_buffer: # prevents enqueued streams from becoming current_stream push_stream(stream_cache, context['System']['user']['userId'], stream) return audio_item
[ "def", "_audio_item", "(", "self", ",", "stream_url", "=", "None", ",", "offset", "=", "0", ",", "push_buffer", "=", "True", ",", "opaque_token", "=", "None", ")", ":", "audio_item", "=", "{", "'stream'", ":", "{", "}", "}", "stream", "=", "audio_item"...
Builds an AudioPlayer Directive's audioItem and updates current_stream
[ "Builds", "an", "AudioPlayer", "Directive", "s", "audioItem", "and", "updates", "current_stream" ]
fe407646ae404a8c90b363c86d5c4c201b6a5580
https://github.com/johnwheeler/flask-ask/blob/fe407646ae404a8c90b363c86d5c4c201b6a5580/flask_ask/models.py#L398-L418
train
223,126
johnwheeler/flask-ask
flask_ask/models.py
audio.clear_queue
def clear_queue(self, stop=False): """Clears queued streams and optionally stops current stream. Keyword Arguments: stop {bool} set True to stop current current stream and clear queued streams. set False to clear queued streams and allow current stream to finish default: {False} """ directive = {} directive['type'] = 'AudioPlayer.ClearQueue' if stop: directive['clearBehavior'] = 'CLEAR_ALL' else: directive['clearBehavior'] = 'CLEAR_ENQUEUED' self._response['directives'].append(directive) return self
python
def clear_queue(self, stop=False): """Clears queued streams and optionally stops current stream. Keyword Arguments: stop {bool} set True to stop current current stream and clear queued streams. set False to clear queued streams and allow current stream to finish default: {False} """ directive = {} directive['type'] = 'AudioPlayer.ClearQueue' if stop: directive['clearBehavior'] = 'CLEAR_ALL' else: directive['clearBehavior'] = 'CLEAR_ENQUEUED' self._response['directives'].append(directive) return self
[ "def", "clear_queue", "(", "self", ",", "stop", "=", "False", ")", ":", "directive", "=", "{", "}", "directive", "[", "'type'", "]", "=", "'AudioPlayer.ClearQueue'", "if", "stop", ":", "directive", "[", "'clearBehavior'", "]", "=", "'CLEAR_ALL'", "else", "...
Clears queued streams and optionally stops current stream. Keyword Arguments: stop {bool} set True to stop current current stream and clear queued streams. set False to clear queued streams and allow current stream to finish default: {False}
[ "Clears", "queued", "streams", "and", "optionally", "stops", "current", "stream", "." ]
fe407646ae404a8c90b363c86d5c4c201b6a5580
https://github.com/johnwheeler/flask-ask/blob/fe407646ae404a8c90b363c86d5c4c201b6a5580/flask_ask/models.py#L425-L442
train
223,127
johnwheeler/flask-ask
flask_ask/core.py
find_ask
def find_ask(): """ Find our instance of Ask, navigating Local's and possible blueprints. Note: This only supports returning a reference to the first instance of Ask found. """ if hasattr(current_app, 'ask'): return getattr(current_app, 'ask') else: if hasattr(current_app, 'blueprints'): blueprints = getattr(current_app, 'blueprints') for blueprint_name in blueprints: if hasattr(blueprints[blueprint_name], 'ask'): return getattr(blueprints[blueprint_name], 'ask')
python
def find_ask(): """ Find our instance of Ask, navigating Local's and possible blueprints. Note: This only supports returning a reference to the first instance of Ask found. """ if hasattr(current_app, 'ask'): return getattr(current_app, 'ask') else: if hasattr(current_app, 'blueprints'): blueprints = getattr(current_app, 'blueprints') for blueprint_name in blueprints: if hasattr(blueprints[blueprint_name], 'ask'): return getattr(blueprints[blueprint_name], 'ask')
[ "def", "find_ask", "(", ")", ":", "if", "hasattr", "(", "current_app", ",", "'ask'", ")", ":", "return", "getattr", "(", "current_app", ",", "'ask'", ")", "else", ":", "if", "hasattr", "(", "current_app", ",", "'blueprints'", ")", ":", "blueprints", "=",...
Find our instance of Ask, navigating Local's and possible blueprints. Note: This only supports returning a reference to the first instance of Ask found.
[ "Find", "our", "instance", "of", "Ask", "navigating", "Local", "s", "and", "possible", "blueprints", "." ]
fe407646ae404a8c90b363c86d5c4c201b6a5580
https://github.com/johnwheeler/flask-ask/blob/fe407646ae404a8c90b363c86d5c4c201b6a5580/flask_ask/core.py#L21-L35
train
223,128
johnwheeler/flask-ask
flask_ask/core.py
Ask.init_app
def init_app(self, app, path='templates.yaml'): """Initializes Ask app by setting configuration variables, loading templates, and maps Ask route to a flask view. The Ask instance is given the following configuration variables by calling on Flask's configuration: `ASK_APPLICATION_ID`: Turn on application ID verification by setting this variable to an application ID or a list of allowed application IDs. By default, application ID verification is disabled and a warning is logged. This variable should be set in production to ensure requests are being sent by the applications you specify. Default: None `ASK_VERIFY_REQUESTS`: Enables or disables Alexa request verification, which ensures requests sent to your skill are from Amazon's Alexa service. This setting should not be disabled in production. It is useful for mocking JSON requests in automated tests. Default: True `ASK_VERIFY_TIMESTAMP_DEBUG`: Turn on request timestamp verification while debugging by setting this to True. Timestamp verification helps mitigate against replay attacks. It relies on the system clock being synchronized with an NTP server. This setting should not be enabled in production. Default: False `ASK_PRETTY_DEBUG_LOGS`: Add tabs and linebreaks to the Alexa request and response printed to the debug log. This improves readability when printing to the console, but breaks formatting when logging to CloudWatch. Default: False """ if self._route is None: raise TypeError("route is a required argument when app is not None") self.app = app app.ask = self app.add_url_rule(self._route, view_func=self._flask_view_func, methods=['POST']) app.jinja_loader = ChoiceLoader([app.jinja_loader, YamlLoader(app, path)])
python
def init_app(self, app, path='templates.yaml'): """Initializes Ask app by setting configuration variables, loading templates, and maps Ask route to a flask view. The Ask instance is given the following configuration variables by calling on Flask's configuration: `ASK_APPLICATION_ID`: Turn on application ID verification by setting this variable to an application ID or a list of allowed application IDs. By default, application ID verification is disabled and a warning is logged. This variable should be set in production to ensure requests are being sent by the applications you specify. Default: None `ASK_VERIFY_REQUESTS`: Enables or disables Alexa request verification, which ensures requests sent to your skill are from Amazon's Alexa service. This setting should not be disabled in production. It is useful for mocking JSON requests in automated tests. Default: True `ASK_VERIFY_TIMESTAMP_DEBUG`: Turn on request timestamp verification while debugging by setting this to True. Timestamp verification helps mitigate against replay attacks. It relies on the system clock being synchronized with an NTP server. This setting should not be enabled in production. Default: False `ASK_PRETTY_DEBUG_LOGS`: Add tabs and linebreaks to the Alexa request and response printed to the debug log. This improves readability when printing to the console, but breaks formatting when logging to CloudWatch. Default: False """ if self._route is None: raise TypeError("route is a required argument when app is not None") self.app = app app.ask = self app.add_url_rule(self._route, view_func=self._flask_view_func, methods=['POST']) app.jinja_loader = ChoiceLoader([app.jinja_loader, YamlLoader(app, path)])
[ "def", "init_app", "(", "self", ",", "app", ",", "path", "=", "'templates.yaml'", ")", ":", "if", "self", ".", "_route", "is", "None", ":", "raise", "TypeError", "(", "\"route is a required argument when app is not None\"", ")", "self", ".", "app", "=", "app",...
Initializes Ask app by setting configuration variables, loading templates, and maps Ask route to a flask view. The Ask instance is given the following configuration variables by calling on Flask's configuration: `ASK_APPLICATION_ID`: Turn on application ID verification by setting this variable to an application ID or a list of allowed application IDs. By default, application ID verification is disabled and a warning is logged. This variable should be set in production to ensure requests are being sent by the applications you specify. Default: None `ASK_VERIFY_REQUESTS`: Enables or disables Alexa request verification, which ensures requests sent to your skill are from Amazon's Alexa service. This setting should not be disabled in production. It is useful for mocking JSON requests in automated tests. Default: True `ASK_VERIFY_TIMESTAMP_DEBUG`: Turn on request timestamp verification while debugging by setting this to True. Timestamp verification helps mitigate against replay attacks. It relies on the system clock being synchronized with an NTP server. This setting should not be enabled in production. Default: False `ASK_PRETTY_DEBUG_LOGS`: Add tabs and linebreaks to the Alexa request and response printed to the debug log. This improves readability when printing to the console, but breaks formatting when logging to CloudWatch. Default: False
[ "Initializes", "Ask", "app", "by", "setting", "configuration", "variables", "loading", "templates", "and", "maps", "Ask", "route", "to", "a", "flask", "view", "." ]
fe407646ae404a8c90b363c86d5c4c201b6a5580
https://github.com/johnwheeler/flask-ask/blob/fe407646ae404a8c90b363c86d5c4c201b6a5580/flask_ask/core.py#L101-L142
train
223,129
johnwheeler/flask-ask
flask_ask/core.py
Ask.launch
def launch(self, f): """Decorator maps a view function as the endpoint for an Alexa LaunchRequest and starts the skill. @ask.launch def launched(): return question('Welcome to Foo') The wrapped function is registered as the launch view function and renders the response for requests to the Launch URL. A request to the launch URL is verified with the Alexa server before the payload is passed to the view function. Arguments: f {function} -- Launch view function """ self._launch_view_func = f @wraps(f) def wrapper(*args, **kw): self._flask_view_func(*args, **kw) return f
python
def launch(self, f): """Decorator maps a view function as the endpoint for an Alexa LaunchRequest and starts the skill. @ask.launch def launched(): return question('Welcome to Foo') The wrapped function is registered as the launch view function and renders the response for requests to the Launch URL. A request to the launch URL is verified with the Alexa server before the payload is passed to the view function. Arguments: f {function} -- Launch view function """ self._launch_view_func = f @wraps(f) def wrapper(*args, **kw): self._flask_view_func(*args, **kw) return f
[ "def", "launch", "(", "self", ",", "f", ")", ":", "self", ".", "_launch_view_func", "=", "f", "@", "wraps", "(", "f", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kw", ")", ":", "self", ".", "_flask_view_func", "(", "*", "args", ",", ...
Decorator maps a view function as the endpoint for an Alexa LaunchRequest and starts the skill. @ask.launch def launched(): return question('Welcome to Foo') The wrapped function is registered as the launch view function and renders the response for requests to the Launch URL. A request to the launch URL is verified with the Alexa server before the payload is passed to the view function. Arguments: f {function} -- Launch view function
[ "Decorator", "maps", "a", "view", "function", "as", "the", "endpoint", "for", "an", "Alexa", "LaunchRequest", "and", "starts", "the", "skill", "." ]
fe407646ae404a8c90b363c86d5c4c201b6a5580
https://github.com/johnwheeler/flask-ask/blob/fe407646ae404a8c90b363c86d5c4c201b6a5580/flask_ask/core.py#L192-L212
train
223,130
johnwheeler/flask-ask
flask_ask/core.py
Ask.session_ended
def session_ended(self, f): """Decorator routes Alexa SessionEndedRequest to the wrapped view function to end the skill. @ask.session_ended def session_ended(): return "{}", 200 The wrapped function is registered as the session_ended view function and renders the response for requests to the end of the session. Arguments: f {function} -- session_ended view function """ self._session_ended_view_func = f @wraps(f) def wrapper(*args, **kw): self._flask_view_func(*args, **kw) return f
python
def session_ended(self, f): """Decorator routes Alexa SessionEndedRequest to the wrapped view function to end the skill. @ask.session_ended def session_ended(): return "{}", 200 The wrapped function is registered as the session_ended view function and renders the response for requests to the end of the session. Arguments: f {function} -- session_ended view function """ self._session_ended_view_func = f @wraps(f) def wrapper(*args, **kw): self._flask_view_func(*args, **kw) return f
[ "def", "session_ended", "(", "self", ",", "f", ")", ":", "self", ".", "_session_ended_view_func", "=", "f", "@", "wraps", "(", "f", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kw", ")", ":", "self", ".", "_flask_view_func", "(", "*", "...
Decorator routes Alexa SessionEndedRequest to the wrapped view function to end the skill. @ask.session_ended def session_ended(): return "{}", 200 The wrapped function is registered as the session_ended view function and renders the response for requests to the end of the session. Arguments: f {function} -- session_ended view function
[ "Decorator", "routes", "Alexa", "SessionEndedRequest", "to", "the", "wrapped", "view", "function", "to", "end", "the", "skill", "." ]
fe407646ae404a8c90b363c86d5c4c201b6a5580
https://github.com/johnwheeler/flask-ask/blob/fe407646ae404a8c90b363c86d5c4c201b6a5580/flask_ask/core.py#L214-L232
train
223,131
johnwheeler/flask-ask
flask_ask/core.py
Ask.intent
def intent(self, intent_name, mapping={}, convert={}, default={}): """Decorator routes an Alexa IntentRequest and provides the slot parameters to the wrapped function. Functions decorated as an intent are registered as the view function for the Intent's URL, and provide the backend responses to give your Skill its functionality. @ask.intent('WeatherIntent', mapping={'city': 'City'}) def weather(city): return statement('I predict great weather for {}'.format(city)) Arguments: intent_name {str} -- Name of the intent request to be mapped to the decorated function Keyword Arguments: mapping {dict} -- Maps parameters to intent slots of a different name default: {} convert {dict} -- Converts slot values to data types before assignment to parameters default: {} default {dict} -- Provides default values for Intent slots if Alexa reuqest returns no corresponding slot, or a slot with an empty value default: {} """ def decorator(f): self._intent_view_funcs[intent_name] = f self._intent_mappings[intent_name] = mapping self._intent_converts[intent_name] = convert self._intent_defaults[intent_name] = default @wraps(f) def wrapper(*args, **kw): self._flask_view_func(*args, **kw) return f return decorator
python
def intent(self, intent_name, mapping={}, convert={}, default={}): """Decorator routes an Alexa IntentRequest and provides the slot parameters to the wrapped function. Functions decorated as an intent are registered as the view function for the Intent's URL, and provide the backend responses to give your Skill its functionality. @ask.intent('WeatherIntent', mapping={'city': 'City'}) def weather(city): return statement('I predict great weather for {}'.format(city)) Arguments: intent_name {str} -- Name of the intent request to be mapped to the decorated function Keyword Arguments: mapping {dict} -- Maps parameters to intent slots of a different name default: {} convert {dict} -- Converts slot values to data types before assignment to parameters default: {} default {dict} -- Provides default values for Intent slots if Alexa reuqest returns no corresponding slot, or a slot with an empty value default: {} """ def decorator(f): self._intent_view_funcs[intent_name] = f self._intent_mappings[intent_name] = mapping self._intent_converts[intent_name] = convert self._intent_defaults[intent_name] = default @wraps(f) def wrapper(*args, **kw): self._flask_view_func(*args, **kw) return f return decorator
[ "def", "intent", "(", "self", ",", "intent_name", ",", "mapping", "=", "{", "}", ",", "convert", "=", "{", "}", ",", "default", "=", "{", "}", ")", ":", "def", "decorator", "(", "f", ")", ":", "self", ".", "_intent_view_funcs", "[", "intent_name", ...
Decorator routes an Alexa IntentRequest and provides the slot parameters to the wrapped function. Functions decorated as an intent are registered as the view function for the Intent's URL, and provide the backend responses to give your Skill its functionality. @ask.intent('WeatherIntent', mapping={'city': 'City'}) def weather(city): return statement('I predict great weather for {}'.format(city)) Arguments: intent_name {str} -- Name of the intent request to be mapped to the decorated function Keyword Arguments: mapping {dict} -- Maps parameters to intent slots of a different name default: {} convert {dict} -- Converts slot values to data types before assignment to parameters default: {} default {dict} -- Provides default values for Intent slots if Alexa reuqest returns no corresponding slot, or a slot with an empty value default: {}
[ "Decorator", "routes", "an", "Alexa", "IntentRequest", "and", "provides", "the", "slot", "parameters", "to", "the", "wrapped", "function", "." ]
fe407646ae404a8c90b363c86d5c4c201b6a5580
https://github.com/johnwheeler/flask-ask/blob/fe407646ae404a8c90b363c86d5c4c201b6a5580/flask_ask/core.py#L234-L268
train
223,132
johnwheeler/flask-ask
flask_ask/core.py
Ask.default_intent
def default_intent(self, f): """Decorator routes any Alexa IntentRequest that is not matched by any existing @ask.intent routing.""" self._default_intent_view_func = f @wraps(f) def wrapper(*args, **kw): self._flask_view_func(*args, **kw) return f
python
def default_intent(self, f): """Decorator routes any Alexa IntentRequest that is not matched by any existing @ask.intent routing.""" self._default_intent_view_func = f @wraps(f) def wrapper(*args, **kw): self._flask_view_func(*args, **kw) return f
[ "def", "default_intent", "(", "self", ",", "f", ")", ":", "self", ".", "_default_intent_view_func", "=", "f", "@", "wraps", "(", "f", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kw", ")", ":", "self", ".", "_flask_view_func", "(", "*", ...
Decorator routes any Alexa IntentRequest that is not matched by any existing @ask.intent routing.
[ "Decorator", "routes", "any", "Alexa", "IntentRequest", "that", "is", "not", "matched", "by", "any", "existing" ]
fe407646ae404a8c90b363c86d5c4c201b6a5580
https://github.com/johnwheeler/flask-ask/blob/fe407646ae404a8c90b363c86d5c4c201b6a5580/flask_ask/core.py#L270-L277
train
223,133
johnwheeler/flask-ask
flask_ask/core.py
Ask.display_element_selected
def display_element_selected(self, f): """Decorator routes Alexa Display.ElementSelected request to the wrapped view function. @ask.display_element_selected def eval_element(): return "", 200 The wrapped function is registered as the display_element_selected view function and renders the response for requests. Arguments: f {function} -- display_element_selected view function """ self._display_element_selected_func = f @wraps(f) def wrapper(*args, **kw): self._flask_view_func(*args, **kw) return f
python
def display_element_selected(self, f): """Decorator routes Alexa Display.ElementSelected request to the wrapped view function. @ask.display_element_selected def eval_element(): return "", 200 The wrapped function is registered as the display_element_selected view function and renders the response for requests. Arguments: f {function} -- display_element_selected view function """ self._display_element_selected_func = f @wraps(f) def wrapper(*args, **kw): self._flask_view_func(*args, **kw) return f
[ "def", "display_element_selected", "(", "self", ",", "f", ")", ":", "self", ".", "_display_element_selected_func", "=", "f", "@", "wraps", "(", "f", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kw", ")", ":", "self", ".", "_flask_view_func", ...
Decorator routes Alexa Display.ElementSelected request to the wrapped view function. @ask.display_element_selected def eval_element(): return "", 200 The wrapped function is registered as the display_element_selected view function and renders the response for requests. Arguments: f {function} -- display_element_selected view function
[ "Decorator", "routes", "Alexa", "Display", ".", "ElementSelected", "request", "to", "the", "wrapped", "view", "function", "." ]
fe407646ae404a8c90b363c86d5c4c201b6a5580
https://github.com/johnwheeler/flask-ask/blob/fe407646ae404a8c90b363c86d5c4c201b6a5580/flask_ask/core.py#L279-L297
train
223,134
johnwheeler/flask-ask
flask_ask/core.py
Ask.on_purchase_completed
def on_purchase_completed(self, mapping={'payload': 'payload','name':'name','status':'status','token':'token'}, convert={}, default={}): """Decorator routes an Connections.Response to the wrapped function. Request is sent when Alexa completes the purchase flow. See https://developer.amazon.com/docs/in-skill-purchase/add-isps-to-a-skill.html#handle-results The wrapped view function may accept parameters from the Request. In addition to locale, requestId, timestamp, and type @ask.on_purchase_completed( mapping={'payload': 'payload','name':'name','status':'status','token':'token'}) def completed(payload, name, status, token): logger.info(payload) logger.info(name) logger.info(status) logger.info(token) """ def decorator(f): self._intent_view_funcs['Connections.Response'] = f self._intent_mappings['Connections.Response'] = mapping self._intent_converts['Connections.Response'] = convert self._intent_defaults['Connections.Response'] = default @wraps(f) def wrapper(*args, **kwargs): self._flask_view_func(*args, **kwargs) return f return decorator
python
def on_purchase_completed(self, mapping={'payload': 'payload','name':'name','status':'status','token':'token'}, convert={}, default={}): """Decorator routes an Connections.Response to the wrapped function. Request is sent when Alexa completes the purchase flow. See https://developer.amazon.com/docs/in-skill-purchase/add-isps-to-a-skill.html#handle-results The wrapped view function may accept parameters from the Request. In addition to locale, requestId, timestamp, and type @ask.on_purchase_completed( mapping={'payload': 'payload','name':'name','status':'status','token':'token'}) def completed(payload, name, status, token): logger.info(payload) logger.info(name) logger.info(status) logger.info(token) """ def decorator(f): self._intent_view_funcs['Connections.Response'] = f self._intent_mappings['Connections.Response'] = mapping self._intent_converts['Connections.Response'] = convert self._intent_defaults['Connections.Response'] = default @wraps(f) def wrapper(*args, **kwargs): self._flask_view_func(*args, **kwargs) return f return decorator
[ "def", "on_purchase_completed", "(", "self", ",", "mapping", "=", "{", "'payload'", ":", "'payload'", ",", "'name'", ":", "'name'", ",", "'status'", ":", "'status'", ",", "'token'", ":", "'token'", "}", ",", "convert", "=", "{", "}", ",", "default", "=",...
Decorator routes an Connections.Response to the wrapped function. Request is sent when Alexa completes the purchase flow. See https://developer.amazon.com/docs/in-skill-purchase/add-isps-to-a-skill.html#handle-results The wrapped view function may accept parameters from the Request. In addition to locale, requestId, timestamp, and type @ask.on_purchase_completed( mapping={'payload': 'payload','name':'name','status':'status','token':'token'}) def completed(payload, name, status, token): logger.info(payload) logger.info(name) logger.info(status) logger.info(token)
[ "Decorator", "routes", "an", "Connections", ".", "Response", "to", "the", "wrapped", "function", "." ]
fe407646ae404a8c90b363c86d5c4c201b6a5580
https://github.com/johnwheeler/flask-ask/blob/fe407646ae404a8c90b363c86d5c4c201b6a5580/flask_ask/core.py#L300-L328
train
223,135
johnwheeler/flask-ask
flask_ask/core.py
Ask.run_aws_lambda
def run_aws_lambda(self, event): """Invoke the Flask Ask application from an AWS Lambda function handler. Use this method to service AWS Lambda requests from a custom Alexa skill. This method will invoke your Flask application providing a WSGI-compatible environment that wraps the original Alexa event provided to the AWS Lambda handler. Returns the output generated by a Flask Ask application, which should be used as the return value to the AWS Lambda handler function. Example usage: from flask import Flask from flask_ask import Ask, statement app = Flask(__name__) ask = Ask(app, '/') # This function name is what you defined when you create an # AWS Lambda function. By default, AWS calls this function # lambda_handler. def lambda_handler(event, _context): return ask.run_aws_lambda(event) @ask.intent('HelloIntent') def hello(firstname): speech_text = "Hello %s" % firstname return statement(speech_text).simple_card('Hello', speech_text) """ # We are guaranteed to be called by AWS as a Lambda function does not # expose a public facing interface. self.app.config['ASK_VERIFY_REQUESTS'] = False # Convert an environment variable to a WSGI "bytes-as-unicode" string enc, esc = sys.getfilesystemencoding(), 'surrogateescape' def unicode_to_wsgi(u): return u.encode(enc, esc).decode('iso-8859-1') # Create a WSGI-compatible environ that can be passed to the # application. It is loaded with the OS environment variables, # mandatory CGI-like variables, as well as the mandatory WSGI # variables. environ = {k: unicode_to_wsgi(v) for k, v in os.environ.items()} environ['REQUEST_METHOD'] = 'POST' environ['PATH_INFO'] = '/' environ['SERVER_NAME'] = 'AWS-Lambda' environ['SERVER_PORT'] = '80' environ['SERVER_PROTOCOL'] = 'HTTP/1.0' environ['wsgi.version'] = (1, 0) environ['wsgi.url_scheme'] = 'http' environ['wsgi.errors'] = sys.stderr environ['wsgi.multithread'] = False environ['wsgi.multiprocess'] = False environ['wsgi.run_once'] = True # Convert the event provided by the AWS Lambda handler to a JSON # string that can be read as the body of a HTTP POST request. body = json.dumps(event) environ['CONTENT_TYPE'] = 'application/json' environ['CONTENT_LENGTH'] = len(body) PY3 = sys.version_info[0] == 3 if PY3: environ['wsgi.input'] = io.StringIO(body) else: environ['wsgi.input'] = io.BytesIO(body) # Start response is a required callback that must be passed when # the application is invoked. It is used to set HTTP status and # headers. Read the WSGI spec for details (PEP3333). headers = [] def start_response(status, response_headers, _exc_info=None): headers[:] = [status, response_headers] # Invoke the actual Flask application providing our environment, # with our Alexa event as the body of the HTTP request, as well # as the callback function above. The result will be an iterator # that provides a serialized JSON string for our Alexa response. result = self.app(environ, start_response) try: if not headers: raise AssertionError("start_response() not called by WSGI app") output = b"".join(result) if not headers[0].startswith("2"): raise AssertionError("Non-2xx from app: hdrs={}, body={}".format(headers, output)) # The Lambda handler expects a Python object that can be # serialized as JSON, so we need to take the already serialized # JSON and deserialize it. return json.loads(output) finally: # Per the WSGI spec, we need to invoke the close method if it # is implemented on the result object. if hasattr(result, 'close'): result.close()
python
def run_aws_lambda(self, event): """Invoke the Flask Ask application from an AWS Lambda function handler. Use this method to service AWS Lambda requests from a custom Alexa skill. This method will invoke your Flask application providing a WSGI-compatible environment that wraps the original Alexa event provided to the AWS Lambda handler. Returns the output generated by a Flask Ask application, which should be used as the return value to the AWS Lambda handler function. Example usage: from flask import Flask from flask_ask import Ask, statement app = Flask(__name__) ask = Ask(app, '/') # This function name is what you defined when you create an # AWS Lambda function. By default, AWS calls this function # lambda_handler. def lambda_handler(event, _context): return ask.run_aws_lambda(event) @ask.intent('HelloIntent') def hello(firstname): speech_text = "Hello %s" % firstname return statement(speech_text).simple_card('Hello', speech_text) """ # We are guaranteed to be called by AWS as a Lambda function does not # expose a public facing interface. self.app.config['ASK_VERIFY_REQUESTS'] = False # Convert an environment variable to a WSGI "bytes-as-unicode" string enc, esc = sys.getfilesystemencoding(), 'surrogateescape' def unicode_to_wsgi(u): return u.encode(enc, esc).decode('iso-8859-1') # Create a WSGI-compatible environ that can be passed to the # application. It is loaded with the OS environment variables, # mandatory CGI-like variables, as well as the mandatory WSGI # variables. environ = {k: unicode_to_wsgi(v) for k, v in os.environ.items()} environ['REQUEST_METHOD'] = 'POST' environ['PATH_INFO'] = '/' environ['SERVER_NAME'] = 'AWS-Lambda' environ['SERVER_PORT'] = '80' environ['SERVER_PROTOCOL'] = 'HTTP/1.0' environ['wsgi.version'] = (1, 0) environ['wsgi.url_scheme'] = 'http' environ['wsgi.errors'] = sys.stderr environ['wsgi.multithread'] = False environ['wsgi.multiprocess'] = False environ['wsgi.run_once'] = True # Convert the event provided by the AWS Lambda handler to a JSON # string that can be read as the body of a HTTP POST request. body = json.dumps(event) environ['CONTENT_TYPE'] = 'application/json' environ['CONTENT_LENGTH'] = len(body) PY3 = sys.version_info[0] == 3 if PY3: environ['wsgi.input'] = io.StringIO(body) else: environ['wsgi.input'] = io.BytesIO(body) # Start response is a required callback that must be passed when # the application is invoked. It is used to set HTTP status and # headers. Read the WSGI spec for details (PEP3333). headers = [] def start_response(status, response_headers, _exc_info=None): headers[:] = [status, response_headers] # Invoke the actual Flask application providing our environment, # with our Alexa event as the body of the HTTP request, as well # as the callback function above. The result will be an iterator # that provides a serialized JSON string for our Alexa response. result = self.app(environ, start_response) try: if not headers: raise AssertionError("start_response() not called by WSGI app") output = b"".join(result) if not headers[0].startswith("2"): raise AssertionError("Non-2xx from app: hdrs={}, body={}".format(headers, output)) # The Lambda handler expects a Python object that can be # serialized as JSON, so we need to take the already serialized # JSON and deserialize it. return json.loads(output) finally: # Per the WSGI spec, we need to invoke the close method if it # is implemented on the result object. if hasattr(result, 'close'): result.close()
[ "def", "run_aws_lambda", "(", "self", ",", "event", ")", ":", "# We are guaranteed to be called by AWS as a Lambda function does not", "# expose a public facing interface.", "self", ".", "app", ".", "config", "[", "'ASK_VERIFY_REQUESTS'", "]", "=", "False", "# Convert an envi...
Invoke the Flask Ask application from an AWS Lambda function handler. Use this method to service AWS Lambda requests from a custom Alexa skill. This method will invoke your Flask application providing a WSGI-compatible environment that wraps the original Alexa event provided to the AWS Lambda handler. Returns the output generated by a Flask Ask application, which should be used as the return value to the AWS Lambda handler function. Example usage: from flask import Flask from flask_ask import Ask, statement app = Flask(__name__) ask = Ask(app, '/') # This function name is what you defined when you create an # AWS Lambda function. By default, AWS calls this function # lambda_handler. def lambda_handler(event, _context): return ask.run_aws_lambda(event) @ask.intent('HelloIntent') def hello(firstname): speech_text = "Hello %s" % firstname return statement(speech_text).simple_card('Hello', speech_text)
[ "Invoke", "the", "Flask", "Ask", "application", "from", "an", "AWS", "Lambda", "function", "handler", "." ]
fe407646ae404a8c90b363c86d5c4c201b6a5580
https://github.com/johnwheeler/flask-ask/blob/fe407646ae404a8c90b363c86d5c4c201b6a5580/flask_ask/core.py#L585-L683
train
223,136
johnwheeler/flask-ask
flask_ask/core.py
Ask._parse_timestamp
def _parse_timestamp(timestamp): """ Parse a given timestamp value, raising ValueError if None or Flasey """ if timestamp: try: return aniso8601.parse_datetime(timestamp) except AttributeError: # raised by aniso8601 if raw_timestamp is not valid string # in ISO8601 format try: return datetime.utcfromtimestamp(timestamp) except: # relax the timestamp a bit in case it was sent in millis return datetime.utcfromtimestamp(timestamp/1000) raise ValueError('Invalid timestamp value! Cannot parse from either ISO8601 string or UTC timestamp.')
python
def _parse_timestamp(timestamp): """ Parse a given timestamp value, raising ValueError if None or Flasey """ if timestamp: try: return aniso8601.parse_datetime(timestamp) except AttributeError: # raised by aniso8601 if raw_timestamp is not valid string # in ISO8601 format try: return datetime.utcfromtimestamp(timestamp) except: # relax the timestamp a bit in case it was sent in millis return datetime.utcfromtimestamp(timestamp/1000) raise ValueError('Invalid timestamp value! Cannot parse from either ISO8601 string or UTC timestamp.')
[ "def", "_parse_timestamp", "(", "timestamp", ")", ":", "if", "timestamp", ":", "try", ":", "return", "aniso8601", ".", "parse_datetime", "(", "timestamp", ")", "except", "AttributeError", ":", "# raised by aniso8601 if raw_timestamp is not valid string", "# in ISO8601 for...
Parse a given timestamp value, raising ValueError if None or Flasey
[ "Parse", "a", "given", "timestamp", "value", "raising", "ValueError", "if", "None", "or", "Flasey" ]
fe407646ae404a8c90b363c86d5c4c201b6a5580
https://github.com/johnwheeler/flask-ask/blob/fe407646ae404a8c90b363c86d5c4c201b6a5580/flask_ask/core.py#L724-L740
train
223,137
johnwheeler/flask-ask
flask_ask/core.py
Ask._map_player_request_to_func
def _map_player_request_to_func(self, player_request_type): """Provides appropriate parameters to the on_playback functions.""" # calbacks for on_playback requests are optional view_func = self._intent_view_funcs.get(player_request_type, lambda: None) argspec = inspect.getargspec(view_func) arg_names = argspec.args arg_values = self._map_params_to_view_args(player_request_type, arg_names) return partial(view_func, *arg_values)
python
def _map_player_request_to_func(self, player_request_type): """Provides appropriate parameters to the on_playback functions.""" # calbacks for on_playback requests are optional view_func = self._intent_view_funcs.get(player_request_type, lambda: None) argspec = inspect.getargspec(view_func) arg_names = argspec.args arg_values = self._map_params_to_view_args(player_request_type, arg_names) return partial(view_func, *arg_values)
[ "def", "_map_player_request_to_func", "(", "self", ",", "player_request_type", ")", ":", "# calbacks for on_playback requests are optional", "view_func", "=", "self", ".", "_intent_view_funcs", ".", "get", "(", "player_request_type", ",", "lambda", ":", "None", ")", "ar...
Provides appropriate parameters to the on_playback functions.
[ "Provides", "appropriate", "parameters", "to", "the", "on_playback", "functions", "." ]
fe407646ae404a8c90b363c86d5c4c201b6a5580
https://github.com/johnwheeler/flask-ask/blob/fe407646ae404a8c90b363c86d5c4c201b6a5580/flask_ask/core.py#L842-L851
train
223,138
johnwheeler/flask-ask
flask_ask/core.py
Ask._map_purchase_request_to_func
def _map_purchase_request_to_func(self, purchase_request_type): """Provides appropriate parameters to the on_purchase functions.""" if purchase_request_type in self._intent_view_funcs: view_func = self._intent_view_funcs[purchase_request_type] else: raise NotImplementedError('Request type "{}" not found and no default view specified.'.format(purchase_request_type)) argspec = inspect.getargspec(view_func) arg_names = argspec.args arg_values = self._map_params_to_view_args(purchase_request_type, arg_names) print('_map_purchase_request_to_func', arg_names, arg_values, view_func, purchase_request_type) return partial(view_func, *arg_values)
python
def _map_purchase_request_to_func(self, purchase_request_type): """Provides appropriate parameters to the on_purchase functions.""" if purchase_request_type in self._intent_view_funcs: view_func = self._intent_view_funcs[purchase_request_type] else: raise NotImplementedError('Request type "{}" not found and no default view specified.'.format(purchase_request_type)) argspec = inspect.getargspec(view_func) arg_names = argspec.args arg_values = self._map_params_to_view_args(purchase_request_type, arg_names) print('_map_purchase_request_to_func', arg_names, arg_values, view_func, purchase_request_type) return partial(view_func, *arg_values)
[ "def", "_map_purchase_request_to_func", "(", "self", ",", "purchase_request_type", ")", ":", "if", "purchase_request_type", "in", "self", ".", "_intent_view_funcs", ":", "view_func", "=", "self", ".", "_intent_view_funcs", "[", "purchase_request_type", "]", "else", ":...
Provides appropriate parameters to the on_purchase functions.
[ "Provides", "appropriate", "parameters", "to", "the", "on_purchase", "functions", "." ]
fe407646ae404a8c90b363c86d5c4c201b6a5580
https://github.com/johnwheeler/flask-ask/blob/fe407646ae404a8c90b363c86d5c4c201b6a5580/flask_ask/core.py#L853-L866
train
223,139
johnwheeler/flask-ask
flask_ask/cache.py
push_stream
def push_stream(cache, user_id, stream): """ Push a stream onto the stream stack in cache. :param cache: werkzeug BasicCache-like object :param user_id: id of user, used as key in cache :param stream: stream object to push onto stack :return: True on successful update, False if failed to update, None if invalid input was given """ stack = cache.get(user_id) if stack is None: stack = [] if stream: stack.append(stream) return cache.set(user_id, stack) return None
python
def push_stream(cache, user_id, stream): """ Push a stream onto the stream stack in cache. :param cache: werkzeug BasicCache-like object :param user_id: id of user, used as key in cache :param stream: stream object to push onto stack :return: True on successful update, False if failed to update, None if invalid input was given """ stack = cache.get(user_id) if stack is None: stack = [] if stream: stack.append(stream) return cache.set(user_id, stack) return None
[ "def", "push_stream", "(", "cache", ",", "user_id", ",", "stream", ")", ":", "stack", "=", "cache", ".", "get", "(", "user_id", ")", "if", "stack", "is", "None", ":", "stack", "=", "[", "]", "if", "stream", ":", "stack", ".", "append", "(", "stream...
Push a stream onto the stream stack in cache. :param cache: werkzeug BasicCache-like object :param user_id: id of user, used as key in cache :param stream: stream object to push onto stack :return: True on successful update, False if failed to update, None if invalid input was given
[ "Push", "a", "stream", "onto", "the", "stream", "stack", "in", "cache", "." ]
fe407646ae404a8c90b363c86d5c4c201b6a5580
https://github.com/johnwheeler/flask-ask/blob/fe407646ae404a8c90b363c86d5c4c201b6a5580/flask_ask/cache.py#L6-L24
train
223,140
johnwheeler/flask-ask
flask_ask/cache.py
pop_stream
def pop_stream(cache, user_id): """ Pop an item off the stack in the cache. If stack is empty after pop, it deletes the stack. :param cache: werkzeug BasicCache-like object :param user_id: id of user, used as key in cache :return: top item from stack, otherwise None """ stack = cache.get(user_id) if stack is None: return None result = stack.pop() if len(stack) == 0: cache.delete(user_id) else: cache.set(user_id, stack) return result
python
def pop_stream(cache, user_id): """ Pop an item off the stack in the cache. If stack is empty after pop, it deletes the stack. :param cache: werkzeug BasicCache-like object :param user_id: id of user, used as key in cache :return: top item from stack, otherwise None """ stack = cache.get(user_id) if stack is None: return None result = stack.pop() if len(stack) == 0: cache.delete(user_id) else: cache.set(user_id, stack) return result
[ "def", "pop_stream", "(", "cache", ",", "user_id", ")", ":", "stack", "=", "cache", ".", "get", "(", "user_id", ")", "if", "stack", "is", "None", ":", "return", "None", "result", "=", "stack", ".", "pop", "(", ")", "if", "len", "(", "stack", ")", ...
Pop an item off the stack in the cache. If stack is empty after pop, it deletes the stack. :param cache: werkzeug BasicCache-like object :param user_id: id of user, used as key in cache :return: top item from stack, otherwise None
[ "Pop", "an", "item", "off", "the", "stack", "in", "the", "cache", ".", "If", "stack", "is", "empty", "after", "pop", "it", "deletes", "the", "stack", "." ]
fe407646ae404a8c90b363c86d5c4c201b6a5580
https://github.com/johnwheeler/flask-ask/blob/fe407646ae404a8c90b363c86d5c4c201b6a5580/flask_ask/cache.py#L27-L48
train
223,141
johnwheeler/flask-ask
flask_ask/cache.py
top_stream
def top_stream(cache, user_id): """ Peek at the top of the stack in the cache. :param cache: werkzeug BasicCache-like object :param user_id: id of user, used as key in cache :return: top item in user's cached stack, otherwise None """ if not user_id: return None stack = cache.get(user_id) if stack is None: return None return stack.pop()
python
def top_stream(cache, user_id): """ Peek at the top of the stack in the cache. :param cache: werkzeug BasicCache-like object :param user_id: id of user, used as key in cache :return: top item in user's cached stack, otherwise None """ if not user_id: return None stack = cache.get(user_id) if stack is None: return None return stack.pop()
[ "def", "top_stream", "(", "cache", ",", "user_id", ")", ":", "if", "not", "user_id", ":", "return", "None", "stack", "=", "cache", ".", "get", "(", "user_id", ")", "if", "stack", "is", "None", ":", "return", "None", "return", "stack", ".", "pop", "("...
Peek at the top of the stack in the cache. :param cache: werkzeug BasicCache-like object :param user_id: id of user, used as key in cache :return: top item in user's cached stack, otherwise None
[ "Peek", "at", "the", "top", "of", "the", "stack", "in", "the", "cache", "." ]
fe407646ae404a8c90b363c86d5c4c201b6a5580
https://github.com/johnwheeler/flask-ask/blob/fe407646ae404a8c90b363c86d5c4c201b6a5580/flask_ask/cache.py#L65-L80
train
223,142
ecederstrand/exchangelib
exchangelib/transport.py
wrap
def wrap(content, version, account=None): """ Generate the necessary boilerplate XML for a raw SOAP request. The XML is specific to the server version. ExchangeImpersonation allows to act as the user we want to impersonate. """ envelope = create_element('s:Envelope', nsmap=ns_translation) header = create_element('s:Header') requestserverversion = create_element('t:RequestServerVersion', Version=version) header.append(requestserverversion) if account: if account.access_type == IMPERSONATION: exchangeimpersonation = create_element('t:ExchangeImpersonation') connectingsid = create_element('t:ConnectingSID') add_xml_child(connectingsid, 't:PrimarySmtpAddress', account.primary_smtp_address) exchangeimpersonation.append(connectingsid) header.append(exchangeimpersonation) timezonecontext = create_element('t:TimeZoneContext') timezonedefinition = create_element('t:TimeZoneDefinition', Id=account.default_timezone.ms_id) timezonecontext.append(timezonedefinition) header.append(timezonecontext) envelope.append(header) body = create_element('s:Body') body.append(content) envelope.append(body) return xml_to_str(envelope, encoding=DEFAULT_ENCODING, xml_declaration=True)
python
def wrap(content, version, account=None): """ Generate the necessary boilerplate XML for a raw SOAP request. The XML is specific to the server version. ExchangeImpersonation allows to act as the user we want to impersonate. """ envelope = create_element('s:Envelope', nsmap=ns_translation) header = create_element('s:Header') requestserverversion = create_element('t:RequestServerVersion', Version=version) header.append(requestserverversion) if account: if account.access_type == IMPERSONATION: exchangeimpersonation = create_element('t:ExchangeImpersonation') connectingsid = create_element('t:ConnectingSID') add_xml_child(connectingsid, 't:PrimarySmtpAddress', account.primary_smtp_address) exchangeimpersonation.append(connectingsid) header.append(exchangeimpersonation) timezonecontext = create_element('t:TimeZoneContext') timezonedefinition = create_element('t:TimeZoneDefinition', Id=account.default_timezone.ms_id) timezonecontext.append(timezonedefinition) header.append(timezonecontext) envelope.append(header) body = create_element('s:Body') body.append(content) envelope.append(body) return xml_to_str(envelope, encoding=DEFAULT_ENCODING, xml_declaration=True)
[ "def", "wrap", "(", "content", ",", "version", ",", "account", "=", "None", ")", ":", "envelope", "=", "create_element", "(", "'s:Envelope'", ",", "nsmap", "=", "ns_translation", ")", "header", "=", "create_element", "(", "'s:Header'", ")", "requestserverversi...
Generate the necessary boilerplate XML for a raw SOAP request. The XML is specific to the server version. ExchangeImpersonation allows to act as the user we want to impersonate.
[ "Generate", "the", "necessary", "boilerplate", "XML", "for", "a", "raw", "SOAP", "request", ".", "The", "XML", "is", "specific", "to", "the", "server", "version", ".", "ExchangeImpersonation", "allows", "to", "act", "as", "the", "user", "we", "want", "to", ...
736347b337c239fcd6d592db5b29e819f753c1ba
https://github.com/ecederstrand/exchangelib/blob/736347b337c239fcd6d592db5b29e819f753c1ba/exchangelib/transport.py#L49-L73
train
223,143
ecederstrand/exchangelib
exchangelib/autodiscover.py
discover
def discover(email, credentials): """ Performs the autodiscover dance and returns the primary SMTP address of the account and a Protocol on success. The autodiscover and EWS server might not be the same, so we use a different Protocol to do the autodiscover request, and return a hopefully-cached Protocol to the callee. """ log.debug('Attempting autodiscover on email %s', email) if not isinstance(credentials, Credentials): raise ValueError("'credentials' %r must be a Credentials instance" % credentials) domain = get_domain(email) # We may be using multiple different credentials and changing our minds on TLS verification. This key combination # should be safe. autodiscover_key = (domain, credentials) # Use lock to guard against multiple threads competing to cache information log.debug('Waiting for _autodiscover_cache_lock') with _autodiscover_cache_lock: # Don't recurse while holding the lock! log.debug('_autodiscover_cache_lock acquired') if autodiscover_key in _autodiscover_cache: protocol = _autodiscover_cache[autodiscover_key] if not isinstance(protocol, AutodiscoverProtocol): raise ValueError('Unexpected autodiscover cache contents: %s' % protocol) log.debug('Cache hit for domain %s credentials %s: %s', domain, credentials, protocol.server) try: # This is the main path when the cache is primed return _autodiscover_quick(credentials=credentials, email=email, protocol=protocol) except AutoDiscoverFailed: # Autodiscover no longer works with this domain. Clear cache and try again after releasing the lock del _autodiscover_cache[autodiscover_key] except AutoDiscoverRedirect as e: log.debug('%s redirects to %s', email, e.redirect_email) if email.lower() == e.redirect_email.lower(): raise_from(AutoDiscoverCircularRedirect('Redirect to same email address: %s' % email), None) # Start over with the new email address after releasing the lock email = e.redirect_email else: log.debug('Cache miss for domain %s credentials %s', domain, credentials) log.debug('Cache contents: %s', _autodiscover_cache) try: # This eventually fills the cache in _autodiscover_hostname return _try_autodiscover(hostname=domain, credentials=credentials, email=email) except AutoDiscoverRedirect as e: if email.lower() == e.redirect_email.lower(): raise_from(AutoDiscoverCircularRedirect('Redirect to same email address: %s' % email), None) log.debug('%s redirects to %s', email, e.redirect_email) # Start over with the new email address after releasing the lock email = e.redirect_email log.debug('Released autodiscover_cache_lock') # We fell out of the with statement, so either cache was filled by someone else, or autodiscover redirected us to # another email address. Start over after releasing the lock. return discover(email=email, credentials=credentials)
python
def discover(email, credentials): """ Performs the autodiscover dance and returns the primary SMTP address of the account and a Protocol on success. The autodiscover and EWS server might not be the same, so we use a different Protocol to do the autodiscover request, and return a hopefully-cached Protocol to the callee. """ log.debug('Attempting autodiscover on email %s', email) if not isinstance(credentials, Credentials): raise ValueError("'credentials' %r must be a Credentials instance" % credentials) domain = get_domain(email) # We may be using multiple different credentials and changing our minds on TLS verification. This key combination # should be safe. autodiscover_key = (domain, credentials) # Use lock to guard against multiple threads competing to cache information log.debug('Waiting for _autodiscover_cache_lock') with _autodiscover_cache_lock: # Don't recurse while holding the lock! log.debug('_autodiscover_cache_lock acquired') if autodiscover_key in _autodiscover_cache: protocol = _autodiscover_cache[autodiscover_key] if not isinstance(protocol, AutodiscoverProtocol): raise ValueError('Unexpected autodiscover cache contents: %s' % protocol) log.debug('Cache hit for domain %s credentials %s: %s', domain, credentials, protocol.server) try: # This is the main path when the cache is primed return _autodiscover_quick(credentials=credentials, email=email, protocol=protocol) except AutoDiscoverFailed: # Autodiscover no longer works with this domain. Clear cache and try again after releasing the lock del _autodiscover_cache[autodiscover_key] except AutoDiscoverRedirect as e: log.debug('%s redirects to %s', email, e.redirect_email) if email.lower() == e.redirect_email.lower(): raise_from(AutoDiscoverCircularRedirect('Redirect to same email address: %s' % email), None) # Start over with the new email address after releasing the lock email = e.redirect_email else: log.debug('Cache miss for domain %s credentials %s', domain, credentials) log.debug('Cache contents: %s', _autodiscover_cache) try: # This eventually fills the cache in _autodiscover_hostname return _try_autodiscover(hostname=domain, credentials=credentials, email=email) except AutoDiscoverRedirect as e: if email.lower() == e.redirect_email.lower(): raise_from(AutoDiscoverCircularRedirect('Redirect to same email address: %s' % email), None) log.debug('%s redirects to %s', email, e.redirect_email) # Start over with the new email address after releasing the lock email = e.redirect_email log.debug('Released autodiscover_cache_lock') # We fell out of the with statement, so either cache was filled by someone else, or autodiscover redirected us to # another email address. Start over after releasing the lock. return discover(email=email, credentials=credentials)
[ "def", "discover", "(", "email", ",", "credentials", ")", ":", "log", ".", "debug", "(", "'Attempting autodiscover on email %s'", ",", "email", ")", "if", "not", "isinstance", "(", "credentials", ",", "Credentials", ")", ":", "raise", "ValueError", "(", "\"'cr...
Performs the autodiscover dance and returns the primary SMTP address of the account and a Protocol on success. The autodiscover and EWS server might not be the same, so we use a different Protocol to do the autodiscover request, and return a hopefully-cached Protocol to the callee.
[ "Performs", "the", "autodiscover", "dance", "and", "returns", "the", "primary", "SMTP", "address", "of", "the", "account", "and", "a", "Protocol", "on", "success", ".", "The", "autodiscover", "and", "EWS", "server", "might", "not", "be", "the", "same", "so",...
736347b337c239fcd6d592db5b29e819f753c1ba
https://github.com/ecederstrand/exchangelib/blob/736347b337c239fcd6d592db5b29e819f753c1ba/exchangelib/autodiscover.py#L173-L223
train
223,144
ecederstrand/exchangelib
exchangelib/properties.py
TimeZone.to_server_timezone
def to_server_timezone(self, timezones, for_year): """Returns the Microsoft timezone ID corresponding to this timezone. There may not be a match at all, and there may be multiple matches. If so, we return a random timezone ID. :param timezones: A list of server timezones, as returned by list(account.protocol.get_timezones(return_full_timezone_data=True)) :param for_year: :return: A Microsoft timezone ID, as a string """ candidates = set() for tz_id, tz_name, tz_periods, tz_transitions, tz_transitions_groups in timezones: candidate = self.from_server_timezone(tz_periods, tz_transitions, tz_transitions_groups, for_year) if candidate == self: log.debug('Found exact candidate: %s (%s)', tz_id, tz_name) # We prefer this timezone over anything else. Return immediately. return tz_id # Reduce list based on base bias and standard / daylight bias values if candidate.bias != self.bias: continue if candidate.standard_time is None: if self.standard_time is not None: continue else: if self.standard_time is None: continue if candidate.standard_time.bias != self.standard_time.bias: continue if candidate.daylight_time is None: if self.daylight_time is not None: continue else: if self.daylight_time is None: continue if candidate.daylight_time.bias != self.daylight_time.bias: continue log.debug('Found candidate with matching biases: %s (%s)', tz_id, tz_name) candidates.add(tz_id) if not candidates: raise ValueError('No server timezones match this timezone definition') if len(candidates) == 1: log.info('Could not find an exact timezone match for %s. Selecting the best candidate', self) else: log.warning('Could not find an exact timezone match for %s. Selecting a random candidate', self) return candidates.pop()
python
def to_server_timezone(self, timezones, for_year): """Returns the Microsoft timezone ID corresponding to this timezone. There may not be a match at all, and there may be multiple matches. If so, we return a random timezone ID. :param timezones: A list of server timezones, as returned by list(account.protocol.get_timezones(return_full_timezone_data=True)) :param for_year: :return: A Microsoft timezone ID, as a string """ candidates = set() for tz_id, tz_name, tz_periods, tz_transitions, tz_transitions_groups in timezones: candidate = self.from_server_timezone(tz_periods, tz_transitions, tz_transitions_groups, for_year) if candidate == self: log.debug('Found exact candidate: %s (%s)', tz_id, tz_name) # We prefer this timezone over anything else. Return immediately. return tz_id # Reduce list based on base bias and standard / daylight bias values if candidate.bias != self.bias: continue if candidate.standard_time is None: if self.standard_time is not None: continue else: if self.standard_time is None: continue if candidate.standard_time.bias != self.standard_time.bias: continue if candidate.daylight_time is None: if self.daylight_time is not None: continue else: if self.daylight_time is None: continue if candidate.daylight_time.bias != self.daylight_time.bias: continue log.debug('Found candidate with matching biases: %s (%s)', tz_id, tz_name) candidates.add(tz_id) if not candidates: raise ValueError('No server timezones match this timezone definition') if len(candidates) == 1: log.info('Could not find an exact timezone match for %s. Selecting the best candidate', self) else: log.warning('Could not find an exact timezone match for %s. Selecting a random candidate', self) return candidates.pop()
[ "def", "to_server_timezone", "(", "self", ",", "timezones", ",", "for_year", ")", ":", "candidates", "=", "set", "(", ")", "for", "tz_id", ",", "tz_name", ",", "tz_periods", ",", "tz_transitions", ",", "tz_transitions_groups", "in", "timezones", ":", "candidat...
Returns the Microsoft timezone ID corresponding to this timezone. There may not be a match at all, and there may be multiple matches. If so, we return a random timezone ID. :param timezones: A list of server timezones, as returned by list(account.protocol.get_timezones(return_full_timezone_data=True)) :param for_year: :return: A Microsoft timezone ID, as a string
[ "Returns", "the", "Microsoft", "timezone", "ID", "corresponding", "to", "this", "timezone", ".", "There", "may", "not", "be", "a", "match", "at", "all", "and", "there", "may", "be", "multiple", "matches", ".", "If", "so", "we", "return", "a", "random", "...
736347b337c239fcd6d592db5b29e819f753c1ba
https://github.com/ecederstrand/exchangelib/blob/736347b337c239fcd6d592db5b29e819f753c1ba/exchangelib/properties.py#L560-L603
train
223,145
ecederstrand/exchangelib
exchangelib/protocol.py
BaseProtocol.decrease_poolsize
def decrease_poolsize(self): """Decreases the session pool size in response to error messages from the server requesting to rate-limit requests. We decrease by one session per call. """ # Take a single session from the pool and discard it. We need to protect this with a lock while we are changing # the pool size variable, to avoid race conditions. We must keep at least one session in the pool. if self._session_pool_size <= 1: raise SessionPoolMinSizeReached('Session pool size cannot be decreased further') with self._session_pool_lock: if self._session_pool_size <= 1: log.debug('Session pool size was decreased in another thread') return log.warning('Lowering session pool size from %s to %s', self._session_pool_size, self._session_pool_size - 1) self.get_session().close() self._session_pool_size -= 1
python
def decrease_poolsize(self): """Decreases the session pool size in response to error messages from the server requesting to rate-limit requests. We decrease by one session per call. """ # Take a single session from the pool and discard it. We need to protect this with a lock while we are changing # the pool size variable, to avoid race conditions. We must keep at least one session in the pool. if self._session_pool_size <= 1: raise SessionPoolMinSizeReached('Session pool size cannot be decreased further') with self._session_pool_lock: if self._session_pool_size <= 1: log.debug('Session pool size was decreased in another thread') return log.warning('Lowering session pool size from %s to %s', self._session_pool_size, self._session_pool_size - 1) self.get_session().close() self._session_pool_size -= 1
[ "def", "decrease_poolsize", "(", "self", ")", ":", "# Take a single session from the pool and discard it. We need to protect this with a lock while we are changing", "# the pool size variable, to avoid race conditions. We must keep at least one session in the pool.", "if", "self", ".", "_sessi...
Decreases the session pool size in response to error messages from the server requesting to rate-limit requests. We decrease by one session per call.
[ "Decreases", "the", "session", "pool", "size", "in", "response", "to", "error", "messages", "from", "the", "server", "requesting", "to", "rate", "-", "limit", "requests", ".", "We", "decrease", "by", "one", "session", "per", "call", "." ]
736347b337c239fcd6d592db5b29e819f753c1ba
https://github.com/ecederstrand/exchangelib/blob/736347b337c239fcd6d592db5b29e819f753c1ba/exchangelib/protocol.py#L100-L115
train
223,146
ecederstrand/exchangelib
exchangelib/util.py
is_iterable
def is_iterable(value, generators_allowed=False): """ Checks if value is a list-like object. Don't match generators and generator-like objects here by default, because callers don't necessarily guarantee that they only iterate the value once. Take care to not match string types and bytes. :param value: any type of object :param generators_allowed: if True, generators will be treated as iterable :return: True or False """ if generators_allowed: if not isinstance(value, string_types + (bytes,)) and hasattr(value, '__iter__'): return True else: if isinstance(value, (tuple, list, set)): return True return False
python
def is_iterable(value, generators_allowed=False): """ Checks if value is a list-like object. Don't match generators and generator-like objects here by default, because callers don't necessarily guarantee that they only iterate the value once. Take care to not match string types and bytes. :param value: any type of object :param generators_allowed: if True, generators will be treated as iterable :return: True or False """ if generators_allowed: if not isinstance(value, string_types + (bytes,)) and hasattr(value, '__iter__'): return True else: if isinstance(value, (tuple, list, set)): return True return False
[ "def", "is_iterable", "(", "value", ",", "generators_allowed", "=", "False", ")", ":", "if", "generators_allowed", ":", "if", "not", "isinstance", "(", "value", ",", "string_types", "+", "(", "bytes", ",", ")", ")", "and", "hasattr", "(", "value", ",", "...
Checks if value is a list-like object. Don't match generators and generator-like objects here by default, because callers don't necessarily guarantee that they only iterate the value once. Take care to not match string types and bytes. :param value: any type of object :param generators_allowed: if True, generators will be treated as iterable :return: True or False
[ "Checks", "if", "value", "is", "a", "list", "-", "like", "object", ".", "Don", "t", "match", "generators", "and", "generator", "-", "like", "objects", "here", "by", "default", "because", "callers", "don", "t", "necessarily", "guarantee", "that", "they", "o...
736347b337c239fcd6d592db5b29e819f753c1ba
https://github.com/ecederstrand/exchangelib/blob/736347b337c239fcd6d592db5b29e819f753c1ba/exchangelib/util.py#L64-L80
train
223,147
ecederstrand/exchangelib
exchangelib/util.py
chunkify
def chunkify(iterable, chunksize): """ Splits an iterable into chunks of size ``chunksize``. The last chunk may be smaller than ``chunksize``. """ from .queryset import QuerySet if hasattr(iterable, '__getitem__') and not isinstance(iterable, QuerySet): # tuple, list. QuerySet has __getitem__ but that evaluates the entire query greedily. We don't want that here. for i in range(0, len(iterable), chunksize): yield iterable[i:i + chunksize] else: # generator, set, map, QuerySet chunk = [] for i in iterable: chunk.append(i) if len(chunk) == chunksize: yield chunk chunk = [] if chunk: yield chunk
python
def chunkify(iterable, chunksize): """ Splits an iterable into chunks of size ``chunksize``. The last chunk may be smaller than ``chunksize``. """ from .queryset import QuerySet if hasattr(iterable, '__getitem__') and not isinstance(iterable, QuerySet): # tuple, list. QuerySet has __getitem__ but that evaluates the entire query greedily. We don't want that here. for i in range(0, len(iterable), chunksize): yield iterable[i:i + chunksize] else: # generator, set, map, QuerySet chunk = [] for i in iterable: chunk.append(i) if len(chunk) == chunksize: yield chunk chunk = [] if chunk: yield chunk
[ "def", "chunkify", "(", "iterable", ",", "chunksize", ")", ":", "from", ".", "queryset", "import", "QuerySet", "if", "hasattr", "(", "iterable", ",", "'__getitem__'", ")", "and", "not", "isinstance", "(", "iterable", ",", "QuerySet", ")", ":", "# tuple, list...
Splits an iterable into chunks of size ``chunksize``. The last chunk may be smaller than ``chunksize``.
[ "Splits", "an", "iterable", "into", "chunks", "of", "size", "chunksize", ".", "The", "last", "chunk", "may", "be", "smaller", "than", "chunksize", "." ]
736347b337c239fcd6d592db5b29e819f753c1ba
https://github.com/ecederstrand/exchangelib/blob/736347b337c239fcd6d592db5b29e819f753c1ba/exchangelib/util.py#L83-L101
train
223,148
ecederstrand/exchangelib
exchangelib/util.py
peek
def peek(iterable): """ Checks if an iterable is empty and returns status and the rewinded iterable """ from .queryset import QuerySet if isinstance(iterable, QuerySet): # QuerySet has __len__ but that evaluates the entire query greedily. We don't want that here. Instead, peek() # should be called on QuerySet.iterator() raise ValueError('Cannot peek on a QuerySet') if hasattr(iterable, '__len__'): # tuple, list, set return not iterable, iterable # generator try: first = next(iterable) except StopIteration: return True, iterable # We can't rewind a generator. Instead, chain the first element and the rest of the generator return False, itertools.chain([first], iterable)
python
def peek(iterable): """ Checks if an iterable is empty and returns status and the rewinded iterable """ from .queryset import QuerySet if isinstance(iterable, QuerySet): # QuerySet has __len__ but that evaluates the entire query greedily. We don't want that here. Instead, peek() # should be called on QuerySet.iterator() raise ValueError('Cannot peek on a QuerySet') if hasattr(iterable, '__len__'): # tuple, list, set return not iterable, iterable # generator try: first = next(iterable) except StopIteration: return True, iterable # We can't rewind a generator. Instead, chain the first element and the rest of the generator return False, itertools.chain([first], iterable)
[ "def", "peek", "(", "iterable", ")", ":", "from", ".", "queryset", "import", "QuerySet", "if", "isinstance", "(", "iterable", ",", "QuerySet", ")", ":", "# QuerySet has __len__ but that evaluates the entire query greedily. We don't want that here. Instead, peek()", "# should ...
Checks if an iterable is empty and returns status and the rewinded iterable
[ "Checks", "if", "an", "iterable", "is", "empty", "and", "returns", "status", "and", "the", "rewinded", "iterable" ]
736347b337c239fcd6d592db5b29e819f753c1ba
https://github.com/ecederstrand/exchangelib/blob/736347b337c239fcd6d592db5b29e819f753c1ba/exchangelib/util.py#L104-L122
train
223,149
ecederstrand/exchangelib
exchangelib/util.py
xml_to_str
def xml_to_str(tree, encoding=None, xml_declaration=False): """Serialize an XML tree. Returns unicode if 'encoding' is None. Otherwise, we return encoded 'bytes'.""" if xml_declaration and not encoding: raise ValueError("'xml_declaration' is not supported when 'encoding' is None") if encoding: return tostring(tree, encoding=encoding, xml_declaration=True) return tostring(tree, encoding=text_type, xml_declaration=False)
python
def xml_to_str(tree, encoding=None, xml_declaration=False): """Serialize an XML tree. Returns unicode if 'encoding' is None. Otherwise, we return encoded 'bytes'.""" if xml_declaration and not encoding: raise ValueError("'xml_declaration' is not supported when 'encoding' is None") if encoding: return tostring(tree, encoding=encoding, xml_declaration=True) return tostring(tree, encoding=text_type, xml_declaration=False)
[ "def", "xml_to_str", "(", "tree", ",", "encoding", "=", "None", ",", "xml_declaration", "=", "False", ")", ":", "if", "xml_declaration", "and", "not", "encoding", ":", "raise", "ValueError", "(", "\"'xml_declaration' is not supported when 'encoding' is None\"", ")", ...
Serialize an XML tree. Returns unicode if 'encoding' is None. Otherwise, we return encoded 'bytes'.
[ "Serialize", "an", "XML", "tree", ".", "Returns", "unicode", "if", "encoding", "is", "None", ".", "Otherwise", "we", "return", "encoded", "bytes", "." ]
736347b337c239fcd6d592db5b29e819f753c1ba
https://github.com/ecederstrand/exchangelib/blob/736347b337c239fcd6d592db5b29e819f753c1ba/exchangelib/util.py#L125-L131
train
223,150
ecederstrand/exchangelib
exchangelib/util.py
is_xml
def is_xml(text): """ Helper function. Lightweight test if response is an XML doc """ # BOM_UTF8 is an UTF-8 byte order mark which may precede the XML from an Exchange server bom_len = len(BOM_UTF8) if text[:bom_len] == BOM_UTF8: return text[bom_len:bom_len + 5] == b'<?xml' return text[:5] == b'<?xml'
python
def is_xml(text): """ Helper function. Lightweight test if response is an XML doc """ # BOM_UTF8 is an UTF-8 byte order mark which may precede the XML from an Exchange server bom_len = len(BOM_UTF8) if text[:bom_len] == BOM_UTF8: return text[bom_len:bom_len + 5] == b'<?xml' return text[:5] == b'<?xml'
[ "def", "is_xml", "(", "text", ")", ":", "# BOM_UTF8 is an UTF-8 byte order mark which may precede the XML from an Exchange server", "bom_len", "=", "len", "(", "BOM_UTF8", ")", "if", "text", "[", ":", "bom_len", "]", "==", "BOM_UTF8", ":", "return", "text", "[", "bo...
Helper function. Lightweight test if response is an XML doc
[ "Helper", "function", ".", "Lightweight", "test", "if", "response", "is", "an", "XML", "doc" ]
736347b337c239fcd6d592db5b29e819f753c1ba
https://github.com/ecederstrand/exchangelib/blob/736347b337c239fcd6d592db5b29e819f753c1ba/exchangelib/util.py#L391-L399
train
223,151
ecederstrand/exchangelib
exchangelib/services.py
GetItem.call
def call(self, items, additional_fields, shape): """ Returns all items in an account that correspond to a list of ID's, in stable order. :param items: a list of (id, changekey) tuples or Item objects :param additional_fields: the extra fields that should be returned with the item, as FieldPath objects :param shape: The shape of returned objects :return: XML elements for the items, in stable order """ return self._pool_requests(payload_func=self.get_payload, **dict( items=items, additional_fields=additional_fields, shape=shape, ))
python
def call(self, items, additional_fields, shape): """ Returns all items in an account that correspond to a list of ID's, in stable order. :param items: a list of (id, changekey) tuples or Item objects :param additional_fields: the extra fields that should be returned with the item, as FieldPath objects :param shape: The shape of returned objects :return: XML elements for the items, in stable order """ return self._pool_requests(payload_func=self.get_payload, **dict( items=items, additional_fields=additional_fields, shape=shape, ))
[ "def", "call", "(", "self", ",", "items", ",", "additional_fields", ",", "shape", ")", ":", "return", "self", ".", "_pool_requests", "(", "payload_func", "=", "self", ".", "get_payload", ",", "*", "*", "dict", "(", "items", "=", "items", ",", "additional...
Returns all items in an account that correspond to a list of ID's, in stable order. :param items: a list of (id, changekey) tuples or Item objects :param additional_fields: the extra fields that should be returned with the item, as FieldPath objects :param shape: The shape of returned objects :return: XML elements for the items, in stable order
[ "Returns", "all", "items", "in", "an", "account", "that", "correspond", "to", "a", "list", "of", "ID", "s", "in", "stable", "order", "." ]
736347b337c239fcd6d592db5b29e819f753c1ba
https://github.com/ecederstrand/exchangelib/blob/736347b337c239fcd6d592db5b29e819f753c1ba/exchangelib/services.py#L689-L702
train
223,152
ecederstrand/exchangelib
exchangelib/services.py
FindFolder.call
def call(self, additional_fields, restriction, shape, depth, max_items, offset): """ Find subfolders of a folder. :param additional_fields: the extra fields that should be returned with the folder, as FieldPath objects :param shape: The set of attributes to return :param depth: How deep in the folder structure to search for folders :param max_items: The maximum number of items to return :param offset: the offset relative to the first item in the item collection. Usually 0. :return: XML elements for the matching folders """ from .folders import Folder roots = {f.root for f in self.folders} if len(roots) != 1: raise ValueError('FindFolder must be called with folders in the same root hierarchy (%r)' % roots) root = roots.pop() for elem in self._paged_call(payload_func=self.get_payload, max_items=max_items, **dict( additional_fields=additional_fields, restriction=restriction, shape=shape, depth=depth, page_size=self.chunk_size, offset=offset, )): if isinstance(elem, Exception): yield elem continue yield Folder.from_xml(elem=elem, root=root)
python
def call(self, additional_fields, restriction, shape, depth, max_items, offset): """ Find subfolders of a folder. :param additional_fields: the extra fields that should be returned with the folder, as FieldPath objects :param shape: The set of attributes to return :param depth: How deep in the folder structure to search for folders :param max_items: The maximum number of items to return :param offset: the offset relative to the first item in the item collection. Usually 0. :return: XML elements for the matching folders """ from .folders import Folder roots = {f.root for f in self.folders} if len(roots) != 1: raise ValueError('FindFolder must be called with folders in the same root hierarchy (%r)' % roots) root = roots.pop() for elem in self._paged_call(payload_func=self.get_payload, max_items=max_items, **dict( additional_fields=additional_fields, restriction=restriction, shape=shape, depth=depth, page_size=self.chunk_size, offset=offset, )): if isinstance(elem, Exception): yield elem continue yield Folder.from_xml(elem=elem, root=root)
[ "def", "call", "(", "self", ",", "additional_fields", ",", "restriction", ",", "shape", ",", "depth", ",", "max_items", ",", "offset", ")", ":", "from", ".", "folders", "import", "Folder", "roots", "=", "{", "f", ".", "root", "for", "f", "in", "self", ...
Find subfolders of a folder. :param additional_fields: the extra fields that should be returned with the folder, as FieldPath objects :param shape: The set of attributes to return :param depth: How deep in the folder structure to search for folders :param max_items: The maximum number of items to return :param offset: the offset relative to the first item in the item collection. Usually 0. :return: XML elements for the matching folders
[ "Find", "subfolders", "of", "a", "folder", "." ]
736347b337c239fcd6d592db5b29e819f753c1ba
https://github.com/ecederstrand/exchangelib/blob/736347b337c239fcd6d592db5b29e819f753c1ba/exchangelib/services.py#L1067-L1094
train
223,153
ecederstrand/exchangelib
exchangelib/services.py
GetFolder.call
def call(self, folders, additional_fields, shape): """ Takes a folder ID and returns the full information for that folder. :param folders: a list of Folder objects :param additional_fields: the extra fields that should be returned with the folder, as FieldPath objects :param shape: The set of attributes to return :return: XML elements for the folders, in stable order """ # We can't easily find the correct folder class from the returned XML. Instead, return objects with the same # class as the folder instance it was requested with. from .folders import Folder, DistinguishedFolderId, RootOfHierarchy folders_list = list(folders) # Convert to a list, in case 'folders' is a generator for folder, elem in zip(folders_list, self._get_elements(payload=self.get_payload( folders=folders, additional_fields=additional_fields, shape=shape, ))): if isinstance(elem, Exception): yield elem continue if isinstance(folder, RootOfHierarchy): f = folder.from_xml(elem=elem, account=self.account) elif isinstance(folder, Folder): f = folder.from_xml(elem=elem, root=folder.root) elif isinstance(folder, DistinguishedFolderId): # We don't know the root, so assume account.root. for folder_cls in self.account.root.WELLKNOWN_FOLDERS: if folder_cls.DISTINGUISHED_FOLDER_ID == folder.id: break else: raise ValueError('Unknown distinguished folder ID: %s', folder.id) f = folder_cls.from_xml(elem=elem, root=self.account.root) else: # 'folder' is a generic FolderId instance. We don't know the root so assume account.root. f = Folder.from_xml(elem=elem, root=self.account.root) if isinstance(folder, DistinguishedFolderId): f.is_distinguished = True elif isinstance(folder, Folder) and folder.is_distinguished: f.is_distinguished = True yield f
python
def call(self, folders, additional_fields, shape): """ Takes a folder ID and returns the full information for that folder. :param folders: a list of Folder objects :param additional_fields: the extra fields that should be returned with the folder, as FieldPath objects :param shape: The set of attributes to return :return: XML elements for the folders, in stable order """ # We can't easily find the correct folder class from the returned XML. Instead, return objects with the same # class as the folder instance it was requested with. from .folders import Folder, DistinguishedFolderId, RootOfHierarchy folders_list = list(folders) # Convert to a list, in case 'folders' is a generator for folder, elem in zip(folders_list, self._get_elements(payload=self.get_payload( folders=folders, additional_fields=additional_fields, shape=shape, ))): if isinstance(elem, Exception): yield elem continue if isinstance(folder, RootOfHierarchy): f = folder.from_xml(elem=elem, account=self.account) elif isinstance(folder, Folder): f = folder.from_xml(elem=elem, root=folder.root) elif isinstance(folder, DistinguishedFolderId): # We don't know the root, so assume account.root. for folder_cls in self.account.root.WELLKNOWN_FOLDERS: if folder_cls.DISTINGUISHED_FOLDER_ID == folder.id: break else: raise ValueError('Unknown distinguished folder ID: %s', folder.id) f = folder_cls.from_xml(elem=elem, root=self.account.root) else: # 'folder' is a generic FolderId instance. We don't know the root so assume account.root. f = Folder.from_xml(elem=elem, root=self.account.root) if isinstance(folder, DistinguishedFolderId): f.is_distinguished = True elif isinstance(folder, Folder) and folder.is_distinguished: f.is_distinguished = True yield f
[ "def", "call", "(", "self", ",", "folders", ",", "additional_fields", ",", "shape", ")", ":", "# We can't easily find the correct folder class from the returned XML. Instead, return objects with the same", "# class as the folder instance it was requested with.", "from", ".", "folders...
Takes a folder ID and returns the full information for that folder. :param folders: a list of Folder objects :param additional_fields: the extra fields that should be returned with the folder, as FieldPath objects :param shape: The set of attributes to return :return: XML elements for the folders, in stable order
[ "Takes", "a", "folder", "ID", "and", "returns", "the", "full", "information", "for", "that", "folder", "." ]
736347b337c239fcd6d592db5b29e819f753c1ba
https://github.com/ecederstrand/exchangelib/blob/736347b337c239fcd6d592db5b29e819f753c1ba/exchangelib/services.py#L1132-L1172
train
223,154
ecederstrand/exchangelib
exchangelib/services.py
UploadItems.get_payload
def get_payload(self, items): """Upload given items to given account data is an iterable of tuples where the first element is a Folder instance representing the ParentFolder that the item will be placed in and the second element is a Data string returned from an ExportItems call. """ from .properties import ParentFolderId uploaditems = create_element('m:%s' % self.SERVICE_NAME) itemselement = create_element('m:Items') uploaditems.append(itemselement) for parent_folder, data_str in items: item = create_element('t:Item', CreateAction='CreateNew') parentfolderid = ParentFolderId(parent_folder.id, parent_folder.changekey) set_xml_value(item, parentfolderid, version=self.account.version) add_xml_child(item, 't:Data', data_str) itemselement.append(item) return uploaditems
python
def get_payload(self, items): """Upload given items to given account data is an iterable of tuples where the first element is a Folder instance representing the ParentFolder that the item will be placed in and the second element is a Data string returned from an ExportItems call. """ from .properties import ParentFolderId uploaditems = create_element('m:%s' % self.SERVICE_NAME) itemselement = create_element('m:Items') uploaditems.append(itemselement) for parent_folder, data_str in items: item = create_element('t:Item', CreateAction='CreateNew') parentfolderid = ParentFolderId(parent_folder.id, parent_folder.changekey) set_xml_value(item, parentfolderid, version=self.account.version) add_xml_child(item, 't:Data', data_str) itemselement.append(item) return uploaditems
[ "def", "get_payload", "(", "self", ",", "items", ")", ":", "from", ".", "properties", "import", "ParentFolderId", "uploaditems", "=", "create_element", "(", "'m:%s'", "%", "self", ".", "SERVICE_NAME", ")", "itemselement", "=", "create_element", "(", "'m:Items'",...
Upload given items to given account data is an iterable of tuples where the first element is a Folder instance representing the ParentFolder that the item will be placed in and the second element is a Data string returned from an ExportItems call.
[ "Upload", "given", "items", "to", "given", "account" ]
736347b337c239fcd6d592db5b29e819f753c1ba
https://github.com/ecederstrand/exchangelib/blob/736347b337c239fcd6d592db5b29e819f753c1ba/exchangelib/services.py#L1880-L1898
train
223,155
ecederstrand/exchangelib
exchangelib/folders.py
FolderCollection.find_items
def find_items(self, q, shape=ID_ONLY, depth=SHALLOW, additional_fields=None, order_fields=None, calendar_view=None, page_size=None, max_items=None, offset=0): """ Private method to call the FindItem service :param q: a Q instance containing any restrictions :param shape: controls whether to return (id, chanegkey) tuples or Item objects. If additional_fields is non-null, we always return Item objects. :param depth: controls the whether to return soft-deleted items or not. :param additional_fields: the extra properties we want on the return objects. Default is no properties. Be aware that complex fields can only be fetched with fetch() (i.e. the GetItem service). :param order_fields: the SortOrder fields, if any :param calendar_view: a CalendarView instance, if any :param page_size: the requested number of items per page :param max_items: the max number of items to return :param offset: the offset relative to the first item in the item collection :return: a generator for the returned item IDs or items """ if shape not in SHAPE_CHOICES: raise ValueError("'shape' %s must be one of %s" % (shape, SHAPE_CHOICES)) if depth not in ITEM_TRAVERSAL_CHOICES: raise ValueError("'depth' %s must be one of %s" % (depth, ITEM_TRAVERSAL_CHOICES)) if not self.folders: log.debug('Folder list is empty') return if additional_fields: for f in additional_fields: self.validate_item_field(field=f) for f in additional_fields: if f.field.is_complex: raise ValueError("find_items() does not support field '%s'. Use fetch() instead" % f.field.name) if calendar_view is not None and not isinstance(calendar_view, CalendarView): raise ValueError("'calendar_view' %s must be a CalendarView instance" % calendar_view) # Build up any restrictions if q.is_empty(): restriction = None query_string = None elif q.query_string: restriction = None query_string = Restriction(q, folders=self.folders, applies_to=Restriction.ITEMS) else: restriction = Restriction(q, folders=self.folders, applies_to=Restriction.ITEMS) query_string = None log.debug( 'Finding %s items in folders %s (shape: %s, depth: %s, additional_fields: %s, restriction: %s)', self.folders, self.account, shape, depth, additional_fields, restriction.q if restriction else None, ) items = FindItem(account=self.account, folders=self.folders, chunk_size=page_size).call( additional_fields=additional_fields, restriction=restriction, order_fields=order_fields, shape=shape, query_string=query_string, depth=depth, calendar_view=calendar_view, max_items=calendar_view.max_items if calendar_view else max_items, offset=offset, ) if shape == ID_ONLY and additional_fields is None: for i in items: yield i if isinstance(i, Exception) else Item.id_from_xml(i) else: for i in items: if isinstance(i, Exception): yield i else: yield Folder.item_model_from_tag(i.tag).from_xml(elem=i, account=self.account)
python
def find_items(self, q, shape=ID_ONLY, depth=SHALLOW, additional_fields=None, order_fields=None, calendar_view=None, page_size=None, max_items=None, offset=0): """ Private method to call the FindItem service :param q: a Q instance containing any restrictions :param shape: controls whether to return (id, chanegkey) tuples or Item objects. If additional_fields is non-null, we always return Item objects. :param depth: controls the whether to return soft-deleted items or not. :param additional_fields: the extra properties we want on the return objects. Default is no properties. Be aware that complex fields can only be fetched with fetch() (i.e. the GetItem service). :param order_fields: the SortOrder fields, if any :param calendar_view: a CalendarView instance, if any :param page_size: the requested number of items per page :param max_items: the max number of items to return :param offset: the offset relative to the first item in the item collection :return: a generator for the returned item IDs or items """ if shape not in SHAPE_CHOICES: raise ValueError("'shape' %s must be one of %s" % (shape, SHAPE_CHOICES)) if depth not in ITEM_TRAVERSAL_CHOICES: raise ValueError("'depth' %s must be one of %s" % (depth, ITEM_TRAVERSAL_CHOICES)) if not self.folders: log.debug('Folder list is empty') return if additional_fields: for f in additional_fields: self.validate_item_field(field=f) for f in additional_fields: if f.field.is_complex: raise ValueError("find_items() does not support field '%s'. Use fetch() instead" % f.field.name) if calendar_view is not None and not isinstance(calendar_view, CalendarView): raise ValueError("'calendar_view' %s must be a CalendarView instance" % calendar_view) # Build up any restrictions if q.is_empty(): restriction = None query_string = None elif q.query_string: restriction = None query_string = Restriction(q, folders=self.folders, applies_to=Restriction.ITEMS) else: restriction = Restriction(q, folders=self.folders, applies_to=Restriction.ITEMS) query_string = None log.debug( 'Finding %s items in folders %s (shape: %s, depth: %s, additional_fields: %s, restriction: %s)', self.folders, self.account, shape, depth, additional_fields, restriction.q if restriction else None, ) items = FindItem(account=self.account, folders=self.folders, chunk_size=page_size).call( additional_fields=additional_fields, restriction=restriction, order_fields=order_fields, shape=shape, query_string=query_string, depth=depth, calendar_view=calendar_view, max_items=calendar_view.max_items if calendar_view else max_items, offset=offset, ) if shape == ID_ONLY and additional_fields is None: for i in items: yield i if isinstance(i, Exception) else Item.id_from_xml(i) else: for i in items: if isinstance(i, Exception): yield i else: yield Folder.item_model_from_tag(i.tag).from_xml(elem=i, account=self.account)
[ "def", "find_items", "(", "self", ",", "q", ",", "shape", "=", "ID_ONLY", ",", "depth", "=", "SHALLOW", ",", "additional_fields", "=", "None", ",", "order_fields", "=", "None", ",", "calendar_view", "=", "None", ",", "page_size", "=", "None", ",", "max_i...
Private method to call the FindItem service :param q: a Q instance containing any restrictions :param shape: controls whether to return (id, chanegkey) tuples or Item objects. If additional_fields is non-null, we always return Item objects. :param depth: controls the whether to return soft-deleted items or not. :param additional_fields: the extra properties we want on the return objects. Default is no properties. Be aware that complex fields can only be fetched with fetch() (i.e. the GetItem service). :param order_fields: the SortOrder fields, if any :param calendar_view: a CalendarView instance, if any :param page_size: the requested number of items per page :param max_items: the max number of items to return :param offset: the offset relative to the first item in the item collection :return: a generator for the returned item IDs or items
[ "Private", "method", "to", "call", "the", "FindItem", "service" ]
736347b337c239fcd6d592db5b29e819f753c1ba
https://github.com/ecederstrand/exchangelib/blob/736347b337c239fcd6d592db5b29e819f753c1ba/exchangelib/folders.py#L185-L257
train
223,156
ecederstrand/exchangelib
exchangelib/folders.py
RootOfHierarchy.get_distinguished
def get_distinguished(cls, account): """Gets the distinguished folder for this folder class""" if not cls.DISTINGUISHED_FOLDER_ID: raise ValueError('Class %s must have a DISTINGUISHED_FOLDER_ID value' % cls) folders = list(FolderCollection( account=account, folders=[cls(account=account, name=cls.DISTINGUISHED_FOLDER_ID, is_distinguished=True)] ).get_folders() ) if not folders: raise ErrorFolderNotFound('Could not find distinguished folder %s' % cls.DISTINGUISHED_FOLDER_ID) if len(folders) != 1: raise ValueError('Expected result length 1, but got %s' % folders) folder = folders[0] if isinstance(folder, Exception): raise folder if folder.__class__ != cls: raise ValueError("Expected 'folder' %r to be a %s instance" % (folder, cls)) return folder
python
def get_distinguished(cls, account): """Gets the distinguished folder for this folder class""" if not cls.DISTINGUISHED_FOLDER_ID: raise ValueError('Class %s must have a DISTINGUISHED_FOLDER_ID value' % cls) folders = list(FolderCollection( account=account, folders=[cls(account=account, name=cls.DISTINGUISHED_FOLDER_ID, is_distinguished=True)] ).get_folders() ) if not folders: raise ErrorFolderNotFound('Could not find distinguished folder %s' % cls.DISTINGUISHED_FOLDER_ID) if len(folders) != 1: raise ValueError('Expected result length 1, but got %s' % folders) folder = folders[0] if isinstance(folder, Exception): raise folder if folder.__class__ != cls: raise ValueError("Expected 'folder' %r to be a %s instance" % (folder, cls)) return folder
[ "def", "get_distinguished", "(", "cls", ",", "account", ")", ":", "if", "not", "cls", ".", "DISTINGUISHED_FOLDER_ID", ":", "raise", "ValueError", "(", "'Class %s must have a DISTINGUISHED_FOLDER_ID value'", "%", "cls", ")", "folders", "=", "list", "(", "FolderCollec...
Gets the distinguished folder for this folder class
[ "Gets", "the", "distinguished", "folder", "for", "this", "folder", "class" ]
736347b337c239fcd6d592db5b29e819f753c1ba
https://github.com/ecederstrand/exchangelib/blob/736347b337c239fcd6d592db5b29e819f753c1ba/exchangelib/folders.py#L1489-L1507
train
223,157
ecederstrand/exchangelib
exchangelib/folders.py
RootOfHierarchy.folder_cls_from_folder_name
def folder_cls_from_folder_name(cls, folder_name, locale): """Returns the folder class that matches a localized folder name. locale is a string, e.g. 'da_DK' """ for folder_cls in cls.WELLKNOWN_FOLDERS + NON_DELETEABLE_FOLDERS: if folder_name.lower() in folder_cls.localized_names(locale): return folder_cls raise KeyError()
python
def folder_cls_from_folder_name(cls, folder_name, locale): """Returns the folder class that matches a localized folder name. locale is a string, e.g. 'da_DK' """ for folder_cls in cls.WELLKNOWN_FOLDERS + NON_DELETEABLE_FOLDERS: if folder_name.lower() in folder_cls.localized_names(locale): return folder_cls raise KeyError()
[ "def", "folder_cls_from_folder_name", "(", "cls", ",", "folder_name", ",", "locale", ")", ":", "for", "folder_cls", "in", "cls", ".", "WELLKNOWN_FOLDERS", "+", "NON_DELETEABLE_FOLDERS", ":", "if", "folder_name", ".", "lower", "(", ")", "in", "folder_cls", ".", ...
Returns the folder class that matches a localized folder name. locale is a string, e.g. 'da_DK'
[ "Returns", "the", "folder", "class", "that", "matches", "a", "localized", "folder", "name", "." ]
736347b337c239fcd6d592db5b29e819f753c1ba
https://github.com/ecederstrand/exchangelib/blob/736347b337c239fcd6d592db5b29e819f753c1ba/exchangelib/folders.py#L1594-L1602
train
223,158
ecederstrand/exchangelib
exchangelib/items.py
RegisterMixIn.register
def register(cls, attr_name, attr_cls): """ Register a custom extended property in this item class so they can be accessed just like any other attribute """ if not cls.INSERT_AFTER_FIELD: raise ValueError('Class %s is missing INSERT_AFTER_FIELD value' % cls) try: cls.get_field_by_fieldname(attr_name) except InvalidField: pass else: raise ValueError("'%s' is already registered" % attr_name) if not issubclass(attr_cls, ExtendedProperty): raise ValueError("%r must be a subclass of ExtendedProperty" % attr_cls) # Check if class attributes are properly defined attr_cls.validate_cls() # ExtendedProperty is not a real field, but a placeholder in the fields list. See # https://msdn.microsoft.com/en-us/library/office/aa580790(v=exchg.150).aspx # # Find the correct index for the new extended property, and insert. field = ExtendedPropertyField(attr_name, value_cls=attr_cls) cls.add_field(field, insert_after=cls.INSERT_AFTER_FIELD)
python
def register(cls, attr_name, attr_cls): """ Register a custom extended property in this item class so they can be accessed just like any other attribute """ if not cls.INSERT_AFTER_FIELD: raise ValueError('Class %s is missing INSERT_AFTER_FIELD value' % cls) try: cls.get_field_by_fieldname(attr_name) except InvalidField: pass else: raise ValueError("'%s' is already registered" % attr_name) if not issubclass(attr_cls, ExtendedProperty): raise ValueError("%r must be a subclass of ExtendedProperty" % attr_cls) # Check if class attributes are properly defined attr_cls.validate_cls() # ExtendedProperty is not a real field, but a placeholder in the fields list. See # https://msdn.microsoft.com/en-us/library/office/aa580790(v=exchg.150).aspx # # Find the correct index for the new extended property, and insert. field = ExtendedPropertyField(attr_name, value_cls=attr_cls) cls.add_field(field, insert_after=cls.INSERT_AFTER_FIELD)
[ "def", "register", "(", "cls", ",", "attr_name", ",", "attr_cls", ")", ":", "if", "not", "cls", ".", "INSERT_AFTER_FIELD", ":", "raise", "ValueError", "(", "'Class %s is missing INSERT_AFTER_FIELD value'", "%", "cls", ")", "try", ":", "cls", ".", "get_field_by_f...
Register a custom extended property in this item class so they can be accessed just like any other attribute
[ "Register", "a", "custom", "extended", "property", "in", "this", "item", "class", "so", "they", "can", "be", "accessed", "just", "like", "any", "other", "attribute" ]
736347b337c239fcd6d592db5b29e819f753c1ba
https://github.com/ecederstrand/exchangelib/blob/736347b337c239fcd6d592db5b29e819f753c1ba/exchangelib/items.py#L92-L113
train
223,159
ecederstrand/exchangelib
exchangelib/items.py
Item.attach
def attach(self, attachments): """Add an attachment, or a list of attachments, to this item. If the item has already been saved, the attachments will be created on the server immediately. If the item has not yet been saved, the attachments will be created on the server the item is saved. Adding attachments to an existing item will update the changekey of the item. """ if not is_iterable(attachments, generators_allowed=True): attachments = [attachments] for a in attachments: if not a.parent_item: a.parent_item = self if self.id and not a.attachment_id: # Already saved object. Attach the attachment server-side now a.attach() if a not in self.attachments: self.attachments.append(a)
python
def attach(self, attachments): """Add an attachment, or a list of attachments, to this item. If the item has already been saved, the attachments will be created on the server immediately. If the item has not yet been saved, the attachments will be created on the server the item is saved. Adding attachments to an existing item will update the changekey of the item. """ if not is_iterable(attachments, generators_allowed=True): attachments = [attachments] for a in attachments: if not a.parent_item: a.parent_item = self if self.id and not a.attachment_id: # Already saved object. Attach the attachment server-side now a.attach() if a not in self.attachments: self.attachments.append(a)
[ "def", "attach", "(", "self", ",", "attachments", ")", ":", "if", "not", "is_iterable", "(", "attachments", ",", "generators_allowed", "=", "True", ")", ":", "attachments", "=", "[", "attachments", "]", "for", "a", "in", "attachments", ":", "if", "not", ...
Add an attachment, or a list of attachments, to this item. If the item has already been saved, the attachments will be created on the server immediately. If the item has not yet been saved, the attachments will be created on the server the item is saved. Adding attachments to an existing item will update the changekey of the item.
[ "Add", "an", "attachment", "or", "a", "list", "of", "attachments", "to", "this", "item", ".", "If", "the", "item", "has", "already", "been", "saved", "the", "attachments", "will", "be", "created", "on", "the", "server", "immediately", ".", "If", "the", "...
736347b337c239fcd6d592db5b29e819f753c1ba
https://github.com/ecederstrand/exchangelib/blob/736347b337c239fcd6d592db5b29e819f753c1ba/exchangelib/items.py#L426-L442
train
223,160
ecederstrand/exchangelib
exchangelib/items.py
Item.detach
def detach(self, attachments): """Remove an attachment, or a list of attachments, from this item. If the item has already been saved, the attachments will be deleted on the server immediately. If the item has not yet been saved, the attachments will simply not be created on the server the item is saved. Removing attachments from an existing item will update the changekey of the item. """ if not is_iterable(attachments, generators_allowed=True): attachments = [attachments] for a in attachments: if a.parent_item is not self: raise ValueError('Attachment does not belong to this item') if self.id: # Item is already created. Detach the attachment server-side now a.detach() if a in self.attachments: self.attachments.remove(a)
python
def detach(self, attachments): """Remove an attachment, or a list of attachments, from this item. If the item has already been saved, the attachments will be deleted on the server immediately. If the item has not yet been saved, the attachments will simply not be created on the server the item is saved. Removing attachments from an existing item will update the changekey of the item. """ if not is_iterable(attachments, generators_allowed=True): attachments = [attachments] for a in attachments: if a.parent_item is not self: raise ValueError('Attachment does not belong to this item') if self.id: # Item is already created. Detach the attachment server-side now a.detach() if a in self.attachments: self.attachments.remove(a)
[ "def", "detach", "(", "self", ",", "attachments", ")", ":", "if", "not", "is_iterable", "(", "attachments", ",", "generators_allowed", "=", "True", ")", ":", "attachments", "=", "[", "attachments", "]", "for", "a", "in", "attachments", ":", "if", "a", "....
Remove an attachment, or a list of attachments, from this item. If the item has already been saved, the attachments will be deleted on the server immediately. If the item has not yet been saved, the attachments will simply not be created on the server the item is saved. Removing attachments from an existing item will update the changekey of the item.
[ "Remove", "an", "attachment", "or", "a", "list", "of", "attachments", "from", "this", "item", ".", "If", "the", "item", "has", "already", "been", "saved", "the", "attachments", "will", "be", "deleted", "on", "the", "server", "immediately", ".", "If", "the"...
736347b337c239fcd6d592db5b29e819f753c1ba
https://github.com/ecederstrand/exchangelib/blob/736347b337c239fcd6d592db5b29e819f753c1ba/exchangelib/items.py#L444-L460
train
223,161
ecederstrand/exchangelib
exchangelib/credentials.py
ServiceAccount.back_off_until
def back_off_until(self): """Returns the back off value as a datetime. Resets the current back off value if it has expired.""" if self._back_off_until is None: return None with self._back_off_lock: if self._back_off_until is None: return None if self._back_off_until < datetime.datetime.now(): self._back_off_until = None # The backoff value has expired. Reset return None return self._back_off_until
python
def back_off_until(self): """Returns the back off value as a datetime. Resets the current back off value if it has expired.""" if self._back_off_until is None: return None with self._back_off_lock: if self._back_off_until is None: return None if self._back_off_until < datetime.datetime.now(): self._back_off_until = None # The backoff value has expired. Reset return None return self._back_off_until
[ "def", "back_off_until", "(", "self", ")", ":", "if", "self", ".", "_back_off_until", "is", "None", ":", "return", "None", "with", "self", ".", "_back_off_lock", ":", "if", "self", ".", "_back_off_until", "is", "None", ":", "return", "None", "if", "self", ...
Returns the back off value as a datetime. Resets the current back off value if it has expired.
[ "Returns", "the", "back", "off", "value", "as", "a", "datetime", ".", "Resets", "the", "current", "back", "off", "value", "if", "it", "has", "expired", "." ]
736347b337c239fcd6d592db5b29e819f753c1ba
https://github.com/ecederstrand/exchangelib/blob/736347b337c239fcd6d592db5b29e819f753c1ba/exchangelib/credentials.py#L103-L113
train
223,162
ecederstrand/exchangelib
exchangelib/winzone.py
generate_map
def generate_map(timeout=10): """ Helper method to update the map if the CLDR database is updated """ r = requests.get(CLDR_WINZONE_URL, timeout=timeout) if r.status_code != 200: raise ValueError('Unexpected response: %s' % r) tz_map = {} for e in to_xml(r.content).find('windowsZones').find('mapTimezones').findall('mapZone'): for location in e.get('type').split(' '): if e.get('territory') == DEFAULT_TERRITORY or location not in tz_map: # Prefer default territory. This is so MS_TIMEZONE_TO_PYTZ_MAP maps from MS timezone ID back to the # "preferred" region/location timezone name. tz_map[location] = e.get('other'), e.get('territory') return tz_map
python
def generate_map(timeout=10): """ Helper method to update the map if the CLDR database is updated """ r = requests.get(CLDR_WINZONE_URL, timeout=timeout) if r.status_code != 200: raise ValueError('Unexpected response: %s' % r) tz_map = {} for e in to_xml(r.content).find('windowsZones').find('mapTimezones').findall('mapZone'): for location in e.get('type').split(' '): if e.get('territory') == DEFAULT_TERRITORY or location not in tz_map: # Prefer default territory. This is so MS_TIMEZONE_TO_PYTZ_MAP maps from MS timezone ID back to the # "preferred" region/location timezone name. tz_map[location] = e.get('other'), e.get('territory') return tz_map
[ "def", "generate_map", "(", "timeout", "=", "10", ")", ":", "r", "=", "requests", ".", "get", "(", "CLDR_WINZONE_URL", ",", "timeout", "=", "timeout", ")", "if", "r", ".", "status_code", "!=", "200", ":", "raise", "ValueError", "(", "'Unexpected response: ...
Helper method to update the map if the CLDR database is updated
[ "Helper", "method", "to", "update", "the", "map", "if", "the", "CLDR", "database", "is", "updated" ]
736347b337c239fcd6d592db5b29e819f753c1ba
https://github.com/ecederstrand/exchangelib/blob/736347b337c239fcd6d592db5b29e819f753c1ba/exchangelib/winzone.py#L11-L23
train
223,163
tanghaibao/goatools
scripts/compare_gos.py
run
def run(): """Compare two or more sets of GO IDs. Best done using sections.""" obj = CompareGOsCli() obj.write(obj.kws.get('xlsx'), obj.kws.get('ofile'), obj.kws.get('verbose', False))
python
def run(): """Compare two or more sets of GO IDs. Best done using sections.""" obj = CompareGOsCli() obj.write(obj.kws.get('xlsx'), obj.kws.get('ofile'), obj.kws.get('verbose', False))
[ "def", "run", "(", ")", ":", "obj", "=", "CompareGOsCli", "(", ")", "obj", ".", "write", "(", "obj", ".", "kws", ".", "get", "(", "'xlsx'", ")", ",", "obj", ".", "kws", ".", "get", "(", "'ofile'", ")", ",", "obj", ".", "kws", ".", "get", "(",...
Compare two or more sets of GO IDs. Best done using sections.
[ "Compare", "two", "or", "more", "sets", "of", "GO", "IDs", ".", "Best", "done", "using", "sections", "." ]
407682e573a108864a79031f8ca19ee3bf377626
https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/scripts/compare_gos.py#L10-L13
train
223,164
tanghaibao/goatools
goatools/grouper/sorter_gos.py
SorterGoIds.sortby
def sortby(self, ntd): """Return function for sorting.""" if 'reldepth' in self.grprobj.gosubdag.prt_attr['flds']: return [ntd.NS, -1*ntd.dcnt, ntd.reldepth] else: return [ntd.NS, -1*ntd.dcnt, ntd.depth]
python
def sortby(self, ntd): """Return function for sorting.""" if 'reldepth' in self.grprobj.gosubdag.prt_attr['flds']: return [ntd.NS, -1*ntd.dcnt, ntd.reldepth] else: return [ntd.NS, -1*ntd.dcnt, ntd.depth]
[ "def", "sortby", "(", "self", ",", "ntd", ")", ":", "if", "'reldepth'", "in", "self", ".", "grprobj", ".", "gosubdag", ".", "prt_attr", "[", "'flds'", "]", ":", "return", "[", "ntd", ".", "NS", ",", "-", "1", "*", "ntd", ".", "dcnt", ",", "ntd", ...
Return function for sorting.
[ "Return", "function", "for", "sorting", "." ]
407682e573a108864a79031f8ca19ee3bf377626
https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/grouper/sorter_gos.py#L33-L38
train
223,165
tanghaibao/goatools
goatools/grouper/sorter_gos.py
SorterGoIds.get_nts_sorted
def get_nts_sorted(self, hdrgo_prt, hdrgos, hdrgo_sort): """Return a flat list of grouped and sorted GO terms.""" nts_flat = [] self.get_sorted_hdrgo2usrgos(hdrgos, nts_flat, hdrgo_prt, hdrgo_sort) return nts_flat
python
def get_nts_sorted(self, hdrgo_prt, hdrgos, hdrgo_sort): """Return a flat list of grouped and sorted GO terms.""" nts_flat = [] self.get_sorted_hdrgo2usrgos(hdrgos, nts_flat, hdrgo_prt, hdrgo_sort) return nts_flat
[ "def", "get_nts_sorted", "(", "self", ",", "hdrgo_prt", ",", "hdrgos", ",", "hdrgo_sort", ")", ":", "nts_flat", "=", "[", "]", "self", ".", "get_sorted_hdrgo2usrgos", "(", "hdrgos", ",", "nts_flat", ",", "hdrgo_prt", ",", "hdrgo_sort", ")", "return", "nts_fl...
Return a flat list of grouped and sorted GO terms.
[ "Return", "a", "flat", "list", "of", "grouped", "and", "sorted", "GO", "terms", "." ]
407682e573a108864a79031f8ca19ee3bf377626
https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/grouper/sorter_gos.py#L64-L68
train
223,166
tanghaibao/goatools
goatools/grouper/sorter_gos.py
SorterGoIds.get_sorted_hdrgo2usrgos
def get_sorted_hdrgo2usrgos(self, hdrgos, flat_list=None, hdrgo_prt=True, hdrgo_sort=True): """Return GO IDs sorting using go2nt's namedtuple.""" # Return user-specfied sort or default sort of header and user GO IDs sorted_hdrgos_usrgos = [] h2u_get = self.grprobj.hdrgo2usrgos.get # Sort GO group headers using GO info in go2nt hdr_go2nt = self._get_go2nt(hdrgos) if hdrgo_sort is True: hdr_go2nt = sorted(hdr_go2nt.items(), key=lambda t: self.hdrgo_sortby(t[1])) for hdrgo_id, hdrgo_nt in hdr_go2nt: if flat_list is not None: if hdrgo_prt or hdrgo_id in self.grprobj.usrgos: flat_list.append(hdrgo_nt) # Sort user GOs which are under the current GO header usrgos_unsorted = h2u_get(hdrgo_id) if usrgos_unsorted: usrgo2nt = self._get_go2nt(usrgos_unsorted) usrgont_sorted = sorted(usrgo2nt.items(), key=lambda t: self.usrgo_sortby(t[1])) usrgos_sorted, usrnts_sorted = zip(*usrgont_sorted) if flat_list is not None: flat_list.extend(usrnts_sorted) sorted_hdrgos_usrgos.append((hdrgo_id, usrgos_sorted)) else: sorted_hdrgos_usrgos.append((hdrgo_id, [])) return cx.OrderedDict(sorted_hdrgos_usrgos)
python
def get_sorted_hdrgo2usrgos(self, hdrgos, flat_list=None, hdrgo_prt=True, hdrgo_sort=True): """Return GO IDs sorting using go2nt's namedtuple.""" # Return user-specfied sort or default sort of header and user GO IDs sorted_hdrgos_usrgos = [] h2u_get = self.grprobj.hdrgo2usrgos.get # Sort GO group headers using GO info in go2nt hdr_go2nt = self._get_go2nt(hdrgos) if hdrgo_sort is True: hdr_go2nt = sorted(hdr_go2nt.items(), key=lambda t: self.hdrgo_sortby(t[1])) for hdrgo_id, hdrgo_nt in hdr_go2nt: if flat_list is not None: if hdrgo_prt or hdrgo_id in self.grprobj.usrgos: flat_list.append(hdrgo_nt) # Sort user GOs which are under the current GO header usrgos_unsorted = h2u_get(hdrgo_id) if usrgos_unsorted: usrgo2nt = self._get_go2nt(usrgos_unsorted) usrgont_sorted = sorted(usrgo2nt.items(), key=lambda t: self.usrgo_sortby(t[1])) usrgos_sorted, usrnts_sorted = zip(*usrgont_sorted) if flat_list is not None: flat_list.extend(usrnts_sorted) sorted_hdrgos_usrgos.append((hdrgo_id, usrgos_sorted)) else: sorted_hdrgos_usrgos.append((hdrgo_id, [])) return cx.OrderedDict(sorted_hdrgos_usrgos)
[ "def", "get_sorted_hdrgo2usrgos", "(", "self", ",", "hdrgos", ",", "flat_list", "=", "None", ",", "hdrgo_prt", "=", "True", ",", "hdrgo_sort", "=", "True", ")", ":", "# Return user-specfied sort or default sort of header and user GO IDs", "sorted_hdrgos_usrgos", "=", "[...
Return GO IDs sorting using go2nt's namedtuple.
[ "Return", "GO", "IDs", "sorting", "using", "go2nt", "s", "namedtuple", "." ]
407682e573a108864a79031f8ca19ee3bf377626
https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/grouper/sorter_gos.py#L70-L94
train
223,167
tanghaibao/goatools
goatools/grouper/sorter_gos.py
SorterGoIds._get_go2nt
def _get_go2nt(self, goids): """Get go2nt for given goids.""" go2nt_all = self.grprobj.go2nt return {go:go2nt_all[go] for go in goids}
python
def _get_go2nt(self, goids): """Get go2nt for given goids.""" go2nt_all = self.grprobj.go2nt return {go:go2nt_all[go] for go in goids}
[ "def", "_get_go2nt", "(", "self", ",", "goids", ")", ":", "go2nt_all", "=", "self", ".", "grprobj", ".", "go2nt", "return", "{", "go", ":", "go2nt_all", "[", "go", "]", "for", "go", "in", "goids", "}" ]
Get go2nt for given goids.
[ "Get", "go2nt", "for", "given", "goids", "." ]
407682e573a108864a79031f8ca19ee3bf377626
https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/grouper/sorter_gos.py#L96-L99
train
223,168
tanghaibao/goatools
goatools/grouper/sorter_gos.py
SorterGoIds._init_hdrgo_sortby
def _init_hdrgo_sortby(self, hdrgo_sortby, sortby): """Initialize header sort function.""" if hdrgo_sortby is not None: return hdrgo_sortby if sortby is not None: return sortby return self.sortby
python
def _init_hdrgo_sortby(self, hdrgo_sortby, sortby): """Initialize header sort function.""" if hdrgo_sortby is not None: return hdrgo_sortby if sortby is not None: return sortby return self.sortby
[ "def", "_init_hdrgo_sortby", "(", "self", ",", "hdrgo_sortby", ",", "sortby", ")", ":", "if", "hdrgo_sortby", "is", "not", "None", ":", "return", "hdrgo_sortby", "if", "sortby", "is", "not", "None", ":", "return", "sortby", "return", "self", ".", "sortby" ]
Initialize header sort function.
[ "Initialize", "header", "sort", "function", "." ]
407682e573a108864a79031f8ca19ee3bf377626
https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/grouper/sorter_gos.py#L101-L107
train
223,169
tanghaibao/goatools
goatools/godag_plot.py
plot_goid2goobj
def plot_goid2goobj(fout_png, goid2goobj, *args, **kws): """Given a dict containing GO id and its goobj, create a plot of paths from GO ids.""" engine = kws['engine'] if 'engine' in kws else 'pydot' godagsmall = OboToGoDagSmall(goid2goobj=goid2goobj).godag godagplot = GODagSmallPlot(godagsmall, *args, **kws) godagplot.plt(fout_png, engine)
python
def plot_goid2goobj(fout_png, goid2goobj, *args, **kws): """Given a dict containing GO id and its goobj, create a plot of paths from GO ids.""" engine = kws['engine'] if 'engine' in kws else 'pydot' godagsmall = OboToGoDagSmall(goid2goobj=goid2goobj).godag godagplot = GODagSmallPlot(godagsmall, *args, **kws) godagplot.plt(fout_png, engine)
[ "def", "plot_goid2goobj", "(", "fout_png", ",", "goid2goobj", ",", "*", "args", ",", "*", "*", "kws", ")", ":", "engine", "=", "kws", "[", "'engine'", "]", "if", "'engine'", "in", "kws", "else", "'pydot'", "godagsmall", "=", "OboToGoDagSmall", "(", "goid...
Given a dict containing GO id and its goobj, create a plot of paths from GO ids.
[ "Given", "a", "dict", "containing", "GO", "id", "and", "its", "goobj", "create", "a", "plot", "of", "paths", "from", "GO", "ids", "." ]
407682e573a108864a79031f8ca19ee3bf377626
https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/godag_plot.py#L19-L24
train
223,170
tanghaibao/goatools
goatools/godag_plot.py
GODagSmallPlot._init_study_items_max
def _init_study_items_max(self): """User can limit the number of genes printed in a GO term.""" if self.study_items is None: return None if self.study_items is True: return None if isinstance(self.study_items, int): return self.study_items return None
python
def _init_study_items_max(self): """User can limit the number of genes printed in a GO term.""" if self.study_items is None: return None if self.study_items is True: return None if isinstance(self.study_items, int): return self.study_items return None
[ "def", "_init_study_items_max", "(", "self", ")", ":", "if", "self", ".", "study_items", "is", "None", ":", "return", "None", "if", "self", ".", "study_items", "is", "True", ":", "return", "None", "if", "isinstance", "(", "self", ".", "study_items", ",", ...
User can limit the number of genes printed in a GO term.
[ "User", "can", "limit", "the", "number", "of", "genes", "printed", "in", "a", "GO", "term", "." ]
407682e573a108864a79031f8ca19ee3bf377626
https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/godag_plot.py#L105-L113
train
223,171
tanghaibao/goatools
goatools/godag_plot.py
GODagSmallPlot._init_go2res
def _init_go2res(**kws): """Initialize GOEA results.""" if 'goea_results' in kws: return {res.GO:res for res in kws['goea_results']} if 'go2nt' in kws: return kws['go2nt']
python
def _init_go2res(**kws): """Initialize GOEA results.""" if 'goea_results' in kws: return {res.GO:res for res in kws['goea_results']} if 'go2nt' in kws: return kws['go2nt']
[ "def", "_init_go2res", "(", "*", "*", "kws", ")", ":", "if", "'goea_results'", "in", "kws", ":", "return", "{", "res", ".", "GO", ":", "res", "for", "res", "in", "kws", "[", "'goea_results'", "]", "}", "if", "'go2nt'", "in", "kws", ":", "return", "...
Initialize GOEA results.
[ "Initialize", "GOEA", "results", "." ]
407682e573a108864a79031f8ca19ee3bf377626
https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/godag_plot.py#L116-L121
train
223,172
tanghaibao/goatools
goatools/godag_plot.py
GODagSmallPlot._get_pydot
def _get_pydot(self): """Return pydot package. Load pydot, if necessary.""" if self.pydot: return self.pydot self.pydot = __import__("pydot") return self.pydot
python
def _get_pydot(self): """Return pydot package. Load pydot, if necessary.""" if self.pydot: return self.pydot self.pydot = __import__("pydot") return self.pydot
[ "def", "_get_pydot", "(", "self", ")", ":", "if", "self", ".", "pydot", ":", "return", "self", ".", "pydot", "self", ".", "pydot", "=", "__import__", "(", "\"pydot\"", ")", "return", "self", ".", "pydot" ]
Return pydot package. Load pydot, if necessary.
[ "Return", "pydot", "package", ".", "Load", "pydot", "if", "necessary", "." ]
407682e573a108864a79031f8ca19ee3bf377626
https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/godag_plot.py#L217-L222
train
223,173
tanghaibao/goatools
goatools/wr_tbl.py
wr_xlsx
def wr_xlsx(fout_xlsx, data_xlsx, **kws): """Write a spreadsheet into a xlsx file.""" from goatools.wr_tbl_class import WrXlsx # optional keyword args: fld2col_widths hdrs prt_if sort_by fld2fmt prt_flds items_str = kws.get("items", "items") if "items" not in kws else kws["items"] if data_xlsx: # Open xlsx file xlsxobj = WrXlsx(fout_xlsx, data_xlsx[0]._fields, **kws) worksheet = xlsxobj.add_worksheet() # Write title (optional) and headers. row_idx = xlsxobj.wr_title(worksheet) row_idx = xlsxobj.wr_hdrs(worksheet, row_idx) row_idx_data0 = row_idx # Write data row_idx = xlsxobj.wr_data(data_xlsx, row_idx, worksheet) # Close xlsx file xlsxobj.workbook.close() sys.stdout.write(" {N:>5} {ITEMS} WROTE: {FOUT}\n".format( N=row_idx-row_idx_data0, ITEMS=items_str, FOUT=fout_xlsx)) else: sys.stdout.write(" 0 {ITEMS}. NOT WRITING {FOUT}\n".format( ITEMS=items_str, FOUT=fout_xlsx))
python
def wr_xlsx(fout_xlsx, data_xlsx, **kws): """Write a spreadsheet into a xlsx file.""" from goatools.wr_tbl_class import WrXlsx # optional keyword args: fld2col_widths hdrs prt_if sort_by fld2fmt prt_flds items_str = kws.get("items", "items") if "items" not in kws else kws["items"] if data_xlsx: # Open xlsx file xlsxobj = WrXlsx(fout_xlsx, data_xlsx[0]._fields, **kws) worksheet = xlsxobj.add_worksheet() # Write title (optional) and headers. row_idx = xlsxobj.wr_title(worksheet) row_idx = xlsxobj.wr_hdrs(worksheet, row_idx) row_idx_data0 = row_idx # Write data row_idx = xlsxobj.wr_data(data_xlsx, row_idx, worksheet) # Close xlsx file xlsxobj.workbook.close() sys.stdout.write(" {N:>5} {ITEMS} WROTE: {FOUT}\n".format( N=row_idx-row_idx_data0, ITEMS=items_str, FOUT=fout_xlsx)) else: sys.stdout.write(" 0 {ITEMS}. NOT WRITING {FOUT}\n".format( ITEMS=items_str, FOUT=fout_xlsx))
[ "def", "wr_xlsx", "(", "fout_xlsx", ",", "data_xlsx", ",", "*", "*", "kws", ")", ":", "from", "goatools", ".", "wr_tbl_class", "import", "WrXlsx", "# optional keyword args: fld2col_widths hdrs prt_if sort_by fld2fmt prt_flds", "items_str", "=", "kws", ".", "get", "(",...
Write a spreadsheet into a xlsx file.
[ "Write", "a", "spreadsheet", "into", "a", "xlsx", "file", "." ]
407682e573a108864a79031f8ca19ee3bf377626
https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/wr_tbl.py#L63-L84
train
223,174
tanghaibao/goatools
goatools/wr_tbl.py
wr_xlsx_sections
def wr_xlsx_sections(fout_xlsx, xlsx_data, **kws): """Write xlsx file containing section names followed by lines of namedtuple data.""" from goatools.wr_tbl_class import WrXlsx items_str = "items" if "items" not in kws else kws["items"] prt_hdr_min = 10 num_items = 0 if xlsx_data: # Basic data checks assert len(xlsx_data[0]) == 2, "wr_xlsx_sections EXPECTED: [(section, nts), ..." assert xlsx_data[0][1], \ "wr_xlsx_sections EXPECTED SECTION({S}) LIST TO HAVE DATA".format(S=xlsx_data[0][0]) # Open xlsx file and write title (optional) and headers. xlsxobj = WrXlsx(fout_xlsx, xlsx_data[0][1][0]._fields, **kws) worksheet = xlsxobj.add_worksheet() row_idx = xlsxobj.wr_title(worksheet) hdrs_wrote = False # Write data for section_text, data_nts in xlsx_data: num_items += len(data_nts) fmt = xlsxobj.wbfmtobj.get_fmt_section() row_idx = xlsxobj.wr_row_mergeall(worksheet, section_text, fmt, row_idx) if hdrs_wrote is False or len(data_nts) > prt_hdr_min: row_idx = xlsxobj.wr_hdrs(worksheet, row_idx) hdrs_wrote = True row_idx = xlsxobj.wr_data(data_nts, row_idx, worksheet) # Close xlsx file xlsxobj.workbook.close() sys.stdout.write(" {N:>5} {ITEMS} WROTE: {FOUT} ({S} sections)\n".format( N=num_items, ITEMS=items_str, FOUT=fout_xlsx, S=len(xlsx_data))) else: sys.stdout.write(" 0 {ITEMS}. NOT WRITING {FOUT}\n".format( ITEMS=items_str, FOUT=fout_xlsx))
python
def wr_xlsx_sections(fout_xlsx, xlsx_data, **kws): """Write xlsx file containing section names followed by lines of namedtuple data.""" from goatools.wr_tbl_class import WrXlsx items_str = "items" if "items" not in kws else kws["items"] prt_hdr_min = 10 num_items = 0 if xlsx_data: # Basic data checks assert len(xlsx_data[0]) == 2, "wr_xlsx_sections EXPECTED: [(section, nts), ..." assert xlsx_data[0][1], \ "wr_xlsx_sections EXPECTED SECTION({S}) LIST TO HAVE DATA".format(S=xlsx_data[0][0]) # Open xlsx file and write title (optional) and headers. xlsxobj = WrXlsx(fout_xlsx, xlsx_data[0][1][0]._fields, **kws) worksheet = xlsxobj.add_worksheet() row_idx = xlsxobj.wr_title(worksheet) hdrs_wrote = False # Write data for section_text, data_nts in xlsx_data: num_items += len(data_nts) fmt = xlsxobj.wbfmtobj.get_fmt_section() row_idx = xlsxobj.wr_row_mergeall(worksheet, section_text, fmt, row_idx) if hdrs_wrote is False or len(data_nts) > prt_hdr_min: row_idx = xlsxobj.wr_hdrs(worksheet, row_idx) hdrs_wrote = True row_idx = xlsxobj.wr_data(data_nts, row_idx, worksheet) # Close xlsx file xlsxobj.workbook.close() sys.stdout.write(" {N:>5} {ITEMS} WROTE: {FOUT} ({S} sections)\n".format( N=num_items, ITEMS=items_str, FOUT=fout_xlsx, S=len(xlsx_data))) else: sys.stdout.write(" 0 {ITEMS}. NOT WRITING {FOUT}\n".format( ITEMS=items_str, FOUT=fout_xlsx))
[ "def", "wr_xlsx_sections", "(", "fout_xlsx", ",", "xlsx_data", ",", "*", "*", "kws", ")", ":", "from", "goatools", ".", "wr_tbl_class", "import", "WrXlsx", "items_str", "=", "\"items\"", "if", "\"items\"", "not", "in", "kws", "else", "kws", "[", "\"items\"",...
Write xlsx file containing section names followed by lines of namedtuple data.
[ "Write", "xlsx", "file", "containing", "section", "names", "followed", "by", "lines", "of", "namedtuple", "data", "." ]
407682e573a108864a79031f8ca19ee3bf377626
https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/wr_tbl.py#L86-L117
train
223,175
tanghaibao/goatools
goatools/wr_tbl.py
wr_tsv
def wr_tsv(fout_tsv, tsv_data, **kws): """Write a file of tab-separated table data""" items_str = "items" if "items" not in kws else kws["items"] if tsv_data: ifstrm = sys.stdout if fout_tsv is None else open(fout_tsv, 'w') num_items = prt_tsv(ifstrm, tsv_data, **kws) if fout_tsv is not None: sys.stdout.write(" {N:>5} {ITEMS} WROTE: {FOUT}\n".format( N=num_items, ITEMS=items_str, FOUT=fout_tsv)) ifstrm.close() else: sys.stdout.write(" 0 {ITEMS}. NOT WRITING {FOUT}\n".format( ITEMS=items_str, FOUT=fout_tsv))
python
def wr_tsv(fout_tsv, tsv_data, **kws): """Write a file of tab-separated table data""" items_str = "items" if "items" not in kws else kws["items"] if tsv_data: ifstrm = sys.stdout if fout_tsv is None else open(fout_tsv, 'w') num_items = prt_tsv(ifstrm, tsv_data, **kws) if fout_tsv is not None: sys.stdout.write(" {N:>5} {ITEMS} WROTE: {FOUT}\n".format( N=num_items, ITEMS=items_str, FOUT=fout_tsv)) ifstrm.close() else: sys.stdout.write(" 0 {ITEMS}. NOT WRITING {FOUT}\n".format( ITEMS=items_str, FOUT=fout_tsv))
[ "def", "wr_tsv", "(", "fout_tsv", ",", "tsv_data", ",", "*", "*", "kws", ")", ":", "items_str", "=", "\"items\"", "if", "\"items\"", "not", "in", "kws", "else", "kws", "[", "\"items\"", "]", "if", "tsv_data", ":", "ifstrm", "=", "sys", ".", "stdout", ...
Write a file of tab-separated table data
[ "Write", "a", "file", "of", "tab", "-", "separated", "table", "data" ]
407682e573a108864a79031f8ca19ee3bf377626
https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/wr_tbl.py#L119-L131
train
223,176
tanghaibao/goatools
goatools/wr_tbl.py
prt_tsv_sections
def prt_tsv_sections(prt, tsv_data, **kws): """Write tsv file containing section names followed by lines of namedtuple data.""" prt_hdr_min = 10 # Print hdr on the 1st section and for any following 'large' sections num_items = 0 if tsv_data: # Basic data checks assert len(tsv_data[0]) == 2, "wr_tsv_sections EXPECTED: [(section, nts), ..." assert tsv_data[0][1], \ "wr_tsv_sections EXPECTED SECTION({S}) LIST TO HAVE DATA".format(S=tsv_data[0][0]) hdrs_wrote = False sep = "\t" if 'sep' not in kws else kws['sep'] prt_flds = kws['prt_flds'] if 'prt_flds' in kws else tsv_data[0]._fields fill = sep*(len(prt_flds) - 1) # Write data for section_text, data_nts in tsv_data: prt.write("{SEC}{FILL}\n".format(SEC=section_text, FILL=fill)) if hdrs_wrote is False or len(data_nts) > prt_hdr_min: prt_tsv_hdr(prt, data_nts, **kws) hdrs_wrote = True num_items += prt_tsv_dat(prt, data_nts, **kws) return num_items else: return 0
python
def prt_tsv_sections(prt, tsv_data, **kws): """Write tsv file containing section names followed by lines of namedtuple data.""" prt_hdr_min = 10 # Print hdr on the 1st section and for any following 'large' sections num_items = 0 if tsv_data: # Basic data checks assert len(tsv_data[0]) == 2, "wr_tsv_sections EXPECTED: [(section, nts), ..." assert tsv_data[0][1], \ "wr_tsv_sections EXPECTED SECTION({S}) LIST TO HAVE DATA".format(S=tsv_data[0][0]) hdrs_wrote = False sep = "\t" if 'sep' not in kws else kws['sep'] prt_flds = kws['prt_flds'] if 'prt_flds' in kws else tsv_data[0]._fields fill = sep*(len(prt_flds) - 1) # Write data for section_text, data_nts in tsv_data: prt.write("{SEC}{FILL}\n".format(SEC=section_text, FILL=fill)) if hdrs_wrote is False or len(data_nts) > prt_hdr_min: prt_tsv_hdr(prt, data_nts, **kws) hdrs_wrote = True num_items += prt_tsv_dat(prt, data_nts, **kws) return num_items else: return 0
[ "def", "prt_tsv_sections", "(", "prt", ",", "tsv_data", ",", "*", "*", "kws", ")", ":", "prt_hdr_min", "=", "10", "# Print hdr on the 1st section and for any following 'large' sections", "num_items", "=", "0", "if", "tsv_data", ":", "# Basic data checks", "assert", "l...
Write tsv file containing section names followed by lines of namedtuple data.
[ "Write", "tsv", "file", "containing", "section", "names", "followed", "by", "lines", "of", "namedtuple", "data", "." ]
407682e573a108864a79031f8ca19ee3bf377626
https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/wr_tbl.py#L133-L155
train
223,177
tanghaibao/goatools
goatools/wr_tbl.py
prt_tsv
def prt_tsv(prt, data_nts, **kws): """Print tab-separated table headers and data""" # User-controlled printing options prt_tsv_hdr(prt, data_nts, **kws) return prt_tsv_dat(prt, data_nts, **kws)
python
def prt_tsv(prt, data_nts, **kws): """Print tab-separated table headers and data""" # User-controlled printing options prt_tsv_hdr(prt, data_nts, **kws) return prt_tsv_dat(prt, data_nts, **kws)
[ "def", "prt_tsv", "(", "prt", ",", "data_nts", ",", "*", "*", "kws", ")", ":", "# User-controlled printing options", "prt_tsv_hdr", "(", "prt", ",", "data_nts", ",", "*", "*", "kws", ")", "return", "prt_tsv_dat", "(", "prt", ",", "data_nts", ",", "*", "*...
Print tab-separated table headers and data
[ "Print", "tab", "-", "separated", "table", "headers", "and", "data" ]
407682e573a108864a79031f8ca19ee3bf377626
https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/wr_tbl.py#L157-L161
train
223,178
tanghaibao/goatools
goatools/wr_tbl.py
prt_tsv_hdr
def prt_tsv_hdr(prt, data_nts, **kws): """Print tab-separated table headers""" sep = "\t" if 'sep' not in kws else kws['sep'] flds_all = data_nts[0]._fields hdrs = get_hdrs(flds_all, **kws) prt.write("# {}\n".format(sep.join(hdrs)))
python
def prt_tsv_hdr(prt, data_nts, **kws): """Print tab-separated table headers""" sep = "\t" if 'sep' not in kws else kws['sep'] flds_all = data_nts[0]._fields hdrs = get_hdrs(flds_all, **kws) prt.write("# {}\n".format(sep.join(hdrs)))
[ "def", "prt_tsv_hdr", "(", "prt", ",", "data_nts", ",", "*", "*", "kws", ")", ":", "sep", "=", "\"\\t\"", "if", "'sep'", "not", "in", "kws", "else", "kws", "[", "'sep'", "]", "flds_all", "=", "data_nts", "[", "0", "]", ".", "_fields", "hdrs", "=", ...
Print tab-separated table headers
[ "Print", "tab", "-", "separated", "table", "headers" ]
407682e573a108864a79031f8ca19ee3bf377626
https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/wr_tbl.py#L163-L168
train
223,179
tanghaibao/goatools
goatools/wr_tbl.py
prt_tsv_dat
def prt_tsv_dat(prt, data_nts, **kws): """Print tab-separated table data""" sep = "\t" if 'sep' not in kws else kws['sep'] fld2fmt = None if 'fld2fmt' not in kws else kws['fld2fmt'] if 'sort_by' in kws: data_nts = sorted(data_nts, key=kws['sort_by']) prt_if = kws['prt_if'] if 'prt_if' in kws else None prt_flds = kws['prt_flds'] if 'prt_flds' in kws else data_nts[0]._fields items = 0 for nt_data_row in data_nts: if prt_if is None or prt_if(nt_data_row): if fld2fmt is not None: row_fld_vals = [(fld, getattr(nt_data_row, fld)) for fld in prt_flds] row_vals = _fmt_fields(row_fld_vals, fld2fmt) else: row_vals = [getattr(nt_data_row, fld) for fld in prt_flds] prt.write("{}\n".format(sep.join(str(d) for d in row_vals))) items += 1 return items
python
def prt_tsv_dat(prt, data_nts, **kws): """Print tab-separated table data""" sep = "\t" if 'sep' not in kws else kws['sep'] fld2fmt = None if 'fld2fmt' not in kws else kws['fld2fmt'] if 'sort_by' in kws: data_nts = sorted(data_nts, key=kws['sort_by']) prt_if = kws['prt_if'] if 'prt_if' in kws else None prt_flds = kws['prt_flds'] if 'prt_flds' in kws else data_nts[0]._fields items = 0 for nt_data_row in data_nts: if prt_if is None or prt_if(nt_data_row): if fld2fmt is not None: row_fld_vals = [(fld, getattr(nt_data_row, fld)) for fld in prt_flds] row_vals = _fmt_fields(row_fld_vals, fld2fmt) else: row_vals = [getattr(nt_data_row, fld) for fld in prt_flds] prt.write("{}\n".format(sep.join(str(d) for d in row_vals))) items += 1 return items
[ "def", "prt_tsv_dat", "(", "prt", ",", "data_nts", ",", "*", "*", "kws", ")", ":", "sep", "=", "\"\\t\"", "if", "'sep'", "not", "in", "kws", "else", "kws", "[", "'sep'", "]", "fld2fmt", "=", "None", "if", "'fld2fmt'", "not", "in", "kws", "else", "k...
Print tab-separated table data
[ "Print", "tab", "-", "separated", "table", "data" ]
407682e573a108864a79031f8ca19ee3bf377626
https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/wr_tbl.py#L170-L188
train
223,180
tanghaibao/goatools
goatools/wr_tbl.py
_chk_flds_fmt
def _chk_flds_fmt(nt_fields, prtfmt): """Check that all fields in the prtfmt have corresponding data in the namedtuple.""" fmtflds = get_fmtflds(prtfmt) missing_data = set(fmtflds).difference(set(nt_fields)) # All data needed for print is present, return. if not missing_data: return #raise Exception('MISSING DATA({M}).'.format(M=" ".join(missing_data))) msg = ['CANNOT PRINT USING: "{PF}"'.format(PF=prtfmt.rstrip())] for fld in fmtflds: errmrk = "" if fld in nt_fields else "ERROR-->" msg.append(" {ERR:8} {FLD}".format(ERR=errmrk, FLD=fld)) raise Exception('\n'.join(msg))
python
def _chk_flds_fmt(nt_fields, prtfmt): """Check that all fields in the prtfmt have corresponding data in the namedtuple.""" fmtflds = get_fmtflds(prtfmt) missing_data = set(fmtflds).difference(set(nt_fields)) # All data needed for print is present, return. if not missing_data: return #raise Exception('MISSING DATA({M}).'.format(M=" ".join(missing_data))) msg = ['CANNOT PRINT USING: "{PF}"'.format(PF=prtfmt.rstrip())] for fld in fmtflds: errmrk = "" if fld in nt_fields else "ERROR-->" msg.append(" {ERR:8} {FLD}".format(ERR=errmrk, FLD=fld)) raise Exception('\n'.join(msg))
[ "def", "_chk_flds_fmt", "(", "nt_fields", ",", "prtfmt", ")", ":", "fmtflds", "=", "get_fmtflds", "(", "prtfmt", ")", "missing_data", "=", "set", "(", "fmtflds", ")", ".", "difference", "(", "set", "(", "nt_fields", ")", ")", "# All data needed for print is pr...
Check that all fields in the prtfmt have corresponding data in the namedtuple.
[ "Check", "that", "all", "fields", "in", "the", "prtfmt", "have", "corresponding", "data", "in", "the", "namedtuple", "." ]
407682e573a108864a79031f8ca19ee3bf377626
https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/wr_tbl.py#L199-L211
train
223,181
tanghaibao/goatools
goatools/wr_tbl.py
_prt_txt_hdr
def _prt_txt_hdr(prt, prtfmt): """Print header for text report.""" tblhdrs = get_fmtfldsdict(prtfmt) # If needed, reformat for format_string for header, which has strings, not floats. hdrfmt = re.sub(r':(\d+)\.\S+}', r':\1}', prtfmt) hdrfmt = re.sub(r':(0+)(\d+)}', r':\2}', hdrfmt) prt.write("#{}".format(hdrfmt.format(**tblhdrs)))
python
def _prt_txt_hdr(prt, prtfmt): """Print header for text report.""" tblhdrs = get_fmtfldsdict(prtfmt) # If needed, reformat for format_string for header, which has strings, not floats. hdrfmt = re.sub(r':(\d+)\.\S+}', r':\1}', prtfmt) hdrfmt = re.sub(r':(0+)(\d+)}', r':\2}', hdrfmt) prt.write("#{}".format(hdrfmt.format(**tblhdrs)))
[ "def", "_prt_txt_hdr", "(", "prt", ",", "prtfmt", ")", ":", "tblhdrs", "=", "get_fmtfldsdict", "(", "prtfmt", ")", "# If needed, reformat for format_string for header, which has strings, not floats.", "hdrfmt", "=", "re", ".", "sub", "(", "r':(\\d+)\\.\\S+}'", ",", "r':...
Print header for text report.
[ "Print", "header", "for", "text", "report", "." ]
407682e573a108864a79031f8ca19ee3bf377626
https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/wr_tbl.py#L223-L229
train
223,182
tanghaibao/goatools
goatools/wr_tbl.py
mk_fmtfld
def mk_fmtfld(nt_item, joinchr=" ", eol="\n"): """Given a namedtuple, return a format_field string.""" fldstrs = [] # Default formats based on fieldname fld2fmt = { 'hdrgo' : lambda f: "{{{FLD}:1,}}".format(FLD=f), 'dcnt' : lambda f: "{{{FLD}:6,}}".format(FLD=f), 'level' : lambda f: "L{{{FLD}:02,}}".format(FLD=f), 'depth' : lambda f: "D{{{FLD}:02,}}".format(FLD=f), } for fld in nt_item._fields: if fld in fld2fmt: val = fld2fmt[fld](fld) else: val = "{{{FLD}}}".format(FLD=fld) fldstrs.append(val) return "{LINE}{EOL}".format(LINE=joinchr.join(fldstrs), EOL=eol)
python
def mk_fmtfld(nt_item, joinchr=" ", eol="\n"): """Given a namedtuple, return a format_field string.""" fldstrs = [] # Default formats based on fieldname fld2fmt = { 'hdrgo' : lambda f: "{{{FLD}:1,}}".format(FLD=f), 'dcnt' : lambda f: "{{{FLD}:6,}}".format(FLD=f), 'level' : lambda f: "L{{{FLD}:02,}}".format(FLD=f), 'depth' : lambda f: "D{{{FLD}:02,}}".format(FLD=f), } for fld in nt_item._fields: if fld in fld2fmt: val = fld2fmt[fld](fld) else: val = "{{{FLD}}}".format(FLD=fld) fldstrs.append(val) return "{LINE}{EOL}".format(LINE=joinchr.join(fldstrs), EOL=eol)
[ "def", "mk_fmtfld", "(", "nt_item", ",", "joinchr", "=", "\" \"", ",", "eol", "=", "\"\\n\"", ")", ":", "fldstrs", "=", "[", "]", "# Default formats based on fieldname", "fld2fmt", "=", "{", "'hdrgo'", ":", "lambda", "f", ":", "\"{{{FLD}:1,}}\"", ".", "forma...
Given a namedtuple, return a format_field string.
[ "Given", "a", "namedtuple", "return", "a", "format_field", "string", "." ]
407682e573a108864a79031f8ca19ee3bf377626
https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/wr_tbl.py#L231-L247
train
223,183
tanghaibao/goatools
goatools/cli/compare_gos.py
CompareGOsCli._get_prtfmt
def _get_prtfmt(self, objgowr, verbose): """Get print format containing markers.""" prtfmt = objgowr.get_prtfmt('fmt') prtfmt = prtfmt.replace('# ', '') # print('PPPPPPPPPPP', prtfmt) if not verbose: prtfmt = prtfmt.replace('{hdr1usr01:2}', '') prtfmt = prtfmt.replace('{childcnt:3} L{level:02} ', '') prtfmt = prtfmt.replace('{num_usrgos:>4} uGOs ', '') prtfmt = prtfmt.replace('{D1:5} {REL} {rel}', '') prtfmt = prtfmt.replace('R{reldepth:02} ', '') # print('PPPPPPPPPPP', prtfmt) marks = ''.join(['{{{}}}'.format(nt.hdr) for nt in self.go_ntsets]) return '{MARKS} {PRTFMT}'.format(MARKS=marks, PRTFMT=prtfmt)
python
def _get_prtfmt(self, objgowr, verbose): """Get print format containing markers.""" prtfmt = objgowr.get_prtfmt('fmt') prtfmt = prtfmt.replace('# ', '') # print('PPPPPPPPPPP', prtfmt) if not verbose: prtfmt = prtfmt.replace('{hdr1usr01:2}', '') prtfmt = prtfmt.replace('{childcnt:3} L{level:02} ', '') prtfmt = prtfmt.replace('{num_usrgos:>4} uGOs ', '') prtfmt = prtfmt.replace('{D1:5} {REL} {rel}', '') prtfmt = prtfmt.replace('R{reldepth:02} ', '') # print('PPPPPPPPPPP', prtfmt) marks = ''.join(['{{{}}}'.format(nt.hdr) for nt in self.go_ntsets]) return '{MARKS} {PRTFMT}'.format(MARKS=marks, PRTFMT=prtfmt)
[ "def", "_get_prtfmt", "(", "self", ",", "objgowr", ",", "verbose", ")", ":", "prtfmt", "=", "objgowr", ".", "get_prtfmt", "(", "'fmt'", ")", "prtfmt", "=", "prtfmt", ".", "replace", "(", "'# '", ",", "''", ")", "# print('PPPPPPPPPPP', prtfmt)", "if", "not"...
Get print format containing markers.
[ "Get", "print", "format", "containing", "markers", "." ]
407682e573a108864a79031f8ca19ee3bf377626
https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/cli/compare_gos.py#L113-L126
train
223,184
tanghaibao/goatools
goatools/cli/compare_gos.py
CompareGOsCli._wr_ver_n_key
def _wr_ver_n_key(self, fout_txt, verbose): """Write GO DAG version and key indicating presence of GO ID in a list.""" with open(fout_txt, 'w') as prt: self._prt_ver_n_key(prt, verbose) print(' WROTE: {TXT}'.format(TXT=fout_txt))
python
def _wr_ver_n_key(self, fout_txt, verbose): """Write GO DAG version and key indicating presence of GO ID in a list.""" with open(fout_txt, 'w') as prt: self._prt_ver_n_key(prt, verbose) print(' WROTE: {TXT}'.format(TXT=fout_txt))
[ "def", "_wr_ver_n_key", "(", "self", ",", "fout_txt", ",", "verbose", ")", ":", "with", "open", "(", "fout_txt", ",", "'w'", ")", "as", "prt", ":", "self", ".", "_prt_ver_n_key", "(", "prt", ",", "verbose", ")", "print", "(", "' WROTE: {TXT}'...
Write GO DAG version and key indicating presence of GO ID in a list.
[ "Write", "GO", "DAG", "version", "and", "key", "indicating", "presence", "of", "GO", "ID", "in", "a", "list", "." ]
407682e573a108864a79031f8ca19ee3bf377626
https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/cli/compare_gos.py#L153-L157
train
223,185
tanghaibao/goatools
goatools/cli/compare_gos.py
CompareGOsCli._prt_ver_n_key
def _prt_ver_n_key(self, prt, verbose): """Print GO DAG version and key indicating presence of GO ID in a list.""" pre = '# ' prt.write('# ----------------------------------------------------------------\n') prt.write('# - Description of GO ID fields\n') prt.write('# ----------------------------------------------------------------\n') prt.write("# Versions:\n# {VER}\n".format(VER="\n# ".join(self.objgrpd.ver_list))) prt.write('\n# Marker keys:\n') for ntgos in self.go_ntsets: prt.write('# X -> GO is present in {HDR}\n'.format(HDR=ntgos.hdr)) if verbose: prt.write('\n# Markers for header GO IDs and user GO IDs:\n') prt.write("# '**' -> GO term is both a header and a user GO ID\n") prt.write("# '* ' -> GO term is a header, but not a user GO ID\n") prt.write("# ' ' -> GO term is a user GO ID\n") prt.write('\n# GO Namspaces:\n') prt.write('# BP -> Biological Process\n') prt.write('# MF -> Molecular Function\n') prt.write('# CC -> Cellualr Component\n') if verbose: prt.write('\n# Example fields: 5 uGOs 362 47 L04 D04 R04\n') prt.write('# N uGOs -> number of user GO IDs under this GO header\n') prt.write('# First integer -> number of GO descendants\n') prt.write('# Second integer -> number of GO children for the current GO ID\n') prt.write('\n# Depth information:\n') if not verbose: prt.write('# int -> number of GO descendants\n') if verbose: prt.write('# Lnn -> level (minimum distance from root to node)\n') prt.write('# Dnn -> depth (maximum distance from root to node)\n') if verbose: prt.write('# Rnn -> depth accounting for relationships\n\n') RelationshipStr().prt_keys(prt, pre) if verbose: prt.write('\n') objd1 = GoDepth1LettersWr(self.gosubdag.rcntobj) objd1.prt_header(prt, 'DEPTH-01 GO terms and their aliases', pre) objd1.prt_txt(prt, pre)
python
def _prt_ver_n_key(self, prt, verbose): """Print GO DAG version and key indicating presence of GO ID in a list.""" pre = '# ' prt.write('# ----------------------------------------------------------------\n') prt.write('# - Description of GO ID fields\n') prt.write('# ----------------------------------------------------------------\n') prt.write("# Versions:\n# {VER}\n".format(VER="\n# ".join(self.objgrpd.ver_list))) prt.write('\n# Marker keys:\n') for ntgos in self.go_ntsets: prt.write('# X -> GO is present in {HDR}\n'.format(HDR=ntgos.hdr)) if verbose: prt.write('\n# Markers for header GO IDs and user GO IDs:\n') prt.write("# '**' -> GO term is both a header and a user GO ID\n") prt.write("# '* ' -> GO term is a header, but not a user GO ID\n") prt.write("# ' ' -> GO term is a user GO ID\n") prt.write('\n# GO Namspaces:\n') prt.write('# BP -> Biological Process\n') prt.write('# MF -> Molecular Function\n') prt.write('# CC -> Cellualr Component\n') if verbose: prt.write('\n# Example fields: 5 uGOs 362 47 L04 D04 R04\n') prt.write('# N uGOs -> number of user GO IDs under this GO header\n') prt.write('# First integer -> number of GO descendants\n') prt.write('# Second integer -> number of GO children for the current GO ID\n') prt.write('\n# Depth information:\n') if not verbose: prt.write('# int -> number of GO descendants\n') if verbose: prt.write('# Lnn -> level (minimum distance from root to node)\n') prt.write('# Dnn -> depth (maximum distance from root to node)\n') if verbose: prt.write('# Rnn -> depth accounting for relationships\n\n') RelationshipStr().prt_keys(prt, pre) if verbose: prt.write('\n') objd1 = GoDepth1LettersWr(self.gosubdag.rcntobj) objd1.prt_header(prt, 'DEPTH-01 GO terms and their aliases', pre) objd1.prt_txt(prt, pre)
[ "def", "_prt_ver_n_key", "(", "self", ",", "prt", ",", "verbose", ")", ":", "pre", "=", "'# '", "prt", ".", "write", "(", "'# ----------------------------------------------------------------\\n'", ")", "prt", ".", "write", "(", "'# - Description of GO ID fields\\n'", ...
Print GO DAG version and key indicating presence of GO ID in a list.
[ "Print", "GO", "DAG", "version", "and", "key", "indicating", "presence", "of", "GO", "ID", "in", "a", "list", "." ]
407682e573a108864a79031f8ca19ee3bf377626
https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/cli/compare_gos.py#L160-L197
train
223,186
tanghaibao/goatools
goatools/cli/compare_gos.py
_Init.get_grouped
def get_grouped(self, go_ntsets, go_all, gosubdag, **kws): """Get Grouped object.""" kws_grpd = {k:v for k, v in kws.items() if k in Grouped.kws_dict} kws_grpd['go2nt'] = self._init_go2ntpresent(go_ntsets, go_all, gosubdag) return Grouped(gosubdag, self.godag.version, **kws_grpd)
python
def get_grouped(self, go_ntsets, go_all, gosubdag, **kws): """Get Grouped object.""" kws_grpd = {k:v for k, v in kws.items() if k in Grouped.kws_dict} kws_grpd['go2nt'] = self._init_go2ntpresent(go_ntsets, go_all, gosubdag) return Grouped(gosubdag, self.godag.version, **kws_grpd)
[ "def", "get_grouped", "(", "self", ",", "go_ntsets", ",", "go_all", ",", "gosubdag", ",", "*", "*", "kws", ")", ":", "kws_grpd", "=", "{", "k", ":", "v", "for", "k", ",", "v", "in", "kws", ".", "items", "(", ")", "if", "k", "in", "Grouped", "."...
Get Grouped object.
[ "Get", "Grouped", "object", "." ]
407682e573a108864a79031f8ca19ee3bf377626
https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/cli/compare_gos.py#L214-L218
train
223,187
tanghaibao/goatools
goatools/cli/compare_gos.py
_Init._init_go2ntpresent
def _init_go2ntpresent(go_ntsets, go_all, gosubdag): """Mark all GO IDs with an X if present in the user GO list.""" go2ntpresent = {} ntobj = namedtuple('NtPresent', " ".join(nt.hdr for nt in go_ntsets)) # Get present marks for GO sources for goid_all in go_all: present_true = [goid_all in nt.go_set for nt in go_ntsets] present_str = ['X' if tf else '.' for tf in present_true] go2ntpresent[goid_all] = ntobj._make(present_str) # Get present marks for all other GO ancestors goids_ancestors = set(gosubdag.go2obj).difference(go2ntpresent) assert not goids_ancestors.intersection(go_all) strmark = ['.' for _ in range(len(go_ntsets))] for goid in goids_ancestors: go2ntpresent[goid] = ntobj._make(strmark) return go2ntpresent
python
def _init_go2ntpresent(go_ntsets, go_all, gosubdag): """Mark all GO IDs with an X if present in the user GO list.""" go2ntpresent = {} ntobj = namedtuple('NtPresent', " ".join(nt.hdr for nt in go_ntsets)) # Get present marks for GO sources for goid_all in go_all: present_true = [goid_all in nt.go_set for nt in go_ntsets] present_str = ['X' if tf else '.' for tf in present_true] go2ntpresent[goid_all] = ntobj._make(present_str) # Get present marks for all other GO ancestors goids_ancestors = set(gosubdag.go2obj).difference(go2ntpresent) assert not goids_ancestors.intersection(go_all) strmark = ['.' for _ in range(len(go_ntsets))] for goid in goids_ancestors: go2ntpresent[goid] = ntobj._make(strmark) return go2ntpresent
[ "def", "_init_go2ntpresent", "(", "go_ntsets", ",", "go_all", ",", "gosubdag", ")", ":", "go2ntpresent", "=", "{", "}", "ntobj", "=", "namedtuple", "(", "'NtPresent'", ",", "\" \"", ".", "join", "(", "nt", ".", "hdr", "for", "nt", "in", "go_ntsets", ")",...
Mark all GO IDs with an X if present in the user GO list.
[ "Mark", "all", "GO", "IDs", "with", "an", "X", "if", "present", "in", "the", "user", "GO", "list", "." ]
407682e573a108864a79031f8ca19ee3bf377626
https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/cli/compare_gos.py#L221-L236
train
223,188
tanghaibao/goatools
goatools/cli/compare_gos.py
_Init.get_go_ntsets
def get_go_ntsets(self, go_fins): """For each file containing GOs, extract GO IDs, store filename and header.""" nts = [] ntobj = namedtuple('NtGOFiles', 'hdr go_set, go_fin') go_sets = self._init_go_sets(go_fins) hdrs = [os.path.splitext(os.path.basename(f))[0] for f in go_fins] assert len(go_fins) == len(go_sets) assert len(go_fins) == len(hdrs) for hdr, go_set, go_fin in zip(hdrs, go_sets, go_fins): nts.append(ntobj(hdr=hdr, go_set=go_set, go_fin=go_fin)) return nts
python
def get_go_ntsets(self, go_fins): """For each file containing GOs, extract GO IDs, store filename and header.""" nts = [] ntobj = namedtuple('NtGOFiles', 'hdr go_set, go_fin') go_sets = self._init_go_sets(go_fins) hdrs = [os.path.splitext(os.path.basename(f))[0] for f in go_fins] assert len(go_fins) == len(go_sets) assert len(go_fins) == len(hdrs) for hdr, go_set, go_fin in zip(hdrs, go_sets, go_fins): nts.append(ntobj(hdr=hdr, go_set=go_set, go_fin=go_fin)) return nts
[ "def", "get_go_ntsets", "(", "self", ",", "go_fins", ")", ":", "nts", "=", "[", "]", "ntobj", "=", "namedtuple", "(", "'NtGOFiles'", ",", "'hdr go_set, go_fin'", ")", "go_sets", "=", "self", ".", "_init_go_sets", "(", "go_fins", ")", "hdrs", "=", "[", "o...
For each file containing GOs, extract GO IDs, store filename and header.
[ "For", "each", "file", "containing", "GOs", "extract", "GO", "IDs", "store", "filename", "and", "header", "." ]
407682e573a108864a79031f8ca19ee3bf377626
https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/cli/compare_gos.py#L238-L248
train
223,189
tanghaibao/goatools
goatools/cli/compare_gos.py
_Init._init_go_sets
def _init_go_sets(self, go_fins): """Get lists of GO IDs.""" go_sets = [] assert go_fins, "EXPECTED FILES CONTAINING GO IDs" assert len(go_fins) >= 2, "EXPECTED 2+ GO LISTS. FOUND: {L}".format( L=' '.join(go_fins)) obj = GetGOs(self.godag) for fin in go_fins: assert os.path.exists(fin), "GO FILE({F}) DOES NOT EXIST".format(F=fin) go_sets.append(obj.get_usrgos(fin, sys.stdout)) return go_sets
python
def _init_go_sets(self, go_fins): """Get lists of GO IDs.""" go_sets = [] assert go_fins, "EXPECTED FILES CONTAINING GO IDs" assert len(go_fins) >= 2, "EXPECTED 2+ GO LISTS. FOUND: {L}".format( L=' '.join(go_fins)) obj = GetGOs(self.godag) for fin in go_fins: assert os.path.exists(fin), "GO FILE({F}) DOES NOT EXIST".format(F=fin) go_sets.append(obj.get_usrgos(fin, sys.stdout)) return go_sets
[ "def", "_init_go_sets", "(", "self", ",", "go_fins", ")", ":", "go_sets", "=", "[", "]", "assert", "go_fins", ",", "\"EXPECTED FILES CONTAINING GO IDs\"", "assert", "len", "(", "go_fins", ")", ">=", "2", ",", "\"EXPECTED 2+ GO LISTS. FOUND: {L}\"", ".", "format", ...
Get lists of GO IDs.
[ "Get", "lists", "of", "GO", "IDs", "." ]
407682e573a108864a79031f8ca19ee3bf377626
https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/cli/compare_gos.py#L250-L260
train
223,190
tanghaibao/goatools
goatools/gosubdag/godag_rcnt.py
CountRelatives.get_parents_letters
def get_parents_letters(self, goobj): """Get the letters representing all parent terms which are depth-01 GO terms.""" parents_all = set.union(self.go2parents[goobj.id]) parents_all.add(goobj.id) # print "{}({}) D{:02}".format(goobj.id, goobj.name, goobj.depth), parents_all parents_d1 = parents_all.intersection(self.gos_depth1) return [self.goone2ntletter[g].D1 for g in parents_d1]
python
def get_parents_letters(self, goobj): """Get the letters representing all parent terms which are depth-01 GO terms.""" parents_all = set.union(self.go2parents[goobj.id]) parents_all.add(goobj.id) # print "{}({}) D{:02}".format(goobj.id, goobj.name, goobj.depth), parents_all parents_d1 = parents_all.intersection(self.gos_depth1) return [self.goone2ntletter[g].D1 for g in parents_d1]
[ "def", "get_parents_letters", "(", "self", ",", "goobj", ")", ":", "parents_all", "=", "set", ".", "union", "(", "self", ".", "go2parents", "[", "goobj", ".", "id", "]", ")", "parents_all", ".", "add", "(", "goobj", ".", "id", ")", "# print \"{}({}) D{:0...
Get the letters representing all parent terms which are depth-01 GO terms.
[ "Get", "the", "letters", "representing", "all", "parent", "terms", "which", "are", "depth", "-", "01", "GO", "terms", "." ]
407682e573a108864a79031f8ca19ee3bf377626
https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/gosubdag/godag_rcnt.py#L28-L34
train
223,191
tanghaibao/goatools
goatools/gosubdag/godag_rcnt.py
CountRelatives.get_d1str
def get_d1str(self, goobj, reverse=False): """Get D1-string representing all parent terms which are depth-01 GO terms.""" return "".join(sorted(self.get_parents_letters(goobj), reverse=reverse))
python
def get_d1str(self, goobj, reverse=False): """Get D1-string representing all parent terms which are depth-01 GO terms.""" return "".join(sorted(self.get_parents_letters(goobj), reverse=reverse))
[ "def", "get_d1str", "(", "self", ",", "goobj", ",", "reverse", "=", "False", ")", ":", "return", "\"\"", ".", "join", "(", "sorted", "(", "self", ".", "get_parents_letters", "(", "goobj", ")", ",", "reverse", "=", "reverse", ")", ")" ]
Get D1-string representing all parent terms which are depth-01 GO terms.
[ "Get", "D1", "-", "string", "representing", "all", "parent", "terms", "which", "are", "depth", "-", "01", "GO", "terms", "." ]
407682e573a108864a79031f8ca19ee3bf377626
https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/gosubdag/godag_rcnt.py#L36-L38
train
223,192
tanghaibao/goatools
goatools/gosubdag/go_most_specific.py
get_most_specific_dcnt
def get_most_specific_dcnt(goids, go2nt): """Get the GO ID with the lowest descendants count.""" # go2nt_usr = {go:go2nt[go] for go in goids} # return min(go2nt_usr.items(), key=lambda t: t[1].dcnt)[0] return min(_get_go2nt(goids, go2nt), key=lambda t: t[1].dcnt)[0]
python
def get_most_specific_dcnt(goids, go2nt): """Get the GO ID with the lowest descendants count.""" # go2nt_usr = {go:go2nt[go] for go in goids} # return min(go2nt_usr.items(), key=lambda t: t[1].dcnt)[0] return min(_get_go2nt(goids, go2nt), key=lambda t: t[1].dcnt)[0]
[ "def", "get_most_specific_dcnt", "(", "goids", ",", "go2nt", ")", ":", "# go2nt_usr = {go:go2nt[go] for go in goids}", "# return min(go2nt_usr.items(), key=lambda t: t[1].dcnt)[0]", "return", "min", "(", "_get_go2nt", "(", "goids", ",", "go2nt", ")", ",", "key", "=", "lam...
Get the GO ID with the lowest descendants count.
[ "Get", "the", "GO", "ID", "with", "the", "lowest", "descendants", "count", "." ]
407682e573a108864a79031f8ca19ee3bf377626
https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/gosubdag/go_most_specific.py#L7-L11
train
223,193
tanghaibao/goatools
goatools/gosubdag/go_most_specific.py
_get_go2nt
def _get_go2nt(goids, go2nt_all): """Get user go2nt using main GO IDs, not alt IDs.""" go_nt_list = [] goids_seen = set() for goid_usr in goids: ntgo = go2nt_all[goid_usr] goid_main = ntgo.id if goid_main not in goids_seen: goids_seen.add(goid_main) go_nt_list.append((goid_main, ntgo)) return go_nt_list
python
def _get_go2nt(goids, go2nt_all): """Get user go2nt using main GO IDs, not alt IDs.""" go_nt_list = [] goids_seen = set() for goid_usr in goids: ntgo = go2nt_all[goid_usr] goid_main = ntgo.id if goid_main not in goids_seen: goids_seen.add(goid_main) go_nt_list.append((goid_main, ntgo)) return go_nt_list
[ "def", "_get_go2nt", "(", "goids", ",", "go2nt_all", ")", ":", "go_nt_list", "=", "[", "]", "goids_seen", "=", "set", "(", ")", "for", "goid_usr", "in", "goids", ":", "ntgo", "=", "go2nt_all", "[", "goid_usr", "]", "goid_main", "=", "ntgo", ".", "id", ...
Get user go2nt using main GO IDs, not alt IDs.
[ "Get", "user", "go2nt", "using", "main", "GO", "IDs", "not", "alt", "IDs", "." ]
407682e573a108864a79031f8ca19ee3bf377626
https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/gosubdag/go_most_specific.py#L25-L35
train
223,194
tanghaibao/goatools
goatools/grouper/aart_geneproducts_one.py
AArtGeneProductSetsOne.prt_gos_grouped
def prt_gos_grouped(self, prt, **kws_grp): """Print grouped GO list.""" prtfmt = self.datobj.kws['fmtgo'] wrobj = WrXlsxSortedGos(self.name, self.sortobj) # Keyword arguments: control content: hdrgo_prt section_prt top_n use_sections desc2nts = self.sortobj.get_desc2nts(**kws_grp) wrobj.prt_txt_desc2nts(prt, desc2nts, prtfmt)
python
def prt_gos_grouped(self, prt, **kws_grp): """Print grouped GO list.""" prtfmt = self.datobj.kws['fmtgo'] wrobj = WrXlsxSortedGos(self.name, self.sortobj) # Keyword arguments: control content: hdrgo_prt section_prt top_n use_sections desc2nts = self.sortobj.get_desc2nts(**kws_grp) wrobj.prt_txt_desc2nts(prt, desc2nts, prtfmt)
[ "def", "prt_gos_grouped", "(", "self", ",", "prt", ",", "*", "*", "kws_grp", ")", ":", "prtfmt", "=", "self", ".", "datobj", ".", "kws", "[", "'fmtgo'", "]", "wrobj", "=", "WrXlsxSortedGos", "(", "self", ".", "name", ",", "self", ".", "sortobj", ")",...
Print grouped GO list.
[ "Print", "grouped", "GO", "list", "." ]
407682e573a108864a79031f8ca19ee3bf377626
https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/grouper/aart_geneproducts_one.py#L74-L80
train
223,195
tanghaibao/goatools
goatools/grouper/aart_geneproducts_one.py
AArtGeneProductSetsOne.prt_gos_flat
def prt_gos_flat(self, prt): """Print flat GO list.""" prtfmt = self.datobj.kws['fmtgo'] _go2nt = self.sortobj.grprobj.go2nt go2nt = {go:_go2nt[go] for go in self.go2nt} prt.write("\n{N} GO IDs:\n".format(N=len(go2nt))) _sortby = self._get_sortgo() for ntgo in sorted(go2nt.values(), key=_sortby): prt.write(prtfmt.format(**ntgo._asdict()))
python
def prt_gos_flat(self, prt): """Print flat GO list.""" prtfmt = self.datobj.kws['fmtgo'] _go2nt = self.sortobj.grprobj.go2nt go2nt = {go:_go2nt[go] for go in self.go2nt} prt.write("\n{N} GO IDs:\n".format(N=len(go2nt))) _sortby = self._get_sortgo() for ntgo in sorted(go2nt.values(), key=_sortby): prt.write(prtfmt.format(**ntgo._asdict()))
[ "def", "prt_gos_flat", "(", "self", ",", "prt", ")", ":", "prtfmt", "=", "self", ".", "datobj", ".", "kws", "[", "'fmtgo'", "]", "_go2nt", "=", "self", ".", "sortobj", ".", "grprobj", ".", "go2nt", "go2nt", "=", "{", "go", ":", "_go2nt", "[", "go",...
Print flat GO list.
[ "Print", "flat", "GO", "list", "." ]
407682e573a108864a79031f8ca19ee3bf377626
https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/grouper/aart_geneproducts_one.py#L82-L90
train
223,196
tanghaibao/goatools
goatools/grouper/aart_geneproducts_one.py
AArtGeneProductSetsOne._get_sortgo
def _get_sortgo(self): """Get function for sorting GO terms in a list of namedtuples.""" if 'sortgo' in self.datobj.kws: return self.datobj.kws['sortgo'] return self.datobj.grprdflt.gosubdag.prt_attr['sort'] + "\n"
python
def _get_sortgo(self): """Get function for sorting GO terms in a list of namedtuples.""" if 'sortgo' in self.datobj.kws: return self.datobj.kws['sortgo'] return self.datobj.grprdflt.gosubdag.prt_attr['sort'] + "\n"
[ "def", "_get_sortgo", "(", "self", ")", ":", "if", "'sortgo'", "in", "self", ".", "datobj", ".", "kws", ":", "return", "self", ".", "datobj", ".", "kws", "[", "'sortgo'", "]", "return", "self", ".", "datobj", ".", "grprdflt", ".", "gosubdag", ".", "p...
Get function for sorting GO terms in a list of namedtuples.
[ "Get", "function", "for", "sorting", "GO", "terms", "in", "a", "list", "of", "namedtuples", "." ]
407682e573a108864a79031f8ca19ee3bf377626
https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/grouper/aart_geneproducts_one.py#L93-L97
train
223,197
tanghaibao/goatools
goatools/grouper/aart_geneproducts_one.py
AArtGeneProductSetsOne.get_gene2binvec
def get_gene2binvec(self): """Return a boolean vector for each gene representing GO section membership.""" _sec2chr = self.sec2chr return {g:[s in s2gos for s in _sec2chr] for g, s2gos in self.gene2section2gos.items()}
python
def get_gene2binvec(self): """Return a boolean vector for each gene representing GO section membership.""" _sec2chr = self.sec2chr return {g:[s in s2gos for s in _sec2chr] for g, s2gos in self.gene2section2gos.items()}
[ "def", "get_gene2binvec", "(", "self", ")", ":", "_sec2chr", "=", "self", ".", "sec2chr", "return", "{", "g", ":", "[", "s", "in", "s2gos", "for", "s", "in", "_sec2chr", "]", "for", "g", ",", "s2gos", "in", "self", ".", "gene2section2gos", ".", "item...
Return a boolean vector for each gene representing GO section membership.
[ "Return", "a", "boolean", "vector", "for", "each", "gene", "representing", "GO", "section", "membership", "." ]
407682e573a108864a79031f8ca19ee3bf377626
https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/grouper/aart_geneproducts_one.py#L140-L143
train
223,198
tanghaibao/goatools
goatools/grouper/aart_geneproducts_one.py
_Init.get_go2nt
def get_go2nt(self, goea_results): """Return go2nt with added formatted string versions of the P-values.""" go2obj = self.objaartall.grprdflt.gosubdag.go2obj # Add string version of P-values goea_nts = MgrNtGOEAs(goea_results).get_nts_strpval() return {go2obj[nt.GO].id:nt for nt in goea_nts if nt.GO in go2obj}
python
def get_go2nt(self, goea_results): """Return go2nt with added formatted string versions of the P-values.""" go2obj = self.objaartall.grprdflt.gosubdag.go2obj # Add string version of P-values goea_nts = MgrNtGOEAs(goea_results).get_nts_strpval() return {go2obj[nt.GO].id:nt for nt in goea_nts if nt.GO in go2obj}
[ "def", "get_go2nt", "(", "self", ",", "goea_results", ")", ":", "go2obj", "=", "self", ".", "objaartall", ".", "grprdflt", ".", "gosubdag", ".", "go2obj", "# Add string version of P-values", "goea_nts", "=", "MgrNtGOEAs", "(", "goea_results", ")", ".", "get_nts_...
Return go2nt with added formatted string versions of the P-values.
[ "Return", "go2nt", "with", "added", "formatted", "string", "versions", "of", "the", "P", "-", "values", "." ]
407682e573a108864a79031f8ca19ee3bf377626
https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/grouper/aart_geneproducts_one.py#L151-L156
train
223,199