问:
Spring security
Following the release of Spring security version 2.0.8 to 3.2.7.release, I have encountered the following problem.

I modified the Java classes for the adaptation of the code suite upgrade, the pom.xml for the escalation to 3.2.7.release, and context-security.xml. This is the error I encounter:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.filterChains': Cannot resolve reference to bean 'org.springframework.security.web.DefaultSecurityFilterChain#0' while setting bean property 'sourceList' with key [0]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.web.DefaultSecurityFilterChain#0': Cannot resolve reference to bean 'org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter#0' while setting constructor argument with key [3]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter#0': Cannot resolve reference to bean 'org.springframework.security.authentication.ProviderManager#0' while setting bean property 'authenticationManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.authentication.ProviderManager#0': Could not resolve matching constructor (hint: specify index/type/name arguments for simple parameters to avoid type ambiguities)

My pom.xml updated for 3.2.7.RELEASE:

<spring-security.version>3.2.7.RELEASE</spring-security.version>

<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-ldap</artifactId>
    <version>${spring.version}</version>
</dependency>

<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-config</artifactId>
    <version>${spring.version}</version>
</dependency>

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-beans</artifactId>
    <version>${spring.version}</version>
</dependency>

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>${spring.version}</version>
</dependency>

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-core</artifactId>
    <version>${spring.version}</version>
</dependency>

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-expression</artifactId>
    <version>${spring.version}</version>
</dependency>

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>${spring.version}</version>
</dependency>

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jms</artifactId>
    <version>${spring.version}</version>
</dependency>

<dependency>
    <groupId>org.springframework.ldap</groupId>
    <artifactId>spring-ldap-core</artifactId>
    <version>1.3.1.RELEASE</version>
</dependency>

<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-core</artifactId>
    <version>${spring-security.version}</version>
</dependency>

<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-taglibs</artifactId>
    <version>${spring-security.version}</version>
</dependency>

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-tx</artifactId>
    <version>${spring.version}</version>
</dependency>

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>${spring.version}</version>
</dependency>
```
<p>My fil applicationContextSecurity.xml</p>
<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="ISO-8859-1"?>
<beans:beans
xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
                    http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
                    http://www.springframework.org/schema/security
                    http://www.springframework.org/schema/security/spring-security-3.2.xsd">

    <global-method-security secured-annotations="enabled" jsr250-annotations="enabled"/>

    <authentication-manager id="multipleLdapProvider">
        <!--<authentication-provider ref="multipleLdapProvider" />-->
    </authentication-manager>

    <http pattern="/referentiel/**"   auto-config="true" use-expressions="true" authentication-manager-ref="multipleLdapProvider">
        <intercept-url pattern='/**'   access="ROLE_ADMIN, ROLE_SERMI, ROLE_CPRMI, ROLE_CDOM" />

        <http-basic />
    </http>
    <http pattern="/bareme/**" auto-config="true" use-expressions="true" authentication-manager-ref="multipleLdapProvider"   >
        <intercept-url pattern='/**' access="ROLE_ADMIN, ROLE_SERMI, ROLE_CPRMI" />
        <http-basic />
    </http>
    <http pattern="/comparaisonHosp/**"   auto-config="true" use-expressions="true"  authentication-manager-ref="multipleLdapProvider">
        <intercept-url pattern='/**' access="ROLE_ADMIN, ROLE_SERMI, ROLE_CPRMI, ROLE_CDOM, ROLE_ELUCN" />
        <http-basic />
    </http>
    <http pattern="/requete/**"  auto-config="true" use-expressions="true" authentication-manager-ref="multipleLdapProvider"  >
        <intercept-url pattern='/**' access="ROLE_ADMIN, ROLE_SERMI, ROLE_CPRMI, ROLE_CDOM" />
        <http-basic />
    </http>
    <http pattern="/refManif/**" auto-config="true" use-expressions="true" authentication-manager-ref="multipleLdapProvider"   >
        <intercept-url pattern='/**' access="ROLE_ADMIN, ROLE_SERMI, ROLE_CPRMI" />
        <http-basic />
    </http>
    <http pattern="/contrat/**" auto-config="true" use-expressions="true" authentication-manager-ref="multipleLdapProvider"  >
        <intercept-url pattern='/**' access="ROLE_ADMIN, ROLE_SERMI, ROLE_CPRMI, ROLE_CDOM, ROLE_ELUCN" />
        <http-basic />
    </http>
    <http pattern="/utilisateur/**"  auto-config="true" use-expressions="true" authentication-manager-ref="multipleLdapProvider"  >
        <intercept-url pattern='/**' access="ROLE_ADMIN, ROLE_SERMI, ROLE_CPRMI, ROLE_INADM" />
        <http-basic />
    </http>
    <http auto-config="true" use-expressions="true" authentication-manager-ref="multipleLdapProvider">
        <intercept-url pattern='/**' access="hasRole('USER')" />
        <form-login login-page='/login.action' default-target-url="/home.action" always-use-default-target='true'/>
        <logout />
    </http>

    <beans:bean id="contextSource"
        class="org.springframework.security.ldap.DefaultSpringSecurityContextSource">

      <beans:constructor-arg type="java.lang.String"><beans:value>${ldap.interne.url}</beans:value></beans:constructor-arg>
      <beans:property name="userDn">
        <beans:value>${ldap.interne.userDn}</beans:value>
      </beans:property>
      <beans:property name="password">
        <beans:value>${ldap.interne.password}</beans:value>
      </beans:property>
      <beans:property name="baseEnvironmentProperties">
            <beans:map>
                <beans:entry key="java.naming.referral" value="follow" />
            </beans:map>
      </beans:property>
    </beans:bean>

    <beans:bean id="contextSourceIndus"
        class="org.springframework.security.ldap.DefaultSpringSecurityContextSource">
      <beans:constructor-arg type="java.lang.String"><beans:value>${ldap.externe.url}</beans:value></beans:constructor-arg>
      <beans:property name="userDn">
        <beans:value>${ldap.externe.userDn}</beans:value>
      </beans:property>
      <beans:property name="password">
        <beans:value>${ldap.externe.password}</beans:value>
      </beans:property>
      <beans:property name="baseEnvironmentProperties">
            <beans:map>
                <beans:entry key="java.naming.referral" value="follow" />
            </beans:map>
      </beans:property>
    </beans:bean>

    <beans:bean id="multipleLdapProvider" class="com.cnom.idahe.utils.spring.MutlipleLdapAuthenticationProvider">
        <beans:constructor-arg>
            <beans:set>
                <beans:bean class="org.springframework.security.ldap.authentication.BindAuthenticator">
                    <beans:constructor-arg ref="contextSource"/>
                    <beans:property name="userSearch" ref="userSearchInterne"/>
                </beans:bean>

                <beans:bean class="org.springframework.security.ldap.authentication.BindAuthenticator">
                    <beans:constructor-arg ref="contextSourceIndus"/>
                    <beans:property name="userSearch" ref="userSearchExterne"/>
                </beans:bean>

            </beans:set>
        </beans:constructor-arg>
        <beans:constructor-arg>
            <beans:bean class="com.cnom.idahe.utils.spring.CnomDBPopulator">
            </beans:bean>
        </beans:constructor-arg>

        <!--<custom-authentication-provider />-->
    </beans:bean>

    <beans:bean id="userSearchInterne" class="org.springframework.security.ldap.search.FilterBasedLdapUserSearch">
          <beans:constructor-arg index="0" value=""/>
          <beans:constructor-arg index="1" >
            <beans:value>(&(${ldap.interne.uid}={0})(objectclass=${ldap.objectClass.person}))</beans:value>
          </beans:constructor-arg>
          <beans:constructor-arg index="2" ref="contextSource" />
    </beans:bean>

    <beans:bean id="userSearchExterne" class="org.springframework.security.ldap.search.FilterBasedLdapUserSearch">
          <beans:constructor-arg index="0" value=""/>
          <beans:constructor-arg index="1" >
            <beans:value>(&(${ldap.externe.uid}={0})(objectclass=${ldap.objectClass.person}))</beans:value>
          </beans:constructor-arg>
          <beans:constructor-arg index="2" ref="contextSourceIndus" />
    </beans:bean>

    <!-- Debut gestion Ldap pour ecran User-->
    <beans:bean id="ldapTemplateInterne" class="org.springframework.ldap.core.LdapTemplate">
        <beans:constructor-arg ref="contextSource" />
    </beans:bean>

    <beans:bean id="ldapTemplateExterne" class="org.springframework.ldap.core.LdapTemplate">
        <beans:constructor-arg ref="contextSourceIndus" />
    </beans:bean>

</beans:beans>
</code>```

Title: Spring security

Body:
Following the release of Spring security version 2.0.8 to 3.2.7.release, I have encountered the following problem.

I modified the Java classes for the adaptation of the code suite upgrade, the pom.xml for the escalation to 3.2.7.release, and context-security.xml. This is the error I encounter:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.filterChains': Cannot resolve reference to bean 'org.springframework.security.web.DefaultSecurityFilterChain#0' while setting bean property 'sourceList' with key [0]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.web.DefaultSecurityFilterChain#0': Cannot resolve reference to bean 'org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter#0' while setting constructor argument with key [3]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter#0': Cannot resolve reference to bean 'org.springframework.security.authentication.ProviderManager#0' while setting bean property 'authenticationManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.authentication.ProviderManager#0': Could not resolve matching constructor (hint: specify index/type/name arguments for simple parameters to avoid type ambiguities)

My pom.xml updated for 3.2.7.RELEASE:

<spring-security.version>3.2.7.RELEASE</spring-security.version>

<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-ldap</artifactId>
    <version>${spring.version}</version>
</dependency>

<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-config</artifactId>
    <version>${spring.version}</version>
</dependency>

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-beans</artifactId>
    <version>${spring.version}</version>
</dependency>

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>${spring.version}</version>
</dependency>

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-core</artifactId>
    <version>${spring.version}</version>
</dependency>

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-expression</artifactId>
    <version>${spring.version}</version>
</dependency>

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>${spring.version}</version>
</dependency>

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jms</artifactId>
    <version>${spring.version}</version>
</dependency>

<dependency>
    <groupId>org.springframework.ldap</groupId>
    <artifactId>spring-ldap-core</artifactId>
    <version>1.3.1.RELEASE</version>
</dependency>

<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-core</artifactId>
    <version>${spring-security.version}</version>
</dependency>

<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-taglibs</artifactId>
    <version>${spring-security.version}</version>
</dependency>

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-tx</artifactId>
    <version>${spring.version}</version>
</dependency>

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>${spring.version}</version>
</dependency>

My fil applicationContextSecurity.xml

