问:
Got an error when try to use Social Auth backends fir dj-rest-auth app DRF
I wanted to add social media auth endpoints from dj-rest-auth third-party app.
I did everything from the dj-rest-auth documentation.

I am getting this strange error, though:

```<code> File "/home/vlad/projects/DjangoProjects/portfolioProjects/resume_website_restapi/env/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner
    response = get_response(request)
  File "/home/vlad/projects/DjangoProjects/portfolioProjects/resume_website_restapi/env/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/vlad/projects/DjangoProjects/portfolioProjects/resume_website_restapi/env/lib/python3.10/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
    return view_func(*args, **kwargs)
  File "/home/vlad/projects/DjangoProjects/portfolioProjects/resume_website_restapi/env/lib/python3.10/site-packages/django/views/generic/base.py", line 103, in view
    return self.dispatch(request, *args, **kwargs)
  File "/home/vlad/projects/DjangoProjects/portfolioProjects/resume_website_restapi/env/lib/python3.10/site-packages/django/utils/decorators.py", line 46, in _wrapper
    return bound_method(*args, **kwargs)
  File "/home/vlad/projects/DjangoProjects/portfolioProjects/resume_website_restapi/env/lib/python3.10/site-packages/django/views/decorators/debug.py", line 92, in sensitive_post_parameters_wrapper
    return view(request, *args, **kwargs)
  File "/home/vlad/projects/DjangoProjects/portfolioProjects/resume_website_restapi/env/lib/python3.10/site-packages/dj_rest_auth/views.py", line 53, in dispatch
    return super().dispatch(*args, **kwargs)
  File "/home/vlad/projects/DjangoProjects/portfolioProjects/resume_website_restapi/env/lib/python3.10/site-packages/rest_framework/views.py", line 509, in dispatch
    response = self.handle_exception(exc)
  File "/home/vlad/projects/DjangoProjects/portfolioProjects/resume_website_restapi/env/lib/python3.10/site-packages/rest_framework/views.py", line 469, in handle_exception
    self.raise_uncaught_exception(exc)
  File "/home/vlad/projects/DjangoProjects/portfolioProjects/resume_website_restapi/env/lib/python3.10/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception
    raise exc
  File "/home/vlad/projects/DjangoProjects/portfolioProjects/resume_website_restapi/env/lib/python3.10/site-packages/rest_framework/views.py", line 506, in dispatch
    response = handler(request, *args, **kwargs)
  File "/home/vlad/projects/DjangoProjects/portfolioProjects/resume_website_restapi/env/lib/python3.10/site-packages/dj_rest_auth/views.py", line 130, in post
    self.serializer.is_valid(raise_exception=True)
  File "/home/vlad/projects/DjangoProjects/portfolioProjects/resume_website_restapi/env/lib/python3.10/site-packages/rest_framework/serializers.py", line 227, in is_valid
    self._validated_data = self.run_validation(self.initial_data)
  File "/home/vlad/projects/DjangoProjects/portfolioProjects/resume_website_restapi/env/lib/python3.10/site-packages/rest_framework/serializers.py", line 429, in run_validation
    value = self.validate(value)
  File "/home/vlad/projects/DjangoProjects/portfolioProjects/resume_website_restapi/env/lib/python3.10/site-packages/dj_rest_auth/serializers.py", line 121, in validate
    user = self.get_auth_user(username, email, password)
  File "/home/vlad/projects/DjangoProjects/portfolioProjects/resume_website_restapi/env/lib/python3.10/site-packages/dj_rest_auth/serializers.py", line 96, in get_auth_user
    return self.get_auth_user_using_allauth(username, email, password)
  File "/home/vlad/projects/DjangoProjects/portfolioProjects/resume_website_restapi/env/lib/python3.10/site-packages/dj_rest_auth/serializers.py", line 62, in get_auth_user_using_allauth
    return self._validate_email(email, password)
  File "/home/vlad/projects/DjangoProjects/portfolioProjects/resume_website_restapi/env/lib/python3.10/site-packages/dj_rest_auth/serializers.py", line 30, in _validate_email
    user = self.authenticate(email=email, password=password)
  File "/home/vlad/projects/DjangoProjects/portfolioProjects/resume_website_restapi/env/lib/python3.10/site-packages/dj_rest_auth/serializers.py", line 26, in authenticate
    return authenticate(self.context['request'], **kwargs)
  File "/home/vlad/projects/DjangoProjects/portfolioProjects/resume_website_restapi/env/lib/python3.10/site-packages/django/views/decorators/debug.py", line 42, in sensitive_variables_wrapper
    return func(*func_args, **func_kwargs)
  File "/home/vlad/projects/DjangoProjects/portfolioProjects/resume_website_restapi/env/lib/python3.10/site-packages/django/contrib/auth/__init__.py", line 68, in authenticate
    for backend, backend_path in _get_backends(return_tuples=True):
  File "/home/vlad/projects/DjangoProjects/portfolioProjects/resume_website_restapi/env/lib/python3.10/site-packages/django/contrib/auth/__init__.py", line 27, in _get_backends
    backend = load_backend(backend_path)
  File "/home/vlad/projects/DjangoProjects/portfolioProjects/resume_website_restapi/env/lib/python3.10/site-packages/django/contrib/auth/__init__.py", line 21, in load_backend
    return import_string(path)()
TypeError: BaseAuth.__init__() missing 1 required positional argument: 'strategy'
</code>```

settings.py

```<code>
"""
Django settings for resume_website_restapi project.

Generated by 'django-admin startproject' using Django 4.1.3.

For more information on this file, see
https://docs.djangoproject.com/en/4.1/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.1/ref/settings/
"""

from pathlib import Path
import os
from datetime import timedelta

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-b#t)ywiymb&@+mv^%j$p&4*y)iq2z-1da*z@beo4s-6-qu9ba%'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

SITE_ID = 2

# Application definition

INSTALLED_APPS = [
    'jazzmin',
    'django.contrib.admin',
    'django.contrib.sites',
    'allauth',
    'allauth.account',
    'allauth.socialaccount',
    'allauth.socialaccount.providers.google',
    'allauth.socialaccount.providers.github',
    'allauth.socialaccount.providers.facebook',

    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'rest_framework.authtoken',
    'dj_rest_auth',
    'django_filters',
    'django_countries',
    'posts.apps.PostsConfig',
    'users.apps.UsersConfig',
    'comments.apps.CommentsConfig',
    'category.apps.CategoryConfig',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'resume_website_restapi.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR / 'templates'],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'resume_website_restapi.wsgi.application'

# Database
# https://docs.djangoproject.com/en/4.1/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}

# Password validation
# https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

REST_FRAMEWORK = {
    # Permissions
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAuthenticatedOrReadOnly',
    ],
    # Authentication
       'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework_simplejwt.authentication.JWTAuthentication',
        'rest_framework.authentication.BasicAuthentication',
        # 'rest_framework.authentication.SessionAuthentication',
    ],
    # django-filters
    'DEFAULT_FILTER_BACKENDS': [
        'django_filters.rest_framework.DjangoFilterBackend',
    ],
    # Pagination
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 3,
}

REST_USE_JWT = True
# JWT_AUTH_RETURN_EXPIRATION = True
# Cookies
JWT_AUTH_COOKIE = 'blog-auth'
JWT_AUTH_REFRESH_COOKIE = 'blog-refresh-token'

# Internationalization
# https://docs.djangoproject.com/en/4.1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.1/howto/static-files/

STATIC_URL = 'static/'
MEDIA_URL = 'media/'

# Default primary key field type
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field

STATIC_ROOT = os.path.join(BASE_DIR, 'static')
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

# Default primary key field type
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

# User model
AUTH_USER_MODEL = "users.Profile"

AUTHENTICATION_BACKENDS = (
"social_core.backends.google.GoogleOAuth2",
"social_core.backends.facebook.FacebookOAuth2",
"social_core.backends.github.GitHubOAuth2",
"allauth.account.auth_backends.AuthenticationBackend",
"django.contrib.auth.backends.ModelBackend",

)

# JWT Auth
SIMPLE_JWT = {
    'ACCESS_TOKEN_LIFETIME': timedelta(days=1),
    'REFRESH_TOKEN_LIFETIME': timedelta(days=1),
    'ROTATE_REFRESH_TOKENS': False,
    'BLACKLIST_AFTER_ROTATION': False,
    'UPDATE_LAST_LOGIN': False,

    'ALGORITHM': 'HS256',
    'SIGNING_KEY': SECRET_KEY,
    'VERIFYING_KEY': None,
    'AUDIENCE': None,
    'ISSUER': None,
    'JWK_URL': None,
    'LEEWAY': 0,

    'AUTH_HEADER_TYPES': ('Bearer',),
    'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION',
    'USER_ID_FIELD': 'id',
    'USER_ID_CLAIM': 'user_id',
    'USER_AUTHENTICATION_RULE': 'rest_framework_simplejwt.authentication.default_user_authentication_rule',

    'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',),
    'TOKEN_TYPE_CLAIM': 'token_type',
    'TOKEN_USER_CLASS': 'rest_framework_simplejwt.models.TokenUser',

    'JTI_CLAIM': 'jti',

    'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp',
    'SLIDING_TOKEN_LIFETIME': timedelta(minutes=5),
    'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1),
}

from django.urls import reverse_lazy

# All auth
LOGIN_URL = reverse_lazy('users:login')
LOGOUT_REDIRECT_URL = reverse_lazy('users:login')
ACCOUNT_EMAIL_VERIFICATION = "mandatory"
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_AUTHENTICATION_METHOD = "email"
ACCOUNT_LOGOUT_ON_PASSWORD_CHANGE = True
ACCOUNT_USERNAME_REQUIRED = False

# SocialAccount Auth
SOCIALACCOUNT_PROVIDERS = {
"github": {
    "APP": {
        "client_id": os.environ.get("GitHub_OAUTH_CLIENT_ID"),
        "secret": os.environ.get("GitHub_OAUTH_SECRET"),
    },
},
"google": {
    "APP": {
        "client_id": os.environ.get("Google_OAUTH_CLIENT_ID"),
        "secret": os.environ.get("Google_OAUTH_SECRET"),
    },
},
}

# Email sending credentials
EMAIL_HOST = 'smtp.mailtrap.io'
EMAIL_HOST_USER = 'a923489850d8ef'
EMAIL_HOST_PASSWORD = 'a47074cae95d6b'
EMAIL_PORT = '2525'

#Custom admin panel with django-jazzmin
JAZZMIN_SETTINGS = {
    "site_title": "Blog",
    "site_header": "your_site_header",
    "site_brand": "Blog",
    "site_icon": "profiles/default.jpg",
    # Add your own branding here
    "site_logo": None,
    "welcome_sign": "Welcome to the Blog",
    # Copyright on the footer
    "copyright": "Blog",
    "user_avatar": "profiles/default.jpg",
    ############
    # Top Menu #
    ############
    # Links to put along the top menu
    "topmenu_links": [
        # Url that gets reversed (Permissions can be added)
        {"name": "Blog", "url": "posts:posts-list", "permissions": ["auth.view_user"]},
        # model admin to link to (Permissions checked against model)
        {"model": "users.Profile"},
    ],
    #############
    # Side Menu #
    #############
    # Whether to display the side menu
    "show_sidebar": True,
    # Whether to aut expand the menu
    "navigation_expanded": True,
    # Custom icons for side menu apps/models See https://fontawesome.com/icons?d=gallery&m=free&v=5.0.0,5.0.1,5.0.10,5.0.11,5.0.12,5.0.13,5.0.2,5.0.3,5.0.4,5.0.5,5.0.6,5.0.7,5.0.8,5.0.9,5.1.0,5.1.1,5.2.0,5.3.0,5.3.1,5.4.0,5.4.1,5.4.2,5.13.0,5.12.0,5.11.2,5.11.1,5.10.0,5.9.0,5.8.2,5.8.1,5.7.2,5.7.1,5.7.0,5.6.3,5.5.0,5.4.2
    # for the full list of 5.13.0 free icon classes
    "icons": {
        "auth": "fas fa-users-cog",
        "auth.user": "fas fa-user",
        "users.User": "fas fa-user",
        "auth.Group": "fas fa-users",
        "admin.LogEntry": "fas fa-file",
    },
    # # Icons that are used when one is not manually specified
    "default_icon_parents": "fas fa-chevron-circle-right",
    "default_icon_children": "fas fa-arrow-circle-right",
    #################
    # Related Modal #
    #################
    # Use modals instead of popups
    "related_modal_active": False,
    #############
    # UI Tweaks #
    #############
    # Relative paths to custom CSS/JS scripts (must be present in static files)
    # Uncomment this line once you create the bootstrap-dark.css file
    "custom_css": "styles/admin.css",
    "custom_js": None,
    # Whether to show the UI customizer on the sidebar
    "show_ui_builder": False,
    ###############
    # Change view #
    ###############
    "changeform_format": "horizontal_tabs",
    # override change forms on a per modeladmin basis
    "changeform_format_overrides": {
        "auth.user": "collapsible",
        "auth.group": "vertical_tabs",
    },
}

JAZZMIN_UI_TWEAKS = {
    "navbar_small_text": False,
    "footer_small_text": False,
    "body_small_text": False,
    "brand_small_text": False,
    "brand_colour": "navbar-success",
    "accent": "accent-teal",
    "navbar": "navbar-dark",
    "no_navbar_border": False,
    "navbar_fixed": False,
    "layout_boxed": False,
    "footer_fixed": False,
    "sidebar_fixed": False,
    "sidebar": "sidebar-dark-info",
    "sidebar_nav_small_text": False,
    "sidebar_disable_expand": False,
    "sidebar_nav_child_indent": False,
    "sidebar_nav_compact_style": False,
    "sidebar_nav_legacy_style": False,
    "sidebar_nav_flat_style": False,
    "theme": "cyborg",
    "dark_mode_theme": None,
    "button_classes": {
        "primary": "btn-primary",
        "secondary": "btn-secondary",
        "info": "btn-info",
        "warning": "btn-warning",
        "danger": "btn-danger",
        "success": "btn-success",
    },
}

</code>```

