问:
EAGER and Pagination : Spring MVC + JPA Repository + Hibernate
I have a entity A which has a relation @OneToMany with a entity B (fetch mode = EAGER). Entitity A has other relations in LAZY with other entities too, but isn't important for this problem.

Entity B has a relation @ManyToOne with entity A too (fech mode = EAGER). Entitity B has other relations in LAZY with other entities too, but isn't important for this problem.

Later, I have a interface that implements JpaRepository class where I define a @Query with some inner joins between others entities for get a coleccion of Entities A of 10 items with a calculated score, using Page and Pageable elements.

Here this process fail. why?

My table for entity A in Database has +1000 registers that have the conditions of @query. But before Hibernate or JPA return me 10 entities A, internally, exect 1000+ selects for get Entities B data (EAGER realation) and explote.

why dont get 10 entities A and exec 10 "selects" for get 10 entities B only?

The unique solution is change my relations from EAGER to LAZY?? dont work pageable with EAGER?

Why did this happend? any solution?

EDIT:
aclaration: +1000 entityA +1000 entityB (in my example one entityA with only one entityB, but entityA can has multiples entitiesB)

```<code>@Entity
@Table(name="EntityA")
public class EntityA implements Serializable{

    @Id
    @GeneratedValue(generator = "uuid")
    @GenericGenerator(name = "uuid", strategy = "uuid2")
    @Column(columnDefinition = "BINARY(16)")
    private UUID id;

    @OneToMany(mappedBy="entityA", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @OrderBy("updatedDate DESC")
    private Set<EntityB> entitiesB = new HashSet<EntityB>();

    ...
}

@Entity
@Table(name="EntityB")
public class EntityB implements Serializable{

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(generator = "uuid")
    @GenericGenerator(name = "uuid", strategy = "uuid2")
    @Column(columnDefinition = "BINARY(16)")
    private UUID id;

    @ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JoinColumn(name = "idEntityA", nullable = false)
    private EntityA entityA;

    ...
}

public interface EntityA_DAO  extends JpaRepository<EntityA, UUID>{
    @Query("SELECT DISTINCT a FROM EntityA a INNER JOIN a.entityB b LEFT JOIN b.scoreEntityB s INNER JOIN a.user u INNER JOIN a.properties p INNER JOIN p.category c " +
            "WHERE c.cod IN (:codcats) AND a.user <> :user AND b.codState = '001' AND a.codState NOT IN ('002','004','005') AND p.deleted <> 1 " +
            "GROUP BY b ORDER BY a.createdDate DESC, COUNT(s) DESC")
    public Page<EntityA> findAllByCategories(@Param("user") User user, @Param("codcats") List<Integer> lstCodCats,  Pageable pageable);
}
</code>```

EDIT 2

this is snippett of my trace error, repeat and repeat same :

at java.util.HashMap.put(Unknown Source)  at
  java.util.HashSet.add(Unknown Source)     at
  java.util.AbstractCollection.addAll(Unknown Source)   at
  org.hibernate.collection.internal.PersistentSet.endRead(PersistentSet.java:327)
    at
  org.hibernate.engine.loading.internal.CollectionLoadContext.endLoadingCollection(CollectionLoadContext.java:234)
    at
  org.hibernate.engine.loading.internal.CollectionLoadContext.endLoadingCollections(CollectionLoadContext.java:221)
    at
  org.hibernate.engine.loading.internal.CollectionLoadContext.endLoadingCollections(CollectionLoadContext.java:194)
    at
  org.hibernate.loader.plan.exec.process.internal.CollectionReferenceInitializerImpl.endLoading(CollectionReferenceInitializerImpl.java:154)
    at
  org.hibernate.loader.plan.exec.process.internal.AbstractRowReader.finishLoadingCollections(AbstractRowReader.java:249)
    at
  org.hibernate.loader.plan.exec.process.internal.AbstractRowReader.finishUp(AbstractRowReader.java:212)
    at
  org.hibernate.loader.plan.exec.process.internal.ResultSetProcessorImpl.extractResults(ResultSetProcessorImpl.java:123)
    at
  org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeLoad(AbstractLoadPlanBasedLoader.java:122)
    at
  org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeLoad(AbstractLoadPlanBasedLoader.java:86)
    at
  org.hibernate.loader.entity.plan.AbstractLoadPlanBasedEntityLoader.load(AbstractLoadPlanBasedEntityLoader.java:167)
    at
  org.hibernate.persister.entity.AbstractEntityPersister.load(AbstractEntityPersister.java:3956)
    at
  org.hibernate.event.internal.DefaultLoadEventListener.loadFromDatasource(DefaultLoadEventListener.java:508)
    at
  org.hibernate.event.internal.DefaultLoadEventListener.doLoad(DefaultLoadEventListener.java:478)
    at
  org.hibernate.event.internal.DefaultLoadEventListener.load(DefaultLoadEventListener.java:219)
    at
  org.hibernate.event.internal.DefaultLoadEventListener.doOnLoad(DefaultLoadEventListener.java:116)
    at
  org.hibernate.event.internal.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:89)
    at org.hibernate.internal.SessionImpl.fireLoad(SessionImpl.java:1129)
    at
  org.hibernate.internal.SessionImpl.immediateLoad(SessionImpl.java:997)
    at
  org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:157)
    at
  org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:266)
    at
  org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:68)
    at
  com.treebuk.model.Fragment_$$_jvsta55_10.hashCode(Fragment_$$_jvsta55_10.java)
    at com.treebuk.model.Fragment.hashCode(Fragment.java:210)   at
  sun.reflect.GeneratedMethodAccessor111.invoke(Unknown Source)     at
  sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)   at
  java.lang.reflect.Method.invoke(Unknown Source)   at
  org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:79)
    at
  com.treebuk.model.Fragment_$$_jvsta55_10.hashCode(Fragment_$$_jvsta55_10.java)
    at com.treebuk.model.TextFragment.hashCode(TextFragment.java:340)   at
  java.util.HashMap.hash(Unknown Source)    at
  java.util.HashMap.put(Unknown Source)     at
  java.util.HashSet.add(Unknown Source)     at
  java.util.AbstractCollection.addAll(Unknown Source)   at
  org.hibernate.collection.internal.PersistentSet.endRead(PersistentSet.java:327)
    at
  org.hibernate.engine.loading.internal.CollectionLoadContext.endLoadingCollection(CollectionLoadContext.java:234)
    at
  org.hibernate.engine.loading.internal.CollectionLoadContext.endLoadingCollections(CollectionLoadContext.java:221)
    at
  org.hibernate.engine.loading.internal.CollectionLoadContext.endLoadingCollections(CollectionLoadContext.java:194)
    at
  org.hibernate.loader.plan.exec.process.internal.CollectionReferenceInitializerImpl.endLoading(CollectionReferenceInitializerImpl.java:154)
    at
  org.hibernate.loader.plan.exec.process.internal.AbstractRowReader.finishLoadingCollections(AbstractRowReader.java:249)
    at
  org.hibernate.loader.plan.exec.process.internal.AbstractRowReader.finishUp(AbstractRowReader.java:212)
    at
  org.hibernate.loader.plan.exec.process.internal.ResultSetProcessorImpl.extractResults(ResultSetProcessorImpl.java:123)
    at
  org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeLoad(AbstractLoadPlanBasedLoader.java:122)
    at
  org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeLoad(AbstractLoadPlanBasedLoader.java:86)
    at
  org.hibernate.loader.entity.plan.AbstractLoadPlanBasedEntityLoader.load(AbstractLoadPlanBasedEntityLoader.java:167)
    at
  org.hibernate.persister.entity.AbstractEntityPersister.load(AbstractEntityPersister.java:3956)
    at
  org.hibernate.event.internal.DefaultLoadEventListener.loadFromDatasource(DefaultLoadEventListener.java:508)
    at
  org.hibernate.event.internal.DefaultLoadEventListener.doLoad(DefaultLoadEventListener.java:478)
    at
  org.hibernate.event.internal.DefaultLoadEventListener.load(DefaultLoadEventListener.java:219)
    at
  org.hibernate.event.internal.DefaultLoadEventListener.doOnLoad(DefaultLoadEventListener.java:116)
    at
  org.hibernate.event.internal.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:89)
    at org.hibernate.internal.SessionImpl.fireLoad(SessionImpl.java:1129)
    at
  org.hibernate.internal.SessionImpl.immediateLoad(SessionImpl.java:997)
    at
  org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:157)
    at
  org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:266)
    at
  org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:68)
    at
  com.treebuk.model.Fragment_$$_jvsta55_10.hashCode(Fragment_$$_jvsta55_10.java)
    at com.treebuk.model.Fragment.hashCode(Fragment.java:210)   at
  sun.reflect.GeneratedMethodAccessor111.invoke(Unknown Source)     at
  sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)   at
  java.lang.reflect.Method.invoke(Unknown Source)   at
  org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:79)
    at
  com.treebuk.model.Fragment_$$_jvsta55_10.hashCode(Fragment_$$_jvsta55_10.java)
    at com.treebuk.model.TextFragment.hashCode(TextFragment.java:340)   at
  java.util.HashMap.hash(Unknown Source)

