问:
Problem with @Autowired in JUnit Test on a Spring MVC project
Hi guys so here are my JUnit Test Class which doesn't get to autowire my DAO Class.
Bellow are my classes and the xml file for the MVC configuration:

```<code>
import java.util.List;

import org.springframework.stereotype.Component;

import com.luv2code.springdemo.entity.Address;

public interface AddressDAO {

    public List<Address> findAllAdrressesOfCustomer(int customerId);

}
</code>```

```<code>package com.luv2code.springdemo.dao;

import java.util.Arrays;
import java.util.List;

import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;

import com.luv2code.springdemo.entity.Address;

@Repository
public class AdrressDAOImpl implements AddressDAO {

    @Override
    public List<Address> findAllAdrressesOfCustomer(int customerId) {
        Address myAddress=new Address(6,"Mainstreet","12A","USA","Los Angeles","Los Angeles","41221") ;
        return Arrays.asList(myAddress);
    }

}
</code>```

Here my Junit class that I want to use in order to test my AdressDAOImpl class:

```<code>package com.luv2code.springdemo.test;

import static org.junit.Assert.assertTrue;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;

import com.luv2code.springdemo.dao.AddressDAO;
import com.luv2code.springdemo.dao.CustomerDAO;

@WebAppConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath*:spring-mvc-crud-demo-servlet_test.xml")
public class AddressDaoLayerTester {

    @Autowired
    AddressDAO myAddressDao;

    @Test
    public void testFindAllById() {
        assertTrue(!myAddressDao.findAllAdrressesOfCustomer(1).isEmpty());

    }

}

</code>```

and here my xml configuration file:

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!-- Add support for component scanning -->
    <context:component-scan base-package="com.luv2code.springdemo" />

    <!-- Add support for conversion, formatting and validation support -->
    <mvc:annotation-driven/>

    <!-- Define Spring MVC view resolver -->
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/view/" />
        <property name="suffix" value=".jsp" />
    </bean>

    <!-- Step 1: Define Database DataSource / connection pool -->
    <bean id="myDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
          destroy-method="close">
        <property name="driverClass" value="com.mysql.jdbc.Driver" />
        <property name="jdbcUrl" value="jdbc:mysql://localhost:6703/my_first_db?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true" />
        <property name="user" value="root" />
        <property name="password" value="24081983" />

        <!-- these are connection pool properties for C3P0 -->
        <property name="minPoolSize" value="5" />
        <property name="maxPoolSize" value="20" />
        <property name="maxIdleTime" value="30000" />
    </bean>

    <!-- Step 2: Setup Hibernate session factory -->
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <property name="dataSource" ref="myDataSource" />
        <property name="packagesToScan" value="com.luv2code.springdemo.entity" />
        <property name="hibernateProperties">
           <props>
              <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
              <prop key="hibernate.show_sql">true</prop>
           </props>
        </property>
   </bean>

    <!-- Step 3: Setup Hibernate transaction manager -->
    <bean id="myTransactionManager"
            class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>

    <!-- Step 4: Enable configuration of transactional behavior based on annotations -->
    <tx:annotation-driven transaction-manager="myTransactionManager" />

    <!-- Add support for reading web resources: css, images, js, etc ... -->
    <mvc:resources location="/resources/" mapping="/resources/**"></mvc:resources>

</beans>

</code>```

So now comes my Problem, when I go ahead and call the class AddressDaoLayerTester I get the following stacktrace:

```<code>org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.luv2code.springdemo.test.AddressDaoLayerTester': Unsatisfied dependency expressed through field 'myAddressDao'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.luv2code.springdemo.dao.AddressDAO' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:643)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:116)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:399)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1422)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:393)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:119)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:244)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:227)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:246)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
    at org.junit.vintage.engine.execution.RunnerExecutor.execute(RunnerExecutor.java:40)
    at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:183)
    at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:195)
    at java.base/java.util.Iterator.forEachRemaining(Iterator.java:133)
    at java.base/java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801)
    at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484)
    at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
    at java.base/java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:150)
    at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:173)
    at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
    at java.base/java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:497)
    at org.junit.vintage.engine.VintageTestEngine.executeAllChildren(VintageTestEngine.java:80)
    at org.junit.vintage.engine.VintageTestEngine.execute(VintageTestEngine.java:71)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:229)
    at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$6(DefaultLauncher.java:197)
    at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:211)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:191)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:137)
    at org.eclipse.jdt.internal.junit5.runner.JUnit5TestReference.run(JUnit5TestReference.java:89)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:542)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:770)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:464)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:210)
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.luv2code.springdemo.dao.AddressDAO' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1695)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1253)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1207)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:640)
    ... 48 more