views.py

```<code>from django.utils.translation import gettext_lazy as _
from django.contrib.auth.tokens import default_token_generator
# Auth
from django.contrib.auth import get_user_model, logout
from allauth.account.utils import logout_on_password_change
# SocialAccount auth
from allauth.socialaccount.providers.facebook.views import FacebookOAuth2Adapter
from allauth.socialaccount.providers.google.views import GoogleOAuth2Adapter
from allauth.socialaccount.providers.github.views import GitHubOAuth2Adapter
from allauth.socialaccount.providers.oauth2.client import OAuth2Client
from dj_rest_auth.registration.views import SocialLoginView

# REST FRAMEWORK
from rest_framework.reverse import reverse, reverse_lazy
from rest_framework.response import Response
from rest_framework import permissions
from rest_framework import status
from rest_framework.decorators import (
                                            api_view,
                                            permission_classes,
                                            authentication_classes,
                                    )
from rest_framework import generics

from .serializers import (
                        UserRegisterSerializer,
                        UserSerializer,
                        PasswordResetSerializer,
                        ChangePasswordSerializer,
                    )

from . import exceptions as custom_exceptions

Profile = get_user_model()

class UserSignUpApiView(generics.CreateAPIView):
    serializer_class = UserRegisterSerializer
    permission_classes = (permissions.AllowAny,)
    authentication_classes = ()

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data, context={'request': request})
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        print(serializer.data)
        return Response(serializer.data, status=status.HTTP_201_CREATED)

class UsersListApiView(generics.ListAPIView):
    serializer_class = UserSerializer
    queryset = Profile.objects.all()

@api_view(['GET', 'POST'])
@permission_classes([permissions.AllowAny,])
def activate_account(request, uuid, token):
    try:
        user = Profile.objects.get(id=uuid)
    except (Profile.DoesNotExist, TypeError, ValueError, OverflowError):
        user = None

    if user is not None and default_token_generator.check_token(user, token):
        user.is_active = True
        user.save()
    else:
        raise custom_exceptions.UserOrTokenNotValid

    return Response(
        {"detail: Activated"},
        status=status.HTTP_200_OK,
        )

@api_view(['POST'])
@permission_classes([permissions.AllowAny,])
def reset_password(request, *args, **kwargs):
    print('kwargs', kwargs)
    serializer = PasswordResetSerializer(
            data=request.data,
            context={'request': request}
    )
    serializer.is_valid(raise_exception=True)

    return Response(
        {"detail": "Sent an confirmation email"},
        status=status.HTTP_302_FOUND,
    )

class PasswordChangeApiView(generics.UpdateAPIView):
    serializer_class = ChangePasswordSerializer
    permission_classes = (permissions.AllowAny,)

    def get_object(self):
        try:
            profile = Profile.objects.get(id=self.kwargs.get('uuid', ''))
        except Profile.DoesNotExist:
            profile = None

        return profile

    def patch(self, request, *args, **kwargs):
        user = self.get_object()
        serializer = self.serializer_class(
                                            instance=user,
                                            data=request.data,
                                            partial=True,
                                            context={'request': self.request},
                                        )
        serializer.is_valid(raise_exception=True)
        self.perform_update(serializer)

        logout_on_password_change(request, user)
        return Response(
            {'detail':'Password changed!'},
            status=status.HTTP_200_OK,
        )

class  ProfileDetailUpdateDeleteApiView(generics.RetrieveUpdateDestroyAPIView):
    serializer_class = UserSerializer

    def get_object(self):
        try:
            profile = Profile.objects.get(id=self.kwargs.get('pk', ''))
        except Profile.DoesNotExist:
            profile = None
        print(self.request.user, self.request.user.is_authenticated)
        print(self.request.user.auth_token)

        return profile

    def destroy(self, request, *args, **kwargs):
        profile = self.get_object()
        if profile is not None:
            self.perform_destroy(profile)
            logout(request)
            return Response(
                {'detail': 'Profile deleted!'},
                status=status.HTTP_200_OK,
            )

        return Response(
                        {'detail': 'Profile does not exist!'},
                        status=status.HTTP_200_OK,
                    )

# the Logout dj-rest-auth view and this one do not work
@api_view(["POST"])
@permission_classes([permissions.IsAuthenticated, ])
def logout_user(request):

    request.user.auth_token.delete()

    logout(request)

    return Response('User Logged out successfully')

# Social account auth

class GitHubLogin(SocialLoginView):
    adapter_class = GitHubOAuth2Adapter
    callback_url = reverse_lazy('posts:posts-list')
    client_class = OAuth2Client

# if you want to use Authorization Code Grant, use this
class GoogleLogin(SocialLoginView):
    adapter_class = GoogleOAuth2Adapter
    callback_url = reverse_lazy('posts:posts-list')
    client_class = OAuth2Client

class FacebookLogin(SocialLoginView):
    adapter_class = FacebookOAuth2Adapter

</code>```

urls.py

```<code>from django.urls import path
from dj_rest_auth import views as dj_rest_auth_views
# DRF
from rest_framework_simplejwt.views import (
    TokenObtainPairView,
    TokenRefreshView,
)
from rest_framework.decorators import authentication_classes

from . import views as custom_views

app_name='users'

urlpatterns = [
     # Get a list of all users
     path('all-users/', custom_views.UsersListApiView.as_view(),
          name='all-users'),

     # Custom register and activate account views
     path('registration/', custom_views.UserSignUpApiView.as_view(),
          name='register'),

     path('activate/<uuid>/<token>/', custom_views.activate_account,
          name='activate'),

     # Custom password reset and change views
     path('password/reset/',
          custom_views.reset_password,
          name='password_reset'),

     path('password/change/<uuid>/<token>/',
          custom_views.PasswordChangeApiView.as_view(),
          name='password_change',
     ),
     # dj-rest-auth views
     path('dj-rest-auth/login/',
          dj_rest_auth_views.LoginView.as_view(
                  authentication_classes = (),
               ), name='login'),

     path('dj-rest-auth/logout/',
          dj_rest_auth_views.LogoutView.as_view(),
          name='logout'),

     # token obtain views
     path('token/', TokenObtainPairView.as_view(),
          name='token_obtain_pair'),

     path('token/refresh/', TokenRefreshView.as_view(),
         name='token_refresh'),

     # Custom views for profile detail update delete views
     path('profile/<uuid:pk>/',
         custom_views.ProfileDetailUpdateDeleteApiView.as_view(),
         name='profile-detail'),

     # SocialAccount auth
     path('dj-rest-auth/github/', custom_views.GitHubLogin.as_view(),
          name='github_login'),

     path('dj-rest-auth/google/', custom_views.GoogleLogin.as_view(),
          name='google_login'),

     path('dj-rest-auth/facebook/', custom_views.FacebookLogin.as_view(),
          name='fb_login'),
]
</code>```

I started to receive the error after adding the social auth feature from dj-rest-auth third-party app to my django project.

Body:
I wanted to add social media auth endpoints from dj-rest-auth third-party app.
I did everything from the dj-rest-auth documentation.

