问:
Passing a parameter on React Dialog from OnClick
I am fairly new to React.js and I'm currently trying to pass parameters on my dialog from onclicks.

```<code>       <IconButton className={classes.approvebutton} onClick={() => handleDialogClick("approve",1)}>
          <ThumbUp />
       </IconButton>
       <IconButton className={classes.rejectbutton} onClick={() => handleDialogClick("reject",1)} >
          <ThumbDown />
       </IconButton>
</code>```

as for the onclick function:

```<code>  function handleDialogClick (approvalType,id){
alert(`hello, ${approvalType}`);
switch(approvalType) {
  case 1:
    setDialogOpen(true);

    break;
  case 2:
    setDialogOpen(true);
    break;
  default:
    setDialogOpen(true);
}}
</code>```

What I would like is for the approval type and id be passed on inside the Dialog:

```<code><Dialog onClose={handleDialogApproveClose} aria-labelledby="simple-dialog-title" open={dialogOpen}>
          <DialogTitle id="simple-dialog-title">Request Approval</DialogTitle>
          <DialogContent>
            <DialogContentText id="alert-dialog-description">
              Do you want to //approvalType goes here//  this request?
            </DialogContentText>
          </DialogContent>
          <DialogActions>
            <Button onClick={handleClose} color="primary">
              No
            </Button>
            <Button onClick={() => submitAction(// id goes here)} color="primary" autoFocus>
              Yes
            </Button>
          </DialogActions>
        </Dialog>
</code>```

All of the code is under a single component.

I tried looking into google but I am confused on how to implement it on my code.

答:
I think your handleDialogClick is working incorrectly. In your switch case, you are using approvalType to check the condition but in each case, you are using id to open or close your dialog setDialogOpen.

If you want to use approvalType to setDialogOpen, the code should be:

function handleDialogClick (approvalType,id){
  alert(`hello, ${approvalType}`);
  switch(approvalType) {
    case 'approve':
      setDialogOpen(true);
      break;
    case 'reject':
      setDialogOpen(true);
      break;
    default:
      setDialogOpen(true);
}}```
</div>
</div>
</p>

<p>If you want to use id to setDialogOpen, the code should be:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function handleDialogClick (approvalType,id){
  alert(`hello, ${approvalType}`);
  switch(id) {
    case 1:
      setDialogOpen(true);
      break;
    case 2:
      setDialogOpen(true);
      break;
    default:
      setDialogOpen(true);
}}</code>```

Body:
I am fairly new to React.js and I'm currently trying to pass parameters on my dialog from onclicks.

       <IconButton className={classes.approvebutton} onClick={() => handleDialogClick("approve",1)}>
          <ThumbUp />
       </IconButton>
       <IconButton className={classes.rejectbutton} onClick={() => handleDialogClick("reject",1)} >
          <ThumbDown />
       </IconButton>

as for the onclick function:

  function handleDialogClick (approvalType,id){
alert(`hello, ${approvalType}`);
switch(approvalType) {
  case 1:
    setDialogOpen(true);

    break;
  case 2:
    setDialogOpen(true);
    break;
  default:
    setDialogOpen(true);
}}

What I would like is for the approval type and id be passed on inside the Dialog:

