问:
middleware updates request.user, but request.user becomes AnonymousUser in view
I wrote a simple JWT middleware to get user from the JWT. The method get_user_from_jwt returns a User object.

```<code># app.middlewares.py

class JwtMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        self.process_request(request)
        return self.get_response(request)

    def process_request(self, request):
        request.user = self.get_user_from_jwt(request.headers)

    def get_user_pk_from_jwt(self, auth_header: str) -> int:
        _, token = auth_header.split(' ')
        decoded_payload = jwt.decode(token, settings.SECRET_KEY)
        user_pk = decoded_payload.get('user_id', None)
        return user_pk

    def get_user_from_jwt(self, auth_header: str) -> User:
        auth_header = headers.get('Authorization', None)
        if auth_header:
            try:
                user_pk = self.get_user_pk_from_jwt(auth_header)
                user = get_object_or_404(User, pk=user_pk)
                return user
            except Exception as error:
                logging.error(f'Error decoding JWT due to: {str(error)}')
                raise AuthenticationFailed
        else:
            raise NotAuthenticated
</code>```

In settings:

```<code>MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    'whitenoise.middleware.WhiteNoiseMiddleware',
    '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',
    'app.middlewares.JwtMiddleware',
]
</code>```

When I log, request.user is set to the proper User instance at the middleware level, but once at a view, request.user becomes AnonymousUser. I tried switching the orders of the middlewares too. Any ideas how I can update what request.user means inside my views using a middleware?

答:
If you are using JWT token authentication with Django rest framework, then you need to update your authentication backends. The request.user is set automatically, when a user is authenticated. So if you are not authenticating the user, your request.user will be over-written by AnonymousUser.

You need to write an authentication Class, for example, JWTAuth, which should inherit the BaseAuthetication.

```<code>from rest_framework import authentication, exceptions

class JWTAuth(authentication.BaseAuthentication):
    authentication_header_prefix = 'Bearer'

    def authenticate(self, request):
        request.user = None
        auth_header = authentication.get_authorization_header(request).split()
        auth_header_prefix = self.authentication_header_prefix.lower()

        if not auth_header:
            return None

        prefix = auth_header[0].decode('utf-8')
        token = auth_header[1].decode('utf-8')

        if prefix.lower() != auth_header_prefix:
            return None

        return self._authenticate_credentials(request, token)

    def _authenticate_credentials(self, request, token):
        try:
            payload = jwt.decode(token, settings.SECRET_KEY)
        except:
            msg = 'Invalid authentication. Could not decode token.'
            raise exceptions.AuthenticationFailed(msg)

        try:
            user = User.objects.get(pk=payload['id'])

        except User.DoesNotExist:
            msg = 'No user matching this token was found.'
            raise exceptions.AuthenticationFailed(msg)

        if not user.is_active:
            msg = 'This user has been deactivated.'
            raise exceptions.AuthenticationFailed(msg)

        return user, token
</code>```

in your settings file

```<code>REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
                         'JWTAuth',
    )
</code>```

If you are also trying to customize your Login process, then you will have to update AUTHENTICATION_BACKENDS in your settings file.

Body:
I wrote a simple JWT middleware to get user from the JWT. The method get_user_from_jwt returns a User object.

# app.middlewares.py

class JwtMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        self.process_request(request)
        return self.get_response(request)

    def process_request(self, request):
        request.user = self.get_user_from_jwt(request.headers)

    def get_user_pk_from_jwt(self, auth_header: str) -> int:
        _, token = auth_header.split(' ')
        decoded_payload = jwt.decode(token, settings.SECRET_KEY)
        user_pk = decoded_payload.get('user_id', None)
        return user_pk

    def get_user_from_jwt(self, auth_header: str) -> User:
        auth_header = headers.get('Authorization', None)
        if auth_header:
            try:
                user_pk = self.get_user_pk_from_jwt(auth_header)
                user = get_object_or_404(User, pk=user_pk)
                return user
            except Exception as error:
                logging.error(f'Error decoding JWT due to: {str(error)}')
                raise AuthenticationFailed
        else:
            raise NotAuthenticated

In settings:

MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    'whitenoise.middleware.WhiteNoiseMiddleware',
    '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',
    'app.middlewares.JwtMiddleware',
]

When I log, request.user is set to the proper User instance at the middleware level, but once at a view, request.user becomes AnonymousUser. I tried switching the orders of the middlewares too. Any ideas how I can update what request.user means inside my views using a middleware?

Body:
If you are using JWT token authentication with Django rest framework, then you need to update your authentication backends. The request.user is set automatically, when a user is authenticated. So if you are not authenticating the user, your request.user will be over-written by AnonymousUser.

You need to write an authentication Class, for example, JWTAuth, which should inherit the BaseAuthetication.

from rest_framework import authentication, exceptions

class JWTAuth(authentication.BaseAuthentication):
    authentication_header_prefix = 'Bearer'

    def authenticate(self, request):
        request.user = None
        auth_header = authentication.get_authorization_header(request).split()
        auth_header_prefix = self.authentication_header_prefix.lower()

        if not auth_header:
            return None

        prefix = auth_header[0].decode('utf-8')
        token = auth_header[1].decode('utf-8')

        if prefix.lower() != auth_header_prefix:
            return None

        return self._authenticate_credentials(request, token)

    def _authenticate_credentials(self, request, token):
        try:
            payload = jwt.decode(token, settings.SECRET_KEY)
        except:
            msg = 'Invalid authentication. Could not decode token.'
            raise exceptions.AuthenticationFailed(msg)

        try:
            user = User.objects.get(pk=payload['id'])

        except User.DoesNotExist:
            msg = 'No user matching this token was found.'
            raise exceptions.AuthenticationFailed(msg)

        if not user.is_active:
            msg = 'This user has been deactivated.'
            raise exceptions.AuthenticationFailed(msg)

        return user, token

in your settings file

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
                         'JWTAuth',
    )

If you are also trying to customize your Login process, then you will have to update AUTHENTICATION_BACKENDS in your settings file.


来源: stackexchange

问:
What is the point of SSE2 instructions such as orpd?
The orpd instruction is a "bitwise logical OR of packed double precision floating point values". Doesn't this do exactly the same thing as por ("bitwise logical OR")? If so, what's the point of having it?

答:
Remember that SSE1 orps came first.  (Well actually MMX por mm, mm/mem came even before SSE1.)

Having the same opcode with a new prefix be the SSE2 orpd instruction makes sense for hardware decoder logic, I guess, just like movapd vs. movaps.  Several instructions like this are redundant between between ps and pd versions, but some aren't, like addps vs. addpd or unpcklps vs. unpcklpd being different shuffles.

The reason for SSE2 also introducing 66 0F EB /r  por xmm,xmm/mem is at least partly for consistency with MMX 0F EB /r  por mm, mm/mem, again same opcode with a new mandatory prefix.  Just like paddb mm, mm vs. paddb xmm, xmm.

But also for the possibility of different bypass-forwarding domains for vec-integer vs. FP.  Different microarchitectures have had different behaviours for how they actually decoded and ran those different instructions.  Some ran all the XMM or instructions the same way, creating extra latency for forwarding between FP and simd-integer domains.

No CPUs have ever actually had different fowarding domains for FP-float vs. FP-double, so yes, movapd and orpd are in practice useless wastes of space that you should never use.  Use the smaller orps encoding instead.

(Or with VEX encoding it doesn't matter; vorps and vorpd are the same size: 2 byte prefix + opcode + modrm ...)

por vs. orps

For more about bypass delay when using por between FP math instructions like addps, or orps between SIMD-integer insns like paddb, see

Do I get a performance penalty when mixing SSE integer/float SIMD instructions

What's the difference between logical SSE intrinsics?

Difference between the AVX instructions vxorpd and vpxor

Does using mix of pxor and xorps affect performance?

Is there any situation where using MOVDQU and MOVUPD is better than MOVUPS?

Choosing SSE instruction execution domains in mixed contexts - pre-Skylake, integer versions have better throughput.

And in case anyone was wondering, the answer to the other interpretation of the title: bitwise booleans on FP values are mostly used to set, clear, or toggle the sign bit.  Or to do stuff with cmpps/pd masks like blending.

ContentLicense: CC BY-SA 4.0


问:
requests.Session() load cookies from CookieJar
How can I load a CookieJar to a new requests.Session object?

```<code>cj = cookielib.MozillaCookieJar("mycookies.txt")
s = requests.Session()
</code>```

This is what I create, now the session will store cookies, but I want it to have my cookies from the file
(The session should load the cookieJar).
How can this be achieved?

I searched the documentation but I can only find code examples and they are never loading a cookieJar, just saving cookies during one session.

答:
Python 3.x code, fully working and well-implemented example. The code is self-explanatory.

This code properly handles "session cookies", preserving them between runs. By default, those are not saved to disk, which means that most websites would require you to constantly login between runs. But with the technique below, all session cookies are kept too!

This is the code you are looking for.

import os
import pathlib
import requests
from http.cookiejar import MozillaCookieJar

cookiesFile = str(pathlib.Path(__file__).parent.absolute() / "cookies.txt")  # Places "cookies.txt" next to the script file.
cj = MozillaCookieJar(cookiesFile)
if os.path.exists(cookiesFile):  # Only attempt to load if the cookie file exists.
    cj.load(ignore_discard=True, ignore_expires=True)  # Loads session cookies too (expirydate=0).

s = requests.Session()
s.headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36",
    "Accept-Language": "en-US,en"
}
s.cookies = cj  # Tell Requests session to use the cookiejar.

# DO STUFF HERE WHICH REQUIRES THE PERSISTENT COOKIES...
s.get("https://www.somewebsite.com/")