I am getting this strange error, though:

 File "/home/vlad/projects/DjangoProjects/portfolioProjects/resume_website_restapi/env/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner
    response = get_response(request)
  File "/home/vlad/projects/DjangoProjects/portfolioProjects/resume_website_restapi/env/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/vlad/projects/DjangoProjects/portfolioProjects/resume_website_restapi/env/lib/python3.10/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
    return view_func(*args, **kwargs)
  File "/home/vlad/projects/DjangoProjects/portfolioProjects/resume_website_restapi/env/lib/python3.10/site-packages/django/views/generic/base.py", line 103, in view
    return self.dispatch(request, *args, **kwargs)
  File "/home/vlad/projects/DjangoProjects/portfolioProjects/resume_website_restapi/env/lib/python3.10/site-packages/django/utils/decorators.py", line 46, in _wrapper
    return bound_method(*args, **kwargs)
  File "/home/vlad/projects/DjangoProjects/portfolioProjects/resume_website_restapi/env/lib/python3.10/site-packages/django/views/decorators/debug.py", line 92, in sensitive_post_parameters_wrapper
    return view(request, *args, **kwargs)
  File "/home/vlad/projects/DjangoProjects/portfolioProjects/resume_website_restapi/env/lib/python3.10/site-packages/dj_rest_auth/views.py", line 53, in dispatch
    return super().dispatch(*args, **kwargs)
  File "/home/vlad/projects/DjangoProjects/portfolioProjects/resume_website_restapi/env/lib/python3.10/site-packages/rest_framework/views.py", line 509, in dispatch
    response = self.handle_exception(exc)
  File "/home/vlad/projects/DjangoProjects/portfolioProjects/resume_website_restapi/env/lib/python3.10/site-packages/rest_framework/views.py", line 469, in handle_exception
    self.raise_uncaught_exception(exc)
  File "/home/vlad/projects/DjangoProjects/portfolioProjects/resume_website_restapi/env/lib/python3.10/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception
    raise exc
  File "/home/vlad/projects/DjangoProjects/portfolioProjects/resume_website_restapi/env/lib/python3.10/site-packages/rest_framework/views.py", line 506, in dispatch
    response = handler(request, *args, **kwargs)
  File "/home/vlad/projects/DjangoProjects/portfolioProjects/resume_website_restapi/env/lib/python3.10/site-packages/dj_rest_auth/views.py", line 130, in post
    self.serializer.is_valid(raise_exception=True)
  File "/home/vlad/projects/DjangoProjects/portfolioProjects/resume_website_restapi/env/lib/python3.10/site-packages/rest_framework/serializers.py", line 227, in is_valid
    self._validated_data = self.run_validation(self.initial_data)
  File "/home/vlad/projects/DjangoProjects/portfolioProjects/resume_website_restapi/env/lib/python3.10/site-packages/rest_framework/serializers.py", line 429, in run_validation
    value = self.validate(value)
  File "/home/vlad/projects/DjangoProjects/portfolioProjects/resume_website_restapi/env/lib/python3.10/site-packages/dj_rest_auth/serializers.py", line 121, in validate
    user = self.get_auth_user(username, email, password)
  File "/home/vlad/projects/DjangoProjects/portfolioProjects/resume_website_restapi/env/lib/python3.10/site-packages/dj_rest_auth/serializers.py", line 96, in get_auth_user
    return self.get_auth_user_using_allauth(username, email, password)
  File "/home/vlad/projects/DjangoProjects/portfolioProjects/resume_website_restapi/env/lib/python3.10/site-packages/dj_rest_auth/serializers.py", line 62, in get_auth_user_using_allauth
    return self._validate_email(email, password)
  File "/home/vlad/projects/DjangoProjects/portfolioProjects/resume_website_restapi/env/lib/python3.10/site-packages/dj_rest_auth/serializers.py", line 30, in _validate_email
    user = self.authenticate(email=email, password=password)
  File "/home/vlad/projects/DjangoProjects/portfolioProjects/resume_website_restapi/env/lib/python3.10/site-packages/dj_rest_auth/serializers.py", line 26, in authenticate
    return authenticate(self.context['request'], **kwargs)
  File "/home/vlad/projects/DjangoProjects/portfolioProjects/resume_website_restapi/env/lib/python3.10/site-packages/django/views/decorators/debug.py", line 42, in sensitive_variables_wrapper
    return func(*func_args, **func_kwargs)
  File "/home/vlad/projects/DjangoProjects/portfolioProjects/resume_website_restapi/env/lib/python3.10/site-packages/django/contrib/auth/__init__.py", line 68, in authenticate
    for backend, backend_path in _get_backends(return_tuples=True):
  File "/home/vlad/projects/DjangoProjects/portfolioProjects/resume_website_restapi/env/lib/python3.10/site-packages/django/contrib/auth/__init__.py", line 27, in _get_backends
    backend = load_backend(backend_path)
  File "/home/vlad/projects/DjangoProjects/portfolioProjects/resume_website_restapi/env/lib/python3.10/site-packages/django/contrib/auth/__init__.py", line 21, in load_backend
    return import_string(path)()
TypeError: BaseAuth.__init__() missing 1 required positional argument: 'strategy'

settings.py

"""
Django settings for resume_website_restapi project.

Generated by 'django-admin startproject' using Django 4.1.3.

For more information on this file, see
https://docs.djangoproject.com/en/4.1/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.1/ref/settings/
"""

from pathlib import Path
import os
from datetime import timedelta

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-b#t)ywiymb&@+mv^%j$p&4*y)iq2z-1da*z@beo4s-6-qu9ba%'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

SITE_ID = 2

# Application definition

INSTALLED_APPS = [
    'jazzmin',
    'django.contrib.admin',
    'django.contrib.sites',
    'allauth',
    'allauth.account',
    'allauth.socialaccount',
    'allauth.socialaccount.providers.google',
    'allauth.socialaccount.providers.github',
    'allauth.socialaccount.providers.facebook',

    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'rest_framework.authtoken',
    'dj_rest_auth',
    'django_filters',
    'django_countries',
    'posts.apps.PostsConfig',
    'users.apps.UsersConfig',
    'comments.apps.CommentsConfig',
    'category.apps.CategoryConfig',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'resume_website_restapi.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR / 'templates'],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'resume_website_restapi.wsgi.application'

# Database
# https://docs.djangoproject.com/en/4.1/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}

# Password validation
# https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

REST_FRAMEWORK = {
    # Permissions
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAuthenticatedOrReadOnly',
    ],
    # Authentication
       'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework_simplejwt.authentication.JWTAuthentication',
        'rest_framework.authentication.BasicAuthentication',
        # 'rest_framework.authentication.SessionAuthentication',
    ],
    # django-filters
    'DEFAULT_FILTER_BACKENDS': [
        'django_filters.rest_framework.DjangoFilterBackend',
    ],
    # Pagination
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 3,
}

REST_USE_JWT = True
# JWT_AUTH_RETURN_EXPIRATION = True
# Cookies
JWT_AUTH_COOKIE = 'blog-auth'
JWT_AUTH_REFRESH_COOKIE = 'blog-refresh-token'

# Internationalization
# https://docs.djangoproject.com/en/4.1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.1/howto/static-files/

STATIC_URL = 'static/'
MEDIA_URL = 'media/'

# Default primary key field type
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field

STATIC_ROOT = os.path.join(BASE_DIR, 'static')
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

# Default primary key field type
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

# User model
AUTH_USER_MODEL = "users.Profile"

AUTHENTICATION_BACKENDS = (
"social_core.backends.google.GoogleOAuth2",
"social_core.backends.facebook.FacebookOAuth2",
"social_core.backends.github.GitHubOAuth2",
"allauth.account.auth_backends.AuthenticationBackend",
"django.contrib.auth.backends.ModelBackend",

)

# JWT Auth
SIMPLE_JWT = {
    'ACCESS_TOKEN_LIFETIME': timedelta(days=1),
    'REFRESH_TOKEN_LIFETIME': timedelta(days=1),
    'ROTATE_REFRESH_TOKENS': False,
    'BLACKLIST_AFTER_ROTATION': False,
    'UPDATE_LAST_LOGIN': False,

    'ALGORITHM': 'HS256',
    'SIGNING_KEY': SECRET_KEY,
    'VERIFYING_KEY': None,
    'AUDIENCE': None,
    'ISSUER': None,
    'JWK_URL': None,
    'LEEWAY': 0,

    'AUTH_HEADER_TYPES': ('Bearer',),
    'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION',
    'USER_ID_FIELD': 'id',
    'USER_ID_CLAIM': 'user_id',
    'USER_AUTHENTICATION_RULE': 'rest_framework_simplejwt.authentication.default_user_authentication_rule',

    'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',),
    'TOKEN_TYPE_CLAIM': 'token_type',
    'TOKEN_USER_CLASS': 'rest_framework_simplejwt.models.TokenUser',

    'JTI_CLAIM': 'jti',

    'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp',
    'SLIDING_TOKEN_LIFETIME': timedelta(minutes=5),
    'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1),
}

from django.urls import reverse_lazy

# All auth
LOGIN_URL = reverse_lazy('users:login')
LOGOUT_REDIRECT_URL = reverse_lazy('users:login')
ACCOUNT_EMAIL_VERIFICATION = "mandatory"
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_AUTHENTICATION_METHOD = "email"
ACCOUNT_LOGOUT_ON_PASSWORD_CHANGE = True
ACCOUNT_USERNAME_REQUIRED = False

# SocialAccount Auth
SOCIALACCOUNT_PROVIDERS = {
"github": {
    "APP": {
        "client_id": os.environ.get("GitHub_OAUTH_CLIENT_ID"),
        "secret": os.environ.get("GitHub_OAUTH_SECRET"),
    },
},
"google": {
    "APP": {
        "client_id": os.environ.get("Google_OAUTH_CLIENT_ID"),
        "secret": os.environ.get("Google_OAUTH_SECRET"),
    },
},
}

# Email sending credentials
EMAIL_HOST = 'smtp.mailtrap.io'
EMAIL_HOST_USER = 'a923489850d8ef'
EMAIL_HOST_PASSWORD = 'a47074cae95d6b'
EMAIL_PORT = '2525'

#Custom admin panel with django-jazzmin
JAZZMIN_SETTINGS = {
    "site_title": "Blog",
    "site_header": "your_site_header",
    "site_brand": "Blog",
    "site_icon": "profiles/default.jpg",
    # Add your own branding here
    "site_logo": None,
    "welcome_sign": "Welcome to the Blog",
    # Copyright on the footer
    "copyright": "Blog",
    "user_avatar": "profiles/default.jpg",
    ############
    # Top Menu #
    ############
    # Links to put along the top menu
    "topmenu_links": [
        # Url that gets reversed (Permissions can be added)
        {"name": "Blog", "url": "posts:posts-list", "permissions": ["auth.view_user"]},
        # model admin to link to (Permissions checked against model)
        {"model": "users.Profile"},
    ],
    #############
    # Side Menu #
    #############
    # Whether to display the side menu
    "show_sidebar": True,
    # Whether to aut expand the menu
    "navigation_expanded": True,
    # Custom icons for side menu apps/models See https://fontawesome.com/icons?d=gallery&m=free&v=5.0.0,5.0.1,5.0.10,5.0.11,5.0.12,5.0.13,5.0.2,5.0.3,5.0.4,5.0.5,5.0.6,5.0.7,5.0.8,5.0.9,5.1.0,5.1.1,5.2.0,5.3.0,5.3.1,5.4.0,5.4.1,5.4.2,5.13.0,5.12.0,5.11.2,5.11.1,5.10.0,5.9.0,5.8.2,5.8.1,5.7.2,5.7.1,5.7.0,5.6.3,5.5.0,5.4.2
    # for the full list of 5.13.0 free icon classes
    "icons": {
        "auth": "fas fa-users-cog",
        "auth.user": "fas fa-user",
        "users.User": "fas fa-user",
        "auth.Group": "fas fa-users",
        "admin.LogEntry": "fas fa-file",
    },
    # # Icons that are used when one is not manually specified
    "default_icon_parents": "fas fa-chevron-circle-right",
    "default_icon_children": "fas fa-arrow-circle-right",
    #################
    # Related Modal #
    #################
    # Use modals instead of popups
    "related_modal_active": False,
    #############
    # UI Tweaks #
    #############
    # Relative paths to custom CSS/JS scripts (must be present in static files)
    # Uncomment this line once you create the bootstrap-dark.css file
    "custom_css": "styles/admin.css",
    "custom_js": None,
    # Whether to show the UI customizer on the sidebar
    "show_ui_builder": False,
    ###############
    # Change view #
    ###############
    "changeform_format": "horizontal_tabs",
    # override change forms on a per modeladmin basis
    "changeform_format_overrides": {
        "auth.user": "collapsible",
        "auth.group": "vertical_tabs",
    },
}