</code>```

I also provide here the structure of my project:

Obviously the stacktrace says that Spring can not autowire the AddressDAO class because he cannot find it, although it is there and it is correctly annotated.
Do you have any suggestion about the reasons that could cause this problem?

答:
Try to use @Mock anotation instead of @Autowired. Also to test your repository you should stub your expected results:</p>

```<code>when(myAddressDao.findAllAdrressesOfCustomer("id").thenReturn("your expected rusult")
</code>```

Body:
Hi guys so here are my JUnit Test Class which doesn't get to autowire my DAO Class.
Bellow are my classes and the xml file for the MVC configuration:

import java.util.List;

import org.springframework.stereotype.Component;

import com.luv2code.springdemo.entity.Address;

public interface AddressDAO {

    public List<Address> findAllAdrressesOfCustomer(int customerId);

}

package com.luv2code.springdemo.dao;

import java.util.Arrays;
import java.util.List;

import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;

import com.luv2code.springdemo.entity.Address;

@Repository
public class AdrressDAOImpl implements AddressDAO {

    @Override
    public List<Address> findAllAdrressesOfCustomer(int customerId) {
        Address myAddress=new Address(6,"Mainstreet","12A","USA","Los Angeles","Los Angeles","41221") ;
        return Arrays.asList(myAddress);
    }

}

Here my Junit class that I want to use in order to test my AdressDAOImpl class:

package com.luv2code.springdemo.test;

import static org.junit.Assert.assertTrue;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;

import com.luv2code.springdemo.dao.AddressDAO;
import com.luv2code.springdemo.dao.CustomerDAO;

@WebAppConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath*:spring-mvc-crud-demo-servlet_test.xml")
public class AddressDaoLayerTester {

    @Autowired
    AddressDAO myAddressDao;

    @Test
    public void testFindAllById() {
        assertTrue(!myAddressDao.findAllAdrressesOfCustomer(1).isEmpty());

    }

}

and here my xml configuration file:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd">

    <context:component-scan base-package="com.luv2code.springdemo" />

    <mvc:annotation-driven/>

    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/view/" />
        <property name="suffix" value=".jsp" />
    </bean>

    <bean id="myDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
          destroy-method="close">
        <property name="driverClass" value="com.mysql.jdbc.Driver" />
        <property name="jdbcUrl" value="jdbc:mysql://localhost:6703/my_first_db?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true" />
        <property name="user" value="root" />
        <property name="password" value="24081983" />

        <property name="minPoolSize" value="5" />
        <property name="maxPoolSize" value="20" />
        <property name="maxIdleTime" value="30000" />
    </bean>

    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <property name="dataSource" ref="myDataSource" />
        <property name="packagesToScan" value="com.luv2code.springdemo.entity" />
        <property name="hibernateProperties">
           <props>
              <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
              <prop key="hibernate.show_sql">true</prop>
           </props>
        </property>
   </bean>

    <bean id="myTransactionManager"
            class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>

    <tx:annotation-driven transaction-manager="myTransactionManager" />

    <mvc:resources location="/resources/" mapping="/resources/**"></mvc:resources>

</beans>

So now comes my Problem, when I go ahead and call the class AddressDaoLayerTester I get the following stacktrace:

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.luv2code.springdemo.test.AddressDaoLayerTester': Unsatisfied dependency expressed through field 'myAddressDao'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.luv2code.springdemo.dao.AddressDAO' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:643)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:116)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:399)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1422)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:393)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:119)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:244)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:227)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:246)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
    at org.junit.vintage.engine.execution.RunnerExecutor.execute(RunnerExecutor.java:40)
    at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:183)
    at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:195)
    at java.base/java.util.Iterator.forEachRemaining(Iterator.java:133)
    at java.base/java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801)
    at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484)
    at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
    at java.base/java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:150)
    at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:173)
    at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
    at java.base/java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:497)
    at org.junit.vintage.engine.VintageTestEngine.executeAllChildren(VintageTestEngine.java:80)
    at org.junit.vintage.engine.VintageTestEngine.execute(VintageTestEngine.java:71)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:229)
    at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$6(DefaultLauncher.java:197)
    at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:211)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:191)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:137)
    at org.eclipse.jdt.internal.junit5.runner.JUnit5TestReference.run(JUnit5TestReference.java:89)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:542)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:770)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:464)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:210)
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.luv2code.springdemo.dao.AddressDAO' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1695)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1253)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1207)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:640)
    ... 48 more

I also provide here the structure of my project:

Obviously the stacktrace says that Spring can not autowire the AddressDAO class because he cannot find it, although it is there and it is correctly annotated.
Do you have any suggestion about the reasons that could cause this problem?

Body:
Try to use @Mock anotation instead of @Autowired. Also to test your repository you should stub your expected results:

when(myAddressDao.findAllAdrressesOfCustomer("id").thenReturn("your expected rusult")


来源: stackexchange

问:
Ask about char in array
example

```<code>char names[2][5] = {"john","boy"};
</code>```

I want to ask about char 2 dimension array in c, in [2] i mean, it's explaining about total element of array, and [5] i mean, it's explaining about length of character in array

So, is it true how to use array 2 dimension in c ?

Sorry for my bad english

答:
A multidimensional array is an array elements of which are in turn arrays.

Let's consider your declaration

```<code>char names[2][5] = {"john","boy"};
</code>```

You can introduce a type alias like

```<code>typedef char T[5];
</code>```

so the name T is an alias for the type char[5].

Now your initial declaration may be rewritten like

```<code>T names[2] = {"john","boy"};
</code>```

That is you have an array of two elements which of them is in turn an array of the type char[5].

String literals are also have types of character arrays. For example the string literal  "John" can be represented like

```<code>char john[5] = { 'J', 'o', 'h', 'n', '\0' };
</code>```

elements of a string literal are used to initialize a corresponding character array.

So you array is initialized like

```<code>char names[2][5] = { { 'J', 'o', 'h', 'n', '\0' }, { 'b', 'o', 'y', '\0', '\0' } };
</code>```

If a string literal contains less elements than the number of elements of the initialized array then all other elements of the array that have no an explicit initializer will be zero-initialized.

ContentLicense: CC BY-SA 4.0

Title: Ask about char in array

Body:
example

char names[2][5] = {"john","boy"};

I want to ask about char 2 dimension array in c, in [2] i mean, it's explaining about total element of array, and [5] i mean, it's explaining about length of character in array

So, is it true how to use array 2 dimension in c ?

Sorry for my bad english

Body:
A multidimensional array is an array elements of which are in turn arrays.

Let's consider your declaration

char names[2][5] = {"john","boy"};

You can introduce a type alias like

typedef char T[5];

so the name T is an alias for the type char[5].

Now your initial declaration may be rewritten like

T names[2] = {"john","boy"};

That is you have an array of two elements which of them is in turn an array of the type char[5].

String literals are also have types of character arrays. For example the string literal  "John" can be represented like

char john[5] = { 'J', 'o', 'h', 'n', '\0' };

elements of a string literal are used to initialize a corresponding character array.

So you array is initialized like

char names[2][5] = { { 'J', 'o', 'h', 'n', '\0' }, { 'b', 'o', 'y', '\0', '\0' } };

If a string literal contains less elements than the number of elements of the initialized array then all other elements of the array that have no an explicit initializer will be zero-initialized.


问:
Code keeps looping into max call stack error
I am trying to make tic tac toe on a website using javascript. That worked and now I'm trying to make a bot that, then you have 2 area's in a row. It needs to block you. But everytime it does block me, it won't do anything else afterwards, because it keeps looping into the error.

The t-numbers are the tile names, 0 means unoccupied,1 means for player 1, and 2 for player 2.
The t-numbers with a 1 behind it are just the tiles but they mustn't interfere with the functions (they are t-numbers too).

How do I fix this?

```<code>function tbot(){
  while (turn == "player 2") {
    if (t41 == 0 &&
      (t01 == 1 && t81 == 1) ||
      (t11 == 1 && t71 == 1) ||
      (t21 == 1 && t61 == 1) ||
      (t31 == 1 && t51 == 1)
    ) {t4()}

    else {
    var tiles = ['0', '1', '2', '3', '4', '5', '6', '7', '8'];
    var tile = tiles[Math.floor(Math.random()*tiles.length)];
         if (tile == '0' && t01 == 0) {t0()}
    else if (tile == '1' && t11 == 0) {t1()}
    else if (tile == '2' && t21 == 0) {t2()}
    else if (tile == '3' && t31 == 0) {t3()}
    else if (tile == '4' && t41 == 0) {t4()}
    else if (tile == '5' && t51 == 0) {t5()}
    else if (tile == '6' && t61 == 0) {t6()}
    else if (tile == '7' && t71 == 0) {t7()}
    else if (tile == '8' && t81 == 0) {t8()}
  }
  }
}
</code>```

```<code>function update() {
  if (t01 == 1 &&
    ((t11 == 1 && t21 == 1)||(t31 == 1 && t61 == 1))
    ||t41 == 1 &&
    ((t31 == 1 && t51 == 1)||(t11 == 1 && t71 == 1)||
    (t01 == 1 && t81 == 1)||(t21 == 1 && t61 == 1))
    ||t81 == 1 &&
    ((t61 == 1 && t71 == 1)||(t21 == 1 && t51 == 1))
) {
  twin = 1;
  document.getElementById('turnshow').innerHTML = "Player 1 is the winner!";
  document.getElementById('treset').style.backgroundColor = '#888';
  } else if (t01 == 2 &&
    ((t11 == 2 && t21 == 2)||(t31 == 2 && t61 == 2))
    ||t41 == 2 &&
    ((t31 == 2 && t51 == 2)||(t11 == 2 && t71 == 2)||
    (t01 == 2 && t81 == 2)||(t21 == 2 && t61 == 2))
    ||t81 == 2 &&
    ((t61 == 2 && t71 == 2)||(t21 == 2 && t51 == 2))
) {
  twin = 1;
  document.getElementById('turnshow').innerHTML = "Player 2 is the winner!";
  document.getElementById('treset').style.backgroundColor = '#888';
  } else {
  if (bot == 1) {tbot();}
  document.getElementById('turnshow').innerHTML = "It is " + turn + "'s turn!";
  }
}
</code>```

```<code>function t4() {
  if (t41 == 0 && twin == 0) {
  if (turn == "player 1") {
    document.getElementById('t4').style.backgroundColor = p1;
    turn = "player 2";
    t41 = 1;
  } else {
    document.getElementById('t4').style.backgroundColor = p2;
    turn = "player 1";
    t41 = 2;
  }
}
update();
}
</code>```

Body:
I am trying to make tic tac toe on a website using javascript. That worked and now I'm trying to make a bot that, then you have 2 area's in a row. It needs to block you. But everytime it does block me, it won't do anything else afterwards, because it keeps looping into the error.

The t-numbers are the tile names, 0 means unoccupied,1 means for player 1, and 2 for player 2.
The t-numbers with a 1 behind it are just the tiles but they mustn't interfere with the functions (they are t-numbers too).

How do I fix this?

function tbot(){
  while (turn == "player 2") {
    if (t41 == 0 &&
      (t01 == 1 && t81 == 1) ||
      (t11 == 1 && t71 == 1) ||
      (t21 == 1 && t61 == 1) ||
      (t31 == 1 && t51 == 1)
    ) {t4()}

    else {
    var tiles = ['0', '1', '2', '3', '4', '5', '6', '7', '8'];
    var tile = tiles[Math.floor(Math.random()*tiles.length)];
         if (tile == '0' && t01 == 0) {t0()}
    else if (tile == '1' && t11 == 0) {t1()}
    else if (tile == '2' && t21 == 0) {t2()}
    else if (tile == '3' && t31 == 0) {t3()}
    else if (tile == '4' && t41 == 0) {t4()}
    else if (tile == '5' && t51 == 0) {t5()}
    else if (tile == '6' && t61 == 0) {t6()}
    else if (tile == '7' && t71 == 0) {t7()}
    else if (tile == '8' && t81 == 0) {t8()}
  }
  }
}

function update() {
  if (t01 == 1 &&
    ((t11 == 1 && t21 == 1)||(t31 == 1 && t61 == 1))
    ||t41 == 1 &&
    ((t31 == 1 && t51 == 1)||(t11 == 1 && t71 == 1)||
    (t01 == 1 && t81 == 1)||(t21 == 1 && t61 == 1))
    ||t81 == 1 &&
    ((t61 == 1 && t71 == 1)||(t21 == 1 && t51 == 1))
) {
  twin = 1;
  document.getElementById('turnshow').innerHTML = "Player 1 is the winner!";
  document.getElementById('treset').style.backgroundColor = '#888';
  } else if (t01 == 2 &&
    ((t11 == 2 && t21 == 2)||(t31 == 2 && t61 == 2))
    ||t41 == 2 &&
    ((t31 == 2 && t51 == 2)||(t11 == 2 && t71 == 2)||
    (t01 == 2 && t81 == 2)||(t21 == 2 && t61 == 2))
    ||t81 == 2 &&
    ((t61 == 2 && t71 == 2)||(t21 == 2 && t51 == 2))
) {
  twin = 1;
  document.getElementById('turnshow').innerHTML = "Player 2 is the winner!";
  document.getElementById('treset').style.backgroundColor = '#888';
  } else {
  if (bot == 1) {tbot();}
  document.getElementById('turnshow').innerHTML = "It is " + turn + "'s turn!";
  }
}

function t4() {
  if (t41 == 0 && twin == 0) {
  if (turn == "player 1") {
    document.getElementById('t4').style.backgroundColor = p1;
    turn = "player 2";
    t41 = 1;
  } else {
    document.getElementById('t4').style.backgroundColor = p2;
    turn = "player 1";
    t41 = 2;
  }
}
update();
}

Body:
I found what i did wrong. When I was checking if there are two area's selected in a row my code was:

if (t41 == 0 &&
      (t01 == 1 && t81 == 1) ||
      (t11 == 1 && t71 == 1) ||
      (t21 == 1 && t61 == 1) ||
      (t31 == 1 && t51 == 1)
    )

But what that did: t41 and t01 and t81 or t11 and t71 or etc.
I just needed to add "()" around the options :/

if (t41 == 0 &&
      ((t01 == 1 && t81 == 1) ||
      (t11 == 1 && t71 == 1) ||
      (t21 == 1 && t61 == 1) ||
      (t31 == 1 && t51 == 1))
    )


问:
Different CUDA versions shown by nvcc and NVIDIA-smi
I am very confused by the different CUDA versions shown by running which nvcc and nvidia-smi. I have both cuda9.2 and cuda10 installed on my ubuntu 16.04. Now I set the PATH to point to cuda9.2. So when I run

$ which nvcc
/usr/local/cuda-9.2/bin/nvcc
```
<p>However, when I run</p>
```$ nvidia-smi
Wed Nov 21 19:41:32 2018
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 410.72       Driver Version: 410.72       CUDA Version: 10.0     |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|===============================+======================+======================|
|   0  GeForce GTX 106...  Off  | 00000000:01:00.0 Off |                  N/A |
| N/A   53C    P0    26W /  N/A |    379MiB /  6078MiB |      2%      Default |
+-------------------------------+----------------------+----------------------+

+-----------------------------------------------------------------------------+
| Processes:                                                       GPU Memory |
|  GPU       PID   Type   Process name                             Usage      |
|=============================================================================|
|    0      1324      G   /usr/lib/xorg/Xorg                           225MiB |
|    0      2844      G   compiz                                       146MiB |
|    0     15550      G   /usr/lib/firefox/firefox                       1MiB |
|    0     19992      G   /usr/lib/firefox/firefox                       1MiB |
|    0     23605      G   /usr/lib/firefox/firefox                       1MiB |
```

So am I using cuda9.2 as which nvcc suggests, or am I using cuda10 as nvidia-smi suggests? I saw this answer but it does not provide direct answer to the confusion, it just asks us to reinstall the CUDA Toolkit, which I already did.

答:
If you are using cuda 10.2 :

```<code>export PATH=/usr/local/cuda-10.2/bin:/opt/nvidia/nsight-compute/2019.5.0${PATH:+:${PATH}}
</code>```

might help because when I checked, there was no directory for nsight-compute in cuda-10.2.
I am not sure if this was just the problem with me or else why wouldn't they mention it in the official documentation.

Body:
I am very confused by the different CUDA versions shown by running which nvcc and nvidia-smi. I have both cuda9.2 and cuda10 installed on my ubuntu 16.04. Now I set the PATH to point to cuda9.2. So when I run

$ which nvcc
/usr/local/cuda-9.2/bin/nvcc

However, when I run

$ nvidia-smi
Wed Nov 21 19:41:32 2018
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 410.72       Driver Version: 410.72       CUDA Version: 10.0     |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|===============================+======================+======================|
|   0  GeForce GTX 106...  Off  | 00000000:01:00.0 Off |                  N/A |
| N/A   53C    P0    26W /  N/A |    379MiB /  6078MiB |      2%      Default |
+-------------------------------+----------------------+----------------------+

+-----------------------------------------------------------------------------+
| Processes:                                                       GPU Memory |
|  GPU       PID   Type   Process name                             Usage      |
|=============================================================================|
|    0      1324      G   /usr/lib/xorg/Xorg                           225MiB |
|    0      2844      G   compiz                                       146MiB |
|    0     15550      G   /usr/lib/firefox/firefox                       1MiB |
|    0     19992      G   /usr/lib/firefox/firefox                       1MiB |
|    0     23605      G   /usr/lib/firefox/firefox                       1MiB |

So am I using cuda9.2 as which nvcc suggests, or am I using cuda10 as nvidia-smi suggests? I saw this answer but it does not provide direct answer to the confusion, it just asks us to reinstall the CUDA Toolkit, which I already did.

Body:
If you are using cuda 10.2 :

export PATH=/usr/local/cuda-10.2/bin:/opt/nvidia/nsight-compute/2019.5.0${PATH:+:${PATH}}

might help because when I checked, there was no directory for nsight-compute in cuda-10.2.
I am not sure if this was just the problem with me or else why wouldn't they mention it in the official documentation.


问:
Refactor jQuery inview event listener
I want to convert the following code to pure JavaScript.

```<code>$(function () {
    $('h2,.single').on('inview', function () {
        $(this).addClass('is-show');
    });
});
</code>```

I tried much time but still can not figure out how. Any helps?

答:
Inview was an old plugin to solve a problem that now has a web API, as long as you don't need to support IE you can use intersection observer to do this.

Without any example or further explanation of how you need things to function it's hard to guess what you want to achieve. But here's a basic implementation that would mimic the tiny bit of JQuery you provided.

const sections = [].slice.call(document.querySelectorAll(".single"));

function createObserver(el) {
  let observer;

  const options = {
    root: null,
    rootMargin: "0px",
    threshold: 0.5
  };

  observer = new IntersectionObserver(handleIntersect, options);
  observer.observe(el);
}

function handleIntersect(entries, observer) {
  entries.forEach((entry) => {
    let box = entry.target;
    let visible = entry.intersectionRatio;
    if(visible > 0.5) {
      box.classList.add('is-show');
    } else {
      box.classList.remove('is-show');
    }
  });
}

const setup = (sections) => {
  for (let i in sections) {
    const el = sections[i];
    createObserver(el);
  }
}

setup(sections);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.single {
  padding: 2rem;
  background: tomato;
  color: #fff;
  margin: 600px 0;
  transition: all .5s ease-out;
  opacity: 0;
}
.is-show {
  opacity: 1
}</code>```

I'm an H2 Element in frame

I'm an H2 Element in frame

I'm an H2 Element in frame

I'm an H2 Element in frame
```

Title: Refactor jQuery inview event listener

Body:
I want to convert the following code to pure JavaScript.

$(function () {
    $('h2,.single').on('inview', function () {
        $(this).addClass('is-show');
    });
});

I tried much time but still can not figure out how. Any helps?

Body:
Inview was an old plugin to solve a problem that now has a web API, as long as you don't need to support IE you can use intersection observer to do this.

Without any example or further explanation of how you need things to function it's hard to guess what you want to achieve. But here's a basic implementation that would mimic the tiny bit of JQuery you provided.

const sections = [].slice.call(document.querySelectorAll(".single"));

function createObserver(el) {
  let observer;

  const options = {
    root: null,
    rootMargin: "0px",
    threshold: 0.5
  };

  observer = new IntersectionObserver(handleIntersect, options);
  observer.observe(el);
}

function handleIntersect(entries, observer) {
  entries.forEach((entry) => {
    let box = entry.target;
    let visible = entry.intersectionRatio;
    if(visible > 0.5) {
      box.classList.add('is-show');
    } else {
      box.classList.remove('is-show');
    }
  });
}

const setup = (sections) => {
  for (let i in sections) {
    const el = sections[i];
    createObserver(el);
  }
}

setup(sections);

.single {
  padding: 2rem;
  background: tomato;
  color: #fff;
  margin: 600px 0;
  transition: all .5s ease-out;
  opacity: 0;
}
.is-show {
  opacity: 1
}

<h2 class="single">I'm an H2 Element in frame</h2>
<h2 class="single">I'm an H2 Element in frame</h2>
<h2 class="single">I'm an H2 Element in frame</h2>
<h2 class="single">I'm an H2 Element in frame</h2>


问:
ElementNotInteractableException: Element could not be scrolled into view in selenium using python and firefox webdriver
The ElementNotInteractableException is occuring because of link.click(). I understand it is because selenium is not finding the content to scroll but how do i fix this?

```<code>def collect_page(self, page):
    # navigate to page
    self.browser.get(
        'https://www.facebook.com/' + page + '/')

    # Scroll down depth-times and wait delay seconds to load
    # between scrolls
    for scroll in range(self.depth):

        # Scroll down to bottom
        self.browser.execute_script(
            "window.scrollTo(0, document.body.scrollHeight);")

        # Wait to load page
        time.sleep(self.delay)

    print("before open")
    # Once the full page is loaded, we can start scraping
    with open(self.dump, "a+", newline='', encoding="utf-8") as save_file:
        writer = csv.writer(save_file)
        links = self.browser.find_elements_by_link_text("See more")

        print("before for")
        for link in links:
            print("in for loop opening link")
            link.click()
            print("opening link")

        posts = self.browser.find_elements_by_class_name(
            "userContentWrapper")
        poster_names = self.browser.find_elements_by_xpath(
            "//a[@data-hovercard-referer]")

        print("before count")
        for count, post in enumerate(posts):
            # Creating first CSV row entry with the poster name (eg. "Donald Trump")
            analysis = [poster_names[count].text]

            # Creating a time entry.
            time_element = post.find_element_by_css_selector("abbr")
            utime = time_element.get_attribute("data-utime")
            analysis.append(utime)

            # Creating post text entry
            text = post.find_element_by_class_name("userContent").text
            status = self.strip(text)
            analysis.append(status)

            # Write row to csv
            print("writing")

            writer.writerow(analysis)
</code>```

答:
Try with wait for element to be clickable so that element will be loaded properly and able to interact.

```<code>for link in links:
    print("in for loop opening link")
   WebDriverWait(self.browser, 30).until(EC.element_to_be_clickable((By.LINK_TEXT,
   "See more")))
    link.click()
    print("opening link")
</code>```

Body:
The ElementNotInteractableException is occuring because of link.click(). I understand it is because selenium is not finding the content to scroll but how do i fix this?

def collect_page(self, page):
    # navigate to page
    self.browser.get(
        'https://www.facebook.com/' + page + '/')

    # Scroll down depth-times and wait delay seconds to load
    # between scrolls
    for scroll in range(self.depth):

        # Scroll down to bottom
        self.browser.execute_script(
            "window.scrollTo(0, document.body.scrollHeight);")

        # Wait to load page
        time.sleep(self.delay)

    print("before open")
    # Once the full page is loaded, we can start scraping
    with open(self.dump, "a+", newline='', encoding="utf-8") as save_file:
        writer = csv.writer(save_file)
        links = self.browser.find_elements_by_link_text("See more")

        print("before for")
        for link in links:
            print("in for loop opening link")
            link.click()
            print("opening link")

        posts = self.browser.find_elements_by_class_name(
            "userContentWrapper")
        poster_names = self.browser.find_elements_by_xpath(
            "//a[@data-hovercard-referer]")

        print("before count")
        for count, post in enumerate(posts):
            # Creating first CSV row entry with the poster name (eg. "Donald Trump")
            analysis = [poster_names[count].text]

            # Creating a time entry.
            time_element = post.find_element_by_css_selector("abbr")
            utime = time_element.get_attribute("data-utime")
            analysis.append(utime)

            # Creating post text entry
            text = post.find_element_by_class_name("userContent").text
            status = self.strip(text)
            analysis.append(status)

            # Write row to csv
            print("writing")

            writer.writerow(analysis)

Body:
Try with wait for element to be clickable so that element will be loaded properly and able to interact.

for link in links:
    print("in for loop opening link")
   WebDriverWait(self.browser, 30).until(EC.element_to_be_clickable((By.LINK_TEXT,
   "See more")))
    link.click()
    print("opening link")


问:
Create a function that separates the characters of a word by symbols
I want to create a function where, for example, if I put the word visual in the input box I have to select from the ComboBox one of these 3 symbols: space, . , or *, in the output box I want the result of the word visual to come out like this: v.i.s.u.a.l or v i s u a l

I already know how to output a result that separates the string by a space but I don't know how to do it using a ComboBox with 3 symbols

This is the code I used for separating with a space

```<code>Public Class Form1

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim n As Integer
        Dim str As String = "mis programing II"
        Dim str2 As String = ""
        Dim cc As String
        For i = 1 To Len(str)
            cc = Mid(str, i, 1)
            str2 = str2 & cc & " "
        Next
        MsgBox(str2)
    End Sub
End Class
</code>```

答:
You can use String.Join like this:

```<code>Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim str As String = "mis programing II"
    Dim str2 As String = String.Join(str.ToCharArray(), ComboBox1.Text)
    MsgBox(str2)
End Sub
</code>```

I assumed the seperator has been selected in the ComboBox. Else, replace ComboBox1.Text with the seperator you want to use.

Update

Thanks to @JQSOFT, I just confirmed that String.Join does not work on Char arrays. Well here's another solution.

```<code>Dim str As String = "mis programing II"
Dim listX As New List(Of String)
Dim act As Action(Of Char) = Sub(c) listX.Add(CStr(c))
For Each c As Char In str.ToCharArray()
    act.Invoke(c)
Next
Dim str2 As String = String.Join(".", listX.ToArray)
Console.WriteLine(str2)
</code>```

Body:
I want to create a function where, for example, if I put the word visual in the input box I have to select from the ComboBox one of these 3 symbols: space, . , or *, in the output box I want the result of the word visual to come out like this: v.i.s.u.a.l or v i s u a l

I already know how to output a result that separates the string by a space but I don't know how to do it using a ComboBox with 3 symbols

This is the code I used for separating with a space

Public Class Form1

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim n As Integer
        Dim str As String = "mis programing II"
        Dim str2 As String = ""
        Dim cc As String
        For i = 1 To Len(str)
            cc = Mid(str, i, 1)
            str2 = str2 & cc & " "
        Next
        MsgBox(str2)
    End Sub
End Class

Body:
You can use String.Join like this:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim str As String = "mis programing II"
    Dim str2 As String = String.Join(str.ToCharArray(), ComboBox1.Text)
    MsgBox(str2)
End Sub

I assumed the seperator has been selected in the ComboBox. Else, replace ComboBox1.Text with the seperator you want to use.

Update

Thanks to @JQSOFT, I just confirmed that String.Join does not work on Char arrays. Well here's another solution.

Dim str As String = "mis programing II"
Dim listX As New List(Of String)
Dim act As Action(Of Char) = Sub(c) listX.Add(CStr(c))
For Each c As Char In str.ToCharArray()
    act.Invoke(c)
Next
Dim str2 As String = String.Join(".", listX.ToArray)
Console.WriteLine(str2)


问:
Is there any way to customize the UNnotification for local notifications in swift
I am new to Xcode and swift. I want to know that is there any way that we can customize the local notifications. If possible I also want to add a map on the notification.
 Thanks in advance</p>

答:
Thanks for the help.
I tried using the notification extension identifier  and called in the function in the app delegate of the main target
It worked for me also the map is displayed in the notification. </p>


问:
Paging with GridView and LINQ to SQL
My grideview:

```<code><asp:GridView runat="server" ID="MyGridView" AutoGenerateColumns="false"
    DataKeyNames="ID"
    OnRowCreated="MyGridView_RowCreated" AllowPaging="true" Width="100%"
    PageSize="5" onpageindexchanging="MyGridView_PageIndexChanging" >
</code>```

My code behind on page_load:

```<code>MyGridView.DataSource = new Emp.GetData();
MyGridView.DataBind();
</code>```

My code:

```<code>using (DataContext db = new DataContext())
{
    var query = //valid query here

    query = query.Skip(StartRowIndex *5 ).Take(5);

    return query.ToList();
}
</code>```

if i have 15 records in my db, upon page load i see links for page 1,2 3 with data for page 1 shown - 5 records. then when i go to page 2 with 5 records, i see page 1 and 3 links. when i go to page 3 i see only 2 records instead of 5 and sometimes the paging link does not show up correctly either.

I want to display 5 records per page and want the GridView to determine how many pages to show.

i am not using a LinqDataSource, just have a method that returns a list.

答:
It actually tends to be easier if you do use a LinqDataSource.

```<code><asp:LinqDataSource ID="MyDataSource" runat="server"
    OnSelecting="MyDataSource_Selecting">
</asp:LinqDataSource>
</code>```

And in the code-behind, you can just re-route the LinqDataSource to call your business logic layer.  However, it will now need to leave the DataContext object open, i.e., don't wrap it in a using block, or you will get an error (and also don't apply the manual paging with Skip(..).Take(..).

```<code>protected void MyDataSource_Selecting(object sender,
        LinqDataSourceSelectEventArgs e) {
    e.Result = Emp.GetData();
}
</code>```

Now the LinqDataSource should manage all the paging for you automatically.

ContentLicense: CC BY-SA 3.0

Title: Paging with GridView and LINQ to SQL

Body:
My grideview:

<asp:GridView runat="server" ID="MyGridView" AutoGenerateColumns="false"
    DataKeyNames="ID"
    OnRowCreated="MyGridView_RowCreated" AllowPaging="true" Width="100%"
    PageSize="5" onpageindexchanging="MyGridView_PageIndexChanging" >

My code behind on page_load:

MyGridView.DataSource = new Emp.GetData();
MyGridView.DataBind();

My code:

using (DataContext db = new DataContext())
{
    var query = //valid query here

    query = query.Skip(StartRowIndex *5 ).Take(5);

    return query.ToList();
}

if i have 15 records in my db, upon page load i see links for page 1,2 3 with data for page 1 shown - 5 records. then when i go to page 2 with 5 records, i see page 1 and 3 links. when i go to page 3 i see only 2 records instead of 5 and sometimes the paging link does not show up correctly either.

I want to display 5 records per page and want the GridView to determine how many pages to show.

i am not using a LinqDataSource, just have a method that returns a list.

Body:
It actually tends to be easier if you do use a LinqDataSource.

<asp:LinqDataSource ID="MyDataSource" runat="server"
    OnSelecting="MyDataSource_Selecting">
</asp:LinqDataSource>

And in the code-behind, you can just re-route the LinqDataSource to call your business logic layer.  However, it will now need to leave the DataContext object open, i.e., don't wrap it in a using block, or you will get an error (and also don't apply the manual paging with Skip(..).Take(..).

protected void MyDataSource_Selecting(object sender,
        LinqDataSourceSelectEventArgs e) {
    e.Result = Emp.GetData();
}

Now the LinqDataSource should manage all the paging for you automatically.


问:
Django Create Class From Multiple Functions
I have several functions in my utils.py file that my views use to calculate trade stats. Below I added just 3 but there are 8 and soon there will be several more. The way I currently have it set up works but it's very inefficient. You can see each function starts from the beginning and calls other functions that set similar variables.

What is the proper way to turn this into a class?

Is this even the right approach?

utils.py | multiple functions

```<code>def max_amount_function (pk):
    trade = get_object_or_404(Trade, pk=pk)
    entries_buy = Entry.objects.filter(trade=trade, entry_type="entry")
    max_amount_function = entries_buy.aggregate(max_amount_function=Sum('amount'))['max_amount_function']
    if max_amount_function is None:
        return 0
    else:
        return max_amount_function

def fees_function (pk):
    trade = get_object_or_404(Trade, pk=pk)
    entries = Entry.objects.filter(trade=trade)
    fees_function = entries.aggregate(fees_function=Sum('fee'))['fees_function']
    return fees_function

def entry_cpu_function (pk):
    if max_amount_function(pk) > 0:
        trade = get_object_or_404(Trade, pk=pk)
        entries_buy = Entry.objects.filter(trade=trade, entry_type="entry")
        entry_cpu_function = entries_buy.annotate(
            s=F('amount') * F('price')
        ).aggregate(
            entry_cpu_function=ExpressionWrapper(
                Sum(
                    Cast('s', output_field=models.FloatField())
                ) / Sum('amount'),
                output_field=models.FloatField()
            )
        )['entry_cpu_function']
        return entry_cpu_function
    else:
        return 0
</code>```

utils.py | one class

```<code>class TradeStats:
    trade = get_object_or_404(Trade)
    entries_buy = Entry.objects.filter(trade=trade, entry_type="entry")

    def __init__(self):
        pass

    def max_amount_functio(pk):
        pass

    def fees_function(pk):
        pass

    def entry_cpu_function(self):
        pass
</code>```

Edit added models.py as it may be relevant for the entries since it's a different class.

models.py

```<code>class Trade(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True)
    status = models.CharField(max_length=2, choices=STATUS_CHOICES, default='op')
    broker = models.ForeignKey(Broker, on_delete=models.CASCADE, blank=True, null=True)
    asset = models.ForeignKey(Asset, on_delete=models.CASCADE, null=True)
    ...

class Entry(models.Model):

    ENTRY = 'entry'
    EXIT = 'exit'
    ENTRY_TYPE_CHOICES = [
        (ENTRY, 'Entry'),
        (EXIT, 'Exit'),

    trade = models.ForeignKey(Trade, on_delete=models.CASCADE)
    amount = models.FloatField(null=True)
    price = models.FloatField(null=True, blank=True)
    entry_type = models.CharField(max_length=5, choices=ENTRY_TYPE_CHOICES, default=ENTRY)
    ...
</code>```

答:
You can move all of these functions under the model or custom QuerySet.

If you move to the model you can do something similar. (Code might not work, just given for your reference)

```<code># MODEL
class Trade(models.Model):

    # Model fields here

    def get_entries(self):
        # NB: assuming you didn't specify a related_name
        # in the `Entry.trade` ForeignKey field. Else,
        # replace `entry_set` with said related_name.
        return self.entry_set.filter(entry_type="entry")

    def max_amount_function(self):
        max_amount_res = self.get_entries().aggregate(max_amount_function=Sum('amount'))['max_amount_function']
        if max_amount_res is None:
            return 0
        else:
            return max_amount_res

    def fees_function(self):
        return self.get_entries().aggregate(fees_function=Sum('fee'))['fees_function']

    def entry_cpu_function(self, ):

        if self.max_amount_function() <= 0:
            return 0

        entry_cpu_function = self.get_entries().annotate(
            s=F('amount') * F('price')
        ).aggregate(
            entry_cpu_function=ExpressionWrapper(
                Sum(
                    Cast('s', output_field=models.FloatField())
                ) / Sum('amount'),
                output_field=models.FloatField()
            )
        )['entry_cpu_function']
        return entry_cpu_function
</code>```

Inside views.py, you can refer this functions like below -

```<code>trade = get_object_or_404(Trade, pk=pk)
trade.max_amount_function()
trade.fees_function()
trade.entry_cpu_function()
</code>```

Body:
I have several functions in my utils.py file that my views use to calculate trade stats. Below I added just 3 but there are 8 and soon there will be several more. The way I currently have it set up works but it's very inefficient. You can see each function starts from the beginning and calls other functions that set similar variables.

What is the proper way to turn this into a class?

Is this even the right approach?

utils.py | multiple functions

def max_amount_function (pk):
    trade = get_object_or_404(Trade, pk=pk)
    entries_buy = Entry.objects.filter(trade=trade, entry_type="entry")
    max_amount_function = entries_buy.aggregate(max_amount_function=Sum('amount'))['max_amount_function']
    if max_amount_function is None:
        return 0
    else:
        return max_amount_function

def fees_function (pk):
    trade = get_object_or_404(Trade, pk=pk)
    entries = Entry.objects.filter(trade=trade)
    fees_function = entries.aggregate(fees_function=Sum('fee'))['fees_function']
    return fees_function

def entry_cpu_function (pk):
    if max_amount_function(pk) > 0:
        trade = get_object_or_404(Trade, pk=pk)
        entries_buy = Entry.objects.filter(trade=trade, entry_type="entry")
        entry_cpu_function = entries_buy.annotate(
            s=F('amount') * F('price')
        ).aggregate(
            entry_cpu_function=ExpressionWrapper(
                Sum(
                    Cast('s', output_field=models.FloatField())
                ) / Sum('amount'),
                output_field=models.FloatField()
            )
        )['entry_cpu_function']
        return entry_cpu_function
    else:
        return 0

utils.py | one class

class TradeStats:
    trade = get_object_or_404(Trade)
    entries_buy = Entry.objects.filter(trade=trade, entry_type="entry")

    def __init__(self):
        pass

    def max_amount_functio(pk):
        pass

    def fees_function(pk):
        pass

    def entry_cpu_function(self):
        pass

Edit added models.py as it may be relevant for the entries since it's a different class.

models.py

class Trade(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True)
    status = models.CharField(max_length=2, choices=STATUS_CHOICES, default='op')
    broker = models.ForeignKey(Broker, on_delete=models.CASCADE, blank=True, null=True)
    asset = models.ForeignKey(Asset, on_delete=models.CASCADE, null=True)
    ...

class Entry(models.Model):

    ENTRY = 'entry'
    EXIT = 'exit'
    ENTRY_TYPE_CHOICES = [
        (ENTRY, 'Entry'),
        (EXIT, 'Exit'),

    trade = models.ForeignKey(Trade, on_delete=models.CASCADE)
    amount = models.FloatField(null=True)
    price = models.FloatField(null=True, blank=True)
    entry_type = models.CharField(max_length=5, choices=ENTRY_TYPE_CHOICES, default=ENTRY)
    ...

Body:
You can move all of these functions under the model or custom QuerySet.

If you move to the model you can do something similar. (Code might not work, just given for your reference)

# MODEL
class Trade(models.Model):

    # Model fields here

    def get_entries(self):
        # NB: assuming you didn't specify a related_name
        # in the `Entry.trade` ForeignKey field. Else,
        # replace `entry_set` with said related_name.
        return self.entry_set.filter(entry_type="entry")

    def max_amount_function(self):
        max_amount_res = self.get_entries().aggregate(max_amount_function=Sum('amount'))['max_amount_function']
        if max_amount_res is None:
            return 0
        else:
            return max_amount_res

    def fees_function(self):
        return self.get_entries().aggregate(fees_function=Sum('fee'))['fees_function']

    def entry_cpu_function(self, ):

        if self.max_amount_function() <= 0:
            return 0

        entry_cpu_function = self.get_entries().annotate(
            s=F('amount') * F('price')
        ).aggregate(
            entry_cpu_function=ExpressionWrapper(
                Sum(
                    Cast('s', output_field=models.FloatField())
                ) / Sum('amount'),
                output_field=models.FloatField()
            )
        )['entry_cpu_function']
        return entry_cpu_function

Inside views.py, you can refer this functions like below -

trade = get_object_or_404(Trade, pk=pk)
trade.max_amount_function()
trade.fees_function()
trade.entry_cpu_function()


问:
How to stay updated as an Android Developer?
I'm an Android Developer with more than 7 years in the software industry. Right now I'm at a point where my knowledge is outdated and I'm looking for a way to get updated with all the recent changes and trends.</p>

答:
In addition to @NikosHidalgo comment, all I want to add is,

Just surround yourself with Android.
 Not just in working hours but even out of it.

Subscribe to Android NewsLetters(Android Weekly).

Subscribe to Medium Android Community.

Subscribe to Android youtube channels( So that, as soon as you open Youtube you see Android feeds).

Follow Android Development pages on Instagram, Facebook, so that you are aware of what's new in Android, even in your free time.

Follow some of the top Android Developers/Consultants/Advocates on Twitter.

When you are doing non-coding tasks(Walking, Cleaning) hear out Android Podcasts.

Attend Android Meetups, great for building a network and learning
  new stuff.

Join the Android group on Reddit.

Just make your whole environment include Android in it.


问:
Ng-fullcalendar with angular 7
We're working on migrating our application from angular 6 to 7 and we're using Ng-fullCalendar.

Our package.json file includes the following versions:

```<code>"fullcalendar": "3.6.1",
"ng-fullcalendar": "1.7.1"
</code>```

When compiling our project, we're getting the following error:

```<code>ERROR in node_modules/@types/jquery/index.d.ts(6123,66): error TS2344: Type '"timeout" | "onreadystatechange" | "responseType" | "withCredentials" | "msCaching"' does not satisfy the constraint '"abort" | "open" | "timeout" | "response" | "getAllResponseHeaders" | "getResponseHeader" | "overrideMimeType" | "readyState" | "responseText" | "setRequestHeader" | "status" | ... 22 more ... | "dispatchEvent"'.
      Type '"msCaching"' is not assignable to type '"abort" | "open" | "timeout" | "response" | "getAllResponseHeaders" | "getResponseHeader" | "overrideMimeType" | "readyState" | "responseText" | "setRequestHeader" | "status" | ... 22 more ... | "dispatchEvent"'.
</code>```

Is there any workaround to resolve this problem?

答:
Maybe this is a trick but I struggle with that issue about a week until I have added this in the compilerOptions

"skipLibCheck": true

in the tsconfig.app.json file and this error has gone

Title: Ng-fullcalendar with angular 7

Body:
We're working on migrating our application from angular 6 to 7 and we're using Ng-fullCalendar.

Our package.json file includes the following versions:

"fullcalendar": "3.6.1",
"ng-fullcalendar": "1.7.1"

When compiling our project, we're getting the following error:

ERROR in node_modules/@types/jquery/index.d.ts(6123,66): error TS2344: Type '"timeout" | "onreadystatechange" | "responseType" | "withCredentials" | "msCaching"' does not satisfy the constraint '"abort" | "open" | "timeout" | "response" | "getAllResponseHeaders" | "getResponseHeader" | "overrideMimeType" | "readyState" | "responseText" | "setRequestHeader" | "status" | ... 22 more ... | "dispatchEvent"'.
      Type '"msCaching"' is not assignable to type '"abort" | "open" | "timeout" | "response" | "getAllResponseHeaders" | "getResponseHeader" | "overrideMimeType" | "readyState" | "responseText" | "setRequestHeader" | "status" | ... 22 more ... | "dispatchEvent"'.

Is there any workaround to resolve this problem?


问:
How to remove some prefix from download file path. e.g. http://localhost:XXXX/section-name"
My web app is running on http://localhost:XXXX port number. In that one section, I want to download some files. but it will prefix "http://localhost:XXXX/section_name" in the path of the download file.

```<code><a href={file_path} download={file_name}>
   <Button variant={"link"}>
      <b>Download File</b>
   </Button>
</a>
</code>```

In the above code, I want to download pdf files. but at click time, it will convert path in the below format.

```<code>http://localhost:XXXX/section_name/file_path

</code>```

I want to remove the "http://localhost:XXXX/section_name" part form download URL.

答:
If you are confirmed that your file_path name will not contain / then you can just slice the url i.e

```<code>file_path.slice(file_path.lastIndexOf('/') + 1, file_path.length);
</code>```

Body:
My web app is running on http://localhost:XXXX port number. In that one section, I want to download some files. but it will prefix "http://localhost:XXXX/section_name" in the path of the download file.

   <Button variant={"link"}>
      Download File
   </Button>

In the above code, I want to download pdf files. but at click time, it will convert path in the below format.

http://localhost:XXXX/section_name/file_path

I want to remove the "http://localhost:XXXX/section_name" part form download URL.

Body:
If you are confirmed that your file_path name will not contain / then you can just slice the url i.e

file_path.slice(file_path.lastIndexOf('/') + 1, file_path.length);


问:
Visualize text file with location info and intensity
I have an ascii text file containing location data (column 9-lat and 10-long) and intensity(column 20)

```<code> 200010  207  020311    40658.5  406593 52 344927.31 7100203.50  -26.2078720  127.4491855 345060.64 7100369.14   26.4  650.3  628.0 55471.293    20.168 55648.817 55637.523  -146.062
</code>```

the text file has many lines 10k+

I am trying to visualize this using GDAL, but not sure how to proceed.

Ideas?

答:
Try QGis. It is free software for making maps with data.

GDAL is for doing sophisticated data transformations.

Body:
I have an ascii text file containing location data (column 9-lat and 10-long) and intensity(column 20)

 200010  207  020311    40658.5  406593 52 344927.31 7100203.50  -26.2078720  127.4491855 345060.64 7100369.14   26.4  650.3  628.0 55471.293    20.168 55648.817 55637.523  -146.062

the text file has many lines 10k+

I am trying to visualize this using GDAL, but not sure how to proceed.

Ideas?


问:
The usage of a static method in Python
I recently came across a code for make bar plots and I am wondering why is there a need for a static method for a function in python. On top of that why self.function_name is used for a staticmethod. Here is the code :

```<code>class Foo :
    @staticmethod
    def make_bar_plot(values, labels, title, ylabel='Activity Count', step=10):

        x_pos = np.arange(len(labels))

        plt.bar(x_pos, values, align='center', alpha=0.5)
        plt.xticks(x_pos, labels)
        plt.yticks(np.arange(0, max(values) + step, step))

        plt.ylabel(ylabel)
        plt.title(title)

        for index, val in enumerate(values):
            plt.text(x=index, y=val+1, s=f'{val}')

        plt.show()
    def get_daywise_activity_stats(self, event_name, no_of_days):

        query = """select edate, count(*)
                    from %s
                        where ip_address not in (
                            select distinct(ip_address)
                            from activity_classic_class_section_start
                                where edate <'2019-12-31')
                        group by edate order by edate desc limit %s;
                        """%(event_name, no_of_days)

        event_dict = {ele[0].strftime("%m/%d/%Y"):ele[1] for ele in self.rs_conn.query(query)}
        print (event_dict)

        labels = list(event_dict.keys())
        values = list(event_dict.values())
        self.make_bar_plot(values, labels, 'Daywise_activity_stats -> '+event_name)
</code>```

Doesn't static methods work without self.function_name and work with class_name.function_name or am I missing something important here?

答:
You could also call make_bar_plot in a follwoing way:

```<code>Foo.make_bar_plot(values, labels, 'Daywise_activity_stats -> '+event_name)
</code>```

It will be the same as your code.
You need to reference your class - you can do it either by self, because every instance of the class will have a reference to make_bar_plot static method, or by giving the class name FOO. The result will be the same.

Title: The usage of a static method in Python

Body:
I recently came across a code for make bar plots and I am wondering why is there a need for a static method for a function in python. On top of that why self.function_name is used for a staticmethod. Here is the code :

class Foo :
    @staticmethod
    def make_bar_plot(values, labels, title, ylabel='Activity Count', step=10):

        x_pos = np.arange(len(labels))

        plt.bar(x_pos, values, align='center', alpha=0.5)
        plt.xticks(x_pos, labels)
        plt.yticks(np.arange(0, max(values) + step, step))

        plt.ylabel(ylabel)
        plt.title(title)

        for index, val in enumerate(values):
            plt.text(x=index, y=val+1, s=f'{val}')

        plt.show()
    def get_daywise_activity_stats(self, event_name, no_of_days):

        query = """select edate, count(*)
                    from %s
                        where ip_address not in (
                            select distinct(ip_address)
                            from activity_classic_class_section_start
                                where edate <'2019-12-31')
                        group by edate order by edate desc limit %s;
                        """%(event_name, no_of_days)

        event_dict = {ele[0].strftime("%m/%d/%Y"):ele[1] for ele in self.rs_conn.query(query)}
        print (event_dict)

        labels = list(event_dict.keys())
        values = list(event_dict.values())
        self.make_bar_plot(values, labels, 'Daywise_activity_stats -> '+event_name)

Doesn't static methods work without self.function_name and work with class_name.function_name or am I missing something important here?

Body:
You could also call make_bar_plot in a follwoing way:

Foo.make_bar_plot(values, labels, 'Daywise_activity_stats -> '+event_name)

It will be the same as your code.
You need to reference your class - you can do it either by self, because every instance of the class will have a reference to make_bar_plot static method, or by giving the class name FOO. The result will be the same.


问:
Access VBA SQL Update - Too few Parameters expected 1
I am new to access VBA.

I am trying to add 1 to all numbers in a field that are equal or greater than the value in text box [TP_Bld_OrderNum_Txt].

This is my code:

```<code>CurrentDb.Execute "UPDATE TP_Matrix " & _
      "SET TP_Matrix.Order_" & Me.TP_Bld_TP_Cbo & " = TP_Matrix.Order_" & Me.TP_Bld_TP_Cbo & "+1 " & _
      "WHERE TP_Matrix.Order_" & Me.TP_Bld_TP_Cbo & ">= Me.TP_Bld_OrderNum_Txt"
</code>```

I get this error:

too few parameters expected 1

I believe it relates to the text box value.

If I replace Me.TP_Bld_OrderNum_Txt with a number, the query works fine.

I have the text box set up as a number.

Why doesn't it recognize its value?

答:
You provided Me.TP_Bld_OrderNum_Txt as a literal (as a fixed string) and not its value:

& ">= Me.TP_Bld_OrderNum_Txt"

Try this instead:

& " >= " &  Me.TP_Bld_OrderNum_Txt.Value

Also, it is a good practice to use .Value to explicitely use the value of the control.

Body:
I am new to access VBA.

I am trying to add 1 to all numbers in a field that are equal or greater than the value in text box [TP_Bld_OrderNum_Txt].

This is my code:

CurrentDb.Execute "UPDATE TP_Matrix " & _
      "SET TP_Matrix.Order_" & Me.TP_Bld_TP_Cbo & " = TP_Matrix.Order_" & Me.TP_Bld_TP_Cbo & "+1 " & _
      "WHERE TP_Matrix.Order_" & Me.TP_Bld_TP_Cbo & ">= Me.TP_Bld_OrderNum_Txt"

I get this error:

too few parameters expected 1

I believe it relates to the text box value.

If I replace Me.TP_Bld_OrderNum_Txt with a number, the query works fine.

I have the text box set up as a number.

Why doesn't it recognize its value?


问:
How to check if a string contains text from an array of substrings in JavaScript?
Pretty straight forward. In javascript, I need to check if a string contains any substrings held in an array.</p>

答:
let obj = [{name : 'amit'},{name : 'arti'},{name : 'sumit'}];
let input = 'it';
```

<p>Use filter :</p>

<pre class="lang-js prettyprint-override"><code>obj.filter((n)=> n.name.trim().toLowerCase().includes(input.trim().toLowerCase()))
</code>```

Body:
let obj = [{name : 'amit'},{name : 'arti'},{name : 'sumit'}];
let input = 'it';

Use filter :

obj.filter((n)=> n.name.trim().toLowerCase().includes(input.trim().toLowerCase()))


问:
How to select hierarchical static fields in Excel using C#
I need to get pivot data table based on FY'19 .
Here i am using power pivotTable but when it is inside the if loop the commented part is giving me error.</p>

```<code>while (index <= System.Convert.ToInt32(oPivotTable.CubeFields.Count))
            {
                if (oPivotTable.CubeFields[index].Name.ToString().Equals("[Range].[Task Closed Fiscal Yr]"))
                {
                    CubeField1 = oPivotTable.CubeFields[index];
                    CubeField1.Orientation = Microsoft.Office.Interop.Excel.XlPivotFieldOrientation.xlPageField;
                     //Facing issue in below code
                    CubeField1.CurrentPageName = String.Format("[{0}].[{1}].&[{2}]", "Task Age Summary", "Task Closed Fiscal Yr", "FY'19");
                }

                index += 1;

            }
        }
</code>```

答:
After applying record macro and doing some testing on the same i am able to solve the answer. I need to remove curly braces     CubeField2.CurrentPageName = "[Range].[Task Status].&[Closed-Complete]";

                    }

Body:
I need to get pivot data table based on FY'19 .
Here i am using power pivotTable but when it is inside the if loop the commented part is giving me error.

while (index <= System.Convert.ToInt32(oPivotTable.CubeFields.Count))
            {
                if (oPivotTable.CubeFields[index].Name.ToString().Equals("[Range].[Task Closed Fiscal Yr]"))
                {
                    CubeField1 = oPivotTable.CubeFields[index];
                    CubeField1.Orientation = Microsoft.Office.Interop.Excel.XlPivotFieldOrientation.xlPageField;
                     //Facing issue in below code
                    CubeField1.CurrentPageName = String.Format("[{0}].[{1}].&[{2}]", "Task Age Summary", "Task Closed Fiscal Yr", "FY'19");
                }

                index += 1;

            }
        }


