buggy stringlengths 35 5.03k | fixed stringlengths 46 62.5k |
|---|---|
class WorkerExternalTaskTest(unittest.TestCase):
'retry-external-tasks',
False) is True
original_get_work = self.scheduler.get_work
def decorated_get_work(*args, **kwargs):
... | class WorkerExternalTaskTest(unittest.TestCase):
'retry-external-tasks',
False) is True
tempdir = tempfile.mkdtemp(prefix='luigi-test-')
with patch('random.randint', return_value=0.1): |
class TestFish(object):
mock.return_value.stdout.read.side_effect = [(
b'cd\nfish_config\nfuck\nfunced\nfuncsave\ngrep\nhistory\nll\nls\n'
b'man\nmath\npopd\npushd\nruby'),
b'alias fish_key_reader /usr/bin/fish_key_reader\nalias g git']
return mock
@pytest.mark.p... | class TestFish(object):
mock.return_value.stdout.read.side_effect = [(
b'cd\nfish_config\nfuck\nfunced\nfuncsave\ngrep\nhistory\nll\nls\n'
b'man\nmath\npopd\npushd\nruby'),
(b'alias fish_key_reader /usr/bin/fish_key_reader\nalias g git\n'
b'alias alias_with_equal... |
class TestFish(object):
'pushd': 'pushd',
'ruby': 'ruby',
'g': 'git',
'fish_key_reader': '/usr/bin/fish_key_reader'}
def test_app_alias(self, shell):
a... | class TestFish(object):
'pushd': 'pushd',
'ruby': 'ruby',
'g': 'git',
'fish_key_reader': '/usr/bin/fish_key_reader',
'alias_w... |
def _get_functions(overridden):
def _get_aliases(overridden):
aliases = {}
proc = Popen(['fish', '-ic', 'alias'], stdout=PIPE, stderr=DEVNULL)
alias_out = proc.stdout.read().decode('utf-8').strip().split('\n')
for alias in alias_out:
name, value = alias.replace('alias ', '', 1).split(' ', 1)
... | def _get_functions(overridden):
def _get_aliases(overridden):
aliases = {}
proc = Popen(['fish', '-ic', 'alias'], stdout=PIPE, stderr=DEVNULL)
alias_out = proc.stdout.read().decode('utf-8').strip()
if not alias_out:
return aliases
for alias in alias_out.split('\n'):
for separator in ... |
def count_leading_spaces(s):
def process_list_block(docstring, starting_point, section_end,
leading_spaces, marker):
ending_point = docstring.find('\n\n', starting_point)
block = docstring[starting_point:(None if ending_point == -1 else
ending_point -... | def count_leading_spaces(s):
def process_list_block(docstring, starting_point, section_end,
leading_spaces, marker):
ending_point = docstring.find('\n\n', starting_point)
block = docstring[starting_point:(ending_point - 1 if ending_point > -1 else
sec... |
y = layer(x)
'''}
def test_doc_lists():
docstring = autogen.process_docstring(test_doc1['doc'])
assert markdown(docstring) == markdown(test_doc1['result'])
dummy_docstring = """Multiplies 2 tensors (and/or variables) and returns a *tensor*. | y = layer(x)
'''}
test_doc_with_arguments_as_last_block = {
'doc': """Base class for recurrent layers.
# Arguments
return_sequences: Boolean. Whether to return the last output
in the output sequence, or the full sequence.
return_state: Boolean. Whether to return the last state
... |
from vyper.builtin_interfaces import ERC20, ERC721
from vyper.cli.utils import extract_file_interface_imports
from vyper.compiler import compile_code, compile_codes
from vyper.exceptions import InterfaceViolation, StructureException
def test_basic_extract_interface(): | from vyper.builtin_interfaces import ERC20, ERC721
from vyper.cli.utils import extract_file_interface_imports
from vyper.compiler import compile_code, compile_codes
from vyper.exceptions import ArgumentException, InterfaceViolation, StructureException
def test_basic_extract_interface(): |
def test():
assert erc20.balanceOf(sender) == 1000
def test_units_interface(w3, get_contract):
code = """
import balanceof as BalanceOf | def test():
assert erc20.balanceOf(sender) == 1000
# test data returned from external interface gets clamped
@pytest.mark.parametrize("typ", ("int128", "uint8"))
def test_external_interface_int_clampers(get_contract, assert_tx_failed, typ):
external_contract = f"""
@external
def ok() -> {typ}:
return 1
@... |
def _dynarray_make_setter(dst, src):
# for ABI-encoded dynamic data, we must loop to unpack, since
# the layout does not match our memory layout
should_loop = (
src.encoding in (Encoding.ABI, Encoding.JSON_ABI)
and src.typ.subtype.abi_type.is_dynamic()
)
... | def _dynarray_make_setter(dst, src):
# for ABI-encoded dynamic data, we must loop to unpack, since
# the layout does not match our memory layout
should_loop = src.encoding == Encoding.ABI and src.typ.subtype.abi_type.is_dynamic()
# if the subtype is dynamic, there might be a lot of
... |
def _get_element_ptr_tuplelike(parent, key):
ofst = 0 # offset from parent start
if parent.encoding in (Encoding.ABI, Encoding.JSON_ABI):
if parent.location == STORAGE:
raise CompilerPanic("storage variables should not be abi encoded") # pragma: notest
| def _get_element_ptr_tuplelike(parent, key):
ofst = 0 # offset from parent start
if parent.encoding == Encoding.ABI:
if parent.location == STORAGE:
raise CompilerPanic("storage variables should not be abi encoded") # pragma: notest
|
def _get_element_ptr_array(parent, key, array_bounds_check):
# NOTE: there are optimization rules for this when ix or bound is literal
ix = IRnode.from_list([clamp_op, ix, bound], typ=ix.typ)
if parent.encoding in (Encoding.ABI, Encoding.JSON_ABI):
if parent.location == STORAGE:
... | def _get_element_ptr_array(parent, key, array_bounds_check):
# NOTE: there are optimization rules for this when ix or bound is literal
ix = IRnode.from_list([clamp_op, ix, bound], typ=ix.typ)
if parent.encoding == Encoding.ABI:
if parent.location == STORAGE:
raise CompilerPanic(... |
def _freshname(name):
# returns True if t is ABI encoded and is a type that needs any kind of
# validation
def needs_clamp(t, encoding):
if encoding not in (Encoding.ABI, Encoding.JSON_ABI):
return False
if isinstance(t, (ByteArrayLike, DArrayType)):
if encoding == Encoding.JSON_ABI:
... | def _freshname(name):
# returns True if t is ABI encoded and is a type that needs any kind of
# validation
def needs_clamp(t, encoding):
if encoding == Encoding.VYPER:
return False
if encoding != Encoding.ABI:
raise CompilerPanic("unreachable") # pragma: notest
if isinstance(t, (ByteArrayLi... |
check_assign,
check_external_call,
dummy_node_for_type,
get_element_ptr,
)
from vyper.codegen.ir_node import Encoding, IRnode
from vyper.codegen.types import InterfaceType, TupleType, get_type_for_exact_size
from vyper.exceptions import StateAccessViolation, TypeCheckFailure
| check_assign,
check_external_call,
dummy_node_for_type,
make_setter,
needs_clamp,
)
from vyper.codegen.ir_node import Encoding, IRnode
from vyper.codegen.types import InterfaceType, TupleType, get_type_for_exact_size
from vyper.codegen.types.convert import new_type_to_old_type
from vyper.exceptions ... |
def _pack_arguments(contract_sig, args, context):
return buf, mstore_method_id + [encode_args], args_ofst, args_len
def _returndata_encoding(contract_sig):
if contract_sig.is_from_json:
return Encoding.JSON_ABI
return Encoding.ABI
def _unpack_returndata(buf, contract_sig, skip_contract_check, co... | def _pack_arguments(contract_sig, args, context):
return buf, mstore_method_id + [encode_args], args_ofst, args_len
def _unpack_returndata(buf, contract_sig, skip_contract_check, context, expr):
# expr.func._metadata["type"].return_type is more accurate
# than contract_sig.return_type in the case of JSON ... |
def _unpack_returndata(buf, contract_sig, skip_contract_check, context):
# revert when returndatasize is not in bounds
ret = []
# runtime: min_return_size <= returndatasize
# TODO move the -1 optimization to IR optimizer
if not skip_contract_check:
ret += [["assert", ["gt", "returndatasize",... | def _unpack_returndata(buf, contract_sig, skip_contract_check, context):
# revert when returndatasize is not in bounds
ret = []
# runtime: min_return_size <= returndatasize
if not skip_contract_check:
ret += [["assert", ["ge", "returndatasize", min_return_size]]]
encoding = Encoding.ABI
... |
def _external_call_helper(
buf, arg_packer, args_ofst, args_len = _pack_arguments(contract_sig, args_ir, context)
ret_unpacker, ret_ofst, ret_len = _unpack_returndata(
buf, contract_sig, skip_contract_check, context
)
sub += arg_packer | def _external_call_helper(
buf, arg_packer, args_ofst, args_len = _pack_arguments(contract_sig, args_ir, context)
ret_unpacker, ret_ofst, ret_len = _unpack_returndata(
buf, contract_sig, skip_contract_check, context, expr
)
sub += arg_packer |
def _external_call_helper(
if contract_sig.return_type is not None:
sub += ret_unpacker
ret = IRnode.from_list(
sub,
typ=contract_sig.return_type,
location=MEMORY,
# set the encoding to ABI here, downstream code will decode and add clampers.
encoding=_returndata_... | def _external_call_helper(
if contract_sig.return_type is not None:
sub += ret_unpacker
return IRnode.from_list(sub, typ=contract_sig.return_type, location=MEMORY)
def _get_special_kwargs(stmt_expr, context): |
import vyper.utils as util
from vyper.address_space import CALLDATA, DATA, MEMORY
from vyper.ast.signatures.function_signature import FunctionSignature, VariableRecord
from vyper.codegen.context import Context
from vyper.codegen.core import get_element_ptr, getpos, make_setter
from vyper.codegen.expr import Expr
from v... | import vyper.utils as util
from vyper.address_space import CALLDATA, DATA, MEMORY
from vyper.ast.signatures.function_signature import FunctionSignature, VariableRecord
from vyper.codegen.abi_encoder import abi_encoding_matches_vyper
from vyper.codegen.context import Context
from vyper.codegen.core import get_element_pt... |
def _register_function_args(context: Context, sig: FunctionSignature) -> List[IR
arg_ir = get_element_ptr(base_args_ofst, i)
if _should_decode(arg.typ):
# allocate a memory slot for it and copy
p = context.new_variable(arg.name, arg.typ, is_mutable=False)
dst = IRno... | def _register_function_args(context: Context, sig: FunctionSignature) -> List[IR
arg_ir = get_element_ptr(base_args_ofst, i)
if needs_clamp(arg.typ, Encoding.ABI):
# allocate a memory slot for it and copy
p = context.new_variable(arg.name, arg.typ, is_mutable=False)
... |
def _register_function_args(context: Context, sig: FunctionSignature) -> List[IR
copy_arg.source_pos = getpos(arg.ast_source)
ret.append(copy_arg)
else:
# leave it in place
context.vars[arg.name] = VariableRecord(
name=arg.name, | def _register_function_args(context: Context, sig: FunctionSignature) -> List[IR
copy_arg.source_pos = getpos(arg.ast_source)
ret.append(copy_arg)
else:
assert abi_encoding_matches_vyper(arg.typ)
# leave it in place
context.vars[arg.name] = VariableRec... |
class Encoding(Enum):
VYPER = auto()
# abi encoded, default for args/return values from external funcs
ABI = auto()
# abi encoded, same as ABI but no clamps for bytestrings
JSON_ABI = auto()
# future: packed
| class Encoding(Enum):
VYPER = auto()
# abi encoded, default for args/return values from external funcs
ABI = auto()
# future: packed
|
def new_type_to_old_type(typ: new.BasePrimitive) -> old.NodeType:
if isinstance(typ, new.DynamicArrayDefinition):
return old.DArrayType(new_type_to_old_type(typ.value_type), typ.length)
if isinstance(typ, new.TupleDefinition):
return old.TupleType(typ.value_type)
if isinstance(typ, new.Struc... | def new_type_to_old_type(typ: new.BasePrimitive) -> old.NodeType:
if isinstance(typ, new.DynamicArrayDefinition):
return old.DArrayType(new_type_to_old_type(typ.value_type), typ.length)
if isinstance(typ, new.TupleDefinition):
return old.TupleType([new_type_to_old_type(t) for t in typ.value_type... |
class Index(IndexOpsMixin, PandasObject):
_infer_as_myclass = False
_engine_type = libindex.ObjectEngine
_accessors = {"str"}
| class Index(IndexOpsMixin, PandasObject):
_infer_as_myclass = False
_engine_type = libindex.ObjectEngine
# whether we support partial string indexing. Overridden
# in DatetimeIndex and PeriodIndex
_supports_partial_string_indexing = False
_accessors = {"str"}
|
class DatetimeIndex(DatetimeIndexOpsMixin, Int64Index, DatetimeDelegateMixin):
)
_engine_type = libindex.DatetimeEngine
_tz = None
_freq = None | class DatetimeIndex(DatetimeIndexOpsMixin, Int64Index, DatetimeDelegateMixin):
)
_engine_type = libindex.DatetimeEngine
_supports_partial_string_indexing = True
_tz = None
_freq = None |
class PeriodIndex(DatetimeIndexOpsMixin, Int64Index, PeriodDelegateMixin):
_data = None
_engine_type = libindex.PeriodEngine
# ------------------------------------------------------------------------
# Index Constructors | class PeriodIndex(DatetimeIndexOpsMixin, Int64Index, PeriodDelegateMixin):
_data = None
_engine_type = libindex.PeriodEngine
_supports_partial_string_indexing = True
# ------------------------------------------------------------------------
# Index Constructors |
class _LocIndexer(_LocationIndexer):
if isinstance(ax, MultiIndex):
return False
if not ax.is_unique:
return False
| class _LocIndexer(_LocationIndexer):
if isinstance(ax, MultiIndex):
return False
if isinstance(k, str) and ax._supports_partial_string_indexing:
# partial string indexing, df.loc['2000', 'A']
# should not be considered scalar
retur... |
class _LocIndexer(_LocationIndexer):
"""Translate any partial string timestamp matches in key, returning the
new key (GH 10331)"""
if isinstance(labels, MultiIndex):
if isinstance(key, str) and labels.levels[0].is_all_dates:
# Convert key '2016-01-01' to
... | class _LocIndexer(_LocationIndexer):
"""Translate any partial string timestamp matches in key, returning the
new key (GH 10331)"""
if isinstance(labels, MultiIndex):
if (
isinstance(key, str)
and labels.levels[0]._supports_partial_string_indexing
... |
class _LocIndexer(_LocationIndexer):
# (..., slice('2016-01-01', '2016-01-01', None), ...)
new_key = []
for i, component in enumerate(key):
if isinstance(component, str) and labels.levels[i].is_all_dates:
new_key.append(slice(co... | class _LocIndexer(_LocationIndexer):
# (..., slice('2016-01-01', '2016-01-01', None), ...)
new_key = []
for i, component in enumerate(key):
if (
isinstance(component, str)
and labels.levels[i]._supports_p... |
def convert_to_index_sliceable(obj, key):
# We might have a datetimelike string that we can translate to a
# slice here via partial string indexing
if idx.is_all_dates:
try:
return idx._get_string_slice(key)
except (KeyError, ValueError, NotImplementedErr... | def convert_to_index_sliceable(obj, key):
# We might have a datetimelike string that we can translate to a
# slice here via partial string indexing
if idx._supports_partial_string_indexing:
try:
return idx._get_string_slice(key)
except (KeyError, ValueErr... |
class TestSlicing:
with pytest.raises(ValueError, match="The index must be timezone"):
df = df.tz_localize(None)
df[start:end] | class TestSlicing:
with pytest.raises(ValueError, match="The index must be timezone"):
df = df.tz_localize(None)
df[start:end]
def test_slice_reduce_to_series(self):
# GH 27516
df = pd.DataFrame(
{"A": range(24)}, index=pd.date_range("2000", periods=24, f... |
from django.utils.translation import gettext, gettext_lazy as _
UserModel = get_user_model()
class ReadOnlyPasswordHashWidget(forms.Widget):
template_name = 'auth/widgets/read_only_password_hash.html'
read_only = True | from django.utils.translation import gettext, gettext_lazy as _
UserModel = get_user_model()
def _unicode_ci_compare(s1, s2):
"""
Perform case-insensitive comparison of two identifiers, using the
recommended algorithm from Unicode Technical Report 36, section
2.11.2(B)(2).
"""
return unicodeda... |
class PasswordResetForm(forms.Form):
that prevent inactive users and users with unusable passwords from
resetting their password.
"""
active_users = UserModel._default_manager.filter(**{
'%s__iexact' % UserModel.get_email_field_name(): email,
'is_active': True,
... | class PasswordResetForm(forms.Form):
that prevent inactive users and users with unusable passwords from
resetting their password.
"""
email_field_name = UserModel.get_email_field_name()
active_users = UserModel._default_manager.filter(**{
'%s__iexact' % email_field_na... |
class PasswordResetForm(forms.Form):
user.
"""
email = self.cleaned_data["email"]
for user in self.get_users(email):
if not domain_override:
current_site = get_current_site(request) | class PasswordResetForm(forms.Form):
user.
"""
email = self.cleaned_data["email"]
email_field_name = UserModel.get_email_field_name()
for user in self.get_users(email):
if not domain_override:
current_site = get_current_site(request) |
class PasswordResetForm(forms.Form):
domain = current_site.domain
else:
site_name = domain = domain_override
context = {
'email': email,
'domain': domain,
'site_name': site_name,
'uid': urlsafe_base64... | class PasswordResetForm(forms.Form):
domain = current_site.domain
else:
site_name = domain = domain_override
user_email = getattr(user, email_field_name)
context = {
'email': user_email,
'domain': domain,
... |
class PasswordResetForm(forms.Form):
}
self.send_mail(
subject_template_name, email_template_name, context, from_email,
email, html_email_template_name=html_email_template_name,
)
| class PasswordResetForm(forms.Form):
}
self.send_mail(
subject_template_name, email_template_name, context, from_email,
user_email, html_email_template_name=html_email_template_name,
)
|
class PasswordResetFormTest(TestDataMixin, TestCase):
self.assertFalse(form.is_valid())
self.assertEqual(form['email'].errors, [_('Enter a valid email address.')])
def test_nonexistent_email(self):
"""
Test nonexistent email address. This should not fail because it would | class PasswordResetFormTest(TestDataMixin, TestCase):
self.assertFalse(form.is_valid())
self.assertEqual(form['email'].errors, [_('Enter a valid email address.')])
def test_user_email_unicode_collision(self):
User.objects.create_user('mike123', 'mike@example.org', 'test123')
User.ob... |
from django.utils.text import (
from django.utils.timesince import timesince, timeuntil
from django.utils.translation import gettext, ngettext
from .base import Variable, VariableDoesNotExist
from .library import Library
register = Library() | from django.utils.text import (
from django.utils.timesince import timesince, timeuntil
from django.utils.translation import gettext, ngettext
from .base import VARIABLE_ATTRIBUTE_SEPARATOR
from .library import Library
register = Library() |
def striptags(value):
def _property_resolver(arg):
"""
When arg is convertible to float, behave like operator.itemgetter(arg)
Otherwise, behave like Variable(arg).resolve
>>> _property_resolver(1)('abc')
'b' | def striptags(value):
def _property_resolver(arg):
"""
When arg is convertible to float, behave like operator.itemgetter(arg)
Otherwise, chain __getitem__() and getattr().
>>> _property_resolver(1)('abc')
'b' |
def _property_resolver(arg):
try:
float(arg)
except ValueError:
return Variable(arg).resolve
else:
return itemgetter(arg)
| def _property_resolver(arg):
try:
float(arg)
except ValueError:
if VARIABLE_ATTRIBUTE_SEPARATOR + '_' in arg or arg[0] == '_':
raise AttributeError('Access to private variables is forbidden.')
parts = arg.split(VARIABLE_ATTRIBUTE_SEPARATOR)
def resolve(value):
... |
def dictsort(value, arg):
"""
try:
return sorted(value, key=_property_resolver(arg))
except (TypeError, VariableDoesNotExist):
return ''
| def dictsort(value, arg):
"""
try:
return sorted(value, key=_property_resolver(arg))
except (AttributeError, TypeError):
return ''
|
def dictsortreversed(value, arg):
"""
try:
return sorted(value, key=_property_resolver(arg), reverse=True)
except (TypeError, VariableDoesNotExist):
return ''
| def dictsortreversed(value, arg):
"""
try:
return sorted(value, key=_property_resolver(arg), reverse=True)
except (AttributeError, TypeError):
return ''
|
from django.template.defaultfilters import dictsort
from django.test import SimpleTestCase
class FunctionTests(SimpleTestCase):
def test_sort(self):
sorted_dicts = dictsort(
[{'age': 23, 'name': 'Barbara-Ann'}, | from django.template.defaultfilters import _property_resolver, dictsort
from django.test import SimpleTestCase
class User:
password = 'abc'
_private = 'private'
@property
def test_property(self):
return 'cde'
def test_method(self):
"""This is just a test method."""
class Funct... |
class FunctionTests(SimpleTestCase):
def test_dictsort_complex_sorting_key(self):
"""
Since dictsort uses template.Variable under the hood, it can sort
on keys like 'foo.bar'.
"""
data = [ | class FunctionTests(SimpleTestCase):
def test_dictsort_complex_sorting_key(self):
"""
Since dictsort uses dict.get()/getattr() under the hood, it can sort
on keys like 'foo.bar'.
"""
data = [ |
class FunctionTests(SimpleTestCase):
self.assertEqual(dictsort('Hello!', 'age'), '')
self.assertEqual(dictsort({'a': 1}, 'age'), '')
self.assertEqual(dictsort(1, 'age'), '') | class FunctionTests(SimpleTestCase):
self.assertEqual(dictsort('Hello!', 'age'), '')
self.assertEqual(dictsort({'a': 1}, 'age'), '')
self.assertEqual(dictsort(1, 'age'), '')
def test_invalid_args(self):
"""Fail silently if invalid lookups are passed."""
self.assertEqual(dict... |
class FunctionTests(SimpleTestCase):
self.assertEqual(dictsortreversed('Hello!', 'age'), '')
self.assertEqual(dictsortreversed({'a': 1}, 'age'), '')
self.assertEqual(dictsortreversed(1, 'age'), '') | class FunctionTests(SimpleTestCase):
self.assertEqual(dictsortreversed('Hello!', 'age'), '')
self.assertEqual(dictsortreversed({'a': 1}, 'age'), '')
self.assertEqual(dictsortreversed(1, 'age'), '')
def test_invalid_args(self):
"""Fail silently if invalid lookups are passed."""
... |
def standardize_weights(y,
"""Performs sample weight validation and standardization.
Everything gets normalized to a single sample-wise (or timestep-wise)
weight array.
# Arguments
y: Numpy array of model targets to be weighted. | def standardize_weights(y,
"""Performs sample weight validation and standardization.
Everything gets normalized to a single sample-wise (or timestep-wise)
weight array. If both `sample_weights` and `class_weights` are provided,
the weights are multiplied together.
# Arguments
y: Numpy arra... |
def standardize_weights(y,
'sample-wise weights, make sure your '
'sample_weight array is 1D.')
if sample_weight is not None and class_weight is not None:
warnings.warn('Found both `sample_weight` and `class_weight`: '
'`class_... | def standardize_weights(y,
'sample-wise weights, make sure your '
'sample_weight array is 1D.')
if sample_weight is not None:
if len(sample_weight.shape) > len(y.shape):
raise ValueError('Found a sample_weight with shape' + |
def standardize_weights(y,
' for an input with shape ' +
str(y.shape) + '. '
'sample_weight cannot be broadcast.')
return sample_weight
elif isinstance(class_weight, dict):
if len(y.shape) > 2:
raise V... | def standardize_weights(y,
' for an input with shape ' +
str(y.shape) + '. '
'sample_weight cannot be broadcast.')
class_sample_weight = None
if isinstance(class_weight, dict):
if len(y.shape) > 2:
raise ... |
def standardize_weights(y,
' The classes %s exist in the data but not in '
'`class_weight`.'
% (existing_classes - existing_class_weight))
return weights
else:
if sample_weight_mode is None:
return np.... | def standardize_weights(y,
' The classes %s exist in the data but not in '
'`class_weight`.'
% (existing_classes - existing_class_weight))
if sample_weight is not None and class_sample_weight is not None:
return sample_w... |
def test_dynamic_set_inputs():
assert preds4.shape == (1, 19)
if __name__ == '__main__':
pytest.main([__file__]) | def test_dynamic_set_inputs():
assert preds4.shape == (1, 19)
def test_sample_weights():
y = np.array([0, 1, 0, 0, 2])
sample_weights = np.array([0.5, 1., 1., 0., 2.])
class_weights = {0: 0.5, 1: 1., 2: 1.5}
# Only `sample_weights`.
weights = training_utils.standardize_weights(y, sample_weigh... |
notes:
rules. This should work out in most cases, but it is theoretically
possible to see spurious changes when target and actual values are
semantically identical but lexically distinct.
version_added: '2.3'
author:
- Jiri Tyr (@jtyr) | notes:
rules. This should work out in most cases, but it is theoretically
possible to see spurious changes when target and actual values are
semantically identical but lexically distinct.
- "The I(params) parameter is deprecated in Ansible-2.7 due to circumventing Ansible's parameter
handling. The I(... |
EXAMPLES = """
# server_uri: ldap://localhost/
# bind_dn: cn=admin,dc=example,dc=com
# bind_pw: password
- name: Get rid of an unneeded attribute
ldap_attr:
dn: uid=jdoe,ou=people,dc=example,dc=com
name: shadowExpire
values: []
state: exact
params: "{{ ldap_auth }}"
"""
| EXAMPLES = """
# server_uri: ldap://localhost/
# bind_dn: cn=admin,dc=example,dc=com
# bind_pw: password
#
# In the example below, 'args' is a task keyword, passed at the same level as the module
- name: Get rid of an unneeded attribute
ldap_attr:
dn: uid=jdoe,ou=people,dc=example,dc=com
name: shadowExp... |
modlist:
"""
import traceback
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils._text import to_native, to_bytes | modlist:
"""
import traceback
from distutils.version import LooseVersion
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils._text import to_native, to_bytes |
def main():
module.fail_json(
msg="Missing required 'ldap' module (pip install python-ldap)")
# Update module parameters with user's parameters if defined
if 'params' in module.params and isinstance(module.params['params'], dict):
module.params.update(module.params['params'])
... | def main():
module.fail_json(
msg="Missing required 'ldap' module (pip install python-ldap)")
# For Ansible-2.9.x and below, allow the params module parameter with a warning
if LooseVersion(module.ansible_version) < LooseVersion('2.10'):
if module.params['params']:
modul... |
notes:
rule allowing root to modify the server configuration. If you need to use
a simple bind to access your server, pass the credentials in I(bind_dn)
and I(bind_pw).
version_added: '2.3'
author:
- Jiri Tyr (@jtyr) | notes:
rule allowing root to modify the server configuration. If you need to use
a simple bind to access your server, pass the credentials in I(bind_dn)
and I(bind_pw).
- "The I(params) parameter is deprecated in Ansible-2.7 due to circumventing Ansible's parameter
handling. The I(params) parameter s... |
options:
- If I(state=present), value or list of values to use when creating
the entry. It can either be a string or an actual list of
strings.
params:
description:
- List of options which allows to overwrite any of the task or the
I(attributes) options. To remove an option, se... | options:
- If I(state=present), value or list of values to use when creating
the entry. It can either be a string or an actual list of
strings.
state:
description:
- The target state of the entry. |
EXAMPLES = """
# server_uri: ldap://localhost/
# bind_dn: cn=admin,dc=example,dc=com
# bind_pw: password
- name: Get rid of an old entry
ldap_entry:
dn: ou=stuff,dc=example,dc=com
state: absent
params: "{{ ldap_auth }}"
"""
| EXAMPLES = """
# server_uri: ldap://localhost/
# bind_dn: cn=admin,dc=example,dc=com
# bind_pw: password
#
# In the example below, 'args' is a task keyword, passed at the same level as the module
- name: Get rid of an old entry
ldap_entry:
dn: ou=stuff,dc=example,dc=com
state: absent
args: "{{ ldap_au... |
RETURN = """
"""
import traceback
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.six import string_types | RETURN = """
"""
import traceback
from distutils.version import LooseVersion
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.six import string_types |
def main():
module.fail_json(
msg="Missing required 'ldap' module (pip install python-ldap).")
state = module.params['state']
# Check if objectClass is present when needed | def main():
module.fail_json(
msg="Missing required 'ldap' module (pip install python-ldap).")
# For Ansible-2.9.x and below, allow the params module parameter with a warning
if LooseVersion(module.ansible_version) < LooseVersion('2.10'):
if module.params['params']:
modu... |
def main():
isinstance(module.params['objectClass'], list))):
module.fail_json(msg="objectClass must be either a string or a list.")
# Update module parameters with user's parameters if defined
if 'params' in module.params and isinstance(module.params['params'], dict):
for key, ... | def main():
isinstance(module.params['objectClass'], list))):
module.fail_json(msg="objectClass must be either a string or a list.")
# Instantiate the LdapEntry object
ldap = LdapEntry(module)
|
def do_POST(self):
L = []
while size_remaining:
chunk_size = min(size_remaining, max_chunk_size)
L.append(self.rfile.read(chunk_size))
size_remaining -= len(L[-1])
data = ''.join(L)
| def do_POST(self):
L = []
while size_remaining:
chunk_size = min(size_remaining, max_chunk_size)
chunk = self.rfile.read(chunk_size)
if not chunk:
break
L.append(chunk)
size_remaining -= len(L[-1]... |
try:
except AttributeError:
pass
_openssl_verify = {
ssl.CERT_NONE: OpenSSL.SSL.VERIFY_NONE,
ssl.CERT_OPTIONAL: OpenSSL.SSL.VERIFY_PEER,
ssl.CERT_REQUIRED:
OpenSSL.SSL.VERIFY_PEER + OpenSSL.SSL.VERIFY_FAIL_IF_NO_PEER_CERT,
}
#: The list of supported SSL/TLS cipher suites.
DEFAULT_SSL_CIPHER_LI... | try:
except AttributeError:
pass
_stdlib_to_openssl_verify = {
ssl.CERT_NONE: OpenSSL.SSL.VERIFY_NONE,
ssl.CERT_OPTIONAL: OpenSSL.SSL.VERIFY_PEER,
ssl.CERT_REQUIRED:
OpenSSL.SSL.VERIFY_PEER + OpenSSL.SSL.VERIFY_FAIL_IF_NO_PEER_CERT,
}
_openssl_to_stdlib_verify = dict(
(v, k) for k, v in _st... |
class PyOpenSSLContext(object):
@property
def verify_mode(self):
return self._ctx.get_verify_mode()
@verify_mode.setter
def verify_mode(self, value):
self._ctx.set_verify(value, _verify_callback)
def set_default_verify_paths(self):
self._ctx.set_default_verify_paths() | class PyOpenSSLContext(object):
@property
def verify_mode(self):
return _openssl_to_stdlib_verify[self._ctx.get_verify_mode()]
@verify_mode.setter
def verify_mode(self, value):
self._ctx.set_verify(
_stdlib_to_openssl_verify[value], _verify_callback
)
def set_d... |
def ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=None,
if keyfile:
ctx.use_privatekey_file(keyfile)
if cert_reqs != ssl.CERT_NONE:
ctx.set_verify(_openssl_verify[cert_reqs], _verify_callback)
if ca_certs or ca_cert_dir:
try:
ctx.load_verify_locations(ca_ce... | def ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=None,
if keyfile:
ctx.use_privatekey_file(keyfile)
if cert_reqs != ssl.CERT_NONE:
ctx.set_verify(_stdlib_to_openssl_verify[cert_reqs], _verify_callback)
if ca_certs or ca_cert_dir:
try:
ctx.load_verify_locat... |
class _Rolling_and_Expanding(_Rolling):
# only default unset
pairwise = True if pairwise is None else pairwise
other = self._shallow_copy(other)
window = self._get_window(other)
def _get_corr(a, b):
a = a.rolling( | class _Rolling_and_Expanding(_Rolling):
# only default unset
pairwise = True if pairwise is None else pairwise
other = self._shallow_copy(other)
window = self._get_window(other) if not self.is_freq_type else self.win_freq
def _get_corr(a, b):
a = a.rolling( |
import warnings
import pytest
from pandas import DataFrame, Series
import pandas._testing as tm
from pandas.core.algorithms import safe_sort
| import warnings
import numpy as np
import pytest
from pandas import DataFrame, Series, date_range
import pandas._testing as tm
from pandas.core.algorithms import safe_sort
|
class TestPairwise:
for i, result in enumerate(results):
if i > 0:
self.compare(result, results[0]) | class TestPairwise:
for i, result in enumerate(results):
if i > 0:
self.compare(result, results[0])
def test_corr_freq_memory_error(self):
# GH 31789
s = Series(range(5), index=date_range("2020", periods=5))
result = s.rolling("12H").corr(s)
expec... |
class AbstractBasicAuthHandler:
# (single quotes are a violation of the RFC, but appear in the wild)
rx = re.compile('(?:^|,)' # start of the string or ','
'[ \t]*' # optional whitespaces
'([^ \t]+)' # scheme like "Basic"
'[ \t]+' # mandatory w... | class AbstractBasicAuthHandler:
# (single quotes are a violation of the RFC, but appear in the wild)
rx = re.compile('(?:^|,)' # start of the string or ','
'[ \t]*' # optional whitespaces
'([^ \t,]+)' # scheme like "Basic"
'[ \t]+' # mandatory ... |
class AbstractBasicAuthHandler:
# (single quotes are a violation of the RFC, but appear in the wild)
rx = re.compile('(?:^|,)' # start of the string or ','
'[ \t]*' # optional whitespaces
'([^ \t]+)' # scheme like "Basic"
'[ \t]+' # mandatory w... | class AbstractBasicAuthHandler:
# (single quotes are a violation of the RFC, but appear in the wild)
rx = re.compile('(?:^|,)' # start of the string or ','
'[ \t]*' # optional whitespaces
'([^ \t,]+)' # scheme like "Basic"
'[ \t]+' # mandatory ... |
setup(name='gym',
if package.startswith('gym')],
zip_safe=False,
install_requires=[
'scipy', 'numpy>=1.10.4', 'pyglet>=1.4.0,<=1.5.0', 'Pillow<=7.2.0', 'cloudpickle>=1.2.0,<1.7.0',
],
extras_require=extras,
package_data={'gym': [ | setup(name='gym',
if package.startswith('gym')],
zip_safe=False,
install_requires=[
'scipy',
'numpy>=1.10.4',
'pyglet>=1.4.0,<=1.5.15',
'Pillow<=8.2.0',
'cloudpickle>=1.2.0,<1.7.0',
],
extras_require=extras,
package_data={'gym': [ |
def test_urlsplit_normalization(self):
urlparse.urlsplit(u'http://\u30d5\u309a\ufe1380')
for scheme in [u"http", u"https", u"ftp"]:
for c in denorm_chars:
url = u"{}://netloc{}false.netloc/path".format(scheme, c)
if test_support.verbose:
... | def test_urlsplit_normalization(self):
urlparse.urlsplit(u'http://\u30d5\u309a\ufe1380')
for scheme in [u"http", u"https", u"ftp"]:
for netloc in [u"netloc{}false.netloc", u"n{}user@netloc"]:
for c in denorm_chars:
url = u"{}://{}/path".format(scheme,... |
def _checknetloc(netloc):
# looking for characters like \u2100 that expand to 'a/c'
# IDNA uses NFKC equivalence, so normalize for this check
import unicodedata
n = netloc.rpartition('@')[2] # ignore anything to the left of '@'
n = n.replace(':', '') # ignore characters already included
n... | def _checknetloc(netloc):
# looking for characters like \u2100 that expand to 'a/c'
# IDNA uses NFKC equivalence, so normalize for this check
import unicodedata
n = netloc.replace(u'@', u'') # ignore characters already included
n = n.replace(u':', u'') # but not the surrounding text
n = n.r... |
from pandas.core.dtypes.inference import is_array_like
from pandas import compat
from pandas.core import ops
from pandas.core.arrays import PandasArray
from pandas.core.construction import extract_array
from pandas.core.indexers import check_array_indexer
from pandas.core.missing import isna | from pandas.core.dtypes.inference import is_array_like
from pandas import compat
from pandas.core import ops
from pandas.core.arrays import IntegerArray, PandasArray
from pandas.core.arrays.integer import _IntegerDtype
from pandas.core.construction import extract_array
from pandas.core.indexers import check_array_inde... |
class StringArray(PandasArray):
if copy:
return self.copy()
return self
return super().astype(dtype, copy)
def _reduce(self, name, skipna=True, **kwargs): | class StringArray(PandasArray):
if copy:
return self.copy()
return self
elif isinstance(dtype, _IntegerDtype):
arr = self._ndarray.copy()
mask = self.isna()
arr[mask] = 0
values = arr.astype(dtype.numpy_dtype)
re... |
def test_from_sequence_no_mutate(copy):
tm.assert_numpy_array_equal(a, original)
@pytest.mark.parametrize("skipna", [True, False])
@pytest.mark.xfail(reason="Not implemented StringArray.sum")
def test_reduce(skipna): | def test_from_sequence_no_mutate(copy):
tm.assert_numpy_array_equal(a, original)
def test_astype_int():
arr = pd.array(["1", pd.NA, "3"], dtype="string")
result = arr.astype("Int64")
expected = pd.array([1, pd.NA, 3], dtype="Int64")
tm.assert_extension_array_equal(result, expected)
@pytest.mark... |
from synapse.http.server import finish_request, respond_with_json
from synapse.http.site import SynapseRequest
from synapse.logging.context import make_deferred_yieldable
from synapse.util.stringutils import is_ascii
logger = logging.getLogger(__name__)
| from synapse.http.server import finish_request, respond_with_json
from synapse.http.site import SynapseRequest
from synapse.logging.context import make_deferred_yieldable
from synapse.util.stringutils import is_ascii, parse_and_validate_server_name
logger = logging.getLogger(__name__)
|
def parse_media_id(request: Request) -> Tuple[str, str, Optional[str]]:
try:
# The type on postpath seems incorrect in Twisted 21.2.0.
postpath: List[bytes] = request.postpath # type: ignore |
def parse_media_id(request: Request) -> Tuple[str, str, Optional[str]]:
"""Parses the server name, media ID and optional file name from the request URI
Also performs some rough validation on the server name.
Args:
request: The `Request`.
Returns:
A tuple containing the parsed server... |
def parse_media_id(request: Request) -> Tuple[str, str, Optional[str]]:
server_name = server_name_bytes.decode("utf-8")
media_id = media_id_bytes.decode("utf8")
file_name = None
if len(postpath) > 2:
try: | def parse_media_id(request: Request) -> Tuple[str, str, Optional[str]]:
server_name = server_name_bytes.decode("utf-8")
media_id = media_id_bytes.decode("utf8")
# Validate the server name, raising if invalid
parse_and_validate_server_name(server_name)
file_name = None
i... |
import functools
import os
import re
from typing import Any, Callable, List, TypeVar, cast
NEW_FORMAT_ID_RE = re.compile(r"^\d\d\d\d-\d\d-\d\d")
| import functools
import os
import re
import string
from typing import Any, Callable, List, TypeVar, Union, cast
NEW_FORMAT_ID_RE = re.compile(r"^\d\d\d\d-\d\d-\d\d")
|
def _wrapped(self: "MediaFilePaths", *args: Any, **kwargs: Any) -> str:
return cast(F, _wrapped)
class MediaFilePaths:
"""Describes where files are stored on disk.
| def _wrapped(self: "MediaFilePaths", *args: Any, **kwargs: Any) -> str:
return cast(F, _wrapped)
GetPathMethod = TypeVar(
"GetPathMethod", bound=Union[Callable[..., str], Callable[..., List[str]]]
)
def _wrap_with_jail_check(func: GetPathMethod) -> GetPathMethod:
"""Wraps a path-returning method to chec... |
class MediaFilePaths:
def __init__(self, primary_base_path: str):
self.base_path = primary_base_path
def local_media_filepath_rel(self, media_id: str) -> str:
return os.path.join("local_content", media_id[0:2], media_id[2:4], media_id[4:])
local_media_filepath = _wrap_in_base_path(local_me... | class MediaFilePaths:
def __init__(self, primary_base_path: str):
self.base_path = primary_base_path
# The media store directory, with all symlinks resolved.
self.real_base_path = os.path.realpath(primary_base_path)
# Refuse to initialize if paths cannot be validated correctly for ... |
def local_media_thumbnail_dir(self, media_id: str) -> str:
return os.path.join(
self.base_path,
"local_thumbnails",
media_id[0:2],
media_id[2:4],
media_id[4:],
)
def remote_media_filepath_rel(self, server_name: str, file_id: str) -> str:
... | def local_media_thumbnail_dir(self, media_id: str) -> str:
return os.path.join(
self.base_path,
"local_thumbnails",
_validate_path_component(media_id[0:2]),
_validate_path_component(media_id[2:4]),
_validate_path_component(media_id[4:]),
)
... |
def remote_media_thumbnail_rel(
file_name = "%i-%i-%s-%s-%s" % (width, height, top_level_type, sub_type, method)
return os.path.join(
"remote_thumbnail",
server_name,
file_id[0:2],
file_id[2:4],
file_id[4:],
file_name,
)
... | def remote_media_thumbnail_rel(
file_name = "%i-%i-%s-%s-%s" % (width, height, top_level_type, sub_type, method)
return os.path.join(
"remote_thumbnail",
_validate_path_component(server_name),
_validate_path_component(file_id[0:2]),
_validate_path_componen... |
def remote_media_thumbnail_rel(
# Legacy path that was used to store thumbnails previously.
# Should be removed after some time, when most of the thumbnails are stored
# using the new path.
def remote_media_thumbnail_rel_legacy(
self, server_name: str, file_id: str, width: int, height: int, cont... | def remote_media_thumbnail_rel(
# Legacy path that was used to store thumbnails previously.
# Should be removed after some time, when most of the thumbnails are stored
# using the new path.
@_wrap_with_jail_check
def remote_media_thumbnail_rel_legacy(
self, server_name: str, file_id: str, wi... |
def remote_media_thumbnail_rel_legacy(
file_name = "%i-%i-%s-%s" % (width, height, top_level_type, sub_type)
return os.path.join(
"remote_thumbnail",
server_name,
file_id[0:2],
file_id[2:4],
file_id[4:],
file_name,
)
de... | def remote_media_thumbnail_rel_legacy(
file_name = "%i-%i-%s-%s" % (width, height, top_level_type, sub_type)
return os.path.join(
"remote_thumbnail",
_validate_path_component(server_name),
_validate_path_component(file_id[0:2]),
_validate_path_component(fi... |
def url_cache_thumbnail_rel(
if NEW_FORMAT_ID_RE.match(media_id):
return os.path.join(
"url_cache_thumbnails", media_id[:10], media_id[11:], file_name
)
else:
return os.path.join(
"url_cache_thumbnails",
media_id[0:2],
... | def url_cache_thumbnail_rel(
if NEW_FORMAT_ID_RE.match(media_id):
return os.path.join(
"url_cache_thumbnails",
_validate_path_component(media_id[:10]),
_validate_path_component(media_id[11:]),
_validate_path_component(file_name),
... |
def url_cache_thumbnail_dirs_to_delete(self, media_id: str) -> List[str]:
if NEW_FORMAT_ID_RE.match(media_id):
return [
os.path.join(
self.base_path, "url_cache_thumbnails", media_id[:10], media_id[11:]
),
os.path.join(self.base_pat... | def url_cache_thumbnail_dirs_to_delete(self, media_id: str) -> List[str]:
if NEW_FORMAT_ID_RE.match(media_id):
return [
os.path.join(
self.base_path,
"url_cache_thumbnails",
_validate_path_component(media_id[:10]),
... |
from collections.abc import Iterable
from typing import Optional, Tuple
from synapse.api.errors import Codes, SynapseError
_string_with_symbols = string.digits + string.ascii_letters + ".,;:^&*-_+=#~@" | from collections.abc import Iterable
from typing import Optional, Tuple
from netaddr import valid_ipv6
from synapse.api.errors import Codes, SynapseError
_string_with_symbols = string.digits + string.ascii_letters + ".,;:^&*-_+=#~@" |
def parse_server_name(server_name: str) -> Tuple[str, Optional[int]]:
raise ValueError("Invalid server name '%s'" % server_name)
VALID_HOST_REGEX = re.compile("\\A[0-9a-zA-Z.-]+\\Z")
def parse_and_validate_server_name(server_name: str) -> Tuple[str, Optional[int]]: | def parse_server_name(server_name: str) -> Tuple[str, Optional[int]]:
raise ValueError("Invalid server name '%s'" % server_name)
# An approximation of the domain name syntax in RFC 1035, section 2.3.1.
# NB: "\Z" is not equivalent to "$".
# The latter will match the position before a "\n" at the end of a ... |
def parse_and_validate_server_name(server_name: str) -> Tuple[str, Optional[int]
if host[0] == "[":
if host[-1] != "]":
raise ValueError("Mismatched [...] in server name '%s'" % (server_name,))
return host, port
# otherwise it should only be alphanumerics.
if not VALID_HOST_REGE... | def parse_and_validate_server_name(server_name: str) -> Tuple[str, Optional[int]
if host[0] == "[":
if host[-1] != "]":
raise ValueError("Mismatched [...] in server name '%s'" % (server_name,))
# valid_ipv6 raises when given an empty string
ipv6_address = host[1:-1]
if n... |
def test_validate_bad_server_names(self):
"localhost:http", # non-numeric port
"1234]", # smells like ipv6 literal but isn't
"[1234",
"underscore_.com",
"percent%65.com",
"1234:5678:80", # too many colons
]
for i in test_data: | def test_validate_bad_server_names(self):
"localhost:http", # non-numeric port
"1234]", # smells like ipv6 literal but isn't
"[1234",
"[1.2.3.4]",
"underscore_.com",
"percent%65.com",
"newline.com\n",
".empty-label.com",
... |
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from synapse.rest.media.v1.filepath import MediaFilePaths
from tests import unittest | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import inspect
from typing import Iterable
from synapse.rest.media.v1.filepath import MediaFilePaths
from tests import unittest |
def test_url_cache_thumbnail_dirs_to_delete_legacy(self):
"/media_store/url_cache_thumbnails/Ge",
],
) | def test_url_cache_thumbnail_dirs_to_delete_legacy(self):
"/media_store/url_cache_thumbnails/Ge",
],
)
def test_server_name_validation(self):
"""Test validation of server names"""
self._test_path_validation(
[
"remote_media_filepath_re... |
from oic.oauth2.message import ErrorResponse
from oic.oauth2.message import Message
from oic.oauth2.message import MessageFactory
from oic.oauth2.util import get_or_post
from oic.oic.message import SCOPE2CLAIMS
from oic.oic.message import AccessTokenResponse | from oic.oauth2.message import ErrorResponse
from oic.oauth2.message import Message
from oic.oauth2.message import MessageFactory
from oic.oauth2.message import WrongSigningAlgorithm
from oic.oauth2.util import get_or_post
from oic.oic.message import SCOPE2CLAIMS
from oic.oic.message import AccessTokenResponse |
def sign_enc_algs(self, typ):
return resp
def _verify_id_token(
self, id_token, nonce="", acr_values=None, auth_time=0, max_age=0
):
"""
Verify IdToken. | def sign_enc_algs(self, typ):
return resp
def _verify_id_token(
self,
id_token,
nonce="",
acr_values=None,
auth_time=0,
max_age=0,
response_type="",
):
"""
Verify IdToken. |
def _verify_id_token(
if _now > id_token["exp"]:
raise OtherError("Passed best before date")
if (
self.id_token_max_age
and _now > int(id_token["iat"]) + self.id_token_max_age | def _verify_id_token(
if _now > id_token["exp"]:
raise OtherError("Passed best before date")
if response_type != ["code"] and id_token.jws_header["alg"] == "none":
raise WrongSigningAlgorithm(
"none is not allowed outside Authorization Flow."
)
... |
def verify_id_token(self, id_token, authn_req):
except KeyError:
pass
for param in ["acr_values", "max_age"]:
try:
kwa[param] = authn_req[param]
except KeyError: | def verify_id_token(self, id_token, authn_req):
except KeyError:
pass
for param in ["acr_values", "max_age", "response_type"]:
try:
kwa[param] = authn_req[param]
except KeyError: |
import warnings
from typing import Dict
from typing import Optional
from oic import rndstr
from oic.exception import AuthzError | import warnings
from typing import Dict
from typing import Optional
from typing import Tuple
from typing import Union
from oic import rndstr
from oic.exception import AuthzError |
from oic.oic.message import BackChannelLogoutRequest
from oic.oic.message import Claims
from oic.oic.message import ClaimsRequest
from oic.utils import http_util
from oic.utils.sanitize import sanitize
from oic.utils.sdb import DictSessionBackend | from oic.oic.message import BackChannelLogoutRequest
from oic.oic.message import Claims
from oic.oic.message import ClaimsRequest
from oic.oic.message import IdToken
from oic.utils import http_util
from oic.utils.sanitize import sanitize
from oic.utils.sdb import DictSessionBackend |
def begin(self, scope="", response_type="", use_nonce=False, path="", **kwargs):
if self.debug:
_log_info("Redirecting to: %s" % location)
return sid, location
def _parse_authz(self, query="", **kwargs): | def begin(self, scope="", response_type="", use_nonce=False, path="", **kwargs):
if self.debug:
_log_info("Redirecting to: %s" % location)
self.authz_req[areq["state"]] = areq
return sid, location
def _parse_authz(self, query="", **kwargs): |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.