JAZZMIN_UI_TWEAKS = {
    "navbar_small_text": False,
    "footer_small_text": False,
    "body_small_text": False,
    "brand_small_text": False,
    "brand_colour": "navbar-success",
    "accent": "accent-teal",
    "navbar": "navbar-dark",
    "no_navbar_border": False,
    "navbar_fixed": False,
    "layout_boxed": False,
    "footer_fixed": False,
    "sidebar_fixed": False,
    "sidebar": "sidebar-dark-info",
    "sidebar_nav_small_text": False,
    "sidebar_disable_expand": False,
    "sidebar_nav_child_indent": False,
    "sidebar_nav_compact_style": False,
    "sidebar_nav_legacy_style": False,
    "sidebar_nav_flat_style": False,
    "theme": "cyborg",
    "dark_mode_theme": None,
    "button_classes": {
        "primary": "btn-primary",
        "secondary": "btn-secondary",
        "info": "btn-info",
        "warning": "btn-warning",
        "danger": "btn-danger",
        "success": "btn-success",
    },
}

views.py

from django.utils.translation import gettext_lazy as _
from django.contrib.auth.tokens import default_token_generator
# Auth
from django.contrib.auth import get_user_model, logout
from allauth.account.utils import logout_on_password_change
# SocialAccount auth
from allauth.socialaccount.providers.facebook.views import FacebookOAuth2Adapter
from allauth.socialaccount.providers.google.views import GoogleOAuth2Adapter
from allauth.socialaccount.providers.github.views import GitHubOAuth2Adapter
from allauth.socialaccount.providers.oauth2.client import OAuth2Client
from dj_rest_auth.registration.views import SocialLoginView

# REST FRAMEWORK
from rest_framework.reverse import reverse, reverse_lazy
from rest_framework.response import Response
from rest_framework import permissions
from rest_framework import status
from rest_framework.decorators import (
                                            api_view,
                                            permission_classes,
                                            authentication_classes,
                                    )
from rest_framework import generics

from .serializers import (
                        UserRegisterSerializer,
                        UserSerializer,
                        PasswordResetSerializer,
                        ChangePasswordSerializer,
                    )

from . import exceptions as custom_exceptions

Profile = get_user_model()

class UserSignUpApiView(generics.CreateAPIView):
    serializer_class = UserRegisterSerializer
    permission_classes = (permissions.AllowAny,)
    authentication_classes = ()

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data, context={'request': request})
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        print(serializer.data)
        return Response(serializer.data, status=status.HTTP_201_CREATED)

class UsersListApiView(generics.ListAPIView):
    serializer_class = UserSerializer
    queryset = Profile.objects.all()

@api_view(['GET', 'POST'])
@permission_classes([permissions.AllowAny,])
def activate_account(request, uuid, token):
    try:
        user = Profile.objects.get(id=uuid)
    except (Profile.DoesNotExist, TypeError, ValueError, OverflowError):
        user = None

    if user is not None and default_token_generator.check_token(user, token):
        user.is_active = True
        user.save()
    else:
        raise custom_exceptions.UserOrTokenNotValid

    return Response(
        {"detail: Activated"},
        status=status.HTTP_200_OK,
        )

@api_view(['POST'])
@permission_classes([permissions.AllowAny,])
def reset_password(request, *args, **kwargs):
    print('kwargs', kwargs)
    serializer = PasswordResetSerializer(
            data=request.data,
            context={'request': request}
    )
    serializer.is_valid(raise_exception=True)

    return Response(
        {"detail": "Sent an confirmation email"},
        status=status.HTTP_302_FOUND,
    )

class PasswordChangeApiView(generics.UpdateAPIView):
    serializer_class = ChangePasswordSerializer
    permission_classes = (permissions.AllowAny,)

    def get_object(self):
        try:
            profile = Profile.objects.get(id=self.kwargs.get('uuid', ''))
        except Profile.DoesNotExist:
            profile = None

        return profile

    def patch(self, request, *args, **kwargs):
        user = self.get_object()
        serializer = self.serializer_class(
                                            instance=user,
                                            data=request.data,
                                            partial=True,
                                            context={'request': self.request},
                                        )
        serializer.is_valid(raise_exception=True)
        self.perform_update(serializer)

        logout_on_password_change(request, user)
        return Response(
            {'detail':'Password changed!'},
            status=status.HTTP_200_OK,
        )

class  ProfileDetailUpdateDeleteApiView(generics.RetrieveUpdateDestroyAPIView):
    serializer_class = UserSerializer

    def get_object(self):
        try:
            profile = Profile.objects.get(id=self.kwargs.get('pk', ''))
        except Profile.DoesNotExist:
            profile = None
        print(self.request.user, self.request.user.is_authenticated)
        print(self.request.user.auth_token)

        return profile

    def destroy(self, request, *args, **kwargs):
        profile = self.get_object()
        if profile is not None:
            self.perform_destroy(profile)
            logout(request)
            return Response(
                {'detail': 'Profile deleted!'},
                status=status.HTTP_200_OK,
            )

        return Response(
                        {'detail': 'Profile does not exist!'},
                        status=status.HTTP_200_OK,
                    )

# the Logout dj-rest-auth view and this one do not work
@api_view(["POST"])
@permission_classes([permissions.IsAuthenticated, ])
def logout_user(request):

    request.user.auth_token.delete()

    logout(request)

    return Response('User Logged out successfully')

# Social account auth

class GitHubLogin(SocialLoginView):
    adapter_class = GitHubOAuth2Adapter
    callback_url = reverse_lazy('posts:posts-list')
    client_class = OAuth2Client

# if you want to use Authorization Code Grant, use this
class GoogleLogin(SocialLoginView):
    adapter_class = GoogleOAuth2Adapter
    callback_url = reverse_lazy('posts:posts-list')
    client_class = OAuth2Client

class FacebookLogin(SocialLoginView):
    adapter_class = FacebookOAuth2Adapter

urls.py

from django.urls import path
from dj_rest_auth import views as dj_rest_auth_views
# DRF
from rest_framework_simplejwt.views import (
    TokenObtainPairView,
    TokenRefreshView,
)
from rest_framework.decorators import authentication_classes

from . import views as custom_views

app_name='users'

urlpatterns = [
     # Get a list of all users
     path('all-users/', custom_views.UsersListApiView.as_view(),
          name='all-users'),

     # Custom register and activate account views
     path('registration/', custom_views.UserSignUpApiView.as_view(),
          name='register'),

     path('activate/<uuid>/<token>/', custom_views.activate_account,
          name='activate'),

     # Custom password reset and change views
     path('password/reset/',
          custom_views.reset_password,
          name='password_reset'),

     path('password/change/<uuid>/<token>/',
          custom_views.PasswordChangeApiView.as_view(),
          name='password_change',
     ),
     # dj-rest-auth views
     path('dj-rest-auth/login/',
          dj_rest_auth_views.LoginView.as_view(
                  authentication_classes = (),
               ), name='login'),

     path('dj-rest-auth/logout/',
          dj_rest_auth_views.LogoutView.as_view(),
          name='logout'),

     # token obtain views
     path('token/', TokenObtainPairView.as_view(),
          name='token_obtain_pair'),

     path('token/refresh/', TokenRefreshView.as_view(),
         name='token_refresh'),

     # Custom views for profile detail update delete views
     path('profile/<uuid:pk>/',
         custom_views.ProfileDetailUpdateDeleteApiView.as_view(),
         name='profile-detail'),

     # SocialAccount auth
     path('dj-rest-auth/github/', custom_views.GitHubLogin.as_view(),
          name='github_login'),

     path('dj-rest-auth/google/', custom_views.GoogleLogin.as_view(),
          name='google_login'),

     path('dj-rest-auth/facebook/', custom_views.FacebookLogin.as_view(),
          name='fb_login'),
]

I started to receive the error after adding the social auth feature from dj-rest-auth third-party app to my django project.


来源: stackexchange

问:
How to get color of an image in js or node.js
I want to get color of some pixels of an image by js or node.js.
How can I do?

I want to find color of every pixels of a png image for choosing pixels with special color in the image

ContentLicense: CC BY-SA 4.0


问:
XMLPullParser - Limit Items
I read an xml.file via XmlPullParser. I can read
the file without any problems.
However, my code continues to write the found
item description until a new item description comes.

this is the file:

```<code><item\>
<title\>....\</title\>
<description\>...\</description\>
<link\>.....\</link\>
<pubDate\>....\</pubDate\>
<guid\>\</guid\>\</item\>
</item\>
<item\>
<title\>....\</title\>
<link\>.....\</link\>
<pubDate\>....\</pubDate\>
<guid\>\</guid\>
</item\>
<item\>
<title\>....\</title\>
<link\>.....\</link\>
<pubDate\>....\</pubDate\>
<guid\>\</guid\>
</item\>
<item\>
<title\>....\</title\>
<description\>...\</description\>
<link\>.....\</link\>
<pubDate\>....\</pubDate\>
<guid\>\</guid\>
</item\>
<item\>
<title\>....\</title\>
<link\>.....\</link\>
<pubDate\>....\</pubDate\>
<guid\>\</guid\>
</item\>
<item\>
<title\>....\</title\>
<description\>...\</description\>
<link\>.....\</link\>
<pubDate\>....\</pubDate\>
<guid\>\</guid\>
</item\>
</code>```

public List<RSSFeed>

