问:
Error creating bean with name 'authenticationmanager' defined in ServletContext
I just started to learn Spring Security and have some trouble. I want to configure User login on page with password and username which stored in database. I use Hibernate and spring 4.3 along with MySQL to store data.i was trying to login using DAO Authentication using spring but i'm struck here. please help me out..

security-context.xml

```<code><!-- custom login Authentication/form -->
        <http use-expressions="true" auto-config="true" >
            <intercept-url pattern="/index*" access="hasRole('ROLE_STUDENT')"/>
            <intercept-url pattern="/resources/**" access="permitAll" />

            <form-login login-page="/login"
                        username-parameter="email"
                        password-parameter="password"
                        default-target-url="/default"
                        authentication-failure-url="/loginfailed"/>
            <logout logout-success-url="/index"/>
            <csrf/>
        </http>

        <b:bean id="daoAuthenticationprovider" class="org.springframework.security.authentication.dao.DaoAuthenticationProvider" >
            <b:property name="userDetailService" ref="userDetailService"></b:property>
        </b:bean>
        <b:bean id="authenticationmanager" class="org.springframework.security.authentication.ProviderManager">
            <b:property name="providers">
                <b:list>
                    <b:ref bean="daoAuthenticationprovider"/>
                </b:list>
            </b:property>
        </b:bean>

        <authentication-manager>
            <authentication-provider user-service-ref="userDetailService">
                <!-- <password-encoder hash="md5"></password-encoder> -->
            </authentication-provider>
        </authentication-manager>
</code>```

Spring-servlet

```<code><context:annotation-config />
    <context:component-scan base-package="com.internbridge" />

    <!-- to prevent browser back button on displaying secure resource after logout -->
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="cacheSeconds" value="0"></property>
    </bean>

    <bean id="propertyConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
        p:location="/WEB-INF/jdbc.properties" />

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close" p:driverClassName="${jdbc.driverClassName}"
        p:url="${jdbc.databaseurl}" p:username="${jdbc.username}" p:password="${jdbc.password}" />
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation">
            <value>classpath:hibernate.cfg.xml</value>
        </property>
        <property name="configurationClass">
            <value>org.hibernate.cfg.AnnotationConfiguration</value>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">${jdbc.dialect}</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
            </props>
        </property>
    </bean>
    <bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
    <tx:annotation-driven />
    <bean id="transactionManager"
        class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>
<!-- Spring Internationalizations -->
    <bean id="messageSource"
        class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basename" value="classpath:messages/messages" />
        <property name="defaultEncoding" value="UTF-8" />
    </bean>

    <bean id="localeResolver"
        class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
        <property name="defaultLocale" value="tl" />
    </bean>

    <bean id="localeChangeInterceptor"
        class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
        <property name="paramName" value="language" />
    </bean>

    <bean id="handlerMapping"
        class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
        <property name="interceptors">
            <ref bean="localeChangeInterceptor" />
        </property>
    </bean>

    <mvc:resources mapping="/resources/**" location="/resources/" />
    <mvc:annotation-driven />
</code>```

web.xml

```<code><display-name>InternBridge</display-name>

    <context-param>
        <param-name>log4jConfigLocation</param-name>
        <param-value>classpath:log4j.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
    </listener>
    <!-- Spring initialization -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/security-context.xml,
            /WEB-INF/spring-servlet.xml
        </param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- Spring security configuration -->
    <!-- filter to use spring security, be sure to use suggested name "springSecurityFilterchain"-->
    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <!-- Spring MVC or Servlet Mapping -->
    <servlet>
        <servlet-name>spring</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>
</code>```

console

```<code>ERROR: org.springframework.web.context.ContextLoader - Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'authenticationmanager' defined in ServletContext resource [/WEB-INF/security-context.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.security.authentication.ProviderManager]: No default constructor found; nested exception is java.lang.NoSuchMethodException: org.springframework.security.authentication.ProviderManager.<init>()
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1155)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1099)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:443)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:325)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4853)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5314)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1407)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1397)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.security.authentication.ProviderManager]: No default constructor found; nested exception is java.lang.NoSuchMethodException: org.springframework.security.authentication.ProviderManager.<init>()
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:85)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1147)
    ... 22 more
Caused by: java.lang.NoSuchMethodException: org.springframework.security.authentication.ProviderManager.<init>()
    at java.lang.Class.getConstructor0(Class.java:3082)
    at java.lang.Class.getDeclaredConstructor(Class.java:2178)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:80)
    ... 23 more
</code>```

答:
As per the stack trace, the org.springframework.security.authentication.ProviderManager class does not have a default constructor. You will need to specify the providers when defining the bean. Here is an example.

How to set-up and configure a ProviderManager using Spring Security namespace?

Body:
I just started to learn Spring Security and have some trouble. I want to configure User login on page with password and username which stored in database. I use Hibernate and spring 4.3 along with MySQL to store data.i was trying to login using DAO Authentication using spring but i'm struck here. please help me out..

security-context.xml

        <http use-expressions="true" auto-config="true" >
            <intercept-url pattern="/index*" access="hasRole('ROLE_STUDENT')"/>
            <intercept-url pattern="/resources/**" access="permitAll" />

            <form-login login-page="/login"
                        username-parameter="email"
                        password-parameter="password"
                        default-target-url="/default"
                        authentication-failure-url="/loginfailed"/>
            <logout logout-success-url="/index"/>
            <csrf/>
        </http>

        <authentication-manager>
            <authentication-provider user-service-ref="userDetailService">

            </authentication-provider>
        </authentication-manager>

Spring-servlet

<context:annotation-config />
    <context:component-scan base-package="com.internbridge" />

    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="cacheSeconds" value="0"></property>
    </bean>

    <bean id="propertyConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
        p:location="/WEB-INF/jdbc.properties" />

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close" p:driverClassName="${jdbc.driverClassName}"
        p:url="${jdbc.databaseurl}" p:username="${jdbc.username}" p:password="${jdbc.password}" />
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation">
            <value>classpath:hibernate.cfg.xml</value>
        </property>
        <property name="configurationClass">
            <value>org.hibernate.cfg.AnnotationConfiguration</value>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">${jdbc.dialect}</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
            </props>
        </property>
    </bean>
    <bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
    <tx:annotation-driven />
    <bean id="transactionManager"
        class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <bean id="messageSource"
        class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basename" value="classpath:messages/messages" />
        <property name="defaultEncoding" value="UTF-8" />
    </bean>

    <bean id="localeResolver"
        class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
        <property name="defaultLocale" value="tl" />
    </bean>

    <bean id="localeChangeInterceptor"
        class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
        <property name="paramName" value="language" />
    </bean>

    <bean id="handlerMapping"
        class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
        <property name="interceptors">
            <ref bean="localeChangeInterceptor" />
        </property>
    </bean>

    <mvc:resources mapping="/resources/**" location="/resources/" />
    <mvc:annotation-driven />

web.xml

<display-name>InternBridge</display-name>

    <context-param>
        <param-name>log4jConfigLocation</param-name>
        <param-value>classpath:log4j.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
    </listener>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/security-context.xml,
            /WEB-INF/spring-servlet.xml
        </param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <servlet>
        <servlet-name>spring</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

console

ERROR: org.springframework.web.context.ContextLoader - Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'authenticationmanager' defined in ServletContext resource [/WEB-INF/security-context.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.security.authentication.ProviderManager]: No default constructor found; nested exception is java.lang.NoSuchMethodException: org.springframework.security.authentication.ProviderManager.<init>()
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1155)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1099)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:443)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:325)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4853)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5314)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1407)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1397)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.security.authentication.ProviderManager]: No default constructor found; nested exception is java.lang.NoSuchMethodException: org.springframework.security.authentication.ProviderManager.<init>()
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:85)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1147)
    ... 22 more
Caused by: java.lang.NoSuchMethodException: org.springframework.security.authentication.ProviderManager.<init>()
    at java.lang.Class.getConstructor0(Class.java:3082)
    at java.lang.Class.getDeclaredConstructor(Class.java:2178)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:80)
    ... 23 more


来源: stackexchange

问:
Is there any function to plot similar to geom_smooth() in Plotly using python?
I have made a scatterplot using Plotly (python), and i want to connect the dots using something similar to geom_smooth() function.

Something like below image :

答:
You should be able to do it by setting the shape='spline' when defining the line. here is the plotly example

```<code>trace2 = go.Scatter(
    x=[1, 2, 3, 4, 5],
    y=[6, 8, 7, 8, 6],
    mode='lines+markers',
    name="'spline'",
    text=["tweak line smoothness<br>with 'smoothing' in line object"],
    hoverinfo='text+name',
    line=dict(
        shape='spline'
    )
)
</code>```

See an example here: plotly line charts

ContentLicense: CC BY-SA 3.0

Body:
You should be able to do it by setting the shape='spline' when defining the line. here is the plotly example

trace2 = go.Scatter(
    x=[1, 2, 3, 4, 5],
    y=[6, 8, 7, 8, 6],
    mode='lines+markers',
    name="'spline'",
    text=["tweak line smoothness<br>with 'smoothing' in line object"],
    hoverinfo='text+name',
    line=dict(
        shape='spline'
    )
)

See an example here: plotly line charts


问:
android problem in getting the screen resolution size
```<code>DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
height = displaymetrics.heightPixels;
width = displaymetrics.widthPixels;
Log.e("FirstImage", "Width = "+width+"Height = "+height);
</code>```

The above was the code I have used to display the screen size.. but the problem is I am getting width=320 and height=569. But I am using motorola milestone with screen size 480x854

How can I get the correct size?

答:
http://realmike.org/blog/2010/12/21/multiple-screen-sizes-with-processing-for-android/

above link has excellent resource that tells about the screen resolution and how to get the real screen resolution etc....read fully you will come to know about the reality

Body:
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
height = displaymetrics.heightPixels;
width = displaymetrics.widthPixels;
Log.e("FirstImage", "Width = "+width+"Height = "+height);

The above was the code I have used to display the screen size.. but the problem is I am getting width=320 and height=569. But I am using motorola milestone with screen size 480x854

How can I get the correct size?

