问:
Adding filterBy to p:dataTable causes java.lang.NullPointerException at javax.faces.component.StateHolderSaver.<init> on postback
I'm trying to develop a datatable with lazy loading.
Unfiltered and filtered records are correctly loaded from the persistence context through the use of UserService (i.e. a simple DAO).
I'm 100% sure the problem is not related to the DAO being used because it has been successfully tested and deployed in other packages.

The error comes out when I try to insert a filter: the collection of filtered items is correctly loaded on the page but it looks like at the end of the process something goes wrong and a NPE is thrown. After that, the table no longer responds to any command.

Thanks for any help!

In the following, the configuration, the view and the controller being used.

Configuration

Wildfly 8.2.0

JDK 1.8.0_25

PrimeFaces 5.1

View (XHTML page)

```<code><?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
      xmlns:h="http://xmlns.jcp.org/jsf/html"
      xmlns:p="http://primefaces.org/ui">

    <ui:composition template="/template/template.xhtml">

        <ui:define name="body">
            <h:form id="UserListForm">
                <p:panel header="#{bundle.ListUserTitle}">
                    <p:dataTable id="UserTable" value="#{userController.users}" var="user" lazy="true" rows="25"
                                 paginator="true" rowKey="#{user.id}" selectionMode="single" selection="#{userController.selected}"
                                 paginatorTemplate="{RowsPerPageDropdown} {FirstPageLink} {PreviousPageLink} {CurrentPageReport} {NextPageLink} {LastPageLink}" >

                        <p:column headerText="#{bundle.User_id}" filterBy="#{user.id}">
                           <h:outputText value="#{user.id}"/>
                        </p:column>
                        <p:column headerText="#{bundle.User_nickname}" filterBy="#{user.nickname}">
                           <h:outputText value="#{user.nickname}"/>
                        </p:column>

                    </p:dataTable>
                </p:panel>
            </h:form>

        </ui:define>
    </ui:composition>

</html>
</code>```

Controller

```<code>import java.io.Serializable;
import javax.annotation.PostConstruct;
import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import javax.inject.Inject;
import javax.transaction.Transactional;

@Named("userController")
@SessionScoped
@Transactional(Transactional.TxType.REQUIRED)
public class UserController implements Serializable {

    @Inject
    private UserService userService;

    private LazyUserDataModel users;
    private User selected;

    @PostConstruct
    public void init() {
        users = new LazyUserDataModel(userService);
    }

    public User getSelected() {
        return selected;
    }

    public void setSelected(User selected) {
        this.selected = selected;
    }

    public LazyUserDataModel getUsers() {
        return users;
    }

    public void setUsers(LazyUserDataModel users) {
        this.users = users;
    }

}
</code>```

Lazy Data Model

```<code>import java.util.List;
import java.util.Map;
import org.primefaces.model.LazyDataModel;
import org.primefaces.model.SortOrder;

public class LazyUserDataModel extends LazyDataModel<User> {

    private List<User> data;
    private final UserService userService;

    public LazyUserDataModel(UserService userService) {
        this.userService = userService;
    }

    @Override
    public User getRowData(String rowKey) {
        Long id = Long.valueOf(rowKey);
        for (User u : data) {
            if (u.getId().equals(id))
                return u;
        }
        return null;
    }

    @Override
    public Object getRowKey(User u) {
        return u.getId();
    }

    @Override
    public List<User> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String,Object> filters) {
        UserFilterCorrector.correct(filters);
        UserFilter filter = new UserFilter(filters, first, pageSize);
        FilteredDataModel<User> userDataModel = userService.findFilteredList(filter);
        data = userDataModel.getData();
        this.setRowCount(userDataModel.getCount().intValue());
        return data;
    }
}
</code>```

Exception

```<code>11:07:46,348 SEVERE [javax.enterprise.resource.webcontainer.jsf.application] (default task-97) Error Rendering View[/user/List.xhtml]: java.lang.NullPointerException
 at javax.faces.component.StateHolderSaver.<init>(StateHolderSaver.java:96) [jboss-jsf-api_2.2_spec-2.2.8.jar:2.2.8]
 at javax.faces.component.UIComponentBase.saveAttachedState(UIComponentBase.java:1746) [jboss-jsf-api_2.2_spec-2.2.8.jar:2.2.8]
 at javax.faces.component.ComponentStateHelper.saveMap(ComponentStateHelper.java:378) [jboss-jsf-api_2.2_spec-2.2.8.jar:2.2.8]
 at javax.faces.component.ComponentStateHelper.saveState(ComponentStateHelper.java:256) [jboss-jsf-api_2.2_spec-2.2.8.jar:2.2.8]
 at javax.faces.component.UIComponentBase.saveState(UIComponentBase.java:1552) [jboss-jsf-api_2.2_spec-2.2.8.jar:2.2.8]
 at javax.faces.component.UIData.saveState(UIData.java:1780) [jboss-jsf-api_2.2_spec-2.2.8.jar:2.2.8]
 at org.primefaces.component.datatable.DataTable.saveState(DataTable.java:1520) [primefaces-5.1.jar:5.1]
 at com.sun.faces.application.view.FaceletPartialStateManagementStrategy$3.visit(FaceletPartialStateManagementStrategy.java:482) [jsf-impl-2.2.8-jbossorg-1.jar:]
 at com.sun.faces.component.visit.FullVisitContext.invokeVisitCallback(FullVisitContext.java:151) [jsf-impl-2.2.8-jbossorg-1.jar:]
 at org.primefaces.component.api.UIData.visitTree(UIData.java:692) [primefaces-5.1.jar:5.1]
 at javax.faces.component.UIComponent.visitTree(UIComponent.java:1700) [jboss-jsf-api_2.2_spec-2.2.8.jar:2.2.8]
 at javax.faces.component.UIComponent.visitTree(UIComponent.java:1700) [jboss-jsf-api_2.2_spec-2.2.8.jar:2.2.8]
 at javax.faces.component.UIForm.visitTree(UIForm.java:371) [jboss-jsf-api_2.2_spec-2.2.8.jar:2.2.8]
 at javax.faces.component.UIComponent.visitTree(UIComponent.java:1700) [jboss-jsf-api_2.2_spec-2.2.8.jar:2.2.8]
 at javax.faces.component.UIComponent.visitTree(UIComponent.java:1700) [jboss-jsf-api_2.2_spec-2.2.8.jar:2.2.8]
 at javax.faces.component.UIComponent.visitTree(UIComponent.java:1700) [jboss-jsf-api_2.2_spec-2.2.8.jar:2.2.8]
 at javax.faces.component.UIComponent.visitTree(UIComponent.java:1700) [jboss-jsf-api_2.2_spec-2.2.8.jar:2.2.8]
 at com.sun.faces.application.view.FaceletPartialStateManagementStrategy.saveView(FaceletPartialStateManagementStrategy.java:472) [jsf-impl-2.2.8-jbossorg-1.jar:]
 at com.sun.faces.application.StateManagerImpl.saveView(StateManagerImpl.java:89) [jsf-impl-2.2.8-jbossorg-1.jar:]
 at javax.faces.application.StateManager.getViewState(StateManager.java:593) [jboss-jsf-api_2.2_spec-2.2.8.jar:2.2.8]
 at com.sun.faces.context.PartialViewContextImpl.renderState(PartialViewContextImpl.java:483) [jsf-impl-2.2.8-jbossorg-1.jar:]
 at com.sun.faces.context.PartialViewContextImpl.processPartial(PartialViewContextImpl.java:325) [jsf-impl-2.2.8-jbossorg-1.jar:]
 at org.primefaces.context.PrimePartialViewContext.processPartial(PrimePartialViewContext.java:60) [primefaces-5.1.jar:5.1]
 at javax.faces.component.UIViewRoot.encodeChildren(UIViewRoot.java:1004) [jboss-jsf-api_2.2_spec-2.2.8.jar:2.2.8]
 at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1856) [jboss-jsf-api_2.2_spec-2.2.8.jar:2.2.8]
 at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:430) [jsf-impl-2.2.8-jbossorg-1.jar:]
 at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:133) [jsf-impl-2.2.8-jbossorg-1.jar:]
 at javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:337) [jboss-jsf-api_2.2_spec-2.2.8.jar:2.2.8]
 at javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:337) [jboss-jsf-api_2.2_spec-2.2.8.jar:2.2.8]
 at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:120) [jsf-impl-2.2.8-jbossorg-1.jar:]
 at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101) [jsf-impl-2.2.8-jbossorg-1.jar:]
 at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:219) [jsf-impl-2.2.8-jbossorg-1.jar:]
 at javax.faces.webapp.FacesServlet.service(FacesServlet.java:647) [jboss-jsf-api_2.2_spec-2.2.8.jar:2.2.8]
 at io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:85) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
 at io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:61) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
 at io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
 at org.wildfly.extension.undertow.security.SecurityContextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78)
 at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43) [undertow-core-1.1.0.Final.jar:1.1.0.Final]
 at io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:131) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
 at io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:56) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
 at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43) [undertow-core-1.1.0.Final.jar:1.1.0.Final]
 at io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:45) [undertow-core-1.1.0.Final.jar:1.1.0.Final]
 at io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:63) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
 at io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:58) [undertow-core-1.1.0.Final.jar:1.1.0.Final]
 at io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:70) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
 at io.undertow.security.handlers.SecurityInitialHandler.handleRequest(SecurityInitialHandler.java:76) [undertow-core-1.1.0.Final.jar:1.1.0.Final]
 at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43) [undertow-core-1.1.0.Final.jar:1.1.0.Final]
 at org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest(JACCContextIdHandler.java:61)
 at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43) [undertow-core-1.1.0.Final.jar:1.1.0.Final]
 at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43) [undertow-core-1.1.0.Final.jar:1.1.0.Final]
 at io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:261) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
 at io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:247) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
 at io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:76) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
 at io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:166) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
 at io.undertow.server.Connectors.executeRootHandler(Connectors.java:197) [undertow-core-1.1.0.Final.jar:1.1.0.Final]
 at io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:759) [undertow-core-1.1.0.Final.jar:1.1.0.Final]
 at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [rt.jar:1.8.0_25]
 at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [rt.jar:1.8.0_25]
 at java.lang.Thread.run(Thread.java:745) [rt.jar:1.8.0_25]
</code>```

答:
I do it:

Decompile jboss-jsf-api_2.2_spec-2.2.11.jar

Create a new proyect with class javax.faces.components.StateHolderSaver and paste the decompiled code.

Add jboss-jsf-api_2.2_spec-2.2.11.jar as library

Changue code:

```<code>public StateHolderSaver(FacesContext context, Object toSave){
   this.className=toSave.getClass().getName();
</code>```

to:

```<code>public StateHolderSaver(FacesContext context, Object toSave){
   this.className=toSave!=null?toSave.getClass().getName():null;
</code>```

clean and build

Replace compiled StateHolderSaver in jboss-jsf-api_2.2_spec-2.2.11.jar

run server and it run ok