```<code>parse() {
    try {

        factory = XmlPullParserFactory.newInstance();
        parser = factory.newPullParser();

        urlStream = downloadUrl(urlString);
        parser.setInput(urlStream, null);
        parser.getInputEncoding();

        int eventType = parser.getEventType();
        boolean done = false;

        rssFeed = new RSSFeed();
        rssFeedList = new ArrayList<RSSFeed>();

        while (eventType != XmlPullParser.END_DOCUMENT && !done) {

            tagName = parser.getName();

            switch (eventType) {
                case XmlPullParser.START_DOCUMENT:
                    break;

                case XmlPullParser.START_TAG:
                    if (tagName.equals(ITEM)) {
                        rssFeed = new RSSFeed();
                    }
                    //if (parser.getName().toString() == null) {
                    //if (tagName.equals(DESCRIPTION) == null) {
                    if (tagName.equals(TITLE)) {
                        title = parser.nextText() + "\r\n";
                        //Log.i("Tag names sind ",tagName);
                    } else if (tagName.equals(DESCRIPTION)) {
                        description = parser.nextText();
                    } else if (tagName.equals(PUBLISHEDDATE)) {
                        pubDate = parser.nextText();
                    } else if (tagName.equals(LINK)) {
                        link = parser.nextText();
                    }

                    Log.i("Tag names sind ", tagName);

                    break;

                case XmlPullParser.END_TAG:
                    if (tagName.equals(CHANNEL)) {
                        done = true;
                    } else if (tagName.equals(ITEM)) {
                        rssFeed = new RSSFeed(
                            replaceUmlaut_Sonderzeichen(title),
                            replaceUmlaut_Sonderzeichen(description),
                            pubDate,
                            link
                        );
                        rssFeedList.add(rssFeed);
                    }
                    break;
            }
            eventType = parser.next();
        }
    } catch (Exception e) {
        e.printStackTrace();
}

return rssFeedList;

}
</code>```

I tried it with

```<code>//if (parser.getName().toString() == null) {
//if (tagName.equals(DESCRIPTION) == null) {
</code>```

but the if - restrictions are unsuccessful

How can I prevent that no description is written where the description item is missing ?
Thanks !

Title: XMLPullParser - Limit Items

Body:
I read an xml.file via XmlPullParser. I can read
the file without any problems.
However, my code continues to write the found
item description until a new item description comes.

this is the file:

<item\>
<title\>....\</title\>
<description\>...\</description\>
<link\>.....\</link\>
<pubDate\>....\</pubDate\>
<guid\>\</guid\>\</item\>
</item\>
<item\>
<title\>....\</title\>
<link\>.....\</link\>
<pubDate\>....\</pubDate\>
<guid\>\</guid\>
</item\>
<item\>
<title\>....\</title\>
<link\>.....\</link\>
<pubDate\>....\</pubDate\>
<guid\>\</guid\>
</item\>
<item\>
<title\>....\</title\>
<description\>...\</description\>
<link\>.....\</link\>
<pubDate\>....\</pubDate\>
<guid\>\</guid\>
</item\>
<item\>
<title\>....\</title\>
<link\>.....\</link\>
<pubDate\>....\</pubDate\>
<guid\>\</guid\>
</item\>
<item\>
<title\>....\</title\>
<description\>...\</description\>
<link\>.....\</link\>
<pubDate\>....\</pubDate\>
<guid\>\</guid\>
</item\>

public List<RSSFeed>

parse() {
    try {

        factory = XmlPullParserFactory.newInstance();
        parser = factory.newPullParser();

        urlStream = downloadUrl(urlString);
        parser.setInput(urlStream, null);
        parser.getInputEncoding();

        int eventType = parser.getEventType();
        boolean done = false;

        rssFeed = new RSSFeed();
        rssFeedList = new ArrayList<RSSFeed>();

        while (eventType != XmlPullParser.END_DOCUMENT && !done) {

            tagName = parser.getName();

            switch (eventType) {
                case XmlPullParser.START_DOCUMENT:
                    break;

                case XmlPullParser.START_TAG:
                    if (tagName.equals(ITEM)) {
                        rssFeed = new RSSFeed();
                    }
                    //if (parser.getName().toString() == null) {
                    //if (tagName.equals(DESCRIPTION) == null) {
                    if (tagName.equals(TITLE)) {
                        title = parser.nextText() + "\r\n";
                        //Log.i("Tag names sind ",tagName);
                    } else if (tagName.equals(DESCRIPTION)) {
                        description = parser.nextText();
                    } else if (tagName.equals(PUBLISHEDDATE)) {
                        pubDate = parser.nextText();
                    } else if (tagName.equals(LINK)) {
                        link = parser.nextText();
                    }

                    Log.i("Tag names sind ", tagName);

                    break;

                case XmlPullParser.END_TAG:
                    if (tagName.equals(CHANNEL)) {
                        done = true;
                    } else if (tagName.equals(ITEM)) {
                        rssFeed = new RSSFeed(
                            replaceUmlaut_Sonderzeichen(title),
                            replaceUmlaut_Sonderzeichen(description),
                            pubDate,
                            link
                        );
                        rssFeedList.add(rssFeed);
                    }
                    break;
            }
            eventType = parser.next();
        }
    } catch (Exception e) {
        e.printStackTrace();
}

return rssFeedList;

}

I tried it with

//if (parser.getName().toString() == null) {
//if (tagName.equals(DESCRIPTION) == null) {

but the if - restrictions are unsuccessful

How can I prevent that no description is written where the description item is missing ?
Thanks !


问:
How to set UTF-8 encoding without BOM for CStdioFileEx?
I try to read a file via MFC:

```<code>CString string;
CStdioFileEx gameFile;
bool have_file = false;
if (PathFileExists(filePathsAndNames[i].first + L"\\main.lua"))
{
    gameFile.Open(filePathsAndNames[i].first + L"\\main.lua", CFile::modeRead);
    have_file = true;
}
else if (PathFileExists(filePathsAndNames[i].first + L"\\main3.lua"))
{
    gameFile.Open(filePathsAndNames[i].first + L"\\main3.lua", CFile::modeRead);
    have_file = true;
}
if (have_file)
{
    gameFile.SetCodePage(CP_UTF8);
    CString game_name;
    CString game_name_en;
    CString game_author;
    CString game_version;
    const int MAX_STR_CNT = 5; //не больше этого количества строк от начала
    int curr_str = 0;
    while (gameFile.ReadString(string)) {
        ...
    }
}
</code>```

When a file has UTF-8 encoding without a BOM, the readString() method skips near two, three characters in the first line. When the file has UTF-8 encoding with a BOM, all is ok.

How can I fix it?

Is it an issue which I should report to Microsoft? If yes, how can I do it?

Body:
I try to read a file via MFC:

CString string;
CStdioFileEx gameFile;
bool have_file = false;
if (PathFileExists(filePathsAndNames[i].first + L"\\main.lua"))
{
    gameFile.Open(filePathsAndNames[i].first + L"\\main.lua", CFile::modeRead);
    have_file = true;
}
else if (PathFileExists(filePathsAndNames[i].first + L"\\main3.lua"))
{
    gameFile.Open(filePathsAndNames[i].first + L"\\main3.lua", CFile::modeRead);
    have_file = true;
}
if (have_file)
{
    gameFile.SetCodePage(CP_UTF8);
    CString game_name;
    CString game_name_en;
    CString game_author;
    CString game_version;
    const int MAX_STR_CNT = 5; //не больше этого количества строк от начала
    int curr_str = 0;
    while (gameFile.ReadString(string)) {
        ...
    }
}

When a file has UTF-8 encoding without a BOM, the readString() method skips near two, three characters in the first line. When the file has UTF-8 encoding with a BOM, all is ok.

How can I fix it?

Is it an issue which I should report to Microsoft? If yes, how can I do it?


问:
HTTP web server cgi processing
I'm writing simple HTTP webserver in c++ for my college project and I want it to have CGI, so I can write some script in PHP or Perl. The question is: how to understand if I should call cgi program and grab its output, or simply give html page as response to a client. Only by a requested file's extension? I see no other options</p>

Title: HTTP web server cgi processing


问:
Return identifier of conflicted insert in postgres
I want to insert rows into a table and return the identifier of the inserted row. Whenever a unique contraint is conflicted, I still want to return the identifier.

I ran the following query:

```<code>insert into operations.my_table (domain, email)
VALUES ('my_domain', 'email@my_domain')
ON CONFLICT do nothing
returning my_table_id
</code>```

However, it does not return anything on conflict.

Body:
I want to insert rows into a table and return the identifier of the inserted row. Whenever a unique contraint is conflicted, I still want to return the identifier.

I ran the following query:

insert into operations.my_table (domain, email)
VALUES ('my_domain', 'email@my_domain')
ON CONFLICT do nothing
returning my_table_id

However, it does not return anything on conflict.


问:
SassError: unidentified variable $carbon--theme--g100;
Im following a tutorial for a portfolio react app, and I'm having trouble with the carbon theme compliling so I can run it.

I tried using different themes, such as g90 and g10, but it's still the same error. I also looked into my layout, and there isn't any typos that I can see so far. Here is my GitHub https://github.com/Maxdj2k/portfolio-create-react-app

the error occurs in src/index.scss


问:
Installed and Portable version of a software on windows 11
Hello and happy new year.

I have a problem with my software. I've installed Visual Studio Code on my windows 11 and commonly I've installed some extensions on it.
also I have my Portable VS Code on an USB flash, but here's my problem. when I plug in my USB into my pc and open the VS Code, I don't know why windows open the installed version,  because I want to install some extensions on the portable VS Code manually but I can't because of this problem,so is there a way to solve it?


问:
Prototypal inheritance between constructor functions
So, I have 2 constructor functions, Person (which is parent) and Student (which is child of parent).
I'm trying to implement inheritance between these constructor functions and everything is working correctly instead of one thing which breaks my logic.

This is my implementation:

```<code>//Parent
const Person = function (this: PersonI, firstName: string, birthYear: number) {
    this.firstName = firstName;
    this.birthYear = birthYear;
}

Person.prototype.calcAge = function () {
    console.log(2040 - this.birthYear);
}

//Child
const Student = function (this: StudentI, firstName: string, birthYear: number, course: string) {
    Person.call(this, firstName, birthYear);
    this.course = course;
}

//Inheritance
Object.setPrototypeOf(Student.prototype, Person.prototype)

Student.prototype.introduce = function () {
    console.log(`My name is ${this.firstName} and I study ${this.course}`);
}

const mike = new (Student as any)('Mike', 2020, 'CS');
console.log(mike);
</code>```

And as a result in console I'm getting:

Methods are set perfeclty in place,
BUT why 'Person' is shown in marked place at screenshot instead of 'Student'?

Body:
So, I have 2 constructor functions, Person (which is parent) and Student (which is child of parent).
I'm trying to implement inheritance between these constructor functions and everything is working correctly instead of one thing which breaks my logic.

This is my implementation:

//Parent
const Person = function (this: PersonI, firstName: string, birthYear: number) {
    this.firstName = firstName;
    this.birthYear = birthYear;
}

Person.prototype.calcAge = function () {
    console.log(2040 - this.birthYear);
}

//Child
const Student = function (this: StudentI, firstName: string, birthYear: number, course: string) {
    Person.call(this, firstName, birthYear);
    this.course = course;
}

