问:
ValueError: Cannot assign "<User: salman>": "DoctorProfile.user" must be a "Doctor" instance

I'm trying to register two types of users the Doctor and the Patient but when I tried I got the following error which made me feel like I'm lost because I really don't know what's happning

thi is the error

```<code>Traceback (most recent call last):
  File "C:\Users\rachi\AppData\Local\Programs\Python\Python310-32\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
    response = get_response(request).....
 ..
    raise ValueError(
ValueError: Cannot assign "<User: salman>": "DoctorProfile.user" must be a "Doctor" instance.
</code>```

This is my code

my models.py

```<code>class User(AbstractUser):
    is_doctor = models.BooleanField(default=False)
    is_patient = models.BooleanField(default=False)

class Doctor(models.Model):
    user = models.OneToOneField(
        User, on_delete=models.CASCADE, primary_key=True)
    number_phone = models.CharField(
        _('االهاتف :'), max_length=50, blank=True, null=True)
    last_login = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return '%s' % (self.user.username)

class DoctorProfile (models.Model):

    }
    user = models.OneToOneField(Doctor, on_delete=models.CASCADE, primary_key=True)

    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = slugify(self.name)
        super(DoctorProfile, self).save(*args, **kwargs)

    def __str__(self):
        return '%s' % (self.name)

    # def get_absolute_url(self):
    #     return reverse("doctor_detail", kwargs={"slug": self.slug})

def create_profile(sender, **kwargs):

    if kwargs['created']:
        DoctorProfile.objects.create(user=kwargs['instance'])

post_save.connect(create_profile, sender=User)

class Patient(models.Model):
    user = models.OneToOneField(
        User, on_delete=models.CASCADE, primary_key=True)
    name = models.CharField(max_length=50, verbose_name="الاسم ")
    last_login = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return '%s' % (self.user.username)

</code>```

please tell me where is the probleme

Body:
I'm trying to register two types of users the Doctor and the Patient but when I tried I got the following error which made me feel like I'm lost because I really don't know what's happning

thi is the error

Traceback (most recent call last):
  File "C:\Users\rachi\AppData\Local\Programs\Python\Python310-32\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
    response = get_response(request).....
 ..
    raise ValueError(
ValueError: Cannot assign "<User: salman>": "DoctorProfile.user" must be a "Doctor" instance.

This is my code

my models.py

class User(AbstractUser):
    is_doctor = models.BooleanField(default=False)
    is_patient = models.BooleanField(default=False)

class Doctor(models.Model):
    user = models.OneToOneField(
        User, on_delete=models.CASCADE, primary_key=True)
    number_phone = models.CharField(
        _('االهاتف :'), max_length=50, blank=True, null=True)
    last_login = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return '%s' % (self.user.username)

class DoctorProfile (models.Model):

    }
    user = models.OneToOneField(Doctor, on_delete=models.CASCADE, primary_key=True)

    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = slugify(self.name)
        super(DoctorProfile, self).save(*args, **kwargs)

    def __str__(self):
        return '%s' % (self.name)

    # def get_absolute_url(self):
    #     return reverse("doctor_detail", kwargs={"slug": self.slug})

def create_profile(sender, **kwargs):

    if kwargs['created']:
        DoctorProfile.objects.create(user=kwargs['instance'])

post_save.connect(create_profile, sender=User)

class Patient(models.Model):
    user = models.OneToOneField(
        User, on_delete=models.CASCADE, primary_key=True)
    name = models.CharField(max_length=50, verbose_name="الاسم ")
    last_login = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return '%s' % (self.user.username)

please tell me where is the probleme


来源: stackexchange

问:
Word Checking With Python
I am pulling data from a sheet using selenium. I have links in the database. He has to take a link, open the ipage, look inside and see if there are some words. If there is, I will not send an e-mail, otherwise I will. I need to do this check for each link. Maybe the codes I added are very wrong, but I have no other idea.

```<code>mydb = mysql.connector.connect(
    host="localhost",
    user="root",
    password="",
    database="send_mail"
)
mycursor = mydb.cursor()

sql = "SELECT ad_link FROM adlinks_de"

mycursor.execute(sql)

myresult = mycursor.fetchall()

all_links = myresult[0:]

len_all_links = len(all_links)

dataframe = pd.DataFrame(all_links, columns=['links'])

options = webdriver.ChromeOptions()
prefs = {"profile.managed_default_content_settings.images": 2}
options.add_experimental_option("prefs", prefs)
service = Service(executable_path=r'C:\Users\Wiveda\Desktop\WebScraping\Mobile-de-Web-Scraping\chromedriver.exe')
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=options)
#driver = webdriver.Chrome(service=Service(ChromeDriverManager()).install(), options=options)

driver.find_element()

base_source = driver.page_source

driver.find_element(base)

driver.maximize_window()

search_kelimeler = ['T','A','B','C','D','E']

for i in range(5):
    if eleman == liste[i]:
        print("\nCannot send mail because it contains the word.Index :", i)
        kontrol = kontrol + 1

      if(kontrol == 0):
        print("Mail sending.")

      else

</code>```

Maybe this is very wrong but I don't know how to do it.

ContentLicense: CC BY-SA 4.0

Title: Word Checking With Python

Body:
I am pulling data from a sheet using selenium. I have links in the database. He has to take a link, open the ipage, look inside and see if there are some words. If there is, I will not send an e-mail, otherwise I will. I need to do this check for each link. Maybe the codes I added are very wrong, but I have no other idea.

mydb = mysql.connector.connect(
    host="localhost",
    user="root",
    password="",
    database="send_mail"
)
mycursor = mydb.cursor()

sql = "SELECT ad_link FROM adlinks_de"

mycursor.execute(sql)

myresult = mycursor.fetchall()

all_links = myresult[0:]

len_all_links = len(all_links)

dataframe = pd.DataFrame(all_links, columns=['links'])

options = webdriver.ChromeOptions()
prefs = {"profile.managed_default_content_settings.images": 2}
options.add_experimental_option("prefs", prefs)
service = Service(executable_path=r'C:\Users\Wiveda\Desktop\WebScraping\Mobile-de-Web-Scraping\chromedriver.exe')
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=options)
#driver = webdriver.Chrome(service=Service(ChromeDriverManager()).install(), options=options)

driver.find_element()

base_source = driver.page_source

driver.find_element(base)

driver.maximize_window()

search_kelimeler = ['T','A','B','C','D','E']

for i in range(5):
    if eleman == liste[i]:
        print("\nCannot send mail because it contains the word.Index :", i)
        kontrol = kontrol + 1

      if(kontrol == 0):
        print("Mail sending.")

      else

Maybe this is very wrong but I don't know how to do it.


问:
Modify checksum and counter of Periodic CAN message using Python CAN module
I am trying to modify the counter and checksum in can bus which is sending periodic cyclic message. The issue is counter is increasing from lets say 0-4. Can anyone help in updating a periodic message (i.e. update checksum based on counter after every cycle time like 20ms)

I found "can.ModifiableCyclicTaskABC" function but its working only once not after each cycle time.

Kindly assist.


问:
fastapi multiple select in open api parameter
Is it possible to add multiple select for a dropdown in fastapi openapi?
I only manage to select one.

if I set Optional[List] it wont run, the enum?).

if I set {[ids]}in the routes openapi says it is a array and no dropdown.

```<code>@app.get("/schedules")
@app.get("/schedules/{ids}", include_in_schema=False)
@app.get("/schedules/{ids}/{active}")
async def GetScedules(
  ids:Optional[str]=Query(None, enum=[str(id) for id in appconfig['projectids']]),
  active:Optional[str]=Query(None, enum=["active", "notactive"])):
  """ list gitlab schedules sorted on projectids """
  if isinstance(ids, str): # convert str to list
    if ',' in ids:
      ids = ids.split(',')
    else:
      ids = [ids]
</code>```

Body:
Is it possible to add multiple select for a dropdown in fastapi openapi?
I only manage to select one.

if I set Optional[List] it wont run, the enum?).

if I set {[ids]}in the routes openapi says it is a array and no dropdown.

@app.get("/schedules")
@app.get("/schedules/{ids}", include_in_schema=False)
@app.get("/schedules/{ids}/{active}")
async def GetScedules(
  ids:Optional[str]=Query(None, enum=[str(id) for id in appconfig['projectids']]),
  active:Optional[str]=Query(None, enum=["active", "notactive"])):
  """ list gitlab schedules sorted on projectids """
  if isinstance(ids, str): # convert str to list
    if ',' in ids:
      ids = ids.split(',')
    else:
      ids = [ids]


问:
Must CLANG be in System Path when using cmake and Visual Studio?
I want to use

Visual Studio 2022

CMakeLists.txt based project

LLVM and C++

To be able to have for future multiple Clang Versions in parallel on my HardDrive (e.g. Support of older projects), I do not want to add Clang to my system path.

If I run that setup in the command line it works without having to add CLANG to my system path. But it does not in Visual Studio

The current setup for Visual Studio works with a batch file adding the Clang Path to the current System Path and starting Visual Studio afterward.

Here is my current CMakeLists.txt

```<code>
cmake_minimum_required(VERSION 3.10)

set(PROJECT_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/../../..")

set(CMAKE_PREFIX_PATH "${PROJECT_ROOT}/tools/compiler/LLVM/bin")

# Check if the compiler is available in the expected directory
find_path(COMPILER_DIR
          NAMES clang.exe
         )

# Check if the compiler was found
IF( IS_DIRECTORY "${COMPILER_DIR}")
  # We want to choose the compiler used for this project
  # This works only if the set is done before the project() call
  set(CMAKE_C_COMPILER   ${COMPILER_DIR}/clang.exe CACHE PATH "" FORCE)
  set(CMAKE_CXX_COMPILER ${COMPILER_DIR}/clang++.exe CACHE PATH "" FORCE)
ELSE()
  MESSAGE(STATUS "Compiler directory not found")
ENDIF()

project(runUnitTests)

# removed some lines ...
set(GTEST "${PROJECT_ROOT}/tools/googletest-main")
set(COMMON "${PROJECT_ROOT}/common")

# ----======================================================================----

add_definitions(-DINLINE=inline)
add_definitions(-DUNIT_TEST)
add_definitions(-DGTEST_USE_OWN_TR1_TUPLE)

 # Prevent overriding the parent project's compiler/linker
 # settings on Windows
 set(gtest_force_shared_crt ON CACHE BOOL "" FORCE)

# ----======================================================================----
#     GTest.
# ----======================================================================----

# enable CMake’s test runner to discover the tests included in the binary,
# using the GoogleTest CMake module.
include(GoogleTest)

# add the google test directory as a subdirectory
# by this it gets automatically build and the libraries are put into the "out" directory
add_subdirectory(${GTEST} out)

# Add include directories
include_directories(
   ${CMAKE_CURRENT_SOURCE_DIR}
   ${GTEST}/googletest/include
   ${GTEST}/googlemock/include
   # removed some lines ...
)

# ----======================================================================----
#     Headers.
# ----======================================================================----

file(GLOB_RECURSE ${PROJECT_NAME}_HEADERS "*.h" "*.hpp")

# ----======================================================================----
#     Sources.
# ----======================================================================----

# Main Sources
set(SOURCES
# removed some lines ...
   ./main_pc.cpp
)

# additional source files
set(ADDITIONAL_SOURCES
  # Please add here the source files needed for your test
  ./sampleClass.cpp
)

# Test case source files
set(TEST_SOURCES
  # Please add here your own test case files
  ./test_sampleClass.cpp
)

# ----======================================================================----
#     Executable setup
# ----======================================================================----

# Test without matlab libraries
add_executable(${PROJECT_NAME} ${SOURCES} ${ADDITIONAL_SOURCES} ${TEST_SOURCES} ${${PROJECT_NAME}_HEADERS})

# add the gtest/gmock library to the linker
target_link_libraries(${PROJECT_NAME} gtest gmock)

# This is so you can do 'make test' to see all your tests run, instead of
# manually running the executable runUnitTests to see those specific tests.
add_test(NAME allTests COMMAND runUnitTests)

# Check if the teamcity envoirnment variable is set
# Because when running on teamcity the gtest_discover_tests call fails
# But this is needed that the Visual Studio Test Explorer can detect the test cases.
if(NOT DEFINED ENV{TEAMCITY_VERSION})
  enable_testing()
  # since CMake 3.10 it is possible to scan the test executable for test
  # This is needed that Visual Studio Test Explorer is able to display the test cases
  gtest_discover_tests(${PROJECT_NAME})
endif(NOT DEFINED ENV{TEAMCITY_VERSION})
</code>```