答: Finnaly, I found the problem. The problem was th method Entity B hasCode(), that this method had a comparation with Entity A, Then when Spring try to get elements, executes hascode method, and entered in infinite loop. I change the hascode() and equal() methods for delete these comparations (not necessary in my case).</p>

Body:
I have a entity A which has a relation @OneToMany with a entity B (fetch mode = EAGER). Entitity A has other relations in LAZY with other entities too, but isn't important for this problem.

Entity B has a relation @ManyToOne with entity A too (fech mode = EAGER). Entitity B has other relations in LAZY with other entities too, but isn't important for this problem.

Later, I have a interface that implements JpaRepository class where I define a @Query with some inner joins between others entities for get a coleccion of Entities A of 10 items with a calculated score, using Page and Pageable elements.

Here this process fail. why?

My table for entity A in Database has +1000 registers that have the conditions of @query. But before Hibernate or JPA return me 10 entities A, internally, exect 1000+ selects for get Entities B data (EAGER realation) and explote.

why dont get 10 entities A and exec 10 "selects" for get 10 entities B only?

The unique solution is change my relations from EAGER to LAZY?? dont work pageable with EAGER?

Why did this happend? any solution?

EDIT:
aclaration: +1000 entityA +1000 entityB (in my example one entityA with only one entityB, but entityA can has multiples entitiesB)

@Entity
@Table(name="EntityA")
public class EntityA implements Serializable{

    @Id
    @GeneratedValue(generator = "uuid")
    @GenericGenerator(name = "uuid", strategy = "uuid2")
    @Column(columnDefinition = "BINARY(16)")
    private UUID id;

    @OneToMany(mappedBy="entityA", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @OrderBy("updatedDate DESC")
    private Set<EntityB> entitiesB = new HashSet<EntityB>();

    ...
}

@Entity
@Table(name="EntityB")
public class EntityB implements Serializable{

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(generator = "uuid")
    @GenericGenerator(name = "uuid", strategy = "uuid2")
    @Column(columnDefinition = "BINARY(16)")
    private UUID id;

    @ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JoinColumn(name = "idEntityA", nullable = false)
    private EntityA entityA;

    ...
}

public interface EntityA_DAO  extends JpaRepository<EntityA, UUID>{
    @Query("SELECT DISTINCT a FROM EntityA a INNER JOIN a.entityB b LEFT JOIN b.scoreEntityB s INNER JOIN a.user u INNER JOIN a.properties p INNER JOIN p.category c " +
            "WHERE c.cod IN (:codcats) AND a.user <> :user AND b.codState = '001' AND a.codState NOT IN ('002','004','005') AND p.deleted <> 1 " +
            "GROUP BY b ORDER BY a.createdDate DESC, COUNT(s) DESC")
    public Page<EntityA> findAllByCategories(@Param("user") User user, @Param("codcats") List<Integer> lstCodCats,  Pageable pageable);
}

EDIT 2

this is snippett of my trace error, repeat and repeat same :

at java.util.HashMap.put(Unknown Source)  at
  java.util.HashSet.add(Unknown Source)     at
  java.util.AbstractCollection.addAll(Unknown Source)   at
  org.hibernate.collection.internal.PersistentSet.endRead(PersistentSet.java:327)
    at
  org.hibernate.engine.loading.internal.CollectionLoadContext.endLoadingCollection(CollectionLoadContext.java:234)
    at
  org.hibernate.engine.loading.internal.CollectionLoadContext.endLoadingCollections(CollectionLoadContext.java:221)
    at
  org.hibernate.engine.loading.internal.CollectionLoadContext.endLoadingCollections(CollectionLoadContext.java:194)
    at
  org.hibernate.loader.plan.exec.process.internal.CollectionReferenceInitializerImpl.endLoading(CollectionReferenceInitializerImpl.java:154)
    at
  org.hibernate.loader.plan.exec.process.internal.AbstractRowReader.finishLoadingCollections(AbstractRowReader.java:249)
    at
  org.hibernate.loader.plan.exec.process.internal.AbstractRowReader.finishUp(AbstractRowReader.java:212)
    at
  org.hibernate.loader.plan.exec.process.internal.ResultSetProcessorImpl.extractResults(ResultSetProcessorImpl.java:123)
    at
  org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeLoad(AbstractLoadPlanBasedLoader.java:122)
    at
  org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeLoad(AbstractLoadPlanBasedLoader.java:86)
    at
  org.hibernate.loader.entity.plan.AbstractLoadPlanBasedEntityLoader.load(AbstractLoadPlanBasedEntityLoader.java:167)
    at
  org.hibernate.persister.entity.AbstractEntityPersister.load(AbstractEntityPersister.java:3956)
    at
  org.hibernate.event.internal.DefaultLoadEventListener.loadFromDatasource(DefaultLoadEventListener.java:508)
    at
  org.hibernate.event.internal.DefaultLoadEventListener.doLoad(DefaultLoadEventListener.java:478)
    at
  org.hibernate.event.internal.DefaultLoadEventListener.load(DefaultLoadEventListener.java:219)
    at
  org.hibernate.event.internal.DefaultLoadEventListener.doOnLoad(DefaultLoadEventListener.java:116)
    at
  org.hibernate.event.internal.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:89)
    at org.hibernate.internal.SessionImpl.fireLoad(SessionImpl.java:1129)
    at
  org.hibernate.internal.SessionImpl.immediateLoad(SessionImpl.java:997)
    at
  org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:157)
    at
  org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:266)
    at
  org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:68)
    at
  com.treebuk.model.Fragment_$$_jvsta55_10.hashCode(Fragment_$$_jvsta55_10.java)
    at com.treebuk.model.Fragment.hashCode(Fragment.java:210)   at
  sun.reflect.GeneratedMethodAccessor111.invoke(Unknown Source)     at
  sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)   at
  java.lang.reflect.Method.invoke(Unknown Source)   at
  org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:79)
    at
  com.treebuk.model.Fragment_$$_jvsta55_10.hashCode(Fragment_$$_jvsta55_10.java)
    at com.treebuk.model.TextFragment.hashCode(TextFragment.java:340)   at
  java.util.HashMap.hash(Unknown Source)    at
  java.util.HashMap.put(Unknown Source)     at
  java.util.HashSet.add(Unknown Source)     at
  java.util.AbstractCollection.addAll(Unknown Source)   at
  org.hibernate.collection.internal.PersistentSet.endRead(PersistentSet.java:327)
    at
  org.hibernate.engine.loading.internal.CollectionLoadContext.endLoadingCollection(CollectionLoadContext.java:234)
    at
  org.hibernate.engine.loading.internal.CollectionLoadContext.endLoadingCollections(CollectionLoadContext.java:221)
    at
  org.hibernate.engine.loading.internal.CollectionLoadContext.endLoadingCollections(CollectionLoadContext.java:194)
    at
  org.hibernate.loader.plan.exec.process.internal.CollectionReferenceInitializerImpl.endLoading(CollectionReferenceInitializerImpl.java:154)
    at
  org.hibernate.loader.plan.exec.process.internal.AbstractRowReader.finishLoadingCollections(AbstractRowReader.java:249)
    at
  org.hibernate.loader.plan.exec.process.internal.AbstractRowReader.finishUp(AbstractRowReader.java:212)
    at
  org.hibernate.loader.plan.exec.process.internal.ResultSetProcessorImpl.extractResults(ResultSetProcessorImpl.java:123)
    at
  org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeLoad(AbstractLoadPlanBasedLoader.java:122)
    at
  org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeLoad(AbstractLoadPlanBasedLoader.java:86)
    at
  org.hibernate.loader.entity.plan.AbstractLoadPlanBasedEntityLoader.load(AbstractLoadPlanBasedEntityLoader.java:167)
    at
  org.hibernate.persister.entity.AbstractEntityPersister.load(AbstractEntityPersister.java:3956)
    at
  org.hibernate.event.internal.DefaultLoadEventListener.loadFromDatasource(DefaultLoadEventListener.java:508)
    at
  org.hibernate.event.internal.DefaultLoadEventListener.doLoad(DefaultLoadEventListener.java:478)
    at
  org.hibernate.event.internal.DefaultLoadEventListener.load(DefaultLoadEventListener.java:219)
    at
  org.hibernate.event.internal.DefaultLoadEventListener.doOnLoad(DefaultLoadEventListener.java:116)
    at
  org.hibernate.event.internal.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:89)
    at org.hibernate.internal.SessionImpl.fireLoad(SessionImpl.java:1129)
    at
  org.hibernate.internal.SessionImpl.immediateLoad(SessionImpl.java:997)
    at
  org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:157)
    at
  org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:266)
    at
  org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:68)
    at
  com.treebuk.model.Fragment_$$_jvsta55_10.hashCode(Fragment_$$_jvsta55_10.java)
    at com.treebuk.model.Fragment.hashCode(Fragment.java:210)   at
  sun.reflect.GeneratedMethodAccessor111.invoke(Unknown Source)     at
  sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)   at
  java.lang.reflect.Method.invoke(Unknown Source)   at
  org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:79)
    at
  com.treebuk.model.Fragment_$$_jvsta55_10.hashCode(Fragment_$$_jvsta55_10.java)
    at com.treebuk.model.TextFragment.hashCode(TextFragment.java:340)   at
  java.util.HashMap.hash(Unknown Source)