问:
SQL Tally up value based on the day of the week
Here is what my table looks like

```<code>ID | Date
------------
13  2013-03-21 00:00:00
13  2013-03-23 00:00:00
13  2013-03-24 00:00:00
25  2013-03-21 00:00:00
25  2013-03-22 00:00:00
25  2013-03-21 00:00:00
25  2013-03-23 00:00:00
25  2013-03-28 00:00:00
25  2013-03-21 00:00:00
82  2013-03-22 00:00:00
82  2013-03-22 00:00:00
I want it to output (combine sat & sun into 'weekend'). It'll combine all the Mondays, Tuesdays, Wednesdays, etc. and combine the values.

day | total
--------------
Friday  2
Thursday 3
Weekend 3
</code>```

This is my query so far

```<code>SELECT
  CASE
    WHEN DATENAME(weekday, [date]) = 'Saturday' OR DATENAME(weekday, [date]) = 'Sunday' THEN 'Weekend'
    ELSE DATENAME(weekday, [date])
  END AS Day,
  COUNT(DISTINCT [id]) AS score

  FROM [table]

GROUP BY
  CASE
    WHEN DATENAME(weekday, [date]) = 'Saturday' OR DATENAME(weekday, [date]) = 'Sunday' THEN 'Weekend'
    ELSE DATENAME(weekday, [date])
  END
</code>```