cj.save(ignore_discard=True, ignore_expires=True)  # Saves session cookies too (expirydate=0).
```

ContentLicense: CC BY-SA 3.0

Body:
How can I load a CookieJar to a new requests.Session object?

cj = cookielib.MozillaCookieJar("mycookies.txt")
s = requests.Session()

This is what I create, now the session will store cookies, but I want it to have my cookies from the file
(The session should load the cookieJar).
How can this be achieved?

I searched the documentation but I can only find code examples and they are never loading a cookieJar, just saving cookies during one session.


问:
Trying to use function from external .py file
I am using import DiGraph to import my external file and trying to run the following code:

prediction = DiGraph.remove_duplicates(make_trips(G, source='c1', target=['c2', 'c3']))

but I get NameError: name 'make_trips' is not defined

All the names are how they appear in my external file and it is even identical code besides the prediction =. What am I missing?

*Edit:
Thanks, Gilch, Kartikeya Sharma, and Nishat for the explanations.

答:
you can import your external function like this

```<code>from <module> import <function>
</code>```

So if your make_trip function is inside make_trip.py file then you can import like this

```<code>from make_trip import make_trip
</code>```

Body:
you can import your external function like this

from <module> import <function>

So if your make_trip function is inside make_trip.py file then you can import like this

from make_trip import make_trip


问:
How to style away the thin border in Google Maps Autocomplete search bar [React Native]
I'm trying to create a borderless search bar from react-native-google-places-autocomplete but I can't seem to get the border or shadow or whatever it may be to disappear (image below).

Search bar rendering with border

This is the style code from the image. I've tried shadowOpacity: 0, translucent shadowColor, and setting a solid border with a translucent color.

```<code>styles = {{
            textInputContainer: {
                width: 370,
                backgroundColor: 'rgba(0,0,0,0)',
                borderColor: 'rgba(0,0,0,0)'
                }
</code>```

Anyone out there successfully styled this border away? Thanks!

答:
```<code>import { GooglePlacesAutocomplete } from "react-native-google-places-autocomplete";
<GooglePlacesAutocomplete
 styles={{
  textInputContainer: {
   backgroundColor: "#fff0",
   borderWidth: 1,
   borderColor: Colors.snowDarkest,
   borderRadius: 3,
   padding: 0,
   justifyContent: "flex-start",
   alignItems: "flex-start",
   width: "100%",
  },
  textInput: {
   color: "#000",
   padding: 0,
   margin: 0,
  },
 }}
/>
</code>```

If you are talking about background color then you can use this code. I am not sure which border you are pointing towards anyway hope this helps you out

Body:
I'm trying to create a borderless search bar from react-native-google-places-autocomplete but I can't seem to get the border or shadow or whatever it may be to disappear (image below).

Search bar rendering with border

This is the style code from the image. I've tried shadowOpacity: 0, translucent shadowColor, and setting a solid border with a translucent color.

styles = {{
            textInputContainer: {
                width: 370,
                backgroundColor: 'rgba(0,0,0,0)',
                borderColor: 'rgba(0,0,0,0)'
                }

Anyone out there successfully styled this border away? Thanks!

Body:
import { GooglePlacesAutocomplete } from "react-native-google-places-autocomplete";
<GooglePlacesAutocomplete
 styles={{
  textInputContainer: {
   backgroundColor: "#fff0",
   borderWidth: 1,
   borderColor: Colors.snowDarkest,
   borderRadius: 3,
   padding: 0,
   justifyContent: "flex-start",
   alignItems: "flex-start",
   width: "100%",
  },
  textInput: {
   color: "#000",
   padding: 0,
   margin: 0,
  },
 }}
/>

If you are talking about background color then you can use this code. I am not sure which border you are pointing towards anyway hope this helps you out


问:
TypeError: argument of type 'int' is not iterable in indexing
Why does my code print: TypeError: argument of type 'int' is not iterable, whenever I run it? I have the following lists given below. What I am trying to do is to get the element/s in O then find its match in J. After finding the match, the index is obtained. Using this index, I will find its corresponding value in R.

```<code>    J = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    R = [[0, 0], [4, 3], [2, 0], [2, 1], [0, 3], [1, 1], [1, 2], [2, 1], [0, 3], [2, 2], [0, 0]]
    O = J[0]

    R_demand = [d for a, d in zip(J, R) if a in O]
    print(R_demand)
</code>```

For the code above, since O = 1 in J, I should get R_demand = [0, 0] as my answer. All values in lists are integers.

答: When you write the condition a in o, then o should be an iterable sequence which in your case is a number. So, it is arising an error ( int is not iterable).</p>

Body:
Why does my code print: TypeError: argument of type 'int' is not iterable, whenever I run it? I have the following lists given below. What I am trying to do is to get the element/s in O then find its match in J. After finding the match, the index is obtained. Using this index, I will find its corresponding value in R.

    J = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    R = [[0, 0], [4, 3], [2, 0], [2, 1], [0, 3], [1, 1], [1, 2], [2, 1], [0, 3], [2, 2], [0, 0]]
    O = J[0]

    R_demand = [d for a, d in zip(J, R) if a in O]
    print(R_demand)

For the code above, since O = 1 in J, I should get R_demand = [0, 0] as my answer. All values in lists are integers.


问:
DJL is unable to find MXNet Engine, troubleshooting doesn't help me
I have now spent way too much time trying to resolve this on my own, but I seem unable to do this on my own. I wanted to try out DJL, looked at some examples and into the tutorial, and was very excited about it because it seems like a very modern, simple and versatile library. However, I ran into a problem I am unable to solve.

DJL proposes using its MXNet Engine as default engine in the tutorial. It is included via the maven dependency ai.djl.mxnet:mxnet-engine:0.5.0. When running the sample code from the tutorial, I encounter the following error message:

```<code>[main] WARN ai.djl.mxnet.engine.MxEngine - Failed to load MXNet native library
java.lang.UnsatisfiedLinkError: Unable to load library 'mxnet':
Das angegebene Modul wurde nicht gefunden.

Das angegebene Modul wurde nicht gefunden.

Das angegebene Modul wurde nicht gefunden.

Native library (win32-x86-64/mxnet.dll) not found in resource path (D:\dev\DJL Test\target\classes;D:\maven\repo\ai\djl\api\0.5.0\api-0.5.0.jar;D:\maven\repo\com\google\code\gson\gson\2.8.5\gson-2.8.5.jar;D:\maven\repo\org\apache\commons\commons-compress\1.20\commons-compress-1.20.jar;D:\maven\repo\ai\djl\basicdataset\0.5.0\basicdataset-0.5.0.jar;D:\maven\repo\ai\djl\model-zoo\0.5.0\model-zoo-0.5.0.jar;D:\maven\repo\ai\djl\mxnet\mxnet-engine\0.5.0\mxnet-engine-0.5.0.jar;D:\maven\repo\net\java\dev\jna\jna\5.3.0\jna-5.3.0.jar;D:\maven\repo\org\slf4j\slf4j-api\1.7.26\slf4j-api-1.7.26.jar;D:\maven\repo\org\slf4j\slf4j-simple\1.7.22\slf4j-simple-1.7.22.jar)
    at com.sun.jna.NativeLibrary.loadLibrary(NativeLibrary.java:302)
    at com.sun.jna.NativeLibrary.getInstance(NativeLibrary.java:455)
    at com.sun.jna.Library$Handler.<init>(Library.java:192)
    at com.sun.jna.Native.load(Native.java:596)
    at com.sun.jna.Native.load(Native.java:570)
    at ai.djl.mxnet.jna.LibUtils.loadLibrary(LibUtils.java:68)
    at ai.djl.mxnet.jna.JnaUtils.<clinit>(JnaUtils.java:69)
    at ai.djl.mxnet.engine.MxEngine.newInstance(MxEngine.java:45)
    at ai.djl.mxnet.engine.MxEngineProvider.<clinit>(MxEngineProvider.java:21)
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:490)
    at java.base/java.util.ServiceLoader$ProviderImpl.newInstance(ServiceLoader.java:779)
    at java.base/java.util.ServiceLoader$ProviderImpl.get(ServiceLoader.java:721)
    at java.base/java.util.ServiceLoader$3.next(ServiceLoader.java:1394)
    at ai.djl.engine.Engine.initEngine(Engine.java:45)
    at ai.djl.engine.Engine.<clinit>(Engine.java:40)
    at ai.djl.basicdataset.Mnist$Builder.<init>(Mnist.java:175)
    at ai.djl.basicdataset.Mnist.builder(Mnist.java:66)
    at Main.main(Main.java:28)
    Suppressed: java.lang.UnsatisfiedLinkError: Das angegebene Modul wurde nicht gefunden.

        at com.sun.jna.Native.open(Native Method)
        at com.sun.jna.NativeLibrary.loadLibrary(NativeLibrary.java:191)
        ... 20 more
    Suppressed: java.lang.UnsatisfiedLinkError: Das angegebene Modul wurde nicht gefunden.

        at com.sun.jna.Native.open(Native Method)
        at com.sun.jna.NativeLibrary.loadLibrary(NativeLibrary.java:204)
        ... 20 more
    Suppressed: java.lang.UnsatisfiedLinkError: Das angegebene Modul wurde nicht gefunden.

        at com.sun.jna.Native.open(Native Method)
        at com.sun.jna.NativeLibrary.loadLibrary(NativeLibrary.java:265)
        ... 20 more
    Suppressed: java.io.IOException: Native library (win32-x86-64/mxnet.dll) not found in resource path (D:\dev\DJL Test\target\classes;D:\maven\repo\ai\djl\api\0.5.0\api-0.5.0.jar;D:\maven\repo\com\google\code\gson\gson\2.8.5\gson-2.8.5.jar;D:\maven\repo\org\apache\commons\commons-compress\1.20\commons-compress-1.20.jar;D:\maven\repo\ai\djl\basicdataset\0.5.0\basicdataset-0.5.0.jar;D:\maven\repo\ai\djl\model-zoo\0.5.0\model-zoo-0.5.0.jar;D:\maven\repo\ai\djl\mxnet\mxnet-engine\0.5.0\mxnet-engine-0.5.0.jar;D:\maven\repo\net\java\dev\jna\jna\5.3.0\jna-5.3.0.jar;D:\maven\repo\org\slf4j\slf4j-api\1.7.26\slf4j-api-1.7.26.jar;D:\maven\repo\org\slf4j\slf4j-simple\1.7.22\slf4j-simple-1.7.22.jar)
        at com.sun.jna.Native.extractFromResourcePath(Native.java:1095)
        at com.sun.jna.NativeLibrary.loadLibrary(NativeLibrary.java:276)
        ... 20 more
Exception in thread "main" ai.djl.engine.EngineException: No deep learning engine found.
Please refer to https://github.com/awslabs/djl/blob/master/docs/development/troubleshooting.md for more details.
    at ai.djl.engine.Engine.getInstance(Engine.java:90)
    at ai.djl.basicdataset.Mnist$Builder.<init>(Mnist.java:175)
    at ai.djl.basicdataset.Mnist.builder(Mnist.java:66)
    at Main.main(Main.java:28)
</code>```

(Please excuse the partially German error messages, I believe this occurs because MXNet is loaded via JNA and the native windows code uses a different locale. "Das angegebene Modul wurde nicht gefunden" means "the specified module was not found"). Now I do understand what this error is trying to tell me: DJL needs a deep learning engine and tries to load MXNet using JNA, but does not find the DLL. The error message provides a link to the troubleshooting doc of DJL which should resolve my issues. But I couldn't figure it out even with this helper. Here are the steps I considered / tried:

Step 1: First of all, the troubleshooting tells me that MXNet is automatically downloaded / installed or whatever by DJL:

By default, DJL is running on the MXNet engine. We use mxnet-mkl on CPU machines and mxnet-cu102mkl on GPU machines. mkl means Intel-MKLDNN is enabled. cu102 means Nvidia CUDA Toolkit version 10.2 is enabled.
  You don't need to download and install MXNet separately. It's automatically done when you build the DJL project by running the ./gradlew build command.

Now I have never worked with gradle, I always use maven. I did not run the command because if I copy it into the terminal, it tells me that . is not a valid command. Is ./gradlew build automatically executed when I build and run my project in IntelliJ?

Step 2: The troubleshooting file provides some details on the "No deep learning engine found" exception. But I've gone through all steps and now I am even more confused:

The dependency is in my pom.xml and is also loaded and visible in my external libraries

I cannot resolve the "IntelliJ issue" like the troubleshooting tells me. It provides two options. The first one tells me to navigate to references-> Build Execution Deployment -> Build Tools -> Gradle and change the option Build and running using: to Gradle. The problem is that this option does not show up, and I also didn't find it elsewhere. The second option is to "navigate to the MXNet engine resources folder using the project view". This confuses me, because where can I access the MXNet engine resources folder? At least I can tell it is not included in my maven-downloaded jar, should it be there?

Step 3: The troubleshooting doc tells me that I can choose to install MXNet externally, which turned out to be very complicated. But I did it, and I set the MXNET_LIBRARY_PATH environment variable as specified. Still I get the same error.

So after all of this, I really don't know how to approach this problem, so I'm posting this question in order to possibly get some hints by people that are a little more proficient with this than me..

Thank you!

System and Applications:

Windows 10 Pro

Intel Core i5-7400 CPU, so I installed mkl and the mkl version of mxnet (mxnet-mkl)

AMD Radeon R9 380 Series, so no CUDA mxnet for me, sadly

mkl version 2020.1

MXNet version 1.5.0

Java 11 (OpenJDK 11)

Maven 3.6.3

DJL 0.5.0

JNA 5.3.0 (required for DJL)

Slf4J api 1.7.26 (required for DJL)

Slf4J simple 1.7.22 (required for DJL)

IntelliJ IDEA Ultimate 2020.1

答:
You need to include MXNet native dependency:
See example project's pom.xml file: https://github.com/awslabs/djl/blob/master/examples/pom.xml#L64-L72

For more detail about MXNet engine dependency, see: https://github.com/awslabs/djl/tree/master/mxnet/mxnet-engine#installation

For Windows, you can use: gradlew build in if you are using CMD, ./ is linux/mac convention, and should work if you are using gitbash on Windows.

Body:
I have now spent way too much time trying to resolve this on my own, but I seem unable to do this on my own. I wanted to try out DJL, looked at some examples and into the tutorial, and was very excited about it because it seems like a very modern, simple and versatile library. However, I ran into a problem I am unable to solve.

DJL proposes using its MXNet Engine as default engine in the tutorial. It is included via the maven dependency ai.djl.mxnet:mxnet-engine:0.5.0. When running the sample code from the tutorial, I encounter the following error message:

[main] WARN ai.djl.mxnet.engine.MxEngine - Failed to load MXNet native library
java.lang.UnsatisfiedLinkError: Unable to load library 'mxnet':
Das angegebene Modul wurde nicht gefunden.

Das angegebene Modul wurde nicht gefunden.

Das angegebene Modul wurde nicht gefunden.

Native library (win32-x86-64/mxnet.dll) not found in resource path (D:\dev\DJL Test\target\classes;D:\maven\repo\ai\djl\api\0.5.0\api-0.5.0.jar;D:\maven\repo\com\google\code\gson\gson\2.8.5\gson-2.8.5.jar;D:\maven\repo\org\apache\commons\commons-compress\1.20\commons-compress-1.20.jar;D:\maven\repo\ai\djl\basicdataset\0.5.0\basicdataset-0.5.0.jar;D:\maven\repo\ai\djl\model-zoo\0.5.0\model-zoo-0.5.0.jar;D:\maven\repo\ai\djl\mxnet\mxnet-engine\0.5.0\mxnet-engine-0.5.0.jar;D:\maven\repo\net\java\dev\jna\jna\5.3.0\jna-5.3.0.jar;D:\maven\repo\org\slf4j\slf4j-api\1.7.26\slf4j-api-1.7.26.jar;D:\maven\repo\org\slf4j\slf4j-simple\1.7.22\slf4j-simple-1.7.22.jar)
    at com.sun.jna.NativeLibrary.loadLibrary(NativeLibrary.java:302)
    at com.sun.jna.NativeLibrary.getInstance(NativeLibrary.java:455)
    at com.sun.jna.Library$Handler.<init>(Library.java:192)
    at com.sun.jna.Native.load(Native.java:596)
    at com.sun.jna.Native.load(Native.java:570)
    at ai.djl.mxnet.jna.LibUtils.loadLibrary(LibUtils.java:68)
    at ai.djl.mxnet.jna.JnaUtils.<clinit>(JnaUtils.java:69)
    at ai.djl.mxnet.engine.MxEngine.newInstance(MxEngine.java:45)
    at ai.djl.mxnet.engine.MxEngineProvider.<clinit>(MxEngineProvider.java:21)
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:490)
    at java.base/java.util.ServiceLoader$ProviderImpl.newInstance(ServiceLoader.java:779)
    at java.base/java.util.ServiceLoader$ProviderImpl.get(ServiceLoader.java:721)
    at java.base/java.util.ServiceLoader$3.next(ServiceLoader.java:1394)
    at ai.djl.engine.Engine.initEngine(Engine.java:45)
    at ai.djl.engine.Engine.<clinit>(Engine.java:40)
    at ai.djl.basicdataset.Mnist$Builder.<init>(Mnist.java:175)
    at ai.djl.basicdataset.Mnist.builder(Mnist.java:66)
    at Main.main(Main.java:28)
    Suppressed: java.lang.UnsatisfiedLinkError: Das angegebene Modul wurde nicht gefunden.

        at com.sun.jna.Native.open(Native Method)
        at com.sun.jna.NativeLibrary.loadLibrary(NativeLibrary.java:191)
        ... 20 more
    Suppressed: java.lang.UnsatisfiedLinkError: Das angegebene Modul wurde nicht gefunden.

        at com.sun.jna.Native.open(Native Method)
        at com.sun.jna.NativeLibrary.loadLibrary(NativeLibrary.java:204)
        ... 20 more
    Suppressed: java.lang.UnsatisfiedLinkError: Das angegebene Modul wurde nicht gefunden.

        at com.sun.jna.Native.open(Native Method)
        at com.sun.jna.NativeLibrary.loadLibrary(NativeLibrary.java:265)
        ... 20 more
    Suppressed: java.io.IOException: Native library (win32-x86-64/mxnet.dll) not found in resource path (D:\dev\DJL Test\target\classes;D:\maven\repo\ai\djl\api\0.5.0\api-0.5.0.jar;D:\maven\repo\com\google\code\gson\gson\2.8.5\gson-2.8.5.jar;D:\maven\repo\org\apache\commons\commons-compress\1.20\commons-compress-1.20.jar;D:\maven\repo\ai\djl\basicdataset\0.5.0\basicdataset-0.5.0.jar;D:\maven\repo\ai\djl\model-zoo\0.5.0\model-zoo-0.5.0.jar;D:\maven\repo\ai\djl\mxnet\mxnet-engine\0.5.0\mxnet-engine-0.5.0.jar;D:\maven\repo\net\java\dev\jna\jna\5.3.0\jna-5.3.0.jar;D:\maven\repo\org\slf4j\slf4j-api\1.7.26\slf4j-api-1.7.26.jar;D:\maven\repo\org\slf4j\slf4j-simple\1.7.22\slf4j-simple-1.7.22.jar)
        at com.sun.jna.Native.extractFromResourcePath(Native.java:1095)
        at com.sun.jna.NativeLibrary.loadLibrary(NativeLibrary.java:276)
        ... 20 more
Exception in thread "main" ai.djl.engine.EngineException: No deep learning engine found.
Please refer to https://github.com/awslabs/djl/blob/master/docs/development/troubleshooting.md for more details.
    at ai.djl.engine.Engine.getInstance(Engine.java:90)
    at ai.djl.basicdataset.Mnist$Builder.<init>(Mnist.java:175)
    at ai.djl.basicdataset.Mnist.builder(Mnist.java:66)
    at Main.main(Main.java:28)

(Please excuse the partially German error messages, I believe this occurs because MXNet is loaded via JNA and the native windows code uses a different locale. "Das angegebene Modul wurde nicht gefunden" means "the specified module was not found"). Now I do understand what this error is trying to tell me: DJL needs a deep learning engine and tries to load MXNet using JNA, but does not find the DLL. The error message provides a link to the troubleshooting doc of DJL which should resolve my issues. But I couldn't figure it out even with this helper. Here are the steps I considered / tried:

Step 1: First of all, the troubleshooting tells me that MXNet is automatically downloaded / installed or whatever by DJL:

By default, DJL is running on the MXNet engine. We use mxnet-mkl on CPU machines and mxnet-cu102mkl on GPU machines. mkl means Intel-MKLDNN is enabled. cu102 means Nvidia CUDA Toolkit version 10.2 is enabled.
  You don't need to download and install MXNet separately. It's automatically done when you build the DJL project by running the ./gradlew build command.

Now I have never worked with gradle, I always use maven. I did not run the command because if I copy it into the terminal, it tells me that . is not a valid command. Is ./gradlew build automatically executed when I build and run my project in IntelliJ?

Step 2: The troubleshooting file provides some details on the "No deep learning engine found" exception. But I've gone through all steps and now I am even more confused:

The dependency is in my pom.xml and is also loaded and visible in my external libraries

I cannot resolve the "IntelliJ issue" like the troubleshooting tells me. It provides two options. The first one tells me to navigate to references-> Build Execution Deployment -> Build Tools -> Gradle and change the option Build and running using: to Gradle. The problem is that this option does not show up, and I also didn't find it elsewhere. The second option is to "navigate to the MXNet engine resources folder using the project view". This confuses me, because where can I access the MXNet engine resources folder? At least I can tell it is not included in my maven-downloaded jar, should it be there?

Step 3: The troubleshooting doc tells me that I can choose to install MXNet externally, which turned out to be very complicated. But I did it, and I set the MXNET_LIBRARY_PATH environment variable as specified. Still I get the same error.

So after all of this, I really don't know how to approach this problem, so I'm posting this question in order to possibly get some hints by people that are a little more proficient with this than me..

Thank you!

System and Applications:

Windows 10 Pro

Intel Core i5-7400 CPU, so I installed mkl and the mkl version of mxnet (mxnet-mkl)

AMD Radeon R9 380 Series, so no CUDA mxnet for me, sadly

mkl version 2020.1

MXNet version 1.5.0

Java 11 (OpenJDK 11)

Maven 3.6.3

DJL 0.5.0

JNA 5.3.0 (required for DJL)

Slf4J api 1.7.26 (required for DJL)

Slf4J simple 1.7.22 (required for DJL)

IntelliJ IDEA Ultimate 2020.1


问:
Cassandra clustering key uniqueness
In the book Cassandra the definitive guide it is said that the combination of partition key and clustering key guarantees a unique record in the data base... i understand that the partition key is the one that guarantees unique of record  - the node where the record is stored. And the clustering key is for the sorting of the records. Can someone help me understand this?
thank and sorry for the question...</p>

答:
Single partition key (without clustering key) is primary key which has to be unique.

A partition key + clustering key has to be unique but it doesn't mean that either partition key or a clustering key has to be unique alone.

You can insert

(a,b) (first record)

(a,c) (same partition key with the first record)

(d,b) (same clustering key with the first record)

When you insert (a,b) again then it will update the non primary key values for existing primary key.

In the following example userid is partition key and date is clustering key.

cqlsh:play> CREATE TABLE example (userid int, date int, name text, PRIMARY KEY (userid, date));
cqlsh:play> INSERT INTO example (userid, date, name) VALUES (1, 20200530, 'a');
cqlsh:play> INSERT INTO example (userid, date, name) VALUES (1, 20200531, 'a');
cqlsh:play> INSERT INTO example (userid, date, name) VALUES (2, 20200531, 'a');
cqlsh:play> SELECT * FROM example;

 userid | date     | name
--------+----------+------
      1 | 20200530 |    a
      1 | 20200531 |    a
      2 | 20200531 |    a

(3 rows)
cqlsh:play> INSERT INTO example (userid, date, name) VALUES (2, 20200531, 'b');
cqlsh:play> SELECT * FROM example;

 userid | date     | name
--------+----------+------
      1 | 20200530 |    a
      1 | 20200531 |    a
      2 | 20200531 |    b

(3 rows)
cqlsh:play>
```

Title: Cassandra clustering key uniqueness


问:
How to do pd.fillna() with condition
Am trying to do a fillna with if condition

```<code>Fimport pandas as pd
df = pd.DataFrame(data={'a':[1,None,3,None],'b':[4,None,None,None]})
print df

df[b].fillna(value=0, inplace=True) only if df[a] is None
print df

  a   b
0 1   4
1 NaN NaN
2 3   NaN
3 NaN NaN
</code>```

##What i want to acheive

```<code>  a   b
0 1   4
1 NaN 0
2 3   NaN
3 NaN 0
</code>```

Please help

答:
You can chain both conditions for test mising values with & for bitwise AND and then replace values to 0:

```<code>df.loc[df.a.isna() & df.b.isna(), 'b'] = 0
#alternative
df.loc[df[['a', 'b']].isna().all(axis=1), 'b'] = 0
print (df)
     a    b
0  1.0  4.0
1  NaN  0.0
2  3.0  NaN
3  NaN  0.0
</code>```

Or you can use fillna with one condition:

```<code>df.loc[df.a.isna(), 'b'] = df.b.fillna(0)
</code>```

Title: How to do pd.fillna() with condition

Body:
Am trying to do a fillna with if condition

Fimport pandas as pd
df = pd.DataFrame(data={'a':[1,None,3,None],'b':[4,None,None,None]})
print df

df[b].fillna(value=0, inplace=True) only if df[a] is None
print df

  a   b
0 1   4
1 NaN NaN
2 3   NaN
3 NaN NaN

##What i want to acheive

  a   b
0 1   4
1 NaN 0
2 3   NaN
3 NaN 0

Please help

Body:
You can chain both conditions for test mising values with & for bitwise AND and then replace values to 0:

df.loc[df.a.isna() & df.b.isna(), 'b'] = 0
#alternative
df.loc[df[['a', 'b']].isna().all(axis=1), 'b'] = 0
print (df)
     a    b
0  1.0  4.0
1  NaN  0.0
2  3.0  NaN
3  NaN  0.0

Or you can use fillna with one condition:

df.loc[df.a.isna(), 'b'] = df.b.fillna(0)


问:
Checking if float is equivalent to an integer value in python
In Python 3, I am checking whether a given value is triangular, that is, it can be represented as n * (n + 1) / 2 for some positive integer n.

Can I just write:

```<code>import math

def is_triangular1(x):
    num = (1 / 2) * (math.sqrt(8 * x + 1) - 1)
    return int(num) == num
</code>```

Or do I need to do check within a tolerance instead?

```<code>epsilon = 0.000000000001
def is_triangular2(x):
    num = (1 / 2) * (math.sqrt(8 * x + 1) - 1)
    return abs(int(num) - num) < epsilon
</code>```

I checked that both of the functions return same results for x up to 1,000,000. But I am not sure if generally speaking int(x) == x will always correctly determine whether a number is integer, because of the cases when for example 5 is represented as 4.99999999999997 etc.

As far as I know, the second way is the correct one if I do it in C, but I am not sure about Python 3.

答:
It is hard to argue with standards.

In C99 and POSIX, the standard for rounding a float to an int is defined by nearbyint() The important concept is the direction of rounding and the locale specific rounding convention.

Assuming the convention is common rounding, this is the same as the C99 convention in Python:

```<code>#!/usr/bin/python

import math

infinity = math.ldexp(1.0, 1023) * 2

def nearbyint(x):
   """returns the nearest int as the C99 standard would"""

   # handle NaN
   if x!=x:
       return x

   if x >= infinity:
       return infinity

   if x <= -infinity:
       return -infinity

   if x==0.0:
       return x

   return math.floor(x + 0.5)
</code>```

If you want more control over rounding, consider using the Decimal module and choose the rounding convention you wish to employ. You may want to use Banker's Rounding for example.

Once you have decided on the convention, round to an int and compare to the other int.

Body:
In Python 3, I am checking whether a given value is triangular, that is, it can be represented as n * (n + 1) / 2 for some positive integer n.

Can I just write:

import math

def is_triangular1(x):
    num = (1 / 2) * (math.sqrt(8 * x + 1) - 1)
    return int(num) == num

Or do I need to do check within a tolerance instead?

epsilon = 0.000000000001
def is_triangular2(x):
    num = (1 / 2) * (math.sqrt(8 * x + 1) - 1)
    return abs(int(num) - num) < epsilon

I checked that both of the functions return same results for x up to 1,000,000. But I am not sure if generally speaking int(x) == x will always correctly determine whether a number is integer, because of the cases when for example 5 is represented as 4.99999999999997 etc.

As far as I know, the second way is the correct one if I do it in C, but I am not sure about Python 3.

Body:
It is hard to argue with standards.

In C99 and POSIX, the standard for rounding a float to an int is defined by nearbyint() The important concept is the direction of rounding and the locale specific rounding convention.

Assuming the convention is common rounding, this is the same as the C99 convention in Python:

#!/usr/bin/python

import math

infinity = math.ldexp(1.0, 1023) * 2

def nearbyint(x):
   """returns the nearest int as the C99 standard would"""

   # handle NaN
   if x!=x:
       return x

   if x >= infinity:
       return infinity

   if x <= -infinity:
       return -infinity

   if x==0.0:
       return x

   return math.floor(x + 0.5)

If you want more control over rounding, consider using the Decimal module and choose the rounding convention you wish to employ. You may want to use Banker's Rounding for example.

Once you have decided on the convention, round to an int and compare to the other int.


问:
Scrapy HTTP Request error when trying to send request login on nike site
I'm trying to make a sneaker bot for Nike sneakers brazil site (nike.com.br/snkrs) using scraping. First, I tried to make a spider that logs into the site, I see that have some login requests on the network so I tried to send the ones that I think are needed.

Here is the full code of the spider:

```<code><https://pastebin.com/Xke6kP1P>
</code>```

But when I tried to crawl the spider to test I get some http request errors like 400 Bad Request, 401 POST HTTP Request not handle or allowed or 403 Forbidden.
Here is the full error code:

```<code><https://pastebin.com/ge9pr6qx>
</code>```

I already using proxy ip and user agent rotation middlewares but still get these errors.

答:
One way to try to solve this problem is editing your settings.py.

You should copy headers that come with a response.
In order to achieve an access with success copy all this parameters from a default web browser.

Access the developer tools (F12) network tab, do a navigation in site, copy information from some request in that domain.

settings.py

```<code>USER_AGENT = '' #copy user-agent from browser

# Override the default request headers:
DEFAULT_REQUEST_HEADERS = {
  'Accept': '', #copy this info from browser
  'Accept-Language': '', #copy this info from browser
}
</code>```

Here is a good tutorial (2017) that explains in detail how can you handle navigation errors, old but you can get the main idea. This tutorial is also linked in scrapy web site resources section.

Hope it helps.

Body:
I'm trying to make a sneaker bot for Nike sneakers brazil site (nike.com.br/snkrs) using scraping. First, I tried to make a spider that logs into the site, I see that have some login requests on the network so I tried to send the ones that I think are needed.

Here is the full code of the spider:

<https://pastebin.com/Xke6kP1P>

But when I tried to crawl the spider to test I get some http request errors like 400 Bad Request, 401 POST HTTP Request not handle or allowed or 403 Forbidden.
Here is the full error code:

<https://pastebin.com/ge9pr6qx>

I already using proxy ip and user agent rotation middlewares but still get these errors.

Body:
One way to try to solve this problem is editing your settings.py.

You should copy headers that come with a response.
In order to achieve an access with success copy all this parameters from a default web browser.

Access the developer tools (F12) network tab, do a navigation in site, copy information from some request in that domain.

settings.py

USER_AGENT = '' #copy user-agent from browser

# Override the default request headers:
DEFAULT_REQUEST_HEADERS = {
  'Accept': '', #copy this info from browser
  'Accept-Language': '', #copy this info from browser
}

Here is a good tutorial (2017) that explains in detail how can you handle navigation errors, old but you can get the main idea. This tutorial is also linked in scrapy web site resources section.

Hope it helps.


问:
couldn't find "libconscrypt_jni.so"
I followed https://stackoverflow.com/a/61560589/6447123 to support TLS 1.2 on Android 4.x

It worked before , but currently I don't know why I have the following error

```<code>2020-05-31 09:13:08.567 8735-8735/com.my_app E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.my_app, PID: 8735
    java.lang.UnsatisfiedLinkError: dalvik.system.PathClassLoader[DexPathList[[zip file "/data/app/com.my_app-jygsQuNVVcvr6CclEptz5A==/base.apk"],nativeLibraryDirectories=[/data/app/com.my_app-jygsQuNVVcvr6CclEptz5A==/lib/arm64, /data/app/com.my_app-jygsQuNVVcvr6CclEptz5A==/base.apk!/lib/arm64-v8a, /system/lib64, /system/vendor/lib64]]] couldn't find "libconscrypt_jni.so"
        at java.lang.Runtime.loadLibrary0(Runtime.java:1011)
        at java.lang.System.loadLibrary(System.java:1657)
        at org.conscrypt.NativeCryptoJni.init(NativeCryptoJni.java:28)
        at org.conscrypt.NativeCrypto.<clinit>(NativeCrypto.java:63)
        at org.conscrypt.NativeCrypto.checkAvailability(NativeCrypto.java:80)
        at org.conscrypt.OpenSSLProvider.<init>(OpenSSLProvider.java:58)
        at org.conscrypt.OpenSSLProvider.<init>(OpenSSLProvider.java:51)
        at org.conscrypt.OpenSSLProvider.<init>(OpenSSLProvider.java:47)
        at com.my_app.MainApplication.onCreate(MainApplication.java:51)
        at android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:1119)
        at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5877)
        at android.app.ActivityThread.-wrap1(Unknown Source:0)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1690)
        at android.os.Handler.dispatchMessage(Handler.java:105)
        at android.os.Looper.loop(Looper.java:173)
        at android.app.ActivityThread.main(ActivityThread.java:6698)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:782)
</code>```

It crashed on a phone that works before

答:
In you class, you should add static block to add conscrypt as security provider

```<code>static {
    // add Conscrypt in list of security providers for device
    Security.addProvider(Conscrypt.newProvider());
}
</code>```

Title: couldn't find "libconscrypt_jni.so"

Body:
I followed https://stackoverflow.com/a/61560589/6447123 to support TLS 1.2 on Android 4.x

It worked before , but currently I don't know why I have the following error

2020-05-31 09:13:08.567 8735-8735/com.my_app E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.my_app, PID: 8735
    java.lang.UnsatisfiedLinkError: dalvik.system.PathClassLoader[DexPathList[[zip file "/data/app/com.my_app-jygsQuNVVcvr6CclEptz5A==/base.apk"],nativeLibraryDirectories=[/data/app/com.my_app-jygsQuNVVcvr6CclEptz5A==/lib/arm64, /data/app/com.my_app-jygsQuNVVcvr6CclEptz5A==/base.apk!/lib/arm64-v8a, /system/lib64, /system/vendor/lib64]]] couldn't find "libconscrypt_jni.so"
        at java.lang.Runtime.loadLibrary0(Runtime.java:1011)
        at java.lang.System.loadLibrary(System.java:1657)
        at org.conscrypt.NativeCryptoJni.init(NativeCryptoJni.java:28)
        at org.conscrypt.NativeCrypto.<clinit>(NativeCrypto.java:63)
        at org.conscrypt.NativeCrypto.checkAvailability(NativeCrypto.java:80)
        at org.conscrypt.OpenSSLProvider.<init>(OpenSSLProvider.java:58)
        at org.conscrypt.OpenSSLProvider.<init>(OpenSSLProvider.java:51)
        at org.conscrypt.OpenSSLProvider.<init>(OpenSSLProvider.java:47)
        at com.my_app.MainApplication.onCreate(MainApplication.java:51)
        at android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:1119)
        at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5877)
        at android.app.ActivityThread.-wrap1(Unknown Source:0)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1690)
        at android.os.Handler.dispatchMessage(Handler.java:105)
        at android.os.Looper.loop(Looper.java:173)
        at android.app.ActivityThread.main(ActivityThread.java:6698)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:782)