来源: stackexchange

问:
I am unable to input items from database into JComboBox
This is the Code. I am getting error while trying to import database items into the combo box. I am not able to take the name of the combob ox in (cmbProjectDetails.additems(name);).

Please see below code.

```<code>import java.awt.Color;

public class ProjectDetails_3_1 {

public JFrame frame;

private Connection connection=null;
private Statement statement;
private ResultSet resultSet=null;
private PreparedStatement pst=null;

private JSplitPane splitPaneRightMaster;

private JSplitPane splitPaneMaster;
private String sqlQuery;
private JPanel panelLeft;

public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                ProjectDetails_3_1 window = new ProjectDetails_3_1();
                window.frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

public ProjectDetails_3_1() {
    initialize();
}

    public  void getDatabaseConnection() {
        try
               {
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); //Load Driver
            Connection con = DriverManager.getConnection("jdbc:odbc:PRMS Build 8"); //Create Connection with Data Source Name : HOD_DATA
            Statement s = con.createStatement(); // Create Statement
            String query = "select PROJ_NAME from PROJECT"; // Create Query
            s.execute(query); // Execute Query
            ResultSet rs = s.getResultSet(); //return the data from Statement into ResultSet
            while(rs.next()) // Retrieve data from ResultSet
            {
                System.out.print("Project Name : "+rs.getString(1)); //1st column of Table from database
                System.out.println();//System.out.print(" , Name : "+rs.getString(2)); //2nd column of Table

            }
            s.close();
            con.close();
        }
        catch (Exception e)
                {
            System.out.println("Exception : "+e);
        }
    }

// Function to get database connection.
 /*public void getDatabaseConnection() {
            //Registering Oracle JDBC driver class
            try {
                Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
            }catch(ClassNotFoundException ex) {
                System.out.println("JDBC-ODBC driver not found: " + ex);
            }

            //Opening database connection
            try {
                connection = DriverManager.getConnection(
                     "jdbc:ucanaccess://D:/workspace/PRMS v1.0 Build 8/PRMS Build 8.mdb;memory=false",
                     "",
                     ""
                     );
                connection.setAutoCommit(false);
                statement = connection.createStatement();
            }catch(Exception ex){
                ex.printStackTrace();
            }

            return;
    }

    */
private void initialize() {

    frame = new JFrame();
    frame.getContentPane().setBackground(new Color(255, 255, 255));
          frame.setIconImage(Toolkit.getDefaultToolkit().getImage("D:\\Eclipse_Workspace\\PRMS v1.0 Build 9\\resources\\Logo_48.png"));
    frame.setResizable(false);
    frame.setTitle("PRMS[Build 9] - User Portal");
    frame.setSize(1000, 700);
    frame.setLocationRelativeTo(null);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setUndecorated(false);
    frame.getContentPane().setLayout(null);
    JPanel panelHeader = new JPanel();
    panelHeader.setBounds(0, 0, 1000, 10);
    panelHeader.setBackground(SystemColor.textHighlight);
    frame.getContentPane().add(panelHeader);
    panelHeader.setLayout(null);
    JPanel panelFooter = new JPanel();
    panelFooter.setBounds(0, 662, 1000, 10);
    panelFooter.setBackground(SystemColor.textHighlight);
    frame.getContentPane().add(panelFooter);
    panelFooter.setLayout(null);

    splitPaneMaster = new JSplitPane();
    splitPaneMaster.setResizeWeight(0.25);
    splitPaneMaster.setVerifyInputWhenFocusTarget(false);
    splitPaneMaster.setFocusable(false);
    splitPaneMaster.setDividerSize(0);
    splitPaneMaster.setBorder(null);
    splitPaneMaster.setOpaque(false);
    splitPaneMaster.setBounds(0, 7, 1000, 655);
    frame.getContentPane().add(splitPaneMaster);

    panelLeft = new JPanel();
    panelLeft.setRequestFocusEnabled(false);
    panelLeft.setBackground(SystemColor.textHighlight);
    splitPaneMaster.setLeftComponent(panelLeft);
    panelLeft.setLayout(null);

    splitPaneRightMaster = new JSplitPane();
    splitPaneRightMaster.setResizeWeight(0.084);
    splitPaneRightMaster.setVerifyInputWhenFocusTarget(false);
    splitPaneRightMaster.setFocusable(false);
    splitPaneRightMaster.setDividerSize(0);
    splitPaneRightMaster.setOrientation(JSplitPane.VERTICAL_SPLIT);
    splitPaneRightMaster.setBorder(null);
    splitPaneRightMaster.setOpaque(false);
    splitPaneMaster.setRightComponent(splitPaneRightMaster);

    JPanel panelDetails3_1 = new JPanel();
    panelDetails3_1.setBackground(Color.WHITE);
    splitPaneRightMaster.setRightComponent(panelDetails3_1);
    panelDetails3_1.setLayout(null);

    JLabel lblProjectDetails = new JLabel("Project Details");
    lblProjectDetails.setFont(new Font("Segoe UI Symbol", Font.BOLD, 18));
    lblProjectDetails.setBounds(80, 26, 178, 27);
    panelDetails3_1.add(lblProjectDetails);

    JLabel lblSelectAnyProject = new JLabel("Select any of the projects tagged to you to view the details.");
    lblSelectAnyProject.setFont(new Font("SansSerif", Font.BOLD, 12));
    lblSelectAnyProject.setBounds(80, 53, 466, 27);
    panelDetails3_1.add(lblSelectAnyProject);

    JLabel lblProjectName = new JLabel("Project Name:");
    lblProjectName.setBounds(80, 102, 83, 16);
    panelDetails3_1.add(lblProjectName);

    JComboBox cmbProjectDetails = new JComboBox<String>();
    //cmbProjectDetails.addItem("1111");
    //cmbProjectDetails.addItem("2222");
    cmbProjectDetails.setBounds(173, 97, 85, 27);
    panelDetails3_1.add(cmbProjectDetails);

}
private void fillCombo(){
    try{
        String sql= "select PROJ_NAME from PROJECT";
        pst=connection.prepareStatement(sql);
        resultSet=pst.executeQuery();

        while(resultSet.next()){
            String name= resultSet.getString("PROJ_NAME");
            cmbProjectDetails.additems(name);**//Error is here**

        }
    }
    catch(Exception e){
        System.out.println("Error releasing connection: " + e);
    }
}
// Function to release database connection and resources.
public void releaseDatabaseConnection() {
    try{
         if(resultSet != null){ resultSet.close();  }
        }catch(Exception ex){
    System.out.println("Error releasing resultSet: " + ex);
    }

    try{
    if(statement != null){  statement.close();  }
        }catch(Exception ex){
    System.out.println("Error releasing statement: " + ex);
    }

    try{
    if(connection != null){ connection.close(); }
        }catch(Exception ex){
    System.out.println("Error releasing connection: " + ex);
    }

    return;
}

}
</code>```