<?xml version="1.0" encoding="ISO-8859-1"?>
<beans:beans
xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
                    http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
                    http://www.springframework.org/schema/security
                    http://www.springframework.org/schema/security/spring-security-3.2.xsd">

    <global-method-security secured-annotations="enabled" jsr250-annotations="enabled"/>

    <authentication-manager id="multipleLdapProvider">

    </authentication-manager>

    <http pattern="/referentiel/**"   auto-config="true" use-expressions="true" authentication-manager-ref="multipleLdapProvider">
        <intercept-url pattern='/**'   access="ROLE_ADMIN, ROLE_SERMI, ROLE_CPRMI, ROLE_CDOM" />

        <http-basic />
    </http>
    <http pattern="/bareme/**" auto-config="true" use-expressions="true" authentication-manager-ref="multipleLdapProvider"   >
        <intercept-url pattern='/**' access="ROLE_ADMIN, ROLE_SERMI, ROLE_CPRMI" />
        <http-basic />
    </http>
    <http pattern="/comparaisonHosp/**"   auto-config="true" use-expressions="true"  authentication-manager-ref="multipleLdapProvider">
        <intercept-url pattern='/**' access="ROLE_ADMIN, ROLE_SERMI, ROLE_CPRMI, ROLE_CDOM, ROLE_ELUCN" />
        <http-basic />
    </http>
    <http pattern="/requete/**"  auto-config="true" use-expressions="true" authentication-manager-ref="multipleLdapProvider"  >
        <intercept-url pattern='/**' access="ROLE_ADMIN, ROLE_SERMI, ROLE_CPRMI, ROLE_CDOM" />
        <http-basic />
    </http>
    <http pattern="/refManif/**" auto-config="true" use-expressions="true" authentication-manager-ref="multipleLdapProvider"   >
        <intercept-url pattern='/**' access="ROLE_ADMIN, ROLE_SERMI, ROLE_CPRMI" />
        <http-basic />
    </http>
    <http pattern="/contrat/**" auto-config="true" use-expressions="true" authentication-manager-ref="multipleLdapProvider"  >
        <intercept-url pattern='/**' access="ROLE_ADMIN, ROLE_SERMI, ROLE_CPRMI, ROLE_CDOM, ROLE_ELUCN" />
        <http-basic />
    </http>
    <http pattern="/utilisateur/**"  auto-config="true" use-expressions="true" authentication-manager-ref="multipleLdapProvider"  >
        <intercept-url pattern='/**' access="ROLE_ADMIN, ROLE_SERMI, ROLE_CPRMI, ROLE_INADM" />
        <http-basic />
    </http>
    <http auto-config="true" use-expressions="true" authentication-manager-ref="multipleLdapProvider">
        <intercept-url pattern='/**' access="hasRole('USER')" />
        <form-login login-page='/login.action' default-target-url="/home.action" always-use-default-target='true'/>
        <logout />
    </http>

    <beans:bean id="contextSource"
        class="org.springframework.security.ldap.DefaultSpringSecurityContextSource">

      <beans:constructor-arg type="java.lang.String"><beans:value>${ldap.interne.url}</beans:value></beans:constructor-arg>
      <beans:property name="userDn">
        <beans:value>${ldap.interne.userDn}</beans:value>
      </beans:property>
      <beans:property name="password">
        <beans:value>${ldap.interne.password}</beans:value>
      </beans:property>
      <beans:property name="baseEnvironmentProperties">
            <beans:map>
                <beans:entry key="java.naming.referral" value="follow" />
            </beans:map>
      </beans:property>
    </beans:bean>

    <beans:bean id="contextSourceIndus"
        class="org.springframework.security.ldap.DefaultSpringSecurityContextSource">
      <beans:constructor-arg type="java.lang.String"><beans:value>${ldap.externe.url}</beans:value></beans:constructor-arg>
      <beans:property name="userDn">
        <beans:value>${ldap.externe.userDn}</beans:value>
      </beans:property>
      <beans:property name="password">
        <beans:value>${ldap.externe.password}</beans:value>
      </beans:property>
      <beans:property name="baseEnvironmentProperties">
            <beans:map>
                <beans:entry key="java.naming.referral" value="follow" />
            </beans:map>
      </beans:property>
    </beans:bean>

    <beans:bean id="multipleLdapProvider" class="com.cnom.idahe.utils.spring.MutlipleLdapAuthenticationProvider">
        <beans:constructor-arg>
            <beans:set>
                <beans:bean class="org.springframework.security.ldap.authentication.BindAuthenticator">
                    <beans:constructor-arg ref="contextSource"/>
                    <beans:property name="userSearch" ref="userSearchInterne"/>
                </beans:bean>

                <beans:bean class="org.springframework.security.ldap.authentication.BindAuthenticator">
                    <beans:constructor-arg ref="contextSourceIndus"/>
                    <beans:property name="userSearch" ref="userSearchExterne"/>
                </beans:bean>

            </beans:set>
        </beans:constructor-arg>
        <beans:constructor-arg>
            <beans:bean class="com.cnom.idahe.utils.spring.CnomDBPopulator">
            </beans:bean>
        </beans:constructor-arg>

    </beans:bean>

    <beans:bean id="userSearchInterne" class="org.springframework.security.ldap.search.FilterBasedLdapUserSearch">
          <beans:constructor-arg index="0" value=""/>
          <beans:constructor-arg index="1" >
            <beans:value>(&(${ldap.interne.uid}={0})(objectclass=${ldap.objectClass.person}))</beans:value>
          </beans:constructor-arg>
          <beans:constructor-arg index="2" ref="contextSource" />
    </beans:bean>

    <beans:bean id="userSearchExterne" class="org.springframework.security.ldap.search.FilterBasedLdapUserSearch">
          <beans:constructor-arg index="0" value=""/>
          <beans:constructor-arg index="1" >
            <beans:value>(&(${ldap.externe.uid}={0})(objectclass=${ldap.objectClass.person}))</beans:value>
          </beans:constructor-arg>
          <beans:constructor-arg index="2" ref="contextSourceIndus" />
    </beans:bean>

    <beans:bean id="ldapTemplateInterne" class="org.springframework.ldap.core.LdapTemplate">
        <beans:constructor-arg ref="contextSource" />
    </beans:bean>

    <beans:bean id="ldapTemplateExterne" class="org.springframework.ldap.core.LdapTemplate">
        <beans:constructor-arg ref="contextSourceIndus" />
    </beans:bean>

</beans:beans>


来源: stackexchange

问:
How to add partition filter in subquery used as table in AWS Glue PySpark?
I have created a job using Aws Glue 4.0 with PySpark 3.3 to perform read and write operation in oracle DB using JDBC.I am using G1.X with 10 worked nodes

SQL subquery is used as dbtable. By default Spark will load the entire table in one Partition But I want that read and write should be done parallelly. For this I used numPartitions, partitionColumn, lowerBound and upperBound options

Sample script

def insert_in_db():
sql = (select a,b from tbl1 join tbl2 on a.id=b.id)

```<code>df1 = spark.read.format("jdbc").options(driver=driver,url=jdbc_url,dbtable=sql,user=usr,password=pwd,numPartitions=10,partitionColumn="column_name") \
.option("oracle.jdbc.mapDateToTimestamp", "false")\
.option("lowerBound", "2022-11-13") \
.option("upperBound", "2023-01-11") \
.option("sessionInitStatement", "ALTER SESSION SET NLS_DATE_FORMAT = 'YYYY-MM-DD'")\
.load()
</code>```

On checked the log I found the partition filter were created as below

```<code>jdbc.JDBCRelation (Logging.scala:logInfo(61)): Number of partitions: 10, WHERE clauses of these partitions: "DATEVAL" \< '2022-11-23' or "DATEVAL" is null, "DATEVAL" \>= '2022-11-23' AND "DATEVAL" \< '2022-11-28', "DATEVAL" \>= '2022-11-28' AND "DATEVAL" \< '2022-12-03', "DATEVAL" \>= '2022-12-03' AND "DATEVAL" \< '2022-12-08', "DATEVAL" \>= '2022-12-08' AND "DATEVAL" \< '2022-12-13', "DATEVAL" \>= '2022-12-13' AND "DATEVAL" \< '2022-12-18', "DATEVAL" \>= '2022-12-18' AND "DATEVAL" \< '2022-12-23', "DATEVAL" \>= '2022-12-23' AND "DATEVAL" \< '2022-12-28', "DATEVAL" \>= '2022-12-28' AND "DATEVAL" \< '2023-01-02', "DATEVAL" \>= '2023-01-02'
</code>```

My concern is that the table is a subquery, so when JBDC will send this query to database for execution then this subquery will run for every partition and the partition filter created by PySpark will be added later. So, for every parallel run Oracle will run the complete query which will be memory intensive at database side.

Is there any solution where partition filter gets applied as a part of subquery i.e. instead of running query like

```<code>select \* from (select a,b from tbl1 join tbl2 on a.id=b.id) where "DATEVAL" \>= '2022-11-23' AND "DATEVAL" \< '2022-11-28'
the query runs like
select a,b from tbl1 join tbl2 on a.id=b.id where "DATEVAL" \>= '2022-11-23' AND "DATEVAL" \< '2022-11-28'
</code>```

Used numPartitions, partitionColumn, lowerBound and upperBound options for parallel read / write

By using this I thought that partition filter will be added in subquery but it's actually added after subquery.

ContentLicense: CC BY-SA 4.0

Body:
I have created a job using Aws Glue 4.0 with PySpark 3.3 to perform read and write operation in oracle DB using JDBC.I am using G1.X with 10 worked nodes

SQL subquery is used as dbtable. By default Spark will load the entire table in one Partition But I want that read and write should be done parallelly. For this I used numPartitions, partitionColumn, lowerBound and upperBound options

Sample script

def insert_in_db():
sql = (select a,b from tbl1 join tbl2 on a.id=b.id)

df1 = spark.read.format("jdbc").options(driver=driver,url=jdbc_url,dbtable=sql,user=usr,password=pwd,numPartitions=10,partitionColumn="column_name") \
.option("oracle.jdbc.mapDateToTimestamp", "false")\
.option("lowerBound", "2022-11-13") \
.option("upperBound", "2023-01-11") \
.option("sessionInitStatement", "ALTER SESSION SET NLS_DATE_FORMAT = 'YYYY-MM-DD'")\
.load()

On checked the log I found the partition filter were created as below