and here is my CMakeSettings.json

```<code>
{
  "configurations": [
    {
      "name": "x86-Debug",
      "generator": "Ninja",
      "configurationType": "Debug",
      "inheritEnvironments": [ "clang_cl_x86" ],
      "buildRoot": "${projectDir}\\out\\build\\${name}",
      "installRoot": "${projectDir}\\out\\install\\${name}",
      "cmakeCommandArgs": "",
      "buildCommandArgs": "",
      "ctestCommandArgs": ""
    }
  ]
}
</code>```

Error message in Visual Studio if Clang is not in Path:

```<code>1> CMakeSettings Error at CMakeSettings.json: Failed to load configuration 'x86-Debug'. Enable Cross Platform Logging for more information.
1> Failed to load configuration 'x86-Debug'. Enable Cross Platform Logging for more information.
1> Failed to load configuration 'x86-Debug'. Enable Cross Platform Logging for more information.
</code>```

I enabled "Cross Platform Logging" but it is empty.

Tried also to set absolute paths in CMakeLists to CLANG. Did not change the situation.

When I run Visual Studio once with CLang in the Path and compile the project -> it works on the next start for Visual Studio that Clang is NOT in the PATH. When I delete the "out" folder, back to failing.

Body:
I want to use

Visual Studio 2022

CMakeLists.txt based project

LLVM and C++

To be able to have for future multiple Clang Versions in parallel on my HardDrive (e.g. Support of older projects), I do not want to add Clang to my system path.

If I run that setup in the command line it works without having to add CLANG to my system path. But it does not in Visual Studio

The current setup for Visual Studio works with a batch file adding the Clang Path to the current System Path and starting Visual Studio afterward.

Here is my current CMakeLists.txt

cmake_minimum_required(VERSION 3.10)

