问:
Why does the compiler complains when `none const copy constructor` is used?
As the subject, the code below is right.

```<code>#include<iostream>

class ABC
{  public:
    ABC()
    {
        std::cout<< "default construction" << std::endl;
    }

    ABC(ABC& a)
    {
        std::cout << "copy construction" << std::endl;
    }

};

int main()
{
   ABC c1 = ABC();
}
</code>```

It could not compile successfully:

```<code><source>: In function 'int main()':
<source>:25:13: error: cannot bind non-const lvalue reference of type 'ABC&' to an rvalue of type 'ABC'
   25 |    ABC c1 = ABC();
      |             ^~~~~
<source>:10:14: note:   initializing argument 1 of 'ABC::ABC(ABC&)'
   10 |     ABC(ABC& a)
      |         ~~~~~^
</code>```

However, it could compile if replace the ABC(ABC& a) by ABC(const ABC&).I know it has some relation with the keyword const.But i could not figure out why.

You could check it on https://godbolt.org/z/jNL5Bd. I am a novice in C++.I would be grateful to have some help with this question.

答:
As the error message said, the temporary ABC() can't be bound to lvalue-reference to non-const, the copy constructor taking ABC& can't be used for initialization. (Temporaries could be bound to lvalue-reference to const or rvalue-reference.)

PS: Since C++17 the code would compile (which doesn't mean the copy constructor taking lvalue-reference to non-const is a good manner), because copy elision is guaranteed, the copy construction would be elided completely.

(emphasis mine)

Under the following circumstances, the compilers are required to omit the copy and move construction of class objects, even if the copy/move constructor and the destructor have observable side-effects. The objects are constructed directly into the storage where they would otherwise be copied/moved to. The copy/move constructors need not be present or accessible:

Body:
As the subject, the code below is right.

#include<iostream>

class ABC
{  public:
    ABC()
    {
        std::cout<< "default construction" << std::endl;
    }

    ABC(ABC& a)
    {
        std::cout << "copy construction" << std::endl;
    }

};

int main()
{
   ABC c1 = ABC();
}

It could not compile successfully:

<source>: In function 'int main()':
<source>:25:13: error: cannot bind non-const lvalue reference of type 'ABC&' to an rvalue of type 'ABC'
   25 |    ABC c1 = ABC();
      |             ^~~~~
<source>:10:14: note:   initializing argument 1 of 'ABC::ABC(ABC&)'
   10 |     ABC(ABC& a)
      |         ~~~~~^

However, it could compile if replace the ABC(ABC& a) by ABC(const ABC&).I know it has some relation with the keyword const.But i could not figure out why.

You could check it on https://godbolt.org/z/jNL5Bd. I am a novice in C++.I would be grateful to have some help with this question.


来源: stackexchange

问:
Searching NTFS directory .NET
I would like to write a web page where users can search a directory on NTFS for certain criteria and display the results.

Does the directory have to be indexed?

Is there a .NET accessible windows search API that I can use to query the directory?

答: DirectoryInfo.GetFiles does support recursing through subdirectories. It's one of the overloaded methods. It allows you to filter by filename only though. </p>

ContentLicense: CC BY-SA 2.5

Title: Searching NTFS directory .NET


问:
vb.net code to enlarge font size, font name and do page setup in ms.excell
I am creating an excel report from vb.net. Now it works. But i realize that the apparent does not make sense. I just want enlarge some font size and change font name plus setting up the page to fit my receipt printer (Epson TM-T88IV).

what should i do ?

thanks in advance

答:
First manually set everything up bit by bit until it all fits nicely on your receipt printer.

Once you have everything just the way you want:

Generate a new, plain copy of the report.

Start recording a macro

Manually replicate the changes that you did in your practice sheet onto your macro recording sheet.

Stop recording the Macro, and press Alt-F11 to get to the VB that was generated.

Use the relevant lines of the generated macro to see what you need to add to your report generation code.

ContentLicense: CC BY-SA 3.0


问:
Build conda package from a local C++ program
I am trying to build (and later upload) a conda package which would contain my custom program that I have developed in C++.

Simplifying the problem, I have a following meta.yaml:

```<code>package:
  name: CoolName
  version: "1.0.0"

source:
  path: ./source

requirements:
  build:
    - make
</code>```

and the following build.sh:

```<code>make
</code>```

I have two questions here:

1) How and where should I copy the binary which is a result of the make compilation so that it is indeed recognized upon environment activation?

2) How should I specify g++ as a dependancy? I would like to have this package be later available for linux-64 and osx-64... In the building process (in the Makefile) I am using only g++.

Edit

I have modified my build script to have:

```<code>make
mkdir -p $PREFIX/bin
cp my_binary $PREFIX/bin/my_binary
</code>```

And now the conda-build is successful. However, when I later try to install the package locally with conda install --use-local I get:

```<code>Collecting package metadata (current_repodata.json): done
Solving environment: done

# All requested packages already installed.
</code>```

But this is not true, my binary is not installed anywhere and is not recognized...

答:
How and where should I copy the binary which is a result of the make compilation so that it is indeed recognized upon environment activation?

As you mentioned in your edit, install somewhere within ${PREFIX}

How should I specify g++ as a dependancy?

To use conda-supplied compilers (rather than your system compiler), use this:

requirements:
  build:
    - {{ compiler('cxx') }}
```
<blockquote>
<p>I would like to have this package be later available for linux-64 and osx-64... In the building process (in the Makefile) I am using only g++.</p>
</blockquote>
<p>Note: On Mac, it will use <code>clang++</code>, not <code>g++</code>.  Make sure your Makefile respects the <code>${CXX}</code> environment variable instead of hard-coding <code>g++</code>.</p>
<blockquote>
<p>However, when I later try to install the package locally with <code>conda install --use-local</code> I get:</p>
</blockquote>
<p>That is strange.  <code>conda install --use-local CoolName</code> should do what you want.  But here are some things to try:</p>
<ul>
<li><p>Double-check the contents of the environment you're trying to install it into:</p>
```  conda list
```
</li>
<li><p>Try installing to a fresh environment:</p>
```  conda create -n my-new-env --use-local CoolName
```
</li>
<li><p>Delete any obsolete versions of the package you might have created before you successfully built the package:</p>
</li>
</ul>
```# Inspect the packages you've created,
# and consider deleting all but the most recent one.
ls $(conda info --base)/conda-bld/linux-64/CoolName*.tar.bz2
```

...then try running conda install again.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to build (and later upload) a conda package which would contain my custom program that I have developed in C++.

Simplifying the problem, I have a following meta.yaml:

package:
  name: CoolName
  version: "1.0.0"

source:
  path: ./source

requirements:
  build:
    - make

and the following build.sh:

make

I have two questions here:

1) How and where should I copy the binary which is a result of the make compilation so that it is indeed recognized upon environment activation?

2) How should I specify g++ as a dependancy? I would like to have this package be later available for linux-64 and osx-64... In the building process (in the Makefile) I am using only g++.

Edit

I have modified my build script to have:

make
mkdir -p $PREFIX/bin
cp my_binary $PREFIX/bin/my_binary

And now the conda-build is successful. However, when I later try to install the package locally with conda install --use-local I get:

Collecting package metadata (current_repodata.json): done
Solving environment: done

# All requested packages already installed.

But this is not true, my binary is not installed anywhere and is not recognized...

Body:
How and where should I copy the binary which is a result of the make compilation so that it is indeed recognized upon environment activation?

As you mentioned in your edit, install somewhere within ${PREFIX}

How should I specify g++ as a dependancy?

To use conda-supplied compilers (rather than your system compiler), use this:

requirements:
  build:
    - {{ compiler('cxx') }}

I would like to have this package be later available for linux-64 and osx-64... In the building process (in the Makefile) I am using only g++.

Note: On Mac, it will use clang++, not g++.  Make sure your Makefile respects the ${CXX} environment variable instead of hard-coding g++.

However, when I later try to install the package locally with conda install --use-local I get:

That is strange.  conda install --use-local CoolName should do what you want.  But here are some things to try:

Double-check the contents of the environment you're trying to install it into:

  conda list

Try installing to a fresh environment:

  conda create -n my-new-env --use-local CoolName

Delete any obsolete versions of the package you might have created before you successfully built the package:

# Inspect the packages you've created,
# and consider deleting all but the most recent one.
ls $(conda info --base)/conda-bld/linux-64/CoolName*.tar.bz2

...then try running conda install again.


问:
How to authorize django-rest-knox login path without 401 error?
I'm trying to put an authentication api on my django app so I can start using a Vue+Node frontend.  I've read over the knox documentation, but I don't seem to see anything suggesting what the issue is.  Any insight would be greatly appreciated.  My suspicious are below.

What I'm doing:  I was following this tutorial which suggest using knox, which seems to have nice features.  When I try to curl to create a user, everything works as expected, but when I try to login (via curl), I get the following response (401) in my console:

API Call

```<code>(venv) brads-mbp:ReportVisualization brads$ curl --request POST --url http://127.0.0.1:8000/backend/auth/register/ --header 'content-type: application/json' --data '{"username": "user3", "password": "hunter2"}'
{"user":{"id":4,"username":"user3"},"token":"2b261fcdcbfff47cd8819accc2a3a08befa169c59982659a64012c680a69c3e8"}
(venv) brads-mbp:ReportVisualization brads$ curl --request POST --url http://127.0.0.1:8000/backend/auth/login/ --header 'content-type: application/json' --data '{"username": "user3","password": "hunter2"}'
{"detail":"Authentication credentials were not provided."}
</code>```

Server Log

```<code>System check identified no issues (0 silenced).
December 18, 2018 - 07:47:05
Django version 2.1.3, using settings 'project.settings'
Starting ASGI/Channels version 2.1.5 development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
HTTP POST /backend/auth/register/ 200 [0.13, 127.0.0.1:61332]
Unauthorized: /backend/auth/login/
HTTP POST /backend/auth/login/ 401 [0.00, 127.0.0.1:61336]
</code>```

The curl login response makes me think there is something wrong with my setup of knox or django's auth.  The server message seems to suggest an issue with the routing, so here is my urls:

project/urls.py

```<code>from django.contrib import admin
from django.urls import path, include
from django.views.generic import RedirectView, TemplateView
from django.contrib.auth import views as auth_views
from .router import ROUTER