jdbc.JDBCRelation (Logging.scala:logInfo(61)): Number of partitions: 10, WHERE clauses of these partitions: "DATEVAL" \< '2022-11-23' or "DATEVAL" is null, "DATEVAL" \>= '2022-11-23' AND "DATEVAL" \< '2022-11-28', "DATEVAL" \>= '2022-11-28' AND "DATEVAL" \< '2022-12-03', "DATEVAL" \>= '2022-12-03' AND "DATEVAL" \< '2022-12-08', "DATEVAL" \>= '2022-12-08' AND "DATEVAL" \< '2022-12-13', "DATEVAL" \>= '2022-12-13' AND "DATEVAL" \< '2022-12-18', "DATEVAL" \>= '2022-12-18' AND "DATEVAL" \< '2022-12-23', "DATEVAL" \>= '2022-12-23' AND "DATEVAL" \< '2022-12-28', "DATEVAL" \>= '2022-12-28' AND "DATEVAL" \< '2023-01-02', "DATEVAL" \>= '2023-01-02'

My concern is that the table is a subquery, so when JBDC will send this query to database for execution then this subquery will run for every partition and the partition filter created by PySpark will be added later. So, for every parallel run Oracle will run the complete query which will be memory intensive at database side.

Is there any solution where partition filter gets applied as a part of subquery i.e. instead of running query like

select \* from (select a,b from tbl1 join tbl2 on a.id=b.id) where "DATEVAL" \>= '2022-11-23' AND "DATEVAL" \< '2022-11-28'
the query runs like
select a,b from tbl1 join tbl2 on a.id=b.id where "DATEVAL" \>= '2022-11-23' AND "DATEVAL" \< '2022-11-28'

Used numPartitions, partitionColumn, lowerBound and upperBound options for parallel read / write

By using this I thought that partition filter will be added in subquery but it's actually added after subquery.


问:
Spyder Python IDE unable to start consolle
today, after a restart of my editor, I discovered that it is not able any more to run the consolle (using it on a daily since years).

In the consolle the following message appears:

```<code>Traceback (most recent call last):
File "C:\Anaconda3\lib\runpy.py", line 194, in _run_module_as_main
return _run_code(code, main_globals, None,
File "C:\Anaconda3\lib\runpy.py", line 87, in _run_code
exec(code, run_globals)
File "C:\Anaconda3\lib\site‑packages\spyder_kernels\console\__main__.py", line 23, in
start.main()
File "C:\Anaconda3\lib\site‑packages\spyder_kernels\console\start.py", line 253, in main
import_spydercustomize()
File "C:\Anaconda3\lib\site‑packages\spyder_kernels\console\start.py", line 43, in import_spydercustomize
import spydercustomize
ModuleNotFoundError: No module named 'spydercustomize'
</code>```

My version of python is:

```<code>Python 3.8.8 (default, Apr 13 2021, 15:08:03) [MSC v.1916 64 bit (AMD64)] :: Anaconda, Inc. on win32
</code>```

and from a Python prompt I can see this:

```<code>>>> import spyder
>>> spyder.__version__
'4.2.5'
>>>
</code>```

Anybody has an idea of what could have happened and how to fix this without reinstalling everything?