答:
I am not able to take the name of the combobox

Define the combo box variable as an instance variable, not a local variable.

An instance variable can be accessed by any method of the class. A local variable can only be accessed in the method where it is defined.

For example, you define these as instance variables:

```<code>private JSplitPane splitPaneRightMaster;

private JSplitPane splitPaneMaster;
private String sqlQuery;
private JPanel panelLeft;
</code>```

Why can't you define the combo box variable here as well?

ContentLicense: CC BY-SA 3.0

Body:
This is the Code. I am getting error while trying to import database items into the combo box. I am not able to take the name of the combob ox in (cmbProjectDetails.additems(name);).

Please see below code.

import java.awt.Color;

public class ProjectDetails_3_1 {

public JFrame frame;

private Connection connection=null;
private Statement statement;
private ResultSet resultSet=null;
private PreparedStatement pst=null;

private JSplitPane splitPaneRightMaster;

private JSplitPane splitPaneMaster;
private String sqlQuery;
private JPanel panelLeft;

public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                ProjectDetails_3_1 window = new ProjectDetails_3_1();
                window.frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

public ProjectDetails_3_1() {
    initialize();
}

    public  void getDatabaseConnection() {
        try
               {
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); //Load Driver
            Connection con = DriverManager.getConnection("jdbc:odbc:PRMS Build 8"); //Create Connection with Data Source Name : HOD_DATA
            Statement s = con.createStatement(); // Create Statement
            String query = "select PROJ_NAME from PROJECT"; // Create Query
            s.execute(query); // Execute Query
            ResultSet rs = s.getResultSet(); //return the data from Statement into ResultSet
            while(rs.next()) // Retrieve data from ResultSet
            {
                System.out.print("Project Name : "+rs.getString(1)); //1st column of Table from database
                System.out.println();//System.out.print(" , Name : "+rs.getString(2)); //2nd column of Table

            }
            s.close();
            con.close();
        }
        catch (Exception e)
                {
            System.out.println("Exception : "+e);
        }
    }

// Function to get database connection.
 /*public void getDatabaseConnection() {
            //Registering Oracle JDBC driver class
            try {
                Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
            }catch(ClassNotFoundException ex) {
                System.out.println("JDBC-ODBC driver not found: " + ex);
            }

            //Opening database connection
            try {
                connection = DriverManager.getConnection(
                     "jdbc:ucanaccess://D:/workspace/PRMS v1.0 Build 8/PRMS Build 8.mdb;memory=false",
                     "",
                     ""
                     );
                connection.setAutoCommit(false);
                statement = connection.createStatement();
            }catch(Exception ex){
                ex.printStackTrace();
            }

            return;
    }

    */
private void initialize() {

    frame = new JFrame();
    frame.getContentPane().setBackground(new Color(255, 255, 255));
          frame.setIconImage(Toolkit.getDefaultToolkit().getImage("D:\\Eclipse_Workspace\\PRMS v1.0 Build 9\\resources\\Logo_48.png"));
    frame.setResizable(false);
    frame.setTitle("PRMS[Build 9] - User Portal");
    frame.setSize(1000, 700);
    frame.setLocationRelativeTo(null);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setUndecorated(false);
    frame.getContentPane().setLayout(null);
    JPanel panelHeader = new JPanel();
    panelHeader.setBounds(0, 0, 1000, 10);
    panelHeader.setBackground(SystemColor.textHighlight);
    frame.getContentPane().add(panelHeader);
    panelHeader.setLayout(null);
    JPanel panelFooter = new JPanel();
    panelFooter.setBounds(0, 662, 1000, 10);
    panelFooter.setBackground(SystemColor.textHighlight);
    frame.getContentPane().add(panelFooter);
    panelFooter.setLayout(null);

    splitPaneMaster = new JSplitPane();
    splitPaneMaster.setResizeWeight(0.25);
    splitPaneMaster.setVerifyInputWhenFocusTarget(false);
    splitPaneMaster.setFocusable(false);
    splitPaneMaster.setDividerSize(0);
    splitPaneMaster.setBorder(null);
    splitPaneMaster.setOpaque(false);
    splitPaneMaster.setBounds(0, 7, 1000, 655);
    frame.getContentPane().add(splitPaneMaster);

    panelLeft = new JPanel();
    panelLeft.setRequestFocusEnabled(false);
    panelLeft.setBackground(SystemColor.textHighlight);
    splitPaneMaster.setLeftComponent(panelLeft);
    panelLeft.setLayout(null);

    splitPaneRightMaster = new JSplitPane();
    splitPaneRightMaster.setResizeWeight(0.084);
    splitPaneRightMaster.setVerifyInputWhenFocusTarget(false);
    splitPaneRightMaster.setFocusable(false);
    splitPaneRightMaster.setDividerSize(0);
    splitPaneRightMaster.setOrientation(JSplitPane.VERTICAL_SPLIT);
    splitPaneRightMaster.setBorder(null);
    splitPaneRightMaster.setOpaque(false);
    splitPaneMaster.setRightComponent(splitPaneRightMaster);

    JPanel panelDetails3_1 = new JPanel();
    panelDetails3_1.setBackground(Color.WHITE);
    splitPaneRightMaster.setRightComponent(panelDetails3_1);
    panelDetails3_1.setLayout(null);

    JLabel lblProjectDetails = new JLabel("Project Details");
    lblProjectDetails.setFont(new Font("Segoe UI Symbol", Font.BOLD, 18));
    lblProjectDetails.setBounds(80, 26, 178, 27);
    panelDetails3_1.add(lblProjectDetails);

    JLabel lblSelectAnyProject = new JLabel("Select any of the projects tagged to you to view the details.");
    lblSelectAnyProject.setFont(new Font("SansSerif", Font.BOLD, 12));
    lblSelectAnyProject.setBounds(80, 53, 466, 27);
    panelDetails3_1.add(lblSelectAnyProject);

    JLabel lblProjectName = new JLabel("Project Name:");
    lblProjectName.setBounds(80, 102, 83, 16);
    panelDetails3_1.add(lblProjectName);

    JComboBox cmbProjectDetails = new JComboBox<String>();
    //cmbProjectDetails.addItem("1111");
    //cmbProjectDetails.addItem("2222");
    cmbProjectDetails.setBounds(173, 97, 85, 27);
    panelDetails3_1.add(cmbProjectDetails);

}
private void fillCombo(){
    try{
        String sql= "select PROJ_NAME from PROJECT";
        pst=connection.prepareStatement(sql);
        resultSet=pst.executeQuery();

        while(resultSet.next()){
            String name= resultSet.getString("PROJ_NAME");
            cmbProjectDetails.additems(name);**//Error is here**

        }
    }
    catch(Exception e){
        System.out.println("Error releasing connection: " + e);
    }
}
// Function to release database connection and resources.
public void releaseDatabaseConnection() {
    try{
         if(resultSet != null){ resultSet.close();  }
        }catch(Exception ex){
    System.out.println("Error releasing resultSet: " + ex);
    }

    try{
    if(statement != null){  statement.close();  }
        }catch(Exception ex){
    System.out.println("Error releasing statement: " + ex);
    }

    try{
    if(connection != null){ connection.close(); }
        }catch(Exception ex){
    System.out.println("Error releasing connection: " + ex);
    }

    return;
}

}