//Inheritance
Object.setPrototypeOf(Student.prototype, Person.prototype)

Student.prototype.introduce = function () {
    console.log(`My name is ${this.firstName} and I study ${this.course}`);
}

const mike = new (Student as any)('Mike', 2020, 'CS');
console.log(mike);

And as a result in console I'm getting:

Methods are set perfeclty in place,
BUT why 'Person' is shown in marked place at screenshot instead of 'Student'?


问:
After login can redirect when on localhost, but can't redirect when already deployed
I can't redirect to index.php page after login.

This happens on the website that I have deployed, but it doesn't happen on localhost (Can redirect to index.php).

I deploy website to Microsoft Azure and deploy database to freemysqlhosting.net(free).

I have tried the solutions here and here, but still can't redirect.

And here's the code login.php:

```<code><!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>
    <title>Variant'C - Your Covid Solutions</title>
    <link rel="icon" href="../images/logo.ico" type="image/x-icon">
    <link rel="stylesheet" href="style.css"/>
</head>
<body>
<?php
    require('db.php');
    session_start();
    // When form submitted, check and create user session.
    if (isset($_POST['username'])) {
        $username = stripslashes($_REQUEST['username']);    // removes backslashes
        $username = mysqli_real_escape_string($con, $username);
        $password = stripslashes($_REQUEST['password']);
        $password = mysqli_real_escape_string($con, $password);
        // Check user is exist in the database
        $query    = "SELECT * FROM `users` WHERE username='$username'
                     AND password='" . md5($password) . "'";
        $result = mysqli_query($con, $query) or die(mysql_error());
        $rows = mysqli_num_rows($result);
        if ($rows == 1) {
            $_SESSION['username'] = $username;
            // Redirect to user dashboard page
            header("Location: index.php");
        } else {
            echo "<div class='form'>
                  <h3>Incorrect Username/password.</h3><br/>
                  <p class='link'>Click here to <a href='login.php'>Login</a> again.</p>
                  </div>";
        }
    } else {
?>
    <form class="form" method="post" name="login">
        <h1 class="login-title">Login</h1>
        <input type="text" class="login-input" name="username" placeholder="Username" autofocus="true"/>
        <input type="password" class="login-input" name="password" placeholder="Password"/>
        <input type="submit" value="Login" name="submit" class="login-button"/>
        <p class="link"><a href="registration.php">New Registration</a></p>
  </form>
<?php
    }
?>
</body>
</html>
</code>```

What's wrong? Is it the code or is it from the deployment?

Thank you in advance :)

Body:
I can't redirect to index.php page after login.

This happens on the website that I have deployed, but it doesn't happen on localhost (Can redirect to index.php).

I deploy website to Microsoft Azure and deploy database to freemysqlhosting.net(free).

I have tried the solutions here and here, but still can't redirect.

And here's the code login.php:

<!DOCTYPE html>

    <meta charset="utf-8"/>
    <title>Variant'C - Your Covid Solutions</title>
    <link rel="icon" href="../images/logo.ico" type="image/x-icon">
    <link rel="stylesheet" href="style.css"/>

<?php
    require('db.php');
    session_start();
    // When form submitted, check and create user session.
    if (isset($_POST['username'])) {
        $username = stripslashes($_REQUEST['username']);    // removes backslashes
        $username = mysqli_real_escape_string($con, $username);
        $password = stripslashes($_REQUEST['password']);
        $password = mysqli_real_escape_string($con, $password);
        // Check user is exist in the database
        $query    = "SELECT * FROM `users` WHERE username='$username'
                     AND password='" . md5($password) . "'";
        $result = mysqli_query($con, $query) or die(mysql_error());
        $rows = mysqli_num_rows($result);
        if ($rows == 1) {
            $_SESSION['username'] = $username;
            // Redirect to user dashboard page
            header("Location: index.php");
        } else {
            echo "

Incorrect Username/password.

Click here to Login again.

";
        }
    } else {
?>
    <form class="form" method="post" name="login">

Login

        <input type="text" class="login-input" name="username" placeholder="Username" autofocus="true"/>
        <input type="password" class="login-input" name="password" placeholder="Password"/>
        <input type="submit" value="Login" name="submit" class="login-button"/>

New Registration

  </form>
<?php
    }
?>

What's wrong? Is it the code or is it from the deployment?

Thank you in advance :)


问:
Cannot invoke "javax.persistence.EntityManagerFactory.createEntityManager()" because "this.entityManagerFactory" is null
I am getting NullPointerException for the following piece of code:

```<code>@SpringBootApplication
public class SpringBootJpaExampleApplication {

   @PersistenceUnit
   private EntityManagerFactory entityManagerFactory;

   public static void main(String[] args) {
      SpringApplication.run(SpringBootJpaExampleApplication.class, args);
   }

   @PostConstruct
   public void start(){
      Employee e = new Employee();
      e.setDob(new Date());

      EntityManager entityManager = entityManagerFactory.createEntityManager();
      EntityTransaction transaction = entityManager.getTransaction();
      transaction.begin();
      entityManager.persist(e);
      transaction.commit();
      entityManager.close();
   }
}
</code>```

I am trying to create Employee table in MySQL through Spring Boot but getting null pointer exception. I am out of ideas regarding the fix. Kindly help !!!

```<code>com.javabrains.SpringBootJPAExample.SpringBootJpaExampleApplication.main(SpringBootJpaExampleApplication.java:19) ~[classes/:na]
Caused by: java.lang.NullPointerException: Cannot invoke "javax.persistence.EntityManagerFactory.createEntityManager()" because "this.entityManagerFactory" is null
    at com.javabrains.SpringBootJPAExample.SpringBootJpaExampleApplication.start(SpringBootJpaExampleApplication.java:28) ~[classes/:na]
    at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:104) ~[na:na]
    at java.base/java.lang.reflect.Method.invoke(Method.java:577) ~[na:na]
    at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleElement.invoke(InitDestroyAnnotationBeanPostProcessor.java:424) ~[spring-beans-6.0.3.jar:6.0.3]
    at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleMetadata.invokeInitMethods(InitDestroyAnnotationBeanPostProcessor.java:368) ~[spring-beans-6.0.3.jar:6.0.3]
    at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:192) ~[spring-beans-6.0.3.jar:6.0.3]
    ... 17 common frames omitted

Process finished with exit code 1

</code>```

Body:
I am getting NullPointerException for the following piece of code:

@SpringBootApplication
public class SpringBootJpaExampleApplication {

   @PersistenceUnit
   private EntityManagerFactory entityManagerFactory;

   public static void main(String[] args) {
      SpringApplication.run(SpringBootJpaExampleApplication.class, args);
   }

   @PostConstruct
   public void start(){
      Employee e = new Employee();
      e.setDob(new Date());

      EntityManager entityManager = entityManagerFactory.createEntityManager();
      EntityTransaction transaction = entityManager.getTransaction();
      transaction.begin();
      entityManager.persist(e);
      transaction.commit();
      entityManager.close();
   }
}

I am trying to create Employee table in MySQL through Spring Boot but getting null pointer exception. I am out of ideas regarding the fix. Kindly help !!!

com.javabrains.SpringBootJPAExample.SpringBootJpaExampleApplication.main(SpringBootJpaExampleApplication.java:19) ~[classes/:na]
Caused by: java.lang.NullPointerException: Cannot invoke "javax.persistence.EntityManagerFactory.createEntityManager()" because "this.entityManagerFactory" is null
    at com.javabrains.SpringBootJPAExample.SpringBootJpaExampleApplication.start(SpringBootJpaExampleApplication.java:28) ~[classes/:na]
    at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:104) ~[na:na]
    at java.base/java.lang.reflect.Method.invoke(Method.java:577) ~[na:na]
    at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleElement.invoke(InitDestroyAnnotationBeanPostProcessor.java:424) ~[spring-beans-6.0.3.jar:6.0.3]
    at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleMetadata.invokeInitMethods(InitDestroyAnnotationBeanPostProcessor.java:368) ~[spring-beans-6.0.3.jar:6.0.3]
    at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:192) ~[spring-beans-6.0.3.jar:6.0.3]
    ... 17 common frames omitted

Process finished with exit code 1


问:
TrueNAS Authentication using session token
I'm in the process of writing a series of Ansible tasks for TrueNAS-SCALE-22.12.0.  The plan was to use a session token for each playbook to authenticate.

There is an api endpoint auth/generate_token which will return what looks like a session token when accessed using a basic authentication (user:password).

I've used both Ansible and Postman to test a dozen or so authentication approaches using the token that is generated, and each results in 401: Unauthorized errors.  I've even tried variations of base 64 encoding (just in case).

It is possible to use the basic authentication to generate a user api token, which then can be used as a bearer token in subsequent requests.  So my question is not so much about how to achieve my automation goal, but rather to understand what the auth/generate_token endpoint is for and how to use it.

Here is some background and here are the docs.  Not really clear to me.

Edit:

Here's an example of the session token returned by the auth/generate_token endpoint:

bYYJSTw8U3kZg5QxIyKgeLgPWIQtVKhu0FoGq3oSYWE7kQFCkNxeHWw7zcZbGPvH


问:
"425 Unable to build data connection" when attempting to download files from a FTPS server using .Net with TLS 1.3
I'm attempting to download files from an FTPS server using the functionality provided by System.Net (.Net Framework 4.8). I'm using the following code:

```<code>var serverUri = new System.Uri("ftp://my.ftp.server.com/directory/");
var request = (System.Net.FtpWebRequest)System.Net.WebRequest.Create(serverUri);
request.Method = System.Net.WebRequestMethods.Ftp.ListDirectory;
request.Credentials = new System.Net.NetworkCredential("username", "password");
request.KeepAlive = true;
request.UseBinary = true;
request.EnableSsl = true;
request.UsePassive = true;

System.Net.ServicePoint sp = request.ServicePoint;
sp.ConnectionLimit = 1;
var response = (System.Net.FtpWebResponse)request.GetResponse();
System.IO.StreamReader readStream = null;

try
{
    using (Stream responseStream = response.GetResponseStream())
    {
        readStream = new System.IO.StreamReader(responseStream, System.Text.Encoding.UTF8);

        if (readStream != null)
        {
            string directoryListing = readStream.ReadToEnd(); // <-- Fails here!
            // Process directory listing...
        }

        readStream.Close();
    }
}
catch (Exception ex)
{
    Console.WriteLine($"### ERROR ### {ex.Message}");
    Console.WriteLine($"### ERROR ### [{response.StatusCode}] {response.StatusDescription}");
}
finally
{
    if (readStream != null)
        readStream.Close();

    if (response != null)
        response.Close();
}

</code>```

Unfortunately the code fails most of the time at the line: string directoryListing = readStream.ReadToEnd();. Most of the time means, around one out of between 5-20 (sometimes more) consecutive attempts (roughly every second) succeeds delivering the desired result. Thus far I haven't been able to find any rule (timeout, etc.) for when it succeeds. The output of the catch block is:

```<code>### ERROR ### The remote server returned an error: (425) Can't open data connection.
### ERROR ### [CantOpenData] 425 Unable to build data connection: TLS session of data connection not resumed.
</code>```

Setting EnableSsl = false results in the error: (503) Bad sequence of commands.

Setting UsePassive = false results in failing to establish a connection (timeout occurs).

Setting KeepAlive = false or UseBinary = false doesn't change anything.

What does work is setting the TLS version the client uses to 1.2:

```<code>System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
</code>```

...just before the line response = (FtpWebResponse)request.GetResponse();.
According to (https://learn.microsoft.com/en-us/windows/win32/secauthn/protocols-in-tls-ssl--schannel-ssp-#tls-protocol-version-support) TLS 1.3 should be functional on Windows 11 (which I'm using).

The server I'm trying to communicate with:

```<code>FileZilla Pro Enterprise Server 1.6.3
Please visit https://filezilla-project.org/
</code>```

The error message above indicates that I should be storing session data and reusing it, yet I haven't found any information on how I can access session data through the functionality provided within System.Net.

So my question: is the implemention of .Net's communication layer using TLS 1.3 faulty/incomplete or am I doing something wrong? In the latter case, how can I fix my code to use TLS 1.3 (wihtout using 3rd party components)? Any help greatly appreciated!

Body:
I'm attempting to download files from an FTPS server using the functionality provided by System.Net (.Net Framework 4.8). I'm using the following code:

var serverUri = new System.Uri("ftp://my.ftp.server.com/directory/");
var request = (System.Net.FtpWebRequest)System.Net.WebRequest.Create(serverUri);
request.Method = System.Net.WebRequestMethods.Ftp.ListDirectory;
request.Credentials = new System.Net.NetworkCredential("username", "password");
request.KeepAlive = true;
request.UseBinary = true;
request.EnableSsl = true;
request.UsePassive = true;

System.Net.ServicePoint sp = request.ServicePoint;
sp.ConnectionLimit = 1;
var response = (System.Net.FtpWebResponse)request.GetResponse();
System.IO.StreamReader readStream = null;

try
{
    using (Stream responseStream = response.GetResponseStream())
    {
        readStream = new System.IO.StreamReader(responseStream, System.Text.Encoding.UTF8);

        if (readStream != null)
        {
            string directoryListing = readStream.ReadToEnd(); // <-- Fails here!
            // Process directory listing...
        }

        readStream.Close();
    }
}
catch (Exception ex)
{
    Console.WriteLine($"### ERROR ### {ex.Message}");
    Console.WriteLine($"### ERROR ### [{response.StatusCode}] {response.StatusDescription}");
}
finally
{
    if (readStream != null)
        readStream.Close();

    if (response != null)
        response.Close();
}

Unfortunately the code fails most of the time at the line: string directoryListing = readStream.ReadToEnd();. Most of the time means, around one out of between 5-20 (sometimes more) consecutive attempts (roughly every second) succeeds delivering the desired result. Thus far I haven't been able to find any rule (timeout, etc.) for when it succeeds. The output of the catch block is:

### ERROR ### The remote server returned an error: (425) Can't open data connection.
### ERROR ### [CantOpenData] 425 Unable to build data connection: TLS session of data connection not resumed.

Setting EnableSsl = false results in the error: (503) Bad sequence of commands.

Setting UsePassive = false results in failing to establish a connection (timeout occurs).

Setting KeepAlive = false or UseBinary = false doesn't change anything.

What does work is setting the TLS version the client uses to 1.2:

System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

...just before the line response = (FtpWebResponse)request.GetResponse();.
According to (https://learn.microsoft.com/en-us/windows/win32/secauthn/protocols-in-tls-ssl--schannel-ssp-#tls-protocol-version-support) TLS 1.3 should be functional on Windows 11 (which I'm using).

The server I'm trying to communicate with:

FileZilla Pro Enterprise Server 1.6.3
Please visit https://filezilla-project.org/

The error message above indicates that I should be storing session data and reusing it, yet I haven't found any information on how I can access session data through the functionality provided within System.Net.

So my question: is the implemention of .Net's communication layer using TLS 1.3 faulty/incomplete or am I doing something wrong? In the latter case, how can I fix my code to use TLS 1.3 (wihtout using 3rd party components)? Any help greatly appreciated!


问:
Can anyone explain me how to work with images in matplotlib?
I wanted to make a chess game in python, but then I saw that you can do a lot of amazing things in matplotlib in terms of designing. I know that this is probably not the best way of doing this but I want to try this. Here is my main question.
How to scale and position images in matplotlib and tell me a bit more about it if possible?

This is what I have at this point:

```<code>import matplotlib.pyplot as plt

im = plt.imread('C:\\...\\bb.png')
imgplot = plt.imshow(im)
plt.show()
</code>```

This just displays the image, I cant realy scale it nor position it.

I also found something like this, it displays the image in the right corner but I can't change anything or it just disappears or nothing happens... In short only misery.

```<code>newax = fig.add_axes([0.6,0.8,0.2,0.2], anchor='NE', zorder=1,)
newax.imshow(im)
newax.axis('off')    #If I remove this there is a frame
</code>```

Please help me out.

Body:
I wanted to make a chess game in python, but then I saw that you can do a lot of amazing things in matplotlib in terms of designing. I know that this is probably not the best way of doing this but I want to try this. Here is my main question.
How to scale and position images in matplotlib and tell me a bit more about it if possible?

This is what I have at this point:

import matplotlib.pyplot as plt

im = plt.imread('C:\\...\\bb.png')
imgplot = plt.imshow(im)
plt.show()

This just displays the image, I cant realy scale it nor position it.

I also found something like this, it displays the image in the right corner but I can't change anything or it just disappears or nothing happens... In short only misery.

newax = fig.add_axes([0.6,0.8,0.2,0.2], anchor='NE', zorder=1,)
newax.imshow(im)
newax.axis('off')    #If I remove this there is a frame

Please help me out.


问:
Error when running an application based on SQL Server in a Docker container
I am new to docker and I encountered the following problem: I want to run an app (that internally uses sql server) in a container, but I get the following error:

Could not run migrations. Reason: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: TCP Provider, error: 40 - Could not open a connection to SQL Server: Could not open a connection to SQL Server)

I tried to install sql server on my laptop and enable tcp just in case, but as far as I know, when running the app in a container, I shoulden't install the dependencies on my laptop.

I mention that for running the app inside docker I use the following commands:

```<code>docker build -t identity_web_api .

docker-compose up
</code>```

The Docker compose file:

```<code>version: "3.9"
services:
  web_api:
    image: identity_web_api
    container_name: identity_web_api
    ports:
      - "5000:80"
  sql:
    image: "mcr.microsoft.com/mssql/server:2022-latest"
    container_name: identity_sql_server
    ports: # not actually needed, because the two services are on the same network
      - "1433:1433"
    environment:
      - ACCEPT_EULA=y
      - SA_PASSWORD=SomePass!234
</code>```

Body:
I am new to docker and I encountered the following problem: I want to run an app (that internally uses sql server) in a container, but I get the following error:

Could not run migrations. Reason: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: TCP Provider, error: 40 - Could not open a connection to SQL Server: Could not open a connection to SQL Server)

I tried to install sql server on my laptop and enable tcp just in case, but as far as I know, when running the app in a container, I shoulden't install the dependencies on my laptop.

I mention that for running the app inside docker I use the following commands:

docker build -t identity_web_api .

docker-compose up

The Docker compose file:

version: "3.9"
services:
  web_api:
    image: identity_web_api
    container_name: identity_web_api
    ports:
      - "5000:80"
  sql:
    image: "mcr.microsoft.com/mssql/server:2022-latest"
    container_name: identity_sql_server
    ports: # not actually needed, because the two services are on the same network
      - "1433:1433"
    environment:
      - ACCEPT_EULA=y
      - SA_PASSWORD=SomePass!234


问:
How can I remove a key from a Python dictionary?
In my python program I am getting this error:

```<code>KeyError('followers')
</code>```

From this code :

```<code>for u in r["followers"]:
with open(r'data.csv', 'a', encoding="utf-8") as f:
writer = csv.writer(f)
row = {}
for x in fieldnames:
    if x in u and u[x]:
        row[x] = str(u[x])
        if x == "uid":
            row[x] = str(u[x]) + ''

            writer = csv.DictWriter(
                f, fieldnames=fieldnames, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
            writer.writerow(row)
</code>```

Can anyone please explain why this is happening?

Body:
In my python program I am getting this error:

KeyError('followers')

From this code :