set(PROJECT_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/../../..")

set(CMAKE_PREFIX_PATH "${PROJECT_ROOT}/tools/compiler/LLVM/bin")

# Check if the compiler is available in the expected directory
find_path(COMPILER_DIR
          NAMES clang.exe
         )

# Check if the compiler was found
IF( IS_DIRECTORY "${COMPILER_DIR}")
  # We want to choose the compiler used for this project
  # This works only if the set is done before the project() call
  set(CMAKE_C_COMPILER   ${COMPILER_DIR}/clang.exe CACHE PATH "" FORCE)
  set(CMAKE_CXX_COMPILER ${COMPILER_DIR}/clang++.exe CACHE PATH "" FORCE)
ELSE()
  MESSAGE(STATUS "Compiler directory not found")
ENDIF()

project(runUnitTests)

# removed some lines ...
set(GTEST "${PROJECT_ROOT}/tools/googletest-main")
set(COMMON "${PROJECT_ROOT}/common")

# ----======================================================================----

add_definitions(-DINLINE=inline)
add_definitions(-DUNIT_TEST)
add_definitions(-DGTEST_USE_OWN_TR1_TUPLE)

 # Prevent overriding the parent project's compiler/linker
 # settings on Windows
 set(gtest_force_shared_crt ON CACHE BOOL "" FORCE)

# ----======================================================================----
#     GTest.
# ----======================================================================----

# enable CMake’s test runner to discover the tests included in the binary,
# using the GoogleTest CMake module.
include(GoogleTest)

# add the google test directory as a subdirectory
# by this it gets automatically build and the libraries are put into the "out" directory
add_subdirectory(${GTEST} out)

# Add include directories
include_directories(
   ${CMAKE_CURRENT_SOURCE_DIR}
   ${GTEST}/googletest/include
   ${GTEST}/googlemock/include
   # removed some lines ...
)

# ----======================================================================----
#     Headers.
# ----======================================================================----

file(GLOB_RECURSE ${PROJECT_NAME}_HEADERS "*.h" "*.hpp")

# ----======================================================================----
#     Sources.
# ----======================================================================----

# Main Sources
set(SOURCES
# removed some lines ...
   ./main_pc.cpp
)

# additional source files
set(ADDITIONAL_SOURCES
  # Please add here the source files needed for your test
  ./sampleClass.cpp
)

# Test case source files
set(TEST_SOURCES
  # Please add here your own test case files
  ./test_sampleClass.cpp
)

# ----======================================================================----
#     Executable setup
# ----======================================================================----

# Test without matlab libraries
add_executable(${PROJECT_NAME} ${SOURCES} ${ADDITIONAL_SOURCES} ${TEST_SOURCES} ${${PROJECT_NAME}_HEADERS})

# add the gtest/gmock library to the linker
target_link_libraries(${PROJECT_NAME} gtest gmock)

# This is so you can do 'make test' to see all your tests run, instead of
# manually running the executable runUnitTests to see those specific tests.
add_test(NAME allTests COMMAND runUnitTests)

# Check if the teamcity envoirnment variable is set
# Because when running on teamcity the gtest_discover_tests call fails
# But this is needed that the Visual Studio Test Explorer can detect the test cases.
if(NOT DEFINED ENV{TEAMCITY_VERSION})
  enable_testing()
  # since CMake 3.10 it is possible to scan the test executable for test
  # This is needed that Visual Studio Test Explorer is able to display the test cases
  gtest_discover_tests(${PROJECT_NAME})
endif(NOT DEFINED ENV{TEAMCITY_VERSION})

and here is my CMakeSettings.json

{
  "configurations": [
    {
      "name": "x86-Debug",
      "generator": "Ninja",
      "configurationType": "Debug",
      "inheritEnvironments": [ "clang_cl_x86" ],
      "buildRoot": "${projectDir}\\out\\build\\${name}",
      "installRoot": "${projectDir}\\out\\install\\${name}",
      "cmakeCommandArgs": "",
      "buildCommandArgs": "",
      "ctestCommandArgs": ""
    }
  ]
}

Error message in Visual Studio if Clang is not in Path:

1> CMakeSettings Error at CMakeSettings.json: Failed to load configuration 'x86-Debug'. Enable Cross Platform Logging for more information.
1> Failed to load configuration 'x86-Debug'. Enable Cross Platform Logging for more information.
1> Failed to load configuration 'x86-Debug'. Enable Cross Platform Logging for more information.

I enabled "Cross Platform Logging" but it is empty.

Tried also to set absolute paths in CMakeLists to CLANG. Did not change the situation.

When I run Visual Studio once with CLang in the Path and compile the project -> it works on the next start for Visual Studio that Clang is NOT in the PATH. When I delete the "out" folder, back to failing.


问:
Recover previously opened in browser Jupyter Notebook's code from cache
I've been working with Jupyter Notebooks code in browser though ssh connenction. The notebook was deleted from server and I wonder is there a way to find browser, Chrome, cache with that notebook code.
I am running Ubuntu 22.04 and Chrome 108.

P.S. I came across this suggestion, but grep didn't find any import code in binaries.


问:
How to make sure uploaded files saved successfully
Here is the scenario:

A user select some files using a browser or an app and send them to a server.

The server save them on the file system permanently.

The server save the address of the files on a database.

How can I make sure this scenario happens like a transaction? For example, do I need to calculate the number/checksum of files both at the client side and the server side? What happens if the server shutdown after the 2nd step and before the 3rd step? What other things should I consider for a robust file uploading?


问:
Unable to use method of a class in different class-missing 2 required positional arguments
I have two python classes:- One class(CloudLink) is responsible for sending JSON events to the app and another(ReadData) is responsible for building the JSON data.
The ReadData class will be using the CloudLink methods to send the JSON data to the App. But I'm getting error _buildJSONdata() missing 1 required positional argument: 'Data'.
ReadData class

```<code>from pyspark.sql import SparkSession
import functools
from pyspark.sql import DataFrame
from pyspark.sql.functions import explode
from  cosmosconnect import azurecosmos

class ReadData:

    @exception(logger)
    def __init__(self):

        self.spark_session = (
            SparkSession.builder
            .appName("readData")
            .getOrCreate()
        )

        mssparkutils.fs.unmount('/mnt/test')
        logger.info("Drive unmounted")
        mssparkutils.fs.mount(
            'abfss://abc@transl.dfs.core.windows.net/',
            '/mnt/test',
            {'linkedService': "linkCosmos"}
        )

        logger.info("Mounted Successfully")
        self.input_directory = (f"synfs:/{mssparkutils.env.getJobId()}/mnt/test/input_path"
        )
        self.output_directory = (f"synfs:/{mssparkutils.env.getJobId()}/mnt/test/output_path"
        )

    '''
    Reading the schema from csv file
    '''
    @exception(logger)
    def readConfig(self):
        try:

            logger.info(f"Reading the Config present in {self.input_directory} ")
            dfConfig = self.spark_session.read.option("multiline","true") \
                           .json(self.input_directory)
            #for f in dfConfig.select("Entity","Query","Business_Rule").collect():
            dfConfig=dfConfig.select(explode('Input').alias('Input_Data'))\
                 .select('Input_Data.Validation_Type','Input_Data.Entity','Input_Data.Query','Input_Data.Business_Rule')
            for f in dfConfig.rdd.toLocalIterator():
            #for index, f in dfConfig.toPandas().iterrows():
                self.Validation_Type=f[0]
                self.container=f[1]
                self.query=f[2]
                self.rule=f[3]
                self.readCosmos(self)
        except:
            raise ValueError("")

    @exception(logger)
    def readCosmos(self,*params):
        #from  cosmosconnect import azurecosmos
        #a=[]
        linkedService='fg'
        df=azurecosmos.cosmosConnect(linkedService,self.query,self.container)
        df.cache()
        if len(df.head(1)) >0:
           outputpath=self.output_directory+'/'+self.container
           df.coalesce(1).write.mode('overwrite').parquet(outputpath)
           Status="Validation Failure"
           Data= {"Validation_Type":[],"Status":[],"Container":[],"Business_Rule":[]}
           Data["Validation_Type"].append(self.Validation_Type)
           Data["Status"].append(Status)
           Data["Container"].append(self.container)
           Data["Business_Rule"].append(self.rule)
           CloudLink._buildJSONdata(Data)

if __name__ == "__main__":
   p = ReadData()
   p.readConfig()
</code>```

CloudLink class

```<code>import json
import datetime
import hashlib
import json
import sys
import traceback

import adal
import requests
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry
import logging
from functools import wraps
import sys
def create_logger():

    #create a logger object
    #logger = logging.getLogger()
    logger = logging.getLogger()
    logger.setLevel(logging.INFO)

    logfile = logging.FileHandler('exc_logger.log')
    #logfile = logging.StreamHandler(sys.stdout)

    fmt = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
    formatter = logging.Formatter(fmt)

    logfile.setFormatter(formatter)
    logger.addHandler(logfile)

    return logger

logger = create_logger()

def exception(logger):

    def decorator(func):

        @wraps(func)
        def wrapper(*args, **kwargs):

            try:
                return func(*args, **kwargs)

            except:
                issue = "exception in "+func.__name__+"\n"
                issue = issue+"-------------------------\
                ------------------------------------------------\n"
                logger.exception(issue)
            raise

        return wrapper
    return decorator

class CloudLink(object):
    _token = None
    _instance = None
    http = None
    cloudclient = TokenLibrary.getSecret("xxxx", "rtrt")
    clientid = TokenLibrary.getSecret("xxxx", "tyty")
    clientcredentials = TokenLibrary.getSecret("xxxx", "abcabc")
    authority_url = TokenLibrary.getSecret("xxxx", "abab")
    cloudtest = TokenLibrary.getSecret("xxxx", "yyyy")

    @staticmethod
    def getInstance():

        if not CloudLink._instance:
            CloudLink._instance = CloudLink()

        return CloudLink._instance

    def __init__(self):

        retry_strategy = Retry(
            total=3,
            backoff_factor=0,
            status_forcelist=[429, 500, 502, 503, 504],
            allowed_methods=["HEAD", "GET", "OPTIONS"],
        )
        adapter = HTTPAdapter(max_retries=retry_strategy)
        self.http = requests.Session()
        self.http.mount("https://", adapter)
        self.http.mount("http://", adapter)
        print("Inside init")

    def parseJSON(self, t):
        try:
            eventData = json.loads(t)
            logger.info(f"Sending {eventData} to cloud")
            self.sendToCloud(eventData)
        except ValueError as e:
            print("Error: %s Please validate JSON in https://www.jsonschemavalidator.net/"% e)
            return None  # or: raise

    def sendToCloud(self, eventData):
        cloudData = {"eventData": eventData, "metadata": self._buildMetadata()}
        logger.info(f"Raising alert with data=({cloudData}")
        response = self.http.post(
            self.cloudtest, headers=self._buildHeaders(), json=cloudData
        )
        logger.info(f"cloud alert response={response}")
        if response.status_code == 202 or response.status_code == 200:
            logger.info("Mail sent to Cloud")
        else:
            raise Exception(f"Cloud reporting failed with Error {response}")

    def _buildJSONdata(self,Data):
        if len(Data) == 0:
            raise Exception("JSON is empty")
        else:
            t = json.dumps(self.Data)
            self.parseJSON(t)

    def _buildMetadata(self):
        return {
            "messageType": "Send Email",
            "messageVersion": "0.0.1",
            "sender": "Send Email",
          }

    def _buildHeaders(self):
        self._refreshADToken()

        headers = {
            "Authorization": "Bearer {}".format(self._token["accessToken"]),
            "Content-type": "application/json",
            "Accept": "text/plain",
        }
        return headers

    def _refreshADToken(self):
        def shouldRenew(token):
            """Returns True if the token should be renewed"""

            expiresOn = datetime.datetime.strptime(
                token["expiresOn"], "%Y-%m-%d %H:%M:%S.%f"
            )
            now = datetime.datetime.now()
            return (expiresOn - now) < datetime.timedelta(minutes=5)

        if not self._token or shouldRenew(self._token):
            logger.info("Renewing credentials for Alerting")
            result = None

            try:
                context = adal.AuthenticationContext(CloudLink.authority_url)
                result = context.acquire_token_with_client_credentials(CloudLink.cloudclient, CloudLink.clientid,CloudLink.clientcredentials)
            except Exception as e:
                error = "Failed to renew client credentials."
                logger.info(error)
                raise

            if result and "accessToken" in result:
                self._token = result
            else:
                logger.error(
                    "Failed to acquire bearer token. accessToken not found in result object on renewing credentials."
                )
                raise Exception("Could not acquire a bearer token")
</code>```

Body:
I have two python classes:- One class(CloudLink) is responsible for sending JSON events to the app and another(ReadData) is responsible for building the JSON data.
The ReadData class will be using the CloudLink methods to send the JSON data to the App. But I'm getting error _buildJSONdata() missing 1 required positional argument: 'Data'.
ReadData class

from pyspark.sql import SparkSession
import functools
from pyspark.sql import DataFrame
from pyspark.sql.functions import explode
from  cosmosconnect import azurecosmos

class ReadData:

    @exception(logger)
    def __init__(self):

        self.spark_session = (
            SparkSession.builder
            .appName("readData")
            .getOrCreate()
        )

        mssparkutils.fs.unmount('/mnt/test')
        logger.info("Drive unmounted")
        mssparkutils.fs.mount(
            'abfss://abc@transl.dfs.core.windows.net/',
            '/mnt/test',
            {'linkedService': "linkCosmos"}
        )

        logger.info("Mounted Successfully")
        self.input_directory = (f"synfs:/{mssparkutils.env.getJobId()}/mnt/test/input_path"
        )
        self.output_directory = (f"synfs:/{mssparkutils.env.getJobId()}/mnt/test/output_path"
        )

    '''
    Reading the schema from csv file
    '''
    @exception(logger)
    def readConfig(self):
        try:

            logger.info(f"Reading the Config present in {self.input_directory} ")
            dfConfig = self.spark_session.read.option("multiline","true") \
                           .json(self.input_directory)
            #for f in dfConfig.select("Entity","Query","Business_Rule").collect():
            dfConfig=dfConfig.select(explode('Input').alias('Input_Data'))\
                 .select('Input_Data.Validation_Type','Input_Data.Entity','Input_Data.Query','Input_Data.Business_Rule')
            for f in dfConfig.rdd.toLocalIterator():
            #for index, f in dfConfig.toPandas().iterrows():
                self.Validation_Type=f[0]
                self.container=f[1]
                self.query=f[2]
                self.rule=f[3]
                self.readCosmos(self)
        except:
            raise ValueError("")

    @exception(logger)
    def readCosmos(self,*params):
        #from  cosmosconnect import azurecosmos
        #a=[]
        linkedService='fg'
        df=azurecosmos.cosmosConnect(linkedService,self.query,self.container)
        df.cache()
        if len(df.head(1)) >0:
           outputpath=self.output_directory+'/'+self.container
           df.coalesce(1).write.mode('overwrite').parquet(outputpath)
           Status="Validation Failure"
           Data= {"Validation_Type":[],"Status":[],"Container":[],"Business_Rule":[]}
           Data["Validation_Type"].append(self.Validation_Type)
           Data["Status"].append(Status)
           Data["Container"].append(self.container)
           Data["Business_Rule"].append(self.rule)
           CloudLink._buildJSONdata(Data)

if __name__ == "__main__":
   p = ReadData()
   p.readConfig()

CloudLink class

import json
import datetime
import hashlib
import json
import sys
import traceback

import adal
import requests
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry
import logging
from functools import wraps
import sys
def create_logger():

    #create a logger object
    #logger = logging.getLogger()
    logger = logging.getLogger()
    logger.setLevel(logging.INFO)

    logfile = logging.FileHandler('exc_logger.log')
    #logfile = logging.StreamHandler(sys.stdout)

    fmt = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
    formatter = logging.Formatter(fmt)

    logfile.setFormatter(formatter)
    logger.addHandler(logfile)

    return logger

logger = create_logger()

def exception(logger):

    def decorator(func):

        @wraps(func)
        def wrapper(*args, **kwargs):

            try:
                return func(*args, **kwargs)

            except:
                issue = "exception in "+func.__name__+"\n"
                issue = issue+"-------------------------\
                ------------------------------------------------\n"
                logger.exception(issue)
            raise

        return wrapper
    return decorator

class CloudLink(object):
    _token = None
    _instance = None
    http = None
    cloudclient = TokenLibrary.getSecret("xxxx", "rtrt")
    clientid = TokenLibrary.getSecret("xxxx", "tyty")
    clientcredentials = TokenLibrary.getSecret("xxxx", "abcabc")
    authority_url = TokenLibrary.getSecret("xxxx", "abab")
    cloudtest = TokenLibrary.getSecret("xxxx", "yyyy")

    @staticmethod
    def getInstance():

        if not CloudLink._instance:
            CloudLink._instance = CloudLink()

        return CloudLink._instance

    def __init__(self):

        retry_strategy = Retry(
            total=3,
            backoff_factor=0,
            status_forcelist=[429, 500, 502, 503, 504],
            allowed_methods=["HEAD", "GET", "OPTIONS"],
        )
        adapter = HTTPAdapter(max_retries=retry_strategy)
        self.http = requests.Session()
        self.http.mount("https://", adapter)
        self.http.mount("http://", adapter)
        print("Inside init")

    def parseJSON(self, t):
        try:
            eventData = json.loads(t)
            logger.info(f"Sending {eventData} to cloud")
            self.sendToCloud(eventData)
        except ValueError as e:
            print("Error: %s Please validate JSON in https://www.jsonschemavalidator.net/"% e)
            return None  # or: raise

    def sendToCloud(self, eventData):
        cloudData = {"eventData": eventData, "metadata": self._buildMetadata()}
        logger.info(f"Raising alert with data=({cloudData}")
        response = self.http.post(
            self.cloudtest, headers=self._buildHeaders(), json=cloudData
        )
        logger.info(f"cloud alert response={response}")
        if response.status_code == 202 or response.status_code == 200:
            logger.info("Mail sent to Cloud")
        else:
            raise Exception(f"Cloud reporting failed with Error {response}")

    def _buildJSONdata(self,Data):
        if len(Data) == 0:
            raise Exception("JSON is empty")
        else:
            t = json.dumps(self.Data)
            self.parseJSON(t)

    def _buildMetadata(self):
        return {
            "messageType": "Send Email",
            "messageVersion": "0.0.1",
            "sender": "Send Email",
          }

    def _buildHeaders(self):
        self._refreshADToken()

        headers = {
            "Authorization": "Bearer {}".format(self._token["accessToken"]),
            "Content-type": "application/json",
            "Accept": "text/plain",
        }
        return headers

    def _refreshADToken(self):
        def shouldRenew(token):
            """Returns True if the token should be renewed"""

            expiresOn = datetime.datetime.strptime(
                token["expiresOn"], "%Y-%m-%d %H:%M:%S.%f"
            )
            now = datetime.datetime.now()
            return (expiresOn - now) < datetime.timedelta(minutes=5)

        if not self._token or shouldRenew(self._token):
            logger.info("Renewing credentials for Alerting")
            result = None

            try:
                context = adal.AuthenticationContext(CloudLink.authority_url)
                result = context.acquire_token_with_client_credentials(CloudLink.cloudclient, CloudLink.clientid,CloudLink.clientcredentials)
            except Exception as e:
                error = "Failed to renew client credentials."
                logger.info(error)
                raise

            if result and "accessToken" in result:
                self._token = result
            else:
                logger.error(
                    "Failed to acquire bearer token. accessToken not found in result object on renewing credentials."
                )
                raise Exception("Could not acquire a bearer token")


问:
How to prevent mui Tooltip from closing when pressed on date popper inside tooltip
I have a Tooltip that serves as a date filter. It has two different date inputs one is for from date and other is for to date, there are also two buttons one is to clear filters and other is to apply them. When I clear filter tooltip is closed, but I also want to close tooltip without clearing dates just by clicking outside of tooltip area. I have made it work but when I press on a date and open options to select date and press on that open popper, tooltip closes because it detects pooper as outside click.

My question is how to prevent outside click when selecting dates?

This is dates component that sits inside tooltip:

```<code>import { EtsButton } from '@components/utils/ets/buttons/ets-button/ets-button';
import { CustomDatePicker } from '@components/utils/ets/inputs/custom-input-date/custom-date-picker';
import {
  mergeDateFiltersData,
  setDateFiltersData
} from '@store/modules/modals-and-forms/actions';
import { useDispatch, useSelector } from '@utilsFn/hooks/use-selector';
import { useTranslation } from 'next-i18next';
import React from 'react';
import styled from 'styled-components';

export const DateFilters = (props: NTableColumnsFilter.IProps) => {
  const { t } = useTranslation();

  const fromDate = useSelector(
    (s) => s?.modalsAndForms?.dateFiltersData?.fromDate
  );

  const toDate = useSelector((s) => s?.modalsAndForms?.dateFiltersData?.toDate);

  const dispatch = useDispatch();

  return (
    <TableColumnsFilterMenu>
      <div className="item">
        <p className="label">{t('page-sales-analysis:::main::Date from')}</p>
        <CustomDatePicker
          value={fromDate || null}
          onChange={(val) => {
            dispatch(
              mergeDateFiltersData({
                fromDate: val
              })
            );
          }}
        />
      </div>
      <div className="item">
        <p className="label">{t('page-sales-analysis:::main::Date until')}</p>

        <CustomDatePicker
          value={toDate || null}
          onChange={(val) => {
            dispatch(
              mergeDateFiltersData({
                toDate: val
              })
            );
          }}
        />
      </div>
      <div className="action-buttons">
        <EtsButton
          button={{
            onClick: () => {
              dispatch(
                setDateFiltersData({
                  openModalType: null,
                  fromDate: null,
                  toDate: null
                })
              );

              props.setFromDateHandler(null);
              props.setToDateHandler(null);

              props.setShowMenuHandler(false);
            }
          }}
          height="Height33"
          padding="Padding7x15"
          color="grey"
          background="whiteFFF"
          fontStyle="bold14"
        >
          {t('page-sales-analysis:::main::Clear the filters')}
        </EtsButton>
        <EtsButton
          button={{
            onClick: () => {
              dispatch(
                mergeDateFiltersData({
                  openModalType: null
                })
              );

              props.setFromDateHandler(fromDate || null);
              props.setToDateHandler(toDate || null);
              props.setShowMenuHandler(false);
            }
          }}
          height="Height33"
          padding="Padding7x15"
          color="white"
          background="redC20"
          fontStyle="bold14"
        >
          {t('page-sales-analysis:::main::Filter')}
        </EtsButton>
      </div>
    </TableColumnsFilterMenu>
  );
};

export namespace NTableColumnsFilter {
  export interface IProps {
    setFromDateHandler: (val: Date | null) => void;
    setToDateHandler: (val: Date | null) => void;
    setShowMenuHandler: (val: boolean) => void;
  }
}

const TableColumnsFilterMenu = styled.div`
  border-radius: 7px;
  background-color: #ffffff;
  box-shadow: 0px 3px 6px #00000029;
  padding: 16px 21px 20px 21px;
  .label {
    font: normal normal 600 14px/20px 'Open Sans';
    color: #000000;
  }

  .item {
    display: flex;
    flex-direction: column;
  }

  .action-buttons {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    margin-top: 20px;

    button:first-child {
      margin-right: 10px;
    }

    button {
      height: 33px;
    }
  }
`;

</code>```

this is date filters tooltip component

```<code>import Tooltip, { TooltipProps } from '@mui/material/Tooltip';
import { SVGIconCalendar } from '@styles/global-icons/icons/svg-icon-calendar';
import { useOutsideClick } from '@utilsFn/hooks/use-outside-click';
import { useSelector } from '@utilsFn/hooks/use-selector';
import React from 'react';
import styled from 'styled-components';

import { DateFilters } from './components/date-filters';

interface ITooltipProps extends TooltipProps {
  mobile: boolean | number;
}

const MenuTooltip = styled(({ className, ...props }: ITooltipProps) => (
  <Tooltip
    {...props}
    classes={{ popper: className }}
    componentsProps={{
      tooltip: {
        sx: {
          backgroundColor: 'transparent',
          padding: '0',
          margin: '0',

          minWidth: props?.mobile ? 200 : 419
        }
      }
    }}
  />
))(() => ({}));

export const MenuDateTooltipFilter = (props: NTableColumnsFilter.IProps) => {
  const isMobile = useSelector((s) => s.device.isMobile);
  const refMenu = React.useRef<HTMLDivElement>(null);

  const [showMenu, setShowMenu] = React.useState<boolean>(false);

  const setShowMenuHandler = (val: boolean) => {
    setShowMenu(val);
  };

  const handlerCloseMenu = () => {
    setShowMenu(() => false);
  };

  useOutsideClick(refMenu, handlerCloseMenu);

  return (
    <ContainerTableColumnsFilter>
      <MenuTooltip
        mobile={isMobile ? 1 : 0}
        placement="bottom-end"
        open={showMenu}
        title={
          <div ref={refMenu}>
            <DateFilters
              setShowMenuHandler={setShowMenuHandler}
              setFromDateHandler={props.setFromDateHandler}
              setToDateHandler={props.setToDateHandler}
            />
          </div>
        }
      >
        <button
          type="button"
          className="icon-button"
          onClick={() => {
            setShowMenu(() => true);
          }}
        >
          <SVGIconCalendar />
        </button>
      </MenuTooltip>
    </ContainerTableColumnsFilter>
  );
};

export namespace NTableColumnsFilter {
  export interface IProps {
    setFromDateHandler: (val: Date | null) => void;
    setToDateHandler: (val: Date | null) => void;
  }
}

const ContainerTableColumnsFilter = styled.div`
  width: 50px;
  height: 50px;

  .icon-button {
    cursor: pointer;
    width: 50px;
    height: 50px;
    display: flex;
    align-items: center;
    justify-content: center;
    border: none;
    background-color: #ffffff;

    :hover {
      svg {
        path {
          fill: #c20b0b;
        }
      }
    }
  }
`;

</code>```

Date picker itself is a customized mui datepicker

Update:
I have achieved my desired result by using onOpen and onClose event existing in on date picker and disabling outside click function when popper is open ,but each time i select date popper flickers for a second before closing

onOpen and OnClose

```<code>    onOpen={() => {
            props.setIsDatePickerOpensHandler(true);
          }}
          onClose={() => {
            props.setIsDatePickerOpensHandler(false);
          }}
</code>```

type of the handler

```<code>setIsDatePickerOpensHandler: (val: boolean) => void;
</code>```

state and handler function in menu-date-tooltip-filter.tsx

```<code>  const [isDatePickerOpen, setIsDatePickerOpen] =
    React.useState<boolean>(false);

  const setIsDatePickerOpensHandler = (val: boolean) => {
    setIsDatePickerOpen(val);
  };
</code>```

if date picker is not open allow the use of outside Click function

```<code>  useOutsideClick(refMenu, () => {
    if (!isDatePickerOpen) {
      setShowMenu(() => false);
    }
  });
</code>```

It looks like after selecting date popper, it gets rerendered several times before closing

My updated question is how to solve this flickering bug?

Body:
I have a Tooltip that serves as a date filter. It has two different date inputs one is for from date and other is for to date, there are also two buttons one is to clear filters and other is to apply them. When I clear filter tooltip is closed, but I also want to close tooltip without clearing dates just by clicking outside of tooltip area. I have made it work but when I press on a date and open options to select date and press on that open popper, tooltip closes because it detects pooper as outside click.

My question is how to prevent outside click when selecting dates?

This is dates component that sits inside tooltip:

import { EtsButton } from '@components/utils/ets/buttons/ets-button/ets-button';
import { CustomDatePicker } from '@components/utils/ets/inputs/custom-input-date/custom-date-picker';
import {
  mergeDateFiltersData,
  setDateFiltersData
} from '@store/modules/modals-and-forms/actions';
import { useDispatch, useSelector } from '@utilsFn/hooks/use-selector';
import { useTranslation } from 'next-i18next';
import React from 'react';
import styled from 'styled-components';

export const DateFilters = (props: NTableColumnsFilter.IProps) => {
  const { t } = useTranslation();

  const fromDate = useSelector(
    (s) => s?.modalsAndForms?.dateFiltersData?.fromDate
  );

  const toDate = useSelector((s) => s?.modalsAndForms?.dateFiltersData?.toDate);

  const dispatch = useDispatch();

  return (
    <TableColumnsFilterMenu>

{t('page-sales-analysis:::main::Date from')}

        <CustomDatePicker
          value={fromDate || null}
          onChange={(val) => {
            dispatch(
              mergeDateFiltersData({
                fromDate: val
              })
            );
          }}
        />

{t('page-sales-analysis:::main::Date until')}

        <CustomDatePicker
          value={toDate || null}
          onChange={(val) => {
            dispatch(
              mergeDateFiltersData({
                toDate: val
              })
            );
          }}
        />

        <EtsButton
          button={{
            onClick: () => {
              dispatch(
                setDateFiltersData({
                  openModalType: null,
                  fromDate: null,
                  toDate: null
                })
              );

              props.setFromDateHandler(null);
              props.setToDateHandler(null);

              props.setShowMenuHandler(false);
            }
          }}
          height="Height33"
          padding="Padding7x15"
          color="grey"
          background="whiteFFF"
          fontStyle="bold14"
        >
          {t('page-sales-analysis:::main::Clear the filters')}
        </EtsButton>
        <EtsButton
          button={{
            onClick: () => {
              dispatch(
                mergeDateFiltersData({
                  openModalType: null
                })
              );

              props.setFromDateHandler(fromDate || null);
              props.setToDateHandler(toDate || null);
              props.setShowMenuHandler(false);
            }
          }}
          height="Height33"
          padding="Padding7x15"
          color="white"
          background="redC20"
          fontStyle="bold14"
        >
          {t('page-sales-analysis:::main::Filter')}
        </EtsButton>

    </TableColumnsFilterMenu>
  );
};

export namespace NTableColumnsFilter {
  export interface IProps {
    setFromDateHandler: (val: Date | null) => void;
    setToDateHandler: (val: Date | null) => void;
    setShowMenuHandler: (val: boolean) => void;
  }
}

const TableColumnsFilterMenu = styled.div`
  border-radius: 7px;
  background-color: #ffffff;
  box-shadow: 0px 3px 6px #00000029;
  padding: 16px 21px 20px 21px;
  .label {
    font: normal normal 600 14px/20px 'Open Sans';
    color: #000000;
  }

  .item {
    display: flex;
    flex-direction: column;
  }

  .action-buttons {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    margin-top: 20px;

    button:first-child {
      margin-right: 10px;
    }

    button {
      height: 33px;
    }
  }
`;

this is date filters tooltip component

import Tooltip, { TooltipProps } from '@mui/material/Tooltip';
import { SVGIconCalendar } from '@styles/global-icons/icons/svg-icon-calendar';
import { useOutsideClick } from '@utilsFn/hooks/use-outside-click';
import { useSelector } from '@utilsFn/hooks/use-selector';
import React from 'react';
import styled from 'styled-components';

import { DateFilters } from './components/date-filters';

interface ITooltipProps extends TooltipProps {
  mobile: boolean | number;
}

const MenuTooltip = styled(({ className, ...props }: ITooltipProps) => (
  <Tooltip
    {...props}
    classes={{ popper: className }}
    componentsProps={{
      tooltip: {
        sx: {
          backgroundColor: 'transparent',
          padding: '0',
          margin: '0',

          minWidth: props?.mobile ? 200 : 419
        }
      }
    }}
  />
))(() => ({}));

export const MenuDateTooltipFilter = (props: NTableColumnsFilter.IProps) => {
  const isMobile = useSelector((s) => s.device.isMobile);
  const refMenu = React.useRef<HTMLDivElement>(null);

  const [showMenu, setShowMenu] = React.useState<boolean>(false);

  const setShowMenuHandler = (val: boolean) => {
    setShowMenu(val);
  };

  const handlerCloseMenu = () => {
    setShowMenu(() => false);
  };

  useOutsideClick(refMenu, handlerCloseMenu);

  return (
    <ContainerTableColumnsFilter>
      <MenuTooltip
        mobile={isMobile ? 1 : 0}
        placement="bottom-end"
        open={showMenu}
        title={

            <DateFilters
              setShowMenuHandler={setShowMenuHandler}
              setFromDateHandler={props.setFromDateHandler}
              setToDateHandler={props.setToDateHandler}
            />

        }
      >
        <button
          type="button"
          className="icon-button"
          onClick={() => {
            setShowMenu(() => true);
          }}
        >
          <SVGIconCalendar />
        </button>
      </MenuTooltip>
    </ContainerTableColumnsFilter>
  );
};

export namespace NTableColumnsFilter {
  export interface IProps {
    setFromDateHandler: (val: Date | null) => void;
    setToDateHandler: (val: Date | null) => void;
  }
}

const ContainerTableColumnsFilter = styled.div`
  width: 50px;
  height: 50px;

  .icon-button {
    cursor: pointer;
    width: 50px;
    height: 50px;
    display: flex;
    align-items: center;
    justify-content: center;
    border: none;
    background-color: #ffffff;

    :hover {
      svg {
        path {
          fill: #c20b0b;
        }
      }
    }
  }
`;

Date picker itself is a customized mui datepicker

Update:
I have achieved my desired result by using onOpen and onClose event existing in on date picker and disabling outside click function when popper is open ,but each time i select date popper flickers for a second before closing

onOpen and OnClose

    onOpen={() => {
            props.setIsDatePickerOpensHandler(true);
          }}
          onClose={() => {
            props.setIsDatePickerOpensHandler(false);
          }}

type of the handler

setIsDatePickerOpensHandler: (val: boolean) => void;

state and handler function in menu-date-tooltip-filter.tsx

  const [isDatePickerOpen, setIsDatePickerOpen] =
    React.useState<boolean>(false);

  const setIsDatePickerOpensHandler = (val: boolean) => {
    setIsDatePickerOpen(val);
  };

if date picker is not open allow the use of outside Click function

  useOutsideClick(refMenu, () => {
    if (!isDatePickerOpen) {
      setShowMenu(() => false);
    }
  });

It looks like after selecting date popper, it gets rerendered several times before closing

My updated question is how to solve this flickering bug?


问:
Uncaught TypeError: Cannot read properties of null (reading 'addEventListener') - Not an issue with DOM ordering
Like the the 10,000 examples with the exact same heading, I am having a trouble with the development of a chrome extension, specifically the execution of scripts between my popup window and my content script.

The specific error i'm receiving is "Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')".