<Dialog onClose={handleDialogApproveClose} aria-labelledby="simple-dialog-title" open={dialogOpen}>
          <DialogTitle id="simple-dialog-title">Request Approval</DialogTitle>
          <DialogContent>
            <DialogContentText id="alert-dialog-description">
              Do you want to //approvalType goes here//  this request?
            </DialogContentText>
          </DialogContent>
          <DialogActions>
            <Button onClick={handleClose} color="primary">
              No
            </Button>
            <Button onClick={() => submitAction(// id goes here)} color="primary" autoFocus>
              Yes
            </Button>
          </DialogActions>
        </Dialog>

All of the code is under a single component.

I tried looking into google but I am confused on how to implement it on my code.

Body:
I think your handleDialogClick is working incorrectly. In your switch case, you are using approvalType to check the condition but in each case, you are using id to open or close your dialog setDialogOpen.

If you want to use approvalType to setDialogOpen, the code should be:

function handleDialogClick (approvalType,id){
  alert(`hello, ${approvalType}`);
  switch(approvalType) {
    case 'approve':
      setDialogOpen(true);
      break;
    case 'reject':
      setDialogOpen(true);
      break;
    default:
      setDialogOpen(true);
}}

If you want to use id to setDialogOpen, the code should be:

function handleDialogClick (approvalType,id){
  alert(`hello, ${approvalType}`);
  switch(id) {
    case 1:
      setDialogOpen(true);
      break;
    case 2:
      setDialogOpen(true);
      break;
    default:
      setDialogOpen(true);
}}


来源: stackexchange

问:
Using CMake for compiling c++ with CUDA code
I am trying to add CUDA functions in existing C++ project which uses CMake.

For example, main.cpp looks like this:

```<code>#include <stdio.h>
#include "kernels/test.cuh"

int main() {
  wrap_test_print();
  return 0;
}
</code>```

And kernels/test.cu looks like:

```<code>#include "test.cuh"
__global__ void test_print(){
  printf("Hello World!\n");
}

void wrap_test_print() {
  test_print<<<1, 1>>>();
  return;
}
</code>```

And kernels/test.cuh looks like:

```<code>#ifndef TEST_CUH__
#define TEST_CUH__

#include <stdio.h>

void wrap_test_print();

#endif
</code>```

And I use following codes for CMakeLists.txt:

```<code>===============
CMakeLists.txt
===============
cmake_minimum_required(VERSION 3.8 FATAL_ERROR)
enable_language(CUDA)
project(cmake_and_cuda)

add_executable(main main.cpp)
add_subdirectory(kernels)

# set_property(TARGET main
#              PROPERTY CUDA_SEPARABLE_COMPILATION ON)
target_link_libraries(main kernels)

===============
kernels/CMakeLists.txt
===============
enable_language(CUDA)
add_library(kernels
test.cu
test.cuh
)
target_compile_features(kernels PUBLIC cxx_std_11)
set_target_properties(kernels
                       PROPERTIES CUDA_SEPARABLE_COMPILATION ON)
target_link_libraries(kernels)

</code>```

However, when I use cmake .. in the build folder in the project, the following error message are printed:

```<code>CMake Error: Error required internal CMake variable not set, cmake may not be built correctly.
Missing variable is:
CMAKE_CUDA_DEVICE_LINK_LIBRARY
CMake Error: Error required internal CMake variable not set, cmake may not be built correctly.
Missing variable is:
CMAKE_CUDA_DEVICE_LINK_LIBRARY
</code>```

I guess this is due to a cudart problem, so I added set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -lcudart") but I could not resolve this issue. How can I solve this issue?

答:
Turning my comment into an answer:

The project() command will initialize many CMake variables concerning your system and compiler. As such, it sets the languages that your CMake project will be using. Without specifying any language in the project() command, the defaults (C and CXX) are enabled:

```<code># Initialize for C and C++ languages.
project(cmake_and_cuda)
</code>```

You should typically place the first project() command directly after the cmake_minimum_required() call, to avoid such errors.  The enable_language() is a light-weight call, typically used to enable further languages later on in the CMake project. So, you should re-arrange your CMake file to place the enable_language() call after the project() call, so that CMake has initialized its internal variables properly.

```<code>cmake_minimum_required(VERSION 3.8 FATAL_ERROR)
# Initialize for C and C++ languages.
project(cmake_and_cuda)
# Also, enable CUDA language support.
enable_language(CUDA)
</code>```

Or, simply enable all the languages your CMake project needs in the project() command itself:

```<code>cmake_minimum_required(VERSION 3.8 FATAL_ERROR)
# Initialize for C++ and CUDA languages.
project(cmake_and_cuda LANGUAGES CXX CUDA)
</code>```

Note: The enable_language() and project() command's languages apply to all CMake directories below them, so there is no need to call enable_language() again in sub-directories.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to add CUDA functions in existing C++ project which uses CMake.

For example, main.cpp looks like this:

#include <stdio.h>
#include "kernels/test.cuh"

int main() {
  wrap_test_print();
  return 0;
}

And kernels/test.cu looks like:

#include "test.cuh"
__global__ void test_print(){
  printf("Hello World!\n");
}

void wrap_test_print() {
  test_print<<<1, 1>>>();
  return;
}

And kernels/test.cuh looks like:

#ifndef TEST_CUH__
#define TEST_CUH__

#include <stdio.h>

void wrap_test_print();

#endif

And I use following codes for CMakeLists.txt:

===============
CMakeLists.txt
===============
cmake_minimum_required(VERSION 3.8 FATAL_ERROR)
enable_language(CUDA)
project(cmake_and_cuda)

add_executable(main main.cpp)
add_subdirectory(kernels)

# set_property(TARGET main
#              PROPERTY CUDA_SEPARABLE_COMPILATION ON)
target_link_libraries(main kernels)

===============
kernels/CMakeLists.txt
===============
enable_language(CUDA)
add_library(kernels
test.cu
test.cuh
)
target_compile_features(kernels PUBLIC cxx_std_11)
set_target_properties(kernels
                       PROPERTIES CUDA_SEPARABLE_COMPILATION ON)
target_link_libraries(kernels)

However, when I use cmake .. in the build folder in the project, the following error message are printed:

CMake Error: Error required internal CMake variable not set, cmake may not be built correctly.
Missing variable is:
CMAKE_CUDA_DEVICE_LINK_LIBRARY
CMake Error: Error required internal CMake variable not set, cmake may not be built correctly.
Missing variable is:
CMAKE_CUDA_DEVICE_LINK_LIBRARY

I guess this is due to a cudart problem, so I added set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -lcudart") but I could not resolve this issue. How can I solve this issue?

Body:
Turning my comment into an answer:

The project() command will initialize many CMake variables concerning your system and compiler. As such, it sets the languages that your CMake project will be using. Without specifying any language in the project() command, the defaults (C and CXX) are enabled:

# Initialize for C and C++ languages.
project(cmake_and_cuda)

You should typically place the first project() command directly after the cmake_minimum_required() call, to avoid such errors.  The enable_language() is a light-weight call, typically used to enable further languages later on in the CMake project. So, you should re-arrange your CMake file to place the enable_language() call after the project() call, so that CMake has initialized its internal variables properly.

cmake_minimum_required(VERSION 3.8 FATAL_ERROR)
# Initialize for C and C++ languages.
project(cmake_and_cuda)
# Also, enable CUDA language support.
enable_language(CUDA)

Or, simply enable all the languages your CMake project needs in the project() command itself:

cmake_minimum_required(VERSION 3.8 FATAL_ERROR)
# Initialize for C++ and CUDA languages.
project(cmake_and_cuda LANGUAGES CXX CUDA)

Note: The enable_language() and project() command's languages apply to all CMake directories below them, so there is no need to call enable_language() again in sub-directories.


问:
Why won't my application install on simulator or device iOS xcode
When trying to build and run my application I get the following error

```<code>Details

Failed to install the requested application
Domain: NSPOSIXErrorDomain
Code: 22
Failure Reason: The bundle identifier of the application could not be determined.
Recovery Suggestion: Ensure that the application's Info.plist contains a value for CFBundleIdentifier.
User Info: {
    bundleURL = "file:///Users/davidhouse/Library/Developer/Xcode/DerivedData/Pikit-evrjzcfwqbcrxwfgrnarwlnvwoli/Build/Products/Debug-iphonesimulator/Pikit.app/";
}
--

System Information

macOS Version 10.15.5 (Build 19F101)
Xcode 11.5 (16139)
</code>```

Here is my info.plist:

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>CFBundleDevelopmentRegion</key>
    <string>$(DEVELOPMENT_LANGUAGE)</string>
    <key>CFBundleExecutable</key>
    <string>$(EXECUTABLE_NAME)</string>
    <key>CFBundleIdentifier</key>
    <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
    <key>CFBundleInfoDictionaryVersion</key>
    <string>6.0</string>
    <key>CFBundleName</key>
    <string>$(PRODUCT_NAME)</string>
    <key>CFBundlePackageType</key>
    <string>$(PRODUCT_BUNDLE_PACKAGE_TYPE)</string>
    <key>CFBundleShortVersionString</key>
    <string>1.0</string>
    <key>CFBundleVersion</key>
    <string>1</string>
    <key>LSRequiresIPhoneOS</key>
    <true/>
    <key>NSCameraUsageDescription</key>
    <string>${PRODUCT_NAME} needs access to your camera to share your ideas with friends</string>
    <key>UIApplicationSceneManifest</key>
    <dict>
        <key>UIApplicationSupportsMultipleScenes</key>
        <false/>
        <key>UISceneConfigurations</key>
        <dict>
            <key>UIWindowSceneSessionRoleApplication</key>
            <array>
                <dict>
                    <key>UISceneConfigurationName</key>
                    <string>Default Configuration</string>
                    <key>UISceneDelegateClassName</key>
                    <string>$(PRODUCT_MODULE_NAME).SceneDelegate</string>
                    <key>UISceneStoryboardFile</key>
                    <string>Main</string>
                </dict>
            </array>
        </dict>
    </dict>
    <key>UILaunchStoryboardName</key>
    <string>LaunchScreen</string>
    <key>UIMainStoryboardFile</key>
    <string>Main</string>
    <key>UIRequiredDeviceCapabilities</key>
    <array>
        <string>armv7</string>
    </array>
    <key>UISupportedInterfaceOrientations</key>
    <array>
        <string>UIInterfaceOrientationPortrait</string>
        <string>UIInterfaceOrientationLandscapeLeft</string>
        <string>UIInterfaceOrientationLandscapeRight</string>
    </array>
    <key>UISupportedInterfaceOrientations~ipad</key>
    <array>
        <string>UIInterfaceOrientationPortrait</string>
        <string>UIInterfaceOrientationPortraitUpsideDown</string>
        <string>UIInterfaceOrientationLandscapeLeft</string>
        <string>UIInterfaceOrientationLandscapeRight</string>
    </array>
</dict>
</plist>
</code>```

As you can see there is an entry for CFBundleIdentifier. The app was installing and running earlier and I had made no changes to the plist.

I have tried running the App on both a simulation(iPhone 11 pro) and a real device(iPad mini) both of which worked previously.

I have tried running clean build folder, restarting xcode, removing and reinstalling my pod file deleting and recreating my plist, deleting the DerivedData folder and rebuilding, and updating my computer all without success. Any help would be greatly appreciated, and please let me know if I can provide anymore information.

After recreating my project from scratch I was able to get it running on the simulator, however it is still not installing on my actual device. Here is the error that I am getting:

```<code>Details

Unable to install "Pikit"
Domain: com.apple.dt.MobileDeviceErrorDomain
Code: -402653103
--
Could not inspect the application package.
Domain: com.apple.dt.MobileDeviceErrorDomain
Code: -402653103
User Info: {
    DVTRadarComponentKey = 282703;
    MobileDeviceErrorCode = "(0xE8000051)";
    "com.apple.dtdevicekit.stacktrace" = (
    0   DTDeviceKitBase                     0x000000011f36581a DTDKCreateNSErrorFromAMDErrorCode + 233
    1   DTDeviceKitBase                     0x000000011f3a6f70 __90-[DTDKMobileDeviceToken installApplicationBundleAtPath:withOptions:andError:withCallback:]_block_invoke + 155
    2   DVTFoundation                       0x0000000106230155 DVTInvokeWithStrongOwnership + 73
    3   DTDeviceKitBase                     0x000000011f3a6ca8 -[DTDKMobileDeviceToken installApplicationBundleAtPath:withOptions:andError:withCallback:] + 1654
    4   IDEiOSSupportCore                   0x000000011f21de91 __118-[DVTiOSDevice(DVTiPhoneApplicationInstallation) processAppInstallSet:appUninstallSet:installOptions:completionBlock:]_block_invoke.352 + 4165
    5   DVTFoundation                       0x00000001063637f4 __DVT_CALLING_CLIENT_BLOCK__ + 7
    6   DVTFoundation                       0x0000000106365436 __DVTDispatchAsync_block_invoke + 1194
    7   libdispatch.dylib                   0x00007fff70bee6c4 _dispatch_call_block_and_release + 12
    8   libdispatch.dylib                   0x00007fff70bef658 _dispatch_client_callout + 8
    9   libdispatch.dylib                   0x00007fff70bf4c44 _dispatch_lane_serial_drain + 597
    10  libdispatch.dylib                   0x00007fff70bf55d6 _dispatch_lane_invoke + 363
    11  libdispatch.dylib                   0x00007fff70bfec09 _dispatch_workloop_worker_thread + 596
    12  libsystem_pthread.dylib             0x00007fff70e4da3d _pthread_wqthread + 290
    13  libsystem_pthread.dylib             0x00007fff70e4cb77 start_wqthread + 15
);
}
--

System Information

macOS Version 10.15.5 (Build 19F101)
Xcode 11.5 (16139)
</code>```

答:
I can replicate the issue and getting the same error.

To solve this search for PRODUCT_BUNDLE_IDENTIFIER in the build settings of the target and add a value there. Like below

Clean all and build. Hope will work.

Body:
When trying to build and run my application I get the following error

Details

Failed to install the requested application
Domain: NSPOSIXErrorDomain
Code: 22
Failure Reason: The bundle identifier of the application could not be determined.
Recovery Suggestion: Ensure that the application's Info.plist contains a value for CFBundleIdentifier.
User Info: {
    bundleURL = "file:///Users/davidhouse/Library/Developer/Xcode/DerivedData/Pikit-evrjzcfwqbcrxwfgrnarwlnvwoli/Build/Products/Debug-iphonesimulator/Pikit.app/";
}
--

System Information

macOS Version 10.15.5 (Build 19F101)
Xcode 11.5 (16139)

Here is my info.plist:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>CFBundleDevelopmentRegion</key>
    <string>$(DEVELOPMENT_LANGUAGE)</string>
    <key>CFBundleExecutable</key>
    <string>$(EXECUTABLE_NAME)</string>
    <key>CFBundleIdentifier</key>
    <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
    <key>CFBundleInfoDictionaryVersion</key>
    <string>6.0</string>
    <key>CFBundleName</key>
    <string>$(PRODUCT_NAME)</string>
    <key>CFBundlePackageType</key>
    <string>$(PRODUCT_BUNDLE_PACKAGE_TYPE)</string>
    <key>CFBundleShortVersionString</key>
    <string>1.0</string>
    <key>CFBundleVersion</key>
    <string>1</string>
    <key>LSRequiresIPhoneOS</key>
    <true/>
    <key>NSCameraUsageDescription</key>
    <string>${PRODUCT_NAME} needs access to your camera to share your ideas with friends</string>
    <key>UIApplicationSceneManifest</key>
    <dict>
        <key>UIApplicationSupportsMultipleScenes</key>
        <false/>
        <key>UISceneConfigurations</key>
        <dict>
            <key>UIWindowSceneSessionRoleApplication</key>
            <array>
                <dict>
                    <key>UISceneConfigurationName</key>
                    <string>Default Configuration</string>
                    <key>UISceneDelegateClassName</key>
                    <string>$(PRODUCT_MODULE_NAME).SceneDelegate</string>
                    <key>UISceneStoryboardFile</key>
                    <string>Main</string>
                </dict>
            </array>
        </dict>
    </dict>
    <key>UILaunchStoryboardName</key>
    <string>LaunchScreen</string>
    <key>UIMainStoryboardFile</key>
    <string>Main</string>
    <key>UIRequiredDeviceCapabilities</key>
    <array>
        <string>armv7</string>
    </array>
    <key>UISupportedInterfaceOrientations</key>
    <array>
        <string>UIInterfaceOrientationPortrait</string>
        <string>UIInterfaceOrientationLandscapeLeft</string>
        <string>UIInterfaceOrientationLandscapeRight</string>
    </array>
    <key>UISupportedInterfaceOrientations~ipad</key>
    <array>
        <string>UIInterfaceOrientationPortrait</string>
        <string>UIInterfaceOrientationPortraitUpsideDown</string>
        <string>UIInterfaceOrientationLandscapeLeft</string>
        <string>UIInterfaceOrientationLandscapeRight</string>
    </array>
</dict>
</plist>

As you can see there is an entry for CFBundleIdentifier. The app was installing and running earlier and I had made no changes to the plist.

I have tried running the App on both a simulation(iPhone 11 pro) and a real device(iPad mini) both of which worked previously.

I have tried running clean build folder, restarting xcode, removing and reinstalling my pod file deleting and recreating my plist, deleting the DerivedData folder and rebuilding, and updating my computer all without success. Any help would be greatly appreciated, and please let me know if I can provide anymore information.

After recreating my project from scratch I was able to get it running on the simulator, however it is still not installing on my actual device. Here is the error that I am getting:

Details

Unable to install "Pikit"
Domain: com.apple.dt.MobileDeviceErrorDomain
Code: -402653103
--
Could not inspect the application package.
Domain: com.apple.dt.MobileDeviceErrorDomain
Code: -402653103
User Info: {
    DVTRadarComponentKey = 282703;
    MobileDeviceErrorCode = "(0xE8000051)";
    "com.apple.dtdevicekit.stacktrace" = (
    0   DTDeviceKitBase                     0x000000011f36581a DTDKCreateNSErrorFromAMDErrorCode + 233
    1   DTDeviceKitBase                     0x000000011f3a6f70 __90-[DTDKMobileDeviceToken installApplicationBundleAtPath:withOptions:andError:withCallback:]_block_invoke + 155
    2   DVTFoundation                       0x0000000106230155 DVTInvokeWithStrongOwnership + 73
    3   DTDeviceKitBase                     0x000000011f3a6ca8 -[DTDKMobileDeviceToken installApplicationBundleAtPath:withOptions:andError:withCallback:] + 1654
    4   IDEiOSSupportCore                   0x000000011f21de91 __118-[DVTiOSDevice(DVTiPhoneApplicationInstallation) processAppInstallSet:appUninstallSet:installOptions:completionBlock:]_block_invoke.352 + 4165
    5   DVTFoundation                       0x00000001063637f4 __DVT_CALLING_CLIENT_BLOCK__ + 7
    6   DVTFoundation                       0x0000000106365436 __DVTDispatchAsync_block_invoke + 1194
    7   libdispatch.dylib                   0x00007fff70bee6c4 _dispatch_call_block_and_release + 12
    8   libdispatch.dylib                   0x00007fff70bef658 _dispatch_client_callout + 8
    9   libdispatch.dylib                   0x00007fff70bf4c44 _dispatch_lane_serial_drain + 597
    10  libdispatch.dylib                   0x00007fff70bf55d6 _dispatch_lane_invoke + 363
    11  libdispatch.dylib                   0x00007fff70bfec09 _dispatch_workloop_worker_thread + 596
    12  libsystem_pthread.dylib             0x00007fff70e4da3d _pthread_wqthread + 290
    13  libsystem_pthread.dylib             0x00007fff70e4cb77 start_wqthread + 15
);
}
--

System Information

macOS Version 10.15.5 (Build 19F101)
Xcode 11.5 (16139)


问:
ES6 Arrow functions vs ES5: how to know which function to bind `this` to when using ES5 non-arrow function
I'm reading this article on using ES6 arrow functions. It gives the following example, where you have to use bind(this), followed by the corresponding code with arrow functions.

```<code>var obj = {
  id: 42,
  counter: function counter() {
    setTimeout(function() {
      console.log(this.id);
    }.bind(this), 1000);
  }
};
</code>```

It says In the ES5 example, .bind(this) is required to help pass the this context into the function.

What I Want To Know: Why do you use bind(this) with the callback to setTimeout rather than with the counter function? ie why isn't the above code like this:

```<code>var obj = {
  id: 42,
  counter: function counter() {
    setTimeout(function() {
      console.log(this.id);
    }, 1000);
  }.bind(this);
};
</code>```

答:
Why do you use bind(this) with the callback to setTimeout rather than with the counter function?

Because the counter function (which works like a method of the obj object) already has the proper this because you call it like obj.counter() so it gets this from calling it as obj.counter().  Assuming you call counter as obj.counter(), then if you do console.log(this.id) on the first line of the counter() function, it will properly show the id value.

The callback you pass to setTimeout() however has no natural this value unless you use an arrow function or .bind() on the callback function itself because when setTimeout() calls your callback it does not set a specific this value (it just calls your callback as a normal function), therefore the this value goes to the default.  That means this will be undefined if running strict mode or the global object if running in loosey-goosey mode inside of the setTimeout() callback.

See the 6 ways that the value of this is set here when calling a function.

I should also mention that if you did what you were proposing like this:

```<code>var obj = {
  id: 42,
  counter: function counter() {
    setTimeout(function() {
      console.log(this.id);
    }, 1000);
  }.bind(this);
};
</code>```

Not only would it not help the setTimeout() callback at all, but it would also bind the wrong value of this to the counter() method.  You would get whatever this was before the var obj definition (also known as the lexical value of this).

Body:
I'm reading this article on using ES6 arrow functions. It gives the following example, where you have to use bind(this), followed by the corresponding code with arrow functions.

var obj = {
  id: 42,
  counter: function counter() {
    setTimeout(function() {
      console.log(this.id);
    }.bind(this), 1000);
  }
};

It says In the ES5 example, .bind(this) is required to help pass the this context into the function.

What I Want To Know: Why do you use bind(this) with the callback to setTimeout rather than with the counter function? ie why isn't the above code like this:

var obj = {
  id: 42,
  counter: function counter() {
    setTimeout(function() {
      console.log(this.id);
    }, 1000);
  }.bind(this);
};

Body:
Why do you use bind(this) with the callback to setTimeout rather than with the counter function?

Because the counter function (which works like a method of the obj object) already has the proper this because you call it like obj.counter() so it gets this from calling it as obj.counter().  Assuming you call counter as obj.counter(), then if you do console.log(this.id) on the first line of the counter() function, it will properly show the id value.

The callback you pass to setTimeout() however has no natural this value unless you use an arrow function or .bind() on the callback function itself because when setTimeout() calls your callback it does not set a specific this value (it just calls your callback as a normal function), therefore the this value goes to the default.  That means this will be undefined if running strict mode or the global object if running in loosey-goosey mode inside of the setTimeout() callback.

See the 6 ways that the value of this is set here when calling a function.

I should also mention that if you did what you were proposing like this:

var obj = {
  id: 42,
  counter: function counter() {
    setTimeout(function() {
      console.log(this.id);
    }, 1000);
  }.bind(this);
};

Not only would it not help the setTimeout() callback at all, but it would also bind the wrong value of this to the counter() method.  You would get whatever this was before the var obj definition (also known as the lexical value of this).


问:
Gmail API returns 403 error code and "Delegation denied for <user email>"
Gmail API fails for one domain when retrieving messages with this error:

```<code>com.google.api.client.googleapis.json.GoogleJsonResponseException: 403 OK
{
  "code" : 403,
  "errors" : [ {
    "domain" : "global",
    "message" : "Delegation denied for <user email>",
    "reason" : "forbidden"
  } ],
  "message" : "Delegation denied for <user email>"
}
</code>```

I am using OAuth 2.0 and Google Apps Domain-Wide delegation of authority to access the user data. The domain has granted data access rights to the application.

答:
I had the same issue before, the solution is super tricky, you need to impersonate the person you need to access gmail content first, then use userId='me' to run the query. It works for me.

here is some sample code:

```<code>   users = # coming from directory service
   for user in users:
     credentials = service_account.Credentials.from_service_account_file(
        SERVICE_ACCOUNT_FILE, scopes=SCOPES)
     ####IMPORTANT######
     credentials_delegated = credentials.with_subject(user['primaryEmail'])

     gmail_service = build('gmail', 'v1', credentials=credentials_delegated)

     results = gmail_service.users().labels().list(userId='me').execute()
     labels = results.get('labels', [])
       for label in labels:
          print(label['name'])
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Gmail API fails for one domain when retrieving messages with this error:

com.google.api.client.googleapis.json.GoogleJsonResponseException: 403 OK
{
  "code" : 403,
  "errors" : [ {
    "domain" : "global",
    "message" : "Delegation denied for <user email>",
    "reason" : "forbidden"
  } ],
  "message" : "Delegation denied for <user email>"
}

I am using OAuth 2.0 and Google Apps Domain-Wide delegation of authority to access the user data. The domain has granted data access rights to the application.

Body:
I had the same issue before, the solution is super tricky, you need to impersonate the person you need to access gmail content first, then use userId='me' to run the query. It works for me.

here is some sample code:

   users = # coming from directory service
   for user in users:
     credentials = service_account.Credentials.from_service_account_file(
        SERVICE_ACCOUNT_FILE, scopes=SCOPES)
     ####IMPORTANT######
     credentials_delegated = credentials.with_subject(user['primaryEmail'])

     gmail_service = build('gmail', 'v1', credentials=credentials_delegated)

     results = gmail_service.users().labels().list(userId='me').execute()
     labels = results.get('labels', [])
       for label in labels:
          print(label['name'])


问:
Uncaught SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse (<anonymous>) at XMLHttpRequest.<anonymous>
I had look to the similar question and its doesn't solve my problem
I want to create file multiple  upload system  with  progressbar using php
and i have this error

```<code>Uncaught SyntaxError: Unexpected token < in JSON at position 0
     at JSON.parse (<anonymous>)
     at XMLHttpRequest.<anonymous>

</code>```

my code is

```<code><?php
error_reporting(0);
$state="white";
$count=0;
if(isset($_GET["state"])){
$state=$_GET["state"];
$count=$_GET["count"];
}
?>
<html >
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="keywords" content="كتابك القريب,أدهم شرقاوي,روايات, كتب pdf,تحميل كتب,كتب دراسية,pdf,books">
    <meta name="google-site-verification" content="ieyWI-BKgki1_LGBMFqdFYkGyEeHlMSEAodDuxKcN7A" />
    <link rel="stylesheet" href="controls.css">
   <!--

   -->
   <style>
    .bar
    {
    position: absolute;
    height: 15px;
    background-color:  rgb(27, 26, 26);
    box-shadow:inset  1px 1px 1px 1px #fff5;
    width: 80%;
    bottom: 45px;
    border-radius:15px ;

    }
    .pbar
    {
    position: absolute;
    height: 15px;
    background-color:#941ab4;
    width: 0;
    border-radius:15px ;
    }

   </style>

    <title>كتابك القريب</title>
    <script src="jquery.js"></script>

   <script>
       var state= <?php echo '"' .$state.'"' ; ?>;
       var Vcount= <?php echo $count; ?>;

        if (state=="succsses") {$(document).ready(function() { $(".succsses").css("display","block");});  }

   </script>
   <script>
       var state= <?php echo '"' .$state.'"' ; ?>;

       if (state=="error") { $(document).ready(function() { $(".error").css("display","block"); }); }

   </script>

    <script>

        $(document).ready(function() {
            $(".x").click(function() {

            $(".succsses").css("display","none");

             });
        });

        $(document).ready(function() {
            $(".x").click(function() {

            $(".error").css("display","none");

             });
        });
    </script>
</head>
<body>
    <div class="succsses" id="succsses" >
    <p><?php  if ($state=="succsses") { echo"تم تحميل  ($count) ملفات بنجاح" ;}?></p>
    <span class="x">x</span>
    </div>
    <div class="error" id="error" >
    <p><?php  if ($state=="error") { echo"فشل التحميل " ;}?></p>
    <span class="x">x</span>
    </div>

    <div class="login-form">
        <img src="https://yourclosebook.com/res/logos/ryhan.png" alt="" class="ava">
        <form action="upload.php" method="post" enctype="multipart/form-data" id="frm">
            <input type="email" name="email" id="" placeholder="email (اختياري)">

                <input type="file" name="file[]" id="costum-file" accept="application/pdf,application/msword,.docx" multiple >

            <input type="submit" value="تحميل" id="upload">

        </form>
        <div class="bar">
               <span class="pbar" id="pb"></span>  <span class="ptext " id="pt"></span>

           </div>
        <P> (*.pdf,*.docx,*.doc,*.ppt,*pptx)يمكنكم تحميل ملفات من الصيغ المدرجة جانبا</P>
        <h3 id="friend"> <a href="https://www.yourclosebook.com" target="_blank"  >  كتابك القريب !</a> صديقك المقرب</h3>
    </div>
    <style>

    </style>

        <script src="upload.js"></script>
        <script>
            document.getElementById('upload').addEventListener('click',function(e){
                e.preventDefault();
                var f = document.getElementById('costum-file');
                var pb = document.getElementById('pb');
                var pt = document.getElementById('pt');
                app.uploader({
                files:f,
                porgressBar:pb,
                porgressText:pt,
                processor:'upload.php',
                    finished:function(data){

                    },
                    error:function(){

                    }
                });

            });

        </script>
</body>
</html>
</code>```

uploade.php

```<code><?php
require_once("conn.php");
header("Content-Type:application/json");
$err="";
$UPLOADED=NULL;
$count=0;
$i=0;
$succeded=[];
$faild=[];
for ($i; $i <count($_FILES['file']['name']) ; $i++) {
    $target_path="uploads/";
    $file=$_FILES['file']['name'][$i];
    $file_temp=$_FILES['file']['tmp_name'][$i];
    $fileSize   =$_FILES['file']['size'][$i];
    $fileError  =$_FILES['file']['error'][$i];
    $fileType   =$_FILES['file']['type'][$i];
    $fileEXT    =explode('.',$file);
      $fileRealExt=strtolower(end($fileEXT));
    $target_path= $target_path.$file;

    $allowed    =array('pdf','doc','docx');
    if (!empty($file))  {
        if (in_array($fileRealExt,$allowed)) {
            if ($fileError===0) {
                $helpTimes=1;
        $email=$_POST['email'];
        $email= $db->real_escape_string($email);
        $file= $db->real_escape_string($file);
        $UPLOADED=move_uploaded_file($file_temp,$target_path);

        if ($UPLOADED) {

            $insert = $db->query("INSERT INTO user_uploads(email,filepath,upload_time,help_times) VALUES('".$email."','".$file."',NOW(),'".$helpTimes."')");

            $count=$i+1;
            $succeded=array(
                'name'=>$name,
                'file'=>$file

            );

        }else{
            $faild= array('name' => $name);

             echo header("Location:index.php?state=error&error=failedUpload");
        }

            }else{
                $err= "حدث خطأ غير متوقع";
                 echo header("Location:index.php?state=error&error=failedUpload");
            }
        }else{
             echo header("Location:index.php?state=error&error=notAcceptedFileFormat");
        }

    }else{
        $err=" يجب اختيار ملف واحد على الاقل";
         echo header("Location:index.php?state=error&error=empty");
    }

  //  --------------------
  if (!empty($_POST['ajax'])) {
     echo json_encode(array(
        'succeded'=> $succeded,
        'faild'=>$faild
     ));
  }

}
echo $err;
if ($count>0) {
    //index.php
  echo  header("Location:index.php?state=succsses&count=$count");
    if (!empty($_POST['email'])) {

          $email=$_POST['email'];

          $from = "MIME-Version: 1.0" . "\r\n";
          $from .= "Content-type:text/html;charset=UTF-8" . "\r\n";
          $from .= 'From: YOUR CLOSE BOOK TEAM <contact@yourclosebook.com>' . "\r\n";
          $s=" رسالة شكر";
          $messagge="<H1>باسمنا نحن فريق موقع كتابك القريب نقد لكم فائق الشكر لاجل مساعدتنا بتقديم كتبكم الثمينة</H1>";
         $mail= mail($email,$s,$messagge,$from);
          if (!$mail) {
             echo"email sending error";
          }
          else{
              echo"check your email";
          }
    }
}else{
   echo header("Location:index.php?state=error");
}
</code>```

upload.js

```<code>var app=app ||{};
(function(o){
"use strict";
var ajax,getFormData,setProgress;

ajax =function (data)
{
   var  xhr= new XMLHttpRequest(),uploaded;
   xhr.addEventListener('readystatechange',function()
   {
        //readyState===4 => done
        if (this.readyState===4)
        {
                /*
                status===200=>  ok*/

            if (this.status===200)
            {
                        uploaded= JSON.parse(this.response);
                        if (typeof o.options.finished==='function')
                        {
                            o.options.finished(uploaded);
                        }
            }
            else
            {
                        if (typeof o.options.error==='function')
                        {
                            o.options.error();
                        }
            }

        }
   });
   xhr.upload.addEventListener('progress',function(event)
   {
    var percent;//%
    if (event.lengthComputable===true)

    {
        percent= Math.round((event.loaded/event.total)/100);
        setProgress(percent);
    }
   });
   xhr.open('post',o.options.processor);
   xhr.send(data);
};
getFormData =function (source) {
   var data = new FormData(),i;
   for ( i = 0; i < source.length; i++) {
      data.append('costum-file[]',source[i]);

   }
   data.append('ajax',true);
   return data;
};
setProgress =function (value) {
    if (o.options.porgressBar !== undefined) {
        o.options.porgressBar.style.width=value?value+'%':0;
    }
};
o.uploader=function (options) {
    o.options=options;
    if (o.options.files!==undefined) {
        ajax(getFormData(o.options.files.files));
    }

}
}(app));
</code>```

答:
There are some issues with your code:

In your main file you have an email element but in your upload.js file you are not adding it to your FormDara object. So in your uploade.php file you don't have access to it and $email=$_POST['email']; will throw an error

In your upload.js you are naming your file objects costum-file fun in your upload.php you are looking for file objects with the name of file. These two should have same name.

echo header("Location:index.php"); is incorrect and you should only use header("Location:index.php");

If you are calling upload.php file via ajax request then you can not do php redirect(header("Location:index.php");). What you should do is to return some json response and then pars it in your main file JavaScript and show relevant messages(Error or success)

So to sum them up what you need to change to fix the error you are getting is(I'm just highlighting the changes and not the whole code):

main(index.php?) file

You need to provide an id for the email element:

```<code><input type="email" name="email" id="email" placeholder="email (اختياري)">
</code>```

You need to add this email element to your JavaScript call

```<code><script type="text/javascript">
document.getElementById('upload').addEventListener('click',function(e){
    e.preventDefault();
    var f = document.getElementById('costum-file');
    var pb = document.getElementById('pb');
    var pt = document.getElementById('pt');
    var eml = document.getElementById('email');
    app.uploader({
    files:f,
    porgressBar:pb,
    porgressText:pt,
    email:eml,
    processor:'upload.php',
        finished:function(data){
        },
        error:function(){
        }
    });
});
</script>
</code>```

upload.js
You need to change the file element to file and also add the email element in the FormData object

```<code>getFormData =function (source) {
    var data = new FormData(), i;
    for ( i = 0; i < source.length; i++) {
        data.append('file[]',source[i]);
    }
    data.append('email', o.options.email.value);
    data.append('ajax', true);
    return data;
};
</code>```

And finally in your upload.php file change all the echo header("Location:index.php") instances with a json encoded string like what you have here:

```<code>echo json_encode(array(
    'succeded'=> $succeded,
    'faild'=>$faild
));
</code>```

With proper response which then you can parse in your index.php file.

Please give it a try and see if it fixes your issue.

Body:
I had look to the similar question and its doesn't solve my problem
I want to create file multiple  upload system  with  progressbar using php
and i have this error

Uncaught SyntaxError: Unexpected token < in JSON at position 0
     at JSON.parse (<anonymous>)
     at XMLHttpRequest.<anonymous>

my code is

<?php
error_reporting(0);
$state="white";
$count=0;
if(isset($_GET["state"])){
$state=$_GET["state"];
$count=$_GET["count"];
}
?>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="keywords" content="كتابك القريب,أدهم شرقاوي,روايات, كتب pdf,تحميل كتب,كتب دراسية,pdf,books">
    <meta name="google-site-verification" content="ieyWI-BKgki1_LGBMFqdFYkGyEeHlMSEAodDuxKcN7A" />
    <link rel="stylesheet" href="controls.css">

    <title>كتابك القريب</title>

<?php  if ($state=="succsses") { echo"تم تحميل  ($count) ملفات بنجاح" ;}?>

    x

<?php  if ($state=="error") { echo"فشل التحميل " ;}?>

    x

        <form action="upload.php" method="post" enctype="multipart/form-data" id="frm">
            <input type="email" name="email" id="" placeholder="email (اختياري)">

                <input type="file" name="file[]" id="costum-file" accept="application/pdf,application/msword,.docx" multiple >

            <input type="submit" value="تحميل" id="upload">

        </form>

 (*.pdf,*.docx,*.doc,*.ppt,*pptx)يمكنكم تحميل ملفات من الصيغ المدرجة جانبا

   كتابك القريب ! صديقك المقرب

uploade.php

<?php
require_once("conn.php");
header("Content-Type:application/json");
$err="";
$UPLOADED=NULL;
$count=0;
$i=0;
$succeded=[];
$faild=[];
for ($i; $i <count($_FILES['file']['name']) ; $i++) {
    $target_path="uploads/";
    $file=$_FILES['file']['name'][$i];
    $file_temp=$_FILES['file']['tmp_name'][$i];
    $fileSize   =$_FILES['file']['size'][$i];
    $fileError  =$_FILES['file']['error'][$i];
    $fileType   =$_FILES['file']['type'][$i];
    $fileEXT    =explode('.',$file);
      $fileRealExt=strtolower(end($fileEXT));
    $target_path= $target_path.$file;

    $allowed    =array('pdf','doc','docx');
    if (!empty($file))  {
        if (in_array($fileRealExt,$allowed)) {
            if ($fileError===0) {
                $helpTimes=1;
        $email=$_POST['email'];
        $email= $db->real_escape_string($email);
        $file= $db->real_escape_string($file);
        $UPLOADED=move_uploaded_file($file_temp,$target_path);

        if ($UPLOADED) {

            $insert = $db->query("INSERT INTO user_uploads(email,filepath,upload_time,help_times) VALUES('".$email."','".$file."',NOW(),'".$helpTimes."')");

            $count=$i+1;
            $succeded=array(
                'name'=>$name,
                'file'=>$file

            );

        }else{
            $faild= array('name' => $name);

             echo header("Location:index.php?state=error&error=failedUpload");
        }

            }else{
                $err= "حدث خطأ غير متوقع";
                 echo header("Location:index.php?state=error&error=failedUpload");
            }
        }else{
             echo header("Location:index.php?state=error&error=notAcceptedFileFormat");
        }

    }else{
        $err=" يجب اختيار ملف واحد على الاقل";
         echo header("Location:index.php?state=error&error=empty");
    }

  //  --------------------
  if (!empty($_POST['ajax'])) {
     echo json_encode(array(
        'succeded'=> $succeded,
        'faild'=>$faild
     ));
  }

}
echo $err;
if ($count>0) {
    //index.php
  echo  header("Location:index.php?state=succsses&count=$count");
    if (!empty($_POST['email'])) {

          $email=$_POST['email'];

          $from = "MIME-Version: 1.0" . "\r\n";
          $from .= "Content-type:text/html;charset=UTF-8" . "\r\n";
          $from .= 'From: YOUR CLOSE BOOK TEAM <contact@yourclosebook.com>' . "\r\n";
          $s=" رسالة شكر";
          $messagge="
باسمنا نحن فريق موقع كتابك القريب نقد لكم فائق الشكر لاجل مساعدتنا بتقديم كتبكم الثمينة
";
         $mail= mail($email,$s,$messagge,$from);
          if (!$mail) {
             echo"email sending error";
          }
          else{
              echo"check your email";
          }
    }
}else{
   echo header("Location:index.php?state=error");
}

upload.js

var app=app ||{};
(function(o){
"use strict";
var ajax,getFormData,setProgress;

ajax =function (data)
{
   var  xhr= new XMLHttpRequest(),uploaded;
   xhr.addEventListener('readystatechange',function()
   {
        //readyState===4 => done
        if (this.readyState===4)
        {
                /*
                status===200=>  ok*/

            if (this.status===200)
            {
                        uploaded= JSON.parse(this.response);
                        if (typeof o.options.finished==='function')
                        {
                            o.options.finished(uploaded);
                        }
            }
            else
            {
                        if (typeof o.options.error==='function')
                        {
                            o.options.error();
                        }
            }

        }
   });
   xhr.upload.addEventListener('progress',function(event)
   {
    var percent;//%
    if (event.lengthComputable===true)

    {
        percent= Math.round((event.loaded/event.total)/100);
        setProgress(percent);
    }
   });
   xhr.open('post',o.options.processor);
   xhr.send(data);
};
getFormData =function (source) {
   var data = new FormData(),i;
   for ( i = 0; i < source.length; i++) {
      data.append('costum-file[]',source[i]);

   }
   data.append('ajax',true);
   return data;
};
setProgress =function (value) {
    if (o.options.porgressBar !== undefined) {
        o.options.porgressBar.style.width=value?value+'%':0;
    }
};
o.uploader=function (options) {
    o.options=options;
    if (o.options.files!==undefined) {
        ajax(getFormData(o.options.files.files));
    }

}
}(app));

Body:
There are some issues with your code:

In your main file you have an email element but in your upload.js file you are not adding it to your FormDara object. So in your uploade.php file you don't have access to it and $email=$_POST['email']; will throw an error

In your upload.js you are naming your file objects costum-file fun in your upload.php you are looking for file objects with the name of file. These two should have same name.

echo header("Location:index.php"); is incorrect and you should only use header("Location:index.php");

If you are calling upload.php file via ajax request then you can not do php redirect(header("Location:index.php");). What you should do is to return some json response and then pars it in your main file JavaScript and show relevant messages(Error or success)

So to sum them up what you need to change to fix the error you are getting is(I'm just highlighting the changes and not the whole code):

main(index.php?) file

You need to provide an id for the email element:

<input type="email" name="email" id="email" placeholder="email (اختياري)">

You need to add this email element to your JavaScript call

<script type="text/javascript">
document.getElementById('upload').addEventListener('click',function(e){
    e.preventDefault();
    var f = document.getElementById('costum-file');
    var pb = document.getElementById('pb');
    var pt = document.getElementById('pt');
    var eml = document.getElementById('email');
    app.uploader({
    files:f,
    porgressBar:pb,
    porgressText:pt,
    email:eml,
    processor:'upload.php',
        finished:function(data){
        },
        error:function(){
        }
    });
});
</script>

upload.js
You need to change the file element to file and also add the email element in the FormData object

getFormData =function (source) {
    var data = new FormData(), i;
    for ( i = 0; i < source.length; i++) {
        data.append('file[]',source[i]);
    }
    data.append('email', o.options.email.value);
    data.append('ajax', true);
    return data;
};

And finally in your upload.php file change all the echo header("Location:index.php") instances with a json encoded string like what you have here:

echo json_encode(array(
    'succeded'=> $succeded,
    'faild'=>$faild
));

With proper response which then you can parse in your index.php file.

Please give it a try and see if it fixes your issue.


问:
Android license status unknown?
For app development I download and installed Flutter sdk along with its dependencies Android studio, Java. After installing all I came to an error
for checking flutter doctor. The following error came:

```<code>    Android toolchain - develop for Android devices (Android SDK version 28.0.3)
        X Android license status unknown.
          Try re-installing or updating your Android SDK Manager.
          See https://developer.android.com/studio/#downloads or visit https://flutter.dev/setup/#android-setup for detailed instructions.
</code>```

Then after searching with the help of Flutter Android license status unknown  I tried to update Android SDK with PathToAndroidSDK --update It again generates following error:

```<code>    Exception in thread "main" java.lang.NoClassDefFoundError: javax/xml/bind/annotation/XmlSchema
            at com.android.repository.api.SchemaModule$SchemaModuleVersion.<init>(SchemaModule.java:156)
            at com.android.repository.api.SchemaModule.<init>(SchemaModule.java:75)
            at com.android.sdklib.repository.AndroidSdkHandler.<clinit>(AndroidSdkHandler.java:81)
            at com.android.sdklib.tool.sdkmanager.SdkManagerCli.main(SdkManagerCli.java:73)
            at com.android.sdklib.tool.sdkmanager.SdkManagerCli.main(SdkManagerCli.java:48)
    Caused by: java.lang.ClassNotFoundException: javax.xml.bind.annotation.XmlSchema
            at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:583)
            at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
            at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
            ... 5 more
</code>```

答:
After a long night i figured out that i have installed a bad Java version.

I solved this installing JDK 8, correctly and setting the jdk path on android studio.

After that

```<code>flutter doctor --android-licenses
</code>```

Of course the obsolete tools should be installed too

Hope it helps. To some one reaching here.

Title: Android license status unknown?

Body:
For app development I download and installed Flutter sdk along with its dependencies Android studio, Java. After installing all I came to an error
for checking flutter doctor. The following error came:

    Android toolchain - develop for Android devices (Android SDK version 28.0.3)
        X Android license status unknown.
          Try re-installing or updating your Android SDK Manager.
          See https://developer.android.com/studio/#downloads or visit https://flutter.dev/setup/#android-setup for detailed instructions.

Then after searching with the help of Flutter Android license status unknown  I tried to update Android SDK with PathToAndroidSDK --update It again generates following error:

    Exception in thread "main" java.lang.NoClassDefFoundError: javax/xml/bind/annotation/XmlSchema
            at com.android.repository.api.SchemaModule$SchemaModuleVersion.<init>(SchemaModule.java:156)
            at com.android.repository.api.SchemaModule.<init>(SchemaModule.java:75)
            at com.android.sdklib.repository.AndroidSdkHandler.<clinit>(AndroidSdkHandler.java:81)
            at com.android.sdklib.tool.sdkmanager.SdkManagerCli.main(SdkManagerCli.java:73)
            at com.android.sdklib.tool.sdkmanager.SdkManagerCli.main(SdkManagerCli.java:48)
    Caused by: java.lang.ClassNotFoundException: javax.xml.bind.annotation.XmlSchema
            at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:583)
            at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
            at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
            ... 5 more

Body:
After a long night i figured out that i have installed a bad Java version.

I solved this installing JDK 8, correctly and setting the jdk path on android studio.

After that

flutter doctor --android-licenses

Of course the obsolete tools should be installed too

Hope it helps. To some one reaching here.


问:
How can i scrape data from a HTML table which does not have URL? href contains 'on-click' link
With pythons beautiful soup, I am trying to scrape data from the 2nd table in the following url: https://www.timeanddate.com/weather/india/bangalore/historic?month=1&year=2018

Here I want to scrape the data for the complete Jan month of 2018, The URL for the page does not change for each date. Is there a way to scrape this kind.

How do I access each table, when the 'href' does not contain the whole data even if I edit the URL.

答:
I think this site uses javascript to change this table. Take a look at selenium library (useful link). It must help you with this kind of sites. You should just iterate over all the dates in the month, load a table and then scrape the data.

There are a lot of tutorials on how to use selenium so you shouldn't have much trouble with it


问:
R xgboost re-convert numbers to character
I have created an xgboost model and satisfied with the accuracy.
Obviously, my "Y" are now numeric. Is there are a way to convert my predicted values to original chr?</p>

答:
Yes, I typically add an additional column of the original labels (i.e. "Placebo" or "Treatment" instead of "0" or "1") when I summarise my results - can you adapt this to your needs?</p>

```<code>Summary_of_results <- data.frame(Patient_ID = rownames(data),
                                 label = labels,
                                 prediction = xgbpred)
Summary_of_results$original_label <- ifelse(
  Summary_of_results$label == 0,
  "Placebo",
  "Treatment")

Summary_of_results
</code>```

Body:
Yes, I typically add an additional column of the original labels (i.e. "Placebo" or "Treatment" instead of "0" or "1") when I summarise my results - can you adapt this to your needs?

Summary_of_results <- data.frame(Patient_ID = rownames(data),
                                 label = labels,
                                 prediction = xgbpred)
Summary_of_results$original_label <- ifelse(
  Summary_of_results$label == 0,
  "Placebo",
  "Treatment")

Summary_of_results


问:
what make a function execute before another one?
I have a html page My goal is  when i click on the button The  first function execute and after that the second one execute

but the actual result is that the function 2 execute first i tried to write an if condition that if the function 1 execute then execute function 2 but it does not work !

How can i make the function 1 execute first and  what make a function execute before another one ?

```<code>but.addEventListener('click',function(){

function FirstFunction(){

   var Interval= setInterval(function(){

    // Code

    },500);

};

FirstFunction();

function SecondFunction(){

    // code

};

 if( FirstFunction() ){

       SecondFunction();

};

});
</code>```

答:
but.addEventListener('click',function(){

function FirstFunction(secFunction){

   var Interval= setInterval(function(){

    // Code

    secFunction();

    },500);

};

function SecondFunction(){

    // code

};
FirstFunction(SecondFunction);
}); ```

Body:
I have a html page My goal is  when i click on the button The  first function execute and after that the second one execute

but the actual result is that the function 2 execute first i tried to write an if condition that if the function 1 execute then execute function 2 but it does not work !

How can i make the function 1 execute first and  what make a function execute before another one ?

but.addEventListener('click',function(){

function FirstFunction(){

   var Interval= setInterval(function(){

    // Code

    },500);

};

FirstFunction();

function SecondFunction(){

    // code

};

 if( FirstFunction() ){

       SecondFunction();

};

});


问:
Locking under exclusive threads constraint
Is necessary to lock this function, when updating the shared Array using many threads?, providing that each Arrays element is accessed (read and written), by only 1 thread at most.

Thank you.

e.g.

       public string[] UpdateArray
        (List<string> myList, Func<string,string>del)
        {
         int count = myList.Count;
         string[] myArray = new string[count];
         Parallel.For(0, count, i => myArray[i] = del(myList[i]));
         return myArray;
       }
```

<p>update:</p>

<p>its intended use would be as follows,in a WPF sync context</p>

<pre class="lang-cs prettyprint-override"><code>
        public Task<string[]> updateArrayTask()
            {
                List<string> myList = GetMyList();
                Func<string, string> del = MyDel;
                var t1=Task<string[]>.Run(() => UpdateArray(myList, del));
                return t1;
            }
</code>```

and then await this Task in an async function.

答:
It is probably unnessesary to lock, but this approach forces you to think about visibility, volatility, memory models, and all this thorny stuff. Which is quite undesirable when you are writing application code with the intention of being easy to maintain, and guaranteed to produce correct results on any CPU architecture it may run. So my suggestion is to bypass the problem by using PLINQ instead of the Parallel class:

```<code>public string[] UpdateArray(List<string> myList, Func<string, string> del)
{
    return myList
        .AsParallel()
        .AsOrdered()
        .Select(s => del(s))
        .ToArray();
}
</code>```

Update: If you find that the PLINQ approach has too much overhead, you could increase the robustness of your current approach by adding a Thread.MemoryBarrier at the end. Technically it may not be required, but it can buy you peace of mind for a very small price!

Synchronizes memory access as follows: The processor executing the current thread cannot reorder instructions in such a way that memory accesses prior to the call to MemoryBarrier() execute after memory accesses that follow the call to MemoryBarrier().

To reduce further the overhead of parallelism you could use the Partitioner.Create method, so that you can work with chunky portions of the list instead of its individual elements.

```<code>public string[] UpdateArray(List<string> myList, Func<string, string> del)
{
    string[] myArray = new string[myList.Count];
    Parallel.ForEach(Partitioner.Create(0, myList.Count), range =>
    {
        for (int i = range.Item1; i < range.Item2; i++)
        {
            myArray[i] = del(myList[i]);
        }
    });
    Thread.MemoryBarrier();
    return myArray;
}
</code>```

Body:
Is necessary to lock this function, when updating the shared Array using many threads?, providing that each Arrays element is accessed (read and written), by only 1 thread at most.

Thank you.

e.g.

       public string[] UpdateArray
        (List<string> myList, Func<string,string>del)
        {
         int count = myList.Count;
         string[] myArray = new string[count];
         Parallel.For(0, count, i => myArray[i] = del(myList[i]));
         return myArray;
       }

update:

its intended use would be as follows,in a WPF sync context

        public Task<string[]> updateArrayTask()
            {
                List<string> myList = GetMyList();
                Func<string, string> del = MyDel;
                var t1=Task<string[]>.Run(() => UpdateArray(myList, del));
                return t1;
            }

and then await this Task in an async function.

Body:
It is probably unnessesary to lock, but this approach forces you to think about visibility, volatility, memory models, and all this thorny stuff. Which is quite undesirable when you are writing application code with the intention of being easy to maintain, and guaranteed to produce correct results on any CPU architecture it may run. So my suggestion is to bypass the problem by using PLINQ instead of the Parallel class:

public string[] UpdateArray(List<string> myList, Func<string, string> del)
{
    return myList
        .AsParallel()
        .AsOrdered()
        .Select(s => del(s))
        .ToArray();
}

Update: If you find that the PLINQ approach has too much overhead, you could increase the robustness of your current approach by adding a Thread.MemoryBarrier at the end. Technically it may not be required, but it can buy you peace of mind for a very small price!

Synchronizes memory access as follows: The processor executing the current thread cannot reorder instructions in such a way that memory accesses prior to the call to MemoryBarrier() execute after memory accesses that follow the call to MemoryBarrier().

To reduce further the overhead of parallelism you could use the Partitioner.Create method, so that you can work with chunky portions of the list instead of its individual elements.

public string[] UpdateArray(List<string> myList, Func<string, string> del)
{
    string[] myArray = new string[myList.Count];
    Parallel.ForEach(Partitioner.Create(0, myList.Count), range =>
    {
        for (int i = range.Item1; i < range.Item2; i++)
        {
            myArray[i] = del(myList[i]);
        }
    });
    Thread.MemoryBarrier();
    return myArray;
}


问:
Sum of an array in which the array is a property of a property in the outer object
```<code>{
    'Edsger W. Dijkstra': [ // o
      { author: 'Edsger W. Dijkstra', likes: 5 },
      { author: 'Edsger W. Dijkstra', likes: 10 }
    ],
    'Benizio Mauritez': [
      { author: 'Benizio Mauritez', likes: 12 },
      { author: 'Benizio Mauritez', likes: 8 }
    ]
  }
</code>```

I have this object which in this case, represents users from a blog in which, I am trying to merge a single author with their total likes already merged, e.g:

```<code>{
    [
        author: Edsger W. Dijkstra,
        likes: 15
    ],
    [
        author: Benizio Mauritez,
        likes: 20
    ],
}
</code>```

How can I do this? I've already trying reducing their props (Got stucked at re-assigning or creating a new prop out of that), tried lodash's sumBy function so if someone can enlight me on how to do this, I would be very much appreciating it!, many thanks
!

答:
You could loop through the authors in your 'input' object, and produce an 'output' object where you sum the 'likes' of the related array...

Something like this:

input = {
    'Edsger W. Dijkstra': [ // o
      { author: 'Edsger W. Dijkstra', likes: 5 },
      { author: 'Edsger W. Dijkstra', likes: 10 }
    ],
    'Benizio Mauritez': [
      { author: 'Benizio Mauritez', likes: 12 },
      { author: 'Benizio Mauritez', likes: 8 }
    ]
  };

output = Object.keys(input).map(key => {
 return { author: key, likes: input[key].reduce((a, b) => a + b['likes'], 0) };
})

console.log(output);
```

<hr>

<p>To give a bit more explanation:</p>

<p><code>Object.keys(input)</code> will give you an array of the authors in the 'input' object.</p>

<pre class="lang-js prettyprint-override"><code>console.log(Object.keys(input));
//["Edsger W. Dijkstra", "Benizio Mauritez"]
</code>```

You can then use the map function to create a new array populated with the results of calling a provided function on every element in the calling array.

output = Object.keys(input).map(key => {
 console.log(input[key]);
})

/*
[{
  author: "Edsger W. Dijkstra",
  likes: 5
}, {
  author: "Edsger W. Dijkstra",
  likes: 10
}]
[{
  author: "Benizio Mauritez",
  likes: 12
}, {
  author: "Benizio Mauritez",
  likes: 8
}]
*/
```

Then finally using the reduce method on the inner array (the array referenced of each key) to sum the 'likes'.

Body:
{
    'Edsger W. Dijkstra': [ // o
      { author: 'Edsger W. Dijkstra', likes: 5 },
      { author: 'Edsger W. Dijkstra', likes: 10 }
    ],
    'Benizio Mauritez': [
      { author: 'Benizio Mauritez', likes: 12 },
      { author: 'Benizio Mauritez', likes: 8 }
    ]
  }

I have this object which in this case, represents users from a blog in which, I am trying to merge a single author with their total likes already merged, e.g:

{
    [
        author: Edsger W. Dijkstra,
        likes: 15
    ],
    [
        author: Benizio Mauritez,
        likes: 20
    ],
}

How can I do this? I've already trying reducing their props (Got stucked at re-assigning or creating a new prop out of that), tried lodash's sumBy function so if someone can enlight me on how to do this, I would be very much appreciating it!, many thanks
!

Body:
You could loop through the authors in your 'input' object, and produce an 'output' object where you sum the 'likes' of the related array...

Something like this:

input = {
    'Edsger W. Dijkstra': [ // o
      { author: 'Edsger W. Dijkstra', likes: 5 },
      { author: 'Edsger W. Dijkstra', likes: 10 }
    ],
    'Benizio Mauritez': [
      { author: 'Benizio Mauritez', likes: 12 },
      { author: 'Benizio Mauritez', likes: 8 }
    ]
  };

output = Object.keys(input).map(key => {
 return { author: key, likes: input[key].reduce((a, b) => a + b['likes'], 0) };
})

console.log(output);

To give a bit more explanation:

Object.keys(input) will give you an array of the authors in the 'input' object.

console.log(Object.keys(input));
//["Edsger W. Dijkstra", "Benizio Mauritez"]

You can then use the map function to create a new array populated with the results of calling a provided function on every element in the calling array.

output = Object.keys(input).map(key => {
 console.log(input[key]);
})

/*
[{
  author: "Edsger W. Dijkstra",
  likes: 5
}, {
  author: "Edsger W. Dijkstra",
  likes: 10
}]
[{
  author: "Benizio Mauritez",
  likes: 12
}, {
  author: "Benizio Mauritez",
  likes: 8
}]
*/

Then finally using the reduce method on the inner array (the array referenced of each key) to sum the 'likes'.


答:
Here is a quick lodash solution (if you need lodash). You will get an array of objects

```<code>const data = {
    'Edsger W. Dijkstra': [
        { author: 'Edsger W. Dijkstra', likes: 5 },
        { author: 'Edsger W. Dijkstra', likes: 10 }
    ],
    'Benizio Mauritez': [
        { author: 'Benizio Mauritez', likes: 12 },
        { author: 'Benizio Mauritez', likes: 8 }
    ]
}

const result = []

for (const key in data) {
    if (data.hasOwnProperty(key)) {
        const element = data[key];
        const groupedElements= lodash(element).groupBy('author')
        const resultOfReduction = groupedElements.map((objs, key) => ({
            author: key,
            likes: lodash.sumBy(objs, 'likes')
        })).value();

        result.push(resultOfReduction[0])
    }
}

console.log(result);
</code>```

The result will be an array of objects (as I assumed based on your example, but your example has a syntax error, but I believe, based on that you will be able to translate the result in the format what you need, if not - let us know =))

```<code>[
  { author: 'Edsger W. Dijkstra', likes: 15 },
  { author: 'Benizio Mauritez', likes: 20 }
]
</code>```

Title: Sum of an array in which the array is a property of a property in the outer object

Body:
Here is a quick lodash solution (if you need lodash). You will get an array of objects

const data = {
    'Edsger W. Dijkstra': [
        { author: 'Edsger W. Dijkstra', likes: 5 },
        { author: 'Edsger W. Dijkstra', likes: 10 }
    ],
    'Benizio Mauritez': [
        { author: 'Benizio Mauritez', likes: 12 },
        { author: 'Benizio Mauritez', likes: 8 }
    ]
}

const result = []

for (const key in data) {
    if (data.hasOwnProperty(key)) {
        const element = data[key];
        const groupedElements= lodash(element).groupBy('author')
        const resultOfReduction = groupedElements.map((objs, key) => ({
            author: key,
            likes: lodash.sumBy(objs, 'likes')
        })).value();

        result.push(resultOfReduction[0])
    }
}

console.log(result);

The result will be an array of objects (as I assumed based on your example, but your example has a syntax error, but I believe, based on that you will be able to translate the result in the format what you need, if not - let us know =))

[
  { author: 'Edsger W. Dijkstra', likes: 15 },
  { author: 'Benizio Mauritez', likes: 20 }
]


答:
I find your initial structure somewhat strange, given that you've pulled the author up into the above object and sorted the author's blog post metadata objects into those lists. Unless I misunderstand, and there is potentially the wrong author's blog post metadata objects under the author's key within the outer object.

At any rate, you should be able to solve this with a loop and a map/reduce.

const postMetadata = {
    "Edsger W. Dijkstra": [
        {
            author: "Edsger W. Dijkstra",
            likes: 5
        },
        {
            author: "Edsger W. Dijkstra",
            likes: 10
        }
    ],
    "Benizio Mauritez": [
        {
            author: "Benizio Mauritez",
            likes: 12
        },
        {
            author: "Benizio Mauritez",
            likes: 8
        }
    ]
};

// result will be a mapping from author to total likes, which is kinda the structure you've described.
const result = {};
for (let author in postMetadata) {
    let summedLikes = postMetadata[author]
        .map(postMeta => postMeta.likes)
        .reduce((sum, curr) => sum + curr);
    // Do something with summedLikes here
    // for example
    result[author] = summedLikes;
}
```

So what I do here is take your initial structure, I loop through each author, and then for each author's blog post metadata object, I use Array.prototype.map to just get an array of their likes values, and then I use Array.prototype.reduce to perform a summing function in order to get the total across each blog post metadata object.

Body:
I find your initial structure somewhat strange, given that you've pulled the author up into the above object and sorted the author's blog post metadata objects into those lists. Unless I misunderstand, and there is potentially the wrong author's blog post metadata objects under the author's key within the outer object.

At any rate, you should be able to solve this with a loop and a map/reduce.

const postMetadata = {
    "Edsger W. Dijkstra": [
        {
            author: "Edsger W. Dijkstra",
            likes: 5
        },
        {
            author: "Edsger W. Dijkstra",
            likes: 10
        }
    ],
    "Benizio Mauritez": [
        {
            author: "Benizio Mauritez",
            likes: 12
        },
        {
            author: "Benizio Mauritez",
            likes: 8
        }
    ]
};

// result will be a mapping from author to total likes, which is kinda the structure you've described.
const result = {};
for (let author in postMetadata) {
    let summedLikes = postMetadata[author]
        .map(postMeta => postMeta.likes)
        .reduce((sum, curr) => sum + curr);
    // Do something with summedLikes here
    // for example
    result[author] = summedLikes;
}

So what I do here is take your initial structure, I loop through each author, and then for each author's blog post metadata object, I use Array.prototype.map to just get an array of their likes values, and then I use Array.prototype.reduce to perform a summing function in order to get the total across each blog post metadata object.


问:
Passing multiple arguments with VBA?
My VBA doesn't work with more than the first parameter. Here is my sub header: Sub filterPivotTables(ParamArray argumentsArray() As Variant , sheetName As String,pivotTableName As String,pivotField As String)

However, when I change the sub header to this: Sub filterPivotTables(ParamArray argumentsArray() As Variant) it works.

Is there a reason why I can’t pass in more than one parameter? How would you pass in more than one parameter? Thanks

答:
ParamArray must be the last argument in the procedure declaration:

```<code>Sub filterPivotTables(sheetName As String, pivotTableName As String, pivotField As String, ParamArray argumentsArray() As Variant)
</code>```

See the docs for a more thorough discussion of ParamArray.

Title: Passing multiple arguments with VBA?

Body:
ParamArray must be the last argument in the procedure declaration:

Sub filterPivotTables(sheetName As String, pivotTableName As String, pivotField As String, ParamArray argumentsArray() As Variant)

See the docs for a more thorough discussion of ParamArray.


问:
Updating a Django Model from DetailView
I have a Django model that is receiving most of it's variable values from a form created by User 1 using CreateView. User 1 creates an object and selects most field values.

Once the object is created it is posted to a wall, another user (User 2) can access the object and add information for the final unfilled field. My question is, how do I allow for this functionality in the DetailView html form? In the code below, "basketball.salary2" is the previously empty field User 2 will be inputting and posting in the DetailView. All other values are already filled in and displaying in the HTML.

basketball_detail.html:

```<code>{% extends "base.html" %}

{% block title %}By: {{ basketball.creator }}{% endblock %}

{% block content %}

<h2>{{ basketball.creator }} has placed an opinion:</h2>
<p>{{ basketball.creator }} says that {{ basketball.player }} deserves
  {{ basketball.salary1 }}

<p> Do you agree with {{ basketball.creator }}? </p>

<p>I believe {{ basketball.player }} deserves {{ basketball.salary2 }} <p>

{% endblock content %}
</code>```

views.py:

```<code>from django.shortcuts import render
from django.views.generic import ListView, CreateView, DetailView
from django.contrib.auth.mixins import LoginRequiredMixin

from .models import Basketball

class BasketballListView(LoginRequiredMixin, ListView):
    model = Basketball

class BasketballDetailView(DetailView):
    model = Basketball

class BasketballCreateView(LoginRequiredMixin, CreateView):
    model = Basketball
    fields = [
    'player',
    'salary1',
    'salary2',
    ]

    def form_valid(self, form):
        form.instance.creator =self.request.user
        return super().form_valid(form)
</code>```

models.py:

```<code>from django.db import models
from django.urls import reverse
from django.conf import settings
from django.utils.text import slugify

from autoslug import AutoSlugField
from model_utils.models import TimeStampedModel

from nba_api.stats.static import players

PLAYER_CHOICES = [(i['full_name'], i['full_name']) for i in players.get_active_players()]

class Basketball(TimeStampedModel):
    player = models.CharField(max_length = 50, choices = PLAYER_CHOICES, default = None)
    slug = AutoSlugField("Basketball Player", unique = True, populate_from ="player")
    salary1 = models.DecimalField(decimal_places = 2, max_digits = 15)
    salary2 = models.DecimalField(decimal_places = 2, max_digits = 15)
    creator = models.ForeignKey(settings.AUTH_USER_MODEL,
    null = True,
    on_delete = models.SET_NULL
    )

    def get_absolute_url(self):
        return reverse(
        'basketball:detail', kwargs={'slug': self.slug}
        )

</code>```

答:
I think for this case UpdateView will work instead of DetailView.

```<code>class BasketballUpdateView(UpdateView):
    model = Basketball
</code>```

Title: Updating a Django Model from DetailView

Body:
I have a Django model that is receiving most of it's variable values from a form created by User 1 using CreateView. User 1 creates an object and selects most field values.

Once the object is created it is posted to a wall, another user (User 2) can access the object and add information for the final unfilled field. My question is, how do I allow for this functionality in the DetailView html form? In the code below, "basketball.salary2" is the previously empty field User 2 will be inputting and posting in the DetailView. All other values are already filled in and displaying in the HTML.

basketball_detail.html:

{% extends "base.html" %}

{% block title %}By: {{ basketball.creator }}{% endblock %}

{% block content %}

{{ basketball.creator }} has placed an opinion:

{{ basketball.creator }} says that {{ basketball.player }} deserves
  {{ basketball.salary1 }}

 Do you agree with {{ basketball.creator }}?

I believe {{ basketball.player }} deserves {{ basketball.salary2 }}

{% endblock content %}

views.py:

from django.shortcuts import render
from django.views.generic import ListView, CreateView, DetailView
from django.contrib.auth.mixins import LoginRequiredMixin

from .models import Basketball

class BasketballListView(LoginRequiredMixin, ListView):
    model = Basketball

class BasketballDetailView(DetailView):
    model = Basketball

class BasketballCreateView(LoginRequiredMixin, CreateView):
    model = Basketball
    fields = [
    'player',
    'salary1',
    'salary2',
    ]

    def form_valid(self, form):
        form.instance.creator =self.request.user
        return super().form_valid(form)

models.py:

from django.db import models
from django.urls import reverse
from django.conf import settings
from django.utils.text import slugify

from autoslug import AutoSlugField
from model_utils.models import TimeStampedModel

from nba_api.stats.static import players

PLAYER_CHOICES = [(i['full_name'], i['full_name']) for i in players.get_active_players()]

class Basketball(TimeStampedModel):
    player = models.CharField(max_length = 50, choices = PLAYER_CHOICES, default = None)
    slug = AutoSlugField("Basketball Player", unique = True, populate_from ="player")
    salary1 = models.DecimalField(decimal_places = 2, max_digits = 15)
    salary2 = models.DecimalField(decimal_places = 2, max_digits = 15)
    creator = models.ForeignKey(settings.AUTH_USER_MODEL,
    null = True,
    on_delete = models.SET_NULL
    )

    def get_absolute_url(self):
        return reverse(
        'basketball:detail', kwargs={'slug': self.slug}
        )

Body:
I think for this case UpdateView will work instead of DetailView.

class BasketballUpdateView(UpdateView):
    model = Basketball


问:
Split a python string by particular identifications
I am trying to split a python string when a particular character appears.

For example:

```<code>mystring="I want to eat an apple. \n 12345 \n 12 34 56"
</code>```

The output I want is a string with

```<code>[["I want to eat an apple"], [12345], [12, 34, 56]]
</code>```

答:
```<code>>>> mystring.split(" \n ")
['I want to eat an apple.', '12345', '12 34 56']
</code>```

If you specifically want each string inside its own list:

```<code>>>> [[s] for s in mystring.split(" \n ")]
[['I want to eat an apple.'], ['12345'], ['12 34 56']]
</code>```

Body:
I am trying to split a python string when a particular character appears.

For example:

mystring="I want to eat an apple. \n 12345 \n 12 34 56"

The output I want is a string with

[["I want to eat an apple"], [12345], [12, 34, 56]]

Body:
>>> mystring.split(" \n ")
['I want to eat an apple.', '12345', '12 34 56']

If you specifically want each string inside its own list:

>>> [[s] for s in mystring.split(" \n ")]
[['I want to eat an apple.'], ['12345'], ['12 34 56']]


问:
Is there way to bind queue to default exchange explicitly in RabbitMQ?
I made a mistake: now both of two queues are explicitly bound to some exchange, which i can edit for every queue. One of those queues must be bound to default exchange. Now when i try to change exchange of that queue to empty string, it throws an exception:

Caused by: com.rabbitmq.client.ShutdownSignalException: channel error; protocol method: #method<channel.close>(reply-code=403, reply-text=ACCESS_REFUSED - operation not permitted on the default exchange, class-id=<..>, method-id=<..>)

Can i pass some specific values to method com.rabbitmq.client.Channel#queueBind to bind queue to defaultChange?
I use Java RabbitMQ client library 5.6.0

答:
First, we need to understand what a default exchange is;

From RabbitMQ Docs

The default exchange is a direct exchange with no name (empty string)
  pre-declared by the broker. It has one special property that makes it
  very useful for simple applications: every queue that is created is
  automatically bound to it with a routing key which is the same as the
  queue name.

So basically, in other words, if you create a queue with no explicit exchange binding, the queue will have an automatic binding created with the default exchange.

In your question, from your description, it looks like you have two queues (lets say A and B) and you have accidentally bound both the queues to an exchange (lets say test.exchange). Instead of doing changes to the "default.exchange", what you should do is remove the binding of queue A or B with your exchange test.exchange.

Please check "/api/bindings" related apis on rabbitMQ Api Guides or you could simply login to the rabbit management console and remove the binding as well.


问:
Consuming OpenRasta services
Following advice on here, I am looking at whether to replace WCF with OpenRasta.

In Visual Studio, how do I consume an OpenRasta in the same way as I would a WCF/ASMX service e.g. Add a service reference, this handles the types using WSDL.

I can't find any examples which don't require a custom WebRequest and parse the xml, which for us is a significant step backwards for utilising a service in code.

答: OpenRasta is designed to give you RESTful services. To consume that, you might want to look at something like RestSharp which is designed to act as a client/consumer for RESTful services.</p>

Title: Consuming OpenRasta services


问:
LoadLibrary() on Windows XP 64 doesn't find DLL in SysWow64 unless it's in the path?
This goes with another question I asked where Windows XP x64 puts up message that an x86 application couldn't start because dll not found, but the app actually does start.   But it turns out to get rid of the message you can simply add c:\windows\syswow64 to the path before running the app and the message goes away.  Which means that it didn't automatically search in SysWow64.  Is that a known issue?  What's the best fix?

TIA!!

答: It appears to be related to console applications as x86 GUI apps run fine.  The answer is to add %SystemRoot%\SysWow64 to the path.</p>


问:
Kafka receive Sasl Exception from Zookeeper when SASL Authentication enabled
I am trying to set up an open-source Kafka cluster. Cluster is comprised of 2 Kafka nodes and 1 zookeeper. When I tried to enabled zookeeper SASL authentication, I got below exception. Providing Zookeeper and Kafka configuration files. Please help me where I am doing wrong.

```<code>ERROR SASL authentication failed using login context 'Client' with exception: {} (org.apache.zookeeper.client.ZooKeeperSaslClient)
javax.security.sasl.SaslException: Error in authenticating with a Zookeeper Quorum member: the quorum member's saslToken is null.
at org.apache.zookeeper.client.ZooKeeperSaslClient.createSaslToken(ZooKeeperSaslClient.java:279)
at org.apache.zookeeper.client.ZooKeeperSaslClient.respondToServer(ZooKeeperSaslClient.java:242)
at org.apache.zookeeper.ClientCnxn$SendThread.readResponse(ClientCnxn.java:805)
at org.apache.zookeeper.ClientCnxnSocketNIO.doIO(ClientCnxnSocketNIO.java:94)
at org.apache.zookeeper.ClientCnxnSocketNIO.doTransport(ClientCnxnSocketNIO.java:366)
at org.apache.zookeeper.ClientCnxn$SendThread.run(ClientCnxn.java:1145)
</code>```

My Zookeeper settings as below

1) zookeeper_jaas.conf

```<code>Server {
com.sun.security.auth.module.Krb5LoginModule required
useKeyTab=true
storeKey=true
keyTab="/tmp/zookeeper.service.keytab"
principal="zookeeper/<<Zookeeper-SERVER-INTERNAL-DNS>>@EXAMPLE.COM";
};
</code>```

2) zookeeper.properties

```<code>dataDir=/home/ubuntu/zookeeper
clientPort=2181
maxClientCnxns=0

authProvider.1=org.apache.zookeeper.server.auth.SASLAuthenticationProvider
jaasLoginRenew=3600000
</code>```

3) export "ZOOKEEPER_OPTS=-Djava.security.auth.login.config=/home/ubuntu/kafka/config/zookeeper_jaas.conf"

4) created ticket using zookeeper Keytab

5) Started the zookeeper server successfully which binds at the port 2181.

Kafka broker settings

1) kafka_server_jaas.conf

```<code>KafkaServer {
    com.sun.security.auth.module.Krb5LoginModule required
    useKeyTab=true
    storeKey=true
    keyTab="/tmp/kafka.service.keytab"
    principal="kafka/<<KAFKA-SERVER-PUBLIC-DNS>>@EXAMPLE.COM";
};

Client {
    com.sun.security.auth.module.Krb5LoginModule required
    useKeyTab=true
    storeKey=true
    servicename="zookeeper"
    keyTab="/tmp/kafka.service.keytab"
    principal="kafka/<<KAFKA-SERVER-PUBLIC-DNS>>@EXAMPLE.COM";
};
</code>```

2) Kafka_client_jass.conf

```<code>KafkaClient {
 com.sun.security.auth.module.Krb5LoginModule required
 useTicketCache=true;
 };
</code>```

3)server.properties

```<code>broker.id=0

listeners=PLAINTEXT://0.0.0.0:9092,SSL://0.0.0.0:9093,SASL_SSL://0.0.0.0:9094
advertised.listeners=PLAINTEXT://<<KAFKA-SERVER-PUBLIC-DNS>>:9092,SSL://<<KAFKA-SERVER-PUBLIC-DNS>>:9093,SASL_SSL://<<KAFKA-SERVER-PUBLIC-DNS>>:9094

zookeeper.connect=<<ZOOKEEPER-SERVER-PRIVATE-DNS>>:2181

sasl.enabled.mechanisms=GSSAPI
sasl.kerberos.service.name=kafka

ssl.keystore.location=/home/ubuntu/ssl/kafka.server.keystore.jks
ssl.keystore.password=serversecret
ssl.key.password=serversecret
ssl.truststore.location=/home/ubuntu/ssl/kafka.server.truststore.jks
ssl.truststore.password=serversecret

ssl.client.auth=required

num.network.threads=3
num.io.threads=8
socket.send.buffer.bytes=102400
socket.receive.buffer.bytes=102400
socket.request.max.bytes=104857600
auto.create.topics.enable=false
log.dirs=/home/ubuntu/kafka-logs
num.partitions=1
num.recovery.threads.per.data.dir=1
offsets.topic.replication.factor=1
transaction.state.log.replication.factor=1
transaction.state.log.min.isr=1
log.retention.hours=168
log.segment.bytes=1073741824
log.retention.check.interval.ms=300000
zookeeper.connection.timeout.ms=6000
</code>```

4) export "KAFKA_OPTS=-Djava.security.auth.login.config=/home/ubuntu/kafka/config/kafka_server_jaas.conf"

5) Created ticket using Kafka Keytab.

6) I started the Kafka broker and got the exception mentioned above.

答: Instead of ZOOKEEPER_OPTS use KAFKA_OPTS in zookeeper settings (point-3). This will work. Thanks!</p>

Body:
I am trying to set up an open-source Kafka cluster. Cluster is comprised of 2 Kafka nodes and 1 zookeeper. When I tried to enabled zookeeper SASL authentication, I got below exception. Providing Zookeeper and Kafka configuration files. Please help me where I am doing wrong.

ERROR SASL authentication failed using login context 'Client' with exception: {} (org.apache.zookeeper.client.ZooKeeperSaslClient)
javax.security.sasl.SaslException: Error in authenticating with a Zookeeper Quorum member: the quorum member's saslToken is null.
at org.apache.zookeeper.client.ZooKeeperSaslClient.createSaslToken(ZooKeeperSaslClient.java:279)
at org.apache.zookeeper.client.ZooKeeperSaslClient.respondToServer(ZooKeeperSaslClient.java:242)
at org.apache.zookeeper.ClientCnxn$SendThread.readResponse(ClientCnxn.java:805)
at org.apache.zookeeper.ClientCnxnSocketNIO.doIO(ClientCnxnSocketNIO.java:94)
at org.apache.zookeeper.ClientCnxnSocketNIO.doTransport(ClientCnxnSocketNIO.java:366)
at org.apache.zookeeper.ClientCnxn$SendThread.run(ClientCnxn.java:1145)

My Zookeeper settings as below

1) zookeeper_jaas.conf

Server {
com.sun.security.auth.module.Krb5LoginModule required
useKeyTab=true
storeKey=true
keyTab="/tmp/zookeeper.service.keytab"
principal="zookeeper/<<Zookeeper-SERVER-INTERNAL-DNS>>@EXAMPLE.COM";
};

2) zookeeper.properties

dataDir=/home/ubuntu/zookeeper
clientPort=2181
maxClientCnxns=0

authProvider.1=org.apache.zookeeper.server.auth.SASLAuthenticationProvider
jaasLoginRenew=3600000

3) export "ZOOKEEPER_OPTS=-Djava.security.auth.login.config=/home/ubuntu/kafka/config/zookeeper_jaas.conf"

4) created ticket using zookeeper Keytab

5) Started the zookeeper server successfully which binds at the port 2181.

Kafka broker settings

1) kafka_server_jaas.conf

KafkaServer {
    com.sun.security.auth.module.Krb5LoginModule required
    useKeyTab=true
    storeKey=true
    keyTab="/tmp/kafka.service.keytab"
    principal="kafka/<<KAFKA-SERVER-PUBLIC-DNS>>@EXAMPLE.COM";
};

Client {
    com.sun.security.auth.module.Krb5LoginModule required
    useKeyTab=true
    storeKey=true
    servicename="zookeeper"
    keyTab="/tmp/kafka.service.keytab"
    principal="kafka/<<KAFKA-SERVER-PUBLIC-DNS>>@EXAMPLE.COM";
};

2) Kafka_client_jass.conf

KafkaClient {
 com.sun.security.auth.module.Krb5LoginModule required
 useTicketCache=true;
 };

3)server.properties

broker.id=0

listeners=PLAINTEXT://0.0.0.0:9092,SSL://0.0.0.0:9093,SASL_SSL://0.0.0.0:9094
advertised.listeners=PLAINTEXT://<<KAFKA-SERVER-PUBLIC-DNS>>:9092,SSL://<<KAFKA-SERVER-PUBLIC-DNS>>:9093,SASL_SSL://<<KAFKA-SERVER-PUBLIC-DNS>>:9094

zookeeper.connect=<<ZOOKEEPER-SERVER-PRIVATE-DNS>>:2181

sasl.enabled.mechanisms=GSSAPI
sasl.kerberos.service.name=kafka

ssl.keystore.location=/home/ubuntu/ssl/kafka.server.keystore.jks
ssl.keystore.password=serversecret
ssl.key.password=serversecret
ssl.truststore.location=/home/ubuntu/ssl/kafka.server.truststore.jks
ssl.truststore.password=serversecret

ssl.client.auth=required

num.network.threads=3
num.io.threads=8
socket.send.buffer.bytes=102400
socket.receive.buffer.bytes=102400
socket.request.max.bytes=104857600
auto.create.topics.enable=false
log.dirs=/home/ubuntu/kafka-logs
num.partitions=1
num.recovery.threads.per.data.dir=1
offsets.topic.replication.factor=1
transaction.state.log.replication.factor=1
transaction.state.log.min.isr=1
log.retention.hours=168
log.segment.bytes=1073741824
log.retention.check.interval.ms=300000
zookeeper.connection.timeout.ms=6000

4) export "KAFKA_OPTS=-Djava.security.auth.login.config=/home/ubuntu/kafka/config/kafka_server_jaas.conf"

5) Created ticket using Kafka Keytab.

6) I started the Kafka broker and got the exception mentioned above.