for u in r["followers"]:
with open(r'data.csv', 'a', encoding="utf-8") as f:
writer = csv.writer(f)
row = {}
for x in fieldnames:
    if x in u and u[x]:
        row[x] = str(u[x])
        if x == "uid":
            row[x] = str(u[x]) + ''

            writer = csv.DictWriter(
                f, fieldnames=fieldnames, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
            writer.writerow(row)

Can anyone please explain why this is happening?


问:
Process crash when repeatly call NodeJS native module
I want to changes the parent window of the specified child window by calling native modules in NodeJS16.(electron 22.)

CPP code:

```<code>#include <napi.h>
#include <windows.h>
#include <winuser.h>

using namespace Napi;

class ContextData
{
private:
    HWND hWnd_;
    LPDWORD lpdwProcessId_;
    Function &cb_;

public:
    ContextData(Function &cb, HWND hWnd, LPDWORD lpdwProcessId) : cb_(cb), hWnd_(hWnd), lpdwProcessId_(lpdwProcessId) {}
    HWND hWnd()
    {
        return hWnd_;
    }
    LPDWORD lpdwProcessId()
    {
        return lpdwProcessId_;
    }
    Function &cb()
    {
        return cb_;
    }
    static BOOL CALLBACK EnumChildProc(HWND hWnd, LPARAM callbackLParam)
    {
        ContextData *lParam = (ContextData *)callbackLParam;

        LPDWORD pid;
        GetWindowThreadProcessId(hWnd, (LPDWORD)pid);

        uint32_t childWindowPid = *(uint32_t *)pid;
        printf("childWindowPid is: %d\n", childWindowPid);

        uint32_t targetWindowPid = *(uint32_t *)(lParam->lpdwProcessId());
        printf("targetWindowPid is: %d\n", targetWindowPid);

        if (childWindowPid == targetWindowPid)
        {
            printf("find successfully\n");
            SetParent(hWnd, lParam->hWnd());
            (lParam->cb()).Call({});
            return FALSE;
        }

        return TRUE;
    }
};

static void Method(const CallbackInfo &info)
{
    Env env = info.Env();

    if (info.Length() < 3)
    {
        TypeError::New(env, "Wrong number of arguments")
            .ThrowAsJavaScriptException();
        return;
    }

    if (!info[0].IsBuffer())
    {
        TypeError::New(env, "hwnd must be buffer")
            .ThrowAsJavaScriptException();
        return;
    }

    if (!info[1].IsNumber())
    {
        TypeError::New(env, "pid must be number")
            .ThrowAsJavaScriptException();
        return;
    }

    if (!info[2].IsFunction())
    {
        TypeError::New(env, "cb must be function")
            .ThrowAsJavaScriptException();
        return;
    }

    // parent window's hWnd
    Buffer<void *> handle = info[0].As<Buffer<void *>>();
    HWND hWnd = static_cast<HWND>(*reinterpret_cast<void **>(handle.Data()));

    // child process identifier
    uint32_t pid = info[1].As<Number>().Uint32Value();
    LPDWORD lpdwProcessId = reinterpret_cast<LPDWORD>(&pid);

    // callback
    Function cb = info[2].As<Function>();
    ContextData context(cb, hWnd, lpdwProcessId);

    EnumChildWindows(hWnd, ContextData::EnumChildProc, (LPARAM)(&context));
    return;
}

Object Init(Env env, Object exports)
{
    exports.Set(String::New(env, "SetParentNapi"),
                Function::New(env, Method));
    return exports;
}

NODE_API_MODULE(addon, Init)

</code>```

JS code:

  const controller = new AbortController()

  try {
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    for await (const _value of setInterval(5000, undefined, {
      signal: controller.signal,
    })) {
      SetParentNapi(buffer, pid, () => {
        log4js.info('SetParent success！')
        controller.abort()
      })
    }
  } catch (error) {
    if (controller.signal.aborted) {
      log4js.debug('timeout aborted！')
      return
    }

    log4js.error(error)
  }
```
<p>If <code>SetParentNapi</code> executes ok, it would print out message like following:</p>
```childWindowPid is: 6872
targetWindowPid is: 8324
childWindowPid is: 8324
targetWindowPid is: 8324
find successfully
```
<p>Every seems ok, but if I try to comment out the following code in JS,</p>
```controller.abort()
```
<p>to force calling native modules repeatedly, the app crash.</p>
```[20464:1231/223445.713:ERROR:crashpad_client_win.cc(844)] not connected

Process finished with exit code -36861

```

Why it happened, how can I fix it?

Body:
I want to changes the parent window of the specified child window by calling native modules in NodeJS16.(electron 22.)

CPP code:

#include <napi.h>
#include <windows.h>
#include <winuser.h>

using namespace Napi;

class ContextData
{
private:
    HWND hWnd_;
    LPDWORD lpdwProcessId_;
    Function &cb_;

public:
    ContextData(Function &cb, HWND hWnd, LPDWORD lpdwProcessId) : cb_(cb), hWnd_(hWnd), lpdwProcessId_(lpdwProcessId) {}
    HWND hWnd()
    {
        return hWnd_;
    }
    LPDWORD lpdwProcessId()
    {
        return lpdwProcessId_;
    }
    Function &cb()
    {
        return cb_;
    }
    static BOOL CALLBACK EnumChildProc(HWND hWnd, LPARAM callbackLParam)
    {
        ContextData *lParam = (ContextData *)callbackLParam;

        LPDWORD pid;
        GetWindowThreadProcessId(hWnd, (LPDWORD)pid);

        uint32_t childWindowPid = *(uint32_t *)pid;
        printf("childWindowPid is: %d\n", childWindowPid);

        uint32_t targetWindowPid = *(uint32_t *)(lParam->lpdwProcessId());
        printf("targetWindowPid is: %d\n", targetWindowPid);

        if (childWindowPid == targetWindowPid)
        {
            printf("find successfully\n");
            SetParent(hWnd, lParam->hWnd());
            (lParam->cb()).Call({});
            return FALSE;
        }

        return TRUE;
    }
};

static void Method(const CallbackInfo &info)
{
    Env env = info.Env();

    if (info.Length() < 3)
    {
        TypeError::New(env, "Wrong number of arguments")
            .ThrowAsJavaScriptException();
        return;
    }

    if (!info[0].IsBuffer())
    {
        TypeError::New(env, "hwnd must be buffer")
            .ThrowAsJavaScriptException();
        return;
    }

    if (!info[1].IsNumber())
    {
        TypeError::New(env, "pid must be number")
            .ThrowAsJavaScriptException();
        return;
    }

    if (!info[2].IsFunction())
    {
        TypeError::New(env, "cb must be function")
            .ThrowAsJavaScriptException();
        return;
    }

    // parent window's hWnd
    Buffer<void *> handle = info[0].As<Buffer<void *>>();
    HWND hWnd = static_cast<HWND>(*reinterpret_cast<void **>(handle.Data()));

    // child process identifier
    uint32_t pid = info[1].As<Number>().Uint32Value();
    LPDWORD lpdwProcessId = reinterpret_cast<LPDWORD>(&pid);

    // callback
    Function cb = info[2].As<Function>();
    ContextData context(cb, hWnd, lpdwProcessId);

    EnumChildWindows(hWnd, ContextData::EnumChildProc, (LPARAM)(&context));
    return;
}

Object Init(Env env, Object exports)
{
    exports.Set(String::New(env, "SetParentNapi"),
                Function::New(env, Method));
    return exports;
}

NODE_API_MODULE(addon, Init)

JS code:

  const controller = new AbortController()

  try {
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    for await (const _value of setInterval(5000, undefined, {
      signal: controller.signal,
    })) {
      SetParentNapi(buffer, pid, () => {
        log4js.info('SetParent success！')
        controller.abort()
      })
    }
  } catch (error) {
    if (controller.signal.aborted) {
      log4js.debug('timeout aborted！')
      return
    }

    log4js.error(error)
  }

If SetParentNapi executes ok, it would print out message like following:

childWindowPid is: 6872
targetWindowPid is: 8324
childWindowPid is: 8324
targetWindowPid is: 8324
find successfully

Every seems ok, but if I try to comment out the following code in JS,

controller.abort()

to force calling native modules repeatedly, the app crash.

[20464:1231/223445.713:ERROR:crashpad_client_win.cc(844)] not connected

Process finished with exit code -36861

Why it happened, how can I fix it?


问:
LWJGL3 Visual artifacts caused by different projections
I have a very simple glsl vertex shader, which is the following:

```<code>#version 430

in vec2 vertices;
in vec2 textures;

out vec2 tex_coords;

uniform mat4 projection;
uniform mat4 texModifier;

void main() {
    tex_coords = (texModifier * vec4(textures,0,1)).xy;
    gl_Position = projection * vec4(vertices, 0, 1);
}
</code>```

This shader is used to render text. The text is just a font sheet where I change the texModifier so that the mat4 coordinates are over the specific letter I want to draw. This works fine, but I noticed that different projection matrixes cause different visual artifacts.

Here is the an example:

This is the text using its original position.

And this is the the same text only the projection matrix is translated 0.1f / 1920 to the left.  The visual artifacts change from being around commas and r to being around the u, S and more. These artifacts appear even when using linear interpolation.

This is the function used to draw text:

```<code>public void drawText(Shader shader, CharSequence text, float x, float y, int letters) {
    if(letters == -1)
        letters = text.length();

    Model model;
    Matrix4f projection = new Matrix4f();
    Texture fontSheet = texture;
    int textHeight = getTextHeight(text);

    projection.setOrtho(-1, 1, -1, 1, -1, 1);

    float drawX = x;
    float drawY = y;

    if (textHeight > fontHeight) {
        drawY += textHeight - fontHeight;
    }

    shader.bind();
    shader.setUniform("sampler", 0);
    fontSheet.bind(0);

    for (int i = 0; i < text.length() && i < letters; i++) {

        char ch = text.charAt(i);

        if (ch == '\n') {
            /* Line feed, set x and y to draw at the next line */
            drawY -= fontHeight;
            drawX = x;
            continue;
        }
        if (ch == '\r') {
            /* Carriage return, just skip it */
            continue;
        }

        Glyph g = glyphs.get(ch);
        model = Model.createQuad((float) g.width / 2, (float) g.height / 2);

        projection.setTranslation(((float) g.width / 2 + drawX) / Main.WINDOW_WIDTH, drawY / Main.WINDOW_HEIGHT, 0);

        Matrix4f texModifier =
                new Matrix4f()
                .translate((float) g.x / fontSheet.getWidth(), 0, 0)
                .scale((float) g.width / fontSheet.getWidth(), -(float) g.height / fontSheet.getHeight(), 1);

        shader.setUniform("projection", projection);
        shader.setUniform("texModifier", texModifier);

        model.render();
        drawX += g.width;
    }

}
</code>```

Why is the projection causing theses artifacts?

Body:
I have a very simple glsl vertex shader, which is the following:

#version 430

in vec2 vertices;
in vec2 textures;

out vec2 tex_coords;

uniform mat4 projection;
uniform mat4 texModifier;

void main() {
    tex_coords = (texModifier * vec4(textures,0,1)).xy;
    gl_Position = projection * vec4(vertices, 0, 1);
}

This shader is used to render text. The text is just a font sheet where I change the texModifier so that the mat4 coordinates are over the specific letter I want to draw. This works fine, but I noticed that different projection matrixes cause different visual artifacts.

Here is the an example:

This is the text using its original position.

And this is the the same text only the projection matrix is translated 0.1f / 1920 to the left.  The visual artifacts change from being around commas and r to being around the u, S and more. These artifacts appear even when using linear interpolation.

This is the function used to draw text:

public void drawText(Shader shader, CharSequence text, float x, float y, int letters) {
    if(letters == -1)
        letters = text.length();

    Model model;
    Matrix4f projection = new Matrix4f();
    Texture fontSheet = texture;
    int textHeight = getTextHeight(text);

    projection.setOrtho(-1, 1, -1, 1, -1, 1);

    float drawX = x;
    float drawY = y;

    if (textHeight > fontHeight) {
        drawY += textHeight - fontHeight;
    }

    shader.bind();
    shader.setUniform("sampler", 0);
    fontSheet.bind(0);

    for (int i = 0; i < text.length() && i < letters; i++) {

        char ch = text.charAt(i);

        if (ch == '\n') {
            /* Line feed, set x and y to draw at the next line */
            drawY -= fontHeight;
            drawX = x;
            continue;
        }
        if (ch == '\r') {
            /* Carriage return, just skip it */
            continue;
        }

        Glyph g = glyphs.get(ch);
        model = Model.createQuad((float) g.width / 2, (float) g.height / 2);

        projection.setTranslation(((float) g.width / 2 + drawX) / Main.WINDOW_WIDTH, drawY / Main.WINDOW_HEIGHT, 0);

        Matrix4f texModifier =
                new Matrix4f()
                .translate((float) g.x / fontSheet.getWidth(), 0, 0)
                .scale((float) g.width / fontSheet.getWidth(), -(float) g.height / fontSheet.getHeight(), 1);

        shader.setUniform("projection", projection);
        shader.setUniform("texModifier", texModifier);

        model.render();
        drawX += g.width;
    }

}

Why is the projection causing theses artifacts?