Currently I can get my query to output this, but it seems like it isn't adding both thursdays or sat + sun.

```<code>Day | total
--------------
Friday 2
Thursday 2
Weekend 2
</code>```

答:
```<code>select Day,Count(day) cnt from (
 SELECT
  CASE
    WHEN DATENAME(weekday, [date]) = 'Saturday' OR DATENAME(weekday, [date]) = 'Sunday' THEN 'Weekend'
    ELSE DATENAME(weekday, [date])
  END AS Day
  ,[date]

   FROM [Infinite_campus].[dbo].[AttendanceRecord]
  ) as t
  group by Day
</code>```

Body:
Here is what my table looks like

ID | Date
------------
13  2013-03-21 00:00:00
13  2013-03-23 00:00:00
13  2013-03-24 00:00:00
25  2013-03-21 00:00:00
25  2013-03-22 00:00:00
25  2013-03-21 00:00:00
25  2013-03-23 00:00:00
25  2013-03-28 00:00:00
25  2013-03-21 00:00:00
82  2013-03-22 00:00:00
82  2013-03-22 00:00:00
I want it to output (combine sat & sun into 'weekend'). It'll combine all the Mondays, Tuesdays, Wednesdays, etc. and combine the values.

day | total
--------------
Friday  2
Thursday 3
Weekend 3