P.S. I noticed that the substrings "site‑packages" in the message from the consolle contains a character alike "-" that is not interpreted by the windows file explorer (it can't find the folder). It looks like to be another kid of minus sign. The folder "C:\Anaconda3\Lib\site-packages\spyder_kernels\customize" and its content are actually present on my PC

Body:
today, after a restart of my editor, I discovered that it is not able any more to run the consolle (using it on a daily since years).

In the consolle the following message appears:

Traceback (most recent call last):
File "C:\Anaconda3\lib\runpy.py", line 194, in _run_module_as_main
return _run_code(code, main_globals, None,
File "C:\Anaconda3\lib\runpy.py", line 87, in _run_code
exec(code, run_globals)
File "C:\Anaconda3\lib\site‑packages\spyder_kernels\console\__main__.py", line 23, in
start.main()
File "C:\Anaconda3\lib\site‑packages\spyder_kernels\console\start.py", line 253, in main
import_spydercustomize()
File "C:\Anaconda3\lib\site‑packages\spyder_kernels\console\start.py", line 43, in import_spydercustomize
import spydercustomize
ModuleNotFoundError: No module named 'spydercustomize'

My version of python is:

Python 3.8.8 (default, Apr 13 2021, 15:08:03) [MSC v.1916 64 bit (AMD64)] :: Anaconda, Inc. on win32

and from a Python prompt I can see this:

>>> import spyder
>>> spyder.__version__
'4.2.5'
>>>

Anybody has an idea of what could have happened and how to fix this without reinstalling everything?

P.S. I noticed that the substrings "site‑packages" in the message from the consolle contains a character alike "-" that is not interpreted by the windows file explorer (it can't find the folder). It looks like to be another kid of minus sign. The folder "C:\Anaconda3\Lib\site-packages\spyder_kernels\customize" and its content are actually present on my PC


问:
kableExtra table repeat_header being strange
I've finally made my dream table with kableExtra, but it's doing very weird things with kable_styling(latex_options=c("repeat_header")), where it's writing the headings over my column labels. Here I'm using the example dataset diamonds. It is also moving the first column below where it should be (red arrows in picture).

(Also can't download LaTex because of work authorization issues, so that's not an option)

Thanks for all the help!

```<code>library(knitr)
library(kableExtra)
library(dplyr)

options(
  knitr.table.toprule = '\\toprule',
  knitr.table.midrule = '\\midrule',
  knitr.table.bottomrule = '\\bottomrule'
)

df1 <- read.csv("diamonds.csv")

a11<-df1%>%
  group_by(cut, color, clarity)%>%
  summarize_at( .vars=c("price"),
                .funs=~mean(.,na.rm=TRUE)) %>%
  mutate(sort = 3)

b11<-df1%>%
  group_by(cut, color) %>%
  summarize_at( .vars=c("price"),
                .funs=~mean(.,na.rm=TRUE)) %>%
  mutate(clarity="", sort = 2) %>%
  select(cut, color, clarity,everything())

c11<-df1 %>%
  group_by(cut) %>%
  summarize_at( .vars=c("price"),
                .funs=~mean(.,na.rm=TRUE)) %>%
  mutate(color="", clarity= "", sort = 1) %>%
  select(cut, color,everything())

table3<-rbind(a11,b11,c11)
table3%>%
  arrange(cut, color, clarity) %>%
  select(-sort)%>%
  filter(price>=3000)%>%
  kbl(
    caption = "Table",
    longtable=T, booktabs=T) %>%
  add_header_above(header = c("Table 1." = 4))%>%
  kable_styling(latex_options=c("repeat_header"))%>%
  kable_paper(full_width = F) %>%
  column_spec(1, bold = T) %>%
  column_spec(3, italic = T) %>%
  collapse_rows(columns = 1:3, valign = "top")
</code>```

Body:
I've finally made my dream table with kableExtra, but it's doing very weird things with kable_styling(latex_options=c("repeat_header")), where it's writing the headings over my column labels. Here I'm using the example dataset diamonds. It is also moving the first column below where it should be (red arrows in picture).

(Also can't download LaTex because of work authorization issues, so that's not an option)

Thanks for all the help!

library(knitr)
library(kableExtra)
library(dplyr)

options(
  knitr.table.toprule = '\\toprule',
  knitr.table.midrule = '\\midrule',
  knitr.table.bottomrule = '\\bottomrule'
)

df1 <- read.csv("diamonds.csv")

a11<-df1%>%
  group_by(cut, color, clarity)%>%
  summarize_at( .vars=c("price"),
                .funs=~mean(.,na.rm=TRUE)) %>%
  mutate(sort = 3)

b11<-df1%>%
  group_by(cut, color) %>%
  summarize_at( .vars=c("price"),
                .funs=~mean(.,na.rm=TRUE)) %>%
  mutate(clarity="", sort = 2) %>%
  select(cut, color, clarity,everything())

c11<-df1 %>%
  group_by(cut) %>%
  summarize_at( .vars=c("price"),
                .funs=~mean(.,na.rm=TRUE)) %>%
  mutate(color="", clarity= "", sort = 1) %>%
  select(cut, color,everything())

table3<-rbind(a11,b11,c11)
table3%>%
  arrange(cut, color, clarity) %>%
  select(-sort)%>%
  filter(price>=3000)%>%
  kbl(
    caption = "Table",
    longtable=T, booktabs=T) %>%
  add_header_above(header = c("Table 1." = 4))%>%
  kable_styling(latex_options=c("repeat_header"))%>%
  kable_paper(full_width = F) %>%
  column_spec(1, bold = T) %>%
  column_spec(3, italic = T) %>%
  collapse_rows(columns = 1:3, valign = "top")


问:
How encode rust enum in javascript (@project-serum/borsh)
i have enum in rust

```<code>pub enum Kind {
Public,
Private,
}
</code>```

I cant encode to buffer in js

```<code>import * as borsh from "@project-serum/borsh";
const struct = borsh.struct(
  [
    borsh.rustEnum([borsh.u8("public"), borsh.u8("private")], "kind"),
    borsh.str("name"),
  ],
  "dto"
);
</code>```

I get an error

```<code>TypeError: defaultLayout must be null or a Layout
</code>```

Please, help me

Body:
i have enum in rust

pub enum Kind {
Public,
Private,
}

I cant encode to buffer in js

import * as borsh from "@project-serum/borsh";
const struct = borsh.struct(
  [
    borsh.rustEnum([borsh.u8("public"), borsh.u8("private")], "kind"),
    borsh.str("name"),
  ],
  "dto"
);

I get an error

TypeError: defaultLayout must be null or a Layout

Please, help me


问:
Model.deleteOne() gives PoolClosedError [MongoPoolClosedError]: Attempted to check out a connection from closed connection pool
```<code>import mongoose from "mongoose";
import Person from "./model/Person.js";

mongoose.connect("mongodb+srv://winson8222:<password>@test.suq6cuh.mongodb.net/test?retryWrites=true&w=majority", {
    useNewUrlParser:true, useUnifiedTopology: true
}, (err)=> {
    if(err)
    {
        console.log(err);
    } else {
        console.log("sucessfully connected")
    }
}
)

Person.deleteOne({_id: "63c14a30fcba10e2f50ff6a5"}, function(err){
    if(err){
        console.log(err);
    }else{
        console.log("Deletion Succeed");
    }
} );

Person.find(function(err, people){
    if(err){
        console.log("failed");
    }else{
        mongoose.connection.close();
         people.forEach(function(p){
            console.log(p.name);
         })
    }
})

const p1 = await Person.find();
console.log(p1);
</code>```

I am trying to deleteOne by id but I keep getting "PoolClosedError [MongoPoolClosedError]: Attempted to check out a connection from closed connection pool". At the bottom i am trying to console.log out the name of the Person one by one, which i think is where is problem is.
However, insertOne works just fine. Can anyone help?

Body:
import mongoose from "mongoose";
import Person from "./model/Person.js";

mongoose.connect("mongodb+srv://winson8222:<password>@test.suq6cuh.mongodb.net/test?retryWrites=true&w=majority", {
    useNewUrlParser:true, useUnifiedTopology: true
}, (err)=> {
    if(err)
    {
        console.log(err);
    } else {
        console.log("sucessfully connected")
    }
}
)

Person.deleteOne({_id: "63c14a30fcba10e2f50ff6a5"}, function(err){
    if(err){
        console.log(err);
    }else{
        console.log("Deletion Succeed");
    }
} );

Person.find(function(err, people){
    if(err){
        console.log("failed");
    }else{
        mongoose.connection.close();
         people.forEach(function(p){
            console.log(p.name);
         })
    }
})

const p1 = await Person.find();
console.log(p1);

I am trying to deleteOne by id but I keep getting "PoolClosedError [MongoPoolClosedError]: Attempted to check out a connection from closed connection pool". At the bottom i am trying to console.log out the name of the Person one by one, which i think is where is problem is.
However, insertOne works just fine. Can anyone help?


问:
startBluetoothSco keeps jumping between SCO_AUDIO_STATE_CONNECTED and SCO_AUDIO_STATE_DISCONNECTED
I'm trying to connect to a bluetooth headset to record audio from device , the issue is that it shows that it is connected but right after it goes to disconnected for some reason , i'm debugging the code but could not figure out the problem , i would appreciate anyone giving some help , Thank you

Manifest File

```<code>    <uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
    <uses-permission android:name="android.permission.RECORD_AUDIO" />
    <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
    <uses-permission android:name="android.permission.BROADCAST_STICKY"/>
    <uses-permission android:name="android.permission.BLUETOOTH" android:required="false" />

</code>```

Registering receiver

```<code>   public void onCreate() {
        super.onCreate();
        recorder = new Recorder(getApplicationContext());
        audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        nm = (NotificationManager) getApplicationContext()
                .getSystemService(Context.NOTIFICATION_SERVICE);
        settings = Core.getInstance().getCache().getPrefs();

        self = this;

        // register new receiver for bluetooth headset
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if(bluetoothAdapter.isEnabled()){
           IntentFilter intentFilter =  new IntentFilter();
            intentFilter.addAction(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED); // API 11
            intentFilter.addAction(AudioManager.ACTION_SCO_AUDIO_STATE_CHANGED); // API 8
            intentFilter.addAction(AudioManager.ACTION_SCO_AUDIO_STATE_UPDATED); // API 14
            registerReceiver(broadcastReceiver,intentFilter);
            audioManager.startBluetoothSco();
        }
    }
</code>```

Receiver code

```<code>  // when the call starts it executed CONNECTED then right after it goes to DISCONNECTED

   private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            int state = intent.getIntExtra(AudioManager.EXTRA_SCO_AUDIO_STATE,-1);
            if(AudioManager.SCO_AUDIO_STATE_CONNECTED == state){
                Log.d("TAG","Connected");
                audioManager.setSpeakerphoneOn(false);
                audioManager.setBluetoothScoOn(true);
            } else if (AudioManager.SCO_AUDIO_STATE_DISCONNECTED == state){
                Log.d("TAG","Disconnected");
            }
        }
    };
</code>```

Body:
I'm trying to connect to a bluetooth headset to record audio from device , the issue is that it shows that it is connected but right after it goes to disconnected for some reason , i'm debugging the code but could not figure out the problem , i would appreciate anyone giving some help , Thank you

Manifest File

    <uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
    <uses-permission android:name="android.permission.RECORD_AUDIO" />
    <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
    <uses-permission android:name="android.permission.BROADCAST_STICKY"/>
    <uses-permission android:name="android.permission.BLUETOOTH" android:required="false" />

Registering receiver

   public void onCreate() {
        super.onCreate();
        recorder = new Recorder(getApplicationContext());
        audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        nm = (NotificationManager) getApplicationContext()
                .getSystemService(Context.NOTIFICATION_SERVICE);
        settings = Core.getInstance().getCache().getPrefs();

        self = this;

        // register new receiver for bluetooth headset
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if(bluetoothAdapter.isEnabled()){
           IntentFilter intentFilter =  new IntentFilter();
            intentFilter.addAction(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED); // API 11
            intentFilter.addAction(AudioManager.ACTION_SCO_AUDIO_STATE_CHANGED); // API 8
            intentFilter.addAction(AudioManager.ACTION_SCO_AUDIO_STATE_UPDATED); // API 14
            registerReceiver(broadcastReceiver,intentFilter);
            audioManager.startBluetoothSco();
        }
    }

Receiver code

  // when the call starts it executed CONNECTED then right after it goes to DISCONNECTED

   private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            int state = intent.getIntExtra(AudioManager.EXTRA_SCO_AUDIO_STATE,-1);
            if(AudioManager.SCO_AUDIO_STATE_CONNECTED == state){
                Log.d("TAG","Connected");
                audioManager.setSpeakerphoneOn(false);
                audioManager.setBluetoothScoOn(true);
            } else if (AudioManager.SCO_AUDIO_STATE_DISCONNECTED == state){
                Log.d("TAG","Disconnected");
            }
        }
    };


问:
I can't find Strapi nested components in my GraphQL query
I'm very new to Strapi and GraphQL. I have created a nested data structure in Strapi that looks like this (this is a Navbar component). But when I go to GraphQL, my query looks like this.

So if this is the query:

```<code>query MyQuery {
  allStrapiNavbar {
    nodes {
      Category {
        Name
        children {
          id
        }
      }
    }
  }
}
</code>```

This is the result:

```<code>{
  "data": {
    "allStrapiNavbar": {
      "nodes": [
        {
          "Category": [
            {
              "Name": "Community",
              "children": []
            },
            {
              "Name": "Modules",
              "children": []
            },
            {
              "Name": "Company",
              "children": []
            },
            {
              "Name": "Pricing",
              "children": []
            }
          ]
        }
      ]
    }
  },
  "extensions": {}
}
</code>```

This means the data is being fetched correctly. However, I can't find the nested component 'Item' inside 'Category'.

This is what my gatsby-config.ts file looks like currently:

```<code>{
    resolve: "gatsby-source-strapi",
    options: {
      apiURL: process.env.STRAPI_API_URL || "http://localhost:1337",
      queryLimit: 1000, // Default to 100
      accessToken: process.env.STRAPI_TOKEN,
      collectionTypes:[ 'faq', 'doc', 'docCategory', 'faqCategory', 'release', 'userType' ],
      // contentTypes: [ 'Faq' ],
      singleTypes: [ 'navbar' ],
    },
</code>```

I don't know why the data isn't showing up in GraphQL. I looked inside the children for Category, but the reality is that it should be at the same level as Name, which shows up.
Do I need to modify the gatsby-config file, or am I missing something else?

Edit: I am using the gatsby-source-strapi plugin.

Body:
I'm very new to Strapi and GraphQL. I have created a nested data structure in Strapi that looks like this (this is a Navbar component). But when I go to GraphQL, my query looks like this.

So if this is the query:

query MyQuery {
  allStrapiNavbar {
    nodes {
      Category {
        Name
        children {
          id
        }
      }
    }
  }
}

This is the result:

{
  "data": {
    "allStrapiNavbar": {
      "nodes": [
        {
          "Category": [
            {
              "Name": "Community",
              "children": []
            },
            {
              "Name": "Modules",
              "children": []
            },
            {
              "Name": "Company",
              "children": []
            },
            {
              "Name": "Pricing",
              "children": []
            }
          ]
        }
      ]
    }
  },
  "extensions": {}
}

This means the data is being fetched correctly. However, I can't find the nested component 'Item' inside 'Category'.

This is what my gatsby-config.ts file looks like currently:

{
    resolve: "gatsby-source-strapi",
    options: {
      apiURL: process.env.STRAPI_API_URL || "http://localhost:1337",
      queryLimit: 1000, // Default to 100
      accessToken: process.env.STRAPI_TOKEN,
      collectionTypes:[ 'faq', 'doc', 'docCategory', 'faqCategory', 'release', 'userType' ],
      // contentTypes: [ 'Faq' ],
      singleTypes: [ 'navbar' ],
    },

I don't know why the data isn't showing up in GraphQL. I looked inside the children for Category, but the reality is that it should be at the same level as Name, which shows up.
Do I need to modify the gatsby-config file, or am I missing something else?

Edit: I am using the gatsby-source-strapi plugin.


问:
Why is Pandas to_datetime slower and shows higher peak memory usage with explicit format argument?
When trying to convert a column in a Pandas dataframe from string '%Y%m%d' to datetime, I noticed a wierd behavior where the code is slower and shows a much higher peak memory usage when format is explicitly set.

Example dataframe:

```<code>import pandas as pd

# Example dataframe with a column formatted as '%Y%m%d'
df = pd.DataFrame({'date': pd.date_range(start='2000-01-01', end='2023-01-01')})
df['date'] = df['date'].dt.strftime('%Y%m%d')
</code>```

Compare time:

```<code>## Option 1: convert the column without explicit format
%timeit -n 500 pd.to_datetime(df['date'])
## 1.35 ms ± 143 µs per loop (mean ± std. dev. of 7 runs, 500 loops each)

## Option 2: convert the column with specific format
%timeit -n 500 pd.to_datetime(df['date'], format='%Y%m%d')
## 5.32 ms ± 166 µs per loop (mean ± std. dev. of 7 runs, 500 loops each)
</code>```

Compare peak memory usage:

```<code>import tracemalloc

tracemalloc.start()

## Option 1: convert the column without explicit format
pd.to_datetime(df['date'])
_, peak = tracemalloc.get_traced_memory()
print(f'Peak memory usage: {peak}')
tracemalloc.clear_traces()
## Peak memory usage: 141349

## Option 2: convert the column with specific format
pd.to_datetime(df['date'], format='%Y%m%d')
_, peak = tracemalloc.get_traced_memory()
print(f'Peak memory usage: {peak}')
tracemalloc.clear_traces()
## Peak memory usage: 1386294
</code>```

Even more surprisingly, when I passed a wrong format pd.to_datetime(df['date'], format='%Y-%m-%d'), the code ran successfully and the performance was similar to when format was not explicitly set.

The results are obtained with Pandas 1.4.3. I'm also seeing similar behavior with Pandas 1.3.4. Appreciate any help to understand why this is happening.

Body:
When trying to convert a column in a Pandas dataframe from string '%Y%m%d' to datetime, I noticed a wierd behavior where the code is slower and shows a much higher peak memory usage when format is explicitly set.

Example dataframe:

import pandas as pd

# Example dataframe with a column formatted as '%Y%m%d'
df = pd.DataFrame({'date': pd.date_range(start='2000-01-01', end='2023-01-01')})
df['date'] = df['date'].dt.strftime('%Y%m%d')

Compare time:

## Option 1: convert the column without explicit format
%timeit -n 500 pd.to_datetime(df['date'])
## 1.35 ms ± 143 µs per loop (mean ± std. dev. of 7 runs, 500 loops each)

## Option 2: convert the column with specific format
%timeit -n 500 pd.to_datetime(df['date'], format='%Y%m%d')
## 5.32 ms ± 166 µs per loop (mean ± std. dev. of 7 runs, 500 loops each)

Compare peak memory usage:

import tracemalloc

tracemalloc.start()

## Option 1: convert the column without explicit format
pd.to_datetime(df['date'])
_, peak = tracemalloc.get_traced_memory()
print(f'Peak memory usage: {peak}')
tracemalloc.clear_traces()
## Peak memory usage: 141349

## Option 2: convert the column with specific format
pd.to_datetime(df['date'], format='%Y%m%d')
_, peak = tracemalloc.get_traced_memory()
print(f'Peak memory usage: {peak}')
tracemalloc.clear_traces()
## Peak memory usage: 1386294

Even more surprisingly, when I passed a wrong format pd.to_datetime(df['date'], format='%Y-%m-%d'), the code ran successfully and the performance was similar to when format was not explicitly set.

The results are obtained with Pandas 1.4.3. I'm also seeing similar behavior with Pandas 1.3.4. Appreciate any help to understand why this is happening.


问:
Google Document AI custom processor training failed for unknown reason
After annotating my data set and training a custom processor on Google Document AI, I get the following error message after 40 mins:

```<code>{
  "name": "projects/500809854407/locations/eu/operations/10980743890623751388",
  "done": true,
  "result": "error",
  "response": {},
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.documentai.uiv1beta3.TrainProcessorVersionMetadata",
    "commonMetadata": {
      "state": "FAILED",
      "createTime": "2023-01-13T15:11:36.505757Z",
      "updateTime": "2023-01-13T15:50:10.343765Z",
      "resource": "projects/500809854407/locations/eu/processors/b94da5023b6cb35d/processorVersions/98637063da2b64d4"
    },
    "trainingDatasetValidation": {},
    "testDatasetValidation": {}
  },
  "error": {
    "code": 13,
    "message": "Internal error encountered.",
    "details": []
  }
}
</code>```

Any idea what could be the problem?

Body:
After annotating my data set and training a custom processor on Google Document AI, I get the following error message after 40 mins:

{
  "name": "projects/500809854407/locations/eu/operations/10980743890623751388",
  "done": true,
  "result": "error",
  "response": {},
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.documentai.uiv1beta3.TrainProcessorVersionMetadata",
    "commonMetadata": {
      "state": "FAILED",
      "createTime": "2023-01-13T15:11:36.505757Z",
      "updateTime": "2023-01-13T15:50:10.343765Z",
      "resource": "projects/500809854407/locations/eu/processors/b94da5023b6cb35d/processorVersions/98637063da2b64d4"
    },
    "trainingDatasetValidation": {},
    "testDatasetValidation": {}
  },
  "error": {
    "code": 13,
    "message": "Internal error encountered.",
    "details": []
  }
}

Any idea what could be the problem?


问:
SignalR.Core not sending message on specific idp
I have signalR.Core on .Net6 for the server and angular on client.
I have on local/developpement environnement an idp based on IdentityServer 4.
On the quality environement the idp is sign&go.

With the identityServer idp, everything works well, I received all message on my angular application.
But with sign&go, I'm able to connect on server/client side but I'm not able to receive anything.

After check on logs, I saw that messages isn't sending by the server
(on local I have something like this on log
)

But with sign&go I have no errors, no specific logs and the hub send function is called without issue.
I have also no specific logs on client side.

Nothing specific on idp as well.

I tried these kind of transports Websocket/LongPooling/Server Sent Events but all types have the same result at the end (working with my idp but not with sign&go).

I tried on local with sign&go same result also.

Logs are already activated on server/client side.

Do you have a way to identify the source of non sending message ?

PS : The result is the same for all sending message.


问:
Internal server error 500 when sending ajax post request in laravel 9
I am using laravel 9. I am trying to make a ajax crud operation using alax. It respond well in get request. but when I sending  the post request it shows:

http://127.0.0.1:8000/add/teacher 500 (Internal Server Error) in the console. I used meta in the head and ajax csrf header according to documentation. Still showing error. here my ajax code example bellow:

```<code><script>
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });

    $(document).ready(function() {

        $(".add_teacher").on('click', function(event) {
            event.preventDefault();
            var name = $("#name").val();
            var email = $("#email").val();
            var position = $("#position").val();
            var phone = $("#phone").val();
            var password = $("#password").val();

            $.ajax({
                method: "post",
                url: "{{route('store')}}",
                data: {
                    name: name,
                    email: email,
                    position: position,
                    phone: phone,
                    password: password
                },
                success: function(res) {
                    if (res.status == 'success') {
                        $("#exampleModal").modal('hide');
                        $("#modalform")[0].reset();
                        $(".table").load(location.href + ' .table');
                    }
                },
                error: function(err) {
                    let error = err.responseJSON;
                    $.each(error.errors, function(index, value) {
                    $(".errorMessage").append('<span class="text-
                      danger">' + value +'</span><br>');
                    });
                }
            });

        });

    });
</script>
</code>```

Here is my route:

```<code>Route::post('/add/teacher', [TeacherController::class,'store'])->name('store');
</code>```

and my controller code is:

```<code>public function store(Request $request)
    {

        $request->validate(
            [
                "name"      => "required",
                "email"     => "requied|unique:teachers",
                "position"  => "requied",
                "phone"     => "requied|unique:tachers",
                "password"  => "requied",
            ],
            [
                "name.required" => "Name is required",
                "email.required" => "Email is required",
                "email.unique" => "Email already exists",
                "position.required" => "Postion is required",
                "phone.required" => "Phone is required",
                "phone.unique" => "Phone already exixts",
                "password.required" => "password is required",
            ]
        );

        $teacher = new Teacher();
        $teacher->name = $request->name;
        $teacher->email = $request->email;
        $teacher->position = $request->position;
        $teacher->phone = $request->phone;
        $teacher->password = $request->password;
        $teacher->save();
        return response()->json([
            'status' => 'success',
        ]);
    }
</code>```

Now I need an exact solution to go farther. Thank you.

Body:
I am using laravel 9. I am trying to make a ajax crud operation using alax. It respond well in get request. but when I sending  the post request it shows:

http://127.0.0.1:8000/add/teacher 500 (Internal Server Error) in the console. I used meta in the head and ajax csrf header according to documentation. Still showing error. here my ajax code example bellow:

Here is my route:

Route::post('/add/teacher', [TeacherController::class,'store'])->name('store');

and my controller code is:

public function store(Request $request)
    {

        $request->validate(
            [
                "name"      => "required",
                "email"     => "requied|unique:teachers",
                "position"  => "requied",
                "phone"     => "requied|unique:tachers",
                "password"  => "requied",
            ],
            [
                "name.required" => "Name is required",
                "email.required" => "Email is required",
                "email.unique" => "Email already exists",
                "position.required" => "Postion is required",
                "phone.required" => "Phone is required",
                "phone.unique" => "Phone already exixts",
                "password.required" => "password is required",
            ]
        );

        $teacher = new Teacher();
        $teacher->name = $request->name;
        $teacher->email = $request->email;
        $teacher->position = $request->position;
        $teacher->phone = $request->phone;
        $teacher->password = $request->password;
        $teacher->save();
        return response()->json([
            'status' => 'success',
        ]);
    }

Now I need an exact solution to go farther. Thank you.


问:
How can I read a value from a Stimulus controller?
Rather than use Stimulus targets to fetch data, I'd like to use Stimulus values in my controller but I can't find the way to retrieve it. Any idea how I could write it? Thanks.

This works:

```<code>HTML:
<div data-controller="admin-invoice-form">
  <div data-target="admin-invoice-form.amountDiscountedTotal" value="100"><div>
<div>

STIMULUS:
static targets = ["amountDiscountedTotal"];

connect() {
  console.log(this.amountDiscountedTotalTarget)
  --> 100
}
</code>```

This doesn't work:

```<code>HTML:
<div data-controller="admin-invoice-form">
  <div data-admin-invoice-form-amount-discounted-total-value="100"><div>
<div>

STIMULUS:
static values = { amountDiscountedTotal: Number }

connect() {
  console.log(this.amountDiscountedTotalValue);
  --> undefined
  console.log(this.data.get("amountDiscountedTotalValue"));
  --> null
}
</code>```

Body:
Rather than use Stimulus targets to fetch data, I'd like to use Stimulus values in my controller but I can't find the way to retrieve it. Any idea how I could write it? Thanks.

This works:

HTML:

STIMULUS:
static targets = ["amountDiscountedTotal"];

connect() {
  console.log(this.amountDiscountedTotalTarget)
  --> 100
}

This doesn't work:

HTML:

STIMULUS:
static values = { amountDiscountedTotal: Number }

connect() {
  console.log(this.amountDiscountedTotalValue);
  --> undefined
  console.log(this.data.get("amountDiscountedTotalValue"));
  --> null
}


问:
I am not able to perform update operation in crud
I am trying to perform update operation in Django. Actually what I need when I click the update button of an existing entry it should load in an another form with the data and once I change the details need to save it. I have referred a video with same requirement but that code is not working for me. Please help me I am really stuck.

These are my files and code details.

forms.py

```<code>from .models import Building
from django.forms import ModelForm

class BuildingForm(ModelForm):
    class Meta:
        model = Building
        fields = '__all__'
</code>```

models.py

```<code>from django.db import models

# Create your models here.
class BuildingType(models.Model):
   building_type = models.CharField(max_length=100)

   def __str__(self):
       return self.building_type

class Building(models.Model):
    building_name = models.CharField(max_length=50)
    name_of_owner = models.CharField(max_length=50)
    building_type = models.ForeignKey(BuildingType, on_delete=models.CASCADE)
    number_of_rooms = models.IntegerField()
    mobile_number = models.IntegerField()
    current_lease_period = models.DateField()
</code>```

urls.py

```<code>from django.urls import path
from . import views

urlpatterns = [
    path('', views.Home, name='home'),
    path('buildings', views.Buildings, name='buildings'),
    path('rooms', views.Rooms, name='rooms'),
    path('customers', views.Customers, name='customers'),
    path('receipts', views.Receipts, name='receipts'),
    path('new_building', views.NewBuilding, name='new_building'),
    path('update/<int:bldg_id>', views.UpdateBuilding, name='update_building'),
    path('delete_building/<int:bldg_id>', views.DeleteBuilding, name='delete_building'),
    path('new_room', views.NewRoom, name='new_room'),
    path('new_customer', views.NewCustomer, name='new_customer'),
    path('new_receipt', views.NewReceipt, name='new_receipt'),
    path('login', views.Login, name='login'),
    path('signup', views.Signup, name='signup'),
]
</code>```

views.py

```<code>from django.shortcuts import render, redirect
from .forms import BuildingForm
from webapp.models import Building, BuildingType

# Create your views here.

def Home(request):
    return render(request, 'index.html', {'context':'null'})

def Buildings(request):
    building_list = Building.objects.all()
    return render(request, 'buildings.html', {'context': 'Buildings', 'building_list': building_list})

def Rooms(request):
    return render(request, 'rooms.html', {'context':'Rooms'})

def Customers(request):
    return render(request, 'customers.html', {'context':'Customers'})

def Receipts(request):
    return render(request, 'receipts.html', {'context':'Receipts'})

# New Building
def NewBuilding(request):
    bldg_type = BuildingType.objects.all()
    form = BuildingForm()
    if request.method == "POST":
        form = BuildingForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('buildings')
        else:
            form = BuildingForm()
    return render(request, 'new_building.html', {'context':'NewBuilding', 'bldg_type':bldg_type, 'form':form})
**
# Update Building
def UpdateBuilding(request, bldg_id):
    bldg_type = BuildingType.objects.all()
    Update_building = Building.objects.get(id=bldg_id)
    form = BuildingForm(instance=Update_building)
    return render(request, 'update_building.html', {'context':'UpdateBuilding', 'bldg_type':bldg_type, 'form':form})**

# Delete Building
def DeleteBuilding(request, bldg_id):
    building_list = Building.objects.all()
    if request.method == "POST":
        bldg=Building.objects.get(id=bldg_id)
        bldg.delete()
        return redirect('buildings')
    return render(request, 'buildings.html', {'building_list':building_list})

def NewRoom(request):
    return render(request, 'new_room.html', {'context':'NewRoom'})

def NewCustomer(request):
    return render(request, 'new_customer.html', {'context':'NewCustomer'})

def NewReceipt(request):
    return render(request, 'new_receipt.html', {'context':'NewReceipt'})

def Login(request):
    return render(request, 'login.html')

def Signup(request):
    return render(request, 'signup.html')

</code>```

buildings.html

```<code>{% extends 'base.html' %}
{% load static %}

{% block title %} Buildings {% endblock %}

{% block content %}
    <!-- Buildings -->
    <div class="container-fluid">
        <div class="sub-box">
            <div class="row">
                <div class="col-sm-12 mt-3">
                    <div class="row">
                        <div class="col-sm-12 col-md-12 col-lg-12 col-xl-12 col-xxl-12 search-col">
                            <form action="" class="d-flex gap-3">
                                <input type="text" class="form-control form-control-lg" id="search" >
                                <button type="submit" class="btn btn-lg search">Search</button>
                            </form>
                        </div>
                    </div>
                </div>
                <div class="col-sm-12 mt-3 table-responsive">
                    <table class="table table-hover table-bordered text-center ">
                        <thead>
                            <tr>
                                <th scope="col" class="align-middle">Building Name</th>
                                <th scope="col" class="align-middle">Building Type</th>
                                <th scope="col" class="align-middle">Rooms</th>
                                <th scope="col" class="align-middle">Owner Name</th>
                                <th scope="col" class="align-middle">Mobile Number</th>
                                <th scope="col" class="align-middle">Lease Period</th>
                                <th scope="col" class="align-middle">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            {% for list in building_list %}
                            <tr>
                                <td class="align-middle">{{list.building_name}}</td>
                                <td class="align-middle">{{list.building_type}}</td>
                                <td class="align-middle">{{list.number_of_rooms}}</td>
                                <td class="align-middle">{{list.name_of_owner}}</td>
                                <td class="align-middle">{{list.mobile_number}}</td>
                                <td class="align-middle">{{list.current_lease_period}}</td>
                                <td class="d-flex justify-content-between gap-3">
                                    <a href="{% url 'update_building' list.id %}" class="btn update">Update</a>
                                    <form action="{% url 'delete_building' list.id %}" method="post">
                                        {% csrf_token %}
                                        <input type="submit" value="Delete" class="btn delete">
                                    </form>
                                </td>
                            </tr>
                            {% endfor %}
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
{% endblock %}
</code>```

update_building.html

```<code>{% extends 'base.html' %}
{% load static %}

{% block title %} UpdateBuilding {% endblock %}

{% block content %}
    <!-- Update Building -->
    <div class="container-fluid">
        <div class="main-box">
            <div class="row d-flex align-items-center justify-content-center">
                <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 col-xl-12 d-flex align-items-start flex-column">
                    <h1 class="mb-4 mt-2">Update Building</h1>
                    <form method="post" autocomplete="off">
                        {% csrf_token %}
                        <div class="row">
                            <div class="col-xs-12 col-sm-12 col-md-12 col-lg-6">
                                <div class="mb-3">
                                    <label for="building_name" class="form-label">building name</label>
                                    <input type="text" class="form-control form-control-lg" id="building_name" name="building_name" >
                                </div>
                            </div>
                            <div class="col-xs-12 col-sm-12 col-md-12 col-lg-6">
                                <div class="mb-3">
                                    <label for="name_of_owner" class="form-label">name of owner</label>
                                    <input type="text" class="form-control form-control-lg" id="name_of_owner" name="name_of_owner" >
                                </div>
                            </div>
                            <div class="col-xs-12 col-sm-12 col-md-12 col-lg-6">
                                <label for="building_type" class="form-label">building type</label>
                                <select class="form-select form-select-lg mb-3" aria-label=".form-select-lg example" id="building_type" name="building_type">
                                    <option selected>select</option>
                                    {% for type in bldg_type %}
                                    <option value="{{type.id}}">{{type.building_type}}</option>
                                    {% endfor%}
                                </select>
                            </div>
                            <div class="col-xs-12 col-sm-12 col-md-12 col-lg-6">
                                <div class="mb-3">
                                    <label for="mobile_number" class="form-label">mobile number</label>
                                    <input type="number" class="form-control form-control-lg" id="mobile_number" name="mobile_number">
                                </div>
                            </div>
                            <div class="col-xs-12 col-sm-12 col-md-12 col-lg-6">
                                <div class="mb-3">
                                    <label for="number_of_rooms" class="form-label">number of rooms</label>
                                    <input type="number" class="form-control form-control-lg" id="number_of_rooms" name="number_of_rooms">
                                </div>
                            </div>
                            <div class="col-xs-12 col-sm-12 col-md-12 col-lg-6">
                                <div class="mb-5">
                                    <label for="current_lease_period" class="form-label">current lease period</label>
                                    <input type="date" class="form-control form-control-lg" id="current_lease_period" name="current_lease_period">
                                </div>
                            </div>
                            <div class="col-xs-12 col-sm-12 col-md-12 col-lg-6">
                                <button type="submit" class="btn btn-lg mb-4">Update</button>
                            </div>
                            <div class="col-xs-12 col-sm-12 col-md-12 col-lg-6">
                                <button type="reset" class="btn btn-lg">Reset</button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
{% endblock %}
</code>```

Body:
I am trying to perform update operation in Django. Actually what I need when I click the update button of an existing entry it should load in an another form with the data and once I change the details need to save it. I have referred a video with same requirement but that code is not working for me. Please help me I am really stuck.

These are my files and code details.

forms.py

from .models import Building
from django.forms import ModelForm

class BuildingForm(ModelForm):
    class Meta:
        model = Building
        fields = '__all__'

models.py

from django.db import models

# Create your models here.
class BuildingType(models.Model):
   building_type = models.CharField(max_length=100)

   def __str__(self):
       return self.building_type

class Building(models.Model):
    building_name = models.CharField(max_length=50)
    name_of_owner = models.CharField(max_length=50)
    building_type = models.ForeignKey(BuildingType, on_delete=models.CASCADE)
    number_of_rooms = models.IntegerField()
    mobile_number = models.IntegerField()
    current_lease_period = models.DateField()

urls.py

from django.urls import path
from . import views

urlpatterns = [
    path('', views.Home, name='home'),
    path('buildings', views.Buildings, name='buildings'),
    path('rooms', views.Rooms, name='rooms'),
    path('customers', views.Customers, name='customers'),
    path('receipts', views.Receipts, name='receipts'),
    path('new_building', views.NewBuilding, name='new_building'),
    path('update/<int:bldg_id>', views.UpdateBuilding, name='update_building'),
    path('delete_building/<int:bldg_id>', views.DeleteBuilding, name='delete_building'),
    path('new_room', views.NewRoom, name='new_room'),
    path('new_customer', views.NewCustomer, name='new_customer'),
    path('new_receipt', views.NewReceipt, name='new_receipt'),
    path('login', views.Login, name='login'),
    path('signup', views.Signup, name='signup'),
]

views.py

from django.shortcuts import render, redirect
from .forms import BuildingForm
from webapp.models import Building, BuildingType

# Create your views here.

def Home(request):
    return render(request, 'index.html', {'context':'null'})

def Buildings(request):
    building_list = Building.objects.all()
    return render(request, 'buildings.html', {'context': 'Buildings', 'building_list': building_list})

def Rooms(request):
    return render(request, 'rooms.html', {'context':'Rooms'})

def Customers(request):
    return render(request, 'customers.html', {'context':'Customers'})

def Receipts(request):
    return render(request, 'receipts.html', {'context':'Receipts'})

# New Building
def NewBuilding(request):
    bldg_type = BuildingType.objects.all()
    form = BuildingForm()
    if request.method == "POST":
        form = BuildingForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('buildings')
        else:
            form = BuildingForm()
    return render(request, 'new_building.html', {'context':'NewBuilding', 'bldg_type':bldg_type, 'form':form})
**
# Update Building
def UpdateBuilding(request, bldg_id):
    bldg_type = BuildingType.objects.all()
    Update_building = Building.objects.get(id=bldg_id)
    form = BuildingForm(instance=Update_building)
    return render(request, 'update_building.html', {'context':'UpdateBuilding', 'bldg_type':bldg_type, 'form':form})**

# Delete Building
def DeleteBuilding(request, bldg_id):
    building_list = Building.objects.all()
    if request.method == "POST":
        bldg=Building.objects.get(id=bldg_id)
        bldg.delete()
        return redirect('buildings')
    return render(request, 'buildings.html', {'building_list':building_list})

def NewRoom(request):
    return render(request, 'new_room.html', {'context':'NewRoom'})

def NewCustomer(request):
    return render(request, 'new_customer.html', {'context':'NewCustomer'})

def NewReceipt(request):
    return render(request, 'new_receipt.html', {'context':'NewReceipt'})

def Login(request):
    return render(request, 'login.html')

def Signup(request):
    return render(request, 'signup.html')

buildings.html

{% extends 'base.html' %}
{% load static %}

{% block title %} Buildings {% endblock %}

{% block content %}

                            <form action="" class="d-flex gap-3">
                                <input type="text" class="form-control form-control-lg" id="search" >
                                <button type="submit" class="btn btn-lg search">Search</button>
                            </form>

                                Building Name
                                Building Type
                                Rooms
                                Owner Name
                                Mobile Number
                                Lease Period
                                Actions

                            {% for list in building_list %}

                                {{list.building_name}}
                                {{list.building_type}}
                                {{list.number_of_rooms}}
                                {{list.name_of_owner}}
                                {{list.mobile_number}}
                                {{list.current_lease_period}}

                                    Update
                                    <form action="{% url 'delete_building' list.id %}" method="post">
                                        {% csrf_token %}
                                        <input type="submit" value="Delete" class="btn delete">
                                    </form>

                            {% endfor %}

{% endblock %}

update_building.html

{% extends 'base.html' %}
{% load static %}

{% block title %} UpdateBuilding {% endblock %}

{% block content %}

Update Building

                    <form method="post" autocomplete="off">
                        {% csrf_token %}

                                    building name
                                    <input type="text" class="form-control form-control-lg" id="building_name" name="building_name" >

                                    name of owner
                                    <input type="text" class="form-control form-control-lg" id="name_of_owner" name="name_of_owner" >

                                building type
                                <select class="form-select form-select-lg mb-3" aria-label=".form-select-lg example" id="building_type" name="building_type">
                                    <option selected>select</option>
                                    {% for type in bldg_type %}
                                    <option value="{{type.id}}">{{type.building_type}}</option>
                                    {% endfor%}
                                </select>

                                    mobile number
                                    <input type="number" class="form-control form-control-lg" id="mobile_number" name="mobile_number">

                                    number of rooms
                                    <input type="number" class="form-control form-control-lg" id="number_of_rooms" name="number_of_rooms">

                                    current lease period
                                    <input type="date" class="form-control form-control-lg" id="current_lease_period" name="current_lease_period">

                                <button type="submit" class="btn btn-lg mb-4">Update</button>

                                <button type="reset" class="btn btn-lg">Reset</button>

                    </form>

{% endblock %}


问:
Can it be true that D* Lite re-planning around an obstacles requires finding the g-values of lots of nodes adjacent to the original path?
I believe this is a half-theoretical, half-practical question as I'm working with a D* Lite planner in C++, but there'll be no code in this post, of course. Sorry in advance for perhaps not using the precisely correct technical terms ^^

D* Lite finds a path by expanding nodes backwards (aka. from goal to start) and at the end we have something as the example below. The nodes that form the shortest path have been expanded and has a rhs- and g-value (I have just given them numbers to highlight them). The (x) nodes have rhs-values since they had updateVertex called on them as they were neighbors to the nodes that formed the shortest path, but no g-values yet as they were not the nodes with the smallest keys.

Now, a path have been found from start to goal, however, suddenly an obstacle appear at (1), right in front of start before a move to start it made. So re-planning is initiated (I know that D* Lite normally move first after a path is found before scanning for changes, but for testing purposes I reset start to the original position so I can compare results).
What happens in my program is that the re-planning produce a result like this:

The numbered route (1-8) is the actual route that my program ends up choosing, (*) are nodes with an rhs- and g-value (besides the route), and (x) nodes are have an rhs-value but a g-value of infinity.

What this post is about and what I'm not sure about is this: (My) D* Lite starts by updating the start node and the (Obs) node, as expected, but then it proceed to move along all the nodes adjacent to the original path (starting down around goal), aka. the (*) nodes. And I'm not sure if this is how D star Lite is supposed to work or not?

And that's basically what I'm wondering about. Whether this is how D* Lite is supposed to work or if I've missed something?
On a small map like this it's no problem, but on larger maps having to basically double the amount of nodes with rhs- and g-values adds up in the time required.

I'm not sure what to think, D* Lite is not as intuitive A* or such. I'm not sure whether my test is built on a bad example. Or whether it has something to do with the fact that it's equally 'cheap' to move along the side of the original path and then move inwards as it is to move inwards first...

Any help would be appreciated.


问:
React Native App - java.lang.RuntimeException: Unable to create application
Everything was working perfectly until suddenly, app won't launch after a new build yarn android

The logcat output the error

```<code>2023-01-13 15:56:54.711 16596-16596/com.AppName E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.AppName, PID: 16596
    java.lang.RuntimeException: Unable to create application com.AppName.MainApplication: java.lang.RuntimeException: Requested enabled DevSupportManager, but BridgeDevSupportManager class was not found or could not be created
        at android.app.ActivityThread.handleBindApplication(ActivityThread.java:6717)
        ...
     Caused by: java.lang.RuntimeException: Requested enabled DevSupportManager, but BridgeDevSupportManager class was not found or could not be created
        at com.facebook.react.devsupport.DefaultDevSupportManagerFactory.create(DefaultDevSupportManagerFactory.java:96)
        ...
     Caused by: java.lang.reflect.InvocationTargetException
        at java.lang.reflect.Constructor.newInstance0(Native Method)
        ...
     Caused by: java.lang.NoClassDefFoundError: Failed resolution of: Lcom/facebook/react/R$string;
        at com.facebook.react.devsupport.BridgeDevSupportManager.<init>(BridgeDevSupportManager.java:116)
        ...
     Caused by: java.lang.ClassNotFoundException: Didn't find class "com.facebook.react.R$string" on path: DexPathList[[zip file "/data/app/~~6UiPPKy-7vbnQlVazFd7pg==/com.AppName-Xr75vbn7O2Cqnb6GFLQDEw==/base.apk"],nativeLibraryDirectories=[/data/app/~~6UiPPKy-7vbnQlVazFd7pg==/com.AppName-Xr75vbn7O2Cqnb6GFLQDEw==/lib/x86, /data/app/~~6UiPPKy-7vbnQlVazFd7pg==/com.AppName-Xr75vbn7O2Cqnb6GFLQDEw==/base.apk!/lib/x86, /system/lib, /system_ext/lib]]
        at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:207)
        ...
</code>```

I have been stuck on this since 3days now, and no solution from all search seem to work. Any help will be appreciated.

Body:
Everything was working perfectly until suddenly, app won't launch after a new build yarn android

The logcat output the error

2023-01-13 15:56:54.711 16596-16596/com.AppName E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.AppName, PID: 16596
    java.lang.RuntimeException: Unable to create application com.AppName.MainApplication: java.lang.RuntimeException: Requested enabled DevSupportManager, but BridgeDevSupportManager class was not found or could not be created
        at android.app.ActivityThread.handleBindApplication(ActivityThread.java:6717)
        ...
     Caused by: java.lang.RuntimeException: Requested enabled DevSupportManager, but BridgeDevSupportManager class was not found or could not be created
        at com.facebook.react.devsupport.DefaultDevSupportManagerFactory.create(DefaultDevSupportManagerFactory.java:96)
        ...
     Caused by: java.lang.reflect.InvocationTargetException
        at java.lang.reflect.Constructor.newInstance0(Native Method)
        ...
     Caused by: java.lang.NoClassDefFoundError: Failed resolution of: Lcom/facebook/react/R$string;
        at com.facebook.react.devsupport.BridgeDevSupportManager.<init>(BridgeDevSupportManager.java:116)
        ...
     Caused by: java.lang.ClassNotFoundException: Didn't find class "com.facebook.react.R$string" on path: DexPathList[[zip file "/data/app/~~6UiPPKy-7vbnQlVazFd7pg==/com.AppName-Xr75vbn7O2Cqnb6GFLQDEw==/base.apk"],nativeLibraryDirectories=[/data/app/~~6UiPPKy-7vbnQlVazFd7pg==/com.AppName-Xr75vbn7O2Cqnb6GFLQDEw==/lib/x86, /data/app/~~6UiPPKy-7vbnQlVazFd7pg==/com.AppName-Xr75vbn7O2Cqnb6GFLQDEw==/base.apk!/lib/x86, /system/lib, /system_ext/lib]]
        at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:207)
        ...

