text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dense_rank(expr, sort=None, ascending=True): """ Calculate dense rank of a sequence expression. :param expr: expression for calculation :param sort: name of the sort column :param ascending: whether to sort in ascending order :return: calculated column """
return _rank_op(expr, DenseRank, types.int64, sort=sort, ascending=ascending)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def percent_rank(expr, sort=None, ascending=True): """ Calculate percentage rank of a sequence expression. :param expr: expression for calculation :param sort: name of the sort column :param ascending: whether to sort in ascending order :return: calculated column """
return _rank_op(expr, PercentRank, types.float64, sort=sort, ascending=ascending)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def row_number(expr, sort=None, ascending=True): """ Calculate row number of a sequence expression. :param expr: expression for calculation :param sort: name of the sort column :param ascending: whether to sort in ascending order :return: calculated column """
return _rank_op(expr, RowNumber, types.int64, sort=sort, ascending=ascending)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def qcut(expr, bins, labels=False, sort=None, ascending=True): """ Get quantile-based bin indices of every element of a grouped and sorted expression. The indices of bins start from 0. If cuts are not of equal sizes, extra items will be appended into the first group. :param expr: expression for calculation :param bins: number of bins :param sort: name of the sort column :param ascending: whether to sort in ascending order :return: calculated column """
if labels is None or labels: raise NotImplementedError('Showing bins or customizing labels not supported') return _rank_op(expr, QCut, types.int64, sort=sort, ascending=ascending, _bins=bins)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cume_dist(expr, sort=None, ascending=True): """ Calculate cumulative ratio of a sequence expression. :param expr: expression for calculation :param sort: name of the sort column :param ascending: whether to sort in ascending order :return: calculated column """
return _rank_op(expr, CumeDist, types.float64, sort=sort, ascending=ascending)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lag(expr, offset, default=None, sort=None, ascending=True): """ Get value in the row ``offset`` rows prior to the current row. :param offset: the offset value :param default: default value for the function, when there are no rows satisfying the offset :param expr: expression for calculation :param sort: name of the sort column :param ascending: whether to sort in ascending order :return: calculated column """
return _shift_op(expr, Lag, offset, default=default, sort=sort, ascending=ascending)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lead(expr, offset, default=None, sort=None, ascending=True): """ Get value in the row ``offset`` rows after to the current row. :param offset: the offset value :param default: default value for the function, when there are no rows satisfying the offset :param expr: expression for calculation :param sort: name of the sort column :param ascending: whether to sort in ascending order :return: calculated column """
return _shift_op(expr, Lead, offset, default=default, sort=sort, ascending=ascending)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_model(self): """ Get PMML text of the current model. Note that model file obtained via this method might be incomplete due to size limitations. """
url = self.resource() params = {'data': ''} resp = self._client.get(url, params=params) return resp.text
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_response(resp): """Parses the content of response and returns an exception object. """
host_id, msg, code = None, None, None try: content = resp.content root = ET.fromstring(content) code = root.find('./Code').text msg = root.find('./Message').text request_id = root.find('./RequestId').text host_id = root.find('./HostId').text except ETParseError: request_id = resp.headers.get('x-odps-request-id', None) if len(resp.content) > 0: obj = json.loads(resp.text) msg = obj['Message'] code = obj.get('Code') host_id = obj.get('HostId') if request_id is None: request_id = obj.get('RequestId') else: return clz = globals().get(code, ODPSError) return clz(msg, request_id=request_id, code=code, host_id=host_id)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def throw_if_parsable(resp): """Try to parse the content of the response and raise an exception if neccessary. """
e = None try: e = parse_response(resp) except: # Error occurred during parsing the response. We ignore it and delegate # the situation to caller to handle. LOG.debug(utils.stringify_expt()) if e is not None: raise e if resp.status_code == 404: raise NoSuchObject('No such object.') else: text = resp.text if six.PY3 else resp.content if text: raise ODPSError(text, code=str(resp.status_code)) else: raise ODPSError(str(resp.status_code))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def merge_data(*data_frames, **kwargs): """ Merge DataFrames by column. Number of rows in tables must be the same. This method can be called both outside and as a DataFrame method. :param list[DataFrame] data_frames: DataFrames to be merged. :param bool auto_rename: if True, fields in source DataFrames will be renamed in the output. :return: merged data frame. :rtype: DataFrame :Example: """
from .specialized import build_merge_expr from ..utils import ML_ARG_PREFIX if len(data_frames) <= 1: raise ValueError('Count of DataFrames should be at least 2.') norm_data_pairs = [] df_tuple = collections.namedtuple('MergeTuple', 'df cols exclude') for pair in data_frames: if isinstance(pair, tuple): if len(pair) == 2: df, cols = pair exclude = False else: df, cols, exclude = pair if isinstance(cols, six.string_types): cols = cols.split(',') else: df, cols, exclude = pair, None, False norm_data_pairs.append(df_tuple(df, cols, exclude)) auto_rename = kwargs.get('auto_rename', False) sel_cols_dict = dict((idx, tp.cols) for idx, tp in enumerate(norm_data_pairs) if tp.cols and not tp.exclude) ex_cols_dict = dict((idx, tp.cols) for idx, tp in enumerate(norm_data_pairs) if tp.cols and tp.exclude) merge_expr = build_merge_expr(len(norm_data_pairs)) arg_dict = dict(_params={'autoRenameCol': str(auto_rename)}, selected_cols=sel_cols_dict, excluded_cols=ex_cols_dict) for idx, dp in enumerate(norm_data_pairs): arg_dict[ML_ARG_PREFIX + 'input%d' % (1 + idx)] = dp.df out_df = merge_expr(register_expr=True, _exec_id=uuid.uuid4(), _output_name='output', **arg_dict) out_df._ml_uplink = [dp.df for dp in norm_data_pairs] out_df._perform_operation(op.MergeFieldsOperation(auto_rename, sel_cols_dict, ex_cols_dict)) out_df._rebuild_df_schema() return out_df
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def exclude_fields(self, *args): """ Exclude one or more fields from feature fields. :rtype: DataFrame """
if not args: raise ValueError("Field list cannot be None.") new_df = copy_df(self) fields = _render_field_set(args) self._assert_ml_fields_valid(*fields) new_df._perform_operation(op.ExcludeFieldsOperation(fields)) return new_df
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def select_features(self, *args, **kwargs): """ Select one or more fields as feature fields. :rtype: DataFrame """
if not args: raise ValueError("Field list cannot be empty.") # generate selected set from args augment = kwargs.get('add', False) fields = _render_field_set(args) self._assert_ml_fields_valid(*fields) return _batch_change_roles(self, fields, FieldRole.FEATURE, augment)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def weight_field(self, f): """ Select one field as the weight field. Note that this field will be exclude from feature fields. :param f: Selected weight field :type f: str :rtype: DataFrame """
if f is None: raise ValueError("Field name cannot be None.") self._assert_ml_fields_valid(f) return _change_singleton_roles(self, {f: FieldRole.WEIGHT}, clear_feature=True)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def label_field(self, f): """ Select one field as the label field. Note that this field will be exclude from feature fields. :param f: Selected label field :type f: str :rtype: DataFrame """
if f is None: raise ValueError("Label field name cannot be None.") self._assert_ml_fields_valid(f) return _change_singleton_roles(self, {_get_field_name(f): FieldRole.LABEL}, clear_feature=True)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def continuous(self, *args): """ Set fields to be continuous. :rtype: DataFrame :Example: """
new_df = copy_df(self) fields = _render_field_set(args) self._assert_ml_fields_valid(*fields) new_df._perform_operation(op.FieldContinuityOperation(dict((_get_field_name(f), True) for f in fields))) return new_df
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def discrete(self, *args): """ Set fields to be discrete. :rtype: DataFrame :Example: """
new_df = copy_df(self) fields = _render_field_set(args) self._assert_ml_fields_valid(*fields) new_df._perform_operation(op.FieldContinuityOperation(dict((_get_field_name(f), False) for f in fields))) return new_df
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def roles(self, clear_features=True, **field_roles): """ Set roles of fields :param clear_features: Clear feature roles on fields :param field_roles: :return: """
field_roles = dict((k, v.name if isinstance(v, SequenceExpr) else v) for k, v in six.iteritems(field_roles)) self._assert_ml_fields_valid(*list(six.itervalues(field_roles))) field_roles = dict((_get_field_name(f), MLField.translate_role_name(role)) for role, f in six.iteritems(field_roles)) if field_roles: return _change_singleton_roles(self, field_roles, clear_features) else: return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def split(self, frac): """ Split the DataFrame into two DataFrames with certain ratio. :param frac: Split ratio :type frac: float :return: two split DataFrame objects :rtype: list[DataFrame] """
from .. import preprocess split_obj = getattr(preprocess, '_Split')(fraction=frac) return split_obj.transform(self)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def append_id(self, id_col_name='append_id', cols=None): """ Append an ID column to current DataFrame. :param str id_col_name: name of appended ID field. :param str cols: fields contained in output. All fields by default. :return: DataFrame with ID field :rtype: DataFrame """
from .. import preprocess if id_col_name in self.schema: raise ValueError('ID column collides with existing columns.') append_id_obj = getattr(preprocess, '_AppendID')(id_col=id_col_name, selected_cols=cols) return append_id_obj.transform(self)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def continuous(self): """ Set sequence to be continuous. :rtype: Column :Example: """
field_name = self.name new_df = copy_df(self) new_df._perform_operation(op.FieldContinuityOperation({field_name: True})) return new_df
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def discrete(self): """ Set sequence to be discrete. :rtype: Column :Example: """
field_name = self.name new_df = copy_df(self) new_df._perform_operation(op.FieldContinuityOperation({field_name: False})) return new_df
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def role(self, role_name): """ Set role of current column :param role_name: name of the role to be selected. :return: """
field_name = self.name field_roles = {field_name: MLField.translate_role_name(role_name)} if field_roles: return _change_singleton_roles(self, field_roles, True) else: return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _init(self, *args, **kwargs): """ _deps is used for common dependencies. When a expr depend on other exprs, and the expr is not calculated from the others, the _deps are specified to identify the dependencies. """
self._init_attr('_deps', None) self._init_attr('_ban_optimize', False) self._init_attr('_engine', None) self._init_attr('_Expr__execution', None) self._init_attr('_need_cache', False) self._init_attr('_mem_cache', False) if '_id' not in kwargs: kwargs['_id'] = new_id() super(Expr, self)._init(*args, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compile(self): """ Compile this expression into an ODPS SQL :return: compiled DAG :rtype: str """
from ..engines import get_default_engine engine = get_default_engine(self) return engine.compile(self)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def persist(self, name, partitions=None, partition=None, lifecycle=None, project=None, **kwargs): """ Persist the execution into a new table. If `partitions` not specified, will create a new table without partitions if the table does not exist, and insert the SQL result into it. If `partitions` are specified, they will be the partition fields of the new table. If `partition` is specified, the data will be inserted into the exact partition of the table. :param name: table name :param partitions: list of string, the partition fields :type partitions: list :param partition: persist to a specified partition :type partition: string or PartitionSpec :param lifecycle: table lifecycle. If absent, `options.lifecycle` will be used. :type lifecycle: int :param project: project name, if not provided, will be the default project :param hints: settings for SQL, e.g. `odps.sql.mapper.split.size` :type hints: dict :param priority: instance priority, 9 as default :type priority: int :param running_cluster: cluster to run this instance :param overwrite: overwrite the table, True as default :type overwrite: bool :param drop_table: drop table if exists, False as default :type drop_table: bool :param create_table: create table first if not exits, True as default :type create_table: bool :param drop_partition: drop partition if exists, False as default :type drop_partition: bool :param create_partition: create partition if not exists, None as default :type create_partition: bool :param cast: cast all columns' types as the existed table, False as default :type cast: bool :return: :class:`odps.df.DataFrame` :Example: """
if lifecycle is None and options.lifecycle is not None: lifecycle = \ options.lifecycle if not name.startswith(TEMP_TABLE_PREFIX) \ else options.temp_lifecycle return self._handle_delay_call('persist', self, name, partitions=partitions, partition=partition, lifecycle=lifecycle, project=project, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def query(self, expr): """ Query the data with a boolean expression. :param expr: the query string, you can use '@' character refer to environment variables. :return: new collection :rtype: :class:`odps.df.expr.expressions.CollectionExpr` """
from .query import CollectionVisitor if not isinstance(expr, six.string_types): raise ValueError('expr must be a string') frame = sys._getframe(2).f_locals try: env = frame.copy() finally: del frame visitor = CollectionVisitor(self, env) predicate = visitor.eval(expr) return self.filter(predicate)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def filter(self, *predicates): """ Filter the data by predicates :param predicates: the conditions to filter :return: new collection :rtype: :class:`odps.df.expr.expressions.CollectionExpr` """
predicates = self._get_fields(predicates) predicate = reduce(operator.and_, predicates) return FilterCollectionExpr(self, predicate, _schema=self._schema)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def select(self, *fields, **kw): """ Projection columns. Remember to avoid column names' conflict. :param fields: columns to project :param kw: columns and their names to project :return: new collection :rtype: :class:`odps.df.expr.expression.CollectionExpr` """
if len(fields) == 1 and isinstance(fields[0], list): fields = fields[0] else: fields = list(fields) if kw: def handle(it): it = self._defunc(it) if not isinstance(it, Expr): it = Scalar(it) return it fields.extend([handle(f).rename(new_name) for new_name, f in six.iteritems(kw)]) return self._project(fields)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def exclude(self, *fields): """ Projection columns which not included in the fields :param fields: field names :return: new collection :rtype: :class:`odps.df.expr.expression.CollectionExpr` """
if len(fields) == 1 and isinstance(fields[0], list): exclude_fields = fields[0] else: exclude_fields = list(fields) exclude_fields = [self._defunc(it) for it in exclude_fields] exclude_fields = [field.name if not isinstance(field, six.string_types) else field for field in exclude_fields] fields = [name for name in self._schema.names if name not in exclude_fields] return self._project(fields)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def head(self, n=None, **kwargs): """ Return the first n rows. Execute at once. :param n: :return: result frame :rtype: :class:`odps.df.backends.frame.ResultFrame` """
if n is None: n = options.display.max_rows return self._handle_delay_call('execute', self, head=n, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tail(self, n=None, **kwargs): """ Return the last n rows. Execute at once. :param n: :return: result frame :rtype: :class:`odps.df.backends.frame.ResultFrame` """
if n is None: n = options.display.max_rows return self._handle_delay_call('execute', self, tail=n, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_pandas(self, wrap=False, **kwargs): """ Convert to pandas DataFrame. Execute at once. :param wrap: if True, wrap the pandas DataFrame into a PyODPS DataFrame :return: pandas DataFrame """
try: import pandas as pd except ImportError: raise DependencyNotInstalledError( 'to_pandas requires `pandas` library') def wrapper(result): res = result.values if wrap: from .. import DataFrame return DataFrame(res, schema=self.schema) return res return self.execute(wrapper=wrapper, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def view(self): """ Clone a same collection. useful for self-join. :return: """
proxied = get_proxied_expr(self) kv = dict((attr, getattr(proxied, attr)) for attr in get_attrs(proxied)) return type(proxied)(**kv)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_pandas(self, wrap=False, **kwargs): """ Convert to pandas Series. Execute at once. :param wrap: if True, wrap the pandas DataFrame into a PyODPS DataFrame :return: pandas Series """
try: import pandas as pd except ImportError: raise DependencyNotInstalledError( 'to_pandas requires for `pandas` library') def wrapper(result): df = result.values if wrap: from .. import DataFrame df = DataFrame(df) return df[self.name] return self.execute(wrapper=wrapper, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def astype(self, data_type): """ Cast to a new data type. :param data_type: the new data type :return: casted sequence :Example: """
data_type = types.validate_data_type(data_type) if data_type == self._data_type: return self attr_dict = dict() attr_dict['_data_type'] = data_type attr_dict['_source_data_type'] = self._source_data_type attr_dict['_input'] = self new_sequence = AsTypedSequenceExpr(**attr_dict) return new_sequence
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def explode(expr, *args, **kwargs): """ Expand list or dict data into multiple rows :param expr: list / dict sequence / scalar :return: """
if not isinstance(expr, Column): expr = to_collection(expr)[expr.name] if isinstance(expr, SequenceExpr): dtype = expr.data_type else: dtype = expr.value_type func_name = 'EXPLODE' if args and isinstance(args[0], (list, tuple, set)): names = list(args[0]) else: names = args pos = kwargs.get('pos', False) if isinstance(expr, ListSequenceExpr): if pos: func_name = 'POSEXPLODE' typos = [df_types.int64, dtype.value_type] if not names: names = [expr.name + '_pos', expr.name] if len(names) == 1: names = [names[0] + '_pos', names[0]] if len(names) != 2: raise ValueError("The length of parameter 'names' should be exactly 1.") else: typos = [dtype.value_type] if not names: names = [expr.name] if len(names) != 1: raise ValueError("The length of parameter 'names' should be exactly 1.") elif isinstance(expr, DictSequenceExpr): if pos: raise ValueError('Cannot support explosion with pos on dicts.') typos = [dtype.key_type, dtype.value_type] if not names: names = [expr.name + '_key', expr.name + '_value'] if len(names) != 2: raise ValueError("The length of parameter 'names' should be exactly 2.") else: raise ValueError('Cannot explode expression with type %s' % type(expr).__name__) schema = Schema.from_lists(names, typos) return RowAppliedCollectionExpr(_input=expr.input, _func=func_name, _schema=schema, _fields=[expr], _keep_nulls=kwargs.get('keep_nulls', False))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _contains(expr, value): """ Check whether certain value is in the inspected list :param expr: list sequence / scalar :param value: value to inspect :return: """
return composite_op(expr, ListContains, df_types.boolean, _value=_scalar(value))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _keys(expr): """ Retrieve keys of a dict :param expr: dict sequence / scalar :return: """
if isinstance(expr, SequenceExpr): dtype = expr.data_type else: dtype = expr.value_type return composite_op(expr, DictKeys, df_types.List(dtype.key_type))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _values(expr): """ Retrieve values of a dict :param expr: dict sequence / scalar :return: """
if isinstance(expr, SequenceExpr): dtype = expr.data_type else: dtype = expr.value_type return composite_op(expr, DictValues, df_types.List(dtype.value_type))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mean_squared_error(df, col_true, col_pred=None): """ Compute mean squared error of a predicted DataFrame. Note that this method will trigger the defined flow to execute. :param df: predicted data frame :type df: DataFrame :param col_true: column name of true value :type col_true: str :param col_true: column name of predicted value, 'prediction_score' by default. :type col_pred: str :return: Mean squared error :rtype: float """
if not col_pred: col_pred = get_field_name_by_role(df, FieldRole.PREDICTED_VALUE) return _run_evaluation_node(df, col_true, col_pred)['mse']
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mean_absolute_error(df, col_true, col_pred=None): """ Compute mean absolute error of a predicted DataFrame. Note that this method will trigger the defined flow to execute. :param df: predicted data frame :type df: DataFrame :param col_true: column name of true value :type col_true: str :param col_true: column name of predicted value, 'prediction_score' by default. :type col_pred: str :return: Mean absolute error :rtype: float """
if not col_pred: col_pred = get_field_name_by_role(df, FieldRole.PREDICTED_VALUE) return _run_evaluation_node(df, col_true, col_pred)['mae']
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mean_absolute_percentage_error(df, col_true, col_pred=None): """ Compute mean absolute percentage error of a predicted DataFrame. Note that this method will trigger the defined flow to execute. :param df: predicted data frame :type df: DataFrame :param col_true: column name of true value :type col_true: str :param col_true: column name of predicted value, 'prediction_score' by default. :type col_pred: str :return: Mean absolute percentage error :rtype: float """
if not col_pred: col_pred = get_field_name_by_role(df, FieldRole.PREDICTED_VALUE) return _run_evaluation_node(df, col_true, col_pred)['mape']
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def residual_histogram(df, col_true, col_pred=None): """ Compute histogram of residuals of a predicted DataFrame. Note that this method will trigger the defined flow to execute. :param df: predicted data frame :type df: DataFrame :param col_true: column name of true value :type col_true: str :param col_true: column name of predicted value, 'prediction_score' by default. :type col_pred: str :return: histograms for every columns, containing histograms and bins. """
if not col_pred: col_pred = get_field_name_by_role(df, FieldRole.PREDICTED_VALUE) return _run_evaluation_node(df, col_true, col_pred)['hist']
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def put_info(self, key, value): """ Put associated information of the task. """
return self.instance.put_task_info(self.name, key, value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def append_little_endian32(self, unsigned_value): """Appends an unsigned 32-bit integer to the internal buffer, in little-endian byte order. """
if not 0 <= unsigned_value <= wire_format.UINT32_MAX: raise errors.EncodeError( 'Unsigned 32-bit out of range: %d' % unsigned_value) self.append_raw_bytes(struct.pack( wire_format.FORMAT_UINT32_LITTLE_ENDIAN, unsigned_value))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def append_little_endian64(self, unsigned_value): """Appends an unsigned 64-bit integer to the internal buffer, in little-endian byte order. """
if not 0 <= unsigned_value <= wire_format.UINT64_MAX: raise errors.EncodeError( 'Unsigned 64-bit out of range: %d' % unsigned_value) self.append_raw_bytes(struct.pack( wire_format.FORMAT_UINT64_LITTLE_ENDIAN, unsigned_value))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def append_var_uint32(self, value): """Appends an unsigned 32-bit integer to the internal buffer, encoded as a varint. """
if not 0 <= value <= wire_format.UINT32_MAX: raise errors.EncodeError('Value out of range: %d' % value) self.append_var_uint64(value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def append_varint64(self, value): """Appends a signed 64-bit integer to the internal buffer, encoded as a varint. """
if not wire_format.INT64_MIN <= value <= wire_format.INT64_MAX: raise errors.EncodeError('Value out of range: %d' % value) if value < 0: value += (1 << 64) self.append_var_uint64(value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def append_var_uint64(self, unsigned_value): """Appends an unsigned 64-bit integer to the internal buffer, encoded as a varint. """
if not 0 <= unsigned_value <= wire_format.UINT64_MAX: raise errors.EncodeError('Value out of range: %d' % unsigned_value) while True: bits = unsigned_value & 0x7f unsigned_value >>= 7 if unsigned_value: bits |= 0x80 self._buffer.append(bits) if not unsigned_value: break
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def groupby(expr, by, *bys): """ Group collection by a series of sequences. :param expr: collection :param by: columns to group :param bys: columns to group :return: GroupBy instance :rtype: :class:`odps.df.expr.groupby.GroupBy` """
if not isinstance(by, list): by = [by, ] if len(bys) > 0: by = by + list(bys) return GroupBy(_input=expr, _by=by)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def value_counts(expr, sort=True, ascending=False, dropna=False): """ Return object containing counts of unique values. The resulting object will be in descending order so that the first element is the most frequently-occuring element. Exclude NA values by default :param expr: sequence :param sort: if sort :type sort: bool :param dropna: Don’t include counts of None, default False :return: collection with two columns :rtype: :class:`odps.df.expr.expressions.CollectionExpr` """
names = [expr.name, 'count'] typos = [expr.dtype, types.int64] return ValueCounts(_input=expr, _schema=Schema.from_lists(names, typos), _sort=sort, _ascending=ascending, _dropna=dropna)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _hashes(self, item): """ To create the hash functions we use the SHA-1 hash of the string and chop that up into 20 bit values and then mod down to the length of the Bloom filter. """
item = self._binary(item) m = hashlib.sha1() m.update(item) digits = m.hexdigest() # Add another 160 bits for every 8 (20-bit long) hashes we need for i in range(int(self.num_hashes // 8)): m.update(self._binary(str(i))) digits += m.hexdigest() hashes = [int(digits[i*5:i*5+5], 16) % self.hashbits for i in range(self.num_hashes)] return hashes
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def join(left, right, on=None, how='inner', suffixes=('_x', '_y'), mapjoin=False): """ Join two collections. If `on` is not specified, we will find the common fields of the left and right collection. `suffixes` means that if column names conflict, the suffixes will be added automatically. For example, both left and right has a field named `col`, there will be col_x, and col_y in the joined collection. :param left: left collection :param right: right collection :param on: fields to join on :param how: 'inner', 'left', 'right', or 'outer' :param suffixes: when name conflict, the suffix will be added to both columns. :param mapjoin: set use mapjoin or not, default value False. :return: collection :Example: ['name', 'id'] ['name', 'id1'] """
if on is None and not mapjoin: on = [name for name in left.schema.names if name in right.schema._name_indexes] if isinstance(suffixes, (tuple, list)) and len(suffixes) == 2: left_suffix, right_suffix = suffixes else: raise ValueError('suffixes must be a tuple or list with two elements, got %s' % suffixes) if not isinstance(on, list): on = [on, ] for i in range(len(on)): it = on[i] if inspect.isfunction(it): on[i] = it(left, right) left, right = _make_different_sources(left, right, on) try: return _join_dict[how.upper()](_lhs=left, _rhs=right, _predicate=on, _left_suffix=left_suffix, _right_suffix=right_suffix, _mapjoin=mapjoin) except KeyError: return JoinCollectionExpr(_lhs=left, _rhs=right, _predicate=on, _how=how, _left_suffix=left_suffix, _right_suffix=right_suffix, _mapjoin=mapjoin)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def inner_join(left, right, on=None, suffixes=('_x', '_y'), mapjoin=False): """ Inner join two collections. If `on` is not specified, we will find the common fields of the left and right collection. `suffixes` means that if column names conflict, the suffixes will be added automatically. For example, both left and right has a field named `col`, there will be col_x, and col_y in the joined collection. :param left: left collection :param right: right collection :param on: fields to join on :param suffixes: when name conflict, the suffixes will be added to both columns. :return: collection :Example: ['name', 'id'] ['name', 'id1'] """
return join(left, right, on, suffixes=suffixes, mapjoin=mapjoin)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def left_join(left, right, on=None, suffixes=('_x', '_y'), mapjoin=False, merge_columns=None): """ Left join two collections. If `on` is not specified, we will find the common fields of the left and right collection. `suffixes` means that if column names conflict, the suffixes will be added automatically. For example, both left and right has a field named `col`, there will be col_x, and col_y in the joined collection. :param left: left collection :param right: right collection :param on: fields to join on :param suffixes: when name conflict, the suffixes will be added to both columns. :param mapjoin: set use mapjoin or not, default value False. :param merge_columns: whether to merge columns with the same name into one column without suffix. If the value is True, columns in the predicate with same names will be merged, with non-null value. If the value is 'left' or 'right', the values of predicates on the left / right collection will be taken. You can also pass a dictionary to describe the behavior of each column, such as { 'a': 'auto', 'b': 'left' }. :return: collection :Example: ['name', 'id'] ['name', 'id1'] """
joined = join(left, right, on, how='left', suffixes=suffixes, mapjoin=mapjoin) return joined._merge_joined_fields(merge_columns)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def union(left, right, distinct=False): """ Union two collections. :param left: left collection :param right: right collection :param distinct: :return: collection :Example: """
left, right = _make_different_sources(left, right) return UnionCollectionExpr(_lhs=left, _rhs=right, _distinct=distinct)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def concat(left, rights, distinct=False, axis=0): """ Concat collections. :param left: left collection :param rights: right collections, can be a DataFrame object or a list of DataFrames :param distinct: whether to remove duplicate entries. only available when axis == 0 :param axis: when axis == 0, the DataFrames are merged vertically, otherwise horizontally. :return: collection Note that axis==1 can only be used under Pandas DataFrames or XFlow. :Example: """
from ..utils import to_collection if isinstance(rights, Node): rights = [rights, ] if not rights: raise ValueError('At least one DataFrame should be provided.') if axis == 0: for right in rights: left = union(left, right, distinct=distinct) return left else: rights = [to_collection(r) for r in rights] ConcatCollectionExpr.validate_input(left, *rights) if hasattr(left, '_xflow_concat'): return left._xflow_concat(rights) else: return __horz_concat(left, rights)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _drop(expr, data, axis=0, columns=None): """ Drop data from a DataFrame. :param expr: collection to drop data from :param data: data to be removed :param axis: 0 for deleting rows, 1 for columns. :param columns: columns of data to select, only useful when axis == 0 :return: collection :Example: a b c 0 1 4 7 1 3 6 9 a b c 0 1 4 7 b c 0 4 7 1 5 8 2 6 9 c 0 7 1 8 2 9 """
from ..utils import to_collection expr = to_collection(expr) if axis == 0: if not isinstance(data, (CollectionExpr, SequenceExpr)): raise ExpressionError('data should be a collection or sequence when axis == 1.') data = to_collection(data) if columns is None: columns = [n for n in data.schema.names] if isinstance(columns, six.string_types): columns = [columns, ] data = data.select(*columns).distinct() drop_predicates = [data[n].isnull() for n in data.schema.names] return expr.left_join(data, on=columns, suffixes=('', '_dp')).filter(*drop_predicates) \ .select(*expr.schema.names) else: if isinstance(data, (CollectionExpr, SequenceExpr)): data = to_collection(data).schema.names return expr.exclude(data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setdiff(left, *rights, **kwargs): """ Exclude data from a collection, like `except` clause in SQL. All collections involved should have same schema. :param left: collection to drop data from :param rights: collection or list of collections :param distinct: whether to preserve duplicate entries :return: collection :Examples: a b 0 2 2 1 3 3 2 3 3 a b 0 2 2 """
import time from ..utils import output distinct = kwargs.get('distinct', False) if isinstance(rights[0], list): rights = rights[0] cols = [n for n in left.schema.names] types = [n for n in left.schema.types] counter_col_name = 'exc_counter_%d' % int(time.time()) left = left[left, Scalar(1).rename(counter_col_name)] rights = [r[r, Scalar(-1).rename(counter_col_name)] for r in rights] unioned = left for r in rights: unioned = unioned.union(r) if distinct: aggregated = unioned.groupby(*cols).agg(**{counter_col_name: unioned[counter_col_name].min()}) return aggregated.filter(aggregated[counter_col_name] == 1).select(*cols) else: aggregated = unioned.groupby(*cols).agg(**{counter_col_name: unioned[counter_col_name].sum()}) @output(cols, types) def exploder(row): import sys irange = xrange if sys.version_info[0] < 3 else range for _ in irange(getattr(row, counter_col_name)): yield row[:-1] return aggregated.map_reduce(mapper=exploder).select(*cols)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def intersect(left, *rights, **kwargs): """ Calc intersection among datasets, :param left: collection :param rights: collection or list of collections :param distinct: whether to preserve duolicate entries :return: collection :Examples: a b 0 1 1 1 3 3 2 3 3 a b 0 1 1 1 3 3 """
import time from ..utils import output distinct = kwargs.get('distinct', False) if isinstance(rights[0], list): rights = rights[0] cols = [n for n in left.schema.names] types = [n for n in left.schema.types] collections = (left, ) + rights idx_col_name = 'idx_%d' % int(time.time()) counter_col_name = 'exc_counter_%d' % int(time.time()) collections = [c[c, Scalar(idx).rename(idx_col_name)] for idx, c in enumerate(collections)] unioned = reduce(lambda a, b: a.union(b), collections) src_agg = unioned.groupby(*(cols + [idx_col_name])) \ .agg(**{counter_col_name: unioned.count()}) aggregators = { idx_col_name: src_agg[idx_col_name].nunique(), counter_col_name: src_agg[counter_col_name].min(), } final_agg = src_agg.groupby(*cols).agg(**aggregators) final_agg = final_agg.filter(final_agg[idx_col_name] == len(collections)) if distinct: return final_agg.filter(final_agg[counter_col_name] > 0).select(*cols) else: @output(cols, types) def exploder(row): import sys irange = xrange if sys.version_info[0] < 3 else range for _ in irange(getattr(row, counter_col_name)): yield row[:-2] return final_agg.map_reduce(mapper=exploder).select(*cols)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _verify_and_add_jwt(): """ This helper method just checks and adds jwt data to the app context. Will not add jwt data if it is already present. Only use in this module """
if not app_context_has_jwt_data(): guard = current_guard() token = guard.read_token_from_header() jwt_data = guard.extract_jwt_token(token) add_jwt_data_to_app_context(jwt_data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def auth_required(method): """ This decorator is used to ensure that a user is authenticated before being able to access a flask route. It also adds the current user to the current flask context. """
@functools.wraps(method) def wrapper(*args, **kwargs): _verify_and_add_jwt() try: return method(*args, **kwargs) finally: remove_jwt_data_from_app_context() return wrapper
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def roles_required(*required_rolenames): """ This decorator ensures that any uses accessing the decorated route have all the needed roles to access it. If an @auth_required decorator is not supplied already, this decorator will implicitly check @auth_required first """
def decorator(method): @functools.wraps(method) def wrapper(*args, **kwargs): role_set = set([str(n) for n in required_rolenames]) _verify_and_add_jwt() try: MissingRoleError.require_condition( current_rolenames().issuperset(role_set), "This endpoint requires all the following roles: {}", [', '.join(role_set)], ) return method(*args, **kwargs) finally: remove_jwt_data_from_app_context() return wrapper return decorator
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def roles_accepted(*accepted_rolenames): """ This decorator ensures that any uses accessing the decorated route have one of the needed roles to access it. If an @auth_required decorator is not supplied already, this decorator will implicitly check @auth_required first """
def decorator(method): @functools.wraps(method) def wrapper(*args, **kwargs): role_set = set([str(n) for n in accepted_rolenames]) _verify_and_add_jwt() try: MissingRoleError.require_condition( not current_rolenames().isdisjoint(role_set), "This endpoint requires one of the following roles: {}", [', '.join(role_set)], ) return method(*args, **kwargs) finally: remove_jwt_data_from_app_context() return wrapper return decorator
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def init_app(self, app, user_class, is_blacklisted=None): """ Initializes the Praetorian extension :param: app: The flask app to bind this extension to :param: user_class: The class used to interact with user data :param: is_blacklisted: A method that may optionally be used to check the token against a blacklist when access or refresh is requested Should take the jti for the token to check as a single argument. Returns True if the jti is blacklisted, False otherwise. By default, always returns False. """
PraetorianError.require_condition( app.config.get('SECRET_KEY') is not None, "There must be a SECRET_KEY app config setting set", ) possible_schemes = [ 'argon2', 'bcrypt', 'pbkdf2_sha512', ] self.pwd_ctx = CryptContext( default='pbkdf2_sha512', schemes=possible_schemes + ['plaintext'], deprecated=[], ) self.hash_scheme = app.config.get('PRAETORIAN_HASH_SCHEME') valid_schemes = self.pwd_ctx.schemes() PraetorianError.require_condition( self.hash_scheme in valid_schemes or self.hash_scheme is None, "If {} is set, it must be one of the following schemes: {}", 'PRAETORIAN_HASH_SCHEME', valid_schemes, ) self.user_class = self._validate_user_class(user_class) self.is_blacklisted = is_blacklisted or (lambda t: False) self.encode_key = app.config['SECRET_KEY'] self.allowed_algorithms = app.config.get( 'JWT_ALLOWED_ALGORITHMS', DEFAULT_JWT_ALLOWED_ALGORITHMS, ) self.encode_algorithm = app.config.get( 'JWT_ALGORITHM', DEFAULT_JWT_ALGORITHM, ) self.access_lifespan = pendulum.Duration(**app.config.get( 'JWT_ACCESS_LIFESPAN', DEFAULT_JWT_ACCESS_LIFESPAN, )) self.refresh_lifespan = pendulum.Duration(**app.config.get( 'JWT_REFRESH_LIFESPAN', DEFAULT_JWT_REFRESH_LIFESPAN, )) self.header_name = app.config.get( 'JWT_HEADER_NAME', DEFAULT_JWT_HEADER_NAME, ) self.header_type = app.config.get( 'JWT_HEADER_TYPE', DEFAULT_JWT_HEADER_TYPE, ) self.user_class_validation_method = app.config.get( 'USER_CLASS_VALIDATION_METHOD', DEFAULT_USER_CLASS_VALIDATION_METHOD, ) if not app.config.get('DISABLE_PRAETORIAN_ERROR_HANDLER'): app.register_error_handler( PraetorianError, PraetorianError.build_error_handler(), ) self.is_testing = app.config.get('TESTING', False) if not hasattr(app, 'extensions'): app.extensions = {} app.extensions['praetorian'] = self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _validate_user_class(cls, user_class): """ Validates the supplied user_class to make sure that it has the class methods necessary to function correctly. Requirements: - ``lookup`` method. Accepts a string parameter, returns instance - ``identify`` method. Accepts an identity parameter, returns instance """
PraetorianError.require_condition( getattr(user_class, 'lookup', None) is not None, textwrap.dedent(""" The user_class must have a lookup class method: user_class.lookup(<str>) -> <user instance> """), ) PraetorianError.require_condition( getattr(user_class, 'identify', None) is not None, textwrap.dedent(""" The user_class must have an identify class method: user_class.identify(<identity>) -> <user instance> """), ) # TODO: Figure out how to check for an identity property return user_class
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def authenticate(self, username, password): """ Verifies that a password matches the stored password for that username. If verification passes, the matching user instance is returned """
PraetorianError.require_condition( self.user_class is not None, "Praetorian must be initialized before this method is available", ) user = self.user_class.lookup(username) MissingUserError.require_condition( user is not None, 'Could not find the requested user', ) AuthenticationError.require_condition( self._verify_password(password, user.password), 'The password is incorrect', ) return user
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _verify_password(self, raw_password, hashed_password): """ Verifies that a plaintext password matches the hashed version of that password using the stored passlib password context """
PraetorianError.require_condition( self.pwd_ctx is not None, "Praetorian must be initialized before this method is available", ) return self.pwd_ctx.verify(raw_password, hashed_password)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def encrypt_password(self, raw_password): """ Encrypts a plaintext password using the stored passlib password context """
PraetorianError.require_condition( self.pwd_ctx is not None, "Praetorian must be initialized before this method is available", ) return self.pwd_ctx.encrypt(raw_password, scheme=self.hash_scheme)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _check_user(self, user): """ Checks to make sure that a user is valid. First, checks that the user is not None. If this check fails, a MissingUserError is raised. Next, checks if the user has a validation method. If the method does not exist, the check passes. If the method exists, it is called. If the result of the call is not truthy, an InvalidUserError is raised """
MissingUserError.require_condition( user is not None, 'Could not find the requested user', ) user_validate_method = getattr( user, self.user_class_validation_method, None ) if user_validate_method is None: return InvalidUserError.require_condition( user_validate_method(), "The user is not valid or has had access revoked", )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def encode_jwt_token( self, user, override_access_lifespan=None, override_refresh_lifespan=None, **custom_claims ): """ Encodes user data into a jwt token that can be used for authorization at protected endpoints :param: override_access_lifespan: Override's the instance's access lifespan to set a custom duration after which the new token's accessability will expire. May not exceed the refresh_lifespan :param: override_refresh_lifespan: Override's the instance's refresh lifespan to set a custom duration after which the new token's refreshability will expire. :param: custom_claims: Additional claims that should be packed in the payload. Note that any claims supplied here must be JSON compatible types """
ClaimCollisionError.require_condition( set(custom_claims.keys()).isdisjoint(RESERVED_CLAIMS), "The custom claims collide with required claims", ) self._check_user(user) moment = pendulum.now('UTC') if override_refresh_lifespan is None: refresh_lifespan = self.refresh_lifespan else: refresh_lifespan = override_refresh_lifespan refresh_expiration = (moment + refresh_lifespan).int_timestamp if override_access_lifespan is None: access_lifespan = self.access_lifespan else: access_lifespan = override_access_lifespan access_expiration = min( (moment + access_lifespan).int_timestamp, refresh_expiration, ) payload_parts = dict( iat=moment.int_timestamp, exp=access_expiration, rf_exp=refresh_expiration, jti=str(uuid.uuid4()), id=user.identity, rls=','.join(user.rolenames), **custom_claims ) return jwt.encode( payload_parts, self.encode_key, self.encode_algorithm, ).decode('utf-8')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def encode_eternal_jwt_token(self, user, **custom_claims): """ This utility function encodes a jwt token that never expires .. note:: This should be used sparingly since the token could become a security concern if it is ever lost. If you use this method, you should be sure that your application also implements a blacklist so that a given token can be blocked should it be lost or become a security concern """
return self.encode_jwt_token( user, override_access_lifespan=VITAM_AETERNUM, override_refresh_lifespan=VITAM_AETERNUM, **custom_claims )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def refresh_jwt_token(self, token, override_access_lifespan=None): """ Creates a new token for a user if and only if the old token's access permission is expired but its refresh permission is not yet expired. The new token's refresh expiration moment is the same as the old token's, but the new token's access expiration is refreshed :param: token: The existing jwt token that needs to be replaced with a new, refreshed token :param: override_access_lifespan: Override's the instance's access lifespan to set a custom duration after which the new token's accessability will expire. May not exceed the refresh lifespan """
moment = pendulum.now('UTC') # Note: we disable exp verification because we do custom checks here with InvalidTokenHeader.handle_errors('failed to decode JWT token'): data = jwt.decode( token, self.encode_key, algorithms=self.allowed_algorithms, options={'verify_exp': False}, ) self._validate_jwt_data(data, access_type=AccessType.refresh) user = self.user_class.identify(data['id']) self._check_user(user) if override_access_lifespan is None: access_lifespan = self.access_lifespan else: access_lifespan = override_access_lifespan refresh_expiration = data['rf_exp'] access_expiration = min( (moment + access_lifespan).int_timestamp, refresh_expiration, ) custom_claims = { k: v for (k, v) in data.items() if k not in RESERVED_CLAIMS } payload_parts = dict( iat=moment.int_timestamp, exp=access_expiration, rf_exp=refresh_expiration, jti=data['jti'], id=data['id'], rls=','.join(user.rolenames), **custom_claims ) return jwt.encode( payload_parts, self.encode_key, self.encode_algorithm, ).decode('utf-8')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extract_jwt_token(self, token): """ Extracts a data dictionary from a jwt token """
# Note: we disable exp verification because we will do it ourselves with InvalidTokenHeader.handle_errors('failed to decode JWT token'): data = jwt.decode( token, self.encode_key, algorithms=self.allowed_algorithms, options={'verify_exp': False}, ) self._validate_jwt_data(data, access_type=AccessType.access) return data
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _validate_jwt_data(self, data, access_type): """ Validates that the data for a jwt token is valid """
MissingClaimError.require_condition( 'jti' in data, 'Token is missing jti claim', ) BlacklistedError.require_condition( not self.is_blacklisted(data['jti']), 'Token has a blacklisted jti', ) MissingClaimError.require_condition( 'id' in data, 'Token is missing id field', ) MissingClaimError.require_condition( 'exp' in data, 'Token is missing exp claim', ) MissingClaimError.require_condition( 'rf_exp' in data, 'Token is missing rf_exp claim', ) moment = pendulum.now('UTC').int_timestamp if access_type == AccessType.access: ExpiredAccessError.require_condition( moment <= data['exp'], 'access permission has expired', ) elif access_type == AccessType.refresh: EarlyRefreshError.require_condition( moment > data['exp'], 'access permission for token has not expired. may not refresh', ) ExpiredRefreshError.require_condition( moment <= data['rf_exp'], 'refresh permission for token has expired', )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _unpack_header(self, headers): """ Unpacks a jwt token from a request header """
jwt_header = headers.get(self.header_name) MissingTokenHeader.require_condition( jwt_header is not None, "JWT token not found in headers under '{}'", self.header_name, ) match = re.match(self.header_type + r'\s*([\w\.-]+)', jwt_header) InvalidTokenHeader.require_condition( match is not None, "JWT header structure is invalid", ) token = match.group(1) return token
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pack_header_for_user( self, user, override_access_lifespan=None, override_refresh_lifespan=None, **custom_claims ): """ Encodes a jwt token and packages it into a header dict for a given user :param: user: The user to package the header for :param: override_access_lifespan: Override's the instance's access lifespan to set a custom duration after which the new token's accessability will expire. May not exceed the refresh_lifespan :param: override_refresh_lifespan: Override's the instance's refresh lifespan to set a custom duration after which the new token's refreshability will expire. :param: custom_claims: Additional claims that should be packed in the payload. Note that any claims supplied here must be JSON compatible types """
token = self.encode_jwt_token( user, override_access_lifespan=override_access_lifespan, override_refresh_lifespan=override_refresh_lifespan, **custom_claims ) return {self.header_name: self.header_type + ' ' + token}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def refresh(): """ Refreshes an existing JWT by creating a new one that is a copy of the old except that it has a refrehsed access expiration. .. example:: $ curl http://localhost:5000/refresh -X GET \ -H "Authorization: Bearer <your_token>" """
old_token = guard.read_token_from_header() new_token = guard.refresh_jwt_token(old_token) ret = {'access_token': new_token} return flask.jsonify(ret), 200
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def disable_user(): """ Disables a user in the data store .. example:: $ curl http://localhost:5000/disable_user -X POST \ -H "Authorization: Bearer <your_token>" \ -d '{"username":"Walter"}' """
req = flask.request.get_json(force=True) usr = User.query.filter_by(username=req.get('username', None)).one() usr.is_active = False db.session.commit() return flask.jsonify(message='disabled user {}'.format(usr.username))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def blacklist_token(): """ Blacklists an existing JWT by registering its jti claim in the blacklist. .. example:: $ curl http://localhost:5000/blacklist_token -X POST \ -d '{"token":"<your_token>"}' """
req = flask.request.get_json(force=True) data = guard.extract_jwt_token(req['token']) blacklist.add(data['jti']) return flask.jsonify(message='token blacklisted ({})'.format(req['token']))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def protected(): """ A protected endpoint. The auth_required decorator will require a header containing a valid JWT .. example:: $ curl http://localhost:5000/protected -X GET \ -H "Authorization: Bearer <your_token>" """
custom_claims = flask_praetorian.current_custom_claims() firstname = custom_claims.pop('firstname', None) nickname = custom_claims.pop('nickname', None) surname = custom_claims.pop('surname', None) if nickname is None: user_string = "{} {}".format(firstname, surname) else: user_string = "{} '{}' {}".format(firstname, nickname, surname) return flask.jsonify( message="protected endpoint (allowed user {u})".format(u=user_string), )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def current_guard(): """ Fetches the current instance of flask-praetorian that is attached to the current flask app """
guard = flask.current_app.extensions.get('praetorian', None) PraetorianError.require_condition( guard is not None, "No current guard found; Praetorian must be initialized first", ) return guard
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def current_user_id(): """ This method returns the user id retrieved from jwt token data attached to the current flask app's context """
jwt_data = get_jwt_data_from_app_context() user_id = jwt_data.get('id') PraetorianError.require_condition( user_id is not None, "Could not fetch an id for the current user", ) return user_id
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def current_user(): """ This method returns a user instance for jwt token data attached to the current flask app's context """
user_id = current_user_id() guard = current_guard() user = guard.user_class.identify(user_id) PraetorianError.require_condition( user is not None, "Could not identify the current user from the current id", ) return user
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def current_rolenames(): """ This method returns the names of all roles associated with the current user """
jwt_data = get_jwt_data_from_app_context() if 'rls' not in jwt_data: # This is necessary so our set arithmetic works correctly return set(['non-empty-but-definitely-not-matching-subset']) else: return set(r.strip() for r in jwt_data['rls'].split(','))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def current_custom_claims(): """ This method returns any custom claims in the current jwt """
jwt_data = get_jwt_data_from_app_context() return {k: v for (k, v) in jwt_data.items() if k not in RESERVED_CLAIMS}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_redirect_uris(uris, client_type=None): """ This function checks all return uris provided and tries to deduce as what type of client we should register. :param uris: The redirect URIs to check. :type uris: list :param client_type: An indicator of which client type you are expecting to be used. If this does not match the deduced type, an error will be raised. :type client_type: str :returns: The deduced client type. :rtype: str :raises ValueError: An error occured while checking the redirect uris. .. versionadded:: 1.0 """
if client_type not in [None, 'native', 'web']: raise ValueError('Invalid client type indicator used') if not isinstance(uris, list): raise ValueError('uris needs to be a list of strings') if len(uris) < 1: raise ValueError('At least one return URI needs to be provided') for uri in uris: if uri.startswith('https://'): if client_type == 'native': raise ValueError('https url with native client') client_type = 'web' elif uri.startswith('http://localhost'): if client_type == 'web': raise ValueError('http://localhost url with web client') client_type = 'native' else: if (uri.startswith('http://') and not uri.startswith('http://localhost')): raise ValueError('http:// url with non-localhost is illegal') else: raise ValueError('Invalid uri provided: %s' % uri) return client_type
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register_client(provider_info, redirect_uris): """ This function registers a new client with the specified OpenID Provider, and then returns the regitered client ID and other information. :param provider_info: The contents of the discovery endpoint as specified by the OpenID Connect Discovery 1.0 specifications. :type provider_info: dict :param redirect_uris: The redirect URIs the application wants to register. :type redirect_uris: list :returns: An object containing the information needed to configure the actual client code to communicate with the OpenID Provider. :rtype: dict :raises ValueError: The same error as used by check_redirect_uris. :raises RegistrationError: Indicates an error was returned by the OpenID Provider during registration. .. versionadded:: 1.0 """
client_type = check_redirect_uris(redirect_uris) submit_info = {'redirect_uris': redirect_uris, 'application_type': client_type, 'token_endpoint_auth_method': 'client_secret_post'} headers = {'Content-type': 'application/json'} resp, content = httplib2.Http().request( provider_info['registration_endpoint'], 'POST', json.dumps(submit_info), headers=headers) if int(resp['status']) >= 400: raise Exception('Error: the server returned HTTP ' + resp['status']) client_info = _json_loads(content) if 'error' in client_info: raise Exception('Error occured during registration: %s (%s)' % (client_info['error'], client_info.get('error_description'))) json_file = {'web': { 'client_id': client_info['client_id'], 'client_secret': client_info['client_secret'], 'auth_uri': provider_info['authorization_endpoint'], 'token_uri': provider_info['token_endpoint'], 'userinfo_uri': provider_info['userinfo_endpoint'], 'redirect_uris': redirect_uris, 'issuer': provider_info['issuer'], }} return json_file
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def discover_OP_information(OP_uri): """ Discovers information about the provided OpenID Provider. :param OP_uri: The base URI of the Provider information is requested for. :type OP_uri: str :returns: The contents of the Provider metadata document. :rtype: dict .. versionadded:: 1.0 """
_, content = httplib2.Http().request( '%s/.well-known/openid-configuration' % OP_uri) return _json_loads(content)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def init_app(self, app): """ Do setup that requires a Flask app. :param app: The application to initialize. :type app: Flask """
secrets = self.load_secrets(app) self.client_secrets = list(secrets.values())[0] secrets_cache = DummySecretsCache(secrets) # Set some default configuration options app.config.setdefault('OIDC_SCOPES', ['openid', 'email']) app.config.setdefault('OIDC_GOOGLE_APPS_DOMAIN', None) app.config.setdefault('OIDC_ID_TOKEN_COOKIE_NAME', 'oidc_id_token') app.config.setdefault('OIDC_ID_TOKEN_COOKIE_PATH', '/') app.config.setdefault('OIDC_ID_TOKEN_COOKIE_TTL', 7 * 86400) # 7 days # should ONLY be turned off for local debugging app.config.setdefault('OIDC_COOKIE_SECURE', True) app.config.setdefault('OIDC_VALID_ISSUERS', (self.client_secrets.get('issuer') or GOOGLE_ISSUERS)) app.config.setdefault('OIDC_CLOCK_SKEW', 60) # 1 minute app.config.setdefault('OIDC_REQUIRE_VERIFIED_EMAIL', False) app.config.setdefault('OIDC_OPENID_REALM', None) app.config.setdefault('OIDC_USER_INFO_ENABLED', True) app.config.setdefault('OIDC_CALLBACK_ROUTE', '/oidc_callback') app.config.setdefault('OVERWRITE_REDIRECT_URI', False) app.config.setdefault("OIDC_EXTRA_REQUEST_AUTH_PARAMS", {}) # Configuration for resource servers app.config.setdefault('OIDC_RESOURCE_SERVER_ONLY', False) app.config.setdefault('OIDC_RESOURCE_CHECK_AUD', False) # We use client_secret_post, because that's what the Google # oauth2client library defaults to app.config.setdefault('OIDC_INTROSPECTION_AUTH_METHOD', 'client_secret_post') app.config.setdefault('OIDC_TOKEN_TYPE_HINT', 'access_token') if not 'openid' in app.config['OIDC_SCOPES']: raise ValueError('The value "openid" must be in the OIDC_SCOPES') # register callback route and cookie-setting decorator if not app.config['OIDC_RESOURCE_SERVER_ONLY']: app.route(app.config['OIDC_CALLBACK_ROUTE'])(self._oidc_callback) app.before_request(self._before_request) app.after_request(self._after_request) # Initialize oauth2client self.flow = flow_from_clientsecrets( app.config['OIDC_CLIENT_SECRETS'], scope=app.config['OIDC_SCOPES'], cache=secrets_cache) assert isinstance(self.flow, OAuth2WebServerFlow) # create signers using the Flask secret key self.extra_data_serializer = JSONWebSignatureSerializer( app.config['SECRET_KEY'], salt='flask-oidc-extra-data') self.cookie_serializer = JSONWebSignatureSerializer( app.config['SECRET_KEY'], salt='flask-oidc-cookie') try: self.credentials_store = app.config['OIDC_CREDENTIALS_STORE'] except KeyError: pass
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def user_getfield(self, field, access_token=None): """ Request a single field of information about the user. :param field: The name of the field requested. :type field: str :returns: The value of the field. Depending on the type, this may be a string, list, dict, or something else. :rtype: object .. versionadded:: 1.0 """
info = self.user_getinfo([field], access_token) return info.get(field)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def user_getinfo(self, fields, access_token=None): """ Request multiple fields of information about the user. :param fields: The names of the fields requested. :type fields: list :returns: The values of the current user for the fields requested. The keys are the field names, values are the values of the fields as indicated by the OpenID Provider. Note that fields that were not provided by the Provider are absent. :rtype: dict :raises Exception: If the user was not authenticated. Check this with user_loggedin. .. versionadded:: 1.0 """
if g.oidc_id_token is None and access_token is None: raise Exception('User was not authenticated') info = {} all_info = None for field in fields: if access_token is None and field in g.oidc_id_token: info[field] = g.oidc_id_token[field] elif current_app.config['OIDC_USER_INFO_ENABLED']: # This was not in the id_token. Let's get user information if all_info is None: all_info = self._retrieve_userinfo(access_token) if all_info is None: # To make sure we don't retry for every field all_info = {} if field in all_info: info[field] = all_info[field] else: # We didn't get this information pass return info
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_access_token(self): """Method to return the current requests' access_token. :returns: Access token or None :rtype: str .. versionadded:: 1.2 """
try: credentials = OAuth2Credentials.from_json( self.credentials_store[g.oidc_id_token['sub']]) return credentials.access_token except KeyError: logger.debug("Expired ID token, credentials missing", exc_info=True) return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_refresh_token(self): """Method to return the current requests' refresh_token. :returns: Access token or None :rtype: str .. versionadded:: 1.2 """
try: credentials = OAuth2Credentials.from_json( self.credentials_store[g.oidc_id_token['sub']]) return credentials.refresh_token except KeyError: logger.debug("Expired ID token, credentials missing", exc_info=True) return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _retrieve_userinfo(self, access_token=None): """ Requests extra user information from the Provider's UserInfo and returns the result. :returns: The contents of the UserInfo endpoint. :rtype: dict """
if 'userinfo_uri' not in self.client_secrets: logger.debug('Userinfo uri not specified') raise AssertionError('UserInfo URI not specified') # Cache the info from this request if '_oidc_userinfo' in g: return g._oidc_userinfo http = httplib2.Http() if access_token is None: try: credentials = OAuth2Credentials.from_json( self.credentials_store[g.oidc_id_token['sub']]) except KeyError: logger.debug("Expired ID token, credentials missing", exc_info=True) return None credentials.authorize(http) resp, content = http.request(self.client_secrets['userinfo_uri']) else: # We have been manually overriden with an access token resp, content = http.request( self.client_secrets['userinfo_uri'], "POST", body=urlencode({"access_token": access_token}), headers={'Content-Type': 'application/x-www-form-urlencoded'}) logger.debug('Retrieved user info: %s' % content) info = _json_loads(content) g._oidc_userinfo = info return info
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _after_request(self, response): """ Set a new ID token cookie if the ID token has changed. """
# This means that if either the new or the old are False, we set # insecure cookies. # We don't define OIDC_ID_TOKEN_COOKIE_SECURE in init_app, because we # don't want people to find it easily. cookie_secure = (current_app.config['OIDC_COOKIE_SECURE'] and current_app.config.get('OIDC_ID_TOKEN_COOKIE_SECURE', True)) if getattr(g, 'oidc_id_token_dirty', False): if g.oidc_id_token: signed_id_token = self.cookie_serializer.dumps(g.oidc_id_token) response.set_cookie( current_app.config['OIDC_ID_TOKEN_COOKIE_NAME'], signed_id_token, secure=cookie_secure, httponly=True, max_age=current_app.config['OIDC_ID_TOKEN_COOKIE_TTL']) else: # This was a log out response.set_cookie( current_app.config['OIDC_ID_TOKEN_COOKIE_NAME'], '', path=current_app.config['OIDC_ID_TOKEN_COOKIE_PATH'], secure=cookie_secure, httponly=True, expires=0) return response
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def require_login(self, view_func): """ Use this to decorate view functions that require a user to be logged in. If the user is not already logged in, they will be sent to the Provider to log in, after which they will be returned. .. versionadded:: 1.0 This was :func:`check` before. """
@wraps(view_func) def decorated(*args, **kwargs): if g.oidc_id_token is None: return self.redirect_to_auth_server(request.url) return view_func(*args, **kwargs) return decorated
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def require_keycloak_role(self, client, role): """ Function to check for a KeyCloak client role in JWT access token. This is intended to be replaced with a more generic 'require this value in token or claims' system, at which point backwards compatibility will be added. .. versionadded:: 1.5.0 """
def wrapper(view_func): @wraps(view_func) def decorated(*args, **kwargs): pre, tkn, post = self.get_access_token().split('.') access_token = json.loads(b64decode(tkn)) if role in access_token['resource_access'][client]['roles']: return view_func(*args, **kwargs) else: return abort(403) return decorated return wrapper
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def redirect_to_auth_server(self, destination=None, customstate=None): """ Set a CSRF token in the session, and redirect to the IdP. :param destination: The page that the user was going to, before we noticed they weren't logged in. :type destination: Url to return the client to if a custom handler is not used. Not available with custom callback. :param customstate: The custom data passed via the ODIC state. Note that this only works with a custom_callback, and this will ignore destination. :type customstate: Anything that can be serialized :returns: A redirect response to start the login process. :rtype: Flask Response .. deprecated:: 1.0 Use :func:`require_login` instead. """
if not self._custom_callback and customstate: raise ValueError('Custom State is only avilable with a custom ' 'handler') if 'oidc_csrf_token' not in session: csrf_token = urlsafe_b64encode(os.urandom(24)).decode('utf-8') session['oidc_csrf_token'] = csrf_token state = { 'csrf_token': session['oidc_csrf_token'], } statefield = 'destination' statevalue = destination if customstate is not None: statefield = 'custom' statevalue = customstate state[statefield] = self.extra_data_serializer.dumps( statevalue).decode('utf-8') extra_params = { 'state': urlsafe_b64encode(json.dumps(state).encode('utf-8')), } extra_params.update(current_app.config['OIDC_EXTRA_REQUEST_AUTH_PARAMS']) if current_app.config['OIDC_GOOGLE_APPS_DOMAIN']: extra_params['hd'] = current_app.config['OIDC_GOOGLE_APPS_DOMAIN'] if current_app.config['OIDC_OPENID_REALM']: extra_params['openid.realm'] = current_app.config[ 'OIDC_OPENID_REALM'] flow = self._flow_for_request() auth_url = '{url}&{extra_params}'.format( url=flow.step1_get_authorize_url(), extra_params=urlencode(extra_params)) # if the user has an ID token, it's invalid, or we wouldn't be here self._set_cookie_id_token(None) return redirect(auth_url)