Body:
I'm trying to develop a datatable with lazy loading.
Unfiltered and filtered records are correctly loaded from the persistence context through the use of UserService (i.e. a simple DAO).
I'm 100% sure the problem is not related to the DAO being used because it has been successfully tested and deployed in other packages.

The error comes out when I try to insert a filter: the collection of filtered items is correctly loaded on the page but it looks like at the end of the process something goes wrong and a NPE is thrown. After that, the table no longer responds to any command.

Thanks for any help!

In the following, the configuration, the view and the controller being used.

Configuration

Wildfly 8.2.0

JDK 1.8.0_25

PrimeFaces 5.1

View (XHTML page)

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <ui:composition template="/template/template.xhtml">

        <ui:define name="body">
            <h:form id="UserListForm">

                           <h:outputText value="#{user.id}"/>

                           <h:outputText value="#{user.nickname}"/>

            </h:form>

        </ui:define>
    </ui:composition>

Controller

import java.io.Serializable;
import javax.annotation.PostConstruct;
import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import javax.inject.Inject;
import javax.transaction.Transactional;

@Named("userController")
@SessionScoped
@Transactional(Transactional.TxType.REQUIRED)
public class UserController implements Serializable {

    @Inject
    private UserService userService;

    private LazyUserDataModel users;
    private User selected;

    @PostConstruct
    public void init() {
        users = new LazyUserDataModel(userService);
    }

    public User getSelected() {
        return selected;
    }

    public void setSelected(User selected) {
        this.selected = selected;
    }

    public LazyUserDataModel getUsers() {
        return users;
    }

    public void setUsers(LazyUserDataModel users) {
        this.users = users;
    }

}

Lazy Data Model

import java.util.List;
import java.util.Map;
import org.primefaces.model.LazyDataModel;
import org.primefaces.model.SortOrder;

public class LazyUserDataModel extends LazyDataModel<User> {

    private List<User> data;
    private final UserService userService;

    public LazyUserDataModel(UserService userService) {
        this.userService = userService;
    }

    @Override
    public User getRowData(String rowKey) {
        Long id = Long.valueOf(rowKey);
        for (User u : data) {
            if (u.getId().equals(id))
                return u;
        }
        return null;
    }

    @Override
    public Object getRowKey(User u) {
        return u.getId();
    }

    @Override
    public List<User> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String,Object> filters) {
        UserFilterCorrector.correct(filters);
        UserFilter filter = new UserFilter(filters, first, pageSize);
        FilteredDataModel<User> userDataModel = userService.findFilteredList(filter);
        data = userDataModel.getData();
        this.setRowCount(userDataModel.getCount().intValue());
        return data;
    }
}

Exception

11:07:46,348 SEVERE [javax.enterprise.resource.webcontainer.jsf.application] (default task-97) Error Rendering View[/user/List.xhtml]: java.lang.NullPointerException
 at javax.faces.component.StateHolderSaver.<init>(StateHolderSaver.java:96) [jboss-jsf-api_2.2_spec-2.2.8.jar:2.2.8]
 at javax.faces.component.UIComponentBase.saveAttachedState(UIComponentBase.java:1746) [jboss-jsf-api_2.2_spec-2.2.8.jar:2.2.8]
 at javax.faces.component.ComponentStateHelper.saveMap(ComponentStateHelper.java:378) [jboss-jsf-api_2.2_spec-2.2.8.jar:2.2.8]
 at javax.faces.component.ComponentStateHelper.saveState(ComponentStateHelper.java:256) [jboss-jsf-api_2.2_spec-2.2.8.jar:2.2.8]
 at javax.faces.component.UIComponentBase.saveState(UIComponentBase.java:1552) [jboss-jsf-api_2.2_spec-2.2.8.jar:2.2.8]
 at javax.faces.component.UIData.saveState(UIData.java:1780) [jboss-jsf-api_2.2_spec-2.2.8.jar:2.2.8]
 at org.primefaces.component.datatable.DataTable.saveState(DataTable.java:1520) [primefaces-5.1.jar:5.1]
 at com.sun.faces.application.view.FaceletPartialStateManagementStrategy$3.visit(FaceletPartialStateManagementStrategy.java:482) [jsf-impl-2.2.8-jbossorg-1.jar:]
 at com.sun.faces.component.visit.FullVisitContext.invokeVisitCallback(FullVisitContext.java:151) [jsf-impl-2.2.8-jbossorg-1.jar:]
 at org.primefaces.component.api.UIData.visitTree(UIData.java:692) [primefaces-5.1.jar:5.1]
 at javax.faces.component.UIComponent.visitTree(UIComponent.java:1700) [jboss-jsf-api_2.2_spec-2.2.8.jar:2.2.8]
 at javax.faces.component.UIComponent.visitTree(UIComponent.java:1700) [jboss-jsf-api_2.2_spec-2.2.8.jar:2.2.8]
 at javax.faces.component.UIForm.visitTree(UIForm.java:371) [jboss-jsf-api_2.2_spec-2.2.8.jar:2.2.8]
 at javax.faces.component.UIComponent.visitTree(UIComponent.java:1700) [jboss-jsf-api_2.2_spec-2.2.8.jar:2.2.8]
 at javax.faces.component.UIComponent.visitTree(UIComponent.java:1700) [jboss-jsf-api_2.2_spec-2.2.8.jar:2.2.8]
 at javax.faces.component.UIComponent.visitTree(UIComponent.java:1700) [jboss-jsf-api_2.2_spec-2.2.8.jar:2.2.8]
 at javax.faces.component.UIComponent.visitTree(UIComponent.java:1700) [jboss-jsf-api_2.2_spec-2.2.8.jar:2.2.8]
 at com.sun.faces.application.view.FaceletPartialStateManagementStrategy.saveView(FaceletPartialStateManagementStrategy.java:472) [jsf-impl-2.2.8-jbossorg-1.jar:]
 at com.sun.faces.application.StateManagerImpl.saveView(StateManagerImpl.java:89) [jsf-impl-2.2.8-jbossorg-1.jar:]
 at javax.faces.application.StateManager.getViewState(StateManager.java:593) [jboss-jsf-api_2.2_spec-2.2.8.jar:2.2.8]
 at com.sun.faces.context.PartialViewContextImpl.renderState(PartialViewContextImpl.java:483) [jsf-impl-2.2.8-jbossorg-1.jar:]
 at com.sun.faces.context.PartialViewContextImpl.processPartial(PartialViewContextImpl.java:325) [jsf-impl-2.2.8-jbossorg-1.jar:]
 at org.primefaces.context.PrimePartialViewContext.processPartial(PrimePartialViewContext.java:60) [primefaces-5.1.jar:5.1]
 at javax.faces.component.UIViewRoot.encodeChildren(UIViewRoot.java:1004) [jboss-jsf-api_2.2_spec-2.2.8.jar:2.2.8]
 at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1856) [jboss-jsf-api_2.2_spec-2.2.8.jar:2.2.8]
 at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:430) [jsf-impl-2.2.8-jbossorg-1.jar:]
 at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:133) [jsf-impl-2.2.8-jbossorg-1.jar:]
 at javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:337) [jboss-jsf-api_2.2_spec-2.2.8.jar:2.2.8]
 at javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:337) [jboss-jsf-api_2.2_spec-2.2.8.jar:2.2.8]
 at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:120) [jsf-impl-2.2.8-jbossorg-1.jar:]
 at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101) [jsf-impl-2.2.8-jbossorg-1.jar:]
 at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:219) [jsf-impl-2.2.8-jbossorg-1.jar:]
 at javax.faces.webapp.FacesServlet.service(FacesServlet.java:647) [jboss-jsf-api_2.2_spec-2.2.8.jar:2.2.8]
 at io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:85) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
 at io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:61) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
 at io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
 at org.wildfly.extension.undertow.security.SecurityContextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78)
 at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43) [undertow-core-1.1.0.Final.jar:1.1.0.Final]
 at io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:131) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
 at io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:56) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
 at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43) [undertow-core-1.1.0.Final.jar:1.1.0.Final]
 at io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:45) [undertow-core-1.1.0.Final.jar:1.1.0.Final]
 at io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:63) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
 at io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:58) [undertow-core-1.1.0.Final.jar:1.1.0.Final]
 at io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:70) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
 at io.undertow.security.handlers.SecurityInitialHandler.handleRequest(SecurityInitialHandler.java:76) [undertow-core-1.1.0.Final.jar:1.1.0.Final]
 at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43) [undertow-core-1.1.0.Final.jar:1.1.0.Final]
 at org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest(JACCContextIdHandler.java:61)
 at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43) [undertow-core-1.1.0.Final.jar:1.1.0.Final]
 at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43) [undertow-core-1.1.0.Final.jar:1.1.0.Final]
 at io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:261) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
 at io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:247) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
 at io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:76) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
 at io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:166) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
 at io.undertow.server.Connectors.executeRootHandler(Connectors.java:197) [undertow-core-1.1.0.Final.jar:1.1.0.Final]
 at io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:759) [undertow-core-1.1.0.Final.jar:1.1.0.Final]
 at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [rt.jar:1.8.0_25]
 at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [rt.jar:1.8.0_25]
 at java.lang.Thread.run(Thread.java:745) [rt.jar:1.8.0_25]

Body:
I do it:

Decompile jboss-jsf-api_2.2_spec-2.2.11.jar

Create a new proyect with class javax.faces.components.StateHolderSaver and paste the decompiled code.

Add jboss-jsf-api_2.2_spec-2.2.11.jar as library

Changue code:

public StateHolderSaver(FacesContext context, Object toSave){
   this.className=toSave.getClass().getName();

to:

public StateHolderSaver(FacesContext context, Object toSave){
   this.className=toSave!=null?toSave.getClass().getName():null;

clean and build

Replace compiled StateHolderSaver in jboss-jsf-api_2.2_spec-2.2.11.jar

run server and it run ok


来源: stackexchange

问:
Error getting ArrayList Coordinates
I've been trying to solve this problem for a week, I've already tried the questions and I've already done some testing, but I still have not found the solution to this problem.

  Java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object java.util.ArrayList.get (int)' on a null object reference

It indicates this line:

```<code>Latitude = Double.parseDouble (location.get (i) .get ("Latitude"). ToString ());
</code>```

Print Error
Complete code:

```<code>public class TabFragment2 extends Fragment {

    private IFragmentToActivity mCallback;
    MapView mMapView;
    private GoogleMap googleMap;

    // Latitude & Longitude
    private Double Latitude = 0.00;
    private Double Longitude = 0.00;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // inflat and return the layout
        View v = inflater.inflate(R.layout.tab_fragment_2, container,
                false);

        //*** Permission StrictMode
        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }

        ArrayList<HashMap<String, String>> location = null;
        String url = "https://192.168.0.1/geo.php";
        try {

            JSONArray data = new JSONArray(getHttpGet(url));

            location = new ArrayList<HashMap<String, String>>();
            HashMap<String, String> map;

            for(int i = 0; i < data.length(); i++){
                JSONObject c = data.getJSONObject(i);

                map = new HashMap<String, String>();
                map.put("LocationID", c.getString("LocationID"));
                map.put("Latitude", c.getString("Latitude"));
                map.put("Longitude", c.getString("Longitude"));
                map.put("LocationName", c.getString("LocationName"));
                map.put("Tipo", c.getString("Tipo"));
                location.add(map);

            }

        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // *** Display Google Map
        googleMap = ((SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.mapView)).getMap();

        // *** Focus & Zoom
        Latitude = Double.parseDouble(location.get(0).get("Latitude").toString());
        Longitude = Double.parseDouble(location.get(0).get("Longitude").toString());
        LatLng coordinate = new LatLng(Latitude, Longitude);
        googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
        googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(coordinate, 17));

        // *** Marker (Loop)
        for (int i = 0; i < location.size(); i++) {
            Latitude = Double.parseDouble(location.get(i).get("Latitude").toString());
            Longitude = Double.parseDouble(location.get(i).get("Longitude").toString());
            String name = location.get(i).get("LocationName").toString();
            String tipo = location.get(i).get("Tipo").toString();
            MarkerOptions marker = new MarkerOptions()
                    .position(new LatLng(Latitude, Longitude)).title(name);
            if(tipo.equals("CORTE")) {
                marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
            }
            if(tipo.equals("RELIGACAO")) {
                marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW));
            }
            if(tipo.equals("VISTORIA")) {
                marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
            }
            googleMap.addMarker(marker);
        }

        return v;
    }

    public static String getHttpGet(String url) {
        StringBuilder str = new StringBuilder();
        HttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        try {
            HttpResponse response = client.execute(httpGet);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (statusCode == 200) { // Download OK
                HttpEntity entity = response.getEntity();
                InputStream content = entity.getContent();
                BufferedReader reader = new BufferedReader(new InputStreamReader(content));
                String line;
                while ((line = reader.readLine()) != null) {
                    str.append(line);
                }
            } else {
                Log.e("Log", "Failed to download result..");
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return str.toString();

    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        try {
            mCallback = (IFragmentToActivity) context;
        } catch (ClassCastException e) {
            throw new ClassCastException(context.toString()
                    + " must implement IFragmentToActivity");
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        mMapView.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mMapView.onDestroy();
    }
    public void onRefresh() {
        Toast.makeText(getActivity(), "Fragment 2: Refresh called.",
                Toast.LENGTH_SHORT).show();
    }

    public void fragmentCommunication() {
        // mTextView1.setText("Hello from Tab Fragment 1");
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        mMapView.onLowMemory();
    }
}
</code>```

Code json:

```<code>[{"LocationID":"19637099","Latitude":" -5.080922","Longitude":"-42.816135","LocationName":"10032576","Tipo":"RELIGACAO"},{"LocationID":"19659563","Latitude":" -5.085750","Longitude":"-42.813892","LocationName":"518620","Tipo":"RELIGACAO"}]
</code>```

答:
I guess it could be that your location ArrayList is actually null if the try/catch statement catches an error. So try to see if that happens and how you can avoid it.</p>

```<code>ArrayList<HashMap<String, String>> location = null;
    String url = "https://192.168.0.1/geo.php";
    try {

        JSONArray data = new JSONArray(getHttpGet(url));

        location = new ArrayList<HashMap<String, String>>();
        HashMap<String, String> map;

        for(int i = 0; i < data.length(); i++){
            JSONObject c = data.getJSONObject(i);

            map = new HashMap<String, String>();
            map.put("LocationID", c.getString("LocationID"));
            map.put("Latitude", c.getString("Latitude"));
            map.put("Longitude", c.getString("Longitude"));
            map.put("LocationName", c.getString("LocationName"));
            map.put("Tipo", c.getString("Tipo"));
            location.add(map);

        }

    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
</code>```

ContentLicense: CC BY-SA 3.0

Title: Error getting ArrayList Coordinates

Body:
I've been trying to solve this problem for a week, I've already tried the questions and I've already done some testing, but I still have not found the solution to this problem.

  Java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object java.util.ArrayList.get (int)' on a null object reference

It indicates this line:

Latitude = Double.parseDouble (location.get (i) .get ("Latitude"). ToString ());

Print Error
Complete code:

public class TabFragment2 extends Fragment {

    private IFragmentToActivity mCallback;
    MapView mMapView;
    private GoogleMap googleMap;

    // Latitude & Longitude
    private Double Latitude = 0.00;
    private Double Longitude = 0.00;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // inflat and return the layout
        View v = inflater.inflate(R.layout.tab_fragment_2, container,
                false);

        //*** Permission StrictMode
        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }

        ArrayList<HashMap<String, String>> location = null;
        String url = "https://192.168.0.1/geo.php";
        try {

            JSONArray data = new JSONArray(getHttpGet(url));

            location = new ArrayList<HashMap<String, String>>();
            HashMap<String, String> map;

            for(int i = 0; i < data.length(); i++){
                JSONObject c = data.getJSONObject(i);

                map = new HashMap<String, String>();
                map.put("LocationID", c.getString("LocationID"));
                map.put("Latitude", c.getString("Latitude"));
                map.put("Longitude", c.getString("Longitude"));
                map.put("LocationName", c.getString("LocationName"));
                map.put("Tipo", c.getString("Tipo"));
                location.add(map);

            }

        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // *** Display Google Map
        googleMap = ((SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.mapView)).getMap();

        // *** Focus & Zoom
        Latitude = Double.parseDouble(location.get(0).get("Latitude").toString());
        Longitude = Double.parseDouble(location.get(0).get("Longitude").toString());
        LatLng coordinate = new LatLng(Latitude, Longitude);
        googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
        googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(coordinate, 17));

        // *** Marker (Loop)
        for (int i = 0; i < location.size(); i++) {
            Latitude = Double.parseDouble(location.get(i).get("Latitude").toString());
            Longitude = Double.parseDouble(location.get(i).get("Longitude").toString());
            String name = location.get(i).get("LocationName").toString();
            String tipo = location.get(i).get("Tipo").toString();
            MarkerOptions marker = new MarkerOptions()
                    .position(new LatLng(Latitude, Longitude)).title(name);
            if(tipo.equals("CORTE")) {
                marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
            }
            if(tipo.equals("RELIGACAO")) {
                marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW));
            }
            if(tipo.equals("VISTORIA")) {
                marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
            }
            googleMap.addMarker(marker);
        }

        return v;
    }

    public static String getHttpGet(String url) {
        StringBuilder str = new StringBuilder();
        HttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        try {
            HttpResponse response = client.execute(httpGet);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (statusCode == 200) { // Download OK
                HttpEntity entity = response.getEntity();
                InputStream content = entity.getContent();
                BufferedReader reader = new BufferedReader(new InputStreamReader(content));
                String line;
                while ((line = reader.readLine()) != null) {
                    str.append(line);
                }
            } else {
                Log.e("Log", "Failed to download result..");
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return str.toString();

    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        try {
            mCallback = (IFragmentToActivity) context;
        } catch (ClassCastException e) {
            throw new ClassCastException(context.toString()
                    + " must implement IFragmentToActivity");
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        mMapView.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mMapView.onDestroy();
    }
    public void onRefresh() {
        Toast.makeText(getActivity(), "Fragment 2: Refresh called.",
                Toast.LENGTH_SHORT).show();
    }

    public void fragmentCommunication() {
        // mTextView1.setText("Hello from Tab Fragment 1");
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        mMapView.onLowMemory();
    }
}

Code json:

[{"LocationID":"19637099","Latitude":" -5.080922","Longitude":"-42.816135","LocationName":"10032576","Tipo":"RELIGACAO"},{"LocationID":"19659563","Latitude":" -5.085750","Longitude":"-42.813892","LocationName":"518620","Tipo":"RELIGACAO"}]

Body:
I guess it could be that your location ArrayList is actually null if the try/catch statement catches an error. So try to see if that happens and how you can avoid it.

ArrayList<HashMap<String, String>> location = null;
    String url = "https://192.168.0.1/geo.php";
    try {

        JSONArray data = new JSONArray(getHttpGet(url));

        location = new ArrayList<HashMap<String, String>>();
        HashMap<String, String> map;

        for(int i = 0; i < data.length(); i++){
            JSONObject c = data.getJSONObject(i);

            map = new HashMap<String, String>();
            map.put("LocationID", c.getString("LocationID"));
            map.put("Latitude", c.getString("Latitude"));
            map.put("Longitude", c.getString("Longitude"));
            map.put("LocationName", c.getString("LocationName"));
            map.put("Tipo", c.getString("Tipo"));
            location.add(map);

        }

    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }


问:
What is a reliable way to detect whether a file or directory has changed in the most recent commit?
I have a web project which I deploy to an ec2 instance simply by pushing new commits.  I use the post-recieve git hook remotely to execute a shell-script which 'deploys' the project by checking it out into a production directory.  The steps are, run npm install on the express app, npm install on the frontend (a create-react-app app), then run npm run build (which basically utilizes web-pack to build an optimized distribution folder from my node source code).

These steps are expensive and in many cases not needed. E.G. if all I did was update a Node component in srcs/components/ then npm run build should run, but npm install on the server and frontend shouldn't.  If all I have done is added a comment to my express app, no scripts should run.

My currently server-side deploy script looks like this:

```<code>#!/usr/bin/env bash

GIT_WORK_TREE=/home/ec2-user/absiteProd git checkout -f

### TODO: conditional NPM work

pm2 restart index
</code>```

My question is then how can I use git (or grep, sed, awk, etc..) to reliably tell me when either /home/ec2-user/absiteProd/frontend/package.json,
/home/ec2-user/absiteProd/server/package.json or anything in 'home/ec2-user/absiteProd/frontend/sources` has changed?

Currently I'm having some success with:

```<code>if `git log --stat -n 1` | grep --quite frontend/src/* ; then
   cd home/ec2-user/frontend
   npm run build
fi
</code>```

But since this seems like such a common requirement in app deployment,  I feel like there must be a simpler way?

答:
Git does not store directories in any useful way, so you must define what you mean by "anything in" yourself (which has its advantages since you can define what you mean rather than getting stuck with someone else's useless-to-you definition, but means you must do more work).

That said, Git stores each file as a path name within each commit.  Your deployment script takes some work-tree—in this case, /home/ec2-user/absiteProd—from one state to another.  Since it uses git checkout to do so, and git checkout does nothing special with time stamps, you now have many options with many different low-level details and subsequent consequences.  Here are two obvious-ish and reasonably simple starting points:

Was /home/ec2-user/absiteProd exactly the same as some previous commit?  If so, which commit?  (Commits have unique hash IDs and these are generally the things to use in scripts.)  You can then have Git compare the previous commit with the new commit, using git diff --name-status for instance.  This is similar to what you are doing now, but better.

If your deployment script is a post-receive script, you already have both the old and new hash IDs of the reference, which you have read from standard input.  Hence the set of files changed, with their statuses, between those two commits, is:

```<code> git diff-tree -r --name-status $oldhash $newhash
</code>```

If git checkout wrote on any file(s), those files will have "now" as their modify-time time-stamps, since git checkout just lets the system's time apply to updated files.  Can you use this?  As long as you never deploy more than twice in a single second, you could combine this with the make build-system, which builds files based on time-stamps.

If make is suitable here, it is probably the best choice, except for its maximum of one-per-second deployment (or whatever your underlying OS has for time stamp resolution on files).  You can just declare that whatever the output file(s) is/are, they depend on the corresponding input file(s), and give the recipe to build the output(s) from the input(s) and run make.

Body:
I have a web project which I deploy to an ec2 instance simply by pushing new commits.  I use the post-recieve git hook remotely to execute a shell-script which 'deploys' the project by checking it out into a production directory.  The steps are, run npm install on the express app, npm install on the frontend (a create-react-app app), then run npm run build (which basically utilizes web-pack to build an optimized distribution folder from my node source code).

These steps are expensive and in many cases not needed. E.G. if all I did was update a Node component in srcs/components/ then npm run build should run, but npm install on the server and frontend shouldn't.  If all I have done is added a comment to my express app, no scripts should run.

My currently server-side deploy script looks like this:

#!/usr/bin/env bash

GIT_WORK_TREE=/home/ec2-user/absiteProd git checkout -f

### TODO: conditional NPM work

pm2 restart index

My question is then how can I use git (or grep, sed, awk, etc..) to reliably tell me when either /home/ec2-user/absiteProd/frontend/package.json,
/home/ec2-user/absiteProd/server/package.json or anything in 'home/ec2-user/absiteProd/frontend/sources` has changed?

Currently I'm having some success with:

if `git log --stat -n 1` | grep --quite frontend/src/* ; then
   cd home/ec2-user/frontend
   npm run build
fi

But since this seems like such a common requirement in app deployment,  I feel like there must be a simpler way?

Body:
Git does not store directories in any useful way, so you must define what you mean by "anything in" yourself (which has its advantages since you can define what you mean rather than getting stuck with someone else's useless-to-you definition, but means you must do more work).

That said, Git stores each file as a path name within each commit.  Your deployment script takes some work-tree—in this case, /home/ec2-user/absiteProd—from one state to another.  Since it uses git checkout to do so, and git checkout does nothing special with time stamps, you now have many options with many different low-level details and subsequent consequences.  Here are two obvious-ish and reasonably simple starting points:

Was /home/ec2-user/absiteProd exactly the same as some previous commit?  If so, which commit?  (Commits have unique hash IDs and these are generally the things to use in scripts.)  You can then have Git compare the previous commit with the new commit, using git diff --name-status for instance.  This is similar to what you are doing now, but better.

If your deployment script is a post-receive script, you already have both the old and new hash IDs of the reference, which you have read from standard input.  Hence the set of files changed, with their statuses, between those two commits, is:

 git diff-tree -r --name-status $oldhash $newhash

If git checkout wrote on any file(s), those files will have "now" as their modify-time time-stamps, since git checkout just lets the system's time apply to updated files.  Can you use this?  As long as you never deploy more than twice in a single second, you could combine this with the make build-system, which builds files based on time-stamps.

If make is suitable here, it is probably the best choice, except for its maximum of one-per-second deployment (or whatever your underlying OS has for time stamp resolution on files).  You can just declare that whatever the output file(s) is/are, they depend on the corresponding input file(s), and give the recipe to build the output(s) from the input(s) and run make.


问:
Custom sort Map Java
i have some troubles when i want to sort a map, when i create a map passing a string, it comes organized like

```<code>nombre=EDIFICADORA JUANA, descripcion=  LOS frst com MEJORES Estamso para servir LOS, correo1=rst008@guan.com, correo2=oipoa@gmaio.com, numero1=24602254, numero2=55655545
</code>```

When i create a map using this data it comes disordered, this is the method that creates the map:

```<code>   private HashMap<String, String> getMap(String rawData) {
    HashMap<String, String> map = new HashMap<>();
    String[] pairs = rawData.split(","); // split into key-value pairs
    for(String pair: pairs) {
        pair = pair.trim(); // get rid of extraneous white-space
        String[] components = pair.split("=");
        String key = components[0].trim();
        String value = components[1].trim();
        map.put(key, value); // put the pair into the map
    }
    return map;
}
</code>```

This function returns something like:

0 = {HashMap$HashMapEntry@5854} "correo2" -> "oipoa@gmaio.com"

1 = {HashMap$HashMapEntry@5855} "correo1" -> "rst008@guan.com"`

2 = {HashMap$HashMapEntry@5856} "numero2" -> "55655545"

3 = {HashMap$HashMapEntry@5857} "nombre" -> "EDIFICADORA JUANA"

4 = {HashMap$HashMapEntry@5858} "descripcion" -> "LOS frst com MEJORES Estamso
par"

5 = {HashMap$HashMapEntry@5859} "numero1" -> "24602254"

How can i sort this Map like the string value comes?

I expect:

0 = {HashMap$HashMapEntry@5857} "nombre" -> "EDIFICADORA JUANA"

1 = {HashMap$HashMapEntry@5858} "descripcion" -> "LOS frst com MEJORES Estamso par"

2 = {HashMap$HashMapEntry@5855} "correo1" -> "rst008@guan.com"`

3 = {HashMap$HashMapEntry@5854} "correo2" -> "oipoa@gmaio.com"

4 = {HashMap$HashMapEntry@5859} "numero1" -> "24602254"

5 = {HashMap$HashMapEntry@5856} "numero2" -> "55655545"

答:
Instead of HashMap, use the LinkedHashMap implementation of Map.

It keeps the insertion order in your map when you iterate on :

Hash table and linked list implementation of the Map interface, with
  predictable iteration order.

So do this change :

```<code>   private LinkedHashMap<String, String> getMap(String rawData) {
    LinkedHashMap<String, String> map = new LinkedHashMap<>(); // change
    String[] pairs = rawData.split(","); // split into key-value pairs
    for(String pair: pairs) {
        pair = pair.trim(); // get rid of extraneous white-space
        String[] components = pair.split("=");
        String key = components[0].trim();
        String value = components[1].trim();
        map.put(key, value); // put the pair into the map
    }
    return map;
}
</code>```

Title: Custom sort Map Java

Body:
i have some troubles when i want to sort a map, when i create a map passing a string, it comes organized like

nombre=EDIFICADORA JUANA, descripcion=  LOS frst com MEJORES Estamso para servir LOS, correo1=rst008@guan.com, correo2=oipoa@gmaio.com, numero1=24602254, numero2=55655545

When i create a map using this data it comes disordered, this is the method that creates the map:

   private HashMap<String, String> getMap(String rawData) {
    HashMap<String, String> map = new HashMap<>();
    String[] pairs = rawData.split(","); // split into key-value pairs
    for(String pair: pairs) {
        pair = pair.trim(); // get rid of extraneous white-space
        String[] components = pair.split("=");
        String key = components[0].trim();
        String value = components[1].trim();
        map.put(key, value); // put the pair into the map
    }
    return map;
}

This function returns something like:

0 = {HashMap$HashMapEntry@5854} "correo2" -> "oipoa@gmaio.com"

1 = {HashMap$HashMapEntry@5855} "correo1" -> "rst008@guan.com"`

2 = {HashMap$HashMapEntry@5856} "numero2" -> "55655545"

3 = {HashMap$HashMapEntry@5857} "nombre" -> "EDIFICADORA JUANA"

4 = {HashMap$HashMapEntry@5858} "descripcion" -> "LOS frst com MEJORES Estamso
par"

5 = {HashMap$HashMapEntry@5859} "numero1" -> "24602254"

How can i sort this Map like the string value comes?

I expect:

0 = {HashMap$HashMapEntry@5857} "nombre" -> "EDIFICADORA JUANA"

1 = {HashMap$HashMapEntry@5858} "descripcion" -> "LOS frst com MEJORES Estamso par"

2 = {HashMap$HashMapEntry@5855} "correo1" -> "rst008@guan.com"`

3 = {HashMap$HashMapEntry@5854} "correo2" -> "oipoa@gmaio.com"

4 = {HashMap$HashMapEntry@5859} "numero1" -> "24602254"

5 = {HashMap$HashMapEntry@5856} "numero2" -> "55655545"

Body:
Instead of HashMap, use the LinkedHashMap implementation of Map.

It keeps the insertion order in your map when you iterate on :

Hash table and linked list implementation of the Map interface, with
  predictable iteration order.

So do this change :

   private LinkedHashMap<String, String> getMap(String rawData) {
    LinkedHashMap<String, String> map = new LinkedHashMap<>(); // change
    String[] pairs = rawData.split(","); // split into key-value pairs
    for(String pair: pairs) {
        pair = pair.trim(); // get rid of extraneous white-space
        String[] components = pair.split("=");
        String key = components[0].trim();
        String value = components[1].trim();
        map.put(key, value); // put the pair into the map
    }
    return map;
}


问:
UWP TimedMetadataTrack Events are not firing
I can not seem to get the a TimedMetadataTrack object to fire the events CueEntered or CueExited for SpeechCue events.

Any thoughts?

答:
So, apparently this line is needed when registering for IMediaCue.CueEntered and IMedia.CueExited events (at least the SpeechCue implementation of the interface):

```<code>((Windows.Media.Playback.MediaPlaybackItem)item).TimedMetadataTracks.SetPresentationMode((uint)index, Windows.Media.Playback.TimedMetadataTrackPresentationMode.ApplicationPresented);
</code>```

This line is required to exactly allow the system to send the CueEntered and CueExited events that are being listened for.

Yet again, another case of Microsoft not fully documenting things in their API Documentation or Code Examples.

Body:
So, apparently this line is needed when registering for IMediaCue.CueEntered and IMedia.CueExited events (at least the SpeechCue implementation of the interface):

((Windows.Media.Playback.MediaPlaybackItem)item).TimedMetadataTracks.SetPresentationMode((uint)index, Windows.Media.Playback.TimedMetadataTrackPresentationMode.ApplicationPresented);

This line is required to exactly allow the system to send the CueEntered and CueExited events that are being listened for.

Yet again, another case of Microsoft not fully documenting things in their API Documentation or Code Examples.


问:
Getting multiple strings as inputs
The Question is to take three names as input and check whether the 4th input is the first letter of one of those three names.
*It needs to be only of alpha type and no other.

Sample Input:

```<code>@ON SNOW
ARYA STARK
HODOR
@
</code>```

Output:

```<code>NO
</code>```

My code:

```<code>#include <stdio.h>
#include <ctype.h>
int main(){
    char s1[100],s2[100],s3[100];
    char ch[1];
    scanf("%[^\n]s",s1);
    scanf("%[^\n]s",s2);
    scanf("%[^\n]s",s3);
    scanf("%s",ch);
    if(isalpha(ch[0]) && (s1[0]==ch[0] || s2[0]==ch[0] || s3[0]==ch[0]))
        printf("yes");
    else
        printf("no");
}
</code>```

As I figured out that gets() no longer works, I tried scanf("%s",s1);.
But since it does not store the calude after the whitespace " ", I tried this scanf("%[^\n]s",s1);. But the scanning stops at the first name itself.

```<code>John Player
NO
</code>```

What is the way to store multiple strings in a char array without using loops and only using branching??

Title: Getting multiple strings as inputs

Body:
The Question is to take three names as input and check whether the 4th input is the first letter of one of those three names.
*It needs to be only of alpha type and no other.

Sample Input:

@ON SNOW
ARYA STARK
HODOR
@

Output:

NO

My code:

#include <stdio.h>
#include <ctype.h>
int main(){
    char s1[100],s2[100],s3[100];
    char ch[1];
    scanf("%[^\n]s",s1);
    scanf("%[^\n]s",s2);
    scanf("%[^\n]s",s3);
    scanf("%s",ch);
    if(isalpha(ch[0]) && (s1[0]==ch[0] || s2[0]==ch[0] || s3[0]==ch[0]))
        printf("yes");
    else
        printf("no");
}

As I figured out that gets() no longer works, I tried scanf("%s",s1);.
But since it does not store the calude after the whitespace " ", I tried this scanf("%[^\n]s",s1);. But the scanning stops at the first name itself.

John Player
NO

What is the way to store multiple strings in a char array without using loops and only using branching??

Body:
#include <stdio.h>
int main(){
char s1[100],s2[100],s3[100];
char ch[1];

fgets(s1,100,stdin);// like gets but limited by length
fgets(s2,100,stdin);
fgets(s3,100,stdin);

scanf("%s",ch);

if( (s1[0]>='a' && s1[0]<='z') || (s1[0]>='A' && s1[0]<='Z') ){//ch-alpha?
    if(s1[0] == ch[0]){  printf("yes"); }//s1[0] == ch[0] ??
    else{ printf("no"); }
    }
else
    printf("no"); return 0; }


问:
JavaCC simple example not working
I am trying javacc for the first time with a simple naive example which is not working. My BNF is as follows:

```<code><exp>:= <num>"+"<num>
<num>:= <digit> | <digit><num>
<digit>:= [0-9]
</code>```

Based on this BNF, I am writing the SimpleAdd.jj as follows:

```<code>    options
{
}
PARSER_BEGIN(SimpleAdd)
public class SimpleAdd
{
}
PARSER_END(SimpleAdd)
SKIP :
{
    " "
|   "\r"
|   "\t"
|   "\n"
}
TOKEN:
{
    < NUMBER: (["0"-"9"])+  >
}

int expr():
{
        int leftValue ;
        int rightValue ;
}
{
        leftValue = num()
        "+"
        rightValue = num()
        { return leftValue+rightValue; }
}

int num():
{
        Token t;
}
{
    t = <NUMBER> { return Integer.parseInt(t.toString()); }
}
</code>```

using the above file, I am generating the java source classes. My main class is as follows:

```<code>public class Main {
    public static void main(String [] args) throws ParseException {
        SimpleAdd parser = new SimpleAdd(System.in);
        int x = parser.expr();
        System.out.println(x);
    }
}
</code>```

When I am entering the expression via System.in, I am getting the following error:

```<code>11+11^D
Exception in thread "main" SimpleAddTest.ParseException: Encountered "<EOF>" at line 0, column 0.
Was expecting:
    <NUMBER> ...

    at SimpleAddTest.SimpleAdd.generateParseException(SimpleAdd.java:200)
    at SimpleAddTest.SimpleAdd.jj_consume_token(SimpleAdd.java:138)
    at SimpleAddTest.SimpleAdd.num(SimpleAdd.java:16)
    at SimpleAddTest.SimpleAdd.expr(SimpleAdd.java:7)
    at SimpleAddTest.Main.main(Main.java:9)
</code>```

Any hint to solve the problem ?

答:
Edit Note that this answer answers an earlier version of the question.

When a BNF production uses a nonterminal that returns a result, you can record that result in a variable.

First declare the variables in the declaration part of the BNF production

```<code>int expr():
{
    int leftValue ;
    int rightValue ;
}
{
</code>```

Second, in the main body of the production, record the results in the variables.

```<code>    leftValue = num()
    "+"
    rightValue = num()
</code>```

Finally, use the values of those variables to compute the result of this production.

```<code>    { return leftValue+rightValue; }
}
</code>```

Title: JavaCC simple example not working

Body:
I am trying javacc for the first time with a simple naive example which is not working. My BNF is as follows:

<exp>:= <num>"+"<num>
<num>:= <digit> | <digit><num>
<digit>:= [0-9]

Based on this BNF, I am writing the SimpleAdd.jj as follows:

    options
{
}
PARSER_BEGIN(SimpleAdd)
public class SimpleAdd
{
}
PARSER_END(SimpleAdd)
SKIP :
{
    " "
|   "\r"
|   "\t"
|   "\n"
}
TOKEN:
{
    < NUMBER: (["0"-"9"])+  >
}

int expr():
{
        int leftValue ;
        int rightValue ;
}
{
        leftValue = num()
        "+"
        rightValue = num()
        { return leftValue+rightValue; }
}

int num():
{
        Token t;
}
{
    t = <NUMBER> { return Integer.parseInt(t.toString()); }
}

using the above file, I am generating the java source classes. My main class is as follows:

public class Main {
    public static void main(String [] args) throws ParseException {
        SimpleAdd parser = new SimpleAdd(System.in);
        int x = parser.expr();
        System.out.println(x);
    }
}

When I am entering the expression via System.in, I am getting the following error:

11+11^D
Exception in thread "main" SimpleAddTest.ParseException: Encountered "<EOF>" at line 0, column 0.
Was expecting:
    <NUMBER> ...

    at SimpleAddTest.SimpleAdd.generateParseException(SimpleAdd.java:200)
    at SimpleAddTest.SimpleAdd.jj_consume_token(SimpleAdd.java:138)
    at SimpleAddTest.SimpleAdd.num(SimpleAdd.java:16)
    at SimpleAddTest.SimpleAdd.expr(SimpleAdd.java:7)
    at SimpleAddTest.Main.main(Main.java:9)

Any hint to solve the problem ?

Body:
Edit Note that this answer answers an earlier version of the question.

When a BNF production uses a nonterminal that returns a result, you can record that result in a variable.

First declare the variables in the declaration part of the BNF production

int expr():
{
    int leftValue ;
    int rightValue ;
}
{

Second, in the main body of the production, record the results in the variables.

    leftValue = num()
    "+"
    rightValue = num()

Finally, use the values of those variables to compute the result of this production.

    { return leftValue+rightValue; }
}


问:
How to run php scripts on button click? I have made a list of upcoming workshops and made a button to register for the workshops.Here is my code
How to run php scripts on button click? I have made a list of upcoming workshops and made a button to register for the workshops.On clicking apply button, i want to insert details of that student in the database. Here is my code.</p>

```<code><?php

    include('connect_db.php');
    $query = "select * from workshop";
    $data = mysqli_query($con,$query);

    echo "<table>";

    while($row=mysqli_fetch_array($data, MYSQLI_ASSOC))
    {
        $wid = $row['Workshop_id'];
        $wname = $row['Workshop_name'];
        $inst = $row['Instructor'];
        $dt = $row['Date'];
        $tm = $row['Time'];

        echo "<tr><td>$wname</td>";
        echo "<td>$inst</td>";
        echo "<td>$dt</td>";
        echo "<td>$tm</td>";

        echo "<td><button type='button' class = 'btn-primary' id =
            'apply'>Apply</button></td>";

    }
    echo "</table>";
?>
</code>```

答:
Spend some time researching Ajax.

The basic method is:

The user clicks a button

A JavaScript function is triggered (jQuery is great for this)

Your PHP code is called

You can process the output of the script (echo's, errors, etc).

Which is exactly what you need.

W3Schools has a great tutorial on this.

Body:
How to run php scripts on button click? I have made a list of upcoming workshops and made a button to register for the workshops.On clicking apply button, i want to insert details of that student in the database. Here is my code.

<?php

    include('connect_db.php');
    $query = "select * from workshop";
    $data = mysqli_query($con,$query);

    echo "
";

    while($row=mysqli_fetch_array($data, MYSQLI_ASSOC))
    {
        $wid = $row['Workshop_id'];
        $wname = $row['Workshop_name'];
        $inst = $row['Instructor'];
        $dt = $row['Date'];
        $tm = $row['Time'];

        echo "
$wname	";
        echo "$inst	";
        echo "$dt	";
        echo "$tm	";

        echo "<button type='button' class = 'btn-primary' id =
            'apply'>Apply</button>	";

    }
    echo "
";
?>


问:
How to make it so String can't be numeric
If you make a variable type String you can still input numbers.

Example:

"Enter name: 123"

The name is still accepted. How would I make it so a variable name only accepts letters, otherwise an error message will appear?

答:
You could check to see whether the string is numeric using a lambda expression:

```<code>String myString = "abcdef1234567890";

if (myString.chars().allMatch( Character::isDigit ))
</code>```

Will output True if the string only contains numbers

Body:
You could check to see whether the string is numeric using a lambda expression:

String myString = "abcdef1234567890";

if (myString.chars().allMatch( Character::isDigit ))

Will output True if the string only contains numbers


问:
How to retrieve JSON using retrofit with headers?
Situation: I have an API token and want to get json data. But that token has to be used as header,not as query parametr. As I've understood I couldn't type on my browser request with header. For more information about API that I use,you can look there: https://developer.fantasydata.com/docs/services/594407b00f14bf15264fd958/operations/5944088b14338d0eb80b2809

Problem: Because of I do not know what kind of fields does JSON request have ,I cannot create a class for that json data. I want to use JacksonConverter. So the question is: how to get that JSON and look how it looks like,then create a class for that in order to convert?

Below you can see my code with understandable comments:

My PrefsApplication class for creating http request:

```<code>public class PrefsApplication extends Application {
    private static Retrofit retrofit = null;

    static String base = "https://api.fantasydata.net/v3/soccer/scores/"; // my base url

    public static Retrofit getClient() {
        if(retrofit == null) {
            retrofit = new Retrofit.Builder().baseUrl(base).addConverterFactory(JacksonConverterFactory.create()).build();
        }
        return retrofit;
    }
}
</code>```

My interface for doing get request and putting header

```<code>public interface RestInterface {
    @Headers("Ocp-Apim-Subscription-Key: {MY_KEY}") // here is header, I don't know is it properly written?
    @GET("scores/json/Areas") // my get request
    Call<List<Country>> getCountries(); // here, I want to get list of countries
}
</code>```

There is MainActivity:

```<code>public class MainActivity extends AppCompatActivity  {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        RestInterface rest = PrefsApplication.getClient().create(RestInterface.class);

        Call<List<Country>>call = rest.getCountries();
        call.enqueue(new Callback<List<Country>>() {
            @Override
            public void onResponse(Call<List<Country>> call, Response<List<Country>> response) { }

            @Override
            public void onFailure(Call<List<Country>> call, Throwable t) { }
        });
    }
}
</code>```

答: You can use a browser extension and make the http request with a custom header. I prefer postman for Chrome</p>

Body:
Situation: I have an API token and want to get json data. But that token has to be used as header,not as query parametr. As I've understood I couldn't type on my browser request with header. For more information about API that I use,you can look there: https://developer.fantasydata.com/docs/services/594407b00f14bf15264fd958/operations/5944088b14338d0eb80b2809

Problem: Because of I do not know what kind of fields does JSON request have ,I cannot create a class for that json data. I want to use JacksonConverter. So the question is: how to get that JSON and look how it looks like,then create a class for that in order to convert?

Below you can see my code with understandable comments:

My PrefsApplication class for creating http request:

public class PrefsApplication extends Application {
    private static Retrofit retrofit = null;

    static String base = "https://api.fantasydata.net/v3/soccer/scores/"; // my base url

    public static Retrofit getClient() {
        if(retrofit == null) {
            retrofit = new Retrofit.Builder().baseUrl(base).addConverterFactory(JacksonConverterFactory.create()).build();
        }
        return retrofit;
    }
}

My interface for doing get request and putting header

public interface RestInterface {
    @Headers("Ocp-Apim-Subscription-Key: {MY_KEY}") // here is header, I don't know is it properly written?
    @GET("scores/json/Areas") // my get request
    Call<List<Country>> getCountries(); // here, I want to get list of countries
}

There is MainActivity:

public class MainActivity extends AppCompatActivity  {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        RestInterface rest = PrefsApplication.getClient().create(RestInterface.class);

        Call<List<Country>>call = rest.getCountries();
        call.enqueue(new Callback<List<Country>>() {
            @Override
            public void onResponse(Call<List<Country>> call, Response<List<Country>> response) { }

            @Override
            public void onFailure(Call<List<Country>> call, Throwable t) { }
        });
    }
}


问:
Running React Native Android on device
I followed this official help page and also consulted this previous SO question.

But I still don't know what is wrong here.

Let's take step by step:

Ensure the package server is running. From the screenshot, you can see the command I typed "react-native run-android" and the reponse "Starting JS server..."

Ensure your device is connected... Yes, Vysor sees my device.  Wee see Vysor showing the app running in the screenshot.

...USB enabled Yes, the app is running, that's why we see the red error screen, but it's the app running nevertheless.

Run "adb reverse tcp:8081 tcp:8081" Yes, the screenshot shows that I ran the command.

Device and port... Yes, did that too.  See next screenshot

What am I still doing wrong?  How can I make it work?

答: I was stuck at this exact step and finally I checked my firewall and lo and behold it was blocking the connection from my device to my computer. I unblocked it and after a reload everything worked. </p>

Title: Running React Native Android on device


问:
List gets empty on button event
Every time when the button event fired my list gets empty and starts adding items from first index. It is not retaining the old items added on previous click. I am trying to store ids of some element in my list on every button clicked and inserting them into hashset to avoid duplication. kindly help me out with this

Here is my code.

```<code> List<int> venues = new List<int>();
 HashSet<int> hashset = new HashSet<int>();

                id = Convert.ToInt32(Request.QueryString["id"].ToString());

                venues.Add(id);

                foreach (int item1 in venues)
                {

                    if (!hashset.Add(item1))
                    {
                        Response.Write("<script>alert('Duplicate Items');</script>");
                        break;
                    }

                    else
                    {

                        foreach (var items in venues)
                        {
                            con.Open();
                            SqlCommand cmd = con.CreateCommand();
                            cmd.CommandType = CommandType.Text;
                            cmd.CommandText = "select * from Venues where VenueID = '" + items + "'";
                            cmd.ExecuteNonQuery();
                            DataTable dt = new DataTable();
                            SqlDataAdapter ds = new SqlDataAdapter(cmd);
                            ds.Fill(dt);
                            foreach (DataRow dr in dt.Rows)
                            {
                                Name = dr["Name"].ToString();
                                Address = dr["Address"].ToString();
                                Picture = dr["Picture"].ToString();
                                Price = dr["Price"].ToString();
                            }
                            con.Close();
                            if (Request.Cookies["aa"] == null)
                            {
                                Response.Cookies["aa"].Value = Name.ToString() + "," + Address.ToString() + "," + Picture.ToString() + "," + Price.ToString();
                                Response.Cookies["aa"].Expires = DateTime.Now.AddDays(1);

                            }
                            else
                            {
                                Response.Cookies["aa"].Value = Request.Cookies["aa"].Value + "|" + Name.ToString() + "," + Address.ToString() + "," + Picture.ToString() + "," + Price.ToString();
                                Response.Cookies["aa"].Expires = DateTime.Now.AddDays(1);
                            }
                        }
                    }
                }

            }
</code>```

答:
This could be about state management. The statelessness of http means you loose any form of state (eg. variables that are created during a request-response cycle) Try using session or any other state management technique to persist the list in between clicks.
Session["venues"] = venues to put the list in the session. And var venues = (list<int>)Session["venues"] to read the list from the session

Title: List gets empty on button event

Body:
Every time when the button event fired my list gets empty and starts adding items from first index. It is not retaining the old items added on previous click. I am trying to store ids of some element in my list on every button clicked and inserting them into hashset to avoid duplication. kindly help me out with this

Here is my code.

 List<int> venues = new List<int>();
 HashSet<int> hashset = new HashSet<int>();

                id = Convert.ToInt32(Request.QueryString["id"].ToString());

                venues.Add(id);

                foreach (int item1 in venues)
                {

                    if (!hashset.Add(item1))
                    {
                        Response.Write("");
                        break;
                    }

                    else
                    {

                        foreach (var items in venues)
                        {
                            con.Open();
                            SqlCommand cmd = con.CreateCommand();
                            cmd.CommandType = CommandType.Text;
                            cmd.CommandText = "select * from Venues where VenueID = '" + items + "'";
                            cmd.ExecuteNonQuery();
                            DataTable dt = new DataTable();
                            SqlDataAdapter ds = new SqlDataAdapter(cmd);
                            ds.Fill(dt);
                            foreach (DataRow dr in dt.Rows)
                            {
                                Name = dr["Name"].ToString();
                                Address = dr["Address"].ToString();
                                Picture = dr["Picture"].ToString();
                                Price = dr["Price"].ToString();
                            }
                            con.Close();
                            if (Request.Cookies["aa"] == null)
                            {
                                Response.Cookies["aa"].Value = Name.ToString() + "," + Address.ToString() + "," + Picture.ToString() + "," + Price.ToString();
                                Response.Cookies["aa"].Expires = DateTime.Now.AddDays(1);

                            }
                            else
                            {
                                Response.Cookies["aa"].Value = Request.Cookies["aa"].Value + "|" + Name.ToString() + "," + Address.ToString() + "," + Picture.ToString() + "," + Price.ToString();
                                Response.Cookies["aa"].Expires = DateTime.Now.AddDays(1);
                            }
                        }
                    }
                }

            }


问:
django ModelChoiceField set queryset from views.py
I am new to django, need some help.

forms.py

```<code>import floppyforms as ff
from django import forms
from django.contrib.auth.models import User

from .models import Prodavnica, Racun, Transakcija
...

class IzdatakForm(forms.ModelForm):
    izdatak = forms.DecimalField(max_digits=20,
                              decimal_places=2,
                              widget=forms.NumberInput(attrs={'min': '0', 'step': '0.01'}))
    datum = ff.DateField(widget=ff.DateInput(format='yyyy-mm-dd'))
    vreme = ff.TimeField(widget=ff.TimeInput(attrs={'step': '60'}, format='HH-MM'))
    prodavnica = forms.ModelChoiceField(required=True,queryset=Prodavnica.objects.all())

    class Meta:
        model = Transakcija
        fields = ['izdatak', 'datum', 'vreme', 'racun', 'prodavnica']
</code>```

models.py

```<code>from django.contrib.auth.models import User
from django.db import models

from django.urls import reverse

# Create your models here.

class Prodavnica(models.Model):
    author = models.ForeignKey(User, on_delete=models.PROTECT)
    naziv = models.CharField(max_length=50, unique=True, blank=False)
    adresa = models.CharField(max_length=200, blank=True)
    telefon = models.CharField(max_length=50, blank=True)
    foursquare = models.URLField(blank=True)

    def get_absolute_url(self):
        return reverse(viewname='finance_detail_shop', kwargs={'pk': self.pk})

    def __str__(self):
        return self.naziv

class Transakcija(models.Model):
    korisnik = models.ForeignKey(User, on_delete=models.PROTECT)
    suma = models.DecimalField(max_digits=20, decimal_places=2, default='0.0')
    izdatak = models.DecimalField(max_digits=20, decimal_places=2, default='0.0', null=True)
    dodatak = models.DecimalField(max_digits=20, decimal_places=2, default='0.0', null=True)
    prodavnica = models.ForeignKey('Prodavnica', related_name='prodavnica', blank=True, null=True)
    racun = models.ForeignKey('Racun', related_name='Racun')
    datum = models.DateField()
    vreme = models.TimeField()

    def get_absolute_url(self):
        return reverse(viewname='finance_detail_transaction', kwargs={'pk': self.pk})

    def __str__(self):
        return '%s %s (%s %s)' % (self.pk, self.suma, self.datum,self.vreme)

class Racun(models.Model):
    vlasnik = models.ForeignKey(User, on_delete=models.PROTECT, related_name='vlasnik')
    ovlacena_lica = models.ManyToManyField(User, related_name='ovlaceno_lice')
    naziv = models.CharField(max_length=50, unique=True)
    broj = models.IntegerField(unique=True)

    def get_absolute_url(self):
        return reverse(viewname='finance_detail_account', kwargs={'pk': self.pk})

    def __str__(self):
        return self.naziv
</code>```

views.py

```<code>class TransakcijaDodatakCreate(CreateView):
    model = Transakcija
    form_class = DodatakForm

    def get_form(self, form_class=None):
        user = self.request.user
        racun = Racun.objects.filter(Q(vlasnik=user) | Q(ovlacena_lica=user))
        self.fields['racun'].queryset = racun
        return super().get_form(form_class)

    def form_valid(self, form):
        user = self.request.user
        form.instance.korisnik = user
        form.instance.izdatak = None
        form.instance.prodavnica = None
        return super(TransakcijaDodatakCreate, self).form_valid(form)

    template_name = 'finance/transakcija/dodaci/form.html'
</code>```

Returns error 'NoneType' object is not subscriptable.

I am trying to have only set ModelChoiceField racun's queryset to only those racuns that user owns.

I was wandering if it is possible to set queryset for ModelChoiceField from CreateView?

答:
That code belongs in an __init__ method on the form, not in the view.

```<code>class DodatakForm(forms.ModelForm):
    ...

    def __init__(self, *args, **kwargs):
        user = kwargs.pop('user', None)
        super(DodatakForm, self).__init__(*args, **kwargs)
        if user:
            racun = Racun.objects.filter(Q(vlasnik=user) | Q(ovlacena_lica=user))
            self.fields['racun'].queryset = racun
</code>```

and in the view, instead of overriding get_form, define get_form_kwargs:

```<code>def get_form_kwargs(self, *args, **kwargs):
    kwargs = super(TransakcijaDodatakCreate, self).get_form_kwargs(*args, **kwargs)
    kwargs['user'] = self.request.user
    return kwargs
</code>```

Body:
I am new to django, need some help.

forms.py

import floppyforms as ff
from django import forms
from django.contrib.auth.models import User

from .models import Prodavnica, Racun, Transakcija
...

class IzdatakForm(forms.ModelForm):
    izdatak = forms.DecimalField(max_digits=20,
                              decimal_places=2,
                              widget=forms.NumberInput(attrs={'min': '0', 'step': '0.01'}))
    datum = ff.DateField(widget=ff.DateInput(format='yyyy-mm-dd'))
    vreme = ff.TimeField(widget=ff.TimeInput(attrs={'step': '60'}, format='HH-MM'))
    prodavnica = forms.ModelChoiceField(required=True,queryset=Prodavnica.objects.all())

    class Meta:
        model = Transakcija
        fields = ['izdatak', 'datum', 'vreme', 'racun', 'prodavnica']

models.py

from django.contrib.auth.models import User
from django.db import models

from django.urls import reverse

# Create your models here.

class Prodavnica(models.Model):
    author = models.ForeignKey(User, on_delete=models.PROTECT)
    naziv = models.CharField(max_length=50, unique=True, blank=False)
    adresa = models.CharField(max_length=200, blank=True)
    telefon = models.CharField(max_length=50, blank=True)
    foursquare = models.URLField(blank=True)

    def get_absolute_url(self):
        return reverse(viewname='finance_detail_shop', kwargs={'pk': self.pk})

    def __str__(self):
        return self.naziv

class Transakcija(models.Model):
    korisnik = models.ForeignKey(User, on_delete=models.PROTECT)
    suma = models.DecimalField(max_digits=20, decimal_places=2, default='0.0')
    izdatak = models.DecimalField(max_digits=20, decimal_places=2, default='0.0', null=True)
    dodatak = models.DecimalField(max_digits=20, decimal_places=2, default='0.0', null=True)
    prodavnica = models.ForeignKey('Prodavnica', related_name='prodavnica', blank=True, null=True)
    racun = models.ForeignKey('Racun', related_name='Racun')
    datum = models.DateField()
    vreme = models.TimeField()

    def get_absolute_url(self):
        return reverse(viewname='finance_detail_transaction', kwargs={'pk': self.pk})

    def __str__(self):
        return '%s %s (%s %s)' % (self.pk, self.suma, self.datum,self.vreme)

class Racun(models.Model):
    vlasnik = models.ForeignKey(User, on_delete=models.PROTECT, related_name='vlasnik')
    ovlacena_lica = models.ManyToManyField(User, related_name='ovlaceno_lice')
    naziv = models.CharField(max_length=50, unique=True)
    broj = models.IntegerField(unique=True)

    def get_absolute_url(self):
        return reverse(viewname='finance_detail_account', kwargs={'pk': self.pk})

    def __str__(self):
        return self.naziv

views.py

class TransakcijaDodatakCreate(CreateView):
    model = Transakcija
    form_class = DodatakForm

    def get_form(self, form_class=None):
        user = self.request.user
        racun = Racun.objects.filter(Q(vlasnik=user) | Q(ovlacena_lica=user))
        self.fields['racun'].queryset = racun
        return super().get_form(form_class)

    def form_valid(self, form):
        user = self.request.user
        form.instance.korisnik = user
        form.instance.izdatak = None
        form.instance.prodavnica = None
        return super(TransakcijaDodatakCreate, self).form_valid(form)

    template_name = 'finance/transakcija/dodaci/form.html'

Returns error 'NoneType' object is not subscriptable.

I am trying to have only set ModelChoiceField racun's queryset to only those racuns that user owns.

I was wandering if it is possible to set queryset for ModelChoiceField from CreateView?

Body:
That code belongs in an __init__ method on the form, not in the view.

class DodatakForm(forms.ModelForm):
    ...

    def __init__(self, *args, **kwargs):
        user = kwargs.pop('user', None)
        super(DodatakForm, self).__init__(*args, **kwargs)
        if user:
            racun = Racun.objects.filter(Q(vlasnik=user) | Q(ovlacena_lica=user))
            self.fields['racun'].queryset = racun

and in the view, instead of overriding get_form, define get_form_kwargs:

def get_form_kwargs(self, *args, **kwargs):
    kwargs = super(TransakcijaDodatakCreate, self).get_form_kwargs(*args, **kwargs)
    kwargs['user'] = self.request.user
    return kwargs


问:
Git exclude a commit in a branch
I have a commit, I have stored in a branch, because this should go only to a specific box.

I have merged it to the branch master, but not the branch dev, that I use locally.

Now, by mistake I merged master to dev and that introduced this commit to dev.

I know can git revert sha, to branch dev; but since this is going to introduce a commit that undoes that commit (I am guessing, I haven't exactly tried this), when I merge master, will this commit be undone too?

If so, how do I undo this commit only from the branch dev.

And oh, git reset HEAD^1 --hard is not an option because there are other commits on master, after the un-needed commit.

If reset back again and apply is the only option, then how do I only merge those extra commits from master other than the un-needed commit.

Update:

Here is the commit tree. Looks complex. I have pointed to the commit, that I don't need in the dev. (I have also removed any personally identifiable information, thanks for understanding. It is so much simpler to screenshot gitk than to ascii art.)

Thanks in advance!

答:
git reflog, then git reset --hard  are your friends to undo mistakes.

In order to avoid a single commit when merging a branch, this is what I have just used in my project:

Assume: merge from branch B to head.

Identify revid of commit to be avoided (R0)

Identify revid of commit just prior to R0  (R1)

```<code>git merge <R1>
git merge -s ours R0
git merge B
</code>```

ContentLicense: CC BY-SA 2.5

Title: Git exclude a commit in a branch

Body:
git reflog, then git reset --hard  are your friends to undo mistakes.

In order to avoid a single commit when merging a branch, this is what I have just used in my project:

Assume: merge from branch B to head.

Identify revid of commit to be avoided (R0)

Identify revid of commit just prior to R0  (R1)

git merge <R1>
git merge -s ours R0
git merge B


问:
Scala scopt error with Seq[String]
I'm trying to create a scopt option for Seq[String]:

```<code>import scopt._
import scopt.Read._
opt[Seq[String]]("foobar")
                ^ error
</code>```

but the compiler complains that it could not find implicit value for evidence parameter of type scopt.Read[Seq[String]].

I'm using Scala 2.11.2 and scopt 3.3.0.

Am I missing an import or something else?

答:
This error seems to be resolved in scopt "3.6.0"

here's what my build.sbt looks like:

```<code>scalaVersion := "2.11.8"
libraryDependencies ++= Seq(
  "org.apache.spark" % "spark-core_2.11" % "2.1.0" ,
  "com.github.scopt" %% "scopt" % "3.6.0")
</code>```

Title: Scala scopt error with Seq[String]

Body:
I'm trying to create a scopt option for Seq[String]:

import scopt._
import scopt.Read._
opt[Seq[String]]("foobar")
                ^ error

but the compiler complains that it could not find implicit value for evidence parameter of type scopt.Read[Seq[String]].

I'm using Scala 2.11.2 and scopt 3.3.0.

Am I missing an import or something else?

Body:
This error seems to be resolved in scopt "3.6.0"

here's what my build.sbt looks like:

scalaVersion := "2.11.8"
libraryDependencies ++= Seq(
  "org.apache.spark" % "spark-core_2.11" % "2.1.0" ,
  "com.github.scopt" %% "scopt" % "3.6.0")


问:
Error download from Yahoo finance
On 16th May 2017 yahoo.finance change the url to download the Eod Price. I try to use the new Url but it doesn't work.

```<code>With ActiveSheet.QueryTables.Add(Connection:= _
       "TEXT;https://query1.finance.yahoo.com/v7/finance/download/APPL?period1=946854000&period2=1495234800&interval=1d&events=history&crumb=" + mycrumb  _
       , Destination:=Range("Dati!$A$2"))
       .Name = "Data Table"
       .FieldNames = True
       .RowNumbers = False
       .FillAdjacentFormulas = False
       .PreserveFormatting = True
       .RefreshOnFileOpen = False
       .RefreshStyle = xlInsertDeleteCells
       .SavePassword = False
       .SaveData = True
       .AdjustColumnWidth = True
       .RefreshPeriod = 0
       .TextFilePromptOnRefresh = False
       .TextFilePlatform = 850
       .TextFileStartRow = 1
       .TextFileParseType = xlDelimited
       .TextFileTextQualifier = xlTextQualifierDoubleQuote
       .TextFileConsecutiveDelimiter = False
       .TextFileTabDelimiter = True
       .TextFileSemicolonDelimiter = False
       .TextFileCommaDelimiter = True
       .TextFileSpaceDelimiter = False
       .TextFileColumnDataTypes = Array(5, 1, 1, 1, 1, 1, 9)
       .TextFileTrailingMinusNumbers = True
       .Refresh BackgroundQuery:=False
</code>```

May someone help me to solve my problem? Have someone the same problem?
Thanks a lot

Andrea

答:
I've been having the same problem since May.  Came up with this code yesterday:</p>

```<code>Sub YahooHistDataHoriztl()
 '---enter in cell A1 for daily:   _https://finance.yahoo.com/quote/AAPL/history?interval=1d
 '---enter in cell A1 for weekly:  _https://finance.yahoo.com/quote/AAPL/history?interval=1wk
 '---enter in cell A1 for DOW weekly:  _https://finance.yahoo.com/quote/^DJI/history?interval=1wk

 '--- Historical Data will load in columns D through J
 '---This program developed after watching video from 'Automate the Web' 2017-07-03
 '---Use Excel & VBA to automate Internet Explorer -beginner
 '----_https://www.youtube.com/watch?v=GRuzoI_kihI&index=3&list=PL0bsMa4HWk9synJWmuqZmI4Z0a3eurN7V
Dim objIE As InternetExplorer 'special object variable representing the IE browser
Dim aEle As HTMLLinkElement 'special object variable for an <a> (link) element
Dim y As Integer 'integer variable used as a counter for Rows
Dim z As Integer 'integer variable used as a counter for Columns
Dim result As String 'string variable that will hold our result link
Dim Pather As String
Dim CurrActiveBook As String
Dim CurrActiveSheet As String
Dim drV As String
Dim targetBook As String

 'dimension (declare or set aside memory for) our variables

Application.DisplayAlerts = False

  Pather = ThisWorkbook.Path & "\"   '---holds current path---
  ChDrive Pather                      '---sets excel to the current drive---
  ChDir Pather                       '---sets excel to the current drive---
  drV = Left(Pather, 3)
  CurrActiveBook = ActiveWorkbook.Name
  CurrActiveSheet = ActiveSheet.Name
   targetBook = ActiveWorkbook.Name
   Range("D2:K62").Select
    Selection.ClearContents         '---clears old data

   Set objIE = New InternetExplorer      'initiating a new instance of Internet Explorer and asigning it to objIE
    objIE.Visible = False      'make IE browser visible (False would allow IE to run in the background)
    objIE.navigate Sheets(CurrActiveSheet).Range("A1").Value      'navigate IE to this web page (a pretty neat search engine really)
     Do While objIE.Busy = True Or objIE.readyState <> 4: DoEvents: Loop     'wait here a few seconds while the browser is busy
      Application.Wait Now + TimeValue("0:00:05")  '---Give an extra 5 seconds to upload

  Range("D1") = "Date"
  Range("E1") = "Open"
  Range("F1") = "High"
  Range("G1") = "Low"
  Range("H1") = "Close"
  Range("I1") = "Adj Close*"
  Range("J1") = "Avg Vol"

  Range("D2").Select
    y = 0   'the first search result will go in row 2
    z = 0
   For Each aEle In objIE.document.getElementsByClassName("Py(10px)")   'for each <a> element in the collection of objects with class of 'result__a'...
      ActiveCell.Offset(y, z).Value = aEle.innerText
        Debug.Print aEle.innerText

 If z > 5 Then   '---Data loads in one column.  This converts to a table.-------
    z = 0
    y = y + 1   'increment our row counter, so the next result goes below
   Application.Wait Now + (TimeValue("0:00:01") / 2) '--giver data an extra 1/2 second to load up---
Else
    If z = 1 Then
     If Right(ActiveCell.Offset(y, z), 5) = "Split" Then   '---Split reset back to date column---
        z = 0
        y = y + 1
         Else
           If Right(ActiveCell.Offset(y, z), 8) = "Dividend" Then   '---Dividend reset back to date column---
            z = 0
            y = y + 1
           Else
         z = z + 1
        End If
      End If
    Else
      z = z + 1
    End If
  End If
   DoEvents
  Next  'repeat times the # of ele's we have in the collection

objIE.Quit      'close the browser
Columns("D:J").Select
 Selection.Columns.AutoFit
  Range("D1").Select

      Application.DisplayAlerts = True
     MsgBox "Done"
   End Sub '---End of program---
</code>```

Title: Error download from Yahoo finance

Body:
On 16th May 2017 yahoo.finance change the url to download the Eod Price. I try to use the new Url but it doesn't work.

With ActiveSheet.QueryTables.Add(Connection:= _
       "TEXT;https://query1.finance.yahoo.com/v7/finance/download/APPL?period1=946854000&period2=1495234800&interval=1d&events=history&crumb=" + mycrumb  _
       , Destination:=Range("Dati!$A$2"))
       .Name = "Data Table"
       .FieldNames = True
       .RowNumbers = False
       .FillAdjacentFormulas = False
       .PreserveFormatting = True
       .RefreshOnFileOpen = False
       .RefreshStyle = xlInsertDeleteCells
       .SavePassword = False
       .SaveData = True
       .AdjustColumnWidth = True
       .RefreshPeriod = 0
       .TextFilePromptOnRefresh = False
       .TextFilePlatform = 850
       .TextFileStartRow = 1
       .TextFileParseType = xlDelimited
       .TextFileTextQualifier = xlTextQualifierDoubleQuote
       .TextFileConsecutiveDelimiter = False
       .TextFileTabDelimiter = True
       .TextFileSemicolonDelimiter = False
       .TextFileCommaDelimiter = True
       .TextFileSpaceDelimiter = False
       .TextFileColumnDataTypes = Array(5, 1, 1, 1, 1, 1, 9)
       .TextFileTrailingMinusNumbers = True
       .Refresh BackgroundQuery:=False

May someone help me to solve my problem? Have someone the same problem?
Thanks a lot

Andrea

Body:
I've been having the same problem since May.  Came up with this code yesterday:

Sub YahooHistDataHoriztl()
 '---enter in cell A1 for daily:   _https://finance.yahoo.com/quote/AAPL/history?interval=1d
 '---enter in cell A1 for weekly:  _https://finance.yahoo.com/quote/AAPL/history?interval=1wk
 '---enter in cell A1 for DOW weekly:  _https://finance.yahoo.com/quote/^DJI/history?interval=1wk

 '--- Historical Data will load in columns D through J
 '---This program developed after watching video from 'Automate the Web' 2017-07-03
 '---Use Excel & VBA to automate Internet Explorer -beginner
 '----_https://www.youtube.com/watch?v=GRuzoI_kihI&index=3&list=PL0bsMa4HWk9synJWmuqZmI4Z0a3eurN7V
Dim objIE As InternetExplorer 'special object variable representing the IE browser
Dim aEle As HTMLLinkElement 'special object variable for an <a> (link) element
Dim y As Integer 'integer variable used as a counter for Rows
Dim z As Integer 'integer variable used as a counter for Columns
Dim result As String 'string variable that will hold our result link
Dim Pather As String
Dim CurrActiveBook As String
Dim CurrActiveSheet As String
Dim drV As String
Dim targetBook As String

 'dimension (declare or set aside memory for) our variables

Application.DisplayAlerts = False

  Pather = ThisWorkbook.Path & "\"   '---holds current path---
  ChDrive Pather                      '---sets excel to the current drive---
  ChDir Pather                       '---sets excel to the current drive---
  drV = Left(Pather, 3)
  CurrActiveBook = ActiveWorkbook.Name
  CurrActiveSheet = ActiveSheet.Name
   targetBook = ActiveWorkbook.Name
   Range("D2:K62").Select
    Selection.ClearContents         '---clears old data

   Set objIE = New InternetExplorer      'initiating a new instance of Internet Explorer and asigning it to objIE
    objIE.Visible = False      'make IE browser visible (False would allow IE to run in the background)
    objIE.navigate Sheets(CurrActiveSheet).Range("A1").Value      'navigate IE to this web page (a pretty neat search engine really)
     Do While objIE.Busy = True Or objIE.readyState <> 4: DoEvents: Loop     'wait here a few seconds while the browser is busy
      Application.Wait Now + TimeValue("0:00:05")  '---Give an extra 5 seconds to upload

  Range("D1") = "Date"
  Range("E1") = "Open"
  Range("F1") = "High"
  Range("G1") = "Low"
  Range("H1") = "Close"
  Range("I1") = "Adj Close*"
  Range("J1") = "Avg Vol"

  Range("D2").Select
    y = 0   'the first search result will go in row 2
    z = 0
   For Each aEle In objIE.document.getElementsByClassName("Py(10px)")   'for each <a> element in the collection of objects with class of 'result__a'...
      ActiveCell.Offset(y, z).Value = aEle.innerText
        Debug.Print aEle.innerText

 If z > 5 Then   '---Data loads in one column.  This converts to a table.-------
    z = 0
    y = y + 1   'increment our row counter, so the next result goes below
   Application.Wait Now + (TimeValue("0:00:01") / 2) '--giver data an extra 1/2 second to load up---
Else
    If z = 1 Then
     If Right(ActiveCell.Offset(y, z), 5) = "Split" Then   '---Split reset back to date column---
        z = 0
        y = y + 1
         Else
           If Right(ActiveCell.Offset(y, z), 8) = "Dividend" Then   '---Dividend reset back to date column---
            z = 0
            y = y + 1
           Else
         z = z + 1
        End If
      End If
    Else
      z = z + 1
    End If
  End If
   DoEvents
  Next  'repeat times the # of ele's we have in the collection

objIE.Quit      'close the browser
Columns("D:J").Select
 Selection.Columns.AutoFit
  Range("D1").Select

      Application.DisplayAlerts = True
     MsgBox "Done"
   End Sub '---End of program---


问:
Sphinx documentation: Include svg images in PDFs via latex
I'm doing an internship for an IT company which needs a document application for its firmware docs (md files).

The request was to maintain these md files and to convert them to rst format (I used pandoc). So now I have a configured Sphinx application with only rst files. The problem now is that some rst have links to SVG images, and I have to use the latex builder of Sphinx to convert them to PDFs.

I've searched around and I found this solution from 2 years ago, which was essentially what I was looking for: https://sites.google.com/site/nickfolse/home/sphinx-latexpdf-output-with-svg-images. I tried to implement it but I'm not an expert with GNU makefiles and I don't know if the current version of Sphinx allows it or if it is out there an easy workaround, so the thing didn't succeed.

Does someone have a viable solution for this?

答:
At this time, SVG is still not supported. I work around it in Pyramid docs by exporting the original file (OmniGraffle) to both SVG and PNG.

In docs/narr/router.rst:

```<code>.. image:: ../_static/pyramid_request_processing.*
</code>```

And we place images in docs/_static.

The HTML uses SVG and the PDF uses PNG.

Body:
At this time, SVG is still not supported. I work around it in Pyramid docs by exporting the original file (OmniGraffle) to both SVG and PNG.

In docs/narr/router.rst:

.. image:: ../_static/pyramid_request_processing.*

And we place images in docs/_static.

The HTML uses SVG and the PDF uses PNG.


问:
Plot histogram for discrete data
I'm struggling a lot to plot histogram using R for the following data:

```<code>ip_addr_player_id,event_name,level,time_to_finish,

118.93.180.241, Puzzle Complete, Puzzle 1,33.28 seconds
</code>```

This is a single row of data. I need to pot histogram of the number player vs the number of levels played. I was able to successfully plot scatter plot, points, lines etc. but no histogram.

```<code>on Xaxis: number of levels.
Yaxis: Number of player.
</code>```

Each ip address is unique and multiple levels can be played by single ip address. I have attached a sample picture.

答:
```<code>library(ggplot2)
df <- data.frame(ip_addr_player_id='118.93.180.241',
                 event_name='Puzzle Complete',
                 level='Puzzle 1',
                 time_to_finish='33.28 seconds')
df$num_levels <- strsplit(var,split =' ')[[1]][-1]
ggplot(df) +geom_bar(aes(num_levels)) +labs(x="Num Levels",y="Num Players")
</code>```

ContentLicense: CC BY-SA 4.0

Title: Plot histogram for discrete data

Body:
I'm struggling a lot to plot histogram using R for the following data:

ip_addr_player_id,event_name,level,time_to_finish,

118.93.180.241, Puzzle Complete, Puzzle 1,33.28 seconds

This is a single row of data. I need to pot histogram of the number player vs the number of levels played. I was able to successfully plot scatter plot, points, lines etc. but no histogram.

on Xaxis: number of levels.
Yaxis: Number of player.

Each ip address is unique and multiple levels can be played by single ip address. I have attached a sample picture.