I have been stuck on this since 3days now, and no solution from all search seem to work. Any help will be appreciated.


问:
How to upgrade gcc compiler
I have gcc 6.3.0 and to run tensorflow 2.11.0 along with cuda 11.2, I require gcc version 9.3.1, but I just cannot find a simple and straightforward way to do that. Some people say install mysys, other sites point to sourceforge download link, while download links on mingw site point to github repos, I just don't understand how to upgrade this thing. It would be really helpful if someone could explain it like you are explaining it to complete newbie, step by step.

Last time, I downloaded mysys2 because someone told that it will automatically upgrade gcc to latest version, mysys2 came with a python 3.10, and I was working with python 3.9, and it created a lot of issues, later I had to reset my pc. That's way I just want to know the direct way to upgrade this thing instead of upgrading other software. I also tried by downloading mingw, but the installer available on sourceforge gives gcc 6.3.0 and not the latest gcc. And what is this cygwin which gives unix like environment, why do i require unix like environment. Even if cygwin can do it easily, I am hesitant to download cygwin, cause i don't want another repeat of tragedy that happened due to mysys2, afterall, installing a complete set of programs that i don't know anything about and will probably never use will only create additional errors.

Title: How to upgrade gcc compiler


问:
Next.Js - Uncaught (in promise) Error: Cancel rendering route
I am trying to create basic authentication and route protection for pages in Next.Js, before I start connecting them to the backend (Express.Js).