ContentLicense: CC BY-SA 2.5


问:
Symfony 2 : ContextErrorException: Notice: serialize():"url" returned as member variable from __sleep() but does not exist in
I'm working in a project that has been already started, and i'm continuing in, I got this exception when I added a property in an entity , this poperty is a simple column that get it's values from another entity (personnal), and it's a multi select value, the render of the new page has no problem but when I submit, I got this Exception, the field I added is this :

```<code>/**
 * @var array
 *
 * @ORM\Column(name="responsable",type="array",  nullable=true)
 *
 */
private $responsable;

 /**
 * Add responsable
 *
 * @param $responsable
 * @return Actionreclamation
 */
public function addResponsable($responsable)
{

    if (!in_array($responsable, $this->responsable, true)) {
        $this->responsable[] = $responsable;
    }

    return $this;
}

/**
 * Remove responsable
 *
 * @param $responsable
 */
public function removeResponsable( $responsable)
{
//    $this->responsable->removeElement($responsable);
     if (false !== $key = array_search($responsable, $this->responsable, true)) {
        unset($this->responsable[$key]);
        $this->responsable = array_values($this->responsable);
    }

    return $this;
}

/**
 * Get responsable
 *
 * @return \Doctrine\Common\Collections\Collection
 */
public function getResponsable()
{
    return $this->responsable;
}

/**
 * Set responsable
 *
 * @param array $responsable
 * @return Actionreclamation
 */
public function setResponsable($responsable)
{
    $this->responsable = $responsable;

    return $this;
}
</code>```

and inside the form type :

```<code>->add('responsable', 'entity', array(
            'class'    => 'UserUserBundle:Personnel',
            'property' => 'nompersonnel',
            'multiple' => true ))
</code>```

inside the view :

```<code><div class="form-group">
                    <label class="col-md-3 control-label">Responsable</label>
                    <div class="col-md-6">
                        <div class="input-icon right">
                            <i class="fa"></i>
                             {{ form_widget(form.responsable) }}
                        </div>
                        <span class="help-block">{{ form_errors(form.responsable) }}</span>
                    </div>
                </div>
</code>```

plz I need help!

the exception is :

```<code>in C:\wamp\www\GESTIBAT0.1\vendor\doctrine\dbal\lib\Doctrine\DBAL\Types\ArrayType.php line 38
at ErrorHandler->handle('8', 'serialize(): "url" returned as member variable from __sleep() but does not exist', 'C:\wamp\www\GESTIBAT0.1\vendor\doctrine\dbal\lib\Doctrine\DBAL\Types\ArrayType.php', '38', array('value' => array(object(Personnel), object(Personnel)), 'platform' => object(MySqlPlatform)))
at serialize(array(object(Personnel), object(Personnel))) in C:\wamp\www\GESTIBAT0.1\vendor\doctrine\dbal\lib\Doctrine\DBAL\Types\ArrayType.php line 38
at ArrayType->convertToDatabaseValue(array(object(Personnel), object(Personnel)), object(MySqlPlatform)) in C:\wamp\www\GESTIBAT0.1\vendor\doctrine\dbal\lib\Doctrine\DBAL\Statement.php line 98
at Statement->bindValue('6', array(object(Personnel), object(Personnel)), 'array') in C:\wamp\www\GESTIBAT0.1\vendor\doctrine\orm\lib\Doctrine\ORM\Persisters\BasicEntityPersister.php line 273
at BasicEntityPersister->executeInserts() in C:\wamp\www\GESTIBAT0.1\vendor\doctrine\orm\lib\Doctrine\ORM\UnitOfWork.php line 929
at UnitOfWork->executeInserts(object(ClassMetadata)) in C:\wamp\www\GESTIBAT0.1\vendor\doctrine\orm\lib\Doctrine\ORM\UnitOfWork.php line 318
at UnitOfWork->commit(null) in C:\wamp\www\GESTIBAT0.1\vendor\doctrine\orm\lib\Doctrine\ORM\EntityManager.php line 355
at EntityManager->flush() in C:\wamp\www\GESTIBAT0.1\src\Client\ClientBundle\Controller\ActionreclamationController.php line 56
at ActionreclamationController->createAction(object(Request))
at call_user_func_array(array(object(ActionreclamationController), 'createAction'), array(object(Request))) in C:\wamp\www\GESTIBAT0.1\app\bootstrap.php.cache line 2843
at HttpKernel->handleRaw(object(Request), '1') in C:\wamp\www\GESTIBAT0.1\app\bootstrap.php.cache line 2817
at HttpKernel->handle(object(Request), '1', true) in C:\wamp\www\GESTIBAT0.1\app\bootstrap.php.cache line 2946
at ContainerAwareHttpKernel->handle(object(Request), '1', true) in C:\wamp\www\GESTIBAT0.1\app\bootstrap.php.cache line 2248
at Kernel->handle(object(Request)) in C:\wamp\www\GESTIBAT0.1\web\app_dev.php line 28
</code>```

thanx in advance!

"Edit"
The main entity is named "ActionReclamation" it has a field (simple column with no relation as varchar in the database) named "responsable" the values for this field are returned from another entity named "Personnel", in the view I show the values of "Personnel" entity and I can choose multiple values

Did I explain well ?
thanx for help

答:
you can also try this :</p>

```<code>php bin/console doctrine:mongodb:generate:hydrators
</code>```

Body:
I'm working in a project that has been already started, and i'm continuing in, I got this exception when I added a property in an entity , this poperty is a simple column that get it's values from another entity (personnal), and it's a multi select value, the render of the new page has no problem but when I submit, I got this Exception, the field I added is this :

/**
 * @var array
 *
 * @ORM\Column(name="responsable",type="array",  nullable=true)
 *
 */
private $responsable;

 /**
 * Add responsable
 *
 * @param $responsable
 * @return Actionreclamation
 */
public function addResponsable($responsable)
{

    if (!in_array($responsable, $this->responsable, true)) {
        $this->responsable[] = $responsable;
    }

    return $this;
}

/**
 * Remove responsable
 *
 * @param $responsable
 */
public function removeResponsable( $responsable)
{
//    $this->responsable->removeElement($responsable);
     if (false !== $key = array_search($responsable, $this->responsable, true)) {
        unset($this->responsable[$key]);
        $this->responsable = array_values($this->responsable);
    }

    return $this;
}

/**
 * Get responsable
 *
 * @return \Doctrine\Common\Collections\Collection
 */
public function getResponsable()
{
    return $this->responsable;
}

/**
 * Set responsable
 *
 * @param array $responsable
 * @return Actionreclamation
 */
public function setResponsable($responsable)
{
    $this->responsable = $responsable;

    return $this;
}

and inside the form type :

->add('responsable', 'entity', array(
            'class'    => 'UserUserBundle:Personnel',
            'property' => 'nompersonnel',
            'multiple' => true ))

inside the view :

                    Responsable

                             {{ form_widget(form.responsable) }}

                        {{ form_errors(form.responsable) }}

plz I need help!

the exception is :

in C:\wamp\www\GESTIBAT0.1\vendor\doctrine\dbal\lib\Doctrine\DBAL\Types\ArrayType.php line 38
at ErrorHandler->handle('8', 'serialize(): "url" returned as member variable from __sleep() but does not exist', 'C:\wamp\www\GESTIBAT0.1\vendor\doctrine\dbal\lib\Doctrine\DBAL\Types\ArrayType.php', '38', array('value' => array(object(Personnel), object(Personnel)), 'platform' => object(MySqlPlatform)))
at serialize(array(object(Personnel), object(Personnel))) in C:\wamp\www\GESTIBAT0.1\vendor\doctrine\dbal\lib\Doctrine\DBAL\Types\ArrayType.php line 38
at ArrayType->convertToDatabaseValue(array(object(Personnel), object(Personnel)), object(MySqlPlatform)) in C:\wamp\www\GESTIBAT0.1\vendor\doctrine\dbal\lib\Doctrine\DBAL\Statement.php line 98
at Statement->bindValue('6', array(object(Personnel), object(Personnel)), 'array') in C:\wamp\www\GESTIBAT0.1\vendor\doctrine\orm\lib\Doctrine\ORM\Persisters\BasicEntityPersister.php line 273
at BasicEntityPersister->executeInserts() in C:\wamp\www\GESTIBAT0.1\vendor\doctrine\orm\lib\Doctrine\ORM\UnitOfWork.php line 929
at UnitOfWork->executeInserts(object(ClassMetadata)) in C:\wamp\www\GESTIBAT0.1\vendor\doctrine\orm\lib\Doctrine\ORM\UnitOfWork.php line 318
at UnitOfWork->commit(null) in C:\wamp\www\GESTIBAT0.1\vendor\doctrine\orm\lib\Doctrine\ORM\EntityManager.php line 355
at EntityManager->flush() in C:\wamp\www\GESTIBAT0.1\src\Client\ClientBundle\Controller\ActionreclamationController.php line 56
at ActionreclamationController->createAction(object(Request))
at call_user_func_array(array(object(ActionreclamationController), 'createAction'), array(object(Request))) in C:\wamp\www\GESTIBAT0.1\app\bootstrap.php.cache line 2843
at HttpKernel->handleRaw(object(Request), '1') in C:\wamp\www\GESTIBAT0.1\app\bootstrap.php.cache line 2817
at HttpKernel->handle(object(Request), '1', true) in C:\wamp\www\GESTIBAT0.1\app\bootstrap.php.cache line 2946
at ContainerAwareHttpKernel->handle(object(Request), '1', true) in C:\wamp\www\GESTIBAT0.1\app\bootstrap.php.cache line 2248
at Kernel->handle(object(Request)) in C:\wamp\www\GESTIBAT0.1\web\app_dev.php line 28

thanx in advance!

"Edit"
The main entity is named "ActionReclamation" it has a field (simple column with no relation as varchar in the database) named "responsable" the values for this field are returned from another entity named "Personnel", in the view I show the values of "Personnel" entity and I can choose multiple values

Did I explain well ?
thanx for help

Body:
you can also try this :

php bin/console doctrine:mongodb:generate:hydrators