It crashed on a phone that works before

Body:
In you class, you should add static block to add conscrypt as security provider

static {
    // add Conscrypt in list of security providers for device
    Security.addProvider(Conscrypt.newProvider());
}


问:
Request failed with status code 404 error
I'm trying to build a Spotify web app now. I'd like to display an artist's albums when an user clicks the artist from its search result. When I try the code below, I get Request failed with status code 404.

SingerBox.js

```<code>import React, { Component } from "react";
import Modal from "react-bootstrap/Modal";
import ImageNotFound from "../../ImageNotFound.jpg";
import "../../App.css";
import { Link } from "react-router-dom";

import Albums from "../Albums/Albums";
import axios from "axios";

const SingerBox = (props) => {
  const { images, name, id } = props;

  //check if the image array is empty since some artists' image data provided by the API call are empty
  const singer_img = images.length === 0 ? ImageNotFound : images[0].url;

  const handleClick = () => {
    axios
      .get(`http://localhost:4000/${id}`, {
        params: {
          id: id,
        },
      })
      .then((res) => {
        console.log(`Returned album data from the server: ${res}`);
        return <Albums albums={res.data} />;
      })
      .catch((err) => console.log(err));
  };

  return (
    <>
      <Link to={`/albums/${id}`}>
        <div className="box" onClick={() => handleClick()}>
          <div>
            <img className="singer-img" src={singer_img} alt="Card image" />
            {name}
          </div>
        </div>
      </Link>
    </>
  );
};

