问:
Using GLSLC's depfile to make included files automatically trigger recompile of SPIRV in CMake
I'm trying to create a cmake function that automatically recompiles glsl to spirv upon changes to the shader files.  Right now direct dependencies work, ie the shaders I use as compile arguments. However I make heavy use of #include feature that glslc provides, and by default I can't get changes in that stuff to trigger recompile. I made sure that I'm using the Ninja

Right now I have the following CMake function and arguments:

```<code>cmake -DCMAKE_BUILD_TYPE=Debug "-DCMAKE_MAKE_PROGRAM=JETBRAINSPATH/bin/ninja/win/ninja.exe" -G Ninja  "PATH_TO_CURRENT_DIRECTORY"
</code>```

function

```<code>set(GLSLC "$ENV{VULKAN_SDK}/Bin/glslc")

function(target_shader_function SHADER_TARGET)
    foreach (SHADER_SOURCE_FILEPATH ${ARGN})
        get_filename_component(SHADER_SOURCE_FILENAME ${SHADER_SOURCE_FILEPATH} NAME)
        get_filename_component(SHADER_SOURCE_DIRECTORY ${SHADER_SOURCE_FILEPATH} DIRECTORY)
        set(SHADER_TARGET_NAME "${SHADER_TARGET}_${SHADER_SOURCE_FILENAME}")
        set(SHADER_BINARY_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/spirv")
        set(SHADER_FINAL_BINARY_FILEPATH "${SHADER_BINARY_DIRECTORY}/${SHADER_SOURCE_FILENAME}.spv")
        #we can use depfiles instead
        #https://stackoverflow.com/questions/60420700/cmake-invocation-of-glslc-with-respect-to-includes-dependencies
        add_custom_command(
                OUTPUT ${SHADER_FINAL_BINARY_FILEPATH}
                DEPENDS ${SHADER_SOURCE_FILEPATH}
                DEPFILE ${SHADER_SOURCE_FILEPATH}.d
                COMMAND ${CMAKE_COMMAND} -E make_directory ${SHADER_BINARY_DIRECTORY}
                COMMAND ${GLSLC} -MD -MF ${SHADER_SOURCE_FILEPATH}.d -O ${SHADER_SOURCE_FILEPATH} -o ${SHADER_FINAL_BINARY_FILEPATH} --target-env=vulkan1.2 -I ${CMAKE_SOURCE_DIR}/shaderutils
                DEPENDS ${SHADER_SOURCE_FILEPATH}
                #                BYPRODUCTS ${SHADER_FINAL_BINARY_FILEPATH} ${SHADER_SOURCE_FILEPATH}.d causes ninja to no longer work
                COMMENT "Compiling SPIRV for \nsource: \n\t${SHADER_SOURCE_FILEPATH} \nbinary: \n\t${SHADER_FINAL_BINARY_FILEPATH} \n"
        )

        add_custom_target(${SHADER_TARGET_NAME} DEPENDS ${SHADER_FINAL_BINARY_FILEPATH} ${SHADER_SOURCE_FILEPATH}.d)
        add_dependencies(${SHADER_TARGET} ${SHADER_TARGET_NAME})
    endforeach (SHADER_SOURCE_FILEPATH)
endfunction()
</code>```

and I use it like this:

```<code>cmake_minimum_required(VERSION 3.21)
cmake_policy(SET CMP0116 NEW)
project(my_workspace)
add_executable(my_target main.cpp)
...
target_shader_function(my_target
        ${CMAKE_CURRENT_SOURCE_DIR}/shaders/example.comp
        )
</code>```

main.cpp

```<code>#include <iostream>

int main(){
std::cout << "hello world!" << std::endl;
return 0;
}
</code>```

Again, everything works fine if I change, for example, example.comp.

However, lets say I have the following shader (lets say that this is example.comp):

```<code>#version 460
#include "fooutils.glsl"
#define WORKGROUP_SIZE 1024
layout (local_size_x = WORKGROUP_SIZE, local_size_y = 1, local_size_z = 1) in;
layout(set = 0, binding = 0) buffer MyBufferBlock{
    float data[];
}
void main(){
   uint tidx = gl_GlobalInvocationID.x;
   data[tidx] += foo(tidx);
}
</code>```

and I include the following:

```<code>#ifndef FOOUTILS_GLSL
#define FOOUTILS_GLSL

float foo(uint tidx){
    return mod(tidx, 4.51);
}

#endif //FOOUTILS_GLSL
</code>```

and I change fooutils.glsl after everything is compiled once (for example in a way that stops it from compiling),

```<code>#ifndef FOOUTILS_GLSL
#define FOOUTILS_GLSL

float foo(uint tidx){
    return x;
    return mod(tidx, 4.51);
}

#endif //FOOUTILS_GLSL
</code>```

I don't get a recompile triggered.  I had assumed that ninja would use this info to accomplish this, but I haven't seen it happen.

How do I use this depfile to force a recompile when an include dependency changes?

答:
Here's my working implementation. But first, here's my terminal output so you can see it's working:

```<code>$ tree
.
├── CMakeLists.txt
├── main.cpp
├── shaders
│   └── example.comp
└── shaderutils
    └── fooutils.glsl
$ cmake -S . -B build -DCMAKE_BUILD_TYPE=Release
...
$ cmake --build build/
[1/3] Compiling SPIRV: shaders/example.comp -> spirv/example.spv
[2/3] Building CXX object CMakeFiles/my_target.dir/main.cpp.o
[3/3] Linking CXX executable my_target
$ cmake --build build/
ninja: no work to do.
$ touch shaderutils/fooutils.glsl
$ cmake --build build/
[1/1] Compiling SPIRV: shaders/example.comp -> spirv/example.spv
$ cat build/spirv/example.d
spirv/example.spv: /path/to/shaders/example.comp /path/to/shaderutils/fooutils.glsl
$ cat build/CMakeFiles/d/*.d
spirv/example.spv: \
  ../shaders/example.comp \
  ../shaderutils/fooutils.glsl
</code>```

Now on to the implementation

```<code>cmake_minimum_required(VERSION 3.22)
project(test)

function(target_shader_function TARGET)
    find_package(Vulkan REQUIRED)

    if (NOT TARGET Vulkan::glslc)
        message(FATAL_ERROR "Could not find glslc")
    endif ()

    foreach (source IN LISTS ARGN)
        cmake_path(ABSOLUTE_PATH source OUTPUT_VARIABLE source_abs)
        cmake_path(GET source STEM basename)

        set(depfile "spirv/${basename}.d")
        set(output "spirv/${basename}.spv")
        set(dirs "$<TARGET_PROPERTY:${TARGET},INCLUDE_DIRECTORIES>")
        set(include_flags "$<$<BOOL:${dirs}>:-I$<JOIN:${dirs},;-I>>")

        add_custom_command(
            OUTPUT "${output}"
            COMMAND "${CMAKE_COMMAND}" -E make_directory spirv
            COMMAND Vulkan::glslc -MD -MF "${depfile}" -O "${source_abs}"
                    -o "${output}" --target-env=vulkan1.2 "${include_flags}"
            DEPENDS "${source_abs}"
            BYPRODUCTS "${depfile}"
            COMMENT "Compiling SPIRV: ${source} -> ${output}"
            DEPFILE "${depfile}"
            VERBATIM
            COMMAND_EXPAND_LISTS
        )

        set(shader_target "${TARGET}_${basename}")
        add_custom_target("${shader_target}"
                          DEPENDS "${CMAKE_CURRENT_BINARY_DIR}/${output}")
        add_dependencies("${TARGET}" "${shader_target}")
    endforeach ()
endfunction()

add_executable(my_target main.cpp)
target_shader_function(my_target shaders/example.comp)
target_include_directories(
    my_target PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/shaderutils")
</code>```

With a CMake minimum version of 3.20 or greater, CMP0116 will be set, which adjusts depfiles that were generated with relative paths to be relative to the top-level binary directory. You can see this in action in the last two command outputs.

For compatibility with this policy, the command to invoke glslc is careful to use only absolute paths or paths relative to ${CMAKE_CURRENT_BINARY_DIR}.

To increase the reusability of this function, I had it reuse the include paths from the TARGET rather than hard-coding shaderutils.

Also remember to always pass absolute paths to the DEPENDS arguments of add_custom_{command,target} to avoid surprising path resolution behaviors.

Finally, since CMake actually comes with a FindVulkan module that can locate glslc, we use that to get the Vulkan::glslc target. Per the documentation, it can be overridden by setting Vulkan_GLSLC_EXECUTABLE.

Terminal logs for VS2022 on Windows with MSVC:

```<code>> cmake -S . -B build
...
> cmake --build build --config Release
  Checking Build System
  Compiling SPIRV: shaders/example.comp -> spirv/example.spv
  Building Custom Rule D:/test/CMakeLists.txt
  Building Custom Rule D:/test/CMakeLists.txt
  main.cpp
  my_target.vcxproj -> D:\test\build\Release\my_target.exe
  Building Custom Rule D:/test/CMakeLists.txt

> cmake --build build --config Release -- -noLogo
  my_target.vcxproj -> D:\test\build\Release\my_target.exe

> notepad shaderutils\fooutils.glsl
> cmake --build build --config Release -- -noLogo
  Compiling SPIRV: shaders/example.comp -> spirv/example.spv
  my_target.vcxproj -> D:\test\build\Release\my_target.exe

> cmake --build build --config Release -- -noLogo
  my_target.vcxproj -> D:\test\build\Release\my_target.exe
</code>```

and again with Ninja instead of msbuild:

```<code>> cmake -G Ninja -S . -B build -DCMAKE_BUILD_TYPE=Release ^
        -DVulkan_ROOT=C:/VulkanSDK/1.2.198.1
...
> powershell "cmake --build build | tee output.txt"
[1/3] Compiling SPIRV: shaders/example.comp -> spirv/example.spv
[2/3] Building CXX object CMakeFiles\my_target.dir\main.cpp.obj
[3/3] Linking CXX executable my_target.exe

> powershell "cmake --build build | tee output.txt"
ninja: no work to do.

> notepad shaderutils\fooutils.glsl
> powershell "cmake --build build | tee output.txt"
[1/1] Compiling SPIRV: shaders/example.comp -> spirv/example.spv
</code>```

The little powershell + tee trick is just to keep the Ninja command log from overwriting itself. I could use --verbose, but then the full command lines would be printed, rather than the tidy summaries.

Body:
I'm trying to create a cmake function that automatically recompiles glsl to spirv upon changes to the shader files.  Right now direct dependencies work, ie the shaders I use as compile arguments. However I make heavy use of #include feature that glslc provides, and by default I can't get changes in that stuff to trigger recompile. I made sure that I'm using the Ninja

Right now I have the following CMake function and arguments:

cmake -DCMAKE_BUILD_TYPE=Debug "-DCMAKE_MAKE_PROGRAM=JETBRAINSPATH/bin/ninja/win/ninja.exe" -G Ninja  "PATH_TO_CURRENT_DIRECTORY"

function

set(GLSLC "$ENV{VULKAN_SDK}/Bin/glslc")