问:
MS Access concurrent users
I just have a quick question on MS Access Concurrency. I have built an input sheet in excel and the VB code opens a connection to a MS Access database logs 8 fields in about 5 milliseconds and closes the connection right away (for that particular user). I realize that Access has its limitations with concurrency, but what I really want to know if this is okay for 70 users? Not all of them will be logging data at the exact same time, if that would happen, I would say like 20-30 out of the 70 (the most) might log something at the exact same time.

On another note, the Access Database is only used for storing data, nothing else.

```<code>    Dim NewCon As ADODB.Connection
    Set NewCon = New ADODB.Connection
    Dim Recordset As ADODB.Recordset
    Set Recordset = New ADODB.Recordset

    NewCon.Open "Provider=Microsoft.ace.oledb.12.0;Data Source=C:\Users\my.user\Desktop\Testing\Database1.accdb"
    Recordset.Open "DATA", NewCon, adOpenDynamic, adLockOptimistic
    Recordset.AddNew
    'Primary Key
    Recordset.Fields(0).Value = G
    'Field 2
    Recordset.Fields(1).Value = A
    'Field 3
    Recordset.Fields(2).Value = B
    'Field 4
    Recordset.Fields(3).Value = C
    'Field 5
    Recordset.Fields(4).Value = D
    'Field 6
    Recordset.Fields(5).Value = E
    'Field 7
    Recordset.Fields(6).Value = F
    'Field 8
    Recordset.Fields(7).Value = Format(Now, "m/d/yyyy h:mm:ss")

    Recordset.Update
    Recordset.Close
    NewCon.Close
</code>```

答:
It should not be an issue. Or catch an error and try again.

If you experience serious trouble, you can use the method described here:

Handle concurrent update conflicts in Access silently

which includes a full demo and code:

```<code>' Function to replace the Edit method of a DAO.Recordset.
' To be used followed by GetUpdate to automatically handle
' concurrent updates.
'
' 2016-02-06. Gustav Brock, Cactus Data ApS, CPH.
'
Public Sub SetEdit(ByRef rs As DAO.Recordset)

    On Error GoTo Err_SetEdit

    ' Attempt to set rs into edit mode.
    Do While rs.EditMode <> dbEditInProgress
        rs.Edit
        If rs.EditMode = dbEditInProgress Then
            ' rs is ready for edit.
            Exit Do
        End If
    Loop

Exit_SetEdit:
    Exit Sub

Err_SetEdit:
    If DebugMode Then Debug.Print "    Edit", Timer, Err.Description
    If Err.Number = 3197 Then
        ' Concurrent edit.
        ' Continue in the loop.
        ' Will normally happen ONCE only for each call of SetEdit.
        Resume Next
    Else
        ' Other error, like deleted record.
        ' Pass error handling to the calling procedure.
        Resume Exit_SetEdit
    End If

End Sub
</code>```

and:

```<code>' Function to replace the Update method of a DAO.Recordset.
' To be used following SetEdit to automatically handle
' concurrent updates.
'
' 2016-01-31. Gustav Brock, Cactus Data ApS, CPH.
'
Public Function GetUpdate(ByRef rs As DAO.Recordset) As Boolean

    On Error GoTo Err_GetUpdate

    ' Attempt to update rs and terminate edit mode.
    rs.Update

    GetUpdate = True

Exit_GetUpdate:
    Exit Function

Err_GetUpdate:
    If DebugMode Then Debug.Print "    Update", Timer, Err.Description
    ' Update failed.
    ' Cancel and return False.
    rs.CancelUpdate
    Resume Exit_GetUpdate

End Function
</code>```

Also at GitHub

Title: MS Access concurrent users

Body:
I just have a quick question on MS Access Concurrency. I have built an input sheet in excel and the VB code opens a connection to a MS Access database logs 8 fields in about 5 milliseconds and closes the connection right away (for that particular user). I realize that Access has its limitations with concurrency, but what I really want to know if this is okay for 70 users? Not all of them will be logging data at the exact same time, if that would happen, I would say like 20-30 out of the 70 (the most) might log something at the exact same time.

On another note, the Access Database is only used for storing data, nothing else.

    Dim NewCon As ADODB.Connection
    Set NewCon = New ADODB.Connection
    Dim Recordset As ADODB.Recordset
    Set Recordset = New ADODB.Recordset

    NewCon.Open "Provider=Microsoft.ace.oledb.12.0;Data Source=C:\Users\my.user\Desktop\Testing\Database1.accdb"
    Recordset.Open "DATA", NewCon, adOpenDynamic, adLockOptimistic
    Recordset.AddNew
    'Primary Key
    Recordset.Fields(0).Value = G
    'Field 2
    Recordset.Fields(1).Value = A
    'Field 3
    Recordset.Fields(2).Value = B
    'Field 4
    Recordset.Fields(3).Value = C
    'Field 5
    Recordset.Fields(4).Value = D
    'Field 6
    Recordset.Fields(5).Value = E
    'Field 7
    Recordset.Fields(6).Value = F
    'Field 8
    Recordset.Fields(7).Value = Format(Now, "m/d/yyyy h:mm:ss")

    Recordset.Update
    Recordset.Close
    NewCon.Close

Body:
It should not be an issue. Or catch an error and try again.

If you experience serious trouble, you can use the method described here:

Handle concurrent update conflicts in Access silently

which includes a full demo and code:

' Function to replace the Edit method of a DAO.Recordset.
' To be used followed by GetUpdate to automatically handle
' concurrent updates.
'
' 2016-02-06. Gustav Brock, Cactus Data ApS, CPH.
'
Public Sub SetEdit(ByRef rs As DAO.Recordset)

    On Error GoTo Err_SetEdit

    ' Attempt to set rs into edit mode.
    Do While rs.EditMode <> dbEditInProgress
        rs.Edit
        If rs.EditMode = dbEditInProgress Then
            ' rs is ready for edit.
            Exit Do
        End If
    Loop

Exit_SetEdit:
    Exit Sub

Err_SetEdit:
    If DebugMode Then Debug.Print "    Edit", Timer, Err.Description
    If Err.Number = 3197 Then
        ' Concurrent edit.
        ' Continue in the loop.
        ' Will normally happen ONCE only for each call of SetEdit.
        Resume Next
    Else
        ' Other error, like deleted record.
        ' Pass error handling to the calling procedure.
        Resume Exit_SetEdit
    End If

End Sub

and:

' Function to replace the Update method of a DAO.Recordset.
' To be used following SetEdit to automatically handle
' concurrent updates.
'
' 2016-01-31. Gustav Brock, Cactus Data ApS, CPH.
'
Public Function GetUpdate(ByRef rs As DAO.Recordset) As Boolean

    On Error GoTo Err_GetUpdate

    ' Attempt to update rs and terminate edit mode.
    rs.Update

    GetUpdate = True

Exit_GetUpdate:
    Exit Function

Err_GetUpdate:
    If DebugMode Then Debug.Print "    Update", Timer, Err.Description
    ' Update failed.
    ' Cancel and return False.
    rs.CancelUpdate
    Resume Exit_GetUpdate

End Function

Also at GitHub


问:
In Unix, WHILE command not reading file from a different directory
In Unix, WHILE command, I am trying to read a file, which is in another directory. But somehow not working, not even throwing any error.

```<code>while read line
do

echo $line

done < /tmp/myfile.txt
</code>```

The file is present in /tmp folder, has all the permissions.

答:
It is not clear why your while loop is not working. Normally loops, if condition syntax are different for different shell. Hence at the beginning of a shell script file we always define the shell where exactly this script should run and that first line is start with a #. Now do the following and check that might help you.

create a file $vi test.sh
  put the below line in it

```<code>#!/usr/bin/ksh
filename="/tmp/myfile.txt"

while [ 1 ]
do
    read -r line
    if [ ${line:-1} -eq 1 ]; then
        break
    else
        echo $line
    fi
done < "$filename"
</code>```

or

```<code>#!/usr/bin/ksh
filename="/tmp/myfile.txt"

while read -r line
do
  echo $line
done < "$filename"
</code>```

save the file and set the permission like below
    $chmod 777 test.sh

now run the file
    $./test.sh

Body:
In Unix, WHILE command, I am trying to read a file, which is in another directory. But somehow not working, not even throwing any error.

while read line
do

echo $line

done < /tmp/myfile.txt

The file is present in /tmp folder, has all the permissions.

Body:
It is not clear why your while loop is not working. Normally loops, if condition syntax are different for different shell. Hence at the beginning of a shell script file we always define the shell where exactly this script should run and that first line is start with a #. Now do the following and check that might help you.

create a file $vi test.sh
  put the below line in it

#!/usr/bin/ksh
filename="/tmp/myfile.txt"

while [ 1 ]
do
    read -r line
    if [ ${line:-1} -eq 1 ]; then
        break
    else
        echo $line
    fi
done < "$filename"

or

#!/usr/bin/ksh
filename="/tmp/myfile.txt"

while read -r line
do
  echo $line
done < "$filename"

save the file and set the permission like below
    $chmod 777 test.sh

now run the file
    $./test.sh


问:
How to minify ES6 functions with gulp-uglify?
When I run gulp I get the following error:

```<code>[12:54:14] { [GulpUglifyError: unable to minify JavaScript]
cause:
{ [SyntaxError: Unexpected token: operator (>)]
 message: 'Unexpected token: operator (>)',
 filename: 'bundle.js',
 line: 3284,
 col: 46,
 pos: 126739 },
plugin: 'gulp-uglify',
fileName: 'C:\\servers\\vagrant\\workspace\\awesome\\web\\tool\\bundle.js',
showStack: false }
</code>```

The offending line contains an arrow function:

```<code>let zeroCount = numberArray.filter(v => v === 0).length
</code>```

I know I can replace it with the following to remedy the minification error by abandoning ES6 syntax:

```<code>let zeroCount = numberArray.filter(function(v) {return v === 0;}).length
</code>```

How can I minify code containing ES6 features via gulp?

答:
The accepted answer doesn't really answer how to minify straight es6. If you want to minify es6 without transpiling, gulp-uglify v3.0.0 makes that possible:

Update March 2019

Using my original answer, you definitely want to replace the uglify-es package with terser, as it seems uglify-es is no longer being maintained.