However I am getting this error:

```<code>Uncaught (in promise) Error: Cancel rendering route
</code>```

I have 2 layouts, Main Layout, which renders the PageHeader, SideBar and the content of the page, and Login layout, which only renders PageHeader and Login Form.

It tells me that the problem is in useUserSession.tsx, but I have no idea what is the error.

My useUserSession.tsx looks like this:

```<code>    import { useRouter } from "next/router"
import { useCallback, useState } from "react"

const useUserSession = () => {

    const[username, setUsername] = useState<any>()
    const[userLoggedIn, setUserLoggedIn] = useState<any>()
    const router = useRouter();

    const login = useCallback(() => {

        setUsername('Admin');
        setUserLoggedIn(true);
        router.push("/")

    }, [])

    const loggout = useCallback(() => {
        setUsername('');
        setUserLoggedIn(false);
        router.push("/login")
    }, [])

    return {username, userLoggedIn, login, loggout }
}

export default useUserSession
</code>```

And my userSession looks like this:

```<code>    import React, { createContext } from 'react'

const userSession = createContext({
    isLoggedIn: false,
    username: String,

    login: () => {

    },

    loggout: () => {

    }
})

export default userSession;
</code>```

My _app.tsx

```<code>import { useContext, useEffect } from 'react';
import { useRouter } from 'next/router';

export default function App({ Component, pageProps }: AppPropsWithLayout) {

    const getLayout = Component.getLayout ?? ((page) => page)

    const { username, userLoggedIn ,login, loggout } = useUserSession();

    return getLayout(
        <userSession.Provider value={{isLoggedIn: userLoggedIn, username, login: login, loggout}} >

            <Component {...pageProps} />

        </userSession.Provider>

    )
}
</code>```