Now, I have reviewed several dozen threads with the same issue and the common theme seems to be that the placement of the scripting within the HTML code is causing the script to execute prior to the DOM loading, however I have attempted the following to resolve placement being an issue.

I have reviewed my code and I have ensured that the script it executing directly above the  tag (as to be the last item executing within the body section, and that the code also has the 'delay' flag within the script has a redundancy. I have also wrapped the code within the content script in window.onload=function() as a further redundancy, but alas, no love. I have also attempted moving the order of the code around within foreground.js, however as expected that didn't resolve the issue.

foreground.js

```<code>function calculatescript() {
    console.log("This prints to the console of the page")
    };

window.onload=function(){
    var runcalculate = document.getElementById("runcalculate");
    runcalculate.addEventListener("click", calculatescript);
    }
</code>```

popup.html

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="popup.css">
    <title>Example Extension</title>
</head>
<body>
    <div>
        <button class="button button1" id="runcalculate">Calculate</button>
    </div>

    <script src="foreground.js" defer></script>

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

manifest.js

```<code>{

    "manifest_version": 3,
    "name": "Example",
    "description": "An example of a chrome extension using manifest v3",
    "version": "0.0.1",
    "icons": {
        "16": "logo/logo-16.png",
        "48": "logo/logo-48.png",
        "128": "logo/logo-128.png"
    },
    "options_page": "settings/settings.html",
    "action": {
        "default_title": "example",
        "default_popup": "popup/popup.html"
    },
    "permissions": [
        "tabs", "scripting"
    ],
    "host_permissions": [
        "*://*/*"
    ],
    "background": {
        "service_worker": "service-worker.js"
    },
    "content_scripts": [{
        "js": ["foreground.js"],
        "matches": ["http://*/*", "https://*/*"]
    }]
}
</code>```

A background js scripts exist however are empty.

If I remove the attempt to pass the script and print directly to the console without trying to wrap it in a button, it works without issue.

I've exhausted my knowledge of what to do to get this working, and the ability to execute off a button is I imagine a fairly common practice, so I'm obviously doing something inherently wrong.

Body:
Like the the 10,000 examples with the exact same heading, I am having a trouble with the development of a chrome extension, specifically the execution of scripts between my popup window and my content script.

The specific error i'm receiving is "Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')".