Original answer, still works:

1.) First, upgrade your gulp-uglify package to > 3.0.0  If you're using yarn and want to update to the latest version:

```<code>yarn upgrade gulp-uglify --latest
</code>```

2.) Now you can use uglify-es, the "es6 version" of uglify, as so:

```<code>const uglifyes = require('uglify-es');
const composer = require('gulp-uglify/composer');
const uglify = composer(uglifyes, console);

gulp.task('compress', function () {
    return gulp.src('src/*.js')
    .pipe(uglify())
    .pipe(gulp.dest('dist'))
});
</code>```

For more info: https://www.npmjs.com/package/gulp-uglify

ContentLicense: CC BY-SA 4.0

Body:
When I run gulp I get the following error:

[12:54:14] { [GulpUglifyError: unable to minify JavaScript]
cause:
{ [SyntaxError: Unexpected token: operator (>)]
 message: 'Unexpected token: operator (>)',
 filename: 'bundle.js',
 line: 3284,
 col: 46,
 pos: 126739 },
plugin: 'gulp-uglify',
fileName: 'C:\\servers\\vagrant\\workspace\\awesome\\web\\tool\\bundle.js',
showStack: false }

The offending line contains an arrow function:

let zeroCount = numberArray.filter(v => v === 0).length

I know I can replace it with the following to remedy the minification error by abandoning ES6 syntax:

let zeroCount = numberArray.filter(function(v) {return v === 0;}).length

How can I minify code containing ES6 features via gulp?

Body:
The accepted answer doesn't really answer how to minify straight es6. If you want to minify es6 without transpiling, gulp-uglify v3.0.0 makes that possible:

Update March 2019

Using my original answer, you definitely want to replace the uglify-es package with terser, as it seems uglify-es is no longer being maintained.

Original answer, still works:

1.) First, upgrade your gulp-uglify package to > 3.0.0  If you're using yarn and want to update to the latest version:

yarn upgrade gulp-uglify --latest

2.) Now you can use uglify-es, the "es6 version" of uglify, as so:

const uglifyes = require('uglify-es');
const composer = require('gulp-uglify/composer');
const uglify = composer(uglifyes, console);

gulp.task('compress', function () {
    return gulp.src('src/*.js')
    .pipe(uglify())
    .pipe(gulp.dest('dist'))
});

For more info: https://www.npmjs.com/package/gulp-uglify


问:
Is it bad practice to have an output parameter in a method in a WCF service?
I'm looking for reasons beyond the usual "out parameters are confusing and indicate the method is doing more than one thing"-style arguments and more about what is specifically bad about output parameters in WCF services.  Where I work now, we have a rule against them in WCF services, and I'm trying to work out why!</p>

答:
One reason is the out parameters are handled by the proxy class generated when you add the service reference - that's extra overhead.

Another reason: according to this post, even if the original out parameter is last when you consume it, it becomes first - confusing and may lead to complication errors that might take time to solve until someone figures this out.

Personal opinion: WCF operation (method) should do something and return something. It might do lots of things, but return only one thing which is the result - if you need extra stuff just have it return complex type with everything you need as data fields of that type.


问:
Function not working but parts do work separately
This routine is to be part of a web page that will allow users to compile a list of artwork they are interested in by clicking a button next to a work. The list on screen will dynamically update.

My first version had 'add' and 'remove' in two different functions. The responses were hardcoded in an href (addTo removeFrom):

```<code>addToList('artlist','Painting #1')
removeFromList('artlist','')

function addToList(id,listEntry) {
    var container = document.getElementById(id);
    container.innerHTML = listEntry;
}

function removeFromList(id,listEntry) {
    var container = document.getElementById(id);
    container.innerHTML = listEntry;
}
</code>```

It worked.