Body:
I am not able to take the name of the combobox

Define the combo box variable as an instance variable, not a local variable.

An instance variable can be accessed by any method of the class. A local variable can only be accessed in the method where it is defined.

For example, you define these as instance variables:

private JSplitPane splitPaneRightMaster;

private JSplitPane splitPaneMaster;
private String sqlQuery;
private JPanel panelLeft;

Why can't you define the combo box variable here as well?


问:
Store data obtained using foreach loop from view into the database using CodeIgniter
I am trying to store the values obtained from the form into the database. I am stuck where I do not know how to obtain the values individually from foreach($questions as $row) and store them into the database.

My database table has the following columns:

```<code>variantid | stepid | questionid | newquestion | radiovalues | description
</code>```

When I click on save, I am trying to save all the details obtained from the view into the database. every value obtained with each loop of foreach($questions as $row) needs to get stored in a new row. I think I should be using insert_batch, but I do not know how I can put all the data into the array.

How can I proceed with this? The following is the code that I have written. I have not written anything in model as I am stuck.

```<code> <form id="theform">
  <label for="variants">Variants:</label><br>
          <?php
          foreach($variants as $row)
          {?>
               <div class="form-group">

              <input type="radio" name="variants[]" checked="true" id="variants" value="<?php echo $row->variantid ?>"/><?php echo $row->variantname ?><br/>

         <?php }

          ?>

<div id='steplist'>
   <?php

     foreach($substeps as $row){
         ?>
               <div id='img_div'>
                 <input type="radio" name="stepid[]" checked="true" id="stepid<?php echo $row->stepid; ?>" value="<?php echo $row->stepid;     ?>"/><?php echo $row->stepname ?><br/>
</div>
    <?php
  foreach($questions as $each){
  ?><br><br>
  <input type="text" name="questions[]" id="questions<?php echo $each->questionid; ?>" value="<?php echo $each->questionname; ?>" readonly/><br/>
<input type="hidden" name="questionid[]" id="questions<?php echo $each->questionid; ?>" value="<?php echo $each->questionid; ?>"/>

<a id="addq">Add question</a>
<input type="text" class="form-control" name="newquestion[]" style="font-weight:bold;width:100%;height:5%" id="new_questions<?php echo $each->questionid; ?>" /><br>

  <div class="radio" id="answer">
  <label style="font-weight:bold"><input type="radio" name="radioquestions[<?php echo $each->questionid; ?>][optradio]" value="no" required>no</label>
  <label style="font-weight:bold"><input type="radio" name="radioquestions[<?php echo $each->questionid; ?>][optradio]" value="probably no" required>probably no </label>
  <label style="font-weight:bold"><input type="radio" name="radioquestions[<?php echo $each->questionid; ?>][optradio]" value="unknown" required>unknown</label>
  <label style="font-weight:bold"><input type="radio" name="radioquestions[<?php echo $each->questionid; ?>][optradio]" value="probably yes" required>probably yes</label>
  <label style="font-weight:bold"><input type="radio" name="radioquestions[<?php echo $each->questionid; ?>][optradio]" value="yes">yes</label>
</div>
<textarea name="question1_text[]" id="description<?php echo $each->questionid; ?>" rows="3" cols="73"></textarea><br>
<?php
}
   ?>
  <?php
  }
  ?>

</div>
</form>
      <input type='button' value='Save' class='save' id='save' />
<script>
    $(document).ready(function(){
   $("#save").click(function(e){
     e.preventDefault();
         $.ajax({
             type:"POST",
             url:"<?= base_url() ?>index.php/task/perform",
             data:$('#theform').serialize(),

               success:function(response){

            alert(response);

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

This is my controller:

```<code>public function perform(){
var_dump($_POST);
$variantid = $this->input->post('variants');
$stepid = $this->input->post('stepid');
$questionid = $this->input->post('questions');
$newquestion = $this->input->post('newquestion');
$radioquestions = $this->input->post('radioquestions');
$question1_text = $this->input->post('question1_text');

 $this->load->model('task_model');
 $result= $this->task_model->performdata();
 if($result){
 echo "Data saved successfully";
 }
}
</code>```

Update

Thank you for the quick reply. I changed the code according to the suggestion. How can I get these values into the controller and send them  into the database?

答:
The HTML inside the foreach is invalid as it is missing a closing div tag and your input does not have the correct name attribute, for multiple inputs you should use variants[] and not the same ID. Do it in this manner:

```<code><?php foreach ($variants as $row) { ?>
    <div class="form-group">
        <input type="radio" name="variants[]" checked="true" class="variants" value="<?php echo $row->variantid ?>"/><?php echo $row->variantname ?><br/>
    </div>
<?php } ?>
</code>```

Body:
I am trying to store the values obtained from the form into the database. I am stuck where I do not know how to obtain the values individually from foreach($questions as $row) and store them into the database.

My database table has the following columns:

variantid | stepid | questionid | newquestion | radiovalues | description

When I click on save, I am trying to save all the details obtained from the view into the database. every value obtained with each loop of foreach($questions as $row) needs to get stored in a new row. I think I should be using insert_batch, but I do not know how I can put all the data into the array.

How can I proceed with this? The following is the code that I have written. I have not written anything in model as I am stuck.

 <form id="theform">
  Variants:

          <?php
          foreach($variants as $row)
          {?>

              <input type="radio" name="variants[]" checked="true" id="variants" value="<?php echo $row->variantid ?>"/><?php echo $row->variantname ?>

         <?php }

          ?>

   <?php

     foreach($substeps as $row){
         ?>

                 <input type="radio" name="stepid[]" checked="true" id="stepid<?php echo $row->stepid; ?>" value="<?php echo $row->stepid;     ?>"/><?php echo $row->stepname ?>

    <?php
  foreach($questions as $each){
  ?>

  <input type="text" name="questions[]" id="questions<?php echo $each->questionid; ?>" value="<?php echo $each->questionname; ?>" readonly/>

<input type="hidden" name="questionid[]" id="questions<?php echo $each->questionid; ?>" value="<?php echo $each->questionid; ?>"/>

Add question
<input type="text" class="form-control" name="newquestion[]" style="font-weight:bold;width:100%;height:5%" id="new_questions<?php echo $each->questionid; ?>" />

  <input type="radio" name="radioquestions[<?php echo $each->questionid; ?>][optradio]" value="no" required>no
  <input type="radio" name="radioquestions[<?php echo $each->questionid; ?>][optradio]" value="probably no" required>probably no
  <input type="radio" name="radioquestions[<?php echo $each->questionid; ?>][optradio]" value="unknown" required>unknown
  <input type="radio" name="radioquestions[<?php echo $each->questionid; ?>][optradio]" value="probably yes" required>probably yes
  <input type="radio" name="radioquestions[<?php echo $each->questionid; ?>][optradio]" value="yes">yes

<textarea name="question1_text[]" id="description<?php echo $each->questionid; ?>" rows="3" cols="73"></textarea>

<?php
}
   ?>
  <?php
  }
  ?>

</form>
      <input type='button' value='Save' class='save' id='save' />

Body:
The HTML inside the foreach is invalid as it is missing a closing div tag and your input does not have the correct name attribute, for multiple inputs you should use variants[] and not the same ID. Do it in this manner:

<?php foreach ($variants as $row) { ?>
    <div class="form-group">
        <input type="radio" name="variants[]" checked="true" class="variants" value="<?php echo $row->variantid ?>"/><?php echo $row->variantname ?><br/>
    </div>
<?php } ?>


问:
how to generate this type of data?
I need to generate a object like this:

```<code>ndarray: [[1  2    3]]
</code>```

so I tried the following:

```<code>test = [[1, 2, 3]]
</code>```

but this is not the same. So I tried:

```<code>test = [[1 2 3]]
</code>```

but this is not valid.

How to generate it?

答:
As you did is its to create a list, but not a numpy array. Besides the @unutbu suggestion, also with numpy you can do it as follows:</p>

```<code>In[1]: test = np.arange(1,4,1)
In[2]: test
Out[2]: array([1, 2, 3])
</code>```

Title: how to generate this type of data?

Body:
I need to generate a object like this:

ndarray: [[1  2    3]]

so I tried the following:

test = [[1, 2, 3]]

but this is not the same. So I tried:

test = [[1 2 3]]

but this is not valid.

How to generate it?

Body:
As you did is its to create a list, but not a numpy array. Besides the @unutbu suggestion, also with numpy you can do it as follows:

In[1]: test = np.arange(1,4,1)
In[2]: test
Out[2]: array([1, 2, 3])


问:
Angular2 http request in an interval
I m trying to make a request every 3 seconds and print out the response but until now no luck :( . I m pretty new to the Observables, so what am I doing wrong ?

```<code>checkConnection() {

const URL = "https://www.google.at/";

Observable.interval(3000)
  .flatMap(() => this.http.get(URL).map(res => res.json()).catch((error:any) => Observable.throw(error.json().error || 'Server error'))
  .subscribe(data => {
     console.log(data)
  })

  )
    }