export default SingerBox;

</code>```

Albums.js

```<code>import React, { Component } from "react";
import { useParams } from "react-router-dom";
import axios from "axios";
import AlbumCard from "./AlbumCard";

const Albums = () => {
  const { id } = useParams();

  return (
    <div className="container" style={{ color: "white" }}>
      {`${id}'s albums`}
    </div>
  );
};

export default Albums;

</code>```

Server.js

```<code>const express = require("express");
const SpotifyWebApi = require("spotify-web-api-node");
const bodyParser = require("body-parser");
const cors = require("cors");
const app = express();
const port = 4000 || process.env.PORT;

require("dotenv").config();

app.use(express.json());
app.use(cors());
app.use(bodyParser.urlencoded({ extended: true }));

// Create the api object with the credentials
var spotifyApi = new SpotifyWebApi({
  clientId: process.env.CLIENT_ID,
  clientSecret: process.env.CLIENT_SECRET,
});

// Retrieve an access token.
spotifyApi.clientCredentialsGrant().then(
  function (data) {
    console.log("The access token expires in " + data.body["expires_in"]);

    // Save the access token so that it's used in future calls
    spotifyApi.setAccessToken(data.body["access_token"]);
  },
  function (err) {
    console.log("Something went wrong when retrieving an access token", err);
  }
);