urlpatterns = [
    # path('', auth_views.LoginView.as_view(template_name='registration/login.html'), name='login'),
    path('admin/', admin.site.urls),
    # path('favicon.ico', RedirectView.as_view(url='/static/project/images/favicon.ico')),
    # path('background.jpg', RedirectView.as_view(url='/static/project/images/background.jpg')),
    # path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'),
    # path('home/', TemplateView.as_view(template_name="index.html")),
    path('backend/', include('backend.urls')),
    path('api/', include(ROUTER.urls))
]
</code>```

backend/urls.py

```<code>from django.urls import path, include

from . import views, authorization_views, dash_views

urlpatterns = [
     # path('filter/', views.DataFilter.as_view(), name='filter'),
     # path('entry/', views.CreateDataEntryBlock.as_view(), name='entry'),
     # path('home/', views.home_view, name='home'),
#     path('home/', views.index, name='index'),
#     path('public/', views.public),
#     path('private/', views.private),
     path('auth', include('knox.urls')),
     path('auth/register/', authorization_views.RegistrationAPI.as_view()),
     path('auth/login/', authorization_views.LoginAPI.as_view()),
]
</code>```

authorization_views.py

```<code>from rest_framework import viewsets, permissions, generics
from rest_framework.response import Response

from knox.models import AuthToken

# from Domino.backend.models import User
from .serializers import CreateUserSerializer, UserSerializer, LoginUserSerializer

class RegistrationAPI(generics.GenericAPIView):
    serializer_class = CreateUserSerializer

    def post(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = serializer.save()
        return Response({
            "user": UserSerializer(user, context=self.get_serializer_context()).data,
            "token": AuthToken.objects.create(user)
        })

class LoginAPI(generics.GenericAPIView):
    serializer_class = LoginUserSerializer

    def post(self, request, *args, **kwargs):
        import pdb; pdb.set_trace()
        print("LoginAPI - post")
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = serializer.validated_data
        return Response({
            "user": UserSerializer(user, context=self.get_serializer_context()).data,
            "token": AuthToken.objects.create(user)
        })
</code>```

backend/serializers.py

```<code>from datetime import datetime, timedelta
from rest_framework import serializers
from django.contrib.auth.models import User
from django.contrib.auth import authenticate

class CreateUserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('id', 'username', 'password')
        extra_kwargs = {'password': {'write_only': True}}

    def create(self, validated_data):
        user = User.objects.create_user(validated_data['username'],
                                        None,
                                        validated_data['password'])
        return user

class LoginUserSerializer(serializers.Serializer):
    username = serializers.CharField()
    password = serializers.CharField()

    def validate(self, data):
        import pdb; pdb.set_trace()
        print("LoginAPI - post")
        user = authenticate(**data)
        if user and user.is_active:
            return user
        raise serializers.ValidationError("Unable to log in with provided credentials.")

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('id', 'username')
</code>```

project/settings.py

```<code>import os

# import json
# from six.moves.urllib import request
# from cryptography.x509 import load_pem_x509_certificate
# from cryptography.hazmat.backends import default_backend

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

SECRET_KEY = '...'

DEBUG = True

ALLOWED_HOSTS = ['*']

# Application definition

INSTALLED_APPS = [
    'backend.apps.BackendConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'channels',
    'widget_tweaks',
    'django_filters',
    'crispy_forms',
    'rest_framework',
    'knox',
    # 'rest_framework_jwt'
    'corsheaders',
]

# App settings
CORS_ORIGIN_ALLOW_ALL = True

MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    '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 = 'project.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'project/templates'),
                 os.path.join(BASE_DIR, 'backend/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 = 'project.wsgi.application'
ASGI_APPLICATION = "project.routing.application"

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

DATABASES = {
    'default': {
        'ENGINE': 'djongo',
        'NAME': 'test',
    }
}

# Password validation
# https://docs.djangoproject.com/en/2.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',
    },
]

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

LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True

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

LOGIN_URL = ''
LOGIN_REDIRECT_URL = 'backend/home/'

STATIC_URL = '/static/'
# STATIC_ROOT = os.path.join(BASE_DIR, '../static/')

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "project/static"),
    os.path.join(BASE_DIR, "backend/static"),
]

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': ('knox.auth.TokenAuthentication',),
}
</code>```

Environment

```<code>(venv) brads-mbp:ReportVisualization brads$ pip list