</code>```

答:
You need to subscribe to the Observable that comes from the flatMaps response like this:

```<code>Observable.interval(3000)
      .flatMap(() => this.http.get(URL)
      .map( res => res.json() )
      .catch( (error:any) => Observable.throw(error.json().error || 'Server error') ) )
      .subscribe(data => {
         console.log(data)
      })
</code>```

And https://www.google.at/ needs to enable cross-domain requests in order for you to get the data.

Example plunker that you can work on: http://plnkr.co/edit/Nz0LZJDSPcUZlYOHU3p7?p=preview

Title: Angular2 http request in an interval

Body:
I m trying to make a request every 3 seconds and print out the response but until now no luck :( . I m pretty new to the Observables, so what am I doing wrong ?

checkConnection() {

const URL = "https://www.google.at/";

Observable.interval(3000)
  .flatMap(() => this.http.get(URL).map(res => res.json()).catch((error:any) => Observable.throw(error.json().error || 'Server error'))
  .subscribe(data => {
     console.log(data)
  })

  )
    }

Body:
You need to subscribe to the Observable that comes from the flatMaps response like this:

Observable.interval(3000)
      .flatMap(() => this.http.get(URL)
      .map( res => res.json() )
      .catch( (error:any) => Observable.throw(error.json().error || 'Server error') ) )
      .subscribe(data => {
         console.log(data)
      })

And https://www.google.at/ needs to enable cross-domain requests in order for you to get the data.

Example plunker that you can work on: http://plnkr.co/edit/Nz0LZJDSPcUZlYOHU3p7?p=preview


问:
Computing distances using distCosine
I want to compute distances between couples of (lat,lon) coordinates, like in this example:
Calculating distances from latitude and longitude coordinates in R

but using dplyr in order to speed up the process, and using the distCosine function from geosphere.

This function accepts only vectors of size 2, and the only way I found that works is:

```<code>p <- data.frame(lat=runif(6,-90,90), lon=runif(6,-180,180),lat2=runif(6,-90,90), lon2=runif(6,-180,180) )
p$dist <- sapply(1:nrow(p), function(x) distCosine(c(p$lon[x], p$lat[x]), c(p$lon2[x], p$lat2[x]) ) )
</code>```

With dplyr I have tried:

```<code>p %>% rowwise() %>% mutate(dist2prev = distCosine(c(lon, lat), c(lon2, lat2)))
p %>% group_by(1:n()) %>% mutate(dist2prev = distCosine(c(lon, lat), c(lon2, lat2)))
</code>```

but the error is always the same:

```<code>Wrong length for a vector, should be 2
</code>```

Any idea why dplyr does not succeed there?

答:
Not sure why your code isn't working. Using do.call seems to be orders of magnitude faster than your vanilla implementation or dplyr:

```<code>library(geosphere)
library(dplyr)

N <- 100
p <- data.frame(lat=runif(N,-90,90), lon=runif(N,-180,180),
                lat2=runif(N,-90,90), lon2=runif(N,-180,180) )

f1 <- function() {
  sapply(1:nrow(p), function(x) distCosine(c(p$lon[x], p$lat[x]),
                                           c(p$lon2[x], p$lat2[x]) ) )
}

pts <- list(p1=p[2:1], p2=p[4:3])
f2 <- function() {
  do.call(distCosine, pts)
}

f3 <- function() {
  p %>% rowwise() %>% mutate(dist2prev = distCosine(c(lon, lat), c(lon2, lat2)))
}
</code>```

The help for geosphere::distCosine (you don't mention which library you're using) implies that the function is vectorized. This will be much faster than doing row-wise operations.

```<code>> microbenchmark::microbenchmark(vanilla=f1(), do.call=f2(), dplyr=f3())
Unit: microseconds
    expr      min        lq      mean    median         uq       max neval
 vanilla 21342.53 32076.194 39113.213 40463.300 45340.3695 80332.304   100
 do.call   371.34   444.391   617.022   562.337   772.5475  1228.161   100
   dplyr 19800.10 27304.895 35627.085 34618.692 42531.5415 66111.814   100