My MainLayout.tsx

```<code>    function MainLayout({children} : {children: ReactNode}) {

    const { username, userLoggedIn ,login, loggout } = useUserSession();

    return (
        <userSession.Provider value={{isLoggedIn: userLoggedIn, username, login: login, loggout}} >
            <PageHeader/>
            <UserSideBar/>
            <div className="pageContent">
                {children}
            </div>
        </userSession.Provider >

    )
}

export default MainLayout
</code>```

My LoginLayout.tsx

```<code>function LoginRegisterLayout({children} : {children: ReactNode}) {
    const { username, userLoggedIn ,login, loggout } = useUserSession();

    return (
        <userSession.Provider  value={{isLoggedIn: userLoggedIn, username, login: login, loggout}} >
            <PageHeader/>
            {children}
        </userSession.Provider>

    )
}

export default LoginRegisterLayout
</code>```

And this is my Login.tsx

```<code>const Login: PageWithLayout = () =>{

    const errorMessagesClass = `${styles.disabled}`;
    const userSessionData = useContext(userSession);

    return (
        <div className={styles.LoginPage}>
            <div className={styles.LoginForm}>
                <h1>Login</h1>
                <form>
                    <div className={styles.LoginFormInputs}>
                        <div>
                            <label htmlFor='usernameInput'>Username or Email: </label>
                            <input type={'text'} id='usernameInput'></input>
                        </div>
                        <div>
                            <label htmlFor='passwordInput'>Password: </label>
                            <input type={'password'} id='passwordInput'/>
                        </div>
                    </div>
                    <div className={`${styles.ErrorMessages} ${errorMessagesClass}`}>

                    </div>
                    <button type='submit' >Login in to your account</button>
                    <Link href="#" onClick={userSessionData.login}>login</Link>
                </form>
                <p className={styles.FormFooter}>Don't have a profile ?
                    <Link href='/register'>Create one now
                        <i className="fa-solid fa-user-plus"></i>
                    </Link>
                </p>

            </div>
        </div>
    )
}

Login.getLayout = function getLayout(page: ReactElement){
    return(
        <LoginRegisterLayout>
            {page}
        </LoginRegisterLayout>
    )
}

export default Login
</code>```