function(target_shader_function SHADER_TARGET)
    foreach (SHADER_SOURCE_FILEPATH ${ARGN})
        get_filename_component(SHADER_SOURCE_FILENAME ${SHADER_SOURCE_FILEPATH} NAME)
        get_filename_component(SHADER_SOURCE_DIRECTORY ${SHADER_SOURCE_FILEPATH} DIRECTORY)
        set(SHADER_TARGET_NAME "${SHADER_TARGET}_${SHADER_SOURCE_FILENAME}")
        set(SHADER_BINARY_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/spirv")
        set(SHADER_FINAL_BINARY_FILEPATH "${SHADER_BINARY_DIRECTORY}/${SHADER_SOURCE_FILENAME}.spv")
        #we can use depfiles instead
        #https://stackoverflow.com/questions/60420700/cmake-invocation-of-glslc-with-respect-to-includes-dependencies
        add_custom_command(
                OUTPUT ${SHADER_FINAL_BINARY_FILEPATH}
                DEPENDS ${SHADER_SOURCE_FILEPATH}
                DEPFILE ${SHADER_SOURCE_FILEPATH}.d
                COMMAND ${CMAKE_COMMAND} -E make_directory ${SHADER_BINARY_DIRECTORY}
                COMMAND ${GLSLC} -MD -MF ${SHADER_SOURCE_FILEPATH}.d -O ${SHADER_SOURCE_FILEPATH} -o ${SHADER_FINAL_BINARY_FILEPATH} --target-env=vulkan1.2 -I ${CMAKE_SOURCE_DIR}/shaderutils
                DEPENDS ${SHADER_SOURCE_FILEPATH}
                #                BYPRODUCTS ${SHADER_FINAL_BINARY_FILEPATH} ${SHADER_SOURCE_FILEPATH}.d causes ninja to no longer work
                COMMENT "Compiling SPIRV for \nsource: \n\t${SHADER_SOURCE_FILEPATH} \nbinary: \n\t${SHADER_FINAL_BINARY_FILEPATH} \n"
        )

        add_custom_target(${SHADER_TARGET_NAME} DEPENDS ${SHADER_FINAL_BINARY_FILEPATH} ${SHADER_SOURCE_FILEPATH}.d)
        add_dependencies(${SHADER_TARGET} ${SHADER_TARGET_NAME})
    endforeach (SHADER_SOURCE_FILEPATH)
endfunction()

and I use it like this:

cmake_minimum_required(VERSION 3.21)
cmake_policy(SET CMP0116 NEW)
project(my_workspace)
add_executable(my_target main.cpp)
...
target_shader_function(my_target
        ${CMAKE_CURRENT_SOURCE_DIR}/shaders/example.comp
        )

main.cpp

#include <iostream>

int main(){
std::cout << "hello world!" << std::endl;
return 0;
}

Again, everything works fine if I change, for example, example.comp.

However, lets say I have the following shader (lets say that this is example.comp):

#version 460
#include "fooutils.glsl"
#define WORKGROUP_SIZE 1024
layout (local_size_x = WORKGROUP_SIZE, local_size_y = 1, local_size_z = 1) in;
layout(set = 0, binding = 0) buffer MyBufferBlock{
    float data[];
}
void main(){
   uint tidx = gl_GlobalInvocationID.x;
   data[tidx] += foo(tidx);
}

and I include the following:

#ifndef FOOUTILS_GLSL
#define FOOUTILS_GLSL

float foo(uint tidx){
    return mod(tidx, 4.51);
}

#endif //FOOUTILS_GLSL

and I change fooutils.glsl after everything is compiled once (for example in a way that stops it from compiling),

#ifndef FOOUTILS_GLSL
#define FOOUTILS_GLSL

float foo(uint tidx){
    return x;
    return mod(tidx, 4.51);
}

#endif //FOOUTILS_GLSL

I don't get a recompile triggered.  I had assumed that ninja would use this info to accomplish this, but I haven't seen it happen.

How do I use this depfile to force a recompile when an include dependency changes?

Body:
Here's my working implementation. But first, here's my terminal output so you can see it's working:

$ tree
.
├── CMakeLists.txt
├── main.cpp
├── shaders
│   └── example.comp
└── shaderutils
    └── fooutils.glsl
$ cmake -S . -B build -DCMAKE_BUILD_TYPE=Release
...
$ cmake --build build/
[1/3] Compiling SPIRV: shaders/example.comp -> spirv/example.spv
[2/3] Building CXX object CMakeFiles/my_target.dir/main.cpp.o
[3/3] Linking CXX executable my_target
$ cmake --build build/
ninja: no work to do.
$ touch shaderutils/fooutils.glsl
$ cmake --build build/
[1/1] Compiling SPIRV: shaders/example.comp -> spirv/example.spv
$ cat build/spirv/example.d
spirv/example.spv: /path/to/shaders/example.comp /path/to/shaderutils/fooutils.glsl
$ cat build/CMakeFiles/d/*.d
spirv/example.spv: \
  ../shaders/example.comp \
  ../shaderutils/fooutils.glsl

Now on to the implementation

cmake_minimum_required(VERSION 3.22)
project(test)

function(target_shader_function TARGET)
    find_package(Vulkan REQUIRED)

    if (NOT TARGET Vulkan::glslc)
        message(FATAL_ERROR "Could not find glslc")
    endif ()

    foreach (source IN LISTS ARGN)
        cmake_path(ABSOLUTE_PATH source OUTPUT_VARIABLE source_abs)
        cmake_path(GET source STEM basename)

        set(depfile "spirv/${basename}.d")
        set(output "spirv/${basename}.spv")
        set(dirs "$<TARGET_PROPERTY:${TARGET},INCLUDE_DIRECTORIES>")
        set(include_flags "$<$<BOOL:${dirs}>:-I$<JOIN:${dirs},;-I>>")

        add_custom_command(
            OUTPUT "${output}"
            COMMAND "${CMAKE_COMMAND}" -E make_directory spirv
            COMMAND Vulkan::glslc -MD -MF "${depfile}" -O "${source_abs}"
                    -o "${output}" --target-env=vulkan1.2 "${include_flags}"
            DEPENDS "${source_abs}"
            BYPRODUCTS "${depfile}"
            COMMENT "Compiling SPIRV: ${source} -> ${output}"
            DEPFILE "${depfile}"
            VERBATIM
            COMMAND_EXPAND_LISTS
        )

        set(shader_target "${TARGET}_${basename}")
        add_custom_target("${shader_target}"
                          DEPENDS "${CMAKE_CURRENT_BINARY_DIR}/${output}")
        add_dependencies("${TARGET}" "${shader_target}")
    endforeach ()
endfunction()

add_executable(my_target main.cpp)
target_shader_function(my_target shaders/example.comp)
target_include_directories(
    my_target PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/shaderutils")

With a CMake minimum version of 3.20 or greater, CMP0116 will be set, which adjusts depfiles that were generated with relative paths to be relative to the top-level binary directory. You can see this in action in the last two command outputs.

For compatibility with this policy, the command to invoke glslc is careful to use only absolute paths or paths relative to ${CMAKE_CURRENT_BINARY_DIR}.

To increase the reusability of this function, I had it reuse the include paths from the TARGET rather than hard-coding shaderutils.

Also remember to always pass absolute paths to the DEPENDS arguments of add_custom_{command,target} to avoid surprising path resolution behaviors.

Finally, since CMake actually comes with a FindVulkan module that can locate glslc, we use that to get the Vulkan::glslc target. Per the documentation, it can be overridden by setting Vulkan_GLSLC_EXECUTABLE.

Terminal logs for VS2022 on Windows with MSVC:

> cmake -S . -B build
...
> cmake --build build --config Release
  Checking Build System
  Compiling SPIRV: shaders/example.comp -> spirv/example.spv
  Building Custom Rule D:/test/CMakeLists.txt
  Building Custom Rule D:/test/CMakeLists.txt
  main.cpp
  my_target.vcxproj -> D:\test\build\Release\my_target.exe
  Building Custom Rule D:/test/CMakeLists.txt

> cmake --build build --config Release -- -noLogo
  my_target.vcxproj -> D:\test\build\Release\my_target.exe

> notepad shaderutils\fooutils.glsl
> cmake --build build --config Release -- -noLogo
  Compiling SPIRV: shaders/example.comp -> spirv/example.spv
  my_target.vcxproj -> D:\test\build\Release\my_target.exe

> cmake --build build --config Release -- -noLogo
  my_target.vcxproj -> D:\test\build\Release\my_target.exe

and again with Ninja instead of msbuild:

> cmake -G Ninja -S . -B build -DCMAKE_BUILD_TYPE=Release ^
        -DVulkan_ROOT=C:/VulkanSDK/1.2.198.1
...
> powershell "cmake --build build | tee output.txt"
[1/3] Compiling SPIRV: shaders/example.comp -> spirv/example.spv
[2/3] Building CXX object CMakeFiles\my_target.dir\main.cpp.obj
[3/3] Linking CXX executable my_target.exe

> powershell "cmake --build build | tee output.txt"
ninja: no work to do.

> notepad shaderutils\fooutils.glsl
> powershell "cmake --build build | tee output.txt"
[1/1] Compiling SPIRV: shaders/example.comp -> spirv/example.spv

The little powershell + tee trick is just to keep the Ninja command log from overwriting itself. I could use --verbose, but then the full command lines would be printed, rather than the tidy summaries.


来源: stackexchange

问:
How can I, scrape data from a Javascript Content of a website?
Actually, I am trying to fetch the content from the Product Description from the Nykaa Website.

URL:- https://www.nykaa.com/nykaa-skinshield-matte-foundation/p/460512?productId=460512&pps=1&skuId=460502

This is the URL, and in the section of the Product description, clicking upon the 'Read More' button, at the end there is some text.

The Text which, I want to extract is :

Explore the entire range of Foundation available on Nykaa. Shop more
Nykaa Cosmetics products here.You can browse through the complete
world of Nykaa Cosmetics Foundation . Alternatively, you can also find
many more products from the Nykaa SkinShield Anti-Pollution Matte
Foundation range.

Expiry Date: 15 February 2024

Country of Origin: India

Name of Mfg / Importer / Brand: FSN E-commerce Ventures Pvt Ltd

Address of Mfg / Importer / Brand: 104 Vasan Udyog Bhavan Sun Mill
Compound Senapati Bapat Marg, Lower Parel, Mumbai City Maharashtra -
400013

After inspecting the page, when I, 'disable the javascript' all the content from 'product description' vanishes off. It means the content is loading dynamically with the help of Javascript.

I have used 'selenium' for this purpose. And This, is what I have tried.

```<code>from msilib.schema import Error
from tkinter import ON
from turtle import goto
import time
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import numpy as np
from random import randint
import pandas as pd
import requests
import csv

browser = webdriver.Chrome(
    r'C:\Users\paart\.wdm\drivers\chromedriver\win32\97.0.4692.71\chromedriver.exe')

browser.maximize_window()  # For maximizing window
browser.implicitly_wait(20)  # gives an implicit wait for 20 seconds

browser.get(
    "https://www.nykaa.com/nykaa-skinshield-matte-foundation/p/460512?productId=460512&pps=1&skuId=460502")

# Creates "load more" button object.
browser.implicitly_wait(20)
loadMore = browser.find_element_by_xpath(xpath="/html/body/div[1]/div/div[3]/div[1]/div[2]/div/div/div[2]")

loadMore.click()
browser.implicitly_wait(20)

desc_data = browser.find_elements_by_class_name('content-details')

for desc in desc_data:
    para_details = browser.find_element_by_xpath(
        './/*[@id="content-details"]/p[1]').text
    extra_details = browser.find_elements_by_xpath(
        './/*[@id="content-details"]/p[2]', './/*[@id="content-details"]/p[3]', './/*[@id="content-details"]/p[4]', './/*[@id="content-details"]/p[5]').text
    print(para_details, extra_details)
</code>```

And this, is the output which is displaying.

```<code>PS E:\Web Scraping - Nykaa> python -u "e:\Web Scraping - Nykaa\scrape_nykaa_final.py"
e:\Web Scraping - Nykaa\scrape_nykaa_final.py:16: DeprecationWarning: executable_path has been deprecated, please pass in a Service object
  browser = webdriver.Chrome(

DevTools listening on ws://127.0.0.1:1033/devtools/browser/097c0e11-6f2c-4742-a2b5-cd05bee72661
e:\Web Scraping - Nykaa\scrape_nykaa_final.py:28: DeprecationWarning: find_element_by_* commands are deprecated. Please use find_element() instead
  loadMore = browser.find_element_by_xpath(
[9312:4972:0206/110327.883:ERROR:ssl_client_socket_impl.cc(996)] handshake failed; returned -1, SSL error code 1, net_error -101
[9312:4972:0206/110328.019:ERROR:ssl_client_socket_impl.cc(996)] handshake failed; returned -1, SSL error code 1, net_error -101
Traceback (most recent call last):
  File "e:\Web Scraping - Nykaa\scrape_nykaa_final.py", line 28, in <module>
    loadMore = browser.find_element_by_xpath(
  File "C:\Python310\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 520, in find_element_by_xpath
    return self.find_element(by=By.XPATH, value=xpath)
  File "C:\Python310\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 1244, in find_element
    return self.execute(Command.FIND_ELEMENT, {
  File "C:\Python310\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 424, in execute
    self.error_handler.check_response(response)
  File "C:\Python310\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 247, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"/html/body/div[1]/div/div[3]/div[1]/div[2]/div/div/div[2]"}
  (Session info: chrome=97.0.4692.99)
Stacktrace:
Backtrace:
        Ordinal0 [0x00FDFDC3+2555331]
        Ordinal0 [0x00F777F1+2127857]
        Ordinal0 [0x00E72E08+1060360]
        Ordinal0 [0x00E9E49E+1238174]
        Ordinal0 [0x00E9E69B+1238683]
        Ordinal0 [0x00EC9252+1413714]
        Ordinal0 [0x00EB7B54+1342292]
        Ordinal0 [0x00EC75FA+1406458]
        Ordinal0 [0x00EB7976+1341814]
        Ordinal0 [0x00E936B6+1193654]
        Ordinal0 [0x00E94546+1197382]
        GetHandleVerifier [0x01179622+1619522]
        GetHandleVerifier [0x0122882C+2336844]
        GetHandleVerifier [0x010723E1+541697]
        GetHandleVerifier [0x01071443+537699]
        Ordinal0 [0x00F7D18E+2150798]
        Ordinal0 [0x00F81518+2168088]
        Ordinal0 [0x00F81660+2168416]
        Ordinal0 [0x00F8B330+2208560]
        BaseThreadInitThunk [0x76C9FA29+25]
        RtlGetAppContainerNamedObjectPath [0x77337A9E+286]
        RtlGetAppContainerNamedObjectPath [0x77337A6E+238]
</code>```

Please, anyone help me getting this issue resolved, or any another specific piece of the code to write, which I am missing to fetch the text content from Product description. It would be a big help.

Thanks .

答:
try

```<code>from msilib.schema import Error
from tkinter import ON
from turtle import goto
import time
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import numpy as np
from random import randint
import pandas as pd
import requests
import csv

browser = webdriver.Chrome(
    r'C:\Users\paart\.wdm\drivers\chromedriver\win32\97.0.4692.71\chromedriver.exe')

browser.maximize_window()  # For maximizing window
browser.implicitly_wait(20)  # gives an implicit wait for 20 seconds

browser.get(
    "https://www.nykaa.com/nykaa-skinshield-matte-foundation/p/460512?productId=460512&pps=1&skuId=460502")

browser.execute_script("document.body.style.zoom='50%'")
time.sleep(1)
browser.execute_script("document.body.style.zoom='100%'")

# Creates "load more" button object.
browser.implicitly_wait(20)
loadMore = browser.find_element_by_xpath(xpath='//div [@class="css-mqbsar"]')
loadMore.click()

browser.implicitly_wait(20)
desc_data = browser.find_elements_by_xpath('//div[@id="content-details"]/p')

# desc_data = browser.find_elements_by_class_name('content-details')
# here in your previous code this class('content-details') which is a single element so it is not iterable
# I used xpath to locate every every element <p> under the (id="content-details) attrid=bute

for desc in desc_data:
    para_detail = desc.text
    print(para_detail)

# if you you want to specify try this
#  para_detail = desc_data[0].text
#  expiry_ date = desc_data[1].text

</code>```

and don't just copy the XPath from the chrome dev tools it's not reliable for dynamic content.

ContentLicense: CC BY-SA 4.0

Body:
Actually, I am trying to fetch the content from the Product Description from the Nykaa Website.

URL:- https://www.nykaa.com/nykaa-skinshield-matte-foundation/p/460512?productId=460512&pps=1&skuId=460502

This is the URL, and in the section of the Product description, clicking upon the 'Read More' button, at the end there is some text.

The Text which, I want to extract is :

Explore the entire range of Foundation available on Nykaa. Shop more
Nykaa Cosmetics products here.You can browse through the complete
world of Nykaa Cosmetics Foundation . Alternatively, you can also find
many more products from the Nykaa SkinShield Anti-Pollution Matte
Foundation range.

Expiry Date: 15 February 2024

Country of Origin: India

Name of Mfg / Importer / Brand: FSN E-commerce Ventures Pvt Ltd

Address of Mfg / Importer / Brand: 104 Vasan Udyog Bhavan Sun Mill
Compound Senapati Bapat Marg, Lower Parel, Mumbai City Maharashtra -
400013

After inspecting the page, when I, 'disable the javascript' all the content from 'product description' vanishes off. It means the content is loading dynamically with the help of Javascript.

I have used 'selenium' for this purpose. And This, is what I have tried.

from msilib.schema import Error
from tkinter import ON
from turtle import goto
import time
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import numpy as np
from random import randint
import pandas as pd
import requests
import csv

browser = webdriver.Chrome(
    r'C:\Users\paart\.wdm\drivers\chromedriver\win32\97.0.4692.71\chromedriver.exe')

browser.maximize_window()  # For maximizing window
browser.implicitly_wait(20)  # gives an implicit wait for 20 seconds

browser.get(
    "https://www.nykaa.com/nykaa-skinshield-matte-foundation/p/460512?productId=460512&pps=1&skuId=460502")

# Creates "load more" button object.
browser.implicitly_wait(20)
loadMore = browser.find_element_by_xpath(xpath="/html/body/div[1]/div/div[3]/div[1]/div[2]/div/div/div[2]")

loadMore.click()
browser.implicitly_wait(20)

desc_data = browser.find_elements_by_class_name('content-details')

for desc in desc_data:
    para_details = browser.find_element_by_xpath(
        './/*[@id="content-details"]/p[1]').text
    extra_details = browser.find_elements_by_xpath(
        './/*[@id="content-details"]/p[2]', './/*[@id="content-details"]/p[3]', './/*[@id="content-details"]/p[4]', './/*[@id="content-details"]/p[5]').text
    print(para_details, extra_details)

And this, is the output which is displaying.

PS E:\Web Scraping - Nykaa> python -u "e:\Web Scraping - Nykaa\scrape_nykaa_final.py"
e:\Web Scraping - Nykaa\scrape_nykaa_final.py:16: DeprecationWarning: executable_path has been deprecated, please pass in a Service object
  browser = webdriver.Chrome(

DevTools listening on ws://127.0.0.1:1033/devtools/browser/097c0e11-6f2c-4742-a2b5-cd05bee72661
e:\Web Scraping - Nykaa\scrape_nykaa_final.py:28: DeprecationWarning: find_element_by_* commands are deprecated. Please use find_element() instead
  loadMore = browser.find_element_by_xpath(
[9312:4972:0206/110327.883:ERROR:ssl_client_socket_impl.cc(996)] handshake failed; returned -1, SSL error code 1, net_error -101
[9312:4972:0206/110328.019:ERROR:ssl_client_socket_impl.cc(996)] handshake failed; returned -1, SSL error code 1, net_error -101
Traceback (most recent call last):
  File "e:\Web Scraping - Nykaa\scrape_nykaa_final.py", line 28, in <module>
    loadMore = browser.find_element_by_xpath(
  File "C:\Python310\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 520, in find_element_by_xpath
    return self.find_element(by=By.XPATH, value=xpath)
  File "C:\Python310\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 1244, in find_element
    return self.execute(Command.FIND_ELEMENT, {
  File "C:\Python310\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 424, in execute
    self.error_handler.check_response(response)
  File "C:\Python310\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 247, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"/html/body/div[1]/div/div[3]/div[1]/div[2]/div/div/div[2]"}
  (Session info: chrome=97.0.4692.99)
Stacktrace:
Backtrace:
        Ordinal0 [0x00FDFDC3+2555331]
        Ordinal0 [0x00F777F1+2127857]
        Ordinal0 [0x00E72E08+1060360]
        Ordinal0 [0x00E9E49E+1238174]
        Ordinal0 [0x00E9E69B+1238683]
        Ordinal0 [0x00EC9252+1413714]
        Ordinal0 [0x00EB7B54+1342292]
        Ordinal0 [0x00EC75FA+1406458]
        Ordinal0 [0x00EB7976+1341814]
        Ordinal0 [0x00E936B6+1193654]
        Ordinal0 [0x00E94546+1197382]
        GetHandleVerifier [0x01179622+1619522]
        GetHandleVerifier [0x0122882C+2336844]
        GetHandleVerifier [0x010723E1+541697]
        GetHandleVerifier [0x01071443+537699]
        Ordinal0 [0x00F7D18E+2150798]
        Ordinal0 [0x00F81518+2168088]
        Ordinal0 [0x00F81660+2168416]
        Ordinal0 [0x00F8B330+2208560]
        BaseThreadInitThunk [0x76C9FA29+25]
        RtlGetAppContainerNamedObjectPath [0x77337A9E+286]
        RtlGetAppContainerNamedObjectPath [0x77337A6E+238]

Please, anyone help me getting this issue resolved, or any another specific piece of the code to write, which I am missing to fetch the text content from Product description. It would be a big help.

Thanks .

Body:
try

from msilib.schema import Error
from tkinter import ON
from turtle import goto
import time
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import numpy as np
from random import randint
import pandas as pd
import requests
import csv

browser = webdriver.Chrome(
    r'C:\Users\paart\.wdm\drivers\chromedriver\win32\97.0.4692.71\chromedriver.exe')

browser.maximize_window()  # For maximizing window
browser.implicitly_wait(20)  # gives an implicit wait for 20 seconds

browser.get(
    "https://www.nykaa.com/nykaa-skinshield-matte-foundation/p/460512?productId=460512&pps=1&skuId=460502")

browser.execute_script("document.body.style.zoom='50%'")
time.sleep(1)
browser.execute_script("document.body.style.zoom='100%'")

# Creates "load more" button object.
browser.implicitly_wait(20)
loadMore = browser.find_element_by_xpath(xpath='//div [@class="css-mqbsar"]')
loadMore.click()

browser.implicitly_wait(20)
desc_data = browser.find_elements_by_xpath('//div[@id="content-details"]/p')

# desc_data = browser.find_elements_by_class_name('content-details')
# here in your previous code this class('content-details') which is a single element so it is not iterable
# I used xpath to locate every every element <p> under the (id="content-details) attrid=bute

for desc in desc_data:
    para_detail = desc.text
    print(para_detail)

# if you you want to specify try this
#  para_detail = desc_data[0].text
#  expiry_ date = desc_data[1].text

and don't just copy the XPath from the chrome dev tools it's not reliable for dynamic content.


问:
Palindrome problem - What am I doing wrong Here?
Problem statement:
You are given a binary string S and an integer K. In one operation, you can pick any bit and flip it, i.e turn 0 to 1 or 1 to 0. Can you make the string S a palindrome using exactly K operations?

Print YES if this is possible, and NO if it is not.

Input Format
The first line of input contains one integer T, denoting the number of test cases. The description of T test cases follows.
Each test case consists of two lines of input.
The first line of each test case contains two space-separated integers N and K, denoting the length of the binary string and the number of operations to be performed.
The second line contains the binary string S.
Output Format
For each test case, print the answer on a new line — YES if the S can be made a palindrome using exactly K operations, and NO otherwise.

You may print each character of YES and NO in either uppercase or lowercase (for example, yes, yEs, Yes will all be considered identical).

My solution:

```<code>T = int(input())
for i in range(T):
    N,K = map(int,input().split())
    S = input()
    counter = 0
    for i in range(int(len(S)/2)):
        if S[i] == S[-1-i]:
            continue
        else:
            counter = counter + 1
    if counter == K:
        print("Yes")
    else:
        print("No")
</code>```

But on submission, it shows the wrong answer, and upon custom input, it shows correct output, can someone point out what am I doing wrong?

答: Maybe because you're using len(S) instead of N</p>

Body:
Problem statement:
You are given a binary string S and an integer K. In one operation, you can pick any bit and flip it, i.e turn 0 to 1 or 1 to 0. Can you make the string S a palindrome using exactly K operations?

Print YES if this is possible, and NO if it is not.

Input Format
The first line of input contains one integer T, denoting the number of test cases. The description of T test cases follows.
Each test case consists of two lines of input.
The first line of each test case contains two space-separated integers N and K, denoting the length of the binary string and the number of operations to be performed.
The second line contains the binary string S.
Output Format
For each test case, print the answer on a new line — YES if the S can be made a palindrome using exactly K operations, and NO otherwise.

You may print each character of YES and NO in either uppercase or lowercase (for example, yes, yEs, Yes will all be considered identical).

My solution:

T = int(input())
for i in range(T):
    N,K = map(int,input().split())
    S = input()
    counter = 0
    for i in range(int(len(S)/2)):
        if S[i] == S[-1-i]:
            continue
        else:
            counter = counter + 1
    if counter == K:
        print("Yes")
    else:
        print("No")

But on submission, it shows the wrong answer, and upon custom input, it shows correct output, can someone point out what am I doing wrong?


问:
What's the correct way of posting this data asynchronously, and canceling/queuing new requests?
I am attempting to improve the stability of the web dashboard I have created. I have noticed that the main cause of getting into a bad state is when the user moves too quickly and requests get cut short.

For instance, I have the following javascript:

```<code>//When a resize occurs a lot of handling needs to happen to convert the user's action into
//a visibly-pleasing result. In addition, the server has to be spoken with in order to save the controls.
function OnClientResizing(pane, eventArgs) {
    eventArgs.set_cancel(true);
    var parameters = new Array();
    parameters.push("Resize");
    parameters.push(pane.get_id());
    parameters.push(eventArgs.get_delta());
    __doPostBack(pane.get_splitter()._uniqueID, parameters);
}
</code>```

This function passes the hard work back to the server, so that it can calculate the appropriate ways to resize the controls on the page during resizes. This takes X seconds. If the user then resizes the page again before X seconds has elapsed -- I enter into a bad state. Either the old request gets cut off prematurely, or the new one runs at the same time. Either way, controls become mishapen on the page.

As such, I would like to queue future resizes, or play around with canceling current requests. I read that the best way to do something like this is to simply set a flag outside the scope of this function. I can do that, but I am not sure how to detect the end of a doPostBack. Am I supposed to change the javascript variable from the server-side somehow in PageRequestManager - EndRequest?

Cheers

答:
First off, don't let your server participate in UI resize algorithms.  Do that entirely client side.  You can send resulting data to the server at any time, but don't make a real-time UI positioning depend upon a server response.  That should be handled client-side with CSS or javascript logic.

Second off, if your code can't handle two ajax calls in flight at the same time, then your options are as follows:

Fix your code so it can handle sequential ajax responses in flight at the same time.

Cancel/ignore the first ajax response the moment you send a second one so that you ignore the response from the first and wait for the response from the second.

Prevent a second ajax request until the first one completes.  I wouldn't suggest queueing them because that's just going to lead to an even worse user experience.

The details of how to do 1, 2 or 3 depend upon how your code works which you have not yet shared.

The easiest is option 3).  That can be done with just a global flag.  Just define a global variable, set it to true when you start an ajax call and clear it when the ajax call completes (in a completion function):

```<code>var ajaxInFlight = false;  // global declaration

function OnClientResizing(pane, eventArgs) {
    if (ajaxInFlight) return;    // do nothing if ajax call already in flight
    ajaxInFlight = true;
    eventArgs.set_cancel(true);
    var parameters = new Array();
    parameters.push("Resize");
    parameters.push(pane.get_id());
    parameters.push(eventArgs.get_delta());
    __doPostBack(pane.get_splitter()._uniqueID, parameters);
}

function postBackCompletionHandler(id, parms) {
    ajaxInFlight = false;               // clear global flag, ajax call done
   // ... rest of your function here
}
</code>```

You will also have to make sure that error conditions are handled so that the global flag is reset if the ajax call fails for any reason.

ContentLicense: CC BY-SA 3.0

Body:
I am attempting to improve the stability of the web dashboard I have created. I have noticed that the main cause of getting into a bad state is when the user moves too quickly and requests get cut short.

For instance, I have the following javascript:

//When a resize occurs a lot of handling needs to happen to convert the user's action into
//a visibly-pleasing result. In addition, the server has to be spoken with in order to save the controls.
function OnClientResizing(pane, eventArgs) {
    eventArgs.set_cancel(true);
    var parameters = new Array();
    parameters.push("Resize");
    parameters.push(pane.get_id());
    parameters.push(eventArgs.get_delta());
    __doPostBack(pane.get_splitter()._uniqueID, parameters);
}

This function passes the hard work back to the server, so that it can calculate the appropriate ways to resize the controls on the page during resizes. This takes X seconds. If the user then resizes the page again before X seconds has elapsed -- I enter into a bad state. Either the old request gets cut off prematurely, or the new one runs at the same time. Either way, controls become mishapen on the page.

As such, I would like to queue future resizes, or play around with canceling current requests. I read that the best way to do something like this is to simply set a flag outside the scope of this function. I can do that, but I am not sure how to detect the end of a doPostBack. Am I supposed to change the javascript variable from the server-side somehow in PageRequestManager - EndRequest?

Cheers

Body:
First off, don't let your server participate in UI resize algorithms.  Do that entirely client side.  You can send resulting data to the server at any time, but don't make a real-time UI positioning depend upon a server response.  That should be handled client-side with CSS or javascript logic.

Second off, if your code can't handle two ajax calls in flight at the same time, then your options are as follows:

Fix your code so it can handle sequential ajax responses in flight at the same time.

Cancel/ignore the first ajax response the moment you send a second one so that you ignore the response from the first and wait for the response from the second.

Prevent a second ajax request until the first one completes.  I wouldn't suggest queueing them because that's just going to lead to an even worse user experience.

The details of how to do 1, 2 or 3 depend upon how your code works which you have not yet shared.

The easiest is option 3).  That can be done with just a global flag.  Just define a global variable, set it to true when you start an ajax call and clear it when the ajax call completes (in a completion function):

var ajaxInFlight = false;  // global declaration

function OnClientResizing(pane, eventArgs) {
    if (ajaxInFlight) return;    // do nothing if ajax call already in flight
    ajaxInFlight = true;
    eventArgs.set_cancel(true);
    var parameters = new Array();
    parameters.push("Resize");
    parameters.push(pane.get_id());
    parameters.push(eventArgs.get_delta());
    __doPostBack(pane.get_splitter()._uniqueID, parameters);
}

function postBackCompletionHandler(id, parms) {
    ajaxInFlight = false;               // clear global flag, ajax call done
   // ... rest of your function here
}

You will also have to make sure that error conditions are handled so that the global flag is reset if the ajax call fails for any reason.


问:
How to preserve original indexing of string elements after using regex
I'm trying to remove all letters and numbers from a string. For this I use the following regex methods:

```<code>txt = read_file()

pattern = r'[ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwzyx0123456789]'
mod_string = re.sub(pattern, '', txt)
new_string = re.sub(r'\s+', '', mod_string)
for i in new_string:
    print(new_string.index(i), i)
</code>```

The first use of the re.sub() method is for removing the letters and numbers, and the second is for removing the white spaces that remain.
However, when I want to access the indexes of the elements of the resulting string, it outputs the following (this is just a snippet of the real output, as that is much larger):

```<code>0 .
91 ]
92 <
92 <
57 -
1 ,
0 .
1 ,
0 .
99 (
100 )
1 ,
99 (
100 )
0 .
0 .
106 >
106 >
0 .
0 .
0 .
0 .
99 (
100 )
</code>```

How can I achieve the same, but have a 'normal' indexing?
For example if I have a string with ">)(.>", if i want to get the indexes, it want 0: >, 1: ), 2: (, 3: ., 4: > this is so that i can work with it easier after. I want to convert the string to a list of individual strings, which is why i need the indexes to be like this.

答:
What about this?

import re

txt = "ab>c)def(0123456    .> 789"

pat = re.compile(r'[a-zA-Z0-9 ]')
new_string = pat.sub('', txt) # new_string is ">)(.>" after pat.sub operation.

for i, s in enumerate(new_string): # Just show a pair of index and character in new_string
    print(i, s)
```

Body:
I'm trying to remove all letters and numbers from a string. For this I use the following regex methods:

txt = read_file()

pattern = r'[ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwzyx0123456789]'
mod_string = re.sub(pattern, '', txt)
new_string = re.sub(r'\s+', '', mod_string)
for i in new_string:
    print(new_string.index(i), i)

The first use of the re.sub() method is for removing the letters and numbers, and the second is for removing the white spaces that remain.
However, when I want to access the indexes of the elements of the resulting string, it outputs the following (this is just a snippet of the real output, as that is much larger):

0 .
91 ]
92 <
92 <
57 -
1 ,
0 .
1 ,
0 .
99 (
100 )
1 ,
99 (
100 )
0 .
0 .
106 >
106 >
0 .
0 .
0 .
0 .
99 (
100 )

How can I achieve the same, but have a 'normal' indexing?
For example if I have a string with ">)(.>", if i want to get the indexes, it want 0: >, 1: ), 2: (, 3: ., 4: > this is so that i can work with it easier after. I want to convert the string to a list of individual strings, which is why i need the indexes to be like this.


问:
Resources$NotFoundException: Resource is not a Drawable (color or path)?
I have a textview, when it is clicked, I am populating a listView inside a dialog. This code used to work fine, but today it is throwing exception.

this is my code:

```<code>tvSelectedFont = (TextView)findViewById(R.id.lblQuoteSelectedFont);
    tvSelectedFont.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            ListView listView = new ListView(context);
            listView.setAdapter(new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1,
                    new String[] {"Default", "Serif", "Monospace"}));
            final Dialog dialog = new Dialog(context);
            dialog.setContentView(listView);
            dialog.setTitle(R.string.txt_settings_QuotefontName);

            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    String selectedTypeFace = ((TextView)view).getText().toString();
                    tvSelectedFont.setText(selectedTypeFace);
                    switch(selectedTypeFace)
                    {
                        case "Serif":
                            selectedQuoteTypeFace = Typeface.SERIF;
                            break;
                        case "Monospace":
                            selectedQuoteTypeFace = Typeface.MONOSPACE;
                            break;
                        default:
                            selectedQuoteTypeFace = Typeface.DEFAULT;
                            break;
                    }
                    tvQuoteTextSample.setTypeface(selectedQuoteTypeFace, selectedQuoteFontStyle);
                    dialog.dismiss();
                }
            });

            dialog.show();
        }
    });
</code>```

The logcat error shows this:

```<code>Device driver API version: 29
User space API version: 29
03-17 14:33:24.701  23220-23220/com.example.manas.dailyquoteswidget E/﹕ mali: REVISION=Linux-r3p2-01rel3 BUILD_DATE=Tue Jul 22 19:59:34 KST 2014
03-17 14:33:27.926  23220-23220/com.example.manas.dailyquoteswidget E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.manas.dailyquoteswidget, PID: 23220
android.content.res.Resources$NotFoundException: Resource is not a Drawable (color or path): TypedValue{t=0x2/d=0x7f0100a7 a=3}
        at android.content.res.Resources.loadDrawable(Resources.java:3415)
        at android.content.res.TypedArray.getDrawable(TypedArray.java:602)
        at android.widget.AbsListView.<init>(AbsListView.java:1089)
        at android.widget.ListView.<init>(ListView.java:152)
        at android.widget.ListView.<init>(ListView.java:148)
        at android.widget.ListView.<init>(ListView.java:144)
        at com.example.manas.dailyquoteswidget.DailyQuotesWidgetConfigureActivity$6.onClick(DailyQuotesWidgetConfigureActivity.java:182)
        at android.view.View.performClick(View.java:4640)
        at android.view.View$PerformClick.run(View.java:19425)
        at android.os.Handler.handleCallback(Handler.java:733)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:146)
        at android.app.ActivityThread.main(ActivityThread.java:5593)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
        at dalvik.system.NativeStart.main(Native Method)
</code>```

Cant figure it out the problem. Any help please?

答:
There are more than one folder included in drawable folders(not visible), if you get these kind of error then please copy paste the file on which error occured to all the directories or atleast copy paste to night and normal drwable folder

enter image description here

Body:
I have a textview, when it is clicked, I am populating a listView inside a dialog. This code used to work fine, but today it is throwing exception.

this is my code:

tvSelectedFont = (TextView)findViewById(R.id.lblQuoteSelectedFont);
    tvSelectedFont.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            ListView listView = new ListView(context);
            listView.setAdapter(new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1,
                    new String[] {"Default", "Serif", "Monospace"}));
            final Dialog dialog = new Dialog(context);
            dialog.setContentView(listView);
            dialog.setTitle(R.string.txt_settings_QuotefontName);

            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    String selectedTypeFace = ((TextView)view).getText().toString();
                    tvSelectedFont.setText(selectedTypeFace);
                    switch(selectedTypeFace)
                    {
                        case "Serif":
                            selectedQuoteTypeFace = Typeface.SERIF;
                            break;
                        case "Monospace":
                            selectedQuoteTypeFace = Typeface.MONOSPACE;
                            break;
                        default:
                            selectedQuoteTypeFace = Typeface.DEFAULT;
                            break;
                    }
                    tvQuoteTextSample.setTypeface(selectedQuoteTypeFace, selectedQuoteFontStyle);
                    dialog.dismiss();
                }
            });

            dialog.show();
        }
    });

The logcat error shows this:

Device driver API version: 29
User space API version: 29
03-17 14:33:24.701  23220-23220/com.example.manas.dailyquoteswidget E/﹕ mali: REVISION=Linux-r3p2-01rel3 BUILD_DATE=Tue Jul 22 19:59:34 KST 2014
03-17 14:33:27.926  23220-23220/com.example.manas.dailyquoteswidget E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.manas.dailyquoteswidget, PID: 23220
android.content.res.Resources$NotFoundException: Resource is not a Drawable (color or path): TypedValue{t=0x2/d=0x7f0100a7 a=3}
        at android.content.res.Resources.loadDrawable(Resources.java:3415)
        at android.content.res.TypedArray.getDrawable(TypedArray.java:602)
        at android.widget.AbsListView.<init>(AbsListView.java:1089)
        at android.widget.ListView.<init>(ListView.java:152)
        at android.widget.ListView.<init>(ListView.java:148)
        at android.widget.ListView.<init>(ListView.java:144)
        at com.example.manas.dailyquoteswidget.DailyQuotesWidgetConfigureActivity$6.onClick(DailyQuotesWidgetConfigureActivity.java:182)
        at android.view.View.performClick(View.java:4640)
        at android.view.View$PerformClick.run(View.java:19425)
        at android.os.Handler.handleCallback(Handler.java:733)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:146)
        at android.app.ActivityThread.main(ActivityThread.java:5593)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
        at dalvik.system.NativeStart.main(Native Method)

Cant figure it out the problem. Any help please?


问:
ModuleNotFoundError: No module named 'pandas' (Problem with Python3.9)
Initially, I ran experiments on python3, which supports Pandas perfectly. Since our lab recently upgraded the server to an RTX 3000 series GPU, it supports Python 3.9, not previous versions. For that, when I ran the tests in python3.9 (python3.9 code file.py), the following error occurred:
ModuleNotFoundError: No module named 'pandas'

Then I ran 'pip install pandas' and found that the requirements had already been met; here's further information:

```<code>Defaulting to user installation because normal site-packages is not writeable
Requirement already satisfied: pandas in ./.local/lib/python3.6/site-packages (1.1.5)
Requirement already satisfied: pytz>=2017.2 in ./.local/lib/python3.6/site-packages (from pandas) (2021.1)
Requirement already satisfied: python-dateutil>=2.7.3 in ./.local/lib/python3.6/site-packages (from pandas) (2.8.2)
Requirement already satisfied: numpy>=1.15.4 in ./.local/lib/python3.6/site-packages (from pandas) (1.19.5)
Requirement already satisfied: six>=1.5 in ./.local/lib/python3.6/site-packages (from python-dateutil>=2.7.3->pandas) (1.15.0)
</code>```

But when I ran the file again, I received the same issue: ModuleNotFoundError: No module named 'pandas'

How can we install solve this issue?

答:
According to my understanding, our lab server supports various Python versions, and I was executing my code files from a directory with a Python version of 3.6, which caused the issue. Therefore, we must either change our project directory to Python 3.9 and install Pandas there or use the following command as instructed here.</p>
```<code>python3.9 -m pip install pandas
</code>```

Body:
Initially, I ran experiments on python3, which supports Pandas perfectly. Since our lab recently upgraded the server to an RTX 3000 series GPU, it supports Python 3.9, not previous versions. For that, when I ran the tests in python3.9 (python3.9 code file.py), the following error occurred:
ModuleNotFoundError: No module named 'pandas'

Then I ran 'pip install pandas' and found that the requirements had already been met; here's further information:

Defaulting to user installation because normal site-packages is not writeable
Requirement already satisfied: pandas in ./.local/lib/python3.6/site-packages (1.1.5)
Requirement already satisfied: pytz>=2017.2 in ./.local/lib/python3.6/site-packages (from pandas) (2021.1)
Requirement already satisfied: python-dateutil>=2.7.3 in ./.local/lib/python3.6/site-packages (from pandas) (2.8.2)
Requirement already satisfied: numpy>=1.15.4 in ./.local/lib/python3.6/site-packages (from pandas) (1.19.5)
Requirement already satisfied: six>=1.5 in ./.local/lib/python3.6/site-packages (from python-dateutil>=2.7.3->pandas) (1.15.0)

But when I ran the file again, I received the same issue: ModuleNotFoundError: No module named 'pandas'

How can we install solve this issue?

Body:
According to my understanding, our lab server supports various Python versions, and I was executing my code files from a directory with a Python version of 3.6, which caused the issue. Therefore, we must either change our project directory to Python 3.9 and install Pandas there or use the following command as instructed here.

python3.9 -m pip install pandas


问:
Remove item from array according to condition
I have an array (given below). I want to remove files, if minified version of the same file exist.

var files = ["foo.js", "foo.min.js", "bar.css","bar.min.css"];

// Should return: [foo.min.js", "bar.min.css"]

```
<pre class="lang-js prettyprint-override"><code>var files = ["foo.js", "foo.min.js", "bar.css"];

// Should return: [foo.min.js", "bar.css"]

</code>```

What i have tried

var files = ["foo.js", "bar.css"];

var tempUnMinified = [];
var tempMinified = [];
files.forEach(function (file) {
  if (file.endsWith(".min.js") || file.endsWith(".min.css")) {
    tempMinified.push(file);
  } else {
    tempUnMinified.push(file);
  }
});

tempUnMinified.forEach(function (unMinFile) {
  var tempRf = unMinFile.replace(".js", ".min.js").replace(".css", ".min.css");
  if (files.includes(tempRf)) {
    files.splice(files.indexOf(unMinFile), 1);
  }
});

console.log(files);

```

What i have tried does works, but i'm not sure if it works every time

and so on.. Thanks in advance

答:
Use the map to manipulate the array data to remove ".min" and Use a set for the uniqueness of filenames</p>
```<code>    const files = ["foo.js", "foo.min.js", "bar.css","bar.min.css"];
    const result = [...new Set(files.map(file => file.replace('.min', '')))];
    console.log(result)
</code>```

Body:
I have an array (given below). I want to remove files, if minified version of the same file exist.

var files = ["foo.js", "foo.min.js", "bar.css","bar.min.css"];

// Should return: [foo.min.js", "bar.min.css"]

var files = ["foo.js", "foo.min.js", "bar.css"];

// Should return: [foo.min.js", "bar.css"]

What i have tried

var files = ["foo.js", "bar.css"];

var tempUnMinified = [];
var tempMinified = [];
files.forEach(function (file) {
  if (file.endsWith(".min.js") || file.endsWith(".min.css")) {
    tempMinified.push(file);
  } else {
    tempUnMinified.push(file);
  }
});

tempUnMinified.forEach(function (unMinFile) {
  var tempRf = unMinFile.replace(".js", ".min.js").replace(".css", ".min.css");
  if (files.includes(tempRf)) {
    files.splice(files.indexOf(unMinFile), 1);
  }
});

console.log(files);

What i have tried does works, but i'm not sure if it works every time

and so on.. Thanks in advance

Body:
Use the map to manipulate the array data to remove ".min" and Use a set for the uniqueness of filenames

    const files = ["foo.js", "foo.min.js", "bar.css","bar.min.css"];
    const result = [...new Set(files.map(file => file.replace('.min', '')))];
    console.log(result)


问:
how to complement the values of std::vector<bool> using range for loop taking element by reference
I need to complement the values of std::vector<bool>. So I thought of using range for loop taking elements by reference. But the compiler is giving me the below error

```<code>error: cannot bind non-const lvalue reference of type 'std::_Bit_reference&' to an rvalue of type 'std::_Bit_iterator::reference'
   13 |     for (auto& bit : rep)
</code>```

This is my sample code

```<code>#include <iostream>
#include <vector>

int main() {
    std::vector<bool> rep;
    rep.push_back(true);
    rep.push_back(false);
    rep.push_back(true);
    rep.push_back(false);
    rep.push_back(true);
    rep.push_back(false);

    for (auto& bit : rep)
        bit = !bit;
}
</code>```

答:
You could also use std::vector<bool>::flip to toggle every value  in the vector<bool>.

```<code>std::vector<bool> rep{true, false, true, false, true, false};

for(bool v: rep)
    std::cout << v;
std::cout << '\n';
rep.flip();
for(bool v: rep)
    std::cout << v;
</code>```

Output:

```<code>101010
010101
</code>```

std::vector<bool>::reference is the proxy type stored underneath which also has flip function std::vector<bool>::reference::flip.

```<code>for(auto&& v: rep)
    v.flip();
</code>```

Body:
I need to complement the values of std::vector<bool>. So I thought of using range for loop taking elements by reference. But the compiler is giving me the below error

error: cannot bind non-const lvalue reference of type 'std::_Bit_reference&' to an rvalue of type 'std::_Bit_iterator::reference'
   13 |     for (auto& bit : rep)

This is my sample code

#include <iostream>
#include <vector>

int main() {
    std::vector<bool> rep;
    rep.push_back(true);
    rep.push_back(false);
    rep.push_back(true);
    rep.push_back(false);
    rep.push_back(true);
    rep.push_back(false);

    for (auto& bit : rep)
        bit = !bit;
}

Body:
You could also use std::vector<bool>::flip to toggle every value  in the vector<bool>.

std::vector<bool> rep{true, false, true, false, true, false};

for(bool v: rep)
    std::cout << v;
std::cout << '\n';
rep.flip();
for(bool v: rep)
    std::cout << v;

Output:

101010
010101

std::vector<bool>::reference is the proxy type stored underneath which also has flip function std::vector<bool>::reference::flip.

for(auto&& v: rep)
    v.flip();


问:
Delete oldest File(s) in a directory until it is under a certain file size
What I'm trying to accomplish is the following: Suppose I have a function that writes an image to a File directory (either SD or internal cache). After writing out the File, I perform a check to see if my image directory is within a certain total file size (right now, I'm using this function to recursively calculate the directory's file size). If the file that I just added makes that directory too big, then what I want to do is keep deleting older files until we are just below that max file size.

I was thinking of first sorting the File directory members from oldest first (via comparator, ascending order using this example), then convert the array into an ArrayList to get its Iterator, then while our directory file size is still above the max file size, and I still have files to iterate to, I delete the older files until I break out of that while loop. Is there a more efficient way of accomplishing this?

答:
Your bottleneck is most likely going to be file system operations (ie: reading the directory contents and deleting the files), not the in-memory manipulation, so you probably shouldn't worry too much about the efficiency of the latter so long as you don't do something grossly inefficient.

The rough algorithm you describe sounds fine. You can avoid the ArrayList conversion by simply doing something like:

```<code>for (Pair pair : pairs) {
    if (totalSize <= maxSize) {
        break;
    }

    totalSize -= pair.f.length();
    pair.f.delete();
}
</code>```

Body:
Your bottleneck is most likely going to be file system operations (ie: reading the directory contents and deleting the files), not the in-memory manipulation, so you probably shouldn't worry too much about the efficiency of the latter so long as you don't do something grossly inefficient.

The rough algorithm you describe sounds fine. You can avoid the ArrayList conversion by simply doing something like:

for (Pair pair : pairs) {
    if (totalSize <= maxSize) {
        break;
    }

    totalSize -= pair.f.length();
    pair.f.delete();
}


问:
How to mock a class method in the test which tests another class method?
I have the following class and I'm writing a test on method2.

y.py

```<code>class C:
    @classmethod
    async def method1(cls):  # to be mocked
        pass

    @classmethod
    async def method2(cls):  # to be tested
        await cls.method1()
</code>```

I have the following

```<code>from asyncio import Future
from unittest.mock import Mock
import pytest
from y import C

@pytest.mark.asyncio
async def test_method2():
    C.method1 = Mock(return_value=Future())
    await C.method2()
    C.method1.assert_called_once()
</code>```

However, it hangs when running python -m pytest test.py?

答:
You are testing async function here. Therefore you should use AsyncMock. With async_mock you could than use awaited_onced instead of called once. You code would look like

from unittest.mock import AsyncMock
@pytest.mark.asyncio
async def test_method2():
    C.method1 = AsyncMock()
    await C.method2()
    C.method1.assert_awaited_once()
```

Body:
I have the following class and I'm writing a test on method2.

y.py

class C:
    @classmethod
    async def method1(cls):  # to be mocked
        pass

    @classmethod
    async def method2(cls):  # to be tested
        await cls.method1()

I have the following

from asyncio import Future
from unittest.mock import Mock
import pytest
from y import C

@pytest.mark.asyncio
async def test_method2():
    C.method1 = Mock(return_value=Future())
    await C.method2()
    C.method1.assert_called_once()

However, it hangs when running python -m pytest test.py?


答:
May be another problem.  Remember that the question is "Can you convert it to a palindrome in K steps", not "Can you convert it to a palindrome in a minimum of K steps".

If you've discovered you can do it in fewer than K steps, you have to figure out if you can do it in K steps.  For even palindromes, you can flip pairs of bits, or just flip the same bit an even number of times.  For odd palindromes, you can just flip the center bit over and over.

Title: Palindrome problem - What am I doing wrong Here?


问:
split a list into groups of n and assign group ID with Python
Given  a list of tuple, with each tuple is a value for a pair of variable.

```<code>[(0.0, 0.0), (0.0, 0.4), (0.0, 0.8), (0.0, 1.2000000000000002), (0.0, 1.6), (0.4, 0.0), (0.4, 0.4)]
</code>```

The objective is to split this list of tuple into N group and append the group ID in each of the tuple.

Currently, the following code answer the objective

```<code>from itertools import product

import numpy as np

def split(a, n):
    k, m = divmod(len(a), n)
    return (a[i*k+min(i, m):(i+1)*k+min(i+1, m)] for i in range(n))

pair_var=list(product(np.arange(*(0.0,2,0.4)), np.arange(*(0.0,2,0.4))))
ngroup=2
pair_var_gr=list(split(pair_var, ngroup))

new_group=[]
for ndex,ltup in enumerate(pair_var_gr):
  for dtup in ltup:
    m=list(dtup)
    m.append(ndex)
    new_group.append(m)
</code>```

Expected output

```<code>[[0.0, 0.0, 0], [0.0, 0.4, 0], [0.0, 0.8, 0], [0.0, 1.2000000000000002, 0], [0.0, 1.6, 0], [0.4, 0.0, 0], [0.4, 0.4, 0]]
</code>```

However, I wonder whether there is compact or proper ways of achieving the above?

答:
Without the group ID, this could simply be accomplished with a list comprehension, like so:</p>
```<code>
new_list = [[item[0], item[1]] for item in output]

print(new_list)```

output: `[[0.0, 0.0], [0.0, 0.4], [0.0, 0.8], [0.0, 1.2000000000000002], [0.0, 1.6], [0.4, 0.0], [0.4, 0.4]]`

Adding an int of the first element just to fill in the Group ID space for example:

`new_list = [[item[0], item[1], int(item[0])] for item in output]`

output: `[[0.0, 0.0, 0], [0.0, 0.4, 0], [0.0, 0.8, 0], [0.0, 1.2000000000000002, 0], [0.0, 1.6, 0], [0.4, 0.0, 0], [0.4, 0.4, 0]]`

That Group ID assignment could be tweaked to fit your needs in the comprehension without need for numpy, I'm guessing.
</code>```

Body:
Given  a list of tuple, with each tuple is a value for a pair of variable.

[(0.0, 0.0), (0.0, 0.4), (0.0, 0.8), (0.0, 1.2000000000000002), (0.0, 1.6), (0.4, 0.0), (0.4, 0.4)]

The objective is to split this list of tuple into N group and append the group ID in each of the tuple.

Currently, the following code answer the objective

from itertools import product

import numpy as np

def split(a, n):
    k, m = divmod(len(a), n)
    return (a[i*k+min(i, m):(i+1)*k+min(i+1, m)] for i in range(n))

pair_var=list(product(np.arange(*(0.0,2,0.4)), np.arange(*(0.0,2,0.4))))
ngroup=2
pair_var_gr=list(split(pair_var, ngroup))

new_group=[]
for ndex,ltup in enumerate(pair_var_gr):
  for dtup in ltup:
    m=list(dtup)
    m.append(ndex)
    new_group.append(m)

Expected output

[[0.0, 0.0, 0], [0.0, 0.4, 0], [0.0, 0.8, 0], [0.0, 1.2000000000000002, 0], [0.0, 1.6, 0], [0.4, 0.0, 0], [0.4, 0.4, 0]]

However, I wonder whether there is compact or proper ways of achieving the above?

Body:
Without the group ID, this could simply be accomplished with a list comprehension, like so:

new_list = [[item[0], item[1]] for item in output]

print(new_list)```

output: `[[0.0, 0.0], [0.0, 0.4], [0.0, 0.8], [0.0, 1.2000000000000002], [0.0, 1.6], [0.4, 0.0], [0.4, 0.4]]`

Adding an int of the first element just to fill in the Group ID space for example:

`new_list = [[item[0], item[1], int(item[0])] for item in output]`

output: `[[0.0, 0.0, 0], [0.0, 0.4, 0], [0.0, 0.8, 0], [0.0, 1.2000000000000002, 0], [0.0, 1.6, 0], [0.4, 0.0, 0], [0.4, 0.4, 0]]`

That Group ID assignment could be tweaked to fit your needs in the comprehension without need for numpy, I'm guessing.


问:
asp.net core dropdown list not setting selected value
I have  a bootstrap drop down and I am using tag helpers to enter render values and read them on post.
Below is the code

asp-for="CfgType"  -- value is set to SIN or UN based on that set the view to the selected value
-- and on submittig the page I need to get the selected value for the drop down from CfgType property.

```<code>                <div class="form-row">
                    <div class="col-md-12">
                        <div class="form-group form-group--float">
                            <div class="form-group form-group--float">
                                <select id="dwType" class="form-control  custom-select" asp-for="CfgType">
                                    @if(Model.VehFlg)
                                    {
                                        <option value="SIN">Serial Num</option>
                                    }

                                    @if(Model.VinFlg)
                                    {
                                        <option value="UN">Unit Number</option>
                                    }

                               </select>
                                <label> Configuration Type</label>
                                <div class="invalid-tooltip"><span asp-validation-for="CfgType"></span></div>
                            </div>
                            <i class="form-group__bar"></i>
                        </div>
</code>```

Below is how the value is being tried to retrive using controller

//now for fvIdentViewModel.CfgType is null

```<code>  [Route("/fv-identification/Save"), HttpPost, ValidateAntiForgeryToken]
 public IActionResult Save(FleetVehicleIdentificationViewModel fvIdentViewModel)
        {

}
</code>```

答:
you should put in tag form with button type submit.</p>
```<code><form action="/fv-identification/Save" method="post">
 <button type="submit" class="btn btn-info">@localizer["Submit"] </button>
</form>
</code>```

Body:
I have  a bootstrap drop down and I am using tag helpers to enter render values and read them on post.
Below is the code

asp-for="CfgType"  -- value is set to SIN or UN based on that set the view to the selected value
-- and on submittig the page I need to get the selected value for the drop down from CfgType property.

                                <select id="dwType" class="form-control  custom-select" asp-for="CfgType">
                                    @if(Model.VehFlg)
                                    {
                                        <option value="SIN">Serial Num</option>
                                    }

                                    @if(Model.VinFlg)
                                    {
                                        <option value="UN">Unit Number</option>
                                    }

                               </select>
                                 Configuration Type

Below is how the value is being tried to retrive using controller

//now for fvIdentViewModel.CfgType is null

  [Route("/fv-identification/Save"), HttpPost, ValidateAntiForgeryToken]
 public IActionResult Save(FleetVehicleIdentificationViewModel fvIdentViewModel)
        {

}

Body:
you should put in tag form with button type submit.

<form action="/fv-identification/Save" method="post">
 <button type="submit" class="btn btn-info">@localizer["Submit"] </button>
</form>


问:
ErrorException in Filesystem.php line 111:file_put_contents(): failed to open stream: No such file or directory
I'm  creating an API and there on making a request I got this. error

ErrorException in Filesystem.php line 111:
file_put_contents(/opt/lampp/htdocs/Baller/storage/framework/cache/data/ce/3c/ce3cca4e3f5b66351ec8b603994311ed663c5c5f): failed to open stream: No such file or directory

I've looked into my code but found nothing in it also I've cleared the cache as suggested in the related questions but nothing has worked for me till now can you people help me in tracing this error?

ScheduleController.php

```<code>public function addSchedule(Request $request) {
    $validator = Validator::make(
        array(
            'homeCourtId' => $request->homeCourtId,
            'timeFrom' => $request->timeFrom,
            'duration' => $request->duration,
        ),
        array(
            'homeCourtId' => 'required',
            'timeFrom' => 'required',
            'duration' => 'required',
        )
    );
    if ($validator->fails()) {
        $errors = $validator->errors();
        if ($errors->first('homeCourtId')) {
            $message = $errors->first('homeCourtId');
        } else if ($errors->first('timeFrom')) {
            $message = $errors->first('timeFrom');
        } else if ($errors->first('duration')) {
            $message = $errors->first('duration');
        } else {
            $message = Constant::MSG_422;
        }
        $this->setMeta("422", $message);
        return response()->json($this->setResponse());
    }
    $timeFrom= $request->timeFrom;
    $getDuration = $request->duration;
    $duration= 360*$getDuration;
    $timeTo = $timeFrom+$duration;
    $userHomeCourtId= UserHomeCourt::where(array('userId'=> $request->userId,'homeCourtId'=> $request->homeCourtId, 'userHomeCourtStatus'=>Constant::STATUS_1))->pluck('userHomeCourtId');
    if(!$userHomeCourtId) {
        $this->setMeta('403', __('apiMessages.invalidHomeCourtId'));
        return response()->json($this->setResponse());
    }
    try {
        $schedule = new Schedule();
        $schedule->userHomeCourtId = $userHomeCourtId;
        $schedule->timeFrom = $request->timeFrom;
        $schedule->timeTo = $timeTo;
        $schedule->duration = $duration;
        $schedule->save();
        $this->setMeta('200', 'Schedule has been successfully set');
        return response()->json($this->setResponse());
    } catch (QueryException $e) {
        $this->setMeta('500', Constant::MSG_500);
        return response()->json($this->setResponse());
    }
}

// get schedule
public function fetchSchedule(Request $request)
{
    $validator = Validator::make(
        array(
            'homeCourtId' => $request->homeCourtId,
            'currentTime' => $request->currentTime,
        ),
        array(
            'homeCourtId' => 'required',
            'currentTime' => 'required',
        )
    );
    if ($validator->fails()) {
        $errors = $validator->errors();
        if ($errors->first('homeCourtId')) {
            $message = $errors->first('homeCourtId');
        } else if ($errors->first('currentTime')) {
            $message = $errors->first('currentTime');
        } else {
            $message = Constant::MSG_422;
        }
        $this->setMeta("422", $message);
        return response()->json($this->setResponse());
    }
    $userHomeCourtId= UserHomeCourt::where(array('userId'=> $request->userId,'homeCourtId'=> $request->homeCourtId, 'userHomeCourtStatus'=>Constant::STATUS_1))->pluck('userHomeCourtId');
    if(!$userHomeCourtId) {
        $this->setMeta('403', __('apiMessages.invalidHomeCourtId'));
        return response()->json($this->setResponse());
    }
    $fetchSchedule=Schedule::where('userHomeCourtId','=',$userHomeCourtId)->get();
    if(!$fetchSchedule) {
        $this->setMeta('200', __('apiMessages.noSchedule'));
        return response()->json($this->setResponse());
    }
    $this->setMeta('200', __('apiMessages.scheduleList'));
    $this->setData('scheduleUsers', $fetchSchedule);
    return response()->json($this->setResponse());

}
</code>```

Routes

api.php

```<code>Route::post('/addSchedule','Api\ScheduleController@addSchedule');
Route::post('/fetchSchedule','Api\ScheduleController@fetchSchedule');
</code>```

答:
The first answer helped me a lot. The following worked for me.</p>
```<code>sudo chmod 777 -R storage/

sudo chmod 777 -R bootstrap/
</code>```

Body:
I'm  creating an API and there on making a request I got this. error

ErrorException in Filesystem.php line 111:
file_put_contents(/opt/lampp/htdocs/Baller/storage/framework/cache/data/ce/3c/ce3cca4e3f5b66351ec8b603994311ed663c5c5f): failed to open stream: No such file or directory

I've looked into my code but found nothing in it also I've cleared the cache as suggested in the related questions but nothing has worked for me till now can you people help me in tracing this error?

ScheduleController.php

public function addSchedule(Request $request) {
    $validator = Validator::make(
        array(
            'homeCourtId' => $request->homeCourtId,
            'timeFrom' => $request->timeFrom,
            'duration' => $request->duration,
        ),
        array(
            'homeCourtId' => 'required',
            'timeFrom' => 'required',
            'duration' => 'required',
        )
    );
    if ($validator->fails()) {
        $errors = $validator->errors();
        if ($errors->first('homeCourtId')) {
            $message = $errors->first('homeCourtId');
        } else if ($errors->first('timeFrom')) {
            $message = $errors->first('timeFrom');
        } else if ($errors->first('duration')) {
            $message = $errors->first('duration');
        } else {
            $message = Constant::MSG_422;
        }
        $this->setMeta("422", $message);
        return response()->json($this->setResponse());
    }
    $timeFrom= $request->timeFrom;
    $getDuration = $request->duration;
    $duration= 360*$getDuration;
    $timeTo = $timeFrom+$duration;
    $userHomeCourtId= UserHomeCourt::where(array('userId'=> $request->userId,'homeCourtId'=> $request->homeCourtId, 'userHomeCourtStatus'=>Constant::STATUS_1))->pluck('userHomeCourtId');
    if(!$userHomeCourtId) {
        $this->setMeta('403', __('apiMessages.invalidHomeCourtId'));
        return response()->json($this->setResponse());
    }
    try {
        $schedule = new Schedule();
        $schedule->userHomeCourtId = $userHomeCourtId;
        $schedule->timeFrom = $request->timeFrom;
        $schedule->timeTo = $timeTo;
        $schedule->duration = $duration;
        $schedule->save();
        $this->setMeta('200', 'Schedule has been successfully set');
        return response()->json($this->setResponse());
    } catch (QueryException $e) {
        $this->setMeta('500', Constant::MSG_500);
        return response()->json($this->setResponse());
    }
}

// get schedule
public function fetchSchedule(Request $request)
{
    $validator = Validator::make(
        array(
            'homeCourtId' => $request->homeCourtId,
            'currentTime' => $request->currentTime,
        ),
        array(
            'homeCourtId' => 'required',
            'currentTime' => 'required',
        )
    );
    if ($validator->fails()) {
        $errors = $validator->errors();
        if ($errors->first('homeCourtId')) {
            $message = $errors->first('homeCourtId');
        } else if ($errors->first('currentTime')) {
            $message = $errors->first('currentTime');
        } else {
            $message = Constant::MSG_422;
        }
        $this->setMeta("422", $message);
        return response()->json($this->setResponse());
    }
    $userHomeCourtId= UserHomeCourt::where(array('userId'=> $request->userId,'homeCourtId'=> $request->homeCourtId, 'userHomeCourtStatus'=>Constant::STATUS_1))->pluck('userHomeCourtId');
    if(!$userHomeCourtId) {
        $this->setMeta('403', __('apiMessages.invalidHomeCourtId'));
        return response()->json($this->setResponse());
    }
    $fetchSchedule=Schedule::where('userHomeCourtId','=',$userHomeCourtId)->get();
    if(!$fetchSchedule) {
        $this->setMeta('200', __('apiMessages.noSchedule'));
        return response()->json($this->setResponse());
    }
    $this->setMeta('200', __('apiMessages.scheduleList'));
    $this->setData('scheduleUsers', $fetchSchedule);
    return response()->json($this->setResponse());

}

Routes

api.php

Route::post('/addSchedule','Api\ScheduleController@addSchedule');
Route::post('/fetchSchedule','Api\ScheduleController@fetchSchedule');

Body:
The first answer helped me a lot. The following worked for me.

sudo chmod 777 -R storage/

sudo chmod 777 -R bootstrap/


问:
How to assert inside a RecyclerView in Espresso?
I am using espresso-contrib to perform actions on a RecyclerView, and it works as it should, ex:

//click on first item
onView(withId(R.id.recycler_view))
    .perform(RecyclerViewActions.actionOnItemAtPosition(0, click()));
```
<p>and I need to perform assertions on it. Something like this:</p>
```onView(withId(R.id.recycler_view))
    .perform(
        RecyclerViewActions.actionOnItemAtPosition(
            0, check(matches(withText("Test Text")))
        )
    );
```

but, because RecyclerViewActions is, of course, expecting an action, it says wrong 2nd argument type. There's no RecyclerViewAssertions on espresso-contrib.

Is there any way to perform assertions on a RecyclerView?

答:
I have written a function that can check every view of view holder in recyclerview. Here is my function :

recyclerViewId is your recyclerview id

position is the position of your recyclerview

itemMatcher is your matcher function

subViewId is the id of recyclerview sub view (view of viewHolder)

```<code>    public static void checkRecyclerSubViews(int recyclerViewId, int position, Matcher<View> itemMatcher, int subViewId)
{
    onView(withId(recyclerViewId)).perform(RecyclerViewActions.scrollToPosition(position))
                                  .check(matches(atPositionOnView(position, itemMatcher, subViewId)));
}

    public static Matcher<View> atPositionOnView(
        final int position, final Matcher<View> itemMatcher, @NonNull final int targetViewId)
{

    return new BoundedMatcher<View, RecyclerView>(RecyclerView.class)
    {
        @Override
        public void describeTo(Description description)
        {
            description.appendText("has view id " + itemMatcher + " at position " + position);
        }

        @Override
        public boolean matchesSafely(final RecyclerView recyclerView)
        {
            RecyclerView.ViewHolder viewHolder = recyclerView.findViewHolderForAdapterPosition(position);
            View targetView = viewHolder.itemView.findViewById(targetViewId);
            return itemMatcher.matches(targetView);
        }
    };
}
</code>```

And this is the examaple of using :

```<code>checkRecyclerSubViews(R.id.recycler_view, 5, withEffectiveVisibility(ViewMatchers.Visibility.VISIBLE), R.id.text_view_plan_tittle);

checkRecyclerSubViews(R.id.recycler_view, 5, withText("test"), R.id.text_view_delete);
</code>```

Body:
I am using espresso-contrib to perform actions on a RecyclerView, and it works as it should, ex:

//click on first item
onView(withId(R.id.recycler_view))
    .perform(RecyclerViewActions.actionOnItemAtPosition(0, click()));

and I need to perform assertions on it. Something like this:

onView(withId(R.id.recycler_view))
    .perform(
        RecyclerViewActions.actionOnItemAtPosition(
            0, check(matches(withText("Test Text")))
        )
    );

but, because RecyclerViewActions is, of course, expecting an action, it says wrong 2nd argument type. There's no RecyclerViewAssertions on espresso-contrib.

Is there any way to perform assertions on a RecyclerView?

Body:
I have written a function that can check every view of view holder in recyclerview. Here is my function :

recyclerViewId is your recyclerview id

position is the position of your recyclerview

itemMatcher is your matcher function

subViewId is the id of recyclerview sub view (view of viewHolder)

    public static void checkRecyclerSubViews(int recyclerViewId, int position, Matcher<View> itemMatcher, int subViewId)
{
    onView(withId(recyclerViewId)).perform(RecyclerViewActions.scrollToPosition(position))
                                  .check(matches(atPositionOnView(position, itemMatcher, subViewId)));
}

    public static Matcher<View> atPositionOnView(
        final int position, final Matcher<View> itemMatcher, @NonNull final int targetViewId)
{

    return new BoundedMatcher<View, RecyclerView>(RecyclerView.class)
    {
        @Override
        public void describeTo(Description description)
        {
            description.appendText("has view id " + itemMatcher + " at position " + position);
        }

        @Override
        public boolean matchesSafely(final RecyclerView recyclerView)
        {
            RecyclerView.ViewHolder viewHolder = recyclerView.findViewHolderForAdapterPosition(position);
            View targetView = viewHolder.itemView.findViewById(targetViewId);
            return itemMatcher.matches(targetView);
        }
    };
}

And this is the examaple of using :

checkRecyclerSubViews(R.id.recycler_view, 5, withEffectiveVisibility(ViewMatchers.Visibility.VISIBLE), R.id.text_view_plan_tittle);

checkRecyclerSubViews(R.id.recycler_view, 5, withText("test"), R.id.text_view_delete);


问:
Empty cell in csv not detected in python
I'm already using .isna and .isnull to check for missing value in my data and it shows that there is no missing value in the data. But when I skimming the data using excel, I found several empty cells in a column. That column was supposed to have numerical data type, but it got identified as object because it has several empty cells. If I want  to delete these cells, what should I do?

答:
That column was supposed to have numerical data type, but it got identified as object because it has several empty cells.

This suggest that they are empty strings, ''. You could replace them with NaN values using replace:

```<code>df = df.replace('', np.nan)
</code>```

Body:
That column was supposed to have numerical data type, but it got identified as object because it has several empty cells.

This suggest that they are empty strings, ''. You could replace them with NaN values using replace:

df = df.replace('', np.nan)


问:
Yarn run multiple scripts in parallel
I'm migrating from NPM to Yarn, and I want to run scripts in parallel such as:

```<code>npm-run-all --parallel script1 script2 script3
</code>```

What is its equivalent in Yarn?

What I found as its equivalent is to run each separately:

```<code>yarn run script1 && yarn run script2 && yarn run script3
</code>```

but I can't run scripts in parallel.

how to use multiple scripts & in parallel?

答:
If your scripts are intended to run continuously in background like daemons, you can use fly-run.

I am using it when I need to spawn multiple processes (yarn serve of multiple micro-services projects in development).

Install it:

```<code>yarn global add @ifnot/fly-run
</code>```

Create a configuration file config.js:

module.exports = [
  {
    name: 'script1',
    command: '/path/to/script1'
  },
  {
    name: 'script1',
    command: '/path/to/script2'
  },
  // more ...
]
```
<p>Run it using the configuration:</p>
```fly-run config.js
```

Use it :

CTRL+C closes all your spawned process, type restart script1 for restarting one script, more commands and configuration on the github.

Title: Yarn run multiple scripts in parallel

Body:
I'm migrating from NPM to Yarn, and I want to run scripts in parallel such as:

npm-run-all --parallel script1 script2 script3

What is its equivalent in Yarn?

What I found as its equivalent is to run each separately:

yarn run script1 && yarn run script2 && yarn run script3

but I can't run scripts in parallel.

how to use multiple scripts & in parallel?

Body:
If your scripts are intended to run continuously in background like daemons, you can use fly-run.

I am using it when I need to spawn multiple processes (yarn serve of multiple micro-services projects in development).

Install it:

yarn global add @ifnot/fly-run

Create a configuration file config.js:

module.exports = [
  {
    name: 'script1',
    command: '/path/to/script1'
  },
  {
    name: 'script1',
    command: '/path/to/script2'
  },
  // more ...
]

Run it using the configuration:

fly-run config.js

Use it :

CTRL+C closes all your spawned process, type restart script1 for restarting one script, more commands and configuration on the github.


问:
is there a way to convert an immutable list to a mutable one?
So I wanted to create a method to add an element into an immutable list but I kinda need it to be a mutable list to be returned at the end. So far, I have have created a mutable copy of the immutable list:

```<code>Grid2D add(int elem) {
          List<Integer> newlist = new ArrayList<Integer>();
          for (int i = 0; i < this.list.size(); i++) {
              newlist.add(list.get(i));
          }
          newlist.add(elem);
          return new Grid2D(newlist, this.numOfCols);
}
</code>```

I was just wondering if there are any other ways to go about converting an ImList to a list? Preferably without the ArrayList package if that's possible!

Thank you for your time and any help is appreciated! :)

答:
Is there a way to convert an immutable list to a mutable one?

The short answer is that there isn't a way.

The long answer is that it depends what you mean by "convert" to mutable.

Obviously, you can create a mutable copy of an immutable list1.  But the downside is that the mutable list is a distinct list.  Changes made to the "immutable" list after you made the copy are not reflected in the new list.  And vice-versa.

If you were to "crack open" the immutable list abstraction, it may be possible to mutate it.  (Nasty reflection is involved, and you need to know how the specific immutable list class has been implemented.)  But this is a really bad idea.  Various parts of your application code-base will be assuming that the immutable collection is immutable.  Violating the invariant could make all sorts of things behave incorrectly.

Finally, if the "immutable list" was originally created using Collections.unmodifiableList, it is not strictly immutable.  You could potentially modify it by modifying the original list that was wrapped by the unmodifiableList call.

1 - You don't necessarily need to use ArrayList for this.  You could use any List implementation class, including a custom implementation that you wrote from scratch.  But you do need to use new to create a new List instance.

Body:
So I wanted to create a method to add an element into an immutable list but I kinda need it to be a mutable list to be returned at the end. So far, I have have created a mutable copy of the immutable list:

Grid2D add(int elem) {
          List<Integer> newlist = new ArrayList<Integer>();
          for (int i = 0; i < this.list.size(); i++) {
              newlist.add(list.get(i));
          }
          newlist.add(elem);
          return new Grid2D(newlist, this.numOfCols);
}

I was just wondering if there are any other ways to go about converting an ImList to a list? Preferably without the ArrayList package if that's possible!

Thank you for your time and any help is appreciated! :)


问:
How to use Program.cs file in .NET 6
In the latest version of .Net the Startup class and Program class are merged together and the using and other statements are simplified and removed from Program.cs. I am really confused about how to use it all in one file.
Please help me to migrate all services to the program.cs file.

Startup.cs file :

```<code>public class Startup
{
    private readonly IConfigurationRoot configRoot;
    private AppSettings AppSettings { get; set; }

    public Startup(IConfiguration configuration)
    {
        Log.Logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger();
        Configuration = configuration;

        IConfigurationBuilder builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json");
        configRoot = builder.Build();

        AppSettings = new AppSettings();
        Configuration.Bind(AppSettings);
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddController();

        services.AddDbContext(Configuration, configRoot);

        services.AddIdentityService(Configuration);

        services.AddAutoMapper();

        services.AddScopedServices();

        services.AddTransientServices();

        services.AddSwaggerOpenAPI();

        services.AddMailSetting(Configuration);

        services.AddServiceLayer();

        services.AddVersion();

        services.AddHealthCheck(AppSettings, Configuration);

        services.AddFeatureManagement();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory log)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseCors(options =>
             options.WithOrigins("http://localhost:3000")
             .AllowAnyHeader()
             .AllowAnyMethod());

        app.ConfigureCustomExceptionMiddleware();

        log.AddSerilog();

        //app.ConfigureHealthCheck();

        app.UseRouting();

        app.UseAuthentication();

        app.UseAuthorization();
        app.ConfigureSwagger();
        app.UseHealthChecks("/healthz", new HealthCheckOptions
        {
            Predicate = _ => true,
            ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse,
            ResultStatusCodes =
            {
                [HealthStatus.Healthy] = StatusCodes.Status200OK,
                [HealthStatus.Degraded] = StatusCodes.Status500InternalServerError,
                [HealthStatus.Unhealthy] = StatusCodes.Status503ServiceUnavailable,
            },
        }).UseHealthChecksUI(setup =>
          {
              setup.ApiPath = "/healthcheck";
              setup.UIPath = "/healthcheck-ui";
              //setup.AddCustomStylesheet("Customization/custom.css");
          });

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
}
</code>```

Program.cs file :

```<code> public class Program
{
    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
}
</code>```

答:
You modify your csproj file

<PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net6.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
</PropertyGroup>
```

Title: How to use Program.cs file in .NET 6

Body:
In the latest version of .Net the Startup class and Program class are merged together and the using and other statements are simplified and removed from Program.cs. I am really confused about how to use it all in one file.
Please help me to migrate all services to the program.cs file.

Startup.cs file :

public class Startup
{
    private readonly IConfigurationRoot configRoot;
    private AppSettings AppSettings { get; set; }

    public Startup(IConfiguration configuration)
    {
        Log.Logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger();
        Configuration = configuration;

        IConfigurationBuilder builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json");
        configRoot = builder.Build();

        AppSettings = new AppSettings();
        Configuration.Bind(AppSettings);
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddController();

        services.AddDbContext(Configuration, configRoot);

        services.AddIdentityService(Configuration);

        services.AddAutoMapper();

        services.AddScopedServices();

        services.AddTransientServices();

        services.AddSwaggerOpenAPI();

        services.AddMailSetting(Configuration);

        services.AddServiceLayer();

        services.AddVersion();

        services.AddHealthCheck(AppSettings, Configuration);

        services.AddFeatureManagement();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory log)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseCors(options =>
             options.WithOrigins("http://localhost:3000")
             .AllowAnyHeader()
             .AllowAnyMethod());

        app.ConfigureCustomExceptionMiddleware();

        log.AddSerilog();

        //app.ConfigureHealthCheck();

        app.UseRouting();

        app.UseAuthentication();

        app.UseAuthorization();
        app.ConfigureSwagger();
        app.UseHealthChecks("/healthz", new HealthCheckOptions
        {
            Predicate = _ => true,
            ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse,
            ResultStatusCodes =
            {
                [HealthStatus.Healthy] = StatusCodes.Status200OK,
                [HealthStatus.Degraded] = StatusCodes.Status500InternalServerError,
                [HealthStatus.Unhealthy] = StatusCodes.Status503ServiceUnavailable,
            },
        }).UseHealthChecksUI(setup =>
          {
              setup.ApiPath = "/healthcheck";
              setup.UIPath = "/healthcheck-ui";
              //setup.AddCustomStylesheet("Customization/custom.css");
          });

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
}

Program.cs file :

 public class Program
{
    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
}