Then this was updated: An array holding a list was added (like what might be the user's previous choices, and a new selection was put into a variable to simulate an active choice.

But there were problems:

The functions each repeated the guts of the routine

```<code>var screenList = document.getElementById(id);
screenList.innerHTML = listEntry;
</code>```

The user could erase the list by hitting the 'remove' button until it was empty, or adding the new selection and then 'remove'”

The user could just keep adding the new selection over and over.

Attempted to combine them in a new function and using a 'key' variable to disallow adding the new selection more than once and only allowing the new selection to be removed once, so the user could change his/her mind.

I found out about push, pop and innerhtml (when I first tried my hand at javascript years ago these were not around - yeah, I know, I'm old) and was able to move the "container" section out to where I needed it only once.

```<code>var workList = ["Man in Blue", "A Collection of Portraits"];
var work = "Stand Out";

function addremove(id,listEntry) {
    if (typeof key === 'undefined') { // first time through set list with  no change
        var key = 0;                  // intitialize key, key=0, can add selection, key=1 already added
    } else if (key === 0) {           // add user selection to list
        workList.push(work);
        key = key++;                  // key=1 selection added don't add again
    } else if (key === 1) {           // allow user to change mind and remove selection
        workList.pop();
        key = key--;                  // key=0 selection removed - can be added again
    }

    var screenList = document.getElementById(id); // add list to div - artlist
    screenList.innerHTML = listEntry;
}
</code>```

With this version I can get the list to populate when key is undefined but I cannot get a selection added or removed. I ran a test with the console running and no errors or other problems showed up. I figure it's a logic problem but I can't see what needs to be changed.

答:
@Phil @Prisoner Thanks for the help. Here is the working routine:

```<code><script type="text/javascript">
var workList = ["Man in Blue", "A Collection of Portraits"];
var work = "Stand Out";
var key = 3;                        // initialize key, key=0, can add selection, key=1 already added

function addremove(id,listEntry) {

    if (key == 0) {                 // add selection to list
        workList.push(work);
        key++;                      // key=1 selection added don't add again
    } else if (key == 1) {          // allow user to change mind and remove selection
        workList.pop();
        key--;                      // key=0 selection removed - can be added again
    }else if (key == 3) {           // first time through set list with  no change
        key = 0;
    }

    var screenList = document.getElementById(id); // add list to div - artlist
    screenList.innerHTML = listEntry;
}
</script>
</code>```

In the declaration I gave key a value of 3 and got rid of "undefined."

The change of key to 0 was moved to the bottom. (Don't know if that does anything but it looks better to me.

"key = key++" changed to "key++"

It all works. It is nice to get some fresh eyes looking at it.
Thanks again!

Body:
This routine is to be part of a web page that will allow users to compile a list of artwork they are interested in by clicking a button next to a work. The list on screen will dynamically update.

My first version had 'add' and 'remove' in two different functions. The responses were hardcoded in an href (addTo removeFrom):

addToList('artlist','Painting #1')
removeFromList('artlist','')

function addToList(id,listEntry) {
    var container = document.getElementById(id);
    container.innerHTML = listEntry;
}

function removeFromList(id,listEntry) {
    var container = document.getElementById(id);
    container.innerHTML = listEntry;
}

It worked.

Then this was updated: An array holding a list was added (like what might be the user's previous choices, and a new selection was put into a variable to simulate an active choice.

But there were problems:

The functions each repeated the guts of the routine

var screenList = document.getElementById(id);
screenList.innerHTML = listEntry;

The user could erase the list by hitting the 'remove' button until it was empty, or adding the new selection and then 'remove'”

The user could just keep adding the new selection over and over.

Attempted to combine them in a new function and using a 'key' variable to disallow adding the new selection more than once and only allowing the new selection to be removed once, so the user could change his/her mind.

I found out about push, pop and innerhtml (when I first tried my hand at javascript years ago these were not around - yeah, I know, I'm old) and was able to move the "container" section out to where I needed it only once.

var workList = ["Man in Blue", "A Collection of Portraits"];
var work = "Stand Out";

function addremove(id,listEntry) {
    if (typeof key === 'undefined') { // first time through set list with  no change
        var key = 0;                  // intitialize key, key=0, can add selection, key=1 already added
    } else if (key === 0) {           // add user selection to list
        workList.push(work);
        key = key++;                  // key=1 selection added don't add again
    } else if (key === 1) {           // allow user to change mind and remove selection
        workList.pop();
        key = key--;                  // key=0 selection removed - can be added again
    }

    var screenList = document.getElementById(id); // add list to div - artlist
    screenList.innerHTML = listEntry;
}

With this version I can get the list to populate when key is undefined but I cannot get a selection added or removed. I ran a test with the console running and no errors or other problems showed up. I figure it's a logic problem but I can't see what needs to be changed.

Body:
@Phil @Prisoner Thanks for the help. Here is the working routine:

<script type="text/javascript">
var workList = ["Man in Blue", "A Collection of Portraits"];
var work = "Stand Out";
var key = 3;                        // initialize key, key=0, can add selection, key=1 already added

function addremove(id,listEntry) {

    if (key == 0) {                 // add selection to list
        workList.push(work);
        key++;                      // key=1 selection added don't add again
    } else if (key == 1) {          // allow user to change mind and remove selection
        workList.pop();
        key--;                      // key=0 selection removed - can be added again
    }else if (key == 3) {           // first time through set list with  no change
        key = 0;
    }

    var screenList = document.getElementById(id); // add list to div - artlist
    screenList.innerHTML = listEntry;
}
</script>

In the declaration I gave key a value of 3 and got rid of "undefined."

The change of key to 0 was moved to the bottom. (Don't know if that does anything but it looks better to me.

"key = key++" changed to "key++"

It all works. It is nice to get some fresh eyes looking at it.
Thanks again!


问:
Django - allowing specified user to modify certain model fields
I need to allow a certain user, who is specified in the model, to modify a few of the model's fields. I know I need to create a permission class, which will control the whole process, but I have no idea how to do that.
Here's the code sample:

```<code>class Task(models.Model):
   creator = models.ForeignKey('auth.User', related_name='created_tasks', on_delete=models.CASCADE)
   target = models.ForeignKey(User, related_name='assigned_tasks', on_delete=models.CASCADE)
   title = models.CharField(max_length=100)
   description = models.TextField()
   created = models.DateTimeField(auto_now_add=True)
   deadline = models.DateTimeField()
   priority = models.CharField(max_length=50, choices=PRIORITY_CHOICES, default='NORMAL')
   progress = models.CharField(max_length=50, choices=PROGRESS_CHOICES, default='ASSIGNED')
   is_finished = models.BooleanField(default=False)
</code>```

So I want to allow the target, to modify only progress and is_finished fields.

I am using DjangoRestFramework, not sure if that will help.
Should I create a method, which will check if user == target, and ignore all the other changes or is it possible to create a permission which will do that.

答:
serializers.py

```<code>from rest_framework import serializers
class TaskSerializer(serializers.ModelSerializer):
    class Meta:
        model = Task
        exclude = ()

    def update(self, instance, validated_data):
        if self.context['request'].user == specified_user:
            setattr(instance, 'progress', validated_data.get('progress', None))
            setattr(instance, 'is_finished', validated_data.get('is_finished', None))
            instance.save()
            return instance
        return super(TaskSerializer, self).update(instance, validated_data)
</code>```

Body:
I need to allow a certain user, who is specified in the model, to modify a few of the model's fields. I know I need to create a permission class, which will control the whole process, but I have no idea how to do that.
Here's the code sample:

class Task(models.Model):
   creator = models.ForeignKey('auth.User', related_name='created_tasks', on_delete=models.CASCADE)
   target = models.ForeignKey(User, related_name='assigned_tasks', on_delete=models.CASCADE)
   title = models.CharField(max_length=100)
   description = models.TextField()
   created = models.DateTimeField(auto_now_add=True)
   deadline = models.DateTimeField()
   priority = models.CharField(max_length=50, choices=PRIORITY_CHOICES, default='NORMAL')
   progress = models.CharField(max_length=50, choices=PROGRESS_CHOICES, default='ASSIGNED')
   is_finished = models.BooleanField(default=False)

So I want to allow the target, to modify only progress and is_finished fields.

I am using DjangoRestFramework, not sure if that will help.
Should I create a method, which will check if user == target, and ignore all the other changes or is it possible to create a permission which will do that.

Body:
serializers.py

from rest_framework import serializers
class TaskSerializer(serializers.ModelSerializer):
    class Meta:
        model = Task
        exclude = ()

    def update(self, instance, validated_data):
        if self.context['request'].user == specified_user:
            setattr(instance, 'progress', validated_data.get('progress', None))
            setattr(instance, 'is_finished', validated_data.get('is_finished', None))
            instance.save()
            return instance
        return super(TaskSerializer, self).update(instance, validated_data)


问:
Is there a way to use a newer version of MongoDB with Meteor js, as in the one that's shipped with it?
Basically, I've become accustomed to developing with the mongo that's packed with Meteor, not for anything other than development of course.

I'm beginning to run into features of MongoDB in the newer version that isn't available to me with the MongoDB that's shipped with Meteor.

For example, in Mongo, the $sort within a $push no longer requires $slice:

http://docs.mongodb.org/manual/reference/operator/update/sort/

Just curious if this is a limitation or if there's a workaround? I can use a remote DB or local one but the quick dev tools are helpful.

答:
Yes!  Just export an environment variable telling Meteor where to look for the Mongo database instance.

```<code>export MONGO_URL="mongodb://username:password@host:27017"
</code>```

On Windows, add the environment variable to your profile.  Open the System control panel interface (shortcut is Windows Key + Pause), then go to Advanced system Settings on the left, then click Environment Variables.

Under the top section, User variables, click New.  Then enter MONGO_URL in the top field, and the mongodb url in the bottom field.

That should do it!

Body:
Yes!  Just export an environment variable telling Meteor where to look for the Mongo database instance.

export MONGO_URL="mongodb://username:password@host:27017"

On Windows, add the environment variable to your profile.  Open the System control panel interface (shortcut is Windows Key + Pause), then go to Advanced system Settings on the left, then click Environment Variables.

Under the top section, User variables, click New.  Then enter MONGO_URL in the top field, and the mongodb url in the bottom field.

That should do it!


问:
Dynamic height and width for knitr plots
In knitr, one can specify the size of plot by simply specifying it in the chunk options.

For example:

```<code>```{r, fig.width=9,fig.height=3}
plot(x)
```
</code>```

I would like to be able to dynamically adjust the figure height and width on the basis of variables in x. Let's say that x is a data.frame:

```<code>x <- data.frame(x=factor(letters[1:3]),y=rnorm(3))
</code>```

For example's sake lets say I would like to adjust fig.height to be equal to length(unique(x$x))

答:
I just found a great blog post about this.

Read more at Michael J Williams' blog - I've shamelessly pilfered the code, so more detail there. Remember to set chunk options to results = "asis".

Say you want to output a bunch of plots using a loop but you want them to each have different sizes. Define the following function (again, I'm just copy-pasting here):

```<code>subchunkify <- function(g, fig_height=7, fig_width=5) {
  g_deparsed <- paste0(deparse(
    function() {g}
  ), collapse = '')

  sub_chunk <- paste0("
  `","``{r sub_chunk_", floor(runif(1) * 10000), ", fig.height=",
   fig_height, ", fig.width=", fig_width, ", echo=FALSE}",
  "\n(",
    g_deparsed
    , ")()",
  "\n`","``
  ")

  cat(knitr::knit(text = knitr::knit_expand(text = sub_chunk), quiet = TRUE))
}
</code>```

And use the function like this, defining your own figure sizes:

```<code>```{r echo=FALSE, results='asis'}
g <- ggplot(economics, aes(date, unemploy)) +
  geom_line()
subchunkify(g, 10, 3)
subchunkify(g, 7, 7)
```
</code>```

Or let the data define the sizes:

```<code>```{r echo=FALSE, results='asis'}
g <- ggplot(economics, aes(date, unemploy)) +
  geom_line()
for (i in seq(2, 5)) {
  subchunkify(g, i / 2, i)
}
```
</code>```

In the post Michael warns that you must be careful:

Since we’re using results='asis', if we want to output text or headings or anything else from the chunk, we must use raw HTML, not Markdown, and we must use cat() to do this, not print(). For instance:

```<code>g <- ggplot(economics, aes(date, unemploy)) +
  geom_line()

cat('<h2>A Small Square Plot</h2>')
subchunkify(g, 3, 3)
</code>```

Again, not my work... head on over to that lovely blog post for more details. Hope this works for you.

Body:
In knitr, one can specify the size of plot by simply specifying it in the chunk options.

For example:

```{r, fig.width=9,fig.height=3}
plot(x)
```

I would like to be able to dynamically adjust the figure height and width on the basis of variables in x. Let's say that x is a data.frame:

x <- data.frame(x=factor(letters[1:3]),y=rnorm(3))

For example's sake lets say I would like to adjust fig.height to be equal to length(unique(x$x))

Body:
I just found a great blog post about this.

Read more at Michael J Williams' blog - I've shamelessly pilfered the code, so more detail there. Remember to set chunk options to results = "asis".

Say you want to output a bunch of plots using a loop but you want them to each have different sizes. Define the following function (again, I'm just copy-pasting here):

subchunkify <- function(g, fig_height=7, fig_width=5) {
  g_deparsed <- paste0(deparse(
    function() {g}
  ), collapse = '')

  sub_chunk <- paste0("
  `","``{r sub_chunk_", floor(runif(1) * 10000), ", fig.height=",
   fig_height, ", fig.width=", fig_width, ", echo=FALSE}",
  "\n(",
    g_deparsed
    , ")()",
  "\n`","``
  ")

  cat(knitr::knit(text = knitr::knit_expand(text = sub_chunk), quiet = TRUE))
}

And use the function like this, defining your own figure sizes:

```{r echo=FALSE, results='asis'}
g <- ggplot(economics, aes(date, unemploy)) +
  geom_line()
subchunkify(g, 10, 3)
subchunkify(g, 7, 7)
```

Or let the data define the sizes:

```{r echo=FALSE, results='asis'}
g <- ggplot(economics, aes(date, unemploy)) +
  geom_line()
for (i in seq(2, 5)) {
  subchunkify(g, i / 2, i)
}
```

In the post Michael warns that you must be careful:

Since we’re using results='asis', if we want to output text or headings or anything else from the chunk, we must use raw HTML, not Markdown, and we must use cat() to do this, not print(). For instance:

g <- ggplot(economics, aes(date, unemploy)) +
  geom_line()

cat('<h2>A Small Square Plot</h2>')
subchunkify(g, 3, 3)

Again, not my work... head on over to that lovely blog post for more details. Hope this works for you.


问:
Sample of a gzipped file on Azure Datalake
How do I preview a .gz file on the azure data lake via cli?
Through the portal, I cannot preview a gzipped file.  I have only access to the CLI.</p>

答: This is not currently possible. Preview does not work with zipped files. </p>


问:
Return sums even if no data exist in given day
I have a table with amounts only on some days, e.g.:

```<code>[DATE] [AMT]
11/1/2017 $123
11/1/2017 $50
11/3/2017 $123
</code>```

How can I query the data and get:

```<code>11/1/2017 $173
11/2/2017 $0
11/3/2017 $123
</code>```

I tried like:

```<code>SELECT Day([Date]) AS [Day], Nz(Sum(AMT),0) AS [Day Total]
FROM mytable
WHERE Month([Date])=11
GROUP BY Day([Date]);
</code>```

But still it doesn't return 0s for days without data, any ideas?

答:
You need a table with all the days, so you can fill the holes, lets call it allDays

Get a list of dates between two dates using a function

Then your query is:

```<code> SELECT a.[date], COALESCE(SUM([AMT]),0)
 FROM allDates a
 LEFT JOIN yourTable t
   ON a.[date] = t.[date]
 GROUP BY a.[date]
</code>```

Body:
I have a table with amounts only on some days, e.g.:

[DATE] [AMT]
11/1/2017 $123
11/1/2017 $50
11/3/2017 $123

How can I query the data and get:

11/1/2017 $173
11/2/2017 $0
11/3/2017 $123

I tried like:

SELECT Day([Date]) AS [Day], Nz(Sum(AMT),0) AS [Day Total]
FROM mytable
WHERE Month([Date])=11
GROUP BY Day([Date]);

But still it doesn't return 0s for days without data, any ideas?

Body:
You need a table with all the days, so you can fill the holes, lets call it allDays

Get a list of dates between two dates using a function

Then your query is:

 SELECT a.[date], COALESCE(SUM([AMT]),0)
 FROM allDates a
 LEFT JOIN yourTable t
   ON a.[date] = t.[date]
 GROUP BY a.[date]


问:
DebugBreak() equivalent in C#
In C# is there any statement equivalent to DebugBreak()? I want to invoke the debugger when ever a particular condition is met.

答:
Concerning the other answers, I prefer using Debugger.Launch().

If the application is not already running in a debugger, Launch() will call up the debugger dialog allowing you to attach Visual Studio (or another debugger) to the process.  However, if you are already debugging, it will sail right past the Debugger.Launch() call.  Break(), on the other hand, will act as a breakpoint - breaking every time it hits that point (and invoking the debugger dialog if the process has not been attached).

Be VERY careful not to leave either statement in your code. Sending code with Debugger calls out to production can halt your application or create very hard to track down errors (bad experience last month).

Title: DebugBreak() equivalent in C#


问:
write the result into input field
I have problem with my javascript. I'm not able to display the results in the input field. Please can anyone help me?? And if it possible it will be better to calculate the result without clicking on the button!! Thanks.

```
<pre class="snippet-code-html lang-html prettyprint-override"><code><span style="font-size:20px;">Your bid:</span> <input type="number"    name="bid" class="form-control" style="max-width:250px; margin-top:10px;"> <br>
        <input type="button" onClick="cal();">
        <span style="font-size:20px;" >Our Fee (10%):</span><input type="number" name="fee" readonly class="form-control" style="max-width:250px; margin-top:10px;"><br>
        <span style="font-size:20px;">You'll paid:</span> <input type="number"  name="get" readonly class="form-control" style="max-width:250px; margin-top:10px;"></code>```

答:
Only form-field elements have a value attribute/property. For regular elements, you want either the .textContent (for plain text) or the .innerHTML (for strings with HTML in them) properties.

Next, avoid inline styles as they just make the HTML more difficult to read and lead to duplication of code. On the same vein, don't use inline HTML event attributes (onclick). There are many reasons for that.

Next, don't use .getElementsByName() as this returns a "live node list", which is only right for a few use cases and can be wasteful otherwise. Give your form fields, not only a name attribute, but also a (usually) matching id attribute as well.

Next, don't use form elements if you aren't expecting users to interact with them (the fee and total areas).

See comments in code below:

// Get references to the DOM elements you will need just once:
var fee = document.getElementById("fee");
var get = document.getElementById("get");
var bid = document.getElementById("bid")
var btn = document.querySelector("input[type=button]");

// Set up event handling in JavaScript, not HTML:
btn.addEventListener("click", cal);

// You can also have the cal function run as the user enters
// their bid. No button click needed.
bid.addEventListener("input", cal);

function cal(){
  var result1 = bid.value * 0.1;
  var result2 = bid.value - result1;
  fee.textContent = result1;
  get.textContent = result2;
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>span {
  font-size:20px;
}

.formField {
   max-width:250px;
   margin-top:10px;
}</code>```

Your bid:
<input type="number" id="bid" name="bid" class="form-control" class="formField">

<input type="button">
Our Fee (10%):

You'll paid:
```

Title: write the result into input field

Body:
I have problem with my javascript. I'm not able to display the results in the input field. Please can anyone help me?? And if it possible it will be better to calculate the result without clicking on the button!! Thanks.

Your bid: <input type="number"    name="bid" class="form-control" style="max-width:250px; margin-top:10px;">

        <input type="button" onClick="cal();">
        Our Fee (10%):<input type="number" name="fee" readonly class="form-control" style="max-width:250px; margin-top:10px;">

        You'll paid: <input type="number"  name="get" readonly class="form-control" style="max-width:250px; margin-top:10px;">

Body:
Only form-field elements have a value attribute/property. For regular elements, you want either the .textContent (for plain text) or the .innerHTML (for strings with HTML in them) properties.

Next, avoid inline styles as they just make the HTML more difficult to read and lead to duplication of code. On the same vein, don't use inline HTML event attributes (onclick). There are many reasons for that.

Next, don't use .getElementsByName() as this returns a "live node list", which is only right for a few use cases and can be wasteful otherwise. Give your form fields, not only a name attribute, but also a (usually) matching id attribute as well.

Next, don't use form elements if you aren't expecting users to interact with them (the fee and total areas).

See comments in code below:

// Get references to the DOM elements you will need just once:
var fee = document.getElementById("fee");
var get = document.getElementById("get");
var bid = document.getElementById("bid")
var btn = document.querySelector("input[type=button]");

// Set up event handling in JavaScript, not HTML:
btn.addEventListener("click", cal);

// You can also have the cal function run as the user enters
// their bid. No button click needed.
bid.addEventListener("input", cal);

function cal(){
  var result1 = bid.value * 0.1;
  var result2 = bid.value - result1;
  fee.textContent = result1;
  get.textContent = result2;
}

span {
  font-size:20px;
}

.formField {
   max-width:250px;
   margin-top:10px;
}

<span>Your bid:</span>
<input type="number" id="bid" name="bid" class="form-control" class="formField"><br>
<input type="button">
<span>Our Fee (10%):</span>
<span id="fee"></span><br>
<span>You'll paid:</span>
<span id="get"></span>


问:
PyQt5: Timer in a thread
Problem Description

I'm trying to make an application that collects data, processes it, displays it, and some actuation (open/close valves, etc). As a practice for future applications where I have some stricter time constraints, I want to run the data capture and processing in a separate thread.

My current problem is that it's telling me I cannot start a timer from another thread.

Current code progress

```<code>import sys
import PyQt5
from PyQt5.QtWidgets import *
from PyQt5.QtCore import QThread, pyqtSignal

# This is our window from QtCreator
import mainwindow_auto

#thread to capture the process data
class DataCaptureThread(QThread):
    def collectProcessData():
        print ("Collecting Process Data")
    #declaring the timer
    dataCollectionTimer = PyQt5.QtCore.QTimer()
    dataCollectionTimer.timeout.connect(collectProcessData)
    def __init__(self):
        QThread.__init__(self)

    def run(self):
        self.dataCollectionTimer.start(1000);

class MainWindow(QMainWindow, mainwindow_auto.Ui_MainWindow):
    def __init__(self):
        super(self.__class__, self).__init__()
        self.setupUi(self) # gets defined in the UI file
        self.btnStart.clicked.connect(self.pressedStartBtn)
        self.btnStop.clicked.connect(self.pressedStopBtn)

    def pressedStartBtn(self):
        self.lblAction.setText("STARTED")
        self.dataCollectionThread = DataCaptureThread()
        self.dataCollectionThread.start()
    def pressedStopBtn(self):
        self.lblAction.setText("STOPPED")
        self.dataCollectionThread.terminate()

def main():
     # a new app instance
     app = QApplication(sys.argv)
     form = MainWindow()
     form.show()
     sys.exit(app.exec_())

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

Any advice on how to get this to work would be appreciated!

答:
You have to move the QTimer to the DataCaptureThread thread, in addition to that when the run method ends, the thread is eliminated so the timer is eliminated, so you must avoid running that function without blocking other tasks. QEventLoop is used for this:</p>

```<code>class DataCaptureThread(QThread):
    def collectProcessData(self):
        print ("Collecting Process Data")

    def __init__(self, *args, **kwargs):
        QThread.__init__(self, *args, **kwargs)
        self.dataCollectionTimer = QTimer()
        self.dataCollectionTimer.moveToThread(self)
        self.dataCollectionTimer.timeout.connect(self.collectProcessData)

    def run(self):
        self.dataCollectionTimer.start(1000)
        loop = QEventLoop()
        loop.exec_()
</code>```

Title: PyQt5: Timer in a thread

Body:
Problem Description

I'm trying to make an application that collects data, processes it, displays it, and some actuation (open/close valves, etc). As a practice for future applications where I have some stricter time constraints, I want to run the data capture and processing in a separate thread.

My current problem is that it's telling me I cannot start a timer from another thread.

Current code progress

import sys
import PyQt5
from PyQt5.QtWidgets import *
from PyQt5.QtCore import QThread, pyqtSignal

# This is our window from QtCreator
import mainwindow_auto

#thread to capture the process data
class DataCaptureThread(QThread):
    def collectProcessData():
        print ("Collecting Process Data")
    #declaring the timer
    dataCollectionTimer = PyQt5.QtCore.QTimer()
    dataCollectionTimer.timeout.connect(collectProcessData)
    def __init__(self):
        QThread.__init__(self)

    def run(self):
        self.dataCollectionTimer.start(1000);

class MainWindow(QMainWindow, mainwindow_auto.Ui_MainWindow):
    def __init__(self):
        super(self.__class__, self).__init__()
        self.setupUi(self) # gets defined in the UI file
        self.btnStart.clicked.connect(self.pressedStartBtn)
        self.btnStop.clicked.connect(self.pressedStopBtn)

    def pressedStartBtn(self):
        self.lblAction.setText("STARTED")
        self.dataCollectionThread = DataCaptureThread()
        self.dataCollectionThread.start()
    def pressedStopBtn(self):
        self.lblAction.setText("STOPPED")
        self.dataCollectionThread.terminate()

def main():
     # a new app instance
     app = QApplication(sys.argv)
     form = MainWindow()
     form.show()
     sys.exit(app.exec_())

if __name__ == "__main__":
     main()

Any advice on how to get this to work would be appreciated!

Body:
You have to move the QTimer to the DataCaptureThread thread, in addition to that when the run method ends, the thread is eliminated so the timer is eliminated, so you must avoid running that function without blocking other tasks. QEventLoop is used for this:

class DataCaptureThread(QThread):
    def collectProcessData(self):
        print ("Collecting Process Data")

    def __init__(self, *args, **kwargs):
        QThread.__init__(self, *args, **kwargs)
        self.dataCollectionTimer = QTimer()
        self.dataCollectionTimer.moveToThread(self)
        self.dataCollectionTimer.timeout.connect(self.collectProcessData)

    def run(self):
        self.dataCollectionTimer.start(1000)
        loop = QEventLoop()
        loop.exec_()


问:
Use derived type in base abstract class
Ok, I have a number of different classes deriving from a base class.
This base class is an abstract containing commom methods.

One of the methods is a Copy method, wich should be present in all derived classes, so, I've put it in the base class.
BUT, I want it to return the derived type not the base nor object.

The solution I got for that, is using a type paramter:

```<code>abstract class CopyableClass<T>
{
    public abstract T Copy();
}

class DerivedClass : CopyableClass<DerivedClass>
{
    public override DerivedClass Copy()
    {
        //do what is needed for copy and return a new DerivedClass
    }
}
</code>```

So, the main purpose here is to

Remove the type parameter in the base class and still make the method return the corresponding derived type.

One workaround.

The best thing I could do so far is one of the comments below, but it still uses a generic parameter

```<code>abstract class BaseClass
{
    //base methods not related to deriving type
}

interface ICopyable<T>
{
     T Copy();
}

class DerivedClass : BaseClass, ICopyable<DerivedClass>
{
    public DerivedClass Copy()
    {
        //do what is needed for copy and return a new DerivedClass
    }
}
</code>```

答:
This solution involves a middle class but I think its more inline with what the you are looking for. At least you get the possible benefit of isolating your copy code</p>

```<code>    public abstract class BaseClass
    {
    }

    public abstract class CopyableClass<T> : BaseClass
        where T: BaseClass, new()
    {
        public T Copy()
        {
            var copy = new T(); // Creating a new instance as proof of concept

            return copy;
        }
    }

    public class DerivedClass : CopyableClass<DerivedClass>
    {
    }
</code>```

Title: Use derived type in base abstract class

Body:
Ok, I have a number of different classes deriving from a base class.
This base class is an abstract containing commom methods.

One of the methods is a Copy method, wich should be present in all derived classes, so, I've put it in the base class.
BUT, I want it to return the derived type not the base nor object.

The solution I got for that, is using a type paramter:

abstract class CopyableClass<T>
{
    public abstract T Copy();
}

class DerivedClass : CopyableClass<DerivedClass>
{
    public override DerivedClass Copy()
    {
        //do what is needed for copy and return a new DerivedClass
    }
}

So, the main purpose here is to

Remove the type parameter in the base class and still make the method return the corresponding derived type.

One workaround.

The best thing I could do so far is one of the comments below, but it still uses a generic parameter

abstract class BaseClass
{
    //base methods not related to deriving type
}

interface ICopyable<T>
{
     T Copy();
}

class DerivedClass : BaseClass, ICopyable<DerivedClass>
{
    public DerivedClass Copy()
    {
        //do what is needed for copy and return a new DerivedClass
    }
}

Body:
This solution involves a middle class but I think its more inline with what the you are looking for. At least you get the possible benefit of isolating your copy code

    public abstract class BaseClass
    {
    }

    public abstract class CopyableClass<T> : BaseClass
        where T: BaseClass, new()
    {
        public T Copy()
        {
            var copy = new T(); // Creating a new instance as proof of concept

            return copy;
        }
    }

    public class DerivedClass : CopyableClass<DerivedClass>
    {
    }


问:
JavaScript Add function called as many times as you wanted
The simplest question for that is like to write a function that could return the sum of all the parameters. How I can do that? </p>

```<code>function add () {

}
add(1)(2)(3)();  //6
add(5)(6)(7)(8)(9)()  //35
</code>```

答:
The basic idea is to create a closure with a variable sum that we can update, and return the sum if the value is undefined, or the the inner function:

const add = (n) => {
  let sum;

  const inner = (n) => n === undefined ? sum : (sum = (sum || 0) + n, inner);

  return inner(n);
};

console.log(add(1)(2)(3)());  //6
console.log(add(5)(6)(7)(8)(9)());  //35```

Body:
The simplest question for that is like to write a function that could return the sum of all the parameters. How I can do that?

function add () {

}
add(1)(2)(3)();  //6
add(5)(6)(7)(8)(9)()  //35


问:
Dependency injection for derived concrete classes
Hope this makes sense:

I have two classes:

ZombieRequest

VampireRequest

They both have to dependency inject:

ICreatureRequest
(which holds endpoints that ZombieRequest and VampireRequest must use)

They both derive from abstract class:

MonsterRequest
(which includes a common method for both ZombieRequest & VampireRequest (validates the response sent back from ICreatureRequest). Also defines how it should be used as an API (success variable, error variable, and a sendRequest() method))

Here's like the pseudo code of how it looks:

ZombieRequest : MonsterRequest

~~ use ICreatureRequest API endpoint~~

~~ use MonsterRequest method to validate the response~~

VampireRequest: MonsterRequest

~~ use ICreatureRequest API endpoint~~

~~ use MonsterRequest method to validate the response~~

In my controller I want to use ZombieRequest and/or VampireRequest, but I am getting lost with how to actually get it in there and use it.

Do I make an IMonsterRequest and inject that in the controller's constructor? But then how do I use a ZombieRequest or a VampireRequest from that?

Controller:

```<code>Get(string someVariable, string anotherVariable)
{
    ZombieRequest z = new ZombieRequest();
    if (z.SendRequest(someVariable, anotherVariable).Success)
       string zombieData = z.ResponseData
}
</code>```

ZombieRequest:

```<code>class ZombieRequest : MonsterRequest
{
   ICreatureRequest  m_CreatureRequest;

   public ZombieRequest(ICreatureRequest c)
   {
      m_CreatureRequest = c;
   }

   public MakeRequest(someVar, anotherVar)
   {
      var response = m_CreatureRequest.GetZombie(someVar, anotherVar);
      ValidateAndSetResponseData(response);
   }
}
</code>```

MonsterRequest:

```<code>abstract class MonsterRequest
{
    public bool Success;
    public string Data;
    public abstract MakeRequest(someVar, anotherVar);

    public void ValidateAndSetResponseData(var response)
    {
        // read response and:
        // set Success
        // set Data
    }

}
</code>```

But apparently I still need to supply a 'ICreatureRequest' when I make the object. Little confused.

答:
Okay, this is starting to make sense so I'll take a crack at an answer. You need to learn the difference between Dependency Injection and a Dependency Injection Framework (sometimes called an Inversion of Control Container or IoC Container).

Your VampireRequest and ZombieRequest classes are set up to allow dependency injection. Your constructors accept the dependencies needed by the code. Your Controller, however, is clearly not set up for dependency injection since you are newing up a request.

So, focusing on the Vampire and Zombie classes..

First, I'll suggest you could move the ICreatureRequest up the hierarchy into MonsterRequest.

More importantly, in order to use dependency injection and create a VampireRequest, you have no choice but to create an instance of ICreatureRequest first. Since you are doing the newing in your controller, you will have to get an instance of the ICreatureRequest there too.

As you identified, why should the controller know about a specific instance of ICreatureRequest just to use MonsterRequest? It probably shouldn't. So you have a few choices: 1) ignore this rule and just have your controller create the ICreatureRequest. 2) inject an ICreatureRequest into the controller. 3) inject a fully created MonsterRequest into the controller. 4) Use an IoC Container to create all your dependencies for you automatically.

You've already made it clear you don't like the sounds of option 1. If you go with option 2 or 3 you'll soon notice that someone needs to new up the ICreatureRequest to pass to the Controller, so you'll probably be back in a few hours. Option 4 is probably the gap in your understanding and pretty much what everyone is talking about when they say dependency injection. It's also a much larger topic than I want to broach here, so instead I'll just refer you to documentation for one of my personal favourites: https://simpleinjector.readthedocs.io/en/latest/index.html

Body:
Hope this makes sense:

I have two classes:

ZombieRequest

VampireRequest

They both have to dependency inject:

ICreatureRequest
(which holds endpoints that ZombieRequest and VampireRequest must use)

They both derive from abstract class:

MonsterRequest
(which includes a common method for both ZombieRequest & VampireRequest (validates the response sent back from ICreatureRequest). Also defines how it should be used as an API (success variable, error variable, and a sendRequest() method))

Here's like the pseudo code of how it looks:

ZombieRequest : MonsterRequest

~~ use ICreatureRequest API endpoint~~

~~ use MonsterRequest method to validate the response~~

VampireRequest: MonsterRequest

~~ use ICreatureRequest API endpoint~~

~~ use MonsterRequest method to validate the response~~

In my controller I want to use ZombieRequest and/or VampireRequest, but I am getting lost with how to actually get it in there and use it.

Do I make an IMonsterRequest and inject that in the controller's constructor? But then how do I use a ZombieRequest or a VampireRequest from that?

Controller:

Get(string someVariable, string anotherVariable)
{
    ZombieRequest z = new ZombieRequest();
    if (z.SendRequest(someVariable, anotherVariable).Success)
       string zombieData = z.ResponseData
}

ZombieRequest:

class ZombieRequest : MonsterRequest
{
   ICreatureRequest  m_CreatureRequest;

   public ZombieRequest(ICreatureRequest c)
   {
      m_CreatureRequest = c;
   }

   public MakeRequest(someVar, anotherVar)
   {
      var response = m_CreatureRequest.GetZombie(someVar, anotherVar);
      ValidateAndSetResponseData(response);
   }
}

MonsterRequest:

abstract class MonsterRequest
{
    public bool Success;
    public string Data;
    public abstract MakeRequest(someVar, anotherVar);

    public void ValidateAndSetResponseData(var response)
    {
        // read response and:
        // set Success
        // set Data
    }

}

But apparently I still need to supply a 'ICreatureRequest' when I make the object. Little confused.


问:
Load external JSON data with pure JavaScript
I am trying a JavaScript challenge but get stuck badly. The requirement is not to modify any other files except app.js and no library (i.e. no JQuery etc.)

Here is the file system:

```<code>css
  bootstrap.min.css
image
  1.gif
  2.gif
  3.gif
  4.gif
  5.gif
js
  app.js
json
  data.js
sample.html
</code>```

Here is the sample.html:

```<code><!doctype>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1, maximum-scale=1">
<title>Sample</title>
<link rel="stylesheet" href="css/bootstrap.min.css">
</head>
<body>
<div class="container">
  <h2>Only Pure JavaScript</h2>
  <div class="contents">
    <table class="table">
      <thead>
        <tr>
          <th>Id</th>
          <th>Image</th>
          <th>Name</th>
          <th>Price</th>
        </tr>
      </thead>
      <tbody>
      </tbody>
    </table>
  </div>
</div>
<script src="json/data.js"></script>
<script src="js/app.js"></script>
</body>
</html>
</code>```

Here is the data.js:

```<code>var sample_data = [
  {
    "id": "5",
    "name": "name #5",
    "thumbnailUrl": "image/5.gif",
    "price": 170
  },
  {
    "id": "1",
    "name": "name #1",
    "thumbnailUrl": "image/1.gif",
    "price": 170
  },
  {
    "id": "2",
    "name": "name #2",
    "thumbnailUrl": "image/2.gif",
    "price": 270
  },
  {
    "id": "8",
    "name": "name #8",
    "thumbnailUrl": "image/8.gif",
    "price": 70
  },
  {
    "id": "10",
    "name": "name #10",
    "thumbnailUrl": "image/10.gif",
    "price": 170
  },
]
</code>```

And this is what I have in app.js currently:

```<code>var jsonFile = "json/data.js";
var len = sample_data.length;
// document.write('len: ' + len + "<br>");

var table = document.createElement('table');
var body = document.createElement('tbody');

for (var i = 0; i < len; i++) {
    var tr = document.createElement('tr');
    var td = document.createElement('td');
    var s = sample_data[i];

    document.write('id: ' + s.id + "<br>");

    td.innerHTML = s.id;
    tr.appendChild(td);

    td = document.createElement('td');
    document.write('name: ' + s.name + "<br>");
    td.innerHTML = s.name;
    tr.appendChild(td);

    td = document.createElement('td');
    document.write('thumbnailUrl: ' + s.thumbnailUrl + "<br>");
    td.innerHTML = s.thumbnailUrl;
    tr.appendChild(td);

    td = document.createElement('td');
    document.write('price: ' + s.price + "<br>");
    td.innerHTML = s.price;
    tr.appendChild(td);

    body.appendChild(tr);
}

table.appendChild(body);
</code>```

I've spent so much time and tried 4 different ways and this one attached is the closest I can get (it shows correctly with document.write). Seriously, without any library or changes in the html page, it is hard for me. Any help or direction of where to look for information will be greatly appreciated. Remember, only app.js can be changed for this.

答:
Do you really need document.write ? Replace it with a simple console.log if you only need it for debugging purposes.

Moreover doesn't look like you are appending the table element anywhere.
Add document.body.appendChild(table) at the end of app.js.

However from your sample.html I can see you already have an existing TBODY element, thus you most likely want to add the values to that existing table.

Instead of doing

var body = document.createElement('tbody');

you can reference the existing element with

var body = document.getElementsByTagName('tbody')[0]

at that point you can remove the table variable completely.

var jsonFile = "json/data.js";
var len = sample_data.length;
// document.write('len: ' + len + "
");

var body = document.getElementsByTagName('tbody')[0];

for (var i = 0; i < len; i++) {
    var tr = document.createElement('tr');
    var td = document.createElement('td');
    var s = sample_data[i];

    //console.log('id: ' + s.id);

    td.innerHTML = s.id;
    tr.appendChild(td);

    td = document.createElement('td');
    //console.log('name: ' + s.name);
    td.innerHTML = s.name;
    tr.appendChild(td);

    td = document.createElement('td');
    //console.log('thumbnailUrl: ' + s.thumbnailUrl);
    td.innerHTML = s.thumbnailUrl;
    tr.appendChild(td);

    td = document.createElement('td');
    //console.log('price: ' + s.price);
    td.innerHTML = s.price;
    tr.appendChild(td);

    body.appendChild(tr);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!doctype>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1, maximum-scale=1">
<title>Sample</title>
<link rel="stylesheet" href="css/bootstrap.min.css">
</head>
<body>
<div class="container">
  <h2>Only Pure JavaScript</h2>
  <div class="contents">
    <table class="table">
      <thead>
        <tr>
          <th>Id</th>
          <th>Image</th>
          <th>Name</th>
          <th>Price</th>
        </tr>
      </thead>
      <tbody>
      </tbody>
    </table>
  </div>
</div>
<script>
var sample_data = [
  {
    "id": "5",
    "name": "name #5",
    "thumbnailUrl": "image/5.gif",
    "price": 170
  },
  {
    "id": "1",
    "name": "name #1",
    "thumbnailUrl": "image/1.gif",
    "price": 170
  },
  {
    "id": "2",
    "name": "name #2",
    "thumbnailUrl": "image/2.gif",
    "price": 270
  },
  {
    "id": "8",
    "name": "name #8",
    "thumbnailUrl": "image/8.gif",
    "price": 70
  },
  {
    "id": "10",
    "name": "name #10",
    "thumbnailUrl": "image/10.gif",
    "price": 170
  },
]
</script>
<script src="js/app.js"></script>
</body>
</html></code>```

Body:
I am trying a JavaScript challenge but get stuck badly. The requirement is not to modify any other files except app.js and no library (i.e. no JQuery etc.)

Here is the file system:

css
  bootstrap.min.css
image
  1.gif
  2.gif
  3.gif
  4.gif
  5.gif
js
  app.js
json
  data.js
sample.html

Here is the sample.html:

<!doctype>

<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1, maximum-scale=1">
<title>Sample</title>
<link rel="stylesheet" href="css/bootstrap.min.css">

Only Pure JavaScript

          Id
          Image
          Name
          Price

Here is the data.js:

var sample_data = [
  {
    "id": "5",
    "name": "name #5",
    "thumbnailUrl": "image/5.gif",
    "price": 170
  },
  {
    "id": "1",
    "name": "name #1",
    "thumbnailUrl": "image/1.gif",
    "price": 170
  },
  {
    "id": "2",
    "name": "name #2",
    "thumbnailUrl": "image/2.gif",
    "price": 270
  },
  {
    "id": "8",
    "name": "name #8",
    "thumbnailUrl": "image/8.gif",
    "price": 70
  },
  {
    "id": "10",
    "name": "name #10",
    "thumbnailUrl": "image/10.gif",
    "price": 170
  },
]

And this is what I have in app.js currently:

var jsonFile = "json/data.js";
var len = sample_data.length;
// document.write('len: ' + len + "
");

var table = document.createElement('table');
var body = document.createElement('tbody');

for (var i = 0; i < len; i++) {
    var tr = document.createElement('tr');
    var td = document.createElement('td');
    var s = sample_data[i];

    document.write('id: ' + s.id + "
");

    td.innerHTML = s.id;
    tr.appendChild(td);

    td = document.createElement('td');
    document.write('name: ' + s.name + "
");
    td.innerHTML = s.name;
    tr.appendChild(td);

    td = document.createElement('td');
    document.write('thumbnailUrl: ' + s.thumbnailUrl + "
");
    td.innerHTML = s.thumbnailUrl;
    tr.appendChild(td);

    td = document.createElement('td');
    document.write('price: ' + s.price + "
");
    td.innerHTML = s.price;
    tr.appendChild(td);

    body.appendChild(tr);
}

table.appendChild(body);

I've spent so much time and tried 4 different ways and this one attached is the closest I can get (it shows correctly with document.write). Seriously, without any library or changes in the html page, it is hard for me. Any help or direction of where to look for information will be greatly appreciated. Remember, only app.js can be changed for this.

Body:
Do you really need document.write ? Replace it with a simple console.log if you only need it for debugging purposes.

Moreover doesn't look like you are appending the table element anywhere.
Add document.body.appendChild(table) at the end of app.js.

However from your sample.html I can see you already have an existing TBODY element, thus you most likely want to add the values to that existing table.

Instead of doing

var body = document.createElement('tbody');

you can reference the existing element with

var body = document.getElementsByTagName('tbody')[0]

at that point you can remove the table variable completely.

var jsonFile = "json/data.js";
var len = sample_data.length;
// document.write('len: ' + len + "<br>");

var body = document.getElementsByTagName('tbody')[0];

for (var i = 0; i < len; i++) {
    var tr = document.createElement('tr');
    var td = document.createElement('td');
    var s = sample_data[i];

    //console.log('id: ' + s.id);

    td.innerHTML = s.id;
    tr.appendChild(td);

    td = document.createElement('td');
    //console.log('name: ' + s.name);
    td.innerHTML = s.name;
    tr.appendChild(td);

    td = document.createElement('td');
    //console.log('thumbnailUrl: ' + s.thumbnailUrl);
    td.innerHTML = s.thumbnailUrl;
    tr.appendChild(td);

    td = document.createElement('td');
    //console.log('price: ' + s.price);
    td.innerHTML = s.price;
    tr.appendChild(td);

    body.appendChild(tr);
}

<!doctype>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1, maximum-scale=1">
<title>Sample</title>
<link rel="stylesheet" href="css/bootstrap.min.css">
</head>
<body>
<div class="container">
  <h2>Only Pure JavaScript</h2>
  <div class="contents">
    <table class="table">
      <thead>
        <tr>
          <th>Id</th>
          <th>Image</th>
          <th>Name</th>
          <th>Price</th>
        </tr>
      </thead>
      <tbody>
      </tbody>
    </table>
  </div>
</div>
<script>
var sample_data = [
  {
    "id": "5",
    "name": "name #5",
    "thumbnailUrl": "image/5.gif",
    "price": 170
  },
  {
    "id": "1",
    "name": "name #1",
    "thumbnailUrl": "image/1.gif",
    "price": 170
  },
  {
    "id": "2",
    "name": "name #2",
    "thumbnailUrl": "image/2.gif",
    "price": 270
  },
  {
    "id": "8",
    "name": "name #8",
    "thumbnailUrl": "image/8.gif",
    "price": 70
  },
  {
    "id": "10",
    "name": "name #10",
    "thumbnailUrl": "image/10.gif",
    "price": 170
  },
]
</script>
<script src="js/app.js"></script>
</body>
</html>