This is my query so far

SELECT
  CASE
    WHEN DATENAME(weekday, [date]) = 'Saturday' OR DATENAME(weekday, [date]) = 'Sunday' THEN 'Weekend'
    ELSE DATENAME(weekday, [date])
  END AS Day,
  COUNT(DISTINCT [id]) AS score

  FROM [table]

GROUP BY
  CASE
    WHEN DATENAME(weekday, [date]) = 'Saturday' OR DATENAME(weekday, [date]) = 'Sunday' THEN 'Weekend'
    ELSE DATENAME(weekday, [date])
  END

Currently I can get my query to output this, but it seems like it isn't adding both thursdays or sat + sun.

Day | total
--------------
Friday 2
Thursday 2
Weekend 2


问:
Download button auto clear by any input change
I have two input selection and an action button to generate a plot and download the data. I would like to clear the output contents (plot and download button) any time there is a change in the input selection. The code below will only clear the plot and not the download button. Not sure if the reactiveValuesunder the downloadhandleris correct.

```<code>library(shiny)
library(ggplot2)
library(openxlsx)

ui = fluidPage(
  textInput("textT", label = "Title", value = ""),
  textInput("textX", label = "X-Axis Label", value = ""),
  actionButton("Btn", "Run", icon=icon("play-circle")),
  plotOutput('plot1'),
  conditionalPanel(condition = "input.Btn>0", downloadButton("dwload", "Download"))
  )

server = function(input, output, session) {

  v <- reactiveValues(clearAll = TRUE)

  observeEvent(c(input$textT, input$textX), {
    v$clearAll <- TRUE
  }, priority = 10)

  observeEvent(input$Btn, {

    output$plot1 = renderPlot({
      if (v$clearAll)
        return()
      else
        ggplot(mtcars, aes(x= gear, y= carb)) + geom_line() +ggtitle(input$textT) + xlab(input$textX)
    })

    output$dwload <- downloadHandler(
        filename = function() {
          paste0("Checks-", gsub(" ", "_", gsub(":", ".", Sys.time())), ".xlsx")
        },
      content = function(file) {
        if (v$clearAll)
          return()
        else
          quick_xlsx(mtcars, file=file)
      }
    )

    v$clearAll <- FALSE

  }, priority = 10)

}

shinyApp(ui, server)
</code>```