Now, I have reviewed several dozen threads with the same issue and the common theme seems to be that the placement of the scripting within the HTML code is causing the script to execute prior to the DOM loading, however I have attempted the following to resolve placement being an issue.

I have reviewed my code and I have ensured that the script it executing directly above the  tag (as to be the last item executing within the body section, and that the code also has the 'delay' flag within the script has a redundancy. I have also wrapped the code within the content script in window.onload=function() as a further redundancy, but alas, no love. I have also attempted moving the order of the code around within foreground.js, however as expected that didn't resolve the issue.

foreground.js

function calculatescript() {
    console.log("This prints to the console of the page")
    };

window.onload=function(){
    var runcalculate = document.getElementById("runcalculate");
    runcalculate.addEventListener("click", calculatescript);
    }

popup.html

<!DOCTYPE html>

    <meta charset="UTF-8">
    <link rel="stylesheet" href="popup.css">
    <title>Example Extension</title>

        <button class="button button1" id="runcalculate">Calculate</button>

manifest.js

{

    "manifest_version": 3,
    "name": "Example",
    "description": "An example of a chrome extension using manifest v3",
    "version": "0.0.1",
    "icons": {
        "16": "logo/logo-16.png",
        "48": "logo/logo-48.png",
        "128": "logo/logo-128.png"
    },
    "options_page": "settings/settings.html",
    "action": {
        "default_title": "example",
        "default_popup": "popup/popup.html"
    },
    "permissions": [
        "tabs", "scripting"
    ],
    "host_permissions": [
        "*://*/*"
    ],
    "background": {
        "service_worker": "service-worker.js"
    },
    "content_scripts": [{
        "js": ["foreground.js"],
        "matches": ["http://*/*", "https://*/*"]
    }]
}

A background js scripts exist however are empty.

If I remove the attempt to pass the script and print directly to the console without trying to wrap it in a button, it works without issue.

I've exhausted my knowledge of what to do to get this working, and the ability to execute off a button is I imagine a fairly common practice, so I'm obviously doing something inherently wrong.


问:
Tests doesn't work properly when using @RunWith(PowerMockRunner.class) and @PowerMockRunnerDelegate(Parameterized.class)
When I run mvn test -Dtest=ClassTest it works however when I run just mvn test it fails because classes that should be mocked by PowerMock are null.

Following some details:

jdk 1.7
mvn 3.6.3

```<code><dependency>
   <groupId>org.powermock</groupId>
   <artifactId>powermock-module-junit4</artifactId>
   <version>1.7.4</version>
   <scope>test</scope>
</dependency>
<dependency>
   <groupId>org.powermock</groupId>
   <artifactId>powermock-api-mockito2</artifactId>
   <version>1.7.4</version>
   <scope>test</scope>
</dependency>
</code>```
```<code>Tests in error:
  Test.souldExecute:99 NullPointer
  Test.souldExecute:99 NullPointer
  Test.souldExecute:99 NullPointer
</code>```

Body:
When I run mvn test -Dtest=ClassTest it works however when I run just mvn test it fails because classes that should be mocked by PowerMock are null.

Following some details:

jdk 1.7
mvn 3.6.3

<dependency>
   <groupId>org.powermock</groupId>
   <artifactId>powermock-module-junit4</artifactId>
   <version>1.7.4</version>
   <scope>test</scope>
</dependency>
<dependency>
   <groupId>org.powermock</groupId>
   <artifactId>powermock-api-mockito2</artifactId>
   <version>1.7.4</version>
   <scope>test</scope>
</dependency>

Tests in error:
  Test.souldExecute:99 NullPointer
  Test.souldExecute:99 NullPointer
  Test.souldExecute:99 NullPointer


问:
Retrieving hashed password from sql database
Having issues comparing user password and hashed password using bcrypt.I'll be glad if anyone helps.

Here is my login code snippet

```<code>app.post('/login', (req, res) => {
  const username = req.body.username;
  const password = req.body.password;
  const searchSql2 = 'SELECT * FROM users WHERE user_name = ?'
  con.query(searchSql2,[username], async(err, results,fields) => {
  if (err) throw err;
  const hashedPassword = results[0].user_password
  const isValid = bcrypt.compareSync(password, hashedPassword)
  if (isValid) {
    //password matched
    req.session.loggedin = true;
    req.session.username = username;
    res.redirect('./home')
    res.end();
  } else {
    res.send("Invalid username or password")
  }
  })
})
</code>```

When user logins even with correct details he/she gets 'Invalid username or password!'.How do I go about this?

Body:
Having issues comparing user password and hashed password using bcrypt.I'll be glad if anyone helps.

Here is my login code snippet

app.post('/login', (req, res) => {
  const username = req.body.username;
  const password = req.body.password;
  const searchSql2 = 'SELECT * FROM users WHERE user_name = ?'
  con.query(searchSql2,[username], async(err, results,fields) => {
  if (err) throw err;
  const hashedPassword = results[0].user_password
  const isValid = bcrypt.compareSync(password, hashedPassword)
  if (isValid) {
    //password matched
    req.session.loggedin = true;
    req.session.username = username;
    res.redirect('./home')
    res.end();
  } else {
    res.send("Invalid username or password")
  }
  })
})

When user logins even with correct details he/she gets 'Invalid username or password!'.How do I go about this?


问:
Not synchronized audio and video recorded with python
i bought an USB microphone and a Camera module for the raspberry pi4. I managed to record Audio and Video but when i merge them with ffmpeg the are not synchronized, i'm trying to solve this for 2 days now.

Here my code, when the program starts it record video with the instruction "camera.start_recording("Video.h264")", this instruction return immediatly so when the program executes the instruction after camera.start_recording("Video.h264") the video is still recording.

For recording Audio i use a while loop that stops when i press a button. When i press the button the video recording also stops.

After everything is written i use ffmpeg to merge the video (After converting it to mp4) and the Audio.

```<code># coding=utf-8

from picamera import PiCamera

import pyaudio

import wave

import os

import time

import RPi.GPIO as GPIO

GPIO.setwarnings(False)

GPIO.setmode(GPIO.BOARD)

GPIO.setup(10, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)

print("Ready")

go = True

camera = PiCamera()

camera.resolution = (1920, 1080)

audio = pyaudio.PyAudio()

stream = audio.open(format=pyaudio.paInt16, channels=1, rate=44100, input=True)

frames = []

camera.start_recording("Video.h264")

while go:

    print("Recording")

    if GPIO.input(10) == GPIO.HIGH:

        camera.stop_recording()

        go = False

        print("Recording has been stopped")

data = stream.read(1024, exception_on_overflow = False)
frames.append(data)

stream.stop_stream()

stream.close()

audio.terminate()

sound_file = wave.open("Audio.wav", "wb")

sound_file.setnchannels(1)

sound_file.setsampwidth(audio.get_sample_size(pyaudio.paInt16))

sound_file.setframerate(44100)

sound_file.writeframes(b''.join(frames))

sound_file.close()

print("Converting in mp4")

os.system("ffmpeg -i Video.h264 Video.mp4")

print("Merging audio and video")

os.system("ffmpeg -i Video.mp4 -i Audio.wav -c:v copy -c:a aac vea.mp4")
</code>```

Body:
i bought an USB microphone and a Camera module for the raspberry pi4. I managed to record Audio and Video but when i merge them with ffmpeg the are not synchronized, i'm trying to solve this for 2 days now.

Here my code, when the program starts it record video with the instruction "camera.start_recording("Video.h264")", this instruction return immediatly so when the program executes the instruction after camera.start_recording("Video.h264") the video is still recording.

For recording Audio i use a while loop that stops when i press a button. When i press the button the video recording also stops.

After everything is written i use ffmpeg to merge the video (After converting it to mp4) and the Audio.

# coding=utf-8

from picamera import PiCamera

import pyaudio

import wave

import os

import time

import RPi.GPIO as GPIO

GPIO.setwarnings(False)

GPIO.setmode(GPIO.BOARD)

GPIO.setup(10, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)

print("Ready")

go = True

camera = PiCamera()

camera.resolution = (1920, 1080)

audio = pyaudio.PyAudio()

stream = audio.open(format=pyaudio.paInt16, channels=1, rate=44100, input=True)

frames = []

camera.start_recording("Video.h264")

while go:

    print("Recording")

    if GPIO.input(10) == GPIO.HIGH:

        camera.stop_recording()

        go = False

        print("Recording has been stopped")

data = stream.read(1024, exception_on_overflow = False)
frames.append(data)

stream.stop_stream()

stream.close()

audio.terminate()

sound_file = wave.open("Audio.wav", "wb")

sound_file.setnchannels(1)

sound_file.setsampwidth(audio.get_sample_size(pyaudio.paInt16))

sound_file.setframerate(44100)

sound_file.writeframes(b''.join(frames))

sound_file.close()

print("Converting in mp4")

os.system("ffmpeg -i Video.h264 Video.mp4")

print("Merging audio and video")

os.system("ffmpeg -i Video.mp4 -i Audio.wav -c:v copy -c:a aac vea.mp4")


问:
How to blur a memory stream image in Maui
I load images from database as memory stream and display them in my app, but I need to blur them before I display them.
How can I do that in MAUI android less than android 31 and IOS?
I found some solutions Xamarin but they are not valid for Maui</p>


问:
Is the rss feed data searchable by the Google search system or not?
Is the RSS feed data on my site that I received from other sites searchable by the Google search system or not? I did not define a database, it is only displayed by the PHP code.

I want to know if only using the following code is enough to display the content of the RSS feed and if there is no need for a database, will the content be searched by Google and other search engines with the following code?

```<code><?php
$rss_feed = simplexml_load_file("https://phppot.com/feed/");
if (! empty($rss_feed)) {
    $i = 0;
    foreach ($rss_feed->channel->item as $feed_item) {
        if ($i >= 10)
            break;
        ?>
<div>
    <a class="feed_title" href="<?php echo $feed_item->link; ?>"><?php echo $feed_item->title; ?></a>
</div>
<div><?php echo implode(' ', array_slice(explode(' ', $feed_item->description), 0, 14)) . "..."; ?></div>
<?php
        $i ++;
    }
}
?>
</code>```

Body:
Is the RSS feed data on my site that I received from other sites searchable by the Google search system or not? I did not define a database, it is only displayed by the PHP code.

I want to know if only using the following code is enough to display the content of the RSS feed and if there is no need for a database, will the content be searched by Google and other search engines with the following code?

<?php
$rss_feed = simplexml_load_file("https://phppot.com/feed/");
if (! empty($rss_feed)) {
    $i = 0;
    foreach ($rss_feed->channel->item as $feed_item) {
        if ($i >= 10)
            break;
        ?>

    <a class="feed_title" href="<?php echo $feed_item->link; ?>"><?php echo $feed_item->title; ?>

<?php echo implode(' ', array_slice(explode(' ', $feed_item->description), 0, 14)) . "..."; ?>

<?php
        $i ++;
    }
}
?>


问:
Limiting jquery .each to only images in #main section
I want to set the Title attribute to images inside my #main and filling this title with text "Click for fullscreen". Even if there is no title definied i want to set.
Reason: tooltip needs a title to display.

This code i used in my custom.js file. It's working but sets the title attribute to all images, also in sliders and left or right columns etc.

How can i limit the routine to only the imgaes present in de #main off the webpages?

Used code:

```<code>jQuery(document).ready(function (){
            jQuery("img").each(function(){
                var Titel = jQuery(this).attr('src');
                jQuery(this).attr("title", "Click for fullscreen")
            });
        });
</code>```

Adding #main selector in this way jQuery("#main, img")..... didn't work.

Please advise.

Body:
I want to set the Title attribute to images inside my #main and filling this title with text "Click for fullscreen". Even if there is no title definied i want to set.
Reason: tooltip needs a title to display.

This code i used in my custom.js file. It's working but sets the title attribute to all images, also in sliders and left or right columns etc.

How can i limit the routine to only the imgaes present in de #main off the webpages?

Used code:

jQuery(document).ready(function (){
            jQuery("img").each(function(){
                var Titel = jQuery(this).attr('src');
                jQuery(this).attr("title", "Click for fullscreen")
            });
        });

Adding #main selector in this way jQuery("#main, img")..... didn't work.

Please advise.


问:
AWS DMS Mongodb to S3 Getting in Loop Error
I have an AWS migration task that extracts data from mongodb and send to s3 in csv file.
After running the tasks for some days, I noticed that DMS was running without errors in the interface but the data was not being updated anymore.

Taking a look in the logs I noticed that it's in a loop with the following error:

```<code>2022-12-09T13:07:28 [SOURCE_CAPTURE  ]I: Connection string: 'mongodb://user:****@host:27017/?retryWrites=false&authSource=admin&ssl=true' (mongodb_imp.c:398)

2022-12-09T09:46:58.000-03:00

2022-12-09T12:46:58 [SOURCE_CAPTURE  ]I:  MongoDB version: 4.2.23  (mongodb_imp.c:200)
2022-12-09T12:46:58 [SOURCE_CAPTURE ]I: MongoDB version: 4.2.23 (mongodb_imp.c:200)

2022-12-09T09:46:58.000-03:00

2022-12-09T12:46:58 [TARGET_APPLY    ]I:  Target components st_0_PHZ527O26SQUKBXSWUIR4AOPAAAO4TPUIBEEMUQ was reattached after 6 seconds.  (subtask.c:1393)
2022-12-09T12:46:58 [TARGET_APPLY ]I: Target components st_0_PHZ527O26SQUKBXSWUIR4AOPAAAO4TPUIBEEMUQ was reattached after 6 seconds. (subtask.c:1393)

2022-12-09T09:46:58.000-03:00

2022-12-09T12:46:58 [TASK_MANAGER    ]I:  Starting component st_0_PHZ527O26SQUKBXSWUIR4AOPAAAO4TPUIBEEMUQ  (subtask.c:1399)
2022-12-09T12:46:58 [TASK_MANAGER ]I: Starting component st_0_PHZ527O26SQUKBXSWUIR4AOPAAAO4TPUIBEEMUQ (subtask.c:1399)

2022-12-09T09:46:58.000-03:00

2022-12-09T12:46:58 [TARGET_APPLY    ]I:  Failed to open repository of URVPYB3AR42L2WPI3ARERUDPO1W43LQASV3PBXI task. [1000153]  (file_imp.c:4916)
2022-12-09T12:46:58 [TARGET_APPLY ]I: Failed to open repository of URVPYB3AR42L2WPI3ARERUDPO1W43LQASV3PBXI task. [1000153] (file_imp.c:4916)

2022-12-09T09:46:58.000-03:00

2022-12-09T12:46:58 [TARGET_APPLY    ]I:  Failed to get task repository of the URVPYB3AR42L2WPI3ARERUDPO1W43LQASV3PBXI task. [1000153]  (file_utils.c:217)
2022-12-09T12:46:58 [TARGET_APPLY ]I: Failed to get task repository of the URVPYB3AR42L2WPI3ARERUDPO1W43LQASV3PBXI task. [1000153] (file_utils.c:217)

2022-12-09T09:46:58.000-03:00   2022-12-09T12:46:58 [TARGET_APPLY ]I: Could not get table definition for table: my_table_name. [1000100] (file_apply.c:527)

2022-12-09T09:46:58.000-03:00

2022-12-09T12:46:58 [TARGET_APPLY    ]I:  Failed to create file writers for on directory: /rdsdbdata/data/tasks/URVPYB3AR42L2WPI3ARERUDPO1W43LQASV3PBXI/bucketFolder [1000100]  (file_apply.c:569)
2022-12-09T12:46:58 [TARGET_APPLY ]I: Failed to create file writers for on directory: /rdsdbdata/data/tasks/URVPYB3AR42L2WPI3ARERUDPO1W43LQASV3PBXI/bucketFolder [1000100] (file_apply.c:569)

2022-12-09T09:46:58.000-03:00

2022-12-09T12:46:58 [TARGET_APPLY    ]I:  Could not init data file writers. [1000100]  (file_apply.c:608)
2022-12-09T12:46:58 [TARGET_APPLY ]I: Could not init data file writers. [1000100] (file_apply.c:608)

2022-12-09T09:46:58.000-03:00

2022-12-09T12:46:58 [TARGET_APPLY    ]I:  Error executing command [1000100]  (streamcomponent.c:1980)
2022-12-09T12:46:58 [TARGET_APPLY ]I: Error executing command [1000100] (streamcomponent.c:1980)

2022-12-09T09:46:58.000-03:00

2022-12-09T12:46:58 [TASK_MANAGER    ]I:  Stream component failed at subtask 0, component st_0_PHZ527O26SQUKBXSWUIR4AOPAAAO4TPUIBEEMUQ [1000100]  (subtask.c:1414)
2022-12-09T12:46:58 [TASK_MANAGER ]I: Stream component failed at subtask 0, component st_0_PHZ527O26SQUKBXSWUIR4AOPAAAO4TPUIBEEMUQ [1000100] (subtask.c:1414)

2022-12-09T09:46:58.000-03:00

2022-12-09T12:46:58 [TARGET_APPLY    ]I:  Target component st_0_PHZ527O26SQUKBXSWUIR4AOPAAAO4TPUIBEEMUQ was detached because of recoverable error. Will try to reattach  (subtask.c:1537)
2022-12-09T12:46:58 [TARGET_APPLY ]I: Target component st_0_PHZ527O26SQUKBXSWUIR4AOPAAAO4TPUIBEEMUQ was detached because of recoverable error. Will try to reattach (subtask.c:1537)

2022-12-09T09:46:58.000-03:00   2022-12-09T12:46:58 [SOURCE_CAPTURE ]I: Destroying mongoc client: '2103315958236' (mongodb_imp.c:1161)
</code>```

I haven't found nothing about this error yet. If someone have any ideia, that would help.
Thanks

Body:
I have an AWS migration task that extracts data from mongodb and send to s3 in csv file.
After running the tasks for some days, I noticed that DMS was running without errors in the interface but the data was not being updated anymore.

Taking a look in the logs I noticed that it's in a loop with the following error:

2022-12-09T13:07:28 [SOURCE_CAPTURE  ]I: Connection string: 'mongodb://user:****@host:27017/?retryWrites=false&authSource=admin&ssl=true' (mongodb_imp.c:398)

2022-12-09T09:46:58.000-03:00

2022-12-09T12:46:58 [SOURCE_CAPTURE  ]I:  MongoDB version: 4.2.23  (mongodb_imp.c:200)
2022-12-09T12:46:58 [SOURCE_CAPTURE ]I: MongoDB version: 4.2.23 (mongodb_imp.c:200)

2022-12-09T09:46:58.000-03:00

2022-12-09T12:46:58 [TARGET_APPLY    ]I:  Target components st_0_PHZ527O26SQUKBXSWUIR4AOPAAAO4TPUIBEEMUQ was reattached after 6 seconds.  (subtask.c:1393)
2022-12-09T12:46:58 [TARGET_APPLY ]I: Target components st_0_PHZ527O26SQUKBXSWUIR4AOPAAAO4TPUIBEEMUQ was reattached after 6 seconds. (subtask.c:1393)

2022-12-09T09:46:58.000-03:00

2022-12-09T12:46:58 [TASK_MANAGER    ]I:  Starting component st_0_PHZ527O26SQUKBXSWUIR4AOPAAAO4TPUIBEEMUQ  (subtask.c:1399)
2022-12-09T12:46:58 [TASK_MANAGER ]I: Starting component st_0_PHZ527O26SQUKBXSWUIR4AOPAAAO4TPUIBEEMUQ (subtask.c:1399)

2022-12-09T09:46:58.000-03:00

2022-12-09T12:46:58 [TARGET_APPLY    ]I:  Failed to open repository of URVPYB3AR42L2WPI3ARERUDPO1W43LQASV3PBXI task. [1000153]  (file_imp.c:4916)
2022-12-09T12:46:58 [TARGET_APPLY ]I: Failed to open repository of URVPYB3AR42L2WPI3ARERUDPO1W43LQASV3PBXI task. [1000153] (file_imp.c:4916)

2022-12-09T09:46:58.000-03:00

2022-12-09T12:46:58 [TARGET_APPLY    ]I:  Failed to get task repository of the URVPYB3AR42L2WPI3ARERUDPO1W43LQASV3PBXI task. [1000153]  (file_utils.c:217)
2022-12-09T12:46:58 [TARGET_APPLY ]I: Failed to get task repository of the URVPYB3AR42L2WPI3ARERUDPO1W43LQASV3PBXI task. [1000153] (file_utils.c:217)

2022-12-09T09:46:58.000-03:00   2022-12-09T12:46:58 [TARGET_APPLY ]I: Could not get table definition for table: my_table_name. [1000100] (file_apply.c:527)

2022-12-09T09:46:58.000-03:00

2022-12-09T12:46:58 [TARGET_APPLY    ]I:  Failed to create file writers for on directory: /rdsdbdata/data/tasks/URVPYB3AR42L2WPI3ARERUDPO1W43LQASV3PBXI/bucketFolder [1000100]  (file_apply.c:569)
2022-12-09T12:46:58 [TARGET_APPLY ]I: Failed to create file writers for on directory: /rdsdbdata/data/tasks/URVPYB3AR42L2WPI3ARERUDPO1W43LQASV3PBXI/bucketFolder [1000100] (file_apply.c:569)

2022-12-09T09:46:58.000-03:00

2022-12-09T12:46:58 [TARGET_APPLY    ]I:  Could not init data file writers. [1000100]  (file_apply.c:608)
2022-12-09T12:46:58 [TARGET_APPLY ]I: Could not init data file writers. [1000100] (file_apply.c:608)

2022-12-09T09:46:58.000-03:00

2022-12-09T12:46:58 [TARGET_APPLY    ]I:  Error executing command [1000100]  (streamcomponent.c:1980)
2022-12-09T12:46:58 [TARGET_APPLY ]I: Error executing command [1000100] (streamcomponent.c:1980)

2022-12-09T09:46:58.000-03:00

2022-12-09T12:46:58 [TASK_MANAGER    ]I:  Stream component failed at subtask 0, component st_0_PHZ527O26SQUKBXSWUIR4AOPAAAO4TPUIBEEMUQ [1000100]  (subtask.c:1414)
2022-12-09T12:46:58 [TASK_MANAGER ]I: Stream component failed at subtask 0, component st_0_PHZ527O26SQUKBXSWUIR4AOPAAAO4TPUIBEEMUQ [1000100] (subtask.c:1414)

2022-12-09T09:46:58.000-03:00

2022-12-09T12:46:58 [TARGET_APPLY    ]I:  Target component st_0_PHZ527O26SQUKBXSWUIR4AOPAAAO4TPUIBEEMUQ was detached because of recoverable error. Will try to reattach  (subtask.c:1537)
2022-12-09T12:46:58 [TARGET_APPLY ]I: Target component st_0_PHZ527O26SQUKBXSWUIR4AOPAAAO4TPUIBEEMUQ was detached because of recoverable error. Will try to reattach (subtask.c:1537)

2022-12-09T09:46:58.000-03:00   2022-12-09T12:46:58 [SOURCE_CAPTURE ]I: Destroying mongoc client: '2103315958236' (mongodb_imp.c:1161)

I haven't found nothing about this error yet. If someone have any ideia, that would help.
Thanks


问:
LLDB or GDB: break if any child/fork hits a breakpoint
I'm trying to figure out the following issue with podman in rootless mode:

$ podman run -it --rm docker.io/archlinux
Error: failed to mount overlay for metacopy check with "" options: permission denied
```
<p>When I <code>strace -f</code> this I get the following:</p>
<pre class="lang-bash prettyprint-override"><code>$ strace -f podman run -it --rm docker.io/archlinux 2>&1 | grep EACCES
[pid 290534] mount("overlay", "/home/user/.local/share/containers/storage/overlay/metacopy-check3697694896/merged", "overlay", 0, "lowerdir=/home/user/.local/s"...) = -1 EACCES (Permission denied)
[pid 290534] openat(10, "work", O_RDONLY|O_CLOEXEC) = -1 EACCES (Permission denied)
</code>```

I want to look at the permissions of the metacopy directory, but podman immediately deletes it, so I cannot look at it after podman has finished running.

I tried break mount in gdb, but it detaches from the child, so the breakpoint is not hit.
I also cannot just follow-forks as podman creates many children, and I cannot manually sort through them.

How can I tell gdb or lldb to attach to all processes and switch to the correct process when the breakpoint is hit?

Body:
I'm trying to figure out the following issue with podman in rootless mode:

$ podman run -it --rm docker.io/archlinux
Error: failed to mount overlay for metacopy check with "" options: permission denied

When I strace -f this I get the following:

$ strace -f podman run -it --rm docker.io/archlinux 2>&1 | grep EACCES
[pid 290534] mount("overlay", "/home/user/.local/share/containers/storage/overlay/metacopy-check3697694896/merged", "overlay", 0, "lowerdir=/home/user/.local/s"...) = -1 EACCES (Permission denied)
[pid 290534] openat(10, "work", O_RDONLY|O_CLOEXEC) = -1 EACCES (Permission denied)

I want to look at the permissions of the metacopy directory, but podman immediately deletes it, so I cannot look at it after podman has finished running.

I tried break mount in gdb, but it detaches from the child, so the breakpoint is not hit.
I also cannot just follow-forks as podman creates many children, and I cannot manually sort through them.

How can I tell gdb or lldb to attach to all processes and switch to the correct process when the breakpoint is hit?


问:
create a bar chart with chartjs 3.9.1
How do you create this structure from code at runtime?</p>
```<code>datasets: [{
 label: "Apples",
 backgroundColor: "#AF7",
 data: [Math.random() * 100],
},{
     label: "Oranges",
     backgroundColor: "#FA4",
     data: [Math.random() * 100],
  },{
     label: "Mangos",
     backgroundColor: "#FF7",
     data: [Math.random() * 100],
  },{
     label: "Avocados",
     backgroundColor: "#2A7",
     data: [Math.random() * 100],
  }]
</code>```

Title: create a bar chart with chartjs 3.9.1

Body:
How do you create this structure from code at runtime?

datasets: [{
 label: "Apples",
 backgroundColor: "#AF7",
 data: [Math.random() * 100],
},{
     label: "Oranges",
     backgroundColor: "#FA4",
     data: [Math.random() * 100],
  },{
     label: "Mangos",
     backgroundColor: "#FF7",
     data: [Math.random() * 100],
  },{
     label: "Avocados",
     backgroundColor: "#2A7",
     data: [Math.random() * 100],
  }]


问:
Inp(Abaqus) mesh file conversion into .msh file via meshio
I'm using meshio to convert an .inp mesh file into compatible form for Gmsh (.msh file type).Αlthough the conversion (meshio convert input.inp output.msh) generates a .msh file, Gmsh can't read it because it appears unusual characters. Please check the attached .pnj. Does anyone have an idea or even better a solution to fix it?
thanks in advance

output.msh file

I tried to convert the .msh output file into ascii but it did not workded


问:
How to solve 'unhashable type error: 'Series' when adding new variable to dataframe that measures readability of FOMC statements
I am looking to calculate the Flesch-Kincaid grade level score of FOMC Statements. When trying to add a new variable for the Flesch-Kincaid score to the dataframe which includes FOMC Statements, I am getting an error which says: "unhashable type error: Series". How can I generate the new variable for the Flesch-Kincaid Score?

I first downloaded the FOMC statements using Fedtools:

```<code>from FedTools import MonetaryPolicyCommittee
fomc_statements = MonetaryPolicyCommittee().find_statements()
</code>```

I used the following code to try to calculate the Flesch Kincaid score of the fomc statements, stored in a variable called 'FOMC_Statements'.

```<code>import textstat
fomc_statements2 = fomc_statements.assign(readability = textstat.flesch_kincaid_grade(fomc_statements.FOMC_Statements))
</code>```

This was causing the unhashable type error: Series

Body:
I am looking to calculate the Flesch-Kincaid grade level score of FOMC Statements. When trying to add a new variable for the Flesch-Kincaid score to the dataframe which includes FOMC Statements, I am getting an error which says: "unhashable type error: Series". How can I generate the new variable for the Flesch-Kincaid Score?

I first downloaded the FOMC statements using Fedtools:

from FedTools import MonetaryPolicyCommittee
fomc_statements = MonetaryPolicyCommittee().find_statements()

I used the following code to try to calculate the Flesch Kincaid score of the fomc statements, stored in a variable called 'FOMC_Statements'.

import textstat
fomc_statements2 = fomc_statements.assign(readability = textstat.flesch_kincaid_grade(fomc_statements.FOMC_Statements))

This was causing the unhashable type error: Series


问:
How to pass the closest common ancestor to superclass type parameter in Java
Let's say I have class TupleN<T...> which I want to derive from some type Tuple<T> like so:

// with Tuple1 that seems okay
class Tuple1<T> implements Tuple<T> { ... }

// but what should I put instead of ***?
class Tuple2<T1, T2> implements Tuple<***> { ... }
```
<p>What I want is a some sort of behaviour that allows me to define methods that accept not any raw typed <code>Tuple</code>, but a <code>Tuple<T></code> with some upper bound type restriction (e.g. for heterogeneous container implementation):</p>
<pre class="lang-java prettyprint-override"><code>void accept(Tuple<Number> tupleOfNumbers) { ... }

...

Tuple<Integer, Float, Double> t = new Tuple3(123, 12.5f, 43.99d);
Tuple<Integer, Float, String> t2 = new Tuple3(123, 12.5f, "43.99");

// ... some Tuple logic here

accept(t); // Okay!
accept(t2); // not okay, common ancestor is not a Number!
</code>```

I know that conversion from TupleN to some homogeneous Tuple<T> is possible through static generic methods:

class Tuple<T> { ... }

record Tuple2<T1, T2>(T1 val1, T2 val2) {

  // ...

 static <T, T1 extends T, T2 extends T> Tuple<T> toTuple(Tuple2<T1, T2> t) {
   return new Tuple<T>(t.val1, t.val2);
 }
}

// ... somewhere else
var t = Tuple2(123, 123f);
Tuple<Number> l = Tuple2.toTuple(t); // types T, T1 and T2 are inferred properly and that works!
```
<p>That works, but seems completely pointless as I simply can replace <code>Tuple<T></code> with <code>List.of()</code>.</p>
<p>So I can't figure out the non-static way of doing this other than adding an explicit third common ancestor type parameter:</p>
<pre class="lang-java prettyprint-override"><code>record Tuple2<T, T1 extends T, T2 extends T>(T1 val1, T2 val2) implements Tuple<T> {}
</code>```

Maybe I'm missing some good approach? Please tell me if you have had the same issue.

Body:
Let's say I have class TupleN<T...> which I want to derive from some type Tuple<T> like so:

// with Tuple1 that seems okay
class Tuple1<T> implements Tuple<T> { ... }

// but what should I put instead of ***?
class Tuple2<T1, T2> implements Tuple<***> { ... }

What I want is a some sort of behaviour that allows me to define methods that accept not any raw typed Tuple, but a Tuple<T> with some upper bound type restriction (e.g. for heterogeneous container implementation):

void accept(Tuple<Number> tupleOfNumbers) { ... }

...

Tuple<Integer, Float, Double> t = new Tuple3(123, 12.5f, 43.99d);
Tuple<Integer, Float, String> t2 = new Tuple3(123, 12.5f, "43.99");

// ... some Tuple logic here

accept(t); // Okay!
accept(t2); // not okay, common ancestor is not a Number!

I know that conversion from TupleN to some homogeneous Tuple<T> is possible through static generic methods:

class Tuple<T> { ... }

record Tuple2<T1, T2>(T1 val1, T2 val2) {

  // ...

 static <T, T1 extends T, T2 extends T> Tuple<T> toTuple(Tuple2<T1, T2> t) {
   return new Tuple<T>(t.val1, t.val2);
 }
}

// ... somewhere else
var t = Tuple2(123, 123f);
Tuple<Number> l = Tuple2.toTuple(t); // types T, T1 and T2 are inferred properly and that works!

That works, but seems completely pointless as I simply can replace Tuple<T> with List.of().

So I can't figure out the non-static way of doing this other than adding an explicit third common ancestor type parameter:

record Tuple2<T, T1 extends T, T2 extends T>(T1 val1, T2 val2) implements Tuple<T> {}

Maybe I'm missing some good approach? Please tell me if you have had the same issue.


问:
CORS Preflight Request succeeded but the request fails
I have a frontend which is sending a POST request to an endpoint using XMLHttpRequest. It has some data and xml file sent in form data. My backend has a spring cloud gateway which has CORS enabled.

```<code>spring:
  cloud:
    gateway:
      globalcors:
        corsConfigurations:
          '[/**]':
            allowedOrigins: "https://myFrontEndSite.com"
            allowedMethods: "*"
            allowedHeaders: "*"
            allowCredentials: true
</code>```

the weird problem one of my user is facing is that when sending a specific file in the post request, they get a CORS error in console and 403 error when checking the call in the network tab of inspector. i can't seem to see if it is a red herring. I am able to import the file which the user cannot to that endpoint. the user is able to import other files to that endpoint.

I have checked the network tab in the inspector. the preflight succeeds but the actual request fails with 403 error. i opened the request but it's response says nothing to preview

Body:
I have a frontend which is sending a POST request to an endpoint using XMLHttpRequest. It has some data and xml file sent in form data. My backend has a spring cloud gateway which has CORS enabled.

spring:
  cloud:
    gateway:
      globalcors:
        corsConfigurations:
          '[/**]':
            allowedOrigins: "https://myFrontEndSite.com"
            allowedMethods: "*"
            allowedHeaders: "*"
            allowCredentials: true

the weird problem one of my user is facing is that when sending a specific file in the post request, they get a CORS error in console and 403 error when checking the call in the network tab of inspector. i can't seem to see if it is a red herring. I am able to import the file which the user cannot to that endpoint. the user is able to import other files to that endpoint.

I have checked the network tab in the inspector. the preflight succeeds but the actual request fails with 403 error. i opened the request but it's response says nothing to preview


问:
kong api gateway is not working in GKE cluster
kong api gateway is not working in GKE cluster with kong proxy and self signed certificate

I am following below doc to create kong api gateway with self signed certificate but its not working,
https://docs.konghq.com/kubernetes-ingress-controller/2.7.x/guides/using-gateway-api/

getting unknow gatewayclass and there is no IP address generated for gateway,

Is kong api gateway with self signed certificate support in GKE Cluster,


问:
Problem with htaccess when making friendly urls with the trailing slash does not work
I have configured the htaccess file on my website to remove the .php extension, it works correctly, when I run for example domain.com/about it runs perfectly but when I run domain.com/about/ the file is executed but it is interpreted as being inside the directory and therefore does not find the CSS, etc...

This is code, is there a way to always put / at the end, even when you call domain.com/about, or vice versa that if you put the slash

```<code> at the end, remove it.

# Remove .php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]
</code>```

Thanks.

I haven't tried anything, because I don't know the solution.

Body:
I have configured the htaccess file on my website to remove the .php extension, it works correctly, when I run for example domain.com/about it runs perfectly but when I run domain.com/about/ the file is executed but it is interpreted as being inside the directory and therefore does not find the CSS, etc...

This is code, is there a way to always put / at the end, even when you call domain.com/about, or vice versa that if you put the slash

 at the end, remove it.

# Remove .php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]

Thanks.

I haven't tried anything, because I don't know the solution.


问:
R: Subset dataset with multiple values based on a variable
I have searched for the solution but probably I did not know how to search with the correct terms, please let me know if the question is duplicated.

I made a minimal sample of my question.

I have a dataset like this:

```<code>fakedata <- data.frame(
  participant = rep(1:10,4),
  stimulus = rep(c('A','B'), each = 10, 2),
  value1 = rep(c(runif(10,0,1),runif(10,0,1)),2),
  value2 = rep(c(runif(10,0,1),runif(10,0,1)),2)
)

</code>```

A stimulus for the same participant always have same value1 and value2 I wanted to subset the dataset so that for every participant stimulus A and stimulus B only occur once (assume runif produces the same value as above):

```<code>fakedata <- data.frame(
  participant = rep(1:10,2),
  stimulus = rep(c('A','B'), each = 10),
  value1 = c(runif(10,0,1),runif(10,0,1)),
  value2 = c(runif(10,0,1),runif(10,0,1))
)
</code>```

Thank you very much for answering this question.

Body:
I have searched for the solution but probably I did not know how to search with the correct terms, please let me know if the question is duplicated.

I made a minimal sample of my question.

I have a dataset like this:

fakedata <- data.frame(
  participant = rep(1:10,4),
  stimulus = rep(c('A','B'), each = 10, 2),
  value1 = rep(c(runif(10,0,1),runif(10,0,1)),2),
  value2 = rep(c(runif(10,0,1),runif(10,0,1)),2)
)

A stimulus for the same participant always have same value1 and value2 I wanted to subset the dataset so that for every participant stimulus A and stimulus B only occur once (assume runif produces the same value as above):

fakedata <- data.frame(
  participant = rep(1:10,2),
  stimulus = rep(c('A','B'), each = 10),
  value1 = c(runif(10,0,1),runif(10,0,1)),
  value2 = c(runif(10,0,1),runif(10,0,1))
)

Thank you very much for answering this question.


问:
How to fetch marketplace insights using api for facebook?
I want to get insights from the Facebook marketplace via their API. I can see that there is a way to do it manually where a user can view the insights of individual listings or of all of listings at once.
Refer docs: https://www.facebook.com/help/265775098821464/?helpref=uf_share

To solve this, I referred to the insights api but these are used to access the marketing data.
Docs : https://developers.facebook.com/docs/marketing-api/insights/

Is there a way to do this via their api?


问:
Create a React app for offline development
I am trying to create a React app that I can use for offline development, without using create-react-app

I started by installing Node.js then in VScode terminal
npm install live-server react react-dom

My index.html is

```<code><html lang="en">
<head>
</head>
<body>
    <div id="root"></div>
    <script src="index.js" type="text/babel"></script>
</body>
</html>
</code>```

index.js is

```<code>import React from "react"
import ReactDOM from "react-dom"

const navbar = (
    <h1>Test</h1>
)

ReactDOM.render(navbar, document.getElementById("root"))
</code>```

I am not getting any output when running live-server

What am I missing?

Do I need to add these web elements to html header?

```<code><script crossorigin src="https://unpkg.com/react@17/udm/react.development.js"></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
</code>```

Body:
I am trying to create a React app that I can use for offline development, without using create-react-app

I started by installing Node.js then in VScode terminal
npm install live-server react react-dom

My index.html is

index.js is

import React from "react"
import ReactDOM from "react-dom"

const navbar = (

Test

)

ReactDOM.render(navbar, document.getElementById("root"))

I am not getting any output when running live-server

What am I missing?

Do I need to add these web elements to html header?


问:
Python changing text file
I am using a text file as a way to save several inputs from an app build in Kivy. I want to display these inputs later on as a summary in a textinput-widget with the inputs as the starting text.

The widget is created in the .kv file and uses text: root.text

def read():
    with open(f"./drafts/draft.txt", "r") as file: #Does not read out current order but old order file
        text = file.read()
        return text
text = read()

```

I can not seem to get the current state of the file displayed. It always just shows the version of the text file when the program starts, even through the file gets modified.

Is it possible to update the text variable, and/or display the current state of the text file in the text widget.

Title: Python changing text file

Body:
I am using a text file as a way to save several inputs from an app build in Kivy. I want to display these inputs later on as a summary in a textinput-widget with the inputs as the starting text.

The widget is created in the .kv file and uses text: root.text

def read():
    with open(f"./drafts/draft.txt", "r") as file: #Does not read out current order but old order file
        text = file.read()
        return text
text = read()

I can not seem to get the current state of the file displayed. It always just shows the version of the text file when the program starts, even through the file gets modified.

Is it possible to update the text variable, and/or display the current state of the text file in the text widget.


问:
SyntaxError: The requested module 'sourcemap-codec' is expected to be of type CommonJS when I'm trying to compile my angular project
```<code>SyntaxError: The requested module 'sourcemap-codec' is expected to be of type CommonJS, which does not support named exports. CommonJS modules can be imported by importing the default export.
<e> For example:
<e> import pkg from 'sourcemap-codec';
<e> const { decode, encode } = pkg;
<e>     at ModuleJob._instantiate (internal/modules/esm/module_job.js:98:21)
<e>     at async ModuleJob.run (internal/modules/esm/module_job.js:137:5)
<e>     at async Loader.import (internal/modules/esm/loader.js:165:24)
</code>```

I tried downgrading angular cli nothing worked

Body:
SyntaxError: The requested module 'sourcemap-codec' is expected to be of type CommonJS, which does not support named exports. CommonJS modules can be imported by importing the default export.
<e> For example:
<e> import pkg from 'sourcemap-codec';
<e> const { decode, encode } = pkg;
<e>     at ModuleJob._instantiate (internal/modules/esm/module_job.js:98:21)
<e>     at async ModuleJob.run (internal/modules/esm/module_job.js:137:5)
<e>     at async Loader.import (internal/modules/esm/loader.js:165:24)

I tried downgrading angular cli nothing worked


问:
NextJS API get response
I'm trying to fetch a message from /api pages on NextJS, how do I get the sent response from API to front end?

Example API:

export default function handler(req, res) {
  res.status(200).json({ name: 'John Doe' })
}
```
<p>My API call on front end:</p>
<pre class="lang-js prettyprint-override"><code>    useEffect(() => {

        fetch("/api/hello",{method: "GET"}).then((response) => {
            console.log(response)
        })

    }, [])
</code>```

Response I'm getting:

Why is the name 'John Doe' not appearing here?

When I was on create-react-app, I fetch APIs with axios and console logging response.data gives all the data sent from res.send from backend, but here on NextJS, it doesn't appear on API response

Title: NextJS API get response

Body:
I'm trying to fetch a message from /api pages on NextJS, how do I get the sent response from API to front end?

Example API:

export default function handler(req, res) {
  res.status(200).json({ name: 'John Doe' })
}

My API call on front end:

    useEffect(() => {

        fetch("/api/hello",{method: "GET"}).then((response) => {
            console.log(response)
        })

    }, [])

Response I'm getting:

Why is the name 'John Doe' not appearing here?

When I was on create-react-app, I fetch APIs with axios and console logging response.data gives all the data sent from res.send from backend, but here on NextJS, it doesn't appear on API response