</code>```

Title: Computing distances using distCosine

Body:
I want to compute distances between couples of (lat,lon) coordinates, like in this example:
Calculating distances from latitude and longitude coordinates in R

but using dplyr in order to speed up the process, and using the distCosine function from geosphere.

This function accepts only vectors of size 2, and the only way I found that works is:

p <- data.frame(lat=runif(6,-90,90), lon=runif(6,-180,180),lat2=runif(6,-90,90), lon2=runif(6,-180,180) )
p$dist <- sapply(1:nrow(p), function(x) distCosine(c(p$lon[x], p$lat[x]), c(p$lon2[x], p$lat2[x]) ) )

With dplyr I have tried:

p %>% rowwise() %>% mutate(dist2prev = distCosine(c(lon, lat), c(lon2, lat2)))
p %>% group_by(1:n()) %>% mutate(dist2prev = distCosine(c(lon, lat), c(lon2, lat2)))

but the error is always the same:

Wrong length for a vector, should be 2

Any idea why dplyr does not succeed there?

Body:
Not sure why your code isn't working. Using do.call seems to be orders of magnitude faster than your vanilla implementation or dplyr:

library(geosphere)
library(dplyr)

N <- 100
p <- data.frame(lat=runif(N,-90,90), lon=runif(N,-180,180),
                lat2=runif(N,-90,90), lon2=runif(N,-180,180) )

f1 <- function() {
  sapply(1:nrow(p), function(x) distCosine(c(p$lon[x], p$lat[x]),
                                           c(p$lon2[x], p$lat2[x]) ) )
}

pts <- list(p1=p[2:1], p2=p[4:3])
f2 <- function() {
  do.call(distCosine, pts)
}

f3 <- function() {
  p %>% rowwise() %>% mutate(dist2prev = distCosine(c(lon, lat), c(lon2, lat2)))
}

The help for geosphere::distCosine (you don't mention which library you're using) implies that the function is vectorized. This will be much faster than doing row-wise operations.

> microbenchmark::microbenchmark(vanilla=f1(), do.call=f2(), dplyr=f3())
Unit: microseconds
    expr      min        lq      mean    median         uq       max neval
 vanilla 21342.53 32076.194 39113.213 40463.300 45340.3695 80332.304   100
 do.call   371.34   444.391   617.022   562.337   772.5475  1228.161   100
   dplyr 19800.10 27304.895 35627.085 34618.692 42531.5415 66111.814   100


问:
How to pass a ResourceDictionary to ViewModelLocator
Hi i created a property in ViewModelLocator to allow a ResourceDictionary to pass to the ViewModelLocator. In my app.xaml i have this defined:

```<code><vm:ViewModelLocator x:Key="Locator">
  <vm:ViewModelLocator.DefaultUIResourceDictionary>
    <ResourceDictionary Source="Resources/DefaultUIResource.xaml"/>
  </vm:ViewModelLocator.DefaultUIResourceDictionary>
</vm:ViewModelLocator>
</code>```

It runs fine, however, when i try to reference the dictionary, it has 0 items in it, which i'm sure DefaultUIResource.xaml has an item defined. Not sure what is wrong.

Another question is, the resources defined in the App.Resources property is only created when referenced? Can anyone tell me the life cycle of the App class? when is the items in the Resources property created? After the constructor?

答:
Rather weirdly, the problem seems to be that your property gets passed the resource dictionary before it has been initialized - if you look at the dictionary's Source property in your DefaultUIResourceDictionary setter, it'll be null. But try this:

```<code>private ResourceDictionary _defaultUIResourceDictionary;