app.post("/search_result", (req, res) => {
  spotifyApi
    .searchArtists(req.body.keyword)
    .then(function (data) {
      let search_res = data.body.artists.items;
      res.json(search_res);
      res.end();
    })
    .catch((err) => {
      console.log(err);
      res.status(500).send(err);
    });
});

app.get("/albums/:id", (req, res) => {
  console.log(req.params.id);
  spotifyApi.getArtistAlbums(req.params.id).then(function (data) {
    res.json(data.body);
    res.end();
  });
});

app.listen(port, () => console.log(`It's running on port ${port}`));
</code>```

I also want to know how I can improve the structure of my codes, like axios calls. They seem messy but I don't know where to start to fix them.

答:
In SingerBox component you are trying to make get on http://localhost:4000/${id} there is not such API in your server.js file. that's why you encounter a 404 error which means not found

```<code>  const handleClick = () => {
  axios
  .get(`http://localhost:4000/${id}`, {
    params: {
      id: id,
    },
  })
  .then((res) => {
    console.log(`Returned album data from the server: ${res}`);
    return <Albums albums={res.data} />;
  })
  .catch((err) => console.log(err));
 };
</code>```

Add in your server.js

```<code> app.get("/:id", (req, res) => {
   " your API logic"
  });
</code>```

Body:
I'm trying to build a Spotify web app now. I'd like to display an artist's albums when an user clicks the artist from its search result. When I try the code below, I get Request failed with status code 404.

SingerBox.js

import React, { Component } from "react";
import Modal from "react-bootstrap/Modal";
import ImageNotFound from "../../ImageNotFound.jpg";
import "../../App.css";
import { Link } from "react-router-dom";

import Albums from "../Albums/Albums";
import axios from "axios";

const SingerBox = (props) => {
  const { images, name, id } = props;

  //check if the image array is empty since some artists' image data provided by the API call are empty
  const singer_img = images.length === 0 ? ImageNotFound : images[0].url;

  const handleClick = () => {
    axios
      .get(`http://localhost:4000/${id}`, {
        params: {
          id: id,
        },
      })
      .then((res) => {
        console.log(`Returned album data from the server: ${res}`);
        return <Albums albums={res.data} />;
      })
      .catch((err) => console.log(err));
  };

  return (
    <>
      <Link to={`/albums/${id}`}>

 handleClick()}>

            {name}

      </Link>
    </>
  );
};

export default SingerBox;

Albums.js

import React, { Component } from "react";
import { useParams } from "react-router-dom";
import axios from "axios";
import AlbumCard from "./AlbumCard";

const Albums = () => {
  const { id } = useParams();

  return (

      {`${id}'s albums`}

  );
};

export default Albums;

Server.js

const express = require("express");
const SpotifyWebApi = require("spotify-web-api-node");
const bodyParser = require("body-parser");
const cors = require("cors");
const app = express();
const port = 4000 || process.env.PORT;