I'd appreciate any help.

Thank you!

答:
Here is a solution using renderUI and req:

```<code>library(shiny)
library(ggplot2)
library(openxlsx)

ui <- fluidPage(
  textInput("textT", label = "Title", value = ""),
  textInput("textX", label = "X-Axis Label", value = ""),
  actionButton("Btn", "Run", icon=icon("play-circle")),
  uiOutput("widgets")
)

server <- function(input, output, session) {

  hideAll <- reactiveVal(TRUE)

  observeEvent(list(input$textT, input$textX), {
    hideAll(TRUE)
  })

  observeEvent(input$Btn, {
    req(input$textT)
    req(input$textX)
    hideAll(FALSE)
  })

  output$plot1 <- renderPlot({
    ggplot(mtcars, aes(x= gear, y= carb)) + geom_line() +
      ggtitle(input$textT) + xlab(input$textX)
  })

  output$dwload <- downloadHandler(
    filename = function() {
      paste0("Checks-", gsub(" ", "_", gsub(":", ".", Sys.time())), ".xlsx")
    },
    content = function(file) {
      quick_xlsx(mtcars, file=file)
    }
  )

  output$widgets <- renderUI({
    req(!hideAll())
    tagList(
      plotOutput('plot1'),
      downloadButton("dwload", "Download")
    )
  })

}

shinyApp(ui, server)
</code>```