public ResourceDictionary DefaultUIResourceDictionary
{
    get { return _defaultUIResourceDictionary; }
    set
    {
        _defaultUIResourceDictionary = value;
        Debug.WriteLine(value.Count);
        Dispatcher.CurrentDispatcher.BeginInvoke((Action) delegate
        {
            Debug.WriteLine(value.Count);
            foreach (var item in value)
            {
                Debug.WriteLine(item);
            }
        },
        DispatcherPriority.Background,
        null);
    }
}
</code>```

You'll find that the first Debug.WriteLine shows a count of 0 - the same behaviour you're seeing. But in the dispatcher callback, the count should now be correct, and the dictionary's contents available. (That's what I see when I try it.)

This may or may not be related to your other question, about when the resources actually get created. Resource dictionaries typically do deferred resource loading in WPF. I say "typically" because there are some situations in which they don't. (E.g., if you load a resource dictionary from an uncompiled Xaml stream.) But certainly, in the usual scenario - dictionaries in the Resources properties of App, or in UI elements in compiled Xaml - resources don't get loaded until you ask for them.

This is not really anything to do with the App class lifecycle. It's not the application that does the deferred loading, it's the resource dictionary itself. And it's done on a per-resource basis - individual resources get loaded the first time you look them up. This means that resources can in theory be loaded at any point in the application lifecycle. Indeed, it's common for some resources never to be loaded.

This speeds up startup for WPF apps - if all your resources got loaded at the start, it'd take much longer than necessary. Imagine you have resources only used during error conditions, for example - you don't want to make the user wait for those to load before they can start using your app.

So resource dictionaries sometimes behave a little strangely in compiled Xaml. And the behaviour you've uncovered here is definitely strange. I'm not sure it's actually meant to be like this - it may just be some unintended consequence of the fact that resource dictionaries are handled as a special case in order to enable deferred loading.

ContentLicense: CC BY-SA 2.5

Body:
Hi i created a property in ViewModelLocator to allow a ResourceDictionary to pass to the ViewModelLocator. In my app.xaml i have this defined:

<vm:ViewModelLocator x:Key="Locator">
  <vm:ViewModelLocator.DefaultUIResourceDictionary>
    <ResourceDictionary Source="Resources/DefaultUIResource.xaml"/>
  </vm:ViewModelLocator.DefaultUIResourceDictionary>
</vm:ViewModelLocator>

It runs fine, however, when i try to reference the dictionary, it has 0 items in it, which i'm sure DefaultUIResource.xaml has an item defined. Not sure what is wrong.

Another question is, the resources defined in the App.Resources property is only created when referenced? Can anyone tell me the life cycle of the App class? when is the items in the Resources property created? After the constructor?

Body:
Rather weirdly, the problem seems to be that your property gets passed the resource dictionary before it has been initialized - if you look at the dictionary's Source property in your DefaultUIResourceDictionary setter, it'll be null. But try this:

private ResourceDictionary _defaultUIResourceDictionary;

public ResourceDictionary DefaultUIResourceDictionary
{
    get { return _defaultUIResourceDictionary; }
    set
    {
        _defaultUIResourceDictionary = value;
        Debug.WriteLine(value.Count);
        Dispatcher.CurrentDispatcher.BeginInvoke((Action) delegate
        {
            Debug.WriteLine(value.Count);
            foreach (var item in value)
            {
                Debug.WriteLine(item);
            }
        },
        DispatcherPriority.Background,
        null);
    }
}

You'll find that the first Debug.WriteLine shows a count of 0 - the same behaviour you're seeing. But in the dispatcher callback, the count should now be correct, and the dictionary's contents available. (That's what I see when I try it.)

This may or may not be related to your other question, about when the resources actually get created. Resource dictionaries typically do deferred resource loading in WPF. I say "typically" because there are some situations in which they don't. (E.g., if you load a resource dictionary from an uncompiled Xaml stream.) But certainly, in the usual scenario - dictionaries in the Resources properties of App, or in UI elements in compiled Xaml - resources don't get loaded until you ask for them.

This is not really anything to do with the App class lifecycle. It's not the application that does the deferred loading, it's the resource dictionary itself. And it's done on a per-resource basis - individual resources get loaded the first time you look them up. This means that resources can in theory be loaded at any point in the application lifecycle. Indeed, it's common for some resources never to be loaded.

This speeds up startup for WPF apps - if all your resources got loaded at the start, it'd take much longer than necessary. Imagine you have resources only used during error conditions, for example - you don't want to make the user wait for those to load before they can start using your app.

So resource dictionaries sometimes behave a little strangely in compiled Xaml. And the behaviour you've uncovered here is definitely strange. I'm not sure it's actually meant to be like this - it may just be some unintended consequence of the fact that resource dictionaries are handled as a special case in order to enable deferred loading.


问:
Python matplotlib error: "maximum recursion depth exceeded"
I am using Python and the matplotlib library.

I run through a very long code creating multiple figures along the way.

I do something like this, many many times:

```<code>plt.figure()
plt.plot(x, y)
plt.grid('on')
plt.close()
</code>```

Then, at some point, I get the error:

More than 20 figures have been opened. Figures created through the pyplot interface (matplotlib.pyplot.figure) are retained until explicitly closed and may consume too much memory.

The error is clear to me, but: I do call "plt.close()".

Now that I am writing this I am realizing that maybe plt.close() has to take a specific qualifier for what figure to close? Like plt.close(1) etc. I guess I can use plt.close('all'), but what if I just want to close the most recent figure?

答:
You should operate on matplotlib objects directly. It's so much less ambiguous:</p>

```<code>fig, ax = plt.subplots()
ax.plot(x, y)
...
plt.close(fig)
</code>```

Body:
I am using Python and the matplotlib library.

I run through a very long code creating multiple figures along the way.

I do something like this, many many times:

plt.figure()
plt.plot(x, y)
plt.grid('on')
plt.close()

Then, at some point, I get the error:

More than 20 figures have been opened. Figures created through the pyplot interface (matplotlib.pyplot.figure) are retained until explicitly closed and may consume too much memory.

The error is clear to me, but: I do call "plt.close()".

Now that I am writing this I am realizing that maybe plt.close() has to take a specific qualifier for what figure to close? Like plt.close(1) etc. I guess I can use plt.close('all'), but what if I just want to close the most recent figure?

Body:
You should operate on matplotlib objects directly. It's so much less ambiguous:

fig, ax = plt.subplots()
ax.plot(x, y)
...
plt.close(fig)


问:
how do i make fillstyle and stroke style work?
```<code>//clear screen
function CLS() {
    draw.fillStyle = "#ffffff";
    draw.strokeStyle = "#ffffff"; //to white
    draw.rect(0, 0, 300, 150); //position
    draw.stroke();
    draw.fill(); //draw it
}
//screen update
function UpdateScreen() {
    //draw ground
    draw.fillStyle = "#000000";
    draw.strokeStyle = "#000000"; //to black
    draw.rect(0, 100, 300, 25); //position
    draw.stroke();
    draw.fill(); //draw it
    //draw guy
    draw.fillStyle = "#c7c7c7";
    draw.strokeStyle = "#c7c7c7"; //to grey
    draw.beginPath();
    draw.arc(guyX, guyY, 15, 0, 2 * Math.PI); //position
    draw.fill();
    draw.stroke(); //draw it
}
CLS();
UpdateScreen();
</code>```

the color set for the white rectangle is using the black color from the next declaration, how do i fix this?

答:
Use beginPath() method, before drawing all the shapes.</p>

```<code>//clear screen
function CLS() {
    draw.beginPath();
    draw.fillStyle = "#ffffff";
    draw.strokeStyle = "#ffffff"; //to white
    draw.rect(0, 0, 300, 150); //position
    draw.stroke();
    draw.fill(); //draw it
}
//screen update
function UpdateScreen() {
    //draw ground
    draw.beginPath();
    draw.fillStyle = "#000000";
    draw.strokeStyle = "#000000"; //to black
    draw.rect(0, 100, 300, 25); //position
    draw.stroke();
    draw.fill(); //draw it
    //draw guy
    draw.beginPath();
    draw.fillStyle = "#c7c7c7";
    draw.strokeStyle = "#c7c7c7"; //to grey
    draw.arc(guyX, guyY, 15, 0, 2 * Math.PI); //position
    draw.fill();
    draw.stroke(); //draw it
}
CLS();
UpdateScreen();
</code>```

Body:
//clear screen
function CLS() {
    draw.fillStyle = "#ffffff";
    draw.strokeStyle = "#ffffff"; //to white
    draw.rect(0, 0, 300, 150); //position
    draw.stroke();
    draw.fill(); //draw it
}
//screen update
function UpdateScreen() {
    //draw ground
    draw.fillStyle = "#000000";
    draw.strokeStyle = "#000000"; //to black
    draw.rect(0, 100, 300, 25); //position
    draw.stroke();
    draw.fill(); //draw it
    //draw guy
    draw.fillStyle = "#c7c7c7";
    draw.strokeStyle = "#c7c7c7"; //to grey
    draw.beginPath();
    draw.arc(guyX, guyY, 15, 0, 2 * Math.PI); //position
    draw.fill();
    draw.stroke(); //draw it
}
CLS();
UpdateScreen();

the color set for the white rectangle is using the black color from the next declaration, how do i fix this?

Body:
Use beginPath() method, before drawing all the shapes.

//clear screen
function CLS() {
    draw.beginPath();
    draw.fillStyle = "#ffffff";
    draw.strokeStyle = "#ffffff"; //to white
    draw.rect(0, 0, 300, 150); //position
    draw.stroke();
    draw.fill(); //draw it
}
//screen update
function UpdateScreen() {
    //draw ground
    draw.beginPath();
    draw.fillStyle = "#000000";
    draw.strokeStyle = "#000000"; //to black
    draw.rect(0, 100, 300, 25); //position
    draw.stroke();
    draw.fill(); //draw it
    //draw guy
    draw.beginPath();
    draw.fillStyle = "#c7c7c7";
    draw.strokeStyle = "#c7c7c7"; //to grey
    draw.arc(guyX, guyY, 15, 0, 2 * Math.PI); //position
    draw.fill();
    draw.stroke(); //draw it
}
CLS();
UpdateScreen();


问:
Backend list filter to toggle global scope
I have a model for job vacancies which has a global scope to only show open vacancies, but in the backend I want a checkbox to toggle this so that all vacancies can be shown. The checkbox type only seems to work with local scopes. Can anyone help?</p>

答:
You could setup a local scope on your model that removes the global scope.

Something like:

```<code>public function scopeAllVacancies($query)
{
    // This is not actually how you remove a global scope,
    // see https://softonsofa.com/laravel-5-eloquent-global-scope-how-to/
    // for more information.
    $query->removeScope(MyGlobalScope);
}
</code>```

As a side note, you won't be able to use the remove method suggested in https://softonsofa.com/laravel-5-eloquent-global-scope-how-to/ as the list widget is using the object through reference, and won't listen to the return value of this scope. So, in order to remove it currently (at least until we get some form of $query->resetQuery() or $query->removeScope($scope) implemented), you'll have to perform the removal of the scope manually on the query object.

Here's an example of interfacing directly with the query object in order to manually remove a scope:

```<code>/**
 * Removes the provided orderby column rule from the QueryBuilder orders array to reset the orderBy for that column
 *
 * @param Builder $query
 * @param string $orderByColumn
 * @return Builder $query
 */
public function scopeRemoveOrder($query, $orderByColumn)
{
    // Orders property can have mixed up integer index, flatten the array to negate any weird keys in this array
    $orders = $query->getQuery()->orders;
    if (is_array($orders)) {
        $orders = array_values($query->getQuery()->orders);
        $i = 0;
        foreach ($orders as $order) {
            if ($order['column'] === $orderByColumn) {
                unset($orders[$i]);
            }
            $i++;
        }
        $query->getQuery()->orders = $orders;
    }
    return $query;
}
</code>```

Body:
You could setup a local scope on your model that removes the global scope.

Something like:

public function scopeAllVacancies($query)
{
    // This is not actually how you remove a global scope,
    // see https://softonsofa.com/laravel-5-eloquent-global-scope-how-to/
    // for more information.
    $query->removeScope(MyGlobalScope);
}

As a side note, you won't be able to use the remove method suggested in https://softonsofa.com/laravel-5-eloquent-global-scope-how-to/ as the list widget is using the object through reference, and won't listen to the return value of this scope. So, in order to remove it currently (at least until we get some form of $query->resetQuery() or $query->removeScope($scope) implemented), you'll have to perform the removal of the scope manually on the query object.

Here's an example of interfacing directly with the query object in order to manually remove a scope:

/**
 * Removes the provided orderby column rule from the QueryBuilder orders array to reset the orderBy for that column
 *
 * @param Builder $query
 * @param string $orderByColumn
 * @return Builder $query
 */
public function scopeRemoveOrder($query, $orderByColumn)
{
    // Orders property can have mixed up integer index, flatten the array to negate any weird keys in this array
    $orders = $query->getQuery()->orders;
    if (is_array($orders)) {
        $orders = array_values($query->getQuery()->orders);
        $i = 0;
        foreach ($orders as $order) {
            if ($order['column'] === $orderByColumn) {
                unset($orders[$i]);
            }
            $i++;
        }
        $query->getQuery()->orders = $orders;
    }
    return $query;
}