require("dotenv").config();

app.use(express.json());
app.use(cors());
app.use(bodyParser.urlencoded({ extended: true }));

// Create the api object with the credentials
var spotifyApi = new SpotifyWebApi({
  clientId: process.env.CLIENT_ID,
  clientSecret: process.env.CLIENT_SECRET,
});

// Retrieve an access token.
spotifyApi.clientCredentialsGrant().then(
  function (data) {
    console.log("The access token expires in " + data.body["expires_in"]);

    // Save the access token so that it's used in future calls
    spotifyApi.setAccessToken(data.body["access_token"]);
  },
  function (err) {
    console.log("Something went wrong when retrieving an access token", err);
  }
);

app.post("/search_result", (req, res) => {
  spotifyApi
    .searchArtists(req.body.keyword)
    .then(function (data) {
      let search_res = data.body.artists.items;
      res.json(search_res);
      res.end();
    })
    .catch((err) => {
      console.log(err);
      res.status(500).send(err);
    });
});

app.get("/albums/:id", (req, res) => {
  console.log(req.params.id);
  spotifyApi.getArtistAlbums(req.params.id).then(function (data) {
    res.json(data.body);
    res.end();
  });
});

app.listen(port, () => console.log(`It's running on port ${port}`));

I also want to know how I can improve the structure of my codes, like axios calls. They seem messy but I don't know where to start to fix them.

Body:
In SingerBox component you are trying to make get on http://localhost:4000/${id} there is not such API in your server.js file. that's why you encounter a 404 error which means not found

  const handleClick = () => {
  axios
  .get(`http://localhost:4000/${id}`, {
    params: {
      id: id,
    },
  })
  .then((res) => {
    console.log(`Returned album data from the server: ${res}`);
    return <Albums albums={res.data} />;
  })
  .catch((err) => console.log(err));
 };

Add in your server.js

 app.get("/:id", (req, res) => {
   " your API logic"
  });


问:
dynamic Javascript in asp.net
well. The problem i'm facing is i have my own custom control and i do a query , get records and dynamically add html controls to the page based on the data.

Now there's the problem of adding some dynamic javascript

I do this with the help of literal controls.

```<code><asp:Literal runat="server" ID="latEventToolTipJqueryScripts"></asp:Literal>
</code>```

This works like a charm

```<code><script language="javascript" type="text/javascript">
// <![CDATA[
    Sys.Application.add_load(WireEvents_<%=this.ID%>); // fix wiring for .NET ajax updatepanel
    $(WireEvents_<%=this.ID%>); // handle page load wiring

    function WireEvents_<%=this.ID%>() {
        <asp:Literal runat="server" ID="latEventToolTipJqueryScripts"></asp:Literal>
    }

// ]]>
</script>
</code>```

I add the literal text dynamically from code behind.

However, when placing the control in an updatepanel, the postbacks don't update the script.

EDIT: The Sys.Application.add_load rewires the necessary functions just fine with the updatepanel. The problem is that the script that needs to be in place of the literal, doesn't update when in an updatepanel.

I've tried the ClientScript.RegisterStartupScript but it has the same effect as with the literal control trick. Any help?

---------------------------SOLVED (tnx to Pranay Rana)----------------------------------

Got rid of the literal in the ascx side. as well as the Sys.Application.add_load

now it's only in the code behind. The thing that was throwing me off was the JQuery thing.

```<code>this.strBuilderJS.Append( "<script language='javascript' type='text/javascript'>" +
                                "$(WireEvents_" + this.ID + ");" +
                                "function WireEvents_" + this.ID + "(){"+
                                "    alert('stuff');");

this.strBuilderJS.Append(       "}</script>");
</code>```

and then

```<code>ScriptManager.RegisterStartupScript(this, this.GetType(), "strBuilderJS", strBuilderJS.ToString(), false);
</code>```

答:
Make use of ScriptManager.RegisterStartupScript() to register your script...may resolve problem ...

Check this resolve your problem : Add JavaScript programmatically using RegisterStartupScript during an Asynchronous postback

Title: dynamic Javascript in asp.net

Body:
well. The problem i'm facing is i have my own custom control and i do a query , get records and dynamically add html controls to the page based on the data.

Now there's the problem of adding some dynamic javascript

I do this with the help of literal controls.

<asp:Literal runat="server" ID="latEventToolTipJqueryScripts"></asp:Literal>

This works like a charm

I add the literal text dynamically from code behind.

However, when placing the control in an updatepanel, the postbacks don't update the script.

EDIT: The Sys.Application.add_load rewires the necessary functions just fine with the updatepanel. The problem is that the script that needs to be in place of the literal, doesn't update when in an updatepanel.

I've tried the ClientScript.RegisterStartupScript but it has the same effect as with the literal control trick. Any help?

---------------------------SOLVED (tnx to Pranay Rana)----------------------------------

Got rid of the literal in the ascx side. as well as the Sys.Application.add_load

now it's only in the code behind. The thing that was throwing me off was the JQuery thing.

this.strBuilderJS.Append( "");

and then

ScriptManager.RegisterStartupScript(this, this.GetType(), "strBuilderJS", strBuilderJS.ToString(), false);


问:
CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. How to fix it in html?
I have created an HTML file, and there I have implemented a fetch request from Javascript. But is it saying blocked by CORS policy. How do I remove this error?

My code:

```<code>    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <!-- <meta name="viewport" content="width-device-width ,initial-scale=1.0"> -->
        <meta http-equiv="X-UA-Compatible" content="ie-edge">

        <script src="https://code.jquery.com/jquery-3.5.0.js" integrity="sha256-r/AaFHrszJtwpe+tHyNi/XCfMxYpbsRg2Uqn0x3s2zc=" crossorigin="anonymous"></script>
        <title>Document</title>

        <script type="text/javascript">
            fetch("http://ec2-13-233-168-148.ap-south-1.compute.amazonaws.com:8181/v1/youtube/detail?url=https://www.youtube.com/watch?v=FS9dkwhPypY").then(

                res=>{
                    res.json().then(
                        data=>{
                            console.log(data.videoDetails.keywords.length);
                console.log(data.videoDetails.thumbnail.thumbnails.length)

                        })
                    });

        </script>

    </head>
    <body>
      <div class="container">
      <table class="table table-stripped">
        <thead>
            <tr>

                <th>Url</th>
                <th> height</th>
            <th>width </th>
            </tr>
        </thead>

        <tbody id="th"></tbody>

      </table>
       <table class="table table-stripped">
        <thead>
          <tr>

            <th>Keyword</th>
          </tr>
        </thead>
        <tbody id="data"></tbody>
      </table>
    </div>
    </body>
    </html>
</code>```

My fetch request is not working in this condition. It says:

```<code>Access to fetch at 'http://ec2-13-233-168-148.ap-south-1.compute.amazonaws.com:8181/v1/youtube/detail?url=https://www.youtube.com/watch?v=FS9dkwhPypY' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
</code>```

How might I fix this issue ?

答:
This is normally happens when your client requesting a resource from a different endpoint (which is different from the your browser URL) other than the client's origin.

So, you will have to enable CORS from your backend web server to solve this problem. The configurations will be vary based on the web server you are using. Please go through below

For Apache

Add below line into your virtual host

```<code>Header set Access-Control-Allow-Origin "*"
</code>```

For Nginx

Add below line into your relevant nginx config file.

```<code>add_header Access-Control-Allow-Origin *;
</code>```

Body:
I have created an HTML file, and there I have implemented a fetch request from Javascript. But is it saying blocked by CORS policy. How do I remove this error?

My code:

    <!DOCTYPE html>

        <meta charset="UTF-8">

        <meta http-equiv="X-UA-Compatible" content="ie-edge">

        <title>Document</title>

                Url
                 height
            width

            Keyword

My fetch request is not working in this condition. It says:

Access to fetch at 'http://ec2-13-233-168-148.ap-south-1.compute.amazonaws.com:8181/v1/youtube/detail?url=https://www.youtube.com/watch?v=FS9dkwhPypY' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

How might I fix this issue ?

Body:
This is normally happens when your client requesting a resource from a different endpoint (which is different from the your browser URL) other than the client's origin.

So, you will have to enable CORS from your backend web server to solve this problem. The configurations will be vary based on the web server you are using. Please go through below

For Apache

Add below line into your virtual host

Header set Access-Control-Allow-Origin "*"

For Nginx

Add below line into your relevant nginx config file.

add_header Access-Control-Allow-Origin *;


问:
iterating over sys.argv[] (python)
I was trying to read several files from a command line argument using this iterating code, but i get a Type error: list indices must be integers or slices, not str

Can someone help me fix this

code:

```<code>for x in sys.argv[1::]
    fileobj = open(sys.argv[x], 'r')
    #read file
</code>```

答:
Type error: list indices must be integers or slices, not str: This means you are using a str for a list index. Where are you accessing a list index? It's at sys.argv[x]. So it's complaining that x is a str instead of an int.

That is because when you say for x in sys.argv[1::], x is the actual content of the list, which in this case are the actual file names. So you either need to say:

```<code>for x in sys.argv[1::]
    fileobj = open(x, 'r')
</code>```

or

```<code>for x in range(1, len(sys.argv))
    fileobj = open(sys.argv[x], 'r')
</code>```

The first one is considered more readable by most.

Title: iterating over sys.argv[] (python)

Body:
I was trying to read several files from a command line argument using this iterating code, but i get a Type error: list indices must be integers or slices, not str

Can someone help me fix this

code:

for x in sys.argv[1::]
    fileobj = open(sys.argv[x], 'r')
    #read file

Body:
Type error: list indices must be integers or slices, not str: This means you are using a str for a list index. Where are you accessing a list index? It's at sys.argv[x]. So it's complaining that x is a str instead of an int.

That is because when you say for x in sys.argv[1::], x is the actual content of the list, which in this case are the actual file names. So you either need to say:

for x in sys.argv[1::]
    fileobj = open(x, 'r')

or

for x in range(1, len(sys.argv))
    fileobj = open(sys.argv[x], 'r')

The first one is considered more readable by most.


问:
Extracting and replacing value in DataFrame
I'm trying to replaces the values from dictionary type to numeric value as the example below. How could I extract them and change the values in the DataFrame?

eg.)

```<code>{'kWh': '-107.368'} -> -107.368
{'kWh': '-143.982'} -> -143.982
</code>```