Body:
I have two input selection and an action button to generate a plot and download the data. I would like to clear the output contents (plot and download button) any time there is a change in the input selection. The code below will only clear the plot and not the download button. Not sure if the reactiveValuesunder the downloadhandleris correct.

library(shiny)
library(ggplot2)
library(openxlsx)

ui = fluidPage(
  textInput("textT", label = "Title", value = ""),
  textInput("textX", label = "X-Axis Label", value = ""),
  actionButton("Btn", "Run", icon=icon("play-circle")),
  plotOutput('plot1'),
  conditionalPanel(condition = "input.Btn>0", downloadButton("dwload", "Download"))
  )

server = function(input, output, session) {

  v <- reactiveValues(clearAll = TRUE)

  observeEvent(c(input$textT, input$textX), {
    v$clearAll <- TRUE
  }, priority = 10)

  observeEvent(input$Btn, {

    output$plot1 = renderPlot({
      if (v$clearAll)
        return()
      else
        ggplot(mtcars, aes(x= gear, y= carb)) + geom_line() +ggtitle(input$textT) + xlab(input$textX)
    })

    output$dwload <- downloadHandler(
        filename = function() {
          paste0("Checks-", gsub(" ", "_", gsub(":", ".", Sys.time())), ".xlsx")
        },
      content = function(file) {
        if (v$clearAll)
          return()
        else
          quick_xlsx(mtcars, file=file)
      }
    )

    v$clearAll <- FALSE

  }, priority = 10)

}

