code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
source = self._source_data
if source is None:
raise ExpressionError('Can only filter on data sources.')
def _parse_partition_predicate(p):
if '=' not in p:
raise ExpressionError('Illegal partition predicate.')
field_name, field_value ... | def filter_parts(self, predicate='', exclude=True) | Filter the data by partition string. A partition string looks like `pt1=1,pt2=2/pt1=2,pt2=1`, where
comma (,) denotes 'and', while (/) denotes 'or'.
:param str|Partition predicate: predicate string of partition filter
:param bool exclude: True if you want to exclude partition fields, otherwise ... | 2.997548 | 2.818733 | 1.063438 |
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)
... | 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` | 4.187656 | 3.822851 | 1.095427 |
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... | 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` | 3.066341 | 2.782441 | 1.102033 |
if n is None:
n = options.display.max_rows
return self._handle_delay_call('execute', self, head=n, **kwargs) | 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` | 11.108291 | 12.297199 | 0.903319 |
if n is None:
n = options.display.max_rows
return self._handle_delay_call('execute', self, tail=n, **kwargs) | 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` | 11.995098 | 12.846374 | 0.933734 |
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
... | 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 | 4.422696 | 4.082943 | 1.083213 |
proxied = get_proxied_expr(self)
kv = dict((attr, getattr(proxied, attr)) for attr in get_attrs(proxied))
return type(proxied)(**kv) | def view(self) | Clone a same collection. useful for self-join.
:return: | 7.144303 | 7.30287 | 0.978287 |
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
... | 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 | 5.196241 | 4.563097 | 1.138753 |
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_sequ... | def astype(self, data_type) | Cast to a new data type.
:param data_type: the new data type
:return: casted sequence
:Example:
>>> df.id.astype('float') | 3.841097 | 4.512234 | 0.851263 |
if not self._iter_local:
params = dict()
url = self.resource()
resp = self._client.get(url, params=params)
Users.parse(self._client, resp, obj=self)
for user in self.users:
yield user | def iterate(self) | :return: | 7.571799 | 7.158953 | 1.057669 |
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])
e... | def explode(expr, *args, **kwargs) | Expand list or dict data into multiple rows
:param expr: list / dict sequence / scalar
:return: | 2.866278 | 2.851771 | 1.005087 |
return composite_op(expr, ListContains, df_types.boolean, _value=_scalar(value)) | def _contains(expr, value) | Check whether certain value is in the inspected list
:param expr: list sequence / scalar
:param value: value to inspect
:return: | 43.356842 | 82.136726 | 0.527862 |
if isinstance(expr, SequenceExpr):
dtype = expr.data_type
else:
dtype = expr.value_type
return composite_op(expr, DictKeys, df_types.List(dtype.key_type)) | def _keys(expr) | Retrieve keys of a dict
:param expr: dict sequence / scalar
:return: | 9.956695 | 9.529236 | 1.044858 |
if isinstance(expr, SequenceExpr):
dtype = expr.data_type
else:
dtype = expr.value_type
return composite_op(expr, DictValues, df_types.List(dtype.value_type)) | def _values(expr) | Retrieve values of a dict
:param expr: dict sequence / scalar
:return: | 10.219795 | 9.861655 | 1.036316 |
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'] | 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_s... | 4.949207 | 4.941616 | 1.001536 |
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'] | 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_... | 4.880399 | 4.894189 | 0.997182 |
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'] | 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, '... | 4.938241 | 4.874207 | 1.013138 |
if not col_pred:
col_pred = get_field_name_by_role(df, FieldRole.PREDICTED_VALUE)
return _run_evaluation_node(df, col_true, col_pred)['sst'] | def total_sum_of_squares(df, col_true, col_pred=None) | Compute total sum of squares (SST) 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, 'pred... | 6.323823 | 5.583325 | 1.132627 |
if not col_pred:
col_pred = get_field_name_by_role(df, FieldRole.PREDICTED_VALUE)
return _run_evaluation_node(df, col_true, col_pred)['sse'] | def explained_sum_of_squares(df, col_true, col_pred=None) | Compute explained sum of squares (SSE) 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, '... | 5.646933 | 5.441274 | 1.037796 |
if not col_pred:
col_pred = get_field_name_by_role(df, FieldRole.PREDICTED_VALUE)
return _run_evaluation_node(df, col_true, col_pred)['r2'] | def r2_score(df, col_true, col_pred=None) | Compute determination coefficient (R2) 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, '... | 4.890442 | 4.907695 | 0.996485 |
if not col_pred:
col_pred = get_field_name_by_role(df, FieldRole.PREDICTED_VALUE)
return _run_evaluation_node(df, col_true, col_pred)['r'] | def multi_corr(df, col_true, col_pred=None) | Compute multiple correlation coefficient (R) 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 va... | 6.158116 | 5.197125 | 1.184908 |
if not col_pred:
col_pred = get_field_name_by_role(df, FieldRole.PREDICTED_VALUE)
return _run_evaluation_node(df, col_true, col_pred)['rmse'] | def rooted_mean_squared_error(df, col_true, col_pred=None) | Compute rooted mean squared error (RMSE) 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,... | 4.629781 | 4.913954 | 0.94217 |
if not col_pred:
col_pred = get_field_name_by_role(df, FieldRole.PREDICTED_VALUE)
return _run_evaluation_node(df, col_true, col_pred)['mad'] | def mean_absolute_deviation(df, col_true, col_pred=None) | Compute mean absolute deviation (MAD) 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, 'p... | 5.830937 | 5.567328 | 1.047349 |
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'] | 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, 'predicti... | 5.661294 | 6.568475 | 0.861889 |
return self.instance.put_task_info(self.name, key, value) | def put_info(self, key, value) | Put associated information of the task. | 8.119374 | 5.663515 | 1.433628 |
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)) | def append_little_endian32(self, unsigned_value) | Appends an unsigned 32-bit integer to the internal buffer,
in little-endian byte order. | 3.513427 | 3.44718 | 1.019218 |
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)) | def append_little_endian64(self, unsigned_value) | Appends an unsigned 64-bit integer to the internal buffer,
in little-endian byte order. | 3.423734 | 3.369383 | 1.016131 |
if not wire_format.INT32_MIN <= value <= wire_format.INT32_MAX:
raise errors.EncodeError('Value out of range: %d' % value)
self.append_varint64(value) | def append_varint32(self, value) | Appends a signed 32-bit integer to the internal buffer,
encoded as a varint. (Note that a negative varint32 will
always require 10 bytes of space.) | 3.516976 | 3.669271 | 0.958495 |
if not 0 <= value <= wire_format.UINT32_MAX:
raise errors.EncodeError('Value out of range: %d' % value)
self.append_var_uint64(value) | def append_var_uint32(self, value) | Appends an unsigned 32-bit integer to the internal buffer,
encoded as a varint. | 3.986247 | 4.012031 | 0.993573 |
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) | def append_varint64(self, value) | Appends a signed 64-bit integer to the internal buffer,
encoded as a varint. | 2.96163 | 3.045128 | 0.97258 |
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
sel... | def append_var_uint64(self, unsigned_value) | Appends an unsigned 64-bit integer to the internal buffer,
encoded as a varint. | 2.446994 | 2.303063 | 1.062496 |
if not isinstance(by, list):
by = [by, ]
if len(bys) > 0:
by = by + list(bys)
return GroupBy(_input=expr, _by=by) | 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` | 3.550382 | 3.398577 | 1.044667 |
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) | 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 ... | 4.894506 | 5.637465 | 0.868211 |
self.hash = 0
self.hashbits, self.num_hashes = self._optimal_size(capacity, error)
if len(initial):
if type(initial) == str:
self.add(initial)
else:
for t in initial:
self.add(t) | def create_hash(self, initial, capacity, error) | Calculates a Bloom filter with the specified parameters.
Initalizes with a string or list/set/tuple of strings. No output.
Reference material: http://bitworking.org/news/380/bloom-filter-resources | 4.19996 | 3.957366 | 1.061302 |
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.hexd... | 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. | 4.004712 | 3.8458 | 1.041321 |
m = math.ceil((capacity * math.log(error)) / math.log(1.0 / (math.pow(2.0, math.log(2.0)))))
k = math.ceil(math.log(2.0) * m / capacity)
return int(m), int(k) | def _optimal_size(self, capacity, error) | Calculates minimum number of bits in filter array and
number of hash functions given a number of enteries (maximum)
and the desired error rate (falese positives).
Example:
m, k = self._optimal_size(3000, 0.01) # m=28756, k=7 | 3.046295 | 2.93312 | 1.038585 |
"Add an item (string) to the filter. Cannot be removed later!"
for pos in self._hashes(item):
self.hash |= (2 ** pos) | def add(self, item) | Add an item (string) to the filter. Cannot be removed later! | 24.04821 | 9.037552 | 2.660921 |
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 e... | 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 join... | 2.665073 | 2.956193 | 0.901522 |
return join(left, right, on, suffixes=suffixes, mapjoin=mapjoin) | 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 th... | 3.034895 | 5.987189 | 0.506898 |
joined = join(left, right, on, how='left', suffixes=suffixes, mapjoin=mapjoin)
return joined._merge_joined_fields(merge_columns) | 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... | 4.364166 | 9.541703 | 0.457378 |
left, right = _make_different_sources(left, right)
return UnionCollectionExpr(_lhs=left, _rhs=right, _distinct=distinct) | def union(left, right, distinct=False) | Union two collections.
:param left: left collection
:param right: right collection
:param distinct:
:return: collection
:Example:
>>> df['name', 'id'].union(df2['id', 'name']) | 7.51443 | 13.771852 | 0.545637 |
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
... | 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 horizonta... | 4.962234 | 5.069726 | 0.978797 |
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:
... | 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:
>>> import pandas as pd
>>> df1 = D... | 3.575758 | 3.806833 | 0.9393 |
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 = l... | 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:
>>... | 3.507922 | 3.767854 | 0.931013 |
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(... | 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:
>>> import pandas as pd
>>> df1 = DataFrame(pd.DataFrame({'a': [1, 2, 3, 3, 3], 'b': [1, 2, 3, 3,... | 3.663465 | 3.893783 | 0.94085 |
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) | 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 | 5.482974 | 4.28539 | 1.279457 |
@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 | 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. | 3.249099 | 3.491609 | 0.930545 |
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().issuperse... | 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 | 4.430627 | 4.339074 | 1.0211 |
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().isdis... | 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 | 4.429375 | 4.261931 | 1.039288 |
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 = Cry... | 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 blackl... | 2.148391 | 2.133501 | 1.00698 |
PraetorianError.require_condition(
getattr(user_class, 'lookup', None) is not None,
textwrap.dedent(),
)
PraetorianError.require_condition(
getattr(user_class, 'identify', None) is not None,
textwrap.dedent(),
)
# TODO: Fig... | 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 | 4.871005 | 4.521635 | 1.077266 |
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,
'Coul... | 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 | 4.225927 | 4.55542 | 0.92767 |
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) | 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 | 5.555384 | 5.554462 | 1.000166 |
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) | def encrypt_password(self, raw_password) | Encrypts a plaintext password using the stored passlib password context | 6.586514 | 5.865022 | 1.123016 |
warnings.warn(
,
warnings.DeprecationWarning,
)
return error.jsonify(), error.status_code, error.headers | def error_handler(self, error) | Provides a flask error handler that is used for PraetorianErrors
(and derived exceptions). | 11.363521 | 8.208959 | 1.384283 |
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
In... | 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... | 5.456569 | 5.197093 | 1.049927 |
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:
... | 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 to... | 2.549509 | 2.682743 | 0.950336 |
return self.encode_jwt_token(
user,
override_access_lifespan=VITAM_AETERNUM,
override_refresh_lifespan=VITAM_AETERNUM,
**custom_claims
) | 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 black... | 4.448748 | 4.944388 | 0.899757 |
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.a... | 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: ... | 3.339785 | 3.536126 | 0.944476 |
# 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,
opt... | def extract_jwt_token(self, token) | Extracts a data dictionary from a jwt token | 6.831036 | 6.724764 | 1.015803 |
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_condit... | def _validate_jwt_data(self, data, access_type) | Validates that the data for a jwt token is valid | 2.75272 | 2.745894 | 1.002486 |
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)
... | def _unpack_header(self, headers) | Unpacks a jwt token from a request header | 4.612027 | 4.064601 | 1.134681 |
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} | 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
... | 2.132882 | 2.587314 | 0.824361 |
req = flask.request.get_json(force=True)
username = req.get('username', None)
password = req.get('password', None)
user = guard.authenticate(username, password)
ret = {'access_token': guard.encode_jwt_token(user)}
return (flask.jsonify(ret), 200) | def login() | Logs a user in by parsing a POST request containing user credentials and
issuing a JWT token.
.. example::
$ curl http://localhost:5000/login -X POST \
-d '{"username":"Walter","password":"calmerthanyouare"}' | 2.448799 | 2.601909 | 0.941155 |
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 | 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>" | 4.178522 | 4.888466 | 0.854772 |
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)) | 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"}' | 2.830597 | 3.196233 | 0.885604 |
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'])) | 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>"}' | 4.722953 | 5.199965 | 0.908266 |
req = flask.request.get_json(force=True)
username = req.pop('username', None)
password = req.pop('password', None)
user = guard.authenticate(username, password)
ret = {'access_token': guard.encode_jwt_token(
user,
firstname=user.firstname,
nickname=user.nickname,
... | def login() | Logs a user in by parsing a POST request containing user credentials and
issuing a JWT token.
.. example::
$ curl http://localhost:5000/login -X POST \
-d '{"username":"Walter","password":"calmerthanyouare"}' | 3.108772 | 3.357347 | 0.925961 |
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:
... | 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>" | 4.062155 | 4.388125 | 0.925715 |
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 | def current_guard() | Fetches the current instance of flask-praetorian that is attached to the
current flask app | 5.825931 | 4.858836 | 1.199038 |
ctx = flask._app_ctx_stack.top
jwt_data = getattr(ctx, 'jwt_data', None)
PraetorianError.require_condition(
jwt_data is not None,
,
)
return jwt_data | def get_jwt_data_from_app_context() | Fetches a dict of jwt token data from the top of the flask app's context | 5.270403 | 5.221837 | 1.009301 |
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 | def current_user_id() | This method returns the user id retrieved from jwt token data attached to
the current flask app's context | 5.62427 | 4.858088 | 1.157713 |
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 | def current_user() | This method returns a user instance for jwt token data attached to the
current flask app's context | 8.162272 | 7.829066 | 1.04256 |
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(',')) | def current_rolenames() | This method returns the names of all roles associated with the current user | 8.619 | 8.414001 | 1.024364 |
jwt_data = get_jwt_data_from_app_context()
return {k: v for (k, v) in jwt_data.items() if k not in RESERVED_CLAIMS} | def current_custom_claims() | This method returns any custom claims in the current jwt | 4.263487 | 3.68563 | 1.156787 |
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')
f... | 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 ... | 2.785403 | 2.729791 | 1.020372 |
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(... | 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... | 2.251345 | 2.46536 | 0.913191 |
_, content = httplib2.Http().request(
'%s/.well-known/openid-configuration' % OP_uri)
return _json_loads(content) | 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 | 4.453096 | 4.400223 | 1.012016 |
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... | def init_app(self, app) | Do setup that requires a Flask app.
:param app: The application to initialize.
:type app: Flask | 2.775739 | 2.815899 | 0.985738 |
info = self.user_getinfo([field], access_token)
return info.get(field) | 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 | 4.91516 | 8.23709 | 0.596711 |
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]
... | 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 b... | 3.426728 | 3.389078 | 1.011109 |
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)
... | def get_access_token(self) | Method to return the current requests' access_token.
:returns: Access token or None
:rtype: str
.. versionadded:: 1.2 | 6.223186 | 7.047315 | 0.883058 |
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)
... | def get_refresh_token(self) | Method to return the current requests' refresh_token.
:returns: Access token or None
:rtype: str
.. versionadded:: 1.2 | 6.185653 | 6.920918 | 0.893762 |
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.... | 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 | 3.383675 | 3.490244 | 0.969467 |
# 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
... | def _after_request(self, response) | Set a new ID token cookie if the ID token has changed. | 2.958304 | 2.750313 | 1.075625 |
# the auth callback and error pages don't need user to be authenticated
if request.endpoint in frozenset(['_oidc_callback', '_oidc_error']):
return None
# retrieve signed ID token cookie
id_token = self._get_cookie_id_token()
if id_token is None:
... | def authenticate_or_redirect(self) | Helper function suitable for @app.before_request and @check.
Sets g.oidc_id_token to the ID token if the user has successfully
authenticated, else returns a redirect object so they can go try
to authenticate.
:returns: A redirect object, or None if the user is logged in.
:rtype:... | 3.466189 | 3.471817 | 0.998379 |
@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 | 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. | 2.441954 | 2.729568 | 0.89463 |
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']:
... | 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 | 2.851381 | 2.700833 | 1.055741 |
flow = copy(self.flow)
redirect_uri = current_app.config['OVERWRITE_REDIRECT_URI']
if not redirect_uri:
flow.redirect_uri = url_for('_oidc_callback', _external=True)
else:
flow.redirect_uri = redirect_uri
return flow | def _flow_for_request(self) | Build a flow with the correct absolute callback URL for this request.
:return: | 3.405506 | 3.433016 | 0.991987 |
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['... | 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.
... | 3.064695 | 2.926376 | 1.047266 |
if not id_token:
return False
# step 2: check issuer
if id_token['iss'] not in current_app.config['OIDC_VALID_ISSUERS']:
logger.error('id_token issued by non-trusted issuer: %s'
% id_token['iss'])
return False
if isi... | def _is_id_token_valid(self, id_token) | Check if `id_token` is a current ID token for this application,
was issued by the Apps domain we expected,
and that the email address has been verified.
@see: http://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation | 2.822829 | 2.802675 | 1.007191 |
@wraps(view_func)
def decorated(*args, **kwargs):
plainreturn, data = self._process_callback('custom')
if plainreturn:
return data
else:
return view_func(data, *args, **kwargs)
self._custom_callback = decorated
... | def custom_callback(self, view_func) | Wrapper function to use a custom callback.
The custom OIDC callback will get the custom state field passed in with
redirect_to_auth_server. | 4.188964 | 4.364714 | 0.959734 |
# retrieve session and callback variables
try:
session_csrf_token = session.get('oidc_csrf_token')
state = _json_loads(urlsafe_b64decode(request.args['state'].encode('utf-8')))
csrf_token = state['csrf_token']
code = request.args['code']
... | def _process_callback(self, statefield) | Exchange the auth code for actual credentials,
then redirect to the originally requested page. | 4.372998 | 4.191665 | 1.04326 |
valid = self._validate_token(token, scopes_required)
if valid is True:
return True
else:
return ErrStr(valid) | def validate_token(self, token, scopes_required=None) | This function can be used to validate tokens.
Note that this only works if a token introspection url is configured,
as that URL will be queried for the validity and scopes of a token.
:param scopes_required: List of scopes that are required to be
granted by the token before returni... | 7.060712 | 4.343105 | 1.625729 |
if scopes_required is None:
scopes_required = []
scopes_required = set(scopes_required)
token_info = None
valid_token = False
has_required_scopes = False
if token:
try:
token_info = self._get_token_info(token)
... | def _validate_token(self, token, scopes_required=None) | The actual implementation of validate_token. | 2.599735 | 2.589181 | 1.004076 |
def wrapper(view_func):
@wraps(view_func)
def decorated(*args, **kwargs):
token = None
if 'Authorization' in request.headers and request.headers['Authorization'].startswith('Bearer '):
token = request.headers['Authorization'].... | def accept_token(self, require_token=False, scopes_required=None,
render_errors=True) | Use this to decorate view functions that should accept OAuth2 tokens,
this will most likely apply to API functions.
Tokens are accepted as part of the query URL (access_token value) or
a POST form value (access_token).
Note that this only works if a token introspection url is configure... | 1.966074 | 2.014519 | 0.975952 |
if not isinstance(mat, scipy.sparse.csr_matrix):
raise ValueError("works only for CSR format -- use .tocsr() first")
indices = list(indices)
mask = np.ones(mat.shape[0], dtype=bool)
mask[indices] = False
return mat[mask] | def delete_rows_csr(mat, indices) | Remove the rows denoted by ``indices`` form the CSR sparse matrix ``mat``. | 3.158649 | 3.115406 | 1.01388 |
''' Returns the string without non ASCII characters'''
stripped = (c for c in string if 0 < ord(c) < 127)
return ''.join(stripped) | def strip_non_ascii(string) | Returns the string without non ASCII characters | 2.766709 | 2.738231 | 1.0104 |
if self.has_been_restricted == True:
return self
new_numerical_cols = []
new_categorical_cols = []
new_additional_numerical_cols = []
new_feature_names = []
new_vocab = {}
for idx, val in enumerate(support):
if val == True:
... | def restrict(self, support) | Restrict the features to those in support using feature selection.
This function modifies the estimator in-place. | 1.886611 | 1.862748 | 1.01281 |
if self.api and self.agent_ids:
return self.api._get_agents(self.agent_ids) | def agents(self) | | Description: IDs of agents involved in the chat | 6.208006 | 6.064588 | 1.023649 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.