And this is my Index.tsx that the user can visit only when he has logged in.

```<code>const Home: PageWithLayout = () => {

    const userSessionData = useContext(userSession);
    const router = useRouter();

    useEffect(() => {
        if(!userSessionData.isLoggedIn){
            router.push("/login");
        }
    }, [])

    return (
        <>
            <Head>
                <title>Kiwi | Home page</title>
                <meta name="description" content="Generated by create next app" />
                <meta name="viewport" content="width=device-width, initial-scale=1" />
                <link rel="icon" href="/favicon.ico" />
            </Head>

            <div className={styles.NewPostContainer} id="NewPostContainer">
                <div className={styles.NewPostFormContainer} id="textAreaContainer">
                    <Image src='/images/user_icon.png' width="512" height="512" alt='User profile image'/>
                    <textarea id='newPostForm' onChange={changeFormHeight}/>
                </div>
                <div className={styles.NewPostToolbar}>
                    <p></p>
                    <button>Post</button>

                </div>

            </div>
            <div className='ContentContainer'>

                <Post/>

            </div>
        </>
    )
}

Home.getLayout = function getLayout(page: ReactElement){
    return(
        <MainLayout>
            {page}
        </MainLayout>
    )
}

export default Home
</code>```

Body:
I am trying to create basic authentication and route protection for pages in Next.Js, before I start connecting them to the backend (Express.Js).

However I am getting this error:

Uncaught (in promise) Error: Cancel rendering route

I have 2 layouts, Main Layout, which renders the PageHeader, SideBar and the content of the page, and Login layout, which only renders PageHeader and Login Form.

It tells me that the problem is in useUserSession.tsx, but I have no idea what is the error.

My useUserSession.tsx looks like this:

    import { useRouter } from "next/router"
import { useCallback, useState } from "react"

const useUserSession = () => {

    const[username, setUsername] = useState<any>()
    const[userLoggedIn, setUserLoggedIn] = useState<any>()
    const router = useRouter();

    const login = useCallback(() => {

        setUsername('Admin');
        setUserLoggedIn(true);
        router.push("/")

    }, [])

    const loggout = useCallback(() => {
        setUsername('');
        setUserLoggedIn(false);
        router.push("/login")
    }, [])

    return {username, userLoggedIn, login, loggout }
}

export default useUserSession

And my userSession looks like this:

    import React, { createContext } from 'react'

const userSession = createContext({
    isLoggedIn: false,
    username: String,

    login: () => {

    },

    loggout: () => {

    }
})

export default userSession;

My _app.tsx

import { useContext, useEffect } from 'react';
import { useRouter } from 'next/router';

export default function App({ Component, pageProps }: AppPropsWithLayout) {

    const getLayout = Component.getLayout ?? ((page) => page)

    const { username, userLoggedIn ,login, loggout } = useUserSession();

    return getLayout(
        <userSession.Provider value={{isLoggedIn: userLoggedIn, username, login: login, loggout}} >

            <Component {...pageProps} />

        </userSession.Provider>

    )
}

My MainLayout.tsx

    function MainLayout({children} : {children: ReactNode}) {

    const { username, userLoggedIn ,login, loggout } = useUserSession();

    return (
        <userSession.Provider value={{isLoggedIn: userLoggedIn, username, login: login, loggout}} >
            <PageHeader/>
            <UserSideBar/>

                {children}

        </userSession.Provider >

    )
}

export default MainLayout

My LoginLayout.tsx

function LoginRegisterLayout({children} : {children: ReactNode}) {
    const { username, userLoggedIn ,login, loggout } = useUserSession();

    return (
        <userSession.Provider  value={{isLoggedIn: userLoggedIn, username, login: login, loggout}} >
            <PageHeader/>
            {children}
        </userSession.Provider>

    )
}

export default LoginRegisterLayout

And this is my Login.tsx

const Login: PageWithLayout = () =>{

    const errorMessagesClass = `${styles.disabled}`;
    const userSessionData = useContext(userSession);

    return (

Login

                <form>

                            Username or Email:
                            <input type={'text'} id='usernameInput'></input>

                            Password:
                            <input type={'password'} id='passwordInput'/>

                    <div className={`${styles.ErrorMessages} ${errorMessagesClass}`}>

                    <button type='submit' >Login in to your account</button>
                    <Link href="#" onClick={userSessionData.login}>login</Link>
                </form>

Don't have a profile ?
                    <Link href='/register'>Create one now

                    </Link>

    )
}

Login.getLayout = function getLayout(page: ReactElement){
    return(
        <LoginRegisterLayout>
            {page}
        </LoginRegisterLayout>
    )
}

export default Login

And this is my Index.tsx that the user can visit only when he has logged in.

const Home: PageWithLayout = () => {

    const userSessionData = useContext(userSession);
    const router = useRouter();

    useEffect(() => {
        if(!userSessionData.isLoggedIn){
            router.push("/login");
        }
    }, [])

    return (
        <>

                <title>Kiwi | Home page</title>
                <meta name="description" content="Generated by create next app" />
                <meta name="viewport" content="width=device-width, initial-scale=1" />
                <link rel="icon" href="/favicon.ico" />

                    <Image src='/images/user_icon.png' width="512" height="512" alt='User profile image'/>
                    <textarea id='newPostForm' onChange={changeFormHeight}/>

                    <button>Post</button>

                <Post/>

        </>
    )
}

Home.getLayout = function getLayout(page: ReactElement){
    return(
        <MainLayout>
            {page}
        </MainLayout>
    )
}

export default Home


问:
Can I parallelize a (python) class method using dask when the method modifies a class attribute?
I am trying to parallelize a class method that modifies an attribute of the class.

As I understand it, this requires the attribute to be a shared memory object. If possible, I would like to use the dask library to perform this task, due to its easy ability to switch between single-threaded and distributed schedulers. My application also uses pytorch, so ideally native tensor operations would be used, but this is not strictly necessary as I can always convert to/from tensors.

Here is a toy example of what I am trying to do:

```<code>import torch
import torch.multiprocessing as mp
from dask import compute, delayed
from dask.distributed import Client
import numpy as np
import time

class ToyExample:
    def __init__(self, array):
        self.array = torch.from_numpy(array).share_memory_()
        self.result = torch.zeros(1).share_memory_()

    def serial_method(self, start, end):
        time.sleep(5)
        with mp.Lock():
            self.result += torch.sum(self.array[start:end])

    def parallel_method(self):
        client = Client(processes=True)
        delayed_results = [delayed(self.serial_method)(i, i + 1000) for i in range(0, len(self.array), 1000)]
        compute(*delayed_results)

def main():
    t0 = time.time()
    array = np.random.rand(10000)
    obj = ToyExample(array)
    obj.parallel_method()
    print(obj.result)
    print('Time elapsed: ', time.time() - t0)

if __name__ == '__main__':
    main()
</code>```

However, this does not actually update the "result" attribute. Is there a way to fix this?

If this cannot be done (or done efficiently) using dask, I would also appreciate suggestions using other parallel libraries.

Thanks in advance!

Body:
I am trying to parallelize a class method that modifies an attribute of the class.

As I understand it, this requires the attribute to be a shared memory object. If possible, I would like to use the dask library to perform this task, due to its easy ability to switch between single-threaded and distributed schedulers. My application also uses pytorch, so ideally native tensor operations would be used, but this is not strictly necessary as I can always convert to/from tensors.

Here is a toy example of what I am trying to do:

import torch
import torch.multiprocessing as mp
from dask import compute, delayed
from dask.distributed import Client
import numpy as np
import time

class ToyExample:
    def __init__(self, array):
        self.array = torch.from_numpy(array).share_memory_()
        self.result = torch.zeros(1).share_memory_()

    def serial_method(self, start, end):
        time.sleep(5)
        with mp.Lock():
            self.result += torch.sum(self.array[start:end])

    def parallel_method(self):
        client = Client(processes=True)
        delayed_results = [delayed(self.serial_method)(i, i + 1000) for i in range(0, len(self.array), 1000)]
        compute(*delayed_results)

def main():
    t0 = time.time()
    array = np.random.rand(10000)
    obj = ToyExample(array)
    obj.parallel_method()
    print(obj.result)
    print('Time elapsed: ', time.time() - t0)

if __name__ == '__main__':
    main()

However, this does not actually update the "result" attribute. Is there a way to fix this?

If this cannot be done (or done efficiently) using dask, I would also appreciate suggestions using other parallel libraries.

Thanks in advance!