shinyApp(ui, server)

I'd appreciate any help.

Thank you!

Body:
Here is a solution using renderUI and req:

library(shiny)
library(ggplot2)
library(openxlsx)

ui <- fluidPage(
  textInput("textT", label = "Title", value = ""),
  textInput("textX", label = "X-Axis Label", value = ""),
  actionButton("Btn", "Run", icon=icon("play-circle")),
  uiOutput("widgets")
)

server <- function(input, output, session) {

  hideAll <- reactiveVal(TRUE)

  observeEvent(list(input$textT, input$textX), {
    hideAll(TRUE)
  })

  observeEvent(input$Btn, {
    req(input$textT)
    req(input$textX)
    hideAll(FALSE)
  })

  output$plot1 <- renderPlot({
    ggplot(mtcars, aes(x= gear, y= carb)) + geom_line() +
      ggtitle(input$textT) + xlab(input$textX)
  })

  output$dwload <- downloadHandler(
    filename = function() {
      paste0("Checks-", gsub(" ", "_", gsub(":", ".", Sys.time())), ".xlsx")
    },
    content = function(file) {
      quick_xlsx(mtcars, file=file)
    }
  )

  output$widgets <- renderUI({
    req(!hideAll())
    tagList(
      plotOutput('plot1'),
      downloadButton("dwload", "Download")
    )
  })

}

shinyApp(ui, server)


问:
passing unknown class as parameter and trying to run function on it
Using C#, lets say I have these classes:

```<code>classZero
classOne
classTwo
</code>```

class classZero and classOne have a public function named "Hello()".

how can i creat a new function (in any class) that takes a unknown class as a paramenter and then run the function "Hello" on this unknown class, if it exists?

in sebdo code this would look something like this:

```<code>function runHelloIfPossible(anyclass aclass):
   if aclass contains function Hello:
      aclass.Hello()
</code>```

if in my case the anyclass argument where any of classZero or classOne the function Hello would run.

答:
```<code>public interface IHello
{
    void Hello();
}

public class Zero: IHello
{
    public void Hello()
    {
    }
//...
}

...

void RunHelloIfPossible(object obj)
{
   if (obj is IHello ih)
   {
      ih.Hello();
   }
}
</code>```

Body:
Using C#, lets say I have these classes:

classZero
classOne
classTwo

class classZero and classOne have a public function named "Hello()".

how can i creat a new function (in any class) that takes a unknown class as a paramenter and then run the function "Hello" on this unknown class, if it exists?

in sebdo code this would look something like this:

function runHelloIfPossible(anyclass aclass):
   if aclass contains function Hello:
      aclass.Hello()

if in my case the anyclass argument where any of classZero or classOne the function Hello would run.


问:
How to broadcast/share a variable/property from a slave to the others?
I have a JMeter script that is executed in distributed mode with 4 nodes. One of them is the controller and does not do any request and the other 3, as workers do the requests.

I can currently set one of the workers as a master worker, setting a property in the user.properties file for that specific worker. This "master" worker perform some requests that has to be done only once, so these requests can't be done by the other workers.

Now I have the need of extract some values from the response of these unique request and send this information to the other slaves.

Is it possible to do this?
How can data be sent form one worker to the other workers at run time?

答:
You can use HTTP Simple Table Server plugin and populate it with data from the "master" worker using ADD command so once you do the setup of the pre-requisites all other workers including the master could access the generated data via READ command

HTTP Simple Table server can be installed using JMeter Plugins Manager


问:
Mapping values from series over a column to replace nan values pandas
I have a DataFrame which has job numbers and the customer names associated with that job. There are instances where the job numbers have no customer name and therefore is null.
I have a separate series which has these job numbers as index and the missing customer names to replace the null values, based on the job numbers. I am not entirely sure how I would go about mapping this over the original DataFrame column.

This is the original DataFrame (df):

```<code>   Job Number  Customer
0    02123      Paul F
1    46456      nan
2    56823      Kevin T
3    62948      nan
</code>```

The series to replace the nan values:

```<code>Job Number
  46456     Kara L
  62948     Sabrina M
  Name: Customers, dtype: object
</code>```

The final output I need is:

```<code>   Job Number  Customer
0    02123      Paul F
1    46456      Kara L
2    56823      Kevin T
3    62948      Sabrina M
</code>```

I hope this makes sense. I have had a look at other answers such as using: df['Customer'] = df['Job Number'].map(customers) but that didn't work or test['Customer'] = df['Customer'].combine_first(df['Customer'].map(customers)).

I wasn't sure how to paste code into here so I have written out the df and series by hand.

Any help would be greatly appreciated.

答:
You could use reset_index with combine_first:

```<code>(df.set_index('JobNumber').squeeze()
   .combine_first(customers.set_index('Job').squeeze())
   .reset_index())

       index  Customer
    0   2123     Paul F
    1  46456     Kara L
    2  56823    Kevin T
    3  62948  Sabrina M
</code>```

Body:
I have a DataFrame which has job numbers and the customer names associated with that job. There are instances where the job numbers have no customer name and therefore is null.
I have a separate series which has these job numbers as index and the missing customer names to replace the null values, based on the job numbers. I am not entirely sure how I would go about mapping this over the original DataFrame column.

This is the original DataFrame (df):

   Job Number  Customer
0    02123      Paul F
1    46456      nan
2    56823      Kevin T
3    62948      nan

The series to replace the nan values:

Job Number
  46456     Kara L
  62948     Sabrina M
  Name: Customers, dtype: object

The final output I need is:

   Job Number  Customer
0    02123      Paul F
1    46456      Kara L
2    56823      Kevin T
3    62948      Sabrina M

I hope this makes sense. I have had a look at other answers such as using: df['Customer'] = df['Job Number'].map(customers) but that didn't work or test['Customer'] = df['Customer'].combine_first(df['Customer'].map(customers)).

I wasn't sure how to paste code into here so I have written out the df and series by hand.

Any help would be greatly appreciated.

Body:
You could use reset_index with combine_first:

(df.set_index('JobNumber').squeeze()
   .combine_first(customers.set_index('Job').squeeze())
   .reset_index())

       index  Customer
    0   2123     Paul F
    1  46456     Kara L
    2  56823    Kevin T
    3  62948  Sabrina M