答:
The .apply() method works:

```<code>df[column] = df[column].apply(
   lambda x: float(x['kWh'])
)
</code>```

Body:
I'm trying to replaces the values from dictionary type to numeric value as the example below. How could I extract them and change the values in the DataFrame?

eg.)

{'kWh': '-107.368'} -> -107.368
{'kWh': '-143.982'} -> -143.982

Body:
The .apply() method works:

df[column] = df[column].apply(
   lambda x: float(x['kWh'])
)


问:
Update multiple columns based on the same list in PySpark dataframes
I am trying to update 3 columns based on text in a fourth column. Each updated column will have a different text.

For example, if the FreeText column has a value that falls into the category of a column, I want to change the column value to "1", the EditedCol column to the name of the column edited, and Match to "1".

Here is the code I am currently using. The parenthesis may be off because I wrote this up quickly, but that is not part of the issue. Is there a way to make it more efficient?

```<code>myList1="horse"
myList2="cheese"
myList3="soccer"

df=df.withColumn("Animal", F.when(F.col("FreeText).rlike(myList1), "Yes").otherwise(F.col("Animal"))
    ).withColumn("EditedCol", F.when(F.col("FreeText).rlike(myList1), "Animal").otherwise(F.col("EditedCol"))
    ).withColumn("Match", F.when(F.col("FreeText).rlike(myList1), "Yes").otherwise(F.col("Match")))

df=df.withColumn("Food", F.when(F.col("FreeText).rlike(myList2), "Yes").otherwise(F.col("Food"))
    ).withColumn("EditedCol", F.when(F.col("FreeText).rlike(myList2), "Food").otherwise(F.col("EditedCol"))
    ).withColumn("Match", F.when(F.col("FreeText).rlike(myList2), "Yes").otherwise(F.col("Match")))

df=df.withColumn("Sport", F.when(F.col("FreeText).rlike(myList3), "Yes").otherwise(F.col("Sport"))
    ).withColumn("EditedCol", F.when(F.col("FreeText).rlike(myList3), "Sport").otherwise(F.col("EditedCol"))
    ).withColumn("Match", F.when(F.col("FreeText).rlike(myList3), "Yes").otherwise(F.col("Match")))
</code>```

Edit:
Thank you, the following code worked:

```<code>myList = ["horse|donkey|monkey", "cheese|mango"]
myCols = ["Animals", "Food"]

for element, col in zip(myList, myCols):
    df = df.withColumn(col, F.when(F.col("FreeText").rlike(element), "Yes"
        ).otherwise(F.col(col))
    ).withColumn("EditedCol", F.when(F.col("FreeText").rlike(element), col
        ).otherwise(F.col("EditedCol"))
    ).withColumn("Match", F.when(F.col("FreeText").rlike(element), "Yes"
        ).otherwise(F.col("Match")))
</code>```

Now for the "EditedCol" variable, I am trying to concatenate the variable list if the keywords in "FreeText" match to more than 1 variable. For my code below, for some reason instead of listing the 2nd variable it just says "Yes". Please advise:

```<code>myList = ["horse|donkey|monkey", "cheese|mango"]
myCols = ["Animals", "Food"]

for element, col in zip(myList, myCols):
    df = df.withColumn(col, F.when(F.col("FreeText").rlike(element), "Yes"
        ).otherwise(F.col(col))
    ).withColumn("EditedCol", F.when((F.col("Overwrite_race_spec").isNull() & F.col("FreeText").rlike(element)), col
        ).otherwise(F.when(F.col("FreeText").rlike(element), F.concat(("EditedCol"), F.lit("; "), col)
        ).otherwise(F.col("EditedCol")))
    ).withColumn("Match", F.when(F.col("FreeText").rlike(element), "Yes"
        ).otherwise(F.col("Match")))
</code>```

答:
If by efficiency you meant code efficiency, then following will be more automated.</p>

```<code>myList = ["horse", "cheese", "soccer"]
myCols = ["Animal", "Food", "Match"]

for element, col in zip(myList, col):
    df = df.withColumn(col, F.when(F.col("FreeText).rlike(element), "Yes").otherwise(F.col(col))) \
            .withColumn("EditedCol", F.when(F.col("FreeText).rlike(element), col).otherwise(F.col("EditedCol"))) \
            .withColumn("Match", F.when(F.col("FreeText).rlike(element), "Yes").otherwise(F.col("Match")))
</code>```

Body:
I am trying to update 3 columns based on text in a fourth column. Each updated column will have a different text.

For example, if the FreeText column has a value that falls into the category of a column, I want to change the column value to "1", the EditedCol column to the name of the column edited, and Match to "1".

Here is the code I am currently using. The parenthesis may be off because I wrote this up quickly, but that is not part of the issue. Is there a way to make it more efficient?

myList1="horse"
myList2="cheese"
myList3="soccer"