brads$
Package                 Version
----------------------- ----------
asgiref                 2.3.2
asn1crypto              0.24.0
astroid                 2.1.0
async-timeout           3.0.1
atomicwrites            1.2.1
attrs                   18.2.0
autobahn                18.11.2
Automat                 0.7.0
certifi                 2018.11.29
cffi                    1.11.5
channels                2.1.5
chardet                 3.0.4
constantly              15.1.0
cryptography            2.4.2
daphne                  2.2.3
dataclasses             0.6
Django                  2.1.3
django-cors-headers     2.4.0
django-crispy-forms     1.7.2
django-filter           2.0.0
django-rest-knox        3.4.0
django-widget-tweaks    1.4.3
djangorestframework     3.9.0
djangorestframework-jwt 1.11.0
djongo                  1.2.30
ecdsa                   0.13
future                  0.17.1
hyperlink               18.0.0
idna                    2.7
incremental             17.5.0
isort                   4.3.4
lazy-object-proxy       1.3.1
mccabe                  0.6.1
more-itertools          4.3.0
numpy                   1.15.4
Pillow                  5.3.0
pip                     18.1
pluggy                  0.8.0
py                      1.7.0
pyasn1                  0.4.4
pyasn1-modules          0.2.2
pycparser               2.19
PyHamcrest              1.9.0
PyJWT                   1.7.1
pylint                  2.2.2
pylint-django           2.0.4
pylint-plugin-utils     0.4
pymongo                 3.7.2
pyOpenSSL               18.0.0
pytest                  4.0.1
python-jose             3.0.1
pytz                    2018.7
requests                2.20.1
rope                    0.11.0
rsa                     4.0
scipy                   1.1.0
service-identity        18.1.0
setuptools              40.6.2
six                     1.11.0
sqlparse                0.2.4
Twisted                 18.9.0
txaio                   18.8.1
typed-ast               1.1.0
urllib3                 1.24.1
wheel                   0.32.3
wrapt                   1.10.11
zope.interface          4.6.0
</code>```

I feel like I have to have something simple that is wrong with a setting, but I can't seem to figure out what it is.  I saw some posts that claimed an issue with "Apache and mod_wsgi" which isn't an issue for me as I am running local atm, however I'm running channels so I wonder if that has any impact, or maybe it has to do with the auth password validators in settings?

答:
Short answer, go to settings.py and edit DEFAULT_AUTHENTICATION_CLASSES :

```<code>REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
         'rest_framework.authentication.BasicAuthentication' ,
         'knox.auth.TokenAuthentication',),
}
</code>```

The issue here is that DEFAULT_AUTHENTICATION_CLASSES is set to knox.auth.TokenAuthentication, this means that all views will have this as their default auth class thus needs a token including the knox login view itself.
By adding  'rest_framework.authentication.BasicAuthentication' , auth classes will be tested in sequence until one of them works, so for login, you can now do as an example:

```<code>curl --location --request POST 'http://127.0.0.1:8000/api/v1/auth/login/' \ --header 'Authorization: Basic username:password'
</code>```

Body:
I'm trying to put an authentication api on my django app so I can start using a Vue+Node frontend.  I've read over the knox documentation, but I don't seem to see anything suggesting what the issue is.  Any insight would be greatly appreciated.  My suspicious are below.

What I'm doing:  I was following this tutorial which suggest using knox, which seems to have nice features.  When I try to curl to create a user, everything works as expected, but when I try to login (via curl), I get the following response (401) in my console:

API Call

(venv) brads-mbp:ReportVisualization brads$ curl --request POST --url http://127.0.0.1:8000/backend/auth/register/ --header 'content-type: application/json' --data '{"username": "user3", "password": "hunter2"}'
{"user":{"id":4,"username":"user3"},"token":"2b261fcdcbfff47cd8819accc2a3a08befa169c59982659a64012c680a69c3e8"}
(venv) brads-mbp:ReportVisualization brads$ curl --request POST --url http://127.0.0.1:8000/backend/auth/login/ --header 'content-type: application/json' --data '{"username": "user3","password": "hunter2"}'
{"detail":"Authentication credentials were not provided."}

Server Log

System check identified no issues (0 silenced).
December 18, 2018 - 07:47:05
Django version 2.1.3, using settings 'project.settings'
Starting ASGI/Channels version 2.1.5 development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
HTTP POST /backend/auth/register/ 200 [0.13, 127.0.0.1:61332]
Unauthorized: /backend/auth/login/
HTTP POST /backend/auth/login/ 401 [0.00, 127.0.0.1:61336]

The curl login response makes me think there is something wrong with my setup of knox or django's auth.  The server message seems to suggest an issue with the routing, so here is my urls:

project/urls.py

from django.contrib import admin
from django.urls import path, include
from django.views.generic import RedirectView, TemplateView
from django.contrib.auth import views as auth_views
from .router import ROUTER

urlpatterns = [
    # path('', auth_views.LoginView.as_view(template_name='registration/login.html'), name='login'),
    path('admin/', admin.site.urls),
    # path('favicon.ico', RedirectView.as_view(url='/static/project/images/favicon.ico')),
    # path('background.jpg', RedirectView.as_view(url='/static/project/images/background.jpg')),
    # path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'),
    # path('home/', TemplateView.as_view(template_name="index.html")),
    path('backend/', include('backend.urls')),
    path('api/', include(ROUTER.urls))
]

backend/urls.py

from django.urls import path, include

from . import views, authorization_views, dash_views

urlpatterns = [
     # path('filter/', views.DataFilter.as_view(), name='filter'),
     # path('entry/', views.CreateDataEntryBlock.as_view(), name='entry'),
     # path('home/', views.home_view, name='home'),
#     path('home/', views.index, name='index'),
#     path('public/', views.public),
#     path('private/', views.private),
     path('auth', include('knox.urls')),
     path('auth/register/', authorization_views.RegistrationAPI.as_view()),
     path('auth/login/', authorization_views.LoginAPI.as_view()),
]

authorization_views.py

from rest_framework import viewsets, permissions, generics
from rest_framework.response import Response

from knox.models import AuthToken

# from Domino.backend.models import User
from .serializers import CreateUserSerializer, UserSerializer, LoginUserSerializer

class RegistrationAPI(generics.GenericAPIView):
    serializer_class = CreateUserSerializer

    def post(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = serializer.save()
        return Response({
            "user": UserSerializer(user, context=self.get_serializer_context()).data,
            "token": AuthToken.objects.create(user)
        })

class LoginAPI(generics.GenericAPIView):
    serializer_class = LoginUserSerializer

    def post(self, request, *args, **kwargs):
        import pdb; pdb.set_trace()
        print("LoginAPI - post")
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = serializer.validated_data
        return Response({
            "user": UserSerializer(user, context=self.get_serializer_context()).data,
            "token": AuthToken.objects.create(user)
        })

backend/serializers.py

from datetime import datetime, timedelta
from rest_framework import serializers
from django.contrib.auth.models import User
from django.contrib.auth import authenticate

class CreateUserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('id', 'username', 'password')
        extra_kwargs = {'password': {'write_only': True}}

    def create(self, validated_data):
        user = User.objects.create_user(validated_data['username'],
                                        None,
                                        validated_data['password'])
        return user

class LoginUserSerializer(serializers.Serializer):
    username = serializers.CharField()
    password = serializers.CharField()

    def validate(self, data):
        import pdb; pdb.set_trace()
        print("LoginAPI - post")
        user = authenticate(**data)
        if user and user.is_active:
            return user
        raise serializers.ValidationError("Unable to log in with provided credentials.")

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('id', 'username')

project/settings.py

import os

# import json
# from six.moves.urllib import request
# from cryptography.x509 import load_pem_x509_certificate
# from cryptography.hazmat.backends import default_backend

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

SECRET_KEY = '...'

DEBUG = True

ALLOWED_HOSTS = ['*']

# Application definition

INSTALLED_APPS = [
    'backend.apps.BackendConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'channels',
    'widget_tweaks',
    'django_filters',
    'crispy_forms',
    'rest_framework',
    'knox',
    # 'rest_framework_jwt'
    'corsheaders',
]

# App settings
CORS_ORIGIN_ALLOW_ALL = True

MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    '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 = 'project.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'project/templates'),
                 os.path.join(BASE_DIR, 'backend/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 = 'project.wsgi.application'
ASGI_APPLICATION = "project.routing.application"

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

DATABASES = {
    'default': {
        'ENGINE': 'djongo',
        'NAME': 'test',
    }
}

# Password validation
# https://docs.djangoproject.com/en/2.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',
    },
]

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

LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True

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

LOGIN_URL = ''
LOGIN_REDIRECT_URL = 'backend/home/'

STATIC_URL = '/static/'
# STATIC_ROOT = os.path.join(BASE_DIR, '../static/')

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "project/static"),
    os.path.join(BASE_DIR, "backend/static"),
]

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': ('knox.auth.TokenAuthentication',),
}

Environment

(venv) brads-mbp:ReportVisualization brads$ pip list

brads$
Package                 Version
----------------------- ----------
asgiref                 2.3.2
asn1crypto              0.24.0
astroid                 2.1.0
async-timeout           3.0.1
atomicwrites            1.2.1
attrs                   18.2.0
autobahn                18.11.2
Automat                 0.7.0
certifi                 2018.11.29
cffi                    1.11.5
channels                2.1.5
chardet                 3.0.4
constantly              15.1.0
cryptography            2.4.2
daphne                  2.2.3
dataclasses             0.6
Django                  2.1.3
django-cors-headers     2.4.0
django-crispy-forms     1.7.2
django-filter           2.0.0
django-rest-knox        3.4.0
django-widget-tweaks    1.4.3
djangorestframework     3.9.0
djangorestframework-jwt 1.11.0
djongo                  1.2.30
ecdsa                   0.13
future                  0.17.1
hyperlink               18.0.0
idna                    2.7
incremental             17.5.0
isort                   4.3.4
lazy-object-proxy       1.3.1
mccabe                  0.6.1
more-itertools          4.3.0
numpy                   1.15.4
Pillow                  5.3.0
pip                     18.1
pluggy                  0.8.0
py                      1.7.0
pyasn1                  0.4.4
pyasn1-modules          0.2.2
pycparser               2.19
PyHamcrest              1.9.0
PyJWT                   1.7.1
pylint                  2.2.2
pylint-django           2.0.4
pylint-plugin-utils     0.4
pymongo                 3.7.2
pyOpenSSL               18.0.0
pytest                  4.0.1
python-jose             3.0.1
pytz                    2018.7
requests                2.20.1
rope                    0.11.0
rsa                     4.0
scipy                   1.1.0
service-identity        18.1.0
setuptools              40.6.2
six                     1.11.0
sqlparse                0.2.4
Twisted                 18.9.0
txaio                   18.8.1
typed-ast               1.1.0
urllib3                 1.24.1
wheel                   0.32.3
wrapt                   1.10.11
zope.interface          4.6.0

I feel like I have to have something simple that is wrong with a setting, but I can't seem to figure out what it is.  I saw some posts that claimed an issue with "Apache and mod_wsgi" which isn't an issue for me as I am running local atm, however I'm running channels so I wonder if that has any impact, or maybe it has to do with the auth password validators in settings?

Body:
Short answer, go to settings.py and edit DEFAULT_AUTHENTICATION_CLASSES :

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
         'rest_framework.authentication.BasicAuthentication' ,
         'knox.auth.TokenAuthentication',),
}

The issue here is that DEFAULT_AUTHENTICATION_CLASSES is set to knox.auth.TokenAuthentication, this means that all views will have this as their default auth class thus needs a token including the knox login view itself.
By adding  'rest_framework.authentication.BasicAuthentication' , auth classes will be tested in sequence until one of them works, so for login, you can now do as an example:

curl --location --request POST 'http://127.0.0.1:8000/api/v1/auth/login/' \ --header 'Authorization: Basic username:password'


问:
SQLite not working with Electron and Node on Windows 10
I have been trying for weeks to get SQLite installed and working with Electron, but rebuild keeps failing.

I am on windows 10 and here is my procedure...

Install Node... node-v12.16.3-x64

During install of Node, I do check the box that says "Automatically install the necessary tools"

Next I create a fresh new folder for my Electron project

Then I run...

npm init -y

npm install --save electron

npm install --save sqlite3

npm install --save-dev electron-builder

All of which complete without errors.

Then I add to my package.json under scripts...

"postinstall": "electron-builder install-app-deps"

Then I run npm run postinstall

which throws a bunch of errors, and I am dead in the water!

I am praying someone can help me.

Here is the output from postinstall:

```<code>> CMPDB@1.0.0 postinstall D:\dropbox\CMPDB
> electron-builder install-app-deps

  • electron-builder  version=22.6.1
  • rebuilding native dependencies  dependencies=sqlite3@4.2.0 platform=win32 arch=x64
  ⨯ cannot execute  cause=exit status 1
                    out=
    > sqlite3@4.2.0 install D:\dropbox\CMPDB\node_modules\sqlite3
    > node-pre-gyp install --fallback-to-build

    Building the projects in this solution one at a time. To enable parallel build, please add the "/m" switch.
      unpack_sqlite_dep
      'C:\Users\Ion' is not recognized as an internal or external command,
      operable program or batch file.
    C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\Common7\IDE\VC\VCTargets\Microsoft.CppCommon.targets(209,5): error MSB6006: "cmd.exe" exited with code 1. [D:\dropbox\CMPDB\node_modules\sqlite3\build\deps\action_before_build.vcxproj]
    Failed to execute 'C:\Program Files\nodejs\node.exe C:\Users\Ion Hatzithomas\AppData\Roaming\npm\node_modules\npm\node_modules\node-gyp\bin\node-gyp.js build --fallback-to-build --module=D:\dropbox\CMPDB\node_modules\sqlite3\lib\binding\electron-v9.0-win32-x64\node_sqlite3.node --module_name=node_sqlite3 --module_path=D:\dropbox\CMPDB\node_modules\sqlite3\lib\binding\electron-v9.0-win32-x64 --napi_version=5 --node_abi_napi=napi --napi_build_version=0 --node_napi_label=electron-v9.0' (1)

                    errorOut=node-pre-gyp WARN Using needle for node-pre-gyp https download
    node-pre-gyp WARN Tried to download(403): https://mapbox-node-binary.s3.amazonaws.com/sqlite3/v4.2.0/electron-v9.0-win32-x64.tar.gz
    node-pre-gyp WARN Pre-built binaries not found for sqlite3@4.2.0 and electron@9.0.0 (electron-v9.0 ABI, unknown) (falling back to source compile with node-gyp)
    gyp ERR! build error
    gyp ERR! stack Error: `C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\MSBuild\15.0\Bin\MSBuild.exe` failed with exit code: 1
    gyp ERR! stack     at ChildProcess.onExit (C:\Users\Ion Hatzithomas\AppData\Roaming\npm\node_modules\npm\node_modules\node-gyp\lib\build.js:194:23)
    gyp ERR! stack     at ChildProcess.emit (events.js:310:20)
    gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:275:12)
    gyp ERR! System Windows_NT 10.0.18362
    gyp ERR! command "C:\\Program Files\\nodejs\\node.exe" "C:\\Users\\Ion Hatzithomas\\AppData\\Roaming\\npm\\node_modules\\npm\\node_modules\\node-gyp\\bin\\node-gyp.js" "build" "--fallback-to-build" "--module=D:\\dropbox\\CMPDB\\node_modules\\sqlite3\\lib\\binding\\electron-v9.0-win32-x64\\node_sqlite3.node" "--module_name=node_sqlite3" "--module_path=D:\\dropbox\\CMPDB\\node_modules\\sqlite3\\lib\\binding\\electron-v9.0-win32-x64" "--napi_version=5" "--node_abi_napi=napi" "--napi_build_version=0" "--node_napi_label=electron-v9.0"
    gyp ERR! cwd D:\dropbox\CMPDB\node_modules\sqlite3
    gyp ERR! node -v v12.16.3
    gyp ERR! node-gyp -v v5.1.0
    gyp ERR! not ok
    node-pre-gyp ERR! build error
    node-pre-gyp ERR! stack Error: Failed to execute 'C:\Program Files\nodejs\node.exe C:\Users\Ion Hatzithomas\AppData\Roaming\npm\node_modules\npm\node_modules\node-gyp\bin\node-gyp.js build --fallback-to-build --module=D:\dropbox\CMPDB\node_modules\sqlite3\lib\binding\electron-v9.0-win32-x64\node_sqlite3.node --module_name=node_sqlite3 --module_path=D:\dropbox\CMPDB\node_modules\sqlite3\lib\binding\electron-v9.0-win32-x64 --napi_version=5 --node_abi_napi=napi --napi_build_version=0 --node_napi_label=electron-v9.0' (1)
    node-pre-gyp ERR! stack     at ChildProcess.<anonymous> (D:\Dropbox\CMPDB\node_modules\node-pre-gyp\lib\util\compile.js:83:29)
    node-pre-gyp ERR! stack     at ChildProcess.emit (events.js:310:20)
    node-pre-gyp ERR! stack     at maybeClose (internal/child_process.js:1021:16)
    node-pre-gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:286:5)
    node-pre-gyp ERR! System Windows_NT 10.0.18362
    node-pre-gyp ERR! command "C:\\Program Files\\nodejs\\node.exe" "D:\\Dropbox\\CMPDB\\node_modules\\node-pre-gyp\\bin\\node-pre-gyp" "install" "--fallback-to-build"
    node-pre-gyp ERR! cwd D:\dropbox\CMPDB\node_modules\sqlite3
    node-pre-gyp ERR! node -v v12.16.3
    node-pre-gyp ERR! node-pre-gyp -v v0.11.0
    node-pre-gyp ERR! not ok
    npm ERR! code ELIFECYCLE
    npm ERR! errno 1
    npm ERR! sqlite3@4.2.0 install: `node-pre-gyp install --fallback-to-build`
    npm ERR! Exit status 1
    npm ERR!
    npm ERR! Failed at the sqlite3@4.2.0 install script.
    npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

    npm ERR! A complete log of this run can be found in:
    npm ERR!     C:\Users\Ion Hatzithomas\AppData\Roaming\npm-cache\_logs\2020-05-25T01_12_42_765Z-debug.log

                    command='C:\Program Files\nodejs\node.exe' 'C:\Users\Ion Hatzithomas\AppData\Roaming\npm\node_modules\npm\bin\npm-cli.js' rebuild sqlite3@4.2.0
                    workingDir=
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! CMPDB@1.0.0 postinstall: `electron-builder install-app-deps`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the CMPDB@1.0.0 postinstall script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Ion Hatzithomas\AppData\Roaming\npm-cache\_logs\2020-05-25T01_12_42_818Z-debug.log
</code>```

答:
Please make sure the following things -

You have a stable internet connection

You have downloaded Microsoft visual studio C++ packages required for nodejs desktop development

Hope it helps...

Body:
I have been trying for weeks to get SQLite installed and working with Electron, but rebuild keeps failing.

I am on windows 10 and here is my procedure...

Install Node... node-v12.16.3-x64

During install of Node, I do check the box that says "Automatically install the necessary tools"

Next I create a fresh new folder for my Electron project

Then I run...

npm init -y

npm install --save electron

npm install --save sqlite3

npm install --save-dev electron-builder

All of which complete without errors.

Then I add to my package.json under scripts...

"postinstall": "electron-builder install-app-deps"

Then I run npm run postinstall

which throws a bunch of errors, and I am dead in the water!

I am praying someone can help me.

Here is the output from postinstall:

> CMPDB@1.0.0 postinstall D:\dropbox\CMPDB
> electron-builder install-app-deps

  • electron-builder  version=22.6.1
  • rebuilding native dependencies  dependencies=sqlite3@4.2.0 platform=win32 arch=x64
  ⨯ cannot execute  cause=exit status 1
                    out=
    > sqlite3@4.2.0 install D:\dropbox\CMPDB\node_modules\sqlite3
    > node-pre-gyp install --fallback-to-build

    Building the projects in this solution one at a time. To enable parallel build, please add the "/m" switch.
      unpack_sqlite_dep
      'C:\Users\Ion' is not recognized as an internal or external command,
      operable program or batch file.
    C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\Common7\IDE\VC\VCTargets\Microsoft.CppCommon.targets(209,5): error MSB6006: "cmd.exe" exited with code 1. [D:\dropbox\CMPDB\node_modules\sqlite3\build\deps\action_before_build.vcxproj]
    Failed to execute 'C:\Program Files\nodejs\node.exe C:\Users\Ion Hatzithomas\AppData\Roaming\npm\node_modules\npm\node_modules\node-gyp\bin\node-gyp.js build --fallback-to-build --module=D:\dropbox\CMPDB\node_modules\sqlite3\lib\binding\electron-v9.0-win32-x64\node_sqlite3.node --module_name=node_sqlite3 --module_path=D:\dropbox\CMPDB\node_modules\sqlite3\lib\binding\electron-v9.0-win32-x64 --napi_version=5 --node_abi_napi=napi --napi_build_version=0 --node_napi_label=electron-v9.0' (1)

                    errorOut=node-pre-gyp WARN Using needle for node-pre-gyp https download
    node-pre-gyp WARN Tried to download(403): https://mapbox-node-binary.s3.amazonaws.com/sqlite3/v4.2.0/electron-v9.0-win32-x64.tar.gz
    node-pre-gyp WARN Pre-built binaries not found for sqlite3@4.2.0 and electron@9.0.0 (electron-v9.0 ABI, unknown) (falling back to source compile with node-gyp)
    gyp ERR! build error
    gyp ERR! stack Error: `C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\MSBuild\15.0\Bin\MSBuild.exe` failed with exit code: 1
    gyp ERR! stack     at ChildProcess.onExit (C:\Users\Ion Hatzithomas\AppData\Roaming\npm\node_modules\npm\node_modules\node-gyp\lib\build.js:194:23)
    gyp ERR! stack     at ChildProcess.emit (events.js:310:20)
    gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:275:12)
    gyp ERR! System Windows_NT 10.0.18362
    gyp ERR! command "C:\\Program Files\\nodejs\\node.exe" "C:\\Users\\Ion Hatzithomas\\AppData\\Roaming\\npm\\node_modules\\npm\\node_modules\\node-gyp\\bin\\node-gyp.js" "build" "--fallback-to-build" "--module=D:\\dropbox\\CMPDB\\node_modules\\sqlite3\\lib\\binding\\electron-v9.0-win32-x64\\node_sqlite3.node" "--module_name=node_sqlite3" "--module_path=D:\\dropbox\\CMPDB\\node_modules\\sqlite3\\lib\\binding\\electron-v9.0-win32-x64" "--napi_version=5" "--node_abi_napi=napi" "--napi_build_version=0" "--node_napi_label=electron-v9.0"
    gyp ERR! cwd D:\dropbox\CMPDB\node_modules\sqlite3
    gyp ERR! node -v v12.16.3
    gyp ERR! node-gyp -v v5.1.0
    gyp ERR! not ok
    node-pre-gyp ERR! build error
    node-pre-gyp ERR! stack Error: Failed to execute 'C:\Program Files\nodejs\node.exe C:\Users\Ion Hatzithomas\AppData\Roaming\npm\node_modules\npm\node_modules\node-gyp\bin\node-gyp.js build --fallback-to-build --module=D:\dropbox\CMPDB\node_modules\sqlite3\lib\binding\electron-v9.0-win32-x64\node_sqlite3.node --module_name=node_sqlite3 --module_path=D:\dropbox\CMPDB\node_modules\sqlite3\lib\binding\electron-v9.0-win32-x64 --napi_version=5 --node_abi_napi=napi --napi_build_version=0 --node_napi_label=electron-v9.0' (1)
    node-pre-gyp ERR! stack     at ChildProcess.<anonymous> (D:\Dropbox\CMPDB\node_modules\node-pre-gyp\lib\util\compile.js:83:29)
    node-pre-gyp ERR! stack     at ChildProcess.emit (events.js:310:20)
    node-pre-gyp ERR! stack     at maybeClose (internal/child_process.js:1021:16)
    node-pre-gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:286:5)
    node-pre-gyp ERR! System Windows_NT 10.0.18362
    node-pre-gyp ERR! command "C:\\Program Files\\nodejs\\node.exe" "D:\\Dropbox\\CMPDB\\node_modules\\node-pre-gyp\\bin\\node-pre-gyp" "install" "--fallback-to-build"
    node-pre-gyp ERR! cwd D:\dropbox\CMPDB\node_modules\sqlite3
    node-pre-gyp ERR! node -v v12.16.3
    node-pre-gyp ERR! node-pre-gyp -v v0.11.0
    node-pre-gyp ERR! not ok
    npm ERR! code ELIFECYCLE
    npm ERR! errno 1
    npm ERR! sqlite3@4.2.0 install: `node-pre-gyp install --fallback-to-build`
    npm ERR! Exit status 1
    npm ERR!
    npm ERR! Failed at the sqlite3@4.2.0 install script.
    npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

    npm ERR! A complete log of this run can be found in:
    npm ERR!     C:\Users\Ion Hatzithomas\AppData\Roaming\npm-cache\_logs\2020-05-25T01_12_42_765Z-debug.log

                    command='C:\Program Files\nodejs\node.exe' 'C:\Users\Ion Hatzithomas\AppData\Roaming\npm\node_modules\npm\bin\npm-cli.js' rebuild sqlite3@4.2.0
                    workingDir=
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! CMPDB@1.0.0 postinstall: `electron-builder install-app-deps`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the CMPDB@1.0.0 postinstall script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Ion Hatzithomas\AppData\Roaming\npm-cache\_logs\2020-05-25T01_12_42_818Z-debug.log


问:
Ordering Timestamps for ARIMA model predicion
Info:

I am trying to predict the price of Bitcoin,as a test and to make it easier, 1 day after my most current datetime in my data. So t = 05/27/2020, t + 1 = 05/28/2020.

So I loaded my data:

```<code>x = pd.read_csv('btcdata.csv', header=0, parse_dates=['Date'], index_col=0)
close = x.Close
</code>```

And this is how it looks like .head():

```<code>Date
2020-05-27    8854.32
2020-05-26    8844.42
2020-05-25    8899.31
2020-05-24    8715.73
2020-05-23    9181.76
</code>```

There is a little problem with this is and that the most recent date is located at the top, and the most oldest date is located at the bottom. Most dates are organized by the opposite, at least that's how the ARIMA model sees it.

So when I fit and predict using the model .forecast() , this was my output[0]:

```<code>[381.59648517]
</code>```

Which actually matches more to the .tail() of my data:

```<code>Date
2014-12-05    377.1
2014-12-04    377.1
2014-12-03    378.0
2014-12-02    378.0
2014-12-01    370.0
</code>```

Question/Problem:

How do I get around this, and order it in a way so that the ARIMA model knows which is my most recent date t and know to predict for t + 1

Also every time I fit my model, there were these two warnings. It may be relevant to the problem:

```<code>ValueWarning: A date index has been provided, but it has no associated frequency information and so will be ignored when e.g. forecasting.
ValueWarning: A date index has been provided, but it is not monotonic and so will be ignored when e.g. forecasting.
</code>```

答:
ValueWarning: A date index has been provided, but it has no associated frequency information and so will be ignored when e.g. forecasting. means that ARIMA doesn't understand the format of your data.

This should convert everything to DatetimeIndex with frequency as days.

```<code>x.index = pd.DatetimeIndex(x.index).to_period('D')
</code>```

ValueWarning: A date index has been provided, but it is not monotonic and so will be ignored when e.g. forecasting. means that the data isn't sorted, so type in this line:

```<code>x = x.sort_index()
</code>```

Body:
Info:

I am trying to predict the price of Bitcoin,as a test and to make it easier, 1 day after my most current datetime in my data. So t = 05/27/2020, t + 1 = 05/28/2020.

So I loaded my data:

x = pd.read_csv('btcdata.csv', header=0, parse_dates=['Date'], index_col=0)
close = x.Close

And this is how it looks like .head():

Date
2020-05-27    8854.32
2020-05-26    8844.42
2020-05-25    8899.31
2020-05-24    8715.73
2020-05-23    9181.76

There is a little problem with this is and that the most recent date is located at the top, and the most oldest date is located at the bottom. Most dates are organized by the opposite, at least that's how the ARIMA model sees it.

So when I fit and predict using the model .forecast() , this was my output[0]:

[381.59648517]

Which actually matches more to the .tail() of my data:

Date
2014-12-05    377.1
2014-12-04    377.1
2014-12-03    378.0
2014-12-02    378.0
2014-12-01    370.0

Question/Problem:

How do I get around this, and order it in a way so that the ARIMA model knows which is my most recent date t and know to predict for t + 1

Also every time I fit my model, there were these two warnings. It may be relevant to the problem:

ValueWarning: A date index has been provided, but it has no associated frequency information and so will be ignored when e.g. forecasting.
ValueWarning: A date index has been provided, but it is not monotonic and so will be ignored when e.g. forecasting.

Body:
ValueWarning: A date index has been provided, but it has no associated frequency information and so will be ignored when e.g. forecasting. means that ARIMA doesn't understand the format of your data.

This should convert everything to DatetimeIndex with frequency as days.

x.index = pd.DatetimeIndex(x.index).to_period('D')

ValueWarning: A date index has been provided, but it is not monotonic and so will be ignored when e.g. forecasting. means that the data isn't sorted, so type in this line:

x = x.sort_index()


问:
Angular Abstract control remove error
I want a way to remove a specific error from a form control and not clear all error.

```<code>control.setError({'firstError': true})
</code>```

and to remove that specific error like

```<code>control.removeError({'firstError}) and not control.setError({null})
</code>```

I tried

```<code>control.setError({'firstError': false})
</code>```

but didn't work.

Any help. Thanks

angular 4.1.1

答:
I came from this github issue and try this little workaround

Using Destructuring assignment

if ( control.hasError('errorToRemove') ) {
  const { errorToRemove, ...errors } = control.errors;
  control.setErrors(errors);
  control.updateValueAndValidity();
}
```

<p>You can also try the omit or pick <code>lodash</code> functions, to respectively omit or pick a series of errors that you can set to the control later.</p>

<pre class="lang-js prettyprint-override"><code>const errors = pick(control.errors, ['onlyErrorsToKeep']);
control.setErrors(errors);
control.updateValueAndValidity();
</code>```

const errors = omit(control.errors, ['allErrorsToRemove']);
control.setErrors(errors);
control.updateValueAndValidity();
```

Title: Angular Abstract control remove error

Body:
I want a way to remove a specific error from a form control and not clear all error.

control.setError({'firstError': true})

and to remove that specific error like

control.removeError({'firstError}) and not control.setError({null})

I tried

control.setError({'firstError': false})

but didn't work.

Any help. Thanks

angular 4.1.1

Body:
I came from this github issue and try this little workaround

Using Destructuring assignment

if ( control.hasError('errorToRemove') ) {
  const { errorToRemove, ...errors } = control.errors;
  control.setErrors(errors);
  control.updateValueAndValidity();
}

You can also try the omit or pick lodash functions, to respectively omit or pick a series of errors that you can set to the control later.

const errors = pick(control.errors, ['onlyErrorsToKeep']);
control.setErrors(errors);
control.updateValueAndValidity();

const errors = omit(control.errors, ['allErrorsToRemove']);
control.setErrors(errors);
control.updateValueAndValidity();


问:
How to prevent form submitting on other button is clicked rather than submit button in JavaScript
There is two buttons with in form, one is for submit the form and other one is close button for hide the form. But the problem is that form is also submitted on close button click, i don't want this behavior and i also don't want to place the close button outside the form.</p>

```<code><form class="add_form" id="add_list_form">
  <input type="text" class="form-control" placeholder="Enter list title..." id="list_value" />
  <div class="mt-2">
    <button type="submit" class="btn btn-sm btn-success mr-1" id="add_list_btn">Add List</button>
    <button class="btn btn-sm btn-danger" id="close_btn">close</button>
  </div>
</form>
<script>
  const add_list_form = document.querySelector('#add_list_form');
  add_list_form.addEventListener('submit',(e)=>{ e.preventDefault();
  console.log('form is submitted..') })
<script>
</code>```

答:
You can add type="button" to the button that you want to use to hide the form, which will remove the default behavior.

Here is an example,

const form = document.getElementById('form');

const otherBtn = document.getElementById('close-btn');

otherBtn.addEventListener('click', () => {console.log('Close button was clicked')});

form.addEventListener('submit', (e) => {e.preventDefault(); console.log("form got submitted")})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form id="form">
 <input type="email" placeholder="email"/>
 <input type="password" placeholder="password"/>
 <button type="submit">Submit</button>
 <button type="button" id="close-btn">Close</button>
<form/></code>```

Body:
There is two buttons with in form, one is for submit the form and other one is close button for hide the form. But the problem is that form is also submitted on close button click, i don't want this behavior and i also don't want to place the close button outside the form.

<form class="add_form" id="add_list_form">
  <input type="text" class="form-control" placeholder="Enter list title..." id="list_value" />

    <button type="submit" class="btn btn-sm btn-success mr-1" id="add_list_btn">Add List</button>
    <button class="btn btn-sm btn-danger" id="close_btn">close</button>

</form>

Body:
You can add type="button" to the button that you want to use to hide the form, which will remove the default behavior.

Here is an example,

const form = document.getElementById('form');

const otherBtn = document.getElementById('close-btn');

otherBtn.addEventListener('click', () => {console.log('Close button was clicked')});

form.addEventListener('submit', (e) => {e.preventDefault(); console.log("form got submitted")})

<form id="form">
 <input type="email" placeholder="email"/>
 <input type="password" placeholder="password"/>
 <button type="submit">Submit</button>
 <button type="button" id="close-btn">Close</button>
<form/>


问:
Grafana maps with rockset and dynamodb
Hy all, i am using grafana with rockset to collect real time series form our dynamodb database, but we have the next problem in the plugin maps.

My data with the next query:

```<code>select country,real,_event_time from commons.Players
</code>```

is

```<code>'US' '0.5' '2020-05-27T08:40:51.548000Z',
'UK' '0.2' '2020-05-27T08:40:50.548000Z'
</code>```

I read that i must pase the country code in the group by:

```<code>select
 country,sum(real) as total ,_event_time
from commons.Players
group by _event_time,country
</code>```

but this doesn't work, I select the correct type of location data (countries) but impossible to see anything.

I don't have problem with any kind of graph but in the map is impossible to my to see the information. I have read documentation and really I don't understand the query that i must use in this part to see the data.

Thanks for everything.

答:
You didn't post your panel configuration so it is blind guess. Use query:

```<code>SELECT
  _event_time AS "time",
  country AS "code",
  real
FROM commons.Players
</code>```

and configure Map Data Options->Location Data: countries to "translate" 2 letter country code to map coordinates.

Title: Grafana maps with rockset and dynamodb

Body:
Hy all, i am using grafana with rockset to collect real time series form our dynamodb database, but we have the next problem in the plugin maps.

My data with the next query:

select country,real,_event_time from commons.Players

is

'US' '0.5' '2020-05-27T08:40:51.548000Z',
'UK' '0.2' '2020-05-27T08:40:50.548000Z'

I read that i must pase the country code in the group by:

select
 country,sum(real) as total ,_event_time
from commons.Players
group by _event_time,country

but this doesn't work, I select the correct type of location data (countries) but impossible to see anything.

I don't have problem with any kind of graph but in the map is impossible to my to see the information. I have read documentation and really I don't understand the query that i must use in this part to see the data.

Thanks for everything.

Body:
You didn't post your panel configuration so it is blind guess. Use query:

SELECT
  _event_time AS "time",
  country AS "code",
  real
FROM commons.Players

and configure Map Data Options->Location Data: countries to "translate" 2 letter country code to map coordinates.


问:
ucwords but ignore words what are in BLOCK capitals?
I was wondering how to format the strings below to uppercase first letter of words but ingore words that are in uppercase already.

Examples

```<code>ABcd Efg = Abcd Efg
abcd EFG = Abcd EFG
</code>```

Could someone please give an example if it is possible.

Thanks

答: Just using $words = ucwords($words) should work for you.

Body:
I was wondering how to format the strings below to uppercase first letter of words but ingore words that are in uppercase already.

Examples

ABcd Efg = Abcd Efg
abcd EFG = Abcd EFG

Could someone please give an example if it is possible.

Thanks


问:
How do I print foreach loop content within a controller?
I have this function that prints a PDF containing the fetched data. I tried loading the view to generate the PDF but it did not work, so I opted on loading the HTML which works fine. The problem is how i will print out the contents within the foreach loop. How do Iprint the item values?

```<code>    public function create( Request $request ) {
    $items = DB::table( 'products' )->get();

    $pdf = App::make( 'dompdf.wrapper' );
    $pdf->loadHTML( '<div class="container">
  <div class="row">
      <div class="col-md-8 col-md-offset-2">
          <div class="panel panel-default">
              <div class="panel-heading">Dashboard</div>
              <div class="panel-body">
                  <table class="table">
                      <thead>
                          <th>Product Name</th>
                      </thead>
                      <tbody>
                      foreach ($items as $item=>$key)
                        <tr>
                            <td>$key->name</td>
                        </tr>
                    endforeach
                      </tbody>
                  </table>
              </div>
          </div>
      </div>
  </div>
  </div>
');
return $pdf->stream( 'quote.pdf' );
}
</code>```

I recieved this outputin the pdf

```<code>Dashboard
Product Name$key->name
</code>```

答:
change this

```<code>     $pdf->loadHTML( '<div class="container">
  <div class="row">
      <div class="col-md-8 col-md-offset-2">
          <div class="panel panel-default">
              <div class="panel-heading">Dashboard</div>
              <div class="panel-body">
                  <table class="table">
                      <thead>
                          <th>Product Name</th>
                      </thead>
                      <tbody>
                      foreach ($items as $item=>$key)
                        <tr>
                            <td>$key->name</td>
                        </tr>
                    endforeach
                      </tbody>
                  </table>
              </div>
          </div>
      </div>
  </div>
  </div>
');
</code>```

to

```<code>$html='<div class="container">
<div class="row">
    <div class="col-md-8 col-md-offset-2">
        <div class="panel panel-default">
            <div class="panel-heading">Dashboard</div>
            <div class="panel-body">
                <table class="table">
                    <thead>
                        <th>Product Name</th>
                    </thead>
                    <tbody>';

foreach ($items as $item=>$key) {
    $html.='<tr><td>'.$key->name.'</td></tr>';
}

$html.='  </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
    </div>';

$pdf->loadHTML($html);
</code>```

Body:
I have this function that prints a PDF containing the fetched data. I tried loading the view to generate the PDF but it did not work, so I opted on loading the HTML which works fine. The problem is how i will print out the contents within the foreach loop. How do Iprint the item values?

    public function create( Request $request ) {
    $items = DB::table( 'products' )->get();

    $pdf = App::make( 'dompdf.wrapper' );
    $pdf->loadHTML( '

Dashboard

                          Product Name

                      foreach ($items as $item=>$key)

                            $key->name

                    endforeach

');
return $pdf->stream( 'quote.pdf' );
}

I recieved this outputin the pdf

Dashboard
Product Name$key->name

Body:
change this

     $pdf->loadHTML( '<div class="container">
  <div class="row">
      <div class="col-md-8 col-md-offset-2">
          <div class="panel panel-default">
              <div class="panel-heading">Dashboard</div>
              <div class="panel-body">
                  <table class="table">
                      <thead>
                          <th>Product Name</th>
                      </thead>
                      <tbody>
                      foreach ($items as $item=>$key)
                        <tr>
                            <td>$key->name</td>
                        </tr>
                    endforeach
                      </tbody>
                  </table>
              </div>
          </div>
      </div>
  </div>
  </div>
');

to

$html='<div class="container">
<div class="row">
    <div class="col-md-8 col-md-offset-2">
        <div class="panel panel-default">
            <div class="panel-heading">Dashboard</div>
            <div class="panel-body">
                <table class="table">
                    <thead>
                        <th>Product Name</th>
                    </thead>
                    <tbody>';

foreach ($items as $item=>$key) {
    $html.='<tr><td>'.$key->name.'</td></tr>';
}

$html.='  </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
    </div>';

$pdf->loadHTML($html);


问:
How to optimize performance with CREATE, PUT, and DELETE requests on MongoDB?
I have a database named "reviews" with a 9.7GB size. It has a collection name products. I was able to optimize the READ request using indexing technical by running the command db.products.ensureIndex({product_name: 1}); When I run the following command db.products.find({product_name:"nobis"}).explain("executionStats"); in MongoDB terminal, it shows that my execution time reduces from 28334ms to 3301ms.

I have the following 2 questions:

1) How do I use explain("executionStats"); on CREATE, PUT and DELETE requests? For example, I got this following error [thread1] TypeError: db.products.insert(...).explain is not a function when I tried to use the following insert function

```<code>db.products.insert({"product_id": 10000002,"product_name": "tissue","review": [{"review_id": 30000001,"user": {"user_id": 30000001,"firstname": "Peter","lastname": "Chen","gender": "Male","nickname": "Superman","email": "hongkongbboy@gmail.com","password": "123"},"opinion": "It's good","text": "It's bad","rating_overall": 3,"doesRecommended": true,"rating_size": "a size too big","rating_width": "Slightly wide","rating_comfort": "Uncomfortable","rating_quality": "What I expected","isHelpful": 23,"isNotHelpful": 17,"created_at": "2007-10-19T09:03:29.967Z","review_photo_path": [{"review_photo_id": 60000001,"review_photo_url": "https://sdcuserphotos.s3.us-west-1.amazonaws.com/741.jpg"}, {"review_photo_id": 60000002,"review_photo_url": "https://sdcuserphotos.s3.us-west-1.amazonaws.com/741.jpg"}]}, {"review_id": 30000002,"user": {"user_id": 30000002,"firstname": "Peter","lastname": "Chen","gender": "Male","nickname": "Superman","email": "hongkongbboy@gmail.com","password": "123"},"opinion": "It's good","text": "It's bad","rating_overall": 3,"doesRecommended": true,"rating_size": "a size too big","rating_width": "Slightly wide","rating_comfort": "Uncomfortable","rating_quality": "What I expected","isHelpful": 23,"isNotHelpful": 17,"created_at": "2007-10-19T09:03:29.967Z","review_photo_path": [{"review_photo_id": 60000003,"review_photo_url": "https://sdcuserphotos.s3.us-west-1.amazonaws.com/741.jpg"}]}]}).explain("executionStats");
</code>```

2) Is there any performance Optimization method I can use for the CREATE, PUT and DELETE requests? For example, I am able to use POSTMAN to get the response time of a DELETE request, but the response time takes 38.73seconds.

```<code>const deleteReview = (request, response) => {
    const id = parseInt(request.params.id);
    Model.ProductModel.findOneAndDelete({ "review.review_id": id}, (error, results) => {
        if (error) {
            response.status(500).send(error);
        } else {
            response.status(200).send(results);
        }
    });
};
</code>```

This is my MongoDB schema:

```<code>const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/reviews', { useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true });
const Schema = mongoose.Schema;
const productSchema = new Schema({
    product_id: { type: Number, required: true, unique: true },
    product_name: { type: String, required: true, unique: true },
    review: [{
        review_id: { type: Number, required: true, unique: true },
        user: {
            user_id: { type: Number },
            firstname: { type: String },
            lastname: { type: String },
            gender: { type: String, enum: ['Male', 'Female', 'Other'] },
            nickname: { type: String },
            email: { type: String, required: true },
            password: { type: String, required: true },
        },
        opinion: { type: String, required: true },
        text: { type: String },
        rating_overall: { type: Number, min: 1, max: 5, required: true },
        doesRecommended: { type: Boolean, required: true },
        rating_size: { type: String, enum: ['a size too small', '1/2 a size too small', 'Perfect', '1/2 a size too big', 'a size too big'], required: true },
        rating_width: { type: String, enum: ['Too narrow', 'Slightly narrow', 'Perfect', 'Slightly wide', 'Too wide'], required: true },
        rating_comfort: { type: String, enum: ['Uncomfortable', 'Slightly uncomfortable', 'Ok', 'Comfortable', 'Perfect'], required: true },
        rating_quality: { type: String, enum: ['Poor', 'Below average', 'What I expected', 'Pretty great', 'Perfect'], required: true },
        isHelpful: { type: Number, required: true, default: 0 },
        isNotHelpful: { type: Number, required: true, default: 0 },
        created_at: { type: Date, required: true },
        review_photo_path: [{
            review_photo_id: { type: Number },
            review_photo_url: { type: String }
        }]
    }]
});
const ProductModel = mongoose.model('product', productSchema);
module.exports = { ProductModel };
</code>```

答:
If you do not have one, ensure you have an index of review.review_id on your products collection. You're using that to look up what to delete so it should be indexed.

I read your deleteReview function as deleting the product document that contains the review, not just removing the individual review -- is that what you expect?

You should be able to just $pull the review from the reviews array to get rid of it.

You can use explain on an update like so:

```<code>db.products.explain().update({...}, {...});
</code>```

See: https://docs.mongodb.com/manual/reference/method/db.collection.explain/

You can explain:

aggregate()

count()

find()

remove()

update()

distinct()

findAndModify()

Body:
I have a database named "reviews" with a 9.7GB size. It has a collection name products. I was able to optimize the READ request using indexing technical by running the command db.products.ensureIndex({product_name: 1}); When I run the following command db.products.find({product_name:"nobis"}).explain("executionStats"); in MongoDB terminal, it shows that my execution time reduces from 28334ms to 3301ms.

I have the following 2 questions:

1) How do I use explain("executionStats"); on CREATE, PUT and DELETE requests? For example, I got this following error [thread1] TypeError: db.products.insert(...).explain is not a function when I tried to use the following insert function

db.products.insert({"product_id": 10000002,"product_name": "tissue","review": [{"review_id": 30000001,"user": {"user_id": 30000001,"firstname": "Peter","lastname": "Chen","gender": "Male","nickname": "Superman","email": "hongkongbboy@gmail.com","password": "123"},"opinion": "It's good","text": "It's bad","rating_overall": 3,"doesRecommended": true,"rating_size": "a size too big","rating_width": "Slightly wide","rating_comfort": "Uncomfortable","rating_quality": "What I expected","isHelpful": 23,"isNotHelpful": 17,"created_at": "2007-10-19T09:03:29.967Z","review_photo_path": [{"review_photo_id": 60000001,"review_photo_url": "https://sdcuserphotos.s3.us-west-1.amazonaws.com/741.jpg"}, {"review_photo_id": 60000002,"review_photo_url": "https://sdcuserphotos.s3.us-west-1.amazonaws.com/741.jpg"}]}, {"review_id": 30000002,"user": {"user_id": 30000002,"firstname": "Peter","lastname": "Chen","gender": "Male","nickname": "Superman","email": "hongkongbboy@gmail.com","password": "123"},"opinion": "It's good","text": "It's bad","rating_overall": 3,"doesRecommended": true,"rating_size": "a size too big","rating_width": "Slightly wide","rating_comfort": "Uncomfortable","rating_quality": "What I expected","isHelpful": 23,"isNotHelpful": 17,"created_at": "2007-10-19T09:03:29.967Z","review_photo_path": [{"review_photo_id": 60000003,"review_photo_url": "https://sdcuserphotos.s3.us-west-1.amazonaws.com/741.jpg"}]}]}).explain("executionStats");

2) Is there any performance Optimization method I can use for the CREATE, PUT and DELETE requests? For example, I am able to use POSTMAN to get the response time of a DELETE request, but the response time takes 38.73seconds.

const deleteReview = (request, response) => {
    const id = parseInt(request.params.id);
    Model.ProductModel.findOneAndDelete({ "review.review_id": id}, (error, results) => {
        if (error) {
            response.status(500).send(error);
        } else {
            response.status(200).send(results);
        }
    });
};

This is my MongoDB schema:

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/reviews', { useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true });
const Schema = mongoose.Schema;
const productSchema = new Schema({
    product_id: { type: Number, required: true, unique: true },
    product_name: { type: String, required: true, unique: true },
    review: [{
        review_id: { type: Number, required: true, unique: true },
        user: {
            user_id: { type: Number },
            firstname: { type: String },
            lastname: { type: String },
            gender: { type: String, enum: ['Male', 'Female', 'Other'] },
            nickname: { type: String },
            email: { type: String, required: true },
            password: { type: String, required: true },
        },
        opinion: { type: String, required: true },
        text: { type: String },
        rating_overall: { type: Number, min: 1, max: 5, required: true },
        doesRecommended: { type: Boolean, required: true },
        rating_size: { type: String, enum: ['a size too small', '1/2 a size too small', 'Perfect', '1/2 a size too big', 'a size too big'], required: true },
        rating_width: { type: String, enum: ['Too narrow', 'Slightly narrow', 'Perfect', 'Slightly wide', 'Too wide'], required: true },
        rating_comfort: { type: String, enum: ['Uncomfortable', 'Slightly uncomfortable', 'Ok', 'Comfortable', 'Perfect'], required: true },
        rating_quality: { type: String, enum: ['Poor', 'Below average', 'What I expected', 'Pretty great', 'Perfect'], required: true },
        isHelpful: { type: Number, required: true, default: 0 },
        isNotHelpful: { type: Number, required: true, default: 0 },
        created_at: { type: Date, required: true },
        review_photo_path: [{
            review_photo_id: { type: Number },
            review_photo_url: { type: String }
        }]
    }]
});
const ProductModel = mongoose.model('product', productSchema);
module.exports = { ProductModel };

Body:
If you do not have one, ensure you have an index of review.review_id on your products collection. You're using that to look up what to delete so it should be indexed.

I read your deleteReview function as deleting the product document that contains the review, not just removing the individual review -- is that what you expect?

You should be able to just $pull the review from the reviews array to get rid of it.

You can use explain on an update like so:

db.products.explain().update({...}, {...});

See: https://docs.mongodb.com/manual/reference/method/db.collection.explain/

You can explain:

aggregate()

count()

find()

remove()

update()

distinct()

findAndModify()


问:
How to display error in modal form using ajax and php if validation fail while redirecting to other page if success
i am working in a signin page which is a modal form when user click on a signin button a modal form appears
here is it

```<code><!-- Signin Window Code -->
            <div class="modal fade" id="signup" tabindex="-1" role="dialog" aria-labelledby="myModalLabel2" aria-hidden="true">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-body">
                     <form action ="login.php" method="POST" id="frmLogin">
                            <div class="new-logwrap">
                                <div class="form-group">
                                <label>Email</label>
                                <div class="input-with-icon">
                                <input type="email" class="form-control" name="login_email" id = "email_login" placeholder="Enter Your Email" required>
                                <i class="theme-cl ti-email"></i>
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label>Password</label>
                                    <div class="input-with-icon">
                                        <input type="password" class="form-control" name="login_pass" id = "pass_login" placeholder="Enter Your Password" required>
                                        <i class="theme-cl ti-lock"></i>
                                    </div>
                                </div>
                                <div class="form-groups">
                                    <button type="submit" name="login" id="logBtn" class="btn btn-primary theme-bg full-width .login">Login</button>
                                </div>
                        <!-- error message will show here -->
                                <div id="ack"></div>
</code>```

and i am using ajax for validating whether user is validate or not

```<code>        $('button#logBtn').click(function(){

            if($("#email_login").val() == "" || $("#pass_login").val() == "")
             $("div#ack").html("please enter username or password");
            else
            $.post($("#frmLogin").attr("action"),
            $("#frmLogin :input").serializeArray(),
            function(data) {
                $("div#ack").html(data);
            });

            $("#frmLogin").submit(function (){
              return false;
            });
   });
</code>```

when user validation fails it display error on the modal form but the problem is if validation is success the page to be redirected is overwritten on the modal form i.e it is not redirecting but showing the next page on the modal itself
here is my php code

```<code><?php
// for testing purpose
require 'dbserver.inc.php';
$email     = mysqli_real_escape_string($conn,$_POST['login_email']);
$password  = mysqli_real_escape_string($conn,$_POST['login_pass']);
$sql = "SELECT count(*) from registergac1 WHERE (email='$email ' AND password = '$password')";
$res  = mysqli_query($conn,$sql);
$row = mysqli_fetch_array($res);
if($row[0] > 0)
{
    header("location: register.php"); //some page to redirect
}
else
{
    echo '<div class="alert alert-danger text-center" role="alert">
    Enter correct email or password!
  </div>';
}

?>
</code>```

答:
You cannot redirect from php directly as you have used ajax the response will send back to success-function of ajax. Now ,to solved this do like below :

Php Code :

```<code>if($row[0] > 0)
{
    echo "success";//send back to ajax
}
else
{
     echo "failed";//send back to ajax
}
</code>```

And check at your ajax side what values has come and depending on that either redirect or show error message.

Ajax Code :

```<code>$('button#logBtn').click(function() {

  if ($("#email_login").val() == "" || $("#pass_login").val() == "")
    $("div#ack").html("please enter username or password");
  else
    $.post($("#frmLogin").attr("action"),
      $("#frmLogin :input").serializeArray(),
      function(data) {
        var datas = $.trim(data); //remove whitespaces if any
        if (datas == "success") {
          window.location.href = "register.php"; //redirect
        } else {
          $("div#ack").html('<div class="alert alert-danger text-center" role="alert">Enter correct email or password!</div>'); //show error message
        }
      });

  $("#frmLogin").submit(function() {
    return false;
  });
});
</code>```

Body:
i am working in a signin page which is a modal form when user click on a signin button a modal form appears
here is it

                     <form action ="login.php" method="POST" id="frmLogin">

                                Email

                                <input type="email" class="form-control" name="login_email" id = "email_login" placeholder="Enter Your Email" required>

                                    Password

                                        <input type="password" class="form-control" name="login_pass" id = "pass_login" placeholder="Enter Your Password" required>

                                    <button type="submit" name="login" id="logBtn" class="btn btn-primary theme-bg full-width .login">Login</button>

and i am using ajax for validating whether user is validate or not

        $('button#logBtn').click(function(){

            if($("#email_login").val() == "" || $("#pass_login").val() == "")
             $("div#ack").html("please enter username or password");
            else
            $.post($("#frmLogin").attr("action"),
            $("#frmLogin :input").serializeArray(),
            function(data) {
                $("div#ack").html(data);
            });

            $("#frmLogin").submit(function (){
              return false;
            });
   });

when user validation fails it display error on the modal form but the problem is if validation is success the page to be redirected is overwritten on the modal form i.e it is not redirecting but showing the next page on the modal itself
here is my php code

<?php
// for testing purpose
require 'dbserver.inc.php';
$email     = mysqli_real_escape_string($conn,$_POST['login_email']);
$password  = mysqli_real_escape_string($conn,$_POST['login_pass']);
$sql = "SELECT count(*) from registergac1 WHERE (email='$email ' AND password = '$password')";
$res  = mysqli_query($conn,$sql);
$row = mysqli_fetch_array($res);
if($row[0] > 0)
{
    header("location: register.php"); //some page to redirect
}
else
{
    echo '

    Enter correct email or password!

';
}

?>

Body:
You cannot redirect from php directly as you have used ajax the response will send back to success-function of ajax. Now ,to solved this do like below :

Php Code :

if($row[0] > 0)
{
    echo "success";//send back to ajax
}
else
{
     echo "failed";//send back to ajax
}

And check at your ajax side what values has come and depending on that either redirect or show error message.

Ajax Code :

$('button#logBtn').click(function() {

  if ($("#email_login").val() == "" || $("#pass_login").val() == "")
    $("div#ack").html("please enter username or password");
  else
    $.post($("#frmLogin").attr("action"),
      $("#frmLogin :input").serializeArray(),
      function(data) {
        var datas = $.trim(data); //remove whitespaces if any
        if (datas == "success") {
          window.location.href = "register.php"; //redirect
        } else {
          $("div#ack").html('<div class="alert alert-danger text-center" role="alert">Enter correct email or password!</div>'); //show error message
        }
      });

  $("#frmLogin").submit(function() {
    return false;
  });
});


问:
how to parse json where key is variable using scala play json reader?
how can i access i4x-IITB-CS101-problem-33e4aac93dc84f368c93b1d08fa984fc_2_1 key and data inside this key ? I have never seen an example json reader that describes how the reader works when the key attribute is a variable such as below example.</p>

```<code>{
    "username": "batista",
    "event_type": "problem_check",
    "ip": "127.0.0.1",
    "event": {
        "submission": {
            "i4x-IITB-CS101-problem-33e4aac93dc84f368c93b1d08fa984fc_2_1": {
                "input_type": "choicegroup",
                "question": "",
                "response_type": "multiplechoiceresponse",
                "answer": "MenuInflater.inflate()",
                "variant": "",
                "correct": true
            }
        },
        "success": "correct",
        "grade": 1,
        "correct_map": {
            "i4x-IITB-CS101-problem-33e4aac93dc84f368c93b1d08fa984fc_2_1": {
                "hint": "",
                "hintmode": null,
                "correctness": "correct",
                "npoints": null,
                "msg": "",
                "queuestate": null
            }
        }
</code>```

答: You can deserialize these as a Map with String keys and values defined by a class that you have written a JSON reader for. Play JSON includes a built-in reader for Map types.

Body:
how can i access i4x-IITB-CS101-problem-33e4aac93dc84f368c93b1d08fa984fc_2_1 key and data inside this key ? I have never seen an example json reader that describes how the reader works when the key attribute is a variable such as below example.

{
    "username": "batista",
    "event_type": "problem_check",
    "ip": "127.0.0.1",
    "event": {
        "submission": {
            "i4x-IITB-CS101-problem-33e4aac93dc84f368c93b1d08fa984fc_2_1": {
                "input_type": "choicegroup",
                "question": "",
                "response_type": "multiplechoiceresponse",
                "answer": "MenuInflater.inflate()",
                "variant": "",
                "correct": true
            }
        },
        "success": "correct",
        "grade": 1,
        "correct_map": {
            "i4x-IITB-CS101-problem-33e4aac93dc84f368c93b1d08fa984fc_2_1": {
                "hint": "",
                "hintmode": null,
                "correctness": "correct",
                "npoints": null,
                "msg": "",
                "queuestate": null
            }
        }