df=df.withColumn("Animal", F.when(F.col("FreeText).rlike(myList1), "Yes").otherwise(F.col("Animal"))
    ).withColumn("EditedCol", F.when(F.col("FreeText).rlike(myList1), "Animal").otherwise(F.col("EditedCol"))
    ).withColumn("Match", F.when(F.col("FreeText).rlike(myList1), "Yes").otherwise(F.col("Match")))

df=df.withColumn("Food", F.when(F.col("FreeText).rlike(myList2), "Yes").otherwise(F.col("Food"))
    ).withColumn("EditedCol", F.when(F.col("FreeText).rlike(myList2), "Food").otherwise(F.col("EditedCol"))
    ).withColumn("Match", F.when(F.col("FreeText).rlike(myList2), "Yes").otherwise(F.col("Match")))

df=df.withColumn("Sport", F.when(F.col("FreeText).rlike(myList3), "Yes").otherwise(F.col("Sport"))
    ).withColumn("EditedCol", F.when(F.col("FreeText).rlike(myList3), "Sport").otherwise(F.col("EditedCol"))
    ).withColumn("Match", F.when(F.col("FreeText).rlike(myList3), "Yes").otherwise(F.col("Match")))

Edit:
Thank you, the following code worked:

myList = ["horse|donkey|monkey", "cheese|mango"]
myCols = ["Animals", "Food"]

for element, col in zip(myList, myCols):
    df = df.withColumn(col, F.when(F.col("FreeText").rlike(element), "Yes"
        ).otherwise(F.col(col))
    ).withColumn("EditedCol", F.when(F.col("FreeText").rlike(element), col
        ).otherwise(F.col("EditedCol"))
    ).withColumn("Match", F.when(F.col("FreeText").rlike(element), "Yes"
        ).otherwise(F.col("Match")))

Now for the "EditedCol" variable, I am trying to concatenate the variable list if the keywords in "FreeText" match to more than 1 variable. For my code below, for some reason instead of listing the 2nd variable it just says "Yes". Please advise:

myList = ["horse|donkey|monkey", "cheese|mango"]
myCols = ["Animals", "Food"]

for element, col in zip(myList, myCols):
    df = df.withColumn(col, F.when(F.col("FreeText").rlike(element), "Yes"
        ).otherwise(F.col(col))
    ).withColumn("EditedCol", F.when((F.col("Overwrite_race_spec").isNull() & F.col("FreeText").rlike(element)), col
        ).otherwise(F.when(F.col("FreeText").rlike(element), F.concat(("EditedCol"), F.lit("; "), col)
        ).otherwise(F.col("EditedCol")))
    ).withColumn("Match", F.when(F.col("FreeText").rlike(element), "Yes"
        ).otherwise(F.col("Match")))

Body:
If by efficiency you meant code efficiency, then following will be more automated.

myList = ["horse", "cheese", "soccer"]
myCols = ["Animal", "Food", "Match"]

for element, col in zip(myList, col):
    df = df.withColumn(col, F.when(F.col("FreeText).rlike(element), "Yes").otherwise(F.col(col))) \
            .withColumn("EditedCol", F.when(F.col("FreeText).rlike(element), col).otherwise(F.col("EditedCol"))) \
            .withColumn("Match", F.when(F.col("FreeText).rlike(element), "Yes").otherwise(F.col("Match")))


问:
How to deal with quotes around an argument in a function?
I have a function I am trying to make in R that looks like this:

```<code>diff_abund <- function(Data, Rank, Taxa) {
subset_taxa(Data, Rank == Taxa)
}

da= diff_abund(frbc1_02, Phylum, "Acidobacteria")
</code>```

And I get the error:

```<code>Error in eval(e, x, parent.frame()) : object 'Rank' not found
</code>```

The problem appears to be with the Rank == Taxa part. If I remove that from the function like so:

```<code>diff_abund <- function(Data) {

subset_taxa(Data, Phylum == "Acidobacteria")

}
da= diff_abund(frbc1_02)
</code>```

The function works normally. The dataset is an S4 object that only works in the package phyloseq. "Rank" is basically a group of vectors ranging from Kingdom down to Species. Not sure what you would call that. Any reason this could be happening?
Thank you,
Sam

答:
You need to substitute your condition and evaluate it in Data. I don't know subset_taxa, but this should work in the same way as substitute. In the following I use mtcars as example data, which comes with R.

```<code>diff_abund <- function(Data, Rank, Taxa) {
  cond <- substitute(Rank == Taxa)
  e <- eval(cond, Data)
  subset(Data, e)
}
diff_abund(mtcars, cyl, "6")
#                 mpg cyl  disp  hp drat    wt  qsec vs am gear carb
# Mazda RX4      21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4
# Mazda RX4 Wag  21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
# Hornet 4 Drive 21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
# Valiant        18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1
# Merc 280       19.2   6 167.6 123 3.92 3.440 18.30  1  0    4    4
# Merc 280C      17.8   6 167.6 123 3.92 3.440 18.90  1  0    4    4
# Ferrari Dino   19.7   6 145.0 175 3.62 2.770 15.50  0  1    5    6
</code>```

In your subquestion you probably want the arguments to be fixed and just define Taxa in the function call dynamically. You could change the order of the arguments, and define the fixed ones using =.

```<code>FX <- function(Taxa, Data=mtcars, Rank=mtcars$cyl) {
  subset(Data, eval(substitute(Rank == Taxa), Data))
}
FX("6")
#                 mpg cyl  disp  hp drat    wt  qsec vs am gear carb
# Mazda RX4      21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4
# Mazda RX4 Wag  21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
# Hornet 4 Drive 21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
# Valiant        18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1
# Merc 280       19.2   6 167.6 123 3.92 3.440 18.30  1  0    4    4
# Merc 280C      17.8   6 167.6 123 3.92 3.440 18.90  1  0    4    4
# Ferrari Dino   19.7   6 145.0 175 3.62 2.770 15.50  0  1    5    6
</code>```

Note: It is better not use F as function name, since it's shorthand for FALSE. You may check if a name is already in use using ?, e.g. ?F.

Body:
I have a function I am trying to make in R that looks like this:

diff_abund <- function(Data, Rank, Taxa) {
subset_taxa(Data, Rank == Taxa)
}

da= diff_abund(frbc1_02, Phylum, "Acidobacteria")

And I get the error:

Error in eval(e, x, parent.frame()) : object 'Rank' not found

The problem appears to be with the Rank == Taxa part. If I remove that from the function like so:

diff_abund <- function(Data) {

subset_taxa(Data, Phylum == "Acidobacteria")

}
da= diff_abund(frbc1_02)

The function works normally. The dataset is an S4 object that only works in the package phyloseq. "Rank" is basically a group of vectors ranging from Kingdom down to Species. Not sure what you would call that. Any reason this could be happening?
Thank you,
Sam

Body:
You need to substitute your condition and evaluate it in Data. I don't know subset_taxa, but this should work in the same way as substitute. In the following I use mtcars as example data, which comes with R.

diff_abund <- function(Data, Rank, Taxa) {
  cond <- substitute(Rank == Taxa)
  e <- eval(cond, Data)
  subset(Data, e)
}
diff_abund(mtcars, cyl, "6")
#                 mpg cyl  disp  hp drat    wt  qsec vs am gear carb
# Mazda RX4      21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4
# Mazda RX4 Wag  21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
# Hornet 4 Drive 21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
# Valiant        18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1
# Merc 280       19.2   6 167.6 123 3.92 3.440 18.30  1  0    4    4
# Merc 280C      17.8   6 167.6 123 3.92 3.440 18.90  1  0    4    4
# Ferrari Dino   19.7   6 145.0 175 3.62 2.770 15.50  0  1    5    6

In your subquestion you probably want the arguments to be fixed and just define Taxa in the function call dynamically. You could change the order of the arguments, and define the fixed ones using =.

FX <- function(Taxa, Data=mtcars, Rank=mtcars$cyl) {
  subset(Data, eval(substitute(Rank == Taxa), Data))
}
FX("6")
#                 mpg cyl  disp  hp drat    wt  qsec vs am gear carb
# Mazda RX4      21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4
# Mazda RX4 Wag  21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
# Hornet 4 Drive 21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
# Valiant        18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1
# Merc 280       19.2   6 167.6 123 3.92 3.440 18.30  1  0    4    4
# Merc 280C      17.8   6 167.6 123 3.92 3.440 18.90  1  0    4    4
# Ferrari Dino   19.7   6 145.0 175 3.62 2.770 15.50  0  1    5    6

Note: It is better not use F as function name, since it's shorthand for FALSE. You may check if a name is already in use using ?, e.g. ?F.


问:
integer constant long long int?
```<code>long long int
</code>```

It seems to be valid in C. but is this valid in c++?

答: Please keep in mind that like all other primitive types in C and C++, only the ranges for the values the primitives may contain are well-defined; the actual size of the primitive, in bits, is left up to the implementation. I have not had much experience using long long int, since I prefer using the types defined in the stdint.h header. If you need to be sure that the primitive is, for example, 64 bits long, you may want to consider using uint64_t or int64_t instead.

Title: integer constant long long int?

Body:
long long int

It seems to be valid in C. but is this valid in c++?


答:
Simply, Use Series.transform to transform the dictionaries to corresponding numeric value with key kWh inside dictionary:

```<code>df['544299'] = df['544299'].transform(lambda d: float(d.get('kWh', np.nan)))
</code>```

You can also use Series.str.get:

```<code>df['544299'] = df['544299'].str.get('kWh').astype(float).abs()
</code>```

Title: Extracting and replacing value in DataFrame

Body:
Simply, Use Series.transform to transform the dictionaries to corresponding numeric value with key kWh inside dictionary:

df['544299'] = df['544299'].transform(lambda d: float(d.get('kWh', np.nan)))

You can also use Series.str.get:

df['544299'] = df['544299'].str.get('kWh').astype(float).abs()


问:
The request was aborted: Could not create SSL/TLS secure channel
We are unable to connect to an HTTPS server using WebRequest because of this error message:

The request was aborted: Could not create SSL/TLS secure channel.

We know that the server doesn't have a valid HTTPS certificate with the path used, but to bypass this issue, we use the following code that we've taken from another StackOverflow post:

```<code>private void Somewhere() {
    ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(AlwaysGoodCertificate);
}

private static bool AlwaysGoodCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors policyErrors) {
   return true;
}
</code>```

The problem is that server never validates the certificate and fails with the above error. Does anyone have any idea of what I should do?

I should mention that a colleague and I performed tests a few weeks ago and it was working fine with something similar to what I wrote above. The only "major difference" we've found is that I'm using Windows 7 and he was using Windows XP.  Does that change something?

答:
none of this answer not working for me , the google chrome and postman work and handshake the server but ie and .net not working. in google chrome in security tab > connection show that encrypted and authenticated using ECDHE_RSA with P-256 and AES_256_GCM cipher suite to handshake with the server.

i install IIS Crypto and in cipher suites list on windows server 2012 R2 ican't find ECDHE_RSA with P-256 and AES_256_GCM cipher suite. then i update windows to the last version but the problem not solve. finally after searches i understood that windows server 2012 R2 not support GSM correctly and update my server to windows server 2016 and my problem solved.

Body:
We are unable to connect to an HTTPS server using WebRequest because of this error message:

The request was aborted: Could not create SSL/TLS secure channel.

We know that the server doesn't have a valid HTTPS certificate with the path used, but to bypass this issue, we use the following code that we've taken from another StackOverflow post:

private void Somewhere() {
    ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(AlwaysGoodCertificate);
}

private static bool AlwaysGoodCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors policyErrors) {
   return true;
}

The problem is that server never validates the certificate and fails with the above error. Does anyone have any idea of what I should do?

I should mention that a colleague and I performed tests a few weeks ago and it was working fine with something similar to what I wrote above. The only "major difference" we've found is that I'm using Windows 7 and he was using Windows XP.  Does that change something?


问:
exchanging SSL certificates in MQ keystores
I am trying to make an SSL connection between two MQ servers. In both of them I am using self signed certificates, I created one cert for QM_A(sender) and another for QM_V(receiver). Since the connection will be 'one-way message' I am not sure if I have to extract the public key from QM_A and import it in the keystore of the QM_V(receiver)?

Right now in the error logs of QM_V I found the error message:

```<code>AMQ9637: Channel is lacking a certificate.
</code>```

答:
Normally you would want both queue mangers to have certs and to validate and match the DN of each other's cert.

The TLS server end (RCVR) must have a cert, while the TLS client end (SDR) optionally needs a cert depending on the SSLCAUTH setting of the RCVR.

In all cases if the SDR queue manger (TLS client) has a cert the RCVR queue manager (TLS server) will validate the SDR cert is signed by a trusted cert, not expired and optionally check it is not revoked by querying a CRL or OCSP server.  The RCVR queue manger will also check if the SDR cert's DN matches any SSLPEER values specified [and if at MQ v8.0 or later that the cert issuer matches any SSLCERTI values specified].

This is the behavior you would want to prevent unauthorized connections to the RCVR.

The SDR queue manager will also validate the RCVR queue manger cert is signed by a trusted cert, not expired and optionally check it is not revoked by querying a CRL or OCSP server.  You can also configure a single SSLPEER value on the SDR side that must match the RCVR queue manger's cert.  This will help to prevent a MITM attack.

Body:
I am trying to make an SSL connection between two MQ servers. In both of them I am using self signed certificates, I created one cert for QM_A(sender) and another for QM_V(receiver). Since the connection will be 'one-way message' I am not sure if I have to extract the public key from QM_A and import it in the keystore of the QM_V(receiver)?

Right now in the error logs of QM_V I found the error message:

AMQ9637: Channel is lacking a certificate.


问:
Where to place a Provider Widget -- Flutter Provider Package
I am currently learning app development with Flutter and have started learning about the Provider package. I was having some difficulty and was getting the error:

"Could not find the correct Provider above this ... Widget"

I ended up moving the Provider widget to wrap around my MaterialApp widget instead of my Scaffold Widget, and that seemed to fix things.

That being said, I'm not sure why this fixed things. Are we supposed to put our Provider widget around our MaterialApp? If so, can someone please explain why this is needed? If not, can someone explain how to determine where to place the Provider widget in our tree?

答: Usually, the best place is where you moved it, in the MaterialApp. This is because since that is where the app starts, the node tree will have access to the provider everywhere.</p>


问:
B trees vs binary trees
If I am implementing in-memory(RAM) search operation with b trees, then would it be better in terms of caching or some other effects when compared with binary trees?

What I know is-

```<code>binary search tress---O(log n)
btrees ---------------O(c log n)
</code>```

there was a lot of discussion regarding that on various blogs.

答: B-trees differ from binary trees in that keys and pointers are clustered in memory, so you get somewhat better cache behavior both on disk and in memory. There is no difference in asymptotic (big-O) runtime, though.</p>

Title: B trees vs binary trees

Body:
If I am implementing in-memory(RAM) search operation with b trees, then would it be better in terms of caching or some other effects when compared with binary trees?

What I know is-

binary search tress---O(log n)
btrees ---------------O(c log n)

there was a lot of discussion regarding that on various blogs.


问:
combase error (CoInitialize has not been called)
onecore\com\combase\objact\objact.cxx(812)\combase.dll!00007FF8BD322169: (caller: 00007FF8BD320F78) ReturnHr(1) tid(b54) 800401F0 CoInitialize has not been called.

I'm using Visual Studio 2015 and have started receiving the following error message. I'm not trying to write dll's or using COM objects or whatever. It's just a simple OpenGL program. I have no idea where this error message has come from. How do I get rid of it?

答:
My program calls CoInitialize(NULL) in WinMain, but I still see this error when loading some DLLs (after it's run.)
However, I get this same error when trying to enumerate sound cards in the system.
The solution is to use CoInitializeEx(NULL, COINIT_MULTITHREADED), which will make sure COM calls are allowed from any thread.</p>