问:
Could not determine type for: javax.persistence.EntityManagerFactory, for columns: [org.hibernate.mapping.Column(emf)]
I work in Eclipse with Hibernate, JPA and postgres and I get following report

```<code>13:54:37,754 ERROR [org.jboss.msc.service.fail] (ServerService Thread Pool -- 85) MSC000001: Failed to start service jboss.persistenceunit."NewPestsList-0.0.1-SNAPSHOT.war#tvTutorialPU": org.jboss.msc.service.StartException in service jboss.persistenceunit."NewPestsList-0.0.1-SNAPSHOT.war#tvTutorialPU": javax.persistence.PersistenceException: [PersistenceUnit: tvTutorialPU] Unable to build Hibernate SessionFactory
at org.jboss.as.jpa@17.0.0.Final//org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1$1.run(PersistenceUnitServiceImpl.java:198)
at org.jboss.as.jpa@17.0.0.Final//org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1$1.run(PersistenceUnitServiceImpl.java:128)
at org.wildfly.security.elytron-private@1.9.1.Final//org.wildfly.security.manager.WildFlySecurityManager.doChecked(WildFlySecurityManager.java:649)
at org.jboss.as.jpa@17.0.0.Final//org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1.run(PersistenceUnitServiceImpl.java:212)
at org.jboss.threads@2.3.3.Final//org.jboss.threads.ContextClassLoaderSavingRunnable.run(ContextClassLoaderSavingRunnable.java:35)
at org.jboss.threads@2.3.3.Final//org.jboss.threads.EnhancedQueueExecutor.safeRun(EnhancedQueueExecutor.java:1982)
at org.jboss.threads@2.3.3.Final//org.jboss.threads.EnhancedQueueExecutor$ThreadBody.doRunTask(EnhancedQueueExecutor.java:1486)
at org.jboss.threads@2.3.3.Final//org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1377)
at java.base/java.lang.Thread.run(Thread.java:830)
at org.jboss.threads@2.3.3.Final//org.jboss.threads.JBossThread.run(JBossThread.java:485)
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: tvTutorialPU] Unable to build Hibernate SessionFactory
at org.hibernate@5.3.10.Final//org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.persistenceException(EntityManagerFactoryBuilderImpl.java:1016)
at org.hibernate@5.3.10.Final//org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:942)
at org.hibernate.jipijapa-hibernate5-3@17.0.0.Final//org.jboss.as.jpa.hibernate5.TwoPhaseBootstrapImpl.__build(TwoPhaseBootstrapImpl.java:44)
at org.hibernate.jipijapa-hibernate5-3@17.0.0.Final//org.jboss.as.jpa.hibernate5.TwoPhaseBootstrapImpl.build(TwoPhaseBootstrapImpl.java:46002)
at org.jboss.as.jpa@17.0.0.Final//org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1$1.run(PersistenceUnitServiceImpl.java:170)
... 9 more
Caused by: org.hibernate.MappingException: Could not determine type for: javax.persistence.EntityManager, at table: smPests, for columns: [org.hibernate.mapping.Column(em)]
at org.hibernate@5.3.10.Final//org.hibernate.mapping.SimpleValue.getType(SimpleValue.java:486)
at org.hibernate@5.3.10.Final//org.hibernate.mapping.SimpleValue.isValid(SimpleValue.java:453)
at org.hibernate@5.3.10.Final//org.hibernate.mapping.Property.isValid(Property.java:226)
at org.hibernate@5.3.10.Final//org.hibernate.mapping.PersistentClass.validate(PersistentClass.java:624)
at org.hibernate@5.3.10.Final//org.hibernate.mapping.SingleTableSubclass.validate(SingleTableSubclass.java:54)
at org.hibernate@5.3.10.Final//org.hibernate.boot.internal.MetadataImpl.validate(MetadataImpl.java:347)
at org.hibernate@5.3.10.Final//org.hibernate.boot.internal.SessionFactoryBuilderImpl.__build(SessionFactoryBuilderImpl.java:466)
at org.hibernate@5.3.10.Final//org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:40008)
at org.hibernate@5.3.10.Final//org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:939)
... 12 more
13:54:37,755 ERROR [org.jboss.as.controller.management-operation] (DeploymentScanner-threads - 2) WFLYCTL0013: Operation ("full-replace-deployment") failed - address: ([]) - failure description: {"WFLYCTL0080: Failed services" => {"jboss.persistenceunit.\"NewPestsList-0.0.1-SNAPSHOT.war#tvTutorialPU\"" => "javax.persistence.PersistenceException: [PersistenceUnit: tvTutorialPU] Unable to build Hibernate SessionFactory
    Caused by: javax.persistence.PersistenceException: [PersistenceUnit: tvTutorialPU] Unable to build Hibernate SessionFactory
    Caused by: org.hibernate.MappingException: Could not determine type for: javax.persistence.EntityManager, at table: smPests, for columns: [org.hibernate.mapping.Column(em)]"}}
13:54:37,779 INFO  [org.jboss.as.server] (DeploymentScanner-threads - 2) WFLYSRV0016: Replaced deployment "NewPestsList-0.0.1-SNAPSHOT.war" with deployment "NewPestsList-0.0.1-SNAPSHOT.war"
13:54:37,779 INFO  [org.jboss.as.controller] (DeploymentScanner-threads - 2) WFLYCTL0183: Service status report
WFLYCTL0186:   Services which failed to start:      service jboss.persistenceunit."NewPestsList-0.0.1-SNAPSHOT.war#tvTutorialPU": javax.persistence.PersistenceException: [PersistenceUnit: tvTutorialPU] Unable to build Hibernate SessionFactory
</code>```

My code is:

@Entity(name = "Smpests")
@Table(name = "smPests")
public class SmPests {

   @Id
   @GeneratedValue
   @Column(name = "id_pest")
   private int idPest;

   @Column(name = "latin")
   private String latinName;

   @OneToMany(targetEntity=SmPestsNames.class, mappedBy = "smpests", cascade = CascadeType.ALL, orphanRemoval = true)
   private List<SmPestsNames> smPestsNames;

   public int getIdPest() {
      return idPest;
   }
   public void setIdPest(int idPest) {
      this.idPest = idPest;
   }

   public String getLatinName() {
     return latinName;
   }
   public void setLatinName(String latinName) {
       this.latinName = latinName;
   }

   public List<SmPestsNames> getSmPestsNames() {
      return smPestsNames;
   }
   public void setSmPestsNames(List<SmPestsNames> smPestsNames) {
        this.smPestsNames = smPestsNames;
   }

@Entity
@Table(name = "smPestsNames")
public class SmPestsNames {

   @Column
   private Long idPestName;

   @Id
   @GeneratedValue
   @Column(name = "id")
   private Long idPest;

   @Column
   private int idLanguage;

   @Column
   private String name;

   @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
   private SmPests smpests;
}

@Entity
@Model
public class SmPestsEdit extends SmPests {

  EntityManagerFactory emf = Persistence.createEntityManagerFactory("tvTutorialPU");
  EntityManager em=emf.createEntityManager();

  public void addButton() {
     SmPests newPest = new SmPests();
     newPest.setCode(getCode());
     newPest.setLatinName(getLatinName());
     SmPestsEdit repository = new SmPestsEdit();
     repository.createPest(newPest);
  }

  @Override
  public SmPests createPest(SmPests smPest)    {
    EntityManager em= emf.createEntityManager();
    em.getTransaction().begin();
    em.persist(smPest);
    em.getTransaction().commit();
    return smPest;
  }
  public SmPests readPest(int idPest)    {
    EntityManager em= emf.createEntityManager();
    em.getTransaction().begin();
    SmPests smPest = em.find(SmPests.class, getIdPest());
    em.getTransaction().commit();
    return smPest;
  }
```

<p>my persistence.xml is:</p>

<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
             http://xmlns.jcp.org/xml/ns/persistence/persistence_2_2.xsd"
    version="2.2">
    <persistence-unit name="tvTutorialPU"
        transaction-type="JTA">
        <jta-data-source>java:jboss/datasources/tvTutorial</jta-data-source>
        <class>si.david.SmPests</class>
        <class>si.david.SmPestsNames</class>
    </persistence-unit>

</persistence>
</code>```

I am fairly new at this so if I need to post anything else, please tell and i will add

Update:
Now I put EntityManagerFactory emf and EntityManager em in:

```<code>    public SmPests createPest(SmPests smPest)   {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("tvTutorialPU");
        EntityManager em= emf.createEntityManager();
        em.getTransaction().begin();
        em.persist(smPest);
        em.getTransaction().commit();
        return smPest;
    }
</code>```

Now I get error:

Target Unreachable, identifier 'smPestsEdit' resolved to null

答:
Your problem is here:

@Entity
@Model
public class SmPestsEdit extends SmPests {
  EntityManagerFactory emf = Persistence.createEntityManagerFactory("tvTutorialPU");
  EntityManager em=emf.createEntityManager();
  // ...
}
```

Hibernate treats EntityManagerFactory emf and EntityManager em as fields which belong to the entity SmPestsEdit. It is a bad practice to put the code related to the work with EntityManager into the entity declaration. This code should be allocated in repositories.

Body:
I work in Eclipse with Hibernate, JPA and postgres and I get following report

13:54:37,754 ERROR [org.jboss.msc.service.fail] (ServerService Thread Pool -- 85) MSC000001: Failed to start service jboss.persistenceunit."NewPestsList-0.0.1-SNAPSHOT.war#tvTutorialPU": org.jboss.msc.service.StartException in service jboss.persistenceunit."NewPestsList-0.0.1-SNAPSHOT.war#tvTutorialPU": javax.persistence.PersistenceException: [PersistenceUnit: tvTutorialPU] Unable to build Hibernate SessionFactory
at org.jboss.as.jpa@17.0.0.Final//org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1$1.run(PersistenceUnitServiceImpl.java:198)
at org.jboss.as.jpa@17.0.0.Final//org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1$1.run(PersistenceUnitServiceImpl.java:128)
at org.wildfly.security.elytron-private@1.9.1.Final//org.wildfly.security.manager.WildFlySecurityManager.doChecked(WildFlySecurityManager.java:649)
at org.jboss.as.jpa@17.0.0.Final//org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1.run(PersistenceUnitServiceImpl.java:212)
at org.jboss.threads@2.3.3.Final//org.jboss.threads.ContextClassLoaderSavingRunnable.run(ContextClassLoaderSavingRunnable.java:35)
at org.jboss.threads@2.3.3.Final//org.jboss.threads.EnhancedQueueExecutor.safeRun(EnhancedQueueExecutor.java:1982)
at org.jboss.threads@2.3.3.Final//org.jboss.threads.EnhancedQueueExecutor$ThreadBody.doRunTask(EnhancedQueueExecutor.java:1486)
at org.jboss.threads@2.3.3.Final//org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1377)
at java.base/java.lang.Thread.run(Thread.java:830)
at org.jboss.threads@2.3.3.Final//org.jboss.threads.JBossThread.run(JBossThread.java:485)
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: tvTutorialPU] Unable to build Hibernate SessionFactory
at org.hibernate@5.3.10.Final//org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.persistenceException(EntityManagerFactoryBuilderImpl.java:1016)
at org.hibernate@5.3.10.Final//org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:942)
at org.hibernate.jipijapa-hibernate5-3@17.0.0.Final//org.jboss.as.jpa.hibernate5.TwoPhaseBootstrapImpl.__build(TwoPhaseBootstrapImpl.java:44)
at org.hibernate.jipijapa-hibernate5-3@17.0.0.Final//org.jboss.as.jpa.hibernate5.TwoPhaseBootstrapImpl.build(TwoPhaseBootstrapImpl.java:46002)
at org.jboss.as.jpa@17.0.0.Final//org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1$1.run(PersistenceUnitServiceImpl.java:170)
... 9 more
Caused by: org.hibernate.MappingException: Could not determine type for: javax.persistence.EntityManager, at table: smPests, for columns: [org.hibernate.mapping.Column(em)]
at org.hibernate@5.3.10.Final//org.hibernate.mapping.SimpleValue.getType(SimpleValue.java:486)
at org.hibernate@5.3.10.Final//org.hibernate.mapping.SimpleValue.isValid(SimpleValue.java:453)
at org.hibernate@5.3.10.Final//org.hibernate.mapping.Property.isValid(Property.java:226)
at org.hibernate@5.3.10.Final//org.hibernate.mapping.PersistentClass.validate(PersistentClass.java:624)
at org.hibernate@5.3.10.Final//org.hibernate.mapping.SingleTableSubclass.validate(SingleTableSubclass.java:54)
at org.hibernate@5.3.10.Final//org.hibernate.boot.internal.MetadataImpl.validate(MetadataImpl.java:347)
at org.hibernate@5.3.10.Final//org.hibernate.boot.internal.SessionFactoryBuilderImpl.__build(SessionFactoryBuilderImpl.java:466)
at org.hibernate@5.3.10.Final//org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:40008)
at org.hibernate@5.3.10.Final//org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:939)
... 12 more
13:54:37,755 ERROR [org.jboss.as.controller.management-operation] (DeploymentScanner-threads - 2) WFLYCTL0013: Operation ("full-replace-deployment") failed - address: ([]) - failure description: {"WFLYCTL0080: Failed services" => {"jboss.persistenceunit.\"NewPestsList-0.0.1-SNAPSHOT.war#tvTutorialPU\"" => "javax.persistence.PersistenceException: [PersistenceUnit: tvTutorialPU] Unable to build Hibernate SessionFactory
    Caused by: javax.persistence.PersistenceException: [PersistenceUnit: tvTutorialPU] Unable to build Hibernate SessionFactory
    Caused by: org.hibernate.MappingException: Could not determine type for: javax.persistence.EntityManager, at table: smPests, for columns: [org.hibernate.mapping.Column(em)]"}}
13:54:37,779 INFO  [org.jboss.as.server] (DeploymentScanner-threads - 2) WFLYSRV0016: Replaced deployment "NewPestsList-0.0.1-SNAPSHOT.war" with deployment "NewPestsList-0.0.1-SNAPSHOT.war"
13:54:37,779 INFO  [org.jboss.as.controller] (DeploymentScanner-threads - 2) WFLYCTL0183: Service status report
WFLYCTL0186:   Services which failed to start:      service jboss.persistenceunit."NewPestsList-0.0.1-SNAPSHOT.war#tvTutorialPU": javax.persistence.PersistenceException: [PersistenceUnit: tvTutorialPU] Unable to build Hibernate SessionFactory

My code is:

@Entity(name = "Smpests")
@Table(name = "smPests")
public class SmPests {

   @Id
   @GeneratedValue
   @Column(name = "id_pest")
   private int idPest;

   @Column(name = "latin")
   private String latinName;

   @OneToMany(targetEntity=SmPestsNames.class, mappedBy = "smpests", cascade = CascadeType.ALL, orphanRemoval = true)
   private List<SmPestsNames> smPestsNames;

   public int getIdPest() {
      return idPest;
   }
   public void setIdPest(int idPest) {
      this.idPest = idPest;
   }

   public String getLatinName() {
     return latinName;
   }
   public void setLatinName(String latinName) {
       this.latinName = latinName;
   }

   public List<SmPestsNames> getSmPestsNames() {
      return smPestsNames;
   }
   public void setSmPestsNames(List<SmPestsNames> smPestsNames) {
        this.smPestsNames = smPestsNames;
   }

@Entity
@Table(name = "smPestsNames")
public class SmPestsNames {

   @Column
   private Long idPestName;

   @Id
   @GeneratedValue
   @Column(name = "id")
   private Long idPest;

   @Column
   private int idLanguage;

   @Column
   private String name;

   @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
   private SmPests smpests;
}

@Entity
@Model
public class SmPestsEdit extends SmPests {

  EntityManagerFactory emf = Persistence.createEntityManagerFactory("tvTutorialPU");
  EntityManager em=emf.createEntityManager();

  public void addButton() {
     SmPests newPest = new SmPests();
     newPest.setCode(getCode());
     newPest.setLatinName(getLatinName());
     SmPestsEdit repository = new SmPestsEdit();
     repository.createPest(newPest);
  }

  @Override
  public SmPests createPest(SmPests smPest)    {
    EntityManager em= emf.createEntityManager();
    em.getTransaction().begin();
    em.persist(smPest);
    em.getTransaction().commit();
    return smPest;
  }
  public SmPests readPest(int idPest)    {
    EntityManager em= emf.createEntityManager();
    em.getTransaction().begin();
    SmPests smPest = em.find(SmPests.class, getIdPest());
    em.getTransaction().commit();
    return smPest;
  }

my persistence.xml is:

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
             http://xmlns.jcp.org/xml/ns/persistence/persistence_2_2.xsd"
    version="2.2">
    <persistence-unit name="tvTutorialPU"
        transaction-type="JTA">
        <jta-data-source>java:jboss/datasources/tvTutorial</jta-data-source>
        <class>si.david.SmPests</class>
        <class>si.david.SmPestsNames</class>
    </persistence-unit>

</persistence>

I am fairly new at this so if I need to post anything else, please tell and i will add

Update:
Now I put EntityManagerFactory emf and EntityManager em in:

    public SmPests createPest(SmPests smPest)   {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("tvTutorialPU");
        EntityManager em= emf.createEntityManager();
        em.getTransaction().begin();
        em.persist(smPest);
        em.getTransaction().commit();
        return smPest;
    }

Now I get error:

Target Unreachable, identifier 'smPestsEdit' resolved to null

Body:
Your problem is here:

@Entity
@Model
public class SmPestsEdit extends SmPests {
  EntityManagerFactory emf = Persistence.createEntityManagerFactory("tvTutorialPU");
  EntityManager em=emf.createEntityManager();
  // ...
}

Hibernate treats EntityManagerFactory emf and EntityManager em as fields which belong to the entity SmPestsEdit. It is a bad practice to put the code related to the work with EntityManager into the entity declaration. This code should be allocated in repositories.


来源: stackexchange

问:
unexpected program termination in java
In this inside main method when i input arrivalTime[0] as 0 then working correctly but as i type input value more the 0 then it unexceptionally failed.

Thsi program is implementing the RR scheduling where i create a method private static void findWaitingTime(int n, int[] bTime, int[] arrivalTime ,int quantum, int[] wTime)

this function will take number of processes , burst time, arrival time, and the quantum slot alotted to each generall processs.

```<code>    package Others;

    import java.io.BufferedReader;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Scanner;
    import java.io.InputStreamReader;
    import java.io.IOException;

    /**
     * RR scheduling implememtation with the process queue as a list
     *
     * @author Badal
     * @data 2 june 2020
     */

    public class RR_Scheduling {

        /**
this function will take number of processes , burst time, arrival time, and the quantum slot alotted to each generall processs. */

        private static void findWaitingTime(int n, int[] bTime, int[] arrivalTime ,int quantum, int[] wTime){
            // array to store remaing time of respective process
            int[] rem_bt = new int[n];

            int cpu_time = 0;

            // initially it will be equal to the burst time of all processes respectively
            for( int i = 0; i < n; i++ ) rem_bt[i] = bTime[i];

            // get the processes queue
            List<Integer> pQueue = new ArrayList<Integer>();

            // get the processes by thier arrival time
            for( int i = 0; i < n; i++ ){
                if( arrivalTime[i] == cpu_time){
                    pQueue.add(i);
                }
            }

            // executed process
            int executedProcess = 0;
            while(executedProcess != n){

                // process all pQueue processes
                for( int p = 0; p < pQueue.size(); p++){

                    // if not done
                    if( rem_bt[ pQueue.get(p) ] > 0 ){

                        // partail execution
                        if( rem_bt[pQueue.get(p)] > quantum){

                            // collect all the processes that arrive under the execution
                            for( int i = 0; i < n; i++){
                                if(  arrivalTime[i] > cpu_time && arrivalTime[i] < cpu_time + quantum ){
                                    // add to pQueue
                                    pQueue.add(i);
                                }
                            }

                            // update cpu_time
                            cpu_time += quantum;

                            // update rem_bt time
                            rem_bt[pQueue.get(p)] -= quantum;
                        }
                        else{

                            // collect all the processes that arrive under the execution
                            for( int i = 0; i < n; i++){
                                if(  arrivalTime[i] > cpu_time && arrivalTime[i] < cpu_time + rem_bt[pQueue.get(p)]){
                                    // add to pQueue
                                    pQueue.add(i);
                                }
                            }

                            // udpate cpu_time
                            cpu_time += rem_bt[pQueue.get(p)];

                            // completely executed
                            rem_bt[pQueue.get(p)] = 0;

                            // fetch completion time and waiting time
                            int completionTime = cpu_time - arrivalTime[pQueue.get(p)];
                            wTime[pQueue.get(p)] = completionTime - bTime[pQueue.get(p)];

                            //update execute process
                            executedProcess++;

                        }
                    }

                    // get the processes by thier arrival time
                    for( int i = 0; i < n; i++ ){
                        if( arrivalTime[i] == cpu_time){
                            pQueue.add(i);
                        }
                    }
                }

            }
        }

        // take number of processes via command line
        public static void main(String[] args) throws IOException{
            BufferedReader br = new BufferedReader( new InputStreamReader( System.in ));

            int processes = Integer.parseInt(br.readLine());
            int[] arrivalTime = new int[processes];
            int[] burstTime = new int[processes];
            for( int i = 0; i < processes; i++ ){
                arrivalTime[i] = Integer.parseInt(br.readLine());
                burstTime[i] = Integer.parseInt(br.readLine());
            }

            int[] waitingTime = new int[processes];
            int quantum = Integer.parseInt(br.readLine());

            findWaitingTime(processes, burstTime, arrivalTime, quantum, waitingTime);// ??? if arrivalTime[0] >= 1 then it terminating the program.. but working if arrivalTime[0] is 0

            for( int i = 0; i < processes; i++){
                System.out.println("Waiting time : " + waitingTime[i]);
            }

        }

    }
</code>```

答:
just add this in place of

```<code>    // get the processes by thier arrival time
            for( int i = 0; i < n; i++ ){
                if( arrivalTime[i] == cpu_time){
                    pQueue.add(i);
                }
            }
</code>```

in the first time only with

```<code>// get the processes by thier arrival time
        while( pQueue.isEmpty() ){
            for( int i = 0; i < n; i++){
                if( arrivalTime[i] == cpu_time){
                    pQueue.add(i);
                }
            }

            if( pQueue.isEmpty()){
                cpu_time++;
            }
        }
</code>```

as if in begin cpu_time is 0 but their is no process with arrivalTime 0 and even others cpu_time is not updated until any process added to queue.

ContentLicense: CC BY-SA 4.0

Title: unexpected program termination in java

Body:
In this inside main method when i input arrivalTime[0] as 0 then working correctly but as i type input value more the 0 then it unexceptionally failed.

Thsi program is implementing the RR scheduling where i create a method private static void findWaitingTime(int n, int[] bTime, int[] arrivalTime ,int quantum, int[] wTime)

this function will take number of processes , burst time, arrival time, and the quantum slot alotted to each generall processs.

    package Others;

    import java.io.BufferedReader;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Scanner;
    import java.io.InputStreamReader;
    import java.io.IOException;

    /**
     * RR scheduling implememtation with the process queue as a list
     *
     * @author Badal
     * @data 2 june 2020
     */

    public class RR_Scheduling {

        /**
this function will take number of processes , burst time, arrival time, and the quantum slot alotted to each generall processs. */

        private static void findWaitingTime(int n, int[] bTime, int[] arrivalTime ,int quantum, int[] wTime){
            // array to store remaing time of respective process
            int[] rem_bt = new int[n];

            int cpu_time = 0;

            // initially it will be equal to the burst time of all processes respectively
            for( int i = 0; i < n; i++ ) rem_bt[i] = bTime[i];

            // get the processes queue
            List<Integer> pQueue = new ArrayList<Integer>();

            // get the processes by thier arrival time
            for( int i = 0; i < n; i++ ){
                if( arrivalTime[i] == cpu_time){
                    pQueue.add(i);
                }
            }

            // executed process
            int executedProcess = 0;
            while(executedProcess != n){

                // process all pQueue processes
                for( int p = 0; p < pQueue.size(); p++){

                    // if not done
                    if( rem_bt[ pQueue.get(p) ] > 0 ){

                        // partail execution
                        if( rem_bt[pQueue.get(p)] > quantum){

                            // collect all the processes that arrive under the execution
                            for( int i = 0; i < n; i++){
                                if(  arrivalTime[i] > cpu_time && arrivalTime[i] < cpu_time + quantum ){
                                    // add to pQueue
                                    pQueue.add(i);
                                }
                            }

                            // update cpu_time
                            cpu_time += quantum;

                            // update rem_bt time
                            rem_bt[pQueue.get(p)] -= quantum;
                        }
                        else{

                            // collect all the processes that arrive under the execution
                            for( int i = 0; i < n; i++){
                                if(  arrivalTime[i] > cpu_time && arrivalTime[i] < cpu_time + rem_bt[pQueue.get(p)]){
                                    // add to pQueue
                                    pQueue.add(i);
                                }
                            }

                            // udpate cpu_time
                            cpu_time += rem_bt[pQueue.get(p)];

                            // completely executed
                            rem_bt[pQueue.get(p)] = 0;

                            // fetch completion time and waiting time
                            int completionTime = cpu_time - arrivalTime[pQueue.get(p)];
                            wTime[pQueue.get(p)] = completionTime - bTime[pQueue.get(p)];

                            //update execute process
                            executedProcess++;

                        }
                    }

                    // get the processes by thier arrival time
                    for( int i = 0; i < n; i++ ){
                        if( arrivalTime[i] == cpu_time){
                            pQueue.add(i);
                        }
                    }
                }

            }
        }

        // take number of processes via command line
        public static void main(String[] args) throws IOException{
            BufferedReader br = new BufferedReader( new InputStreamReader( System.in ));

            int processes = Integer.parseInt(br.readLine());
            int[] arrivalTime = new int[processes];
            int[] burstTime = new int[processes];
            for( int i = 0; i < processes; i++ ){
                arrivalTime[i] = Integer.parseInt(br.readLine());
                burstTime[i] = Integer.parseInt(br.readLine());
            }

            int[] waitingTime = new int[processes];
            int quantum = Integer.parseInt(br.readLine());

            findWaitingTime(processes, burstTime, arrivalTime, quantum, waitingTime);// ??? if arrivalTime[0] >= 1 then it terminating the program.. but working if arrivalTime[0] is 0

            for( int i = 0; i < processes; i++){
                System.out.println("Waiting time : " + waitingTime[i]);
            }

        }

    }

Body:
just add this in place of

    // get the processes by thier arrival time
            for( int i = 0; i < n; i++ ){
                if( arrivalTime[i] == cpu_time){
                    pQueue.add(i);
                }
            }

in the first time only with

// get the processes by thier arrival time
        while( pQueue.isEmpty() ){
            for( int i = 0; i < n; i++){
                if( arrivalTime[i] == cpu_time){
                    pQueue.add(i);
                }
            }

            if( pQueue.isEmpty()){
                cpu_time++;
            }
        }

as if in begin cpu_time is 0 but their is no process with arrivalTime 0 and even others cpu_time is not updated until any process added to queue.


问:
Applying macro on existing data
I have an excel sheet (exactly multiple sheets which looks the same) where I want to apply macro to change existing data. If value in cells is above 4.0 I need to change it, also I want to add "-" symbol if a cell is empty.
I know my formula will look something like this:

```<code>if(x>=4,RANDBETWEEN(28,39)/10,x)
</code>```

It would be nice if a macro had shortcut like: ctrl+a

答:
Select the cells and try this:</p>

```<code>Sub laszlo()
    Dim r As Range, v As Variant

    For Each r In Selection
        v = r.Value
        If v = "" Then
            r.Value = "-"
        ElseIf IsNumeric(v) Then
            If v >= 4 Then
                r.Value = Application.WorksheetFunction.RandBetween(28, 39) / 10
            End If
        End If
    Next r
End Sub
</code>```

Title: Applying macro on existing data

Body:
I have an excel sheet (exactly multiple sheets which looks the same) where I want to apply macro to change existing data. If value in cells is above 4.0 I need to change it, also I want to add "-" symbol if a cell is empty.
I know my formula will look something like this:

if(x>=4,RANDBETWEEN(28,39)/10,x)

It would be nice if a macro had shortcut like: ctrl+a

Body:
Select the cells and try this:

Sub laszlo()
    Dim r As Range, v As Variant

    For Each r In Selection
        v = r.Value
        If v = "" Then
            r.Value = "-"
        ElseIf IsNumeric(v) Then
            If v >= 4 Then
                r.Value = Application.WorksheetFunction.RandBetween(28, 39) / 10
            End If
        End If
    Next r
End Sub


问:
EF 6.4 Migration with .NET Core and ef6.dll yields in NullReferenceException
I am creating a migration bundle for external usage by our database team to execute Entity Framework Migrations. The bundle is composed of an Entity Framework Project (which includes all our migrations) and the ef6.dll migration tool from the Entity Framework 6.4 NuGet package, which is located at ef64package/tools/netcoreapp3.0/any.

The migration bundle also contains a simple PowerShell script that executes ef6.dll somehow like this:

```<code>dotnet .\ef6.dll database update --verbose --assembly MyApp.Core.EF.dll --connection-string "Data Source=localhost;Initial Catalog=MyApp;Trusted_Connection=True;" --connection-provider "System.Data.SqlClient"
</code>```

Using the migrate.exe (in previous versions of Entity Framework) and ef6.exe for .NET Framework this bundle worked just fine. But after switching to .NET Core and ef6.dll the execution results in the following error:

```<code>Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
System.NullReferenceException: Object reference not set to an instance of an object.
   at System.Data.Entity.Internal.LazyInternalConnection.CreateConnectionFromProviderName(String providerInvariantName)
   at System.Data.Entity.Internal.LazyInternalConnection.InitializeFromConnectionStringSetting(ConnectionStringSettings appConfigConnection)
   at System.Data.Entity.Internal.LazyInternalConnection.Initialize()
   at System.Data.Entity.Internal.LazyInternalConnection.get_Connection()
   at System.Data.Entity.Internal.LazyInternalContext.get_Connection()
   at System.Data.Entity.Infrastructure.DbContextInfo..ctor(Type contextType, DbProviderInfo modelProviderInfo, AppConfig config, DbConnectionInfo connectionInfo, Func`1 resolver)
   at System.Data.Entity.Infrastructure.DbContextInfo..ctor(Type contextType, DbConnectionInfo connectionInfo)
   at System.Data.Entity.Migrations.DbMigrator..ctor(DbMigrationsConfiguration configuration, DbContext usersContext, DatabaseExistenceState existenceState, Boolean calledByCreateDatabase)
   at System.Data.Entity.Migrations.DbMigrator..ctor(DbMigrationsConfiguration configuration)
   at System.Data.Entity.Infrastructure.Design.Executor.CreateMigrator(DbMigrationsConfiguration configuration)
   at System.Data.Entity.Infrastructure.Design.Executor.UpdateInternal(String targetMigration, Boolean force, DbConnectionInfo connectionInfo, String migrationsConfigurationName)
   at System.Data.Entity.Infrastructure.Design.Executor.Update.<>c__DisplayClass0_0.<.ctor>b__0()
   at System.Data.Entity.Infrastructure.Design.Executor.OperationBase.Execute(Action action)
Object reference not set to an instance of an object.
</code>```

A very generic error, but according to the EF source code (https://github.com/dotnet/ef6/blob/02104044fae2aca5d3a1f50f55f4af940a3c64a8/src/EntityFramework/Internal/LazyInternalConnection.cs), i looks like a DbProviderFactory registration is missing or the providerInvariantName is messed up in the process. I've got a feeling this is a side effect due to a missing configuration or dependency. But so far i could not figure out how to fix this error.

Any ideas on how to fix this error?
Also other approaches in creating a standalone migration bundle are highly welcome.

Thanks in advance!

答:
This is how I got it to work:

```<code>dotnet exec --depsfile MyApp.Core.EF.json --runtimeconfig MyApp.Core.EF.runtimeconfig.json "....\packages\entityframework\6.4.0\tools\netcoreapp3.0\any\ef6.dll" database update --assembly MyApp.Core.EF.dll --connection-string "xxx" --verbose
</code>```

See also this Github issue or Entity Framework Migration Azure DevOps Release Pipeline.

Body:
I am creating a migration bundle for external usage by our database team to execute Entity Framework Migrations. The bundle is composed of an Entity Framework Project (which includes all our migrations) and the ef6.dll migration tool from the Entity Framework 6.4 NuGet package, which is located at ef64package/tools/netcoreapp3.0/any.

The migration bundle also contains a simple PowerShell script that executes ef6.dll somehow like this:

dotnet .\ef6.dll database update --verbose --assembly MyApp.Core.EF.dll --connection-string "Data Source=localhost;Initial Catalog=MyApp;Trusted_Connection=True;" --connection-provider "System.Data.SqlClient"

Using the migrate.exe (in previous versions of Entity Framework) and ef6.exe for .NET Framework this bundle worked just fine. But after switching to .NET Core and ef6.dll the execution results in the following error:

Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
System.NullReferenceException: Object reference not set to an instance of an object.
   at System.Data.Entity.Internal.LazyInternalConnection.CreateConnectionFromProviderName(String providerInvariantName)
   at System.Data.Entity.Internal.LazyInternalConnection.InitializeFromConnectionStringSetting(ConnectionStringSettings appConfigConnection)
   at System.Data.Entity.Internal.LazyInternalConnection.Initialize()
   at System.Data.Entity.Internal.LazyInternalConnection.get_Connection()
   at System.Data.Entity.Internal.LazyInternalContext.get_Connection()
   at System.Data.Entity.Infrastructure.DbContextInfo..ctor(Type contextType, DbProviderInfo modelProviderInfo, AppConfig config, DbConnectionInfo connectionInfo, Func`1 resolver)
   at System.Data.Entity.Infrastructure.DbContextInfo..ctor(Type contextType, DbConnectionInfo connectionInfo)
   at System.Data.Entity.Migrations.DbMigrator..ctor(DbMigrationsConfiguration configuration, DbContext usersContext, DatabaseExistenceState existenceState, Boolean calledByCreateDatabase)
   at System.Data.Entity.Migrations.DbMigrator..ctor(DbMigrationsConfiguration configuration)
   at System.Data.Entity.Infrastructure.Design.Executor.CreateMigrator(DbMigrationsConfiguration configuration)
   at System.Data.Entity.Infrastructure.Design.Executor.UpdateInternal(String targetMigration, Boolean force, DbConnectionInfo connectionInfo, String migrationsConfigurationName)
   at System.Data.Entity.Infrastructure.Design.Executor.Update.<>c__DisplayClass0_0.<.ctor>b__0()
   at System.Data.Entity.Infrastructure.Design.Executor.OperationBase.Execute(Action action)
Object reference not set to an instance of an object.

A very generic error, but according to the EF source code (https://github.com/dotnet/ef6/blob/02104044fae2aca5d3a1f50f55f4af940a3c64a8/src/EntityFramework/Internal/LazyInternalConnection.cs), i looks like a DbProviderFactory registration is missing or the providerInvariantName is messed up in the process. I've got a feeling this is a side effect due to a missing configuration or dependency. But so far i could not figure out how to fix this error.

Any ideas on how to fix this error?
Also other approaches in creating a standalone migration bundle are highly welcome.

Thanks in advance!

Body:
This is how I got it to work:

dotnet exec --depsfile MyApp.Core.EF.json --runtimeconfig MyApp.Core.EF.runtimeconfig.json "....\packages\entityframework\6.4.0\tools\netcoreapp3.0\any\ef6.dll" database update --assembly MyApp.Core.EF.dll --connection-string "xxx" --verbose

See also this Github issue or Entity Framework Migration Azure DevOps Release Pipeline.


问:
Equivalent of 'class_indices' attribute of 'flow_from_directory' object in case of 'ImageDataGenerator' object
I am following a tutorial at  https://medium.com/@vijayabhaskar96/tutorial-image-classification-with-keras-flow-from-directory-and-generators-95f75ebe5720

I am using 'ImageDataGenerator' object and want to predict the out put using the following method.

```<code>pred=model.predict_generator(test_generator,
steps=10,
verbose=1)

predicted_class_indices=np.argmax(pred,axis=1)

labels = (train_generator.class_indices)
labels = dict((v,k) for k,v in labels.items())
predictions = [labels[k] for k in predicted_class_indices]
</code>```

But I am using Keras 'ImageDataGenerator'  and 'flow_from_dataframe' object.
 'ImageDataGenerator' has no 'class_indices' attribute. How can I get the indices of the classes

答:
End to End example which uses ImageDataGenerator.flow_from_dataframe and which answers your question of How can I get the indices of the classes

```<code>from tensorflow.keras.models import Sequential
#Import from keras_preprocessing not from keras.preprocessing
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.layers import Dense, Activation, Flatten, Dropout, BatchNormalization
from tensorflow.keras.layers import Conv2D, MaxPooling2D
from tensorflow.keras import regularizers, optimizers
import pandas as pd
import numpy as np

def append_ext(fn):
    return fn+".png"
traindf=pd.read_csv("trainLabels.csv",dtype=str)
testdf=pd.read_csv("sampleSubmission.csv",dtype=str)
traindf["id"]=traindf["id"].apply(append_ext)
testdf["id"]=testdf["id"].apply(append_ext)
datagen=ImageDataGenerator(rescale=1./255.,validation_split=0.25)

train_generator=datagen.flow_from_dataframe(
dataframe=traindf,
directory="train/",
x_col="id",
y_col="label",
subset="training",
batch_size=32,
seed=42,
shuffle=True,
class_mode="categorical",
target_size=(32,32))

valid_generator=datagen.flow_from_dataframe(
dataframe=traindf,
directory="train/",
x_col="id",
y_col="label",
subset="validation",
batch_size=32,
seed=42,
shuffle=True,
class_mode="categorical",
target_size=(32,32))

test_datagen=ImageDataGenerator(rescale=1./255.)
test_generator=test_datagen.flow_from_dataframe(
dataframe=testdf,
directory="test/",
x_col="id",
y_col=None,
batch_size=32,
seed=42,
shuffle=False,
class_mode=None,
target_size=(32,32))

model = Sequential()
model.add(Conv2D(32, (3, 3), padding='same',
                 input_shape=(32,32,3)))
model.add(Activation('relu'))
model.add(Conv2D(32, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Conv2D(64, (3, 3), padding='same'))
model.add(Activation('relu'))
model.add(Conv2D(64, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(512))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(10, activation='softmax'))
model.compile(optimizers.RMSprop(lr=0.0001, decay=1e-6),loss="categorical_crossentropy",metrics=["accuracy"])

STEP_SIZE_TRAIN=train_generator.n//train_generator.batch_size
STEP_SIZE_VALID=valid_generator.n//valid_generator.batch_size
STEP_SIZE_TEST=test_generator.n//test_generator.batch_size
model.fit_generator(generator=train_generator,
                    steps_per_epoch=STEP_SIZE_TRAIN,
                    validation_data=valid_generator,
                    validation_steps=STEP_SIZE_VALID,
                    epochs=10
)

model.evaluate_generator(generator=valid_generator,
steps=STEP_SIZE_TEST)

test_generator.reset()
pred=model.predict_generator(test_generator,
steps=STEP_SIZE_TEST,
verbose=1)

predicted_class_indices=np.argmax(pred,axis=1)

labels = (train_generator.class_indices)
labels = dict((v,k) for k,v in labels.items())
predictions = [labels[k] for k in predicted_class_indices]
</code>```

Finally, we print the Classes as shown below:

```<code>print(predictions)
</code>```

Output of above print statement is:

```<code>['bird',
 'dog',
 'bird',
 'cat',
 'horse',
 'deer',
 'deer',
 'airplane',
 'cat',
 'cat',
 'ship',
 'bird',
 'automobile',..........]
</code>```

For more information, please refer this Article written by Vijaya Bhaskar.

Hope this helps. Happy Learning!

Body:
I am following a tutorial at  https://medium.com/@vijayabhaskar96/tutorial-image-classification-with-keras-flow-from-directory-and-generators-95f75ebe5720

I am using 'ImageDataGenerator' object and want to predict the out put using the following method.

pred=model.predict_generator(test_generator,
steps=10,
verbose=1)

predicted_class_indices=np.argmax(pred,axis=1)

labels = (train_generator.class_indices)
labels = dict((v,k) for k,v in labels.items())
predictions = [labels[k] for k in predicted_class_indices]

But I am using Keras 'ImageDataGenerator'  and 'flow_from_dataframe' object.
 'ImageDataGenerator' has no 'class_indices' attribute. How can I get the indices of the classes

Body:
End to End example which uses ImageDataGenerator.flow_from_dataframe and which answers your question of How can I get the indices of the classes

from tensorflow.keras.models import Sequential
#Import from keras_preprocessing not from keras.preprocessing
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.layers import Dense, Activation, Flatten, Dropout, BatchNormalization
from tensorflow.keras.layers import Conv2D, MaxPooling2D
from tensorflow.keras import regularizers, optimizers
import pandas as pd
import numpy as np

def append_ext(fn):
    return fn+".png"
traindf=pd.read_csv("trainLabels.csv",dtype=str)
testdf=pd.read_csv("sampleSubmission.csv",dtype=str)
traindf["id"]=traindf["id"].apply(append_ext)
testdf["id"]=testdf["id"].apply(append_ext)
datagen=ImageDataGenerator(rescale=1./255.,validation_split=0.25)

train_generator=datagen.flow_from_dataframe(
dataframe=traindf,
directory="train/",
x_col="id",
y_col="label",
subset="training",
batch_size=32,
seed=42,
shuffle=True,
class_mode="categorical",
target_size=(32,32))

valid_generator=datagen.flow_from_dataframe(
dataframe=traindf,
directory="train/",
x_col="id",
y_col="label",
subset="validation",
batch_size=32,
seed=42,
shuffle=True,
class_mode="categorical",
target_size=(32,32))

test_datagen=ImageDataGenerator(rescale=1./255.)
test_generator=test_datagen.flow_from_dataframe(
dataframe=testdf,
directory="test/",
x_col="id",
y_col=None,
batch_size=32,
seed=42,
shuffle=False,
class_mode=None,
target_size=(32,32))

model = Sequential()
model.add(Conv2D(32, (3, 3), padding='same',
                 input_shape=(32,32,3)))
model.add(Activation('relu'))
model.add(Conv2D(32, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Conv2D(64, (3, 3), padding='same'))
model.add(Activation('relu'))
model.add(Conv2D(64, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(512))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(10, activation='softmax'))
model.compile(optimizers.RMSprop(lr=0.0001, decay=1e-6),loss="categorical_crossentropy",metrics=["accuracy"])

STEP_SIZE_TRAIN=train_generator.n//train_generator.batch_size
STEP_SIZE_VALID=valid_generator.n//valid_generator.batch_size
STEP_SIZE_TEST=test_generator.n//test_generator.batch_size
model.fit_generator(generator=train_generator,
                    steps_per_epoch=STEP_SIZE_TRAIN,
                    validation_data=valid_generator,
                    validation_steps=STEP_SIZE_VALID,
                    epochs=10
)

model.evaluate_generator(generator=valid_generator,
steps=STEP_SIZE_TEST)

test_generator.reset()
pred=model.predict_generator(test_generator,
steps=STEP_SIZE_TEST,
verbose=1)

predicted_class_indices=np.argmax(pred,axis=1)

labels = (train_generator.class_indices)
labels = dict((v,k) for k,v in labels.items())
predictions = [labels[k] for k in predicted_class_indices]

Finally, we print the Classes as shown below:

print(predictions)

Output of above print statement is:

['bird',
 'dog',
 'bird',
 'cat',
 'horse',
 'deer',
 'deer',
 'airplane',
 'cat',
 'cat',
 'ship',
 'bird',
 'automobile',..........]

For more information, please refer this Article written by Vijaya Bhaskar.

Hope this helps. Happy Learning!


问:
Switch rows in data.table to create uniform variable
I want to write a script to help me distribute piglets over pens while maintaining a similar average weight between pens by switching animals (rows) between pens to achieve this, but only switching piglets which have the same mother (i.e. the same sowid). So far I got the following script which leads to some improvement but I suspect it is not the optimal algorithm to achieve this goal. Any better ideas?

```<code>    test <- data.table(sowid=c(12,23,25,45,65,12,58,85,96,85,45,23),pen=c(1,1,1,1,2,2,2,2,3,3,3,3),pigletid=c(1,2,3,4,5,6,7,8,9,10,11,12),weight=c(6.5,5.9,6.2,5.8,7.5,7.2,7.8,6.9,9.5,10.2,9.8,6.4))

count <- 0
switch <- c(0,0)
cutoff <- 0.1

while(count == 0){
  meanPP <- test [,mean(weight),.(pen)]
  names(meanPP) <- c("pen","Mean")
  meanPP <- meanPP[order(Mean)]

  if (max(meanPP$Mean) - min(meanPP$Mean) <= cutoff){
    test <- test[order(pen)]
    count <- count + 1
  }else{
    count2 <- 0
    i <- 0
    while (count2 == 0 & i <= nrow(meanPP)){
      maxH <- meanPP$pen[nrow(meanPP)-i]
      for (j in (nrow(test)/nrow(meanPP)):1){
        maxA <- test[pen==maxH]
        maxA <- maxA[order(weight)]$pigletid[j]
        if ((test$sowid[which(test$pigletid == maxA)] %in% test$sowid[-which(test$pigletid == maxA)]) && test[sowid == test$sowid[which(test$pigletid == maxA)],min(weight)] < test[pigletid == maxA,weight]){
          maxA <- which(test$pigletid == maxA)
          count2 <- count2 +1
          break
        }
      }
      i <- i + 1
    }

    for (i in 1:nrow(meanPP)) {
      minH <- meanPP$pen[i]
      minA <- test[pen==minH]
      if (test$sowid[maxA] %in% minA$sowid && minA[sowid==test$sowid[maxA]]$weight < test$weight[maxA]){
        minA <- minA[sowid==test$sowid[maxA]]
        minA <- minA[sowid==test$sowid[maxA]]$pigletid
        minA <- which(test$pigletid == minA)
        break
      }
    }

    if (minA == switch[2] & maxA == switch[1]){
      count <- count +1
    }

    switch <- c(minA,maxA)

    tempRow <- test$pen[maxA]
    test$pen[maxA] <- test$pen[minA]
    test$pen[minA] <- tempRow

    test <- test[order(pen)]
  }
}
</code>```

In response to Anurag N. Sharma, I would like output something like this:

```<code>> test
    sowid pen pigletid weight
 1:    25   1        3    6.2
 2:    45   1       11    9.8
 3:    23   1       12    6.4
 4:    12   1        6    7.2
 5:    12   2        1    6.5
 6:    65   2        5    7.5
 7:    58   2        7    7.8
 8:    85   2        8    6.9
 9:    85   3       10   10.2
10:    23   3        2    5.9
11:    45   3        4    5.8
12:    96   3        9    9.5
</code>```

Where I can get the mean weight of each pen within as close to 0.1 difference as possible to the other pens.

答:
I'd suggest trying a (stochastic) Local Search to solve
the problem.  In essence, you make random switches to
your allocation of piglets and keep those that decrease
the differences in weights.

Alternative representations are possible, but one
possibility is this: A candidate solution is a vector
that maps the piglets to pens; so your column pen
would be an initial solution.  The k-th element of
such a solution gives the pen in which piglet k goes.

Let's map this initial solution into a solution
quality, i.e. write an objective function OF.

```<code>df <- data.frame(sowid = c(12,23,25,45,65,12,58,85,96,85,45,23),
                 pen   = c(1,1,1,1,2,2,2,2,3,3,3,3),
                 pigletid = c(1,2,3,4,5,6,7,8,9,10,11,12),
                 weight   = c(6.5,5.9,6.2,5.8,7.5,7.2,7.8,6.9,9.5,10.2,9.8,6.4))

x <- df$pen
OF <- function(x, df, ...)
    sd(tapply(df$weight, x, mean))
OF(x, df)
## [1] 1.44157
</code>```

Note that I used a standard data.frame to represent
your data. OF computes the standard deviation of
average weights, but you could try other specifications
as well.

Now for the random sampling: randomly select one sow
s with more than one piglet; random select two
piglets that belong to s; exchange their positions.
Note that I precompute sowids so that I do not end up
with sows with only a single piglet.

```<code>sowids <- as.numeric(names(table(df$sowid)[table(df$sowid) > 1]))

nb <- function(x, df, sowids) {
    s <- sowids[sample(length(sowids), 1)]
    ij <- sample(which(df$sowid == s))[1:2]
    x[ij] <- x[rev(ij)]
    x
}
</code>```

nb (which stands for neighbour) implements this sampling. The function takes a candidate
solution xand returns a slightly changed solution.

```<code>x
## [1] 1 1 1 1 2 2 2 2 3 3 3 3
nb(x, df, sowids)
## [1] 1 1 1 2 2 1 2 2 3 3 3 3
nb(nb(x, df, sowids), df, sowids)
## [1] 2 1 1 1 2 2 1 2 3 3 3 3
</code>```

Now we can run the Local Search.  I use the
implementation in package NMOF (of which I am the
maintainer).

```<code>library("NMOF")
sol.ls <- LSopt(OF, list(x0 = df$pen,
                         neighbour = nb,
                         nI = 1000),
                df = df, sowids = sowids)
## Local Search.
## Initial solution:  1.44157
## Best solution overall: 0.3307189
</code>```

We can compare the final solution with the initial one:
average weights by pen.

```<code>tapply(df$weight, df$pen, mean)
##     1     2     3
## 6.100 7.350 8.975
tapply(df$weight, sol.ls$xbest, mean)
##     1     2     3
## 7.225 7.350 7.850
</code>```

And a check: did we keep the correct sowids?

```<code>sort(df$sowid[test$pen == 1])
sort(df$sowid[which(sol.ls$xbest == 1)])

sort(df$sowid[test$pen == 2])
sort(df$sowid[which(sol.ls$xbest == 2)])

sort(df$sowid[test$pen == 3])
sort(df$sowid[which(sol.ls$xbest == 3)])
</code>```

Body:
I want to write a script to help me distribute piglets over pens while maintaining a similar average weight between pens by switching animals (rows) between pens to achieve this, but only switching piglets which have the same mother (i.e. the same sowid). So far I got the following script which leads to some improvement but I suspect it is not the optimal algorithm to achieve this goal. Any better ideas?

    test <- data.table(sowid=c(12,23,25,45,65,12,58,85,96,85,45,23),pen=c(1,1,1,1,2,2,2,2,3,3,3,3),pigletid=c(1,2,3,4,5,6,7,8,9,10,11,12),weight=c(6.5,5.9,6.2,5.8,7.5,7.2,7.8,6.9,9.5,10.2,9.8,6.4))

count <- 0
switch <- c(0,0)
cutoff <- 0.1

while(count == 0){
  meanPP <- test [,mean(weight),.(pen)]
  names(meanPP) <- c("pen","Mean")
  meanPP <- meanPP[order(Mean)]

  if (max(meanPP$Mean) - min(meanPP$Mean) <= cutoff){
    test <- test[order(pen)]
    count <- count + 1
  }else{
    count2 <- 0
    i <- 0
    while (count2 == 0 & i <= nrow(meanPP)){
      maxH <- meanPP$pen[nrow(meanPP)-i]
      for (j in (nrow(test)/nrow(meanPP)):1){
        maxA <- test[pen==maxH]
        maxA <- maxA[order(weight)]$pigletid[j]
        if ((test$sowid[which(test$pigletid == maxA)] %in% test$sowid[-which(test$pigletid == maxA)]) && test[sowid == test$sowid[which(test$pigletid == maxA)],min(weight)] < test[pigletid == maxA,weight]){
          maxA <- which(test$pigletid == maxA)
          count2 <- count2 +1
          break
        }
      }
      i <- i + 1
    }

    for (i in 1:nrow(meanPP)) {
      minH <- meanPP$pen[i]
      minA <- test[pen==minH]
      if (test$sowid[maxA] %in% minA$sowid && minA[sowid==test$sowid[maxA]]$weight < test$weight[maxA]){
        minA <- minA[sowid==test$sowid[maxA]]
        minA <- minA[sowid==test$sowid[maxA]]$pigletid
        minA <- which(test$pigletid == minA)
        break
      }
    }

    if (minA == switch[2] & maxA == switch[1]){
      count <- count +1
    }

    switch <- c(minA,maxA)

    tempRow <- test$pen[maxA]
    test$pen[maxA] <- test$pen[minA]
    test$pen[minA] <- tempRow

    test <- test[order(pen)]
  }
}

In response to Anurag N. Sharma, I would like output something like this:

> test
    sowid pen pigletid weight
 1:    25   1        3    6.2
 2:    45   1       11    9.8
 3:    23   1       12    6.4
 4:    12   1        6    7.2
 5:    12   2        1    6.5
 6:    65   2        5    7.5
 7:    58   2        7    7.8
 8:    85   2        8    6.9
 9:    85   3       10   10.2
10:    23   3        2    5.9
11:    45   3        4    5.8
12:    96   3        9    9.5

Where I can get the mean weight of each pen within as close to 0.1 difference as possible to the other pens.

Body:
I'd suggest trying a (stochastic) Local Search to solve
the problem.  In essence, you make random switches to
your allocation of piglets and keep those that decrease
the differences in weights.

Alternative representations are possible, but one
possibility is this: A candidate solution is a vector
that maps the piglets to pens; so your column pen
would be an initial solution.  The k-th element of
such a solution gives the pen in which piglet k goes.

Let's map this initial solution into a solution
quality, i.e. write an objective function OF.

df <- data.frame(sowid = c(12,23,25,45,65,12,58,85,96,85,45,23),
                 pen   = c(1,1,1,1,2,2,2,2,3,3,3,3),
                 pigletid = c(1,2,3,4,5,6,7,8,9,10,11,12),
                 weight   = c(6.5,5.9,6.2,5.8,7.5,7.2,7.8,6.9,9.5,10.2,9.8,6.4))

x <- df$pen
OF <- function(x, df, ...)
    sd(tapply(df$weight, x, mean))
OF(x, df)
## [1] 1.44157

Note that I used a standard data.frame to represent
your data. OF computes the standard deviation of
average weights, but you could try other specifications
as well.

Now for the random sampling: randomly select one sow
s with more than one piglet; random select two
piglets that belong to s; exchange their positions.
Note that I precompute sowids so that I do not end up
with sows with only a single piglet.

sowids <- as.numeric(names(table(df$sowid)[table(df$sowid) > 1]))

nb <- function(x, df, sowids) {
    s <- sowids[sample(length(sowids), 1)]
    ij <- sample(which(df$sowid == s))[1:2]
    x[ij] <- x[rev(ij)]
    x
}

nb (which stands for neighbour) implements this sampling. The function takes a candidate
solution xand returns a slightly changed solution.

x
## [1] 1 1 1 1 2 2 2 2 3 3 3 3
nb(x, df, sowids)
## [1] 1 1 1 2 2 1 2 2 3 3 3 3
nb(nb(x, df, sowids), df, sowids)
## [1] 2 1 1 1 2 2 1 2 3 3 3 3

Now we can run the Local Search.  I use the
implementation in package NMOF (of which I am the
maintainer).

library("NMOF")
sol.ls <- LSopt(OF, list(x0 = df$pen,
                         neighbour = nb,
                         nI = 1000),
                df = df, sowids = sowids)
## Local Search.
## Initial solution:  1.44157
## Best solution overall: 0.3307189

We can compare the final solution with the initial one:
average weights by pen.

tapply(df$weight, df$pen, mean)
##     1     2     3
## 6.100 7.350 8.975
tapply(df$weight, sol.ls$xbest, mean)
##     1     2     3
## 7.225 7.350 7.850

And a check: did we keep the correct sowids?

sort(df$sowid[test$pen == 1])
sort(df$sowid[which(sol.ls$xbest == 1)])

sort(df$sowid[test$pen == 2])
sort(df$sowid[which(sol.ls$xbest == 2)])

sort(df$sowid[test$pen == 3])
sort(df$sowid[which(sol.ls$xbest == 3)])


问:
How to get a random position within a rotated plane (created out of a center position and size in X and Z)?
I've been defining a plane using a position and a size in the X and Z axis and then getting a random position within that plane in order to make characters to traverse randomly within.

So far I didn't need to change the orientation so to get a random position within the plane was rather simple.

However now I need to rate the plane (in the Y axis) to accommodate it to the terrain, and I would like to know how to keep getting a random position within a rotated plane?

Many thanks!

答:
If you just rotate it around the Y-axis, then you still get a random position within the original plane boundaries, then rotate it accordingly with 2d rotation formulas.

What it means is that you multiply your Vector3 by a rotation matrix, or you just apply the fomula. So assuming you have your random Vector3 position (called pos in my code) generated and you want to apply a rotation of theta , your code could be :

```<code>Vector3 newPosition = new Vector3(pos.x * Math.cos(theta) - pos.z * Math.sin(theta), pos.y, pos.x * Math.sin(theta) + pos.z * Math.cos(theta));
</code>```

I haven't tested it but it should work.

Body:
If you just rotate it around the Y-axis, then you still get a random position within the original plane boundaries, then rotate it accordingly with 2d rotation formulas.

What it means is that you multiply your Vector3 by a rotation matrix, or you just apply the fomula. So assuming you have your random Vector3 position (called pos in my code) generated and you want to apply a rotation of theta , your code could be :

Vector3 newPosition = new Vector3(pos.x * Math.cos(theta) - pos.z * Math.sin(theta), pos.y, pos.x * Math.sin(theta) + pos.z * Math.cos(theta));

I haven't tested it but it should work.


问:
Scatterplot with abline function is not matching Spearman's rho
I need to run a correlation with Spearman between two variables and then plot the result with a scatterplot in R.
I know that normally a positive rho is associated with an ascending trendline in a scatterplot, and a negative with a descending one.

However, I got a positive rho (rho = 0.02 with p = 0.91)
and a scatterplot with trendline going down, as shown in the figure below.

The code that I used is given below and the dataset can be found here

```<code>cor.test(Finale_from_trials_online$Mean_lat_LG, Finale_from_trials_online$Mean_Lat_cue_1, method = "spearman", exact = FALSE)

plot(Finale_from_trials$Mean_Lat_cue_1, Finale_from_trials$Mean_lat_LG, main="LG and cue 1",
     xlab="Mean latency 1", ylab="Mean latency LG", pch=19)
abline(lm(Finale_from_trials$Mean_lat_LG~Finale_from_trials$Mean_Lat_cue_1), col="red") # regression line (y~x)

</code>```

Did I do anything wrong in the code?
Is the problem concerning the lm in the abline argument, since Spearman is just checking for monotonic correlation, and I am plotting a linear trendline?

Or is it just as it is, since the p value is so big and the result is not significant?

Does anybody know why a high p value can cause this?

答:
Spearman's r is calculated using the rank of the values. That is why the outliers with large y values on the left side of the plot are outweighed by the more numerous values with slightly lower y-values than those on the hand side of the plot. But as you have pointed out, the r value is so small, that based on your hypothesis test you cannot say if Spearman's r is truely different from 0.

In contrast, the linear model you have included is sensitive to these outliers. In fact, a bivariate linear model will always have the same sign for beta as Pearson's r, because the sign in both cases come from the covariance. If you do cor.test() with method = "pearson" you will see that it is negative. Yet, as Spearman's r is not based on the covariance these sign can differ.

Body:
I need to run a correlation with Spearman between two variables and then plot the result with a scatterplot in R.
I know that normally a positive rho is associated with an ascending trendline in a scatterplot, and a negative with a descending one.

However, I got a positive rho (rho = 0.02 with p = 0.91)
and a scatterplot with trendline going down, as shown in the figure below.

The code that I used is given below and the dataset can be found here

cor.test(Finale_from_trials_online$Mean_lat_LG, Finale_from_trials_online$Mean_Lat_cue_1, method = "spearman", exact = FALSE)

plot(Finale_from_trials$Mean_Lat_cue_1, Finale_from_trials$Mean_lat_LG, main="LG and cue 1",
     xlab="Mean latency 1", ylab="Mean latency LG", pch=19)
abline(lm(Finale_from_trials$Mean_lat_LG~Finale_from_trials$Mean_Lat_cue_1), col="red") # regression line (y~x)

Did I do anything wrong in the code?
Is the problem concerning the lm in the abline argument, since Spearman is just checking for monotonic correlation, and I am plotting a linear trendline?

Or is it just as it is, since the p value is so big and the result is not significant?

Does anybody know why a high p value can cause this?


问:
Spring JDBC obtaining a list of maps
probably something super simple. I'd like to retrieve two sets of key (String) and value(double) from a simple query which returns one row with two columns.

There must be a cleaner way to do it than what I have below - that's 10 lines to get the job done, which seems overkill. Any recommendation what to use instead? Thanks!

```<code>List<Map<String, Double>> RecordList = namedParameterJdbcTemplate.query(Queries.GET_DATASET(),
                getParsedQuery(request), resultSet -> {
                    List<Map<String, Double>> list = new ArrayList();
                    HashMap mMap = new HashMap();
                    mMap.put("this_year", resultSet.getDouble("this_year"));
                    list.add(mMap);
                    mMap = new HashMap();
                    mMap.put("last_year", resultSet.getDouble("last_year"));
                    list.add(mMap);
                    return list;
                });
</code>```

答:
I would use a MutablePair from Apache Commons. You can find javadoc here:

With that approach you could keep this_year in the L, and last_year on R. L meaning left object and R right object.

You could replace the code with something like that:

```<code>return MutablePair.of(resultSet.getDouble("this_year"),resultSet.getDouble("last_year")));
</code>```

If you prefer not to use the Apache Commons, have a look at some alternatives:

Title: Spring JDBC obtaining a list of maps

Body:
probably something super simple. I'd like to retrieve two sets of key (String) and value(double) from a simple query which returns one row with two columns.

There must be a cleaner way to do it than what I have below - that's 10 lines to get the job done, which seems overkill. Any recommendation what to use instead? Thanks!

List<Map<String, Double>> RecordList = namedParameterJdbcTemplate.query(Queries.GET_DATASET(),
                getParsedQuery(request), resultSet -> {
                    List<Map<String, Double>> list = new ArrayList();
                    HashMap mMap = new HashMap();
                    mMap.put("this_year", resultSet.getDouble("this_year"));
                    list.add(mMap);
                    mMap = new HashMap();
                    mMap.put("last_year", resultSet.getDouble("last_year"));
                    list.add(mMap);
                    return list;
                });

Body:
I would use a MutablePair from Apache Commons. You can find javadoc here:

With that approach you could keep this_year in the L, and last_year on R. L meaning left object and R right object.

You could replace the code with something like that:

return MutablePair.of(resultSet.getDouble("this_year"),resultSet.getDouble("last_year")));

If you prefer not to use the Apache Commons, have a look at some alternatives:


问:
Concise way to write the same line in multiple files - Python
I have several opened files. Now, I need to write the same line in all of them. My current code is the following, but it is unelegant and very repetitive. Is there a way of doing it in less lines?

```<code>with open("a.txt", "a+") as fa,\
     open("b.txt", "a+") as fb,\
     open("c.txt", "a+") as fc,\
     open("d.txt",  "a+") as fd,\
     open("e.txt", "a+") as fe,\
     open("f.txt", "a+") as ff,\
     open("g.txt", "a+") as fg:

    fa.write("header")
    fb.write("header")
    fc.write("header")
    fd.write("header")
    fe.write("header")
    ff.write("header")
    fg.write("header")
</code>```

In the rest of the program (not shown), I deal with each file differently, appending different information to each of them.

If this post is duplicate, I am sorry!

答:
You could create a context manager to create a dictionary of the opened files and then iterate through this dictionary to write the header in all of them.

A dictionary is used instead of a list to make sure you can use the files independently and reliably in the main code

A possible implementation:

from contextlib import contextmanager

@contextmanager
def open_many(key_path):
    opened_files = {}
    try:
        opened_files = {key: open(path, "w") for key, path in key_path.items()}
        yield opened_files
    finally:
        for f in opened_files.values():
            f.close()

with open_many({"a": "a.txt", "b": "b.txt"}) as file_map:
    for f in file_map.values():
        f.write("header")
```

Body:
I have several opened files. Now, I need to write the same line in all of them. My current code is the following, but it is unelegant and very repetitive. Is there a way of doing it in less lines?

with open("a.txt", "a+") as fa,\
     open("b.txt", "a+") as fb,\
     open("c.txt", "a+") as fc,\
     open("d.txt",  "a+") as fd,\
     open("e.txt", "a+") as fe,\
     open("f.txt", "a+") as ff,\
     open("g.txt", "a+") as fg:

    fa.write("header")
    fb.write("header")
    fc.write("header")
    fd.write("header")
    fe.write("header")
    ff.write("header")
    fg.write("header")

In the rest of the program (not shown), I deal with each file differently, appending different information to each of them.

If this post is duplicate, I am sorry!


问:
How come using += to add to a list in python without using square brackets adds one character at a time?
I'm trying to understand why, computationally, using += to add to a list, where square brackets have not been used to encapsulate the value, results in a single character at a time being added to the list as an element.

I hope that the question is clear; here is an example:

```<code>In:

def generate_sentences(subjects, predicates, objects):
    lst1 = []
    lst2 = []
    lst3 = []
    lst4 = []
    lst5 = []
    subjects = sorted(subjects)
    predicates = sorted(predicates)
    objects = sorted(objects)
    for i in subjects:
        for j in predicates:
            for k in objects:
                lst1 += i + " "
                lst2 += (i + " ")
                lst3 += [i + " "]
                lst4.append(i + " ")
                lst5.append([i + " "])

    print("+= no paren: ")
    print(lst1)
    print(" ")
    print("+= paren: ")
    print(lst2)
    print(" ")
    print("+= brackets: ")
    print(lst3)
    print(" ")
    print("append standard: ")
    print(lst4)
    print(" ")
    print("append with brackets: ")
    print(lst5)

generate_sentences(["John", "Mary"], ["hates", "loves"],\
    ["apples", "bananas"])

generate_sentences(["Vlad", "Hubie"], ["drives"],\
["car", "motorcycle", "bus"])
</code>```

and

```<code>Out:

+= no paren:
['H', 'u', 'b', 'i', 'e', ' ', 'H', 'u', 'b', 'i', 'e', ' ', 'H', 'u', 'b', 'i', 'e', ' ', 'V', 'l', 'a', 'd', ' ', 'V', 'l', 'a', 'd', ' ', 'V', 'l', 'a', 'd', ' ']

+= paren:
['H', 'u', 'b', 'i', 'e', ' ', 'H', 'u', 'b', 'i', 'e', ' ', 'H', 'u', 'b', 'i', 'e', ' ', 'V', 'l', 'a', 'd', ' ', 'V', 'l', 'a', 'd', ' ', 'V', 'l', 'a', 'd', ' ']

+= brackets:
['Hubie ', 'Hubie ', 'Hubie ', 'Vlad ', 'Vlad ', 'Vlad ']

append standard:
['Hubie ', 'Hubie ', 'Hubie ', 'Vlad ', 'Vlad ', 'Vlad ']

append with brackets:
[['Hubie '], ['Hubie '], ['Hubie '], ['Vlad '], ['Vlad '], ['Vlad ']]
</code>```

答:
I think I understand your issue, let me know if I got this correct or not :).
So there are several things to this behavior,
First, the difference between append and += is that :

+= merges 2 lists into one list.

append adds an element to a list.

So fundamentally they are not the same thing.

Second, a string is basically a list of characters, so when you are doing this :

```<code>mylist += "a word"
</code>```

You are basically doing this :

```<code>mylist += ['a', ' ', 'w', 'o', 'r', 'd']
</code>```

Try adding an int to your list with a +=, this will occur :

```<code>Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
</code>```

On the other end if you use append to add an integer, it will work because it is not adding a list but an item that can be any type.

I think I answered your question, let me know if you need clarification :)

Body:
I'm trying to understand why, computationally, using += to add to a list, where square brackets have not been used to encapsulate the value, results in a single character at a time being added to the list as an element.

I hope that the question is clear; here is an example:

In:

def generate_sentences(subjects, predicates, objects):
    lst1 = []
    lst2 = []
    lst3 = []
    lst4 = []
    lst5 = []
    subjects = sorted(subjects)
    predicates = sorted(predicates)
    objects = sorted(objects)
    for i in subjects:
        for j in predicates:
            for k in objects:
                lst1 += i + " "
                lst2 += (i + " ")
                lst3 += [i + " "]
                lst4.append(i + " ")
                lst5.append([i + " "])

    print("+= no paren: ")
    print(lst1)
    print(" ")
    print("+= paren: ")
    print(lst2)
    print(" ")
    print("+= brackets: ")
    print(lst3)
    print(" ")
    print("append standard: ")
    print(lst4)
    print(" ")
    print("append with brackets: ")
    print(lst5)

generate_sentences(["John", "Mary"], ["hates", "loves"],\
    ["apples", "bananas"])

generate_sentences(["Vlad", "Hubie"], ["drives"],\
["car", "motorcycle", "bus"])

and

Out:

+= no paren:
['H', 'u', 'b', 'i', 'e', ' ', 'H', 'u', 'b', 'i', 'e', ' ', 'H', 'u', 'b', 'i', 'e', ' ', 'V', 'l', 'a', 'd', ' ', 'V', 'l', 'a', 'd', ' ', 'V', 'l', 'a', 'd', ' ']

+= paren:
['H', 'u', 'b', 'i', 'e', ' ', 'H', 'u', 'b', 'i', 'e', ' ', 'H', 'u', 'b', 'i', 'e', ' ', 'V', 'l', 'a', 'd', ' ', 'V', 'l', 'a', 'd', ' ', 'V', 'l', 'a', 'd', ' ']

+= brackets:
['Hubie ', 'Hubie ', 'Hubie ', 'Vlad ', 'Vlad ', 'Vlad ']

append standard:
['Hubie ', 'Hubie ', 'Hubie ', 'Vlad ', 'Vlad ', 'Vlad ']

append with brackets:
[['Hubie '], ['Hubie '], ['Hubie '], ['Vlad '], ['Vlad '], ['Vlad ']]

Body:
I think I understand your issue, let me know if I got this correct or not :).
So there are several things to this behavior,
First, the difference between append and += is that :

+= merges 2 lists into one list.

append adds an element to a list.

So fundamentally they are not the same thing.

Second, a string is basically a list of characters, so when you are doing this :

mylist += "a word"

You are basically doing this :

mylist += ['a', ' ', 'w', 'o', 'r', 'd']

Try adding an int to your list with a +=, this will occur :

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable

On the other end if you use append to add an integer, it will work because it is not adding a list but an item that can be any type.

I think I answered your question, let me know if you need clarification :)


问:
Use rpad in delphi grid
Use rpad in tdbgrid not working correctly. In sql devleper work fine.
Any solution for this problem.

```<code>Select rpad('Lionel Messi',20,'.') as COL_1 from dual
union all
Select rpad('Cristiano Ronaldo',20,'.') as COL_1 from dual
union all
Select rpad('Pele',20,'.') as COL_1 from dual
</code>```

Example:

答:
Looks like your Sql developer is using a fixed-pitch font, whereas your DBGrid isn't. Set your DBGrid to use a fixed-pitch font like Courier New.

In any case, for future reference, it is not very sound practice to use SQL on your SQL Server to do output formatting by using e.g. RPad(), especially when it is applied to every single row of a result set - it pointlessly consumes server resources and network bandwidth for something that should be left to the client to do.

Title: Use rpad in delphi grid

Body:
Use rpad in tdbgrid not working correctly. In sql devleper work fine.
Any solution for this problem.

Select rpad('Lionel Messi',20,'.') as COL_1 from dual
union all
Select rpad('Cristiano Ronaldo',20,'.') as COL_1 from dual
union all
Select rpad('Pele',20,'.') as COL_1 from dual

Example:


问:
Change order of orders in Woocommerce based on how much time is left by the date the order should be ready
I need to change order of orders in Woocommerce admin page. I have some custom column with date / time and based on this data I will change the order of orders. It is not stricly date / time filtering (from oldest to newest or vice versa).

The decisive factor is how much time is left by the date the order should be ready. In my case, it's one hour. At that point, the order should be at the top of the list, regardless of whether it was created, for example, a week ago.

Examples:

1) Default ordering (newest on top, oldest on bottom)

```<code>+--------------------------------+------------+---------+--------------------+-------+
| ACTUAL DATE: 28.5.2020 - 15:00 |            |         |                    |       |
+--------------------------------+------------+---------+--------------------+-------+
| ORDER                          | DATE       | STATUS  | DATE/TIME (custom) | PRICE |
| Frank                          | 28.05.2020 | PENDING | -                  | 100   |
| Lucy                           | 27.05.2020 | DONE    | -                  | 50    |
| Thomas                         | 27.05.2020 | DONE    | -                  | 80    |
| Jane                           | 26.05.2020 | PENDING | 28.5.2020 - 16:00  | 90    |
+--------------------------------+------------+---------+--------------------+-------+
</code>```

2) One hour left to complete Jane's order

```<code>+--------------------------------+------------+---------+--------------------+-------+
| ACTUAL DATE: 28.5.2020 - 15:00 |            |         |                    |       |
+--------------------------------+------------+---------+--------------------+-------+
| ORDER                          | DATE       | STATUS  | DATE/TIME (custom) | PRICE |
| Jane                           | 26.05.2020 | PENDING | 28.5.2020 - 16:00  | 90    |
| Frank                          | 28.05.2020 | PENDING | -                  | 100   |
| Lucy                           | 27.05.2020 | DONE    | -                  | 50    |
| Thomas                         | 27.05.2020 | DONE    | -                  | 80    |
+--------------------------------+------------+---------+--------------------+-------+

</code>```

3) Two hour left to complete Jane's order

```<code>+--------------------------------+------------+---------+--------------------+-------+
| ACTUAL DATE: 28.5.2020 - 14:00 |            |         |                    |       |
+--------------------------------+------------+---------+--------------------+-------+
| ORDER                          | DATE       | STATUS  | DATE/TIME (custom) | PRICE |
| Frank                          | 28.05.2020 | PENDING | -                  | 100   |
| Lucy                           | 27.05.2020 | DONE    | -                  | 50    |
| Thomas                         | 27.05.2020 | DONE    | -                  | 80    |
| Jane                           | 26.05.2020 | PENDING | 28.5.2020 - 16:00  | 90    |
+--------------------------------+------------+---------+--------------------+-------+
</code>```

Could you please give me a hint how to start? What hooks in my child theme function.php should I use?

EDIT:
Example code for adding new column:

```<code>// Add column
add_filter( 'manage_edit-shop_order_columns', 'custom_delivery_time' );
function custom_delivery_time( $columns ) {
    $new_columns = ( is_array( $columns ) ) ? $columns : array();
    unset( $new_columns[ 'order_actions' ] );

    $new_columns['custom_datetime'] = 'Date / Time';
    $new_columns[ 'order_actions' ] = $columns[ 'order_actions' ];

    return $new_columns;
}

// Change order of columns, populate
add_action( 'manage_shop_order_posts_custom_column', 'custom_woo_admin_value', 2 );
function custom_woo_admin_value( $column ) {
    global $post, $the_order;

    if ( empty( $the_order ) || $the_order->get_id() != $post->ID ) {
        $the_order = wc_get_order( $post->ID );
    }

    if ( $column == 'custom_datetime' ) {
        $custom_datetime = $the_order->get_custom_datetime();
        echo empty($custom_datetime) ? '' : $custom_datetime;
    }
}
</code>```

答:
Ok. I solved it this way. I created a custom "priority" column, which contains a numeric value that determines how high in the list the order should be. I then sort orders according to this custom column from the smallest (highest priorty) to the largest. Whenever a admin "orders list" page is updated, the appropriate priority is selected according to the time of delivery.  I'm only interested in not finished orders, so there is not much to process.

I would still like to hear if someone comes up with a better solution.

Body:
I need to change order of orders in Woocommerce admin page. I have some custom column with date / time and based on this data I will change the order of orders. It is not stricly date / time filtering (from oldest to newest or vice versa).

The decisive factor is how much time is left by the date the order should be ready. In my case, it's one hour. At that point, the order should be at the top of the list, regardless of whether it was created, for example, a week ago.

Examples:

1) Default ordering (newest on top, oldest on bottom)

+--------------------------------+------------+---------+--------------------+-------+
| ACTUAL DATE: 28.5.2020 - 15:00 |            |         |                    |       |
+--------------------------------+------------+---------+--------------------+-------+
| ORDER                          | DATE       | STATUS  | DATE/TIME (custom) | PRICE |
| Frank                          | 28.05.2020 | PENDING | -                  | 100   |
| Lucy                           | 27.05.2020 | DONE    | -                  | 50    |
| Thomas                         | 27.05.2020 | DONE    | -                  | 80    |
| Jane                           | 26.05.2020 | PENDING | 28.5.2020 - 16:00  | 90    |
+--------------------------------+------------+---------+--------------------+-------+

2) One hour left to complete Jane's order

+--------------------------------+------------+---------+--------------------+-------+
| ACTUAL DATE: 28.5.2020 - 15:00 |            |         |                    |       |
+--------------------------------+------------+---------+--------------------+-------+
| ORDER                          | DATE       | STATUS  | DATE/TIME (custom) | PRICE |
| Jane                           | 26.05.2020 | PENDING | 28.5.2020 - 16:00  | 90    |
| Frank                          | 28.05.2020 | PENDING | -                  | 100   |
| Lucy                           | 27.05.2020 | DONE    | -                  | 50    |
| Thomas                         | 27.05.2020 | DONE    | -                  | 80    |
+--------------------------------+------------+---------+--------------------+-------+

3) Two hour left to complete Jane's order

+--------------------------------+------------+---------+--------------------+-------+
| ACTUAL DATE: 28.5.2020 - 14:00 |            |         |                    |       |
+--------------------------------+------------+---------+--------------------+-------+
| ORDER                          | DATE       | STATUS  | DATE/TIME (custom) | PRICE |
| Frank                          | 28.05.2020 | PENDING | -                  | 100   |
| Lucy                           | 27.05.2020 | DONE    | -                  | 50    |
| Thomas                         | 27.05.2020 | DONE    | -                  | 80    |
| Jane                           | 26.05.2020 | PENDING | 28.5.2020 - 16:00  | 90    |
+--------------------------------+------------+---------+--------------------+-------+

Could you please give me a hint how to start? What hooks in my child theme function.php should I use?

EDIT:
Example code for adding new column:

// Add column
add_filter( 'manage_edit-shop_order_columns', 'custom_delivery_time' );
function custom_delivery_time( $columns ) {
    $new_columns = ( is_array( $columns ) ) ? $columns : array();
    unset( $new_columns[ 'order_actions' ] );

    $new_columns['custom_datetime'] = 'Date / Time';
    $new_columns[ 'order_actions' ] = $columns[ 'order_actions' ];

    return $new_columns;
}

// Change order of columns, populate
add_action( 'manage_shop_order_posts_custom_column', 'custom_woo_admin_value', 2 );
function custom_woo_admin_value( $column ) {
    global $post, $the_order;

    if ( empty( $the_order ) || $the_order->get_id() != $post->ID ) {
        $the_order = wc_get_order( $post->ID );
    }

    if ( $column == 'custom_datetime' ) {
        $custom_datetime = $the_order->get_custom_datetime();
        echo empty($custom_datetime) ? '' : $custom_datetime;
    }
}


问:
What are the benefits of a Hypervisor VM?
I'm looking into using virtual machines to host multiple OSes and I'm looking at the free solutions which there are a lot of them. I'm confused by what a hypervisor is and why are they different or better than a "standard" virtual machine. When I mean standard I going to use the benchmark virtual machine VMWare Server 2.0.

For a dual core system with 4 GB of ram that would be capable of running a max of 3 VMs. Which is the best choice? Hypervisor or non-hypervisor and why? I've already read the Wikipedia article but the technical details are over my head. I need a basic answer of what can these different VM flavors do for me.

My main question relates to how I would do testing on multiple environments. I am concerned about the isolation of OSes so I can test applications on multiple OSes at the same time. Also which flavor gives a closer experience of how a real machine operates?

I'm considering the following:

(hypervisor)

Xen

Hyper-V

(non-hypervisor)

VirtualBox

VMWare Server 2.0

Virtual PC 2007

*The classifications of the VMs I've listed may be incorrect.

答:
The main difference is that Hyper-V doesn't run on top of the OS but instead along with the system it runs on top of a thin layer called hypervisor. Hypervisor is a computer hardware platform virtualization software that allows multiple operating systems to run on a host computer concurrently.

Many other virtualization solution uses other techniques like emulation. For more details see Wikipedia.

OwnerDisplayName: Jeremy Edwards

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Jeremy Edwards

OwnerDisplayName: David Pokluda


问:
how to find a file name using find command when the name can contain "_" and sometime may not contain
In my directory there are multiple files and sometime file name contains "_" i am trying to find file names based on the ordernumber coming in the file name itself and update the filename

for e.g.

```<code>f3 =822220222 # order number that changes every time
f4=`find . -name *$f3*`  # command i am using to find the filename having this order number in name itself
# Files in directory are like
Filename_822220222_1 or Filename_822220222_1_1 or Filename_822220222 (e.g.)
</code>```

答:
try this:

```<code>f4=$(find ./ -name "$f3*")
</code>```

even if you will add the _ it will work

Body:
In my directory there are multiple files and sometime file name contains "_" i am trying to find file names based on the ordernumber coming in the file name itself and update the filename

for e.g.

f3 =822220222 # order number that changes every time
f4=`find . -name *$f3*`  # command i am using to find the filename having this order number in name itself
# Files in directory are like
Filename_822220222_1 or Filename_822220222_1_1 or Filename_822220222 (e.g.)

Body:
try this:

f4=$(find ./ -name "$f3*")

even if you will add the _ it will work


问:
How to check a resource's MIME type in Javascript?
I'm trying to make a function that checks a resource that the user provides, to see if it is a valid audio file.

Everything I've found on here, is related to checking a files MIME type after uploading a file. That is not my goal here.

//insert MIME type checking function here
const urlParams = new URLSearchParams(window.location.search);
const audioURL = urlParams('audiourl') // get audiourl from query (example.com/?audiourl=https://example.com/audio.wav)

if (mimetypecheck()) { // function to check mime type here
    var audio = new Audio(audioURL);
    audio.play();
} else {
    //tell user invalid audio url, or unsupported audio type
}
```

答:
As it has been said in comments, the only way to check that a resource points to some playable media, is to actually try to play it.

A MIME type won't tell you much, moreover for audio/video media:

you can't be 100% sure that what the container (which is declared by the MIME type) really contains, it could very well be encoded in a codec that the browser can't decode, even if it wrapped in a container the browser should know.

This means that even though a simple HEAD request could tell you for some URLs what the server would send in the Content-Type headers, that wouldn't tell you exactly if the browser would be able to play it. And given most server won't let you read these headers anyway, that doesn't worth the cost of trying to implement this.

For your case the best is thus to try to play it.

So you can rewrite your code to

const urlParams = new URLSearchParams(window.location.search);
const audioURL = urlParams('audiourl') // get audiourl from query (example.com/?audiourl=https://example.com/audio.wav)

const audio = new Audio(audioURL);
audio.onerror = (evt) => {
  //tell user invalid audio url, or unsupported audio type
};
audio.play();
```

<p>Note that we could also have bound to the <code>catch()</code> method of the Promise returned by the <code>HTMLMediaElement.play()</code> method, but it could actually fire for an other reason (e.g if the user never did interact with the page before in Chrome, or if this code is not in direct response to an user-gesture in Safari).  If you are sure only invalid URLs could be the reason for a failure to play, then you could do</p>

```const audio = new Audio(audioURL);
audio.play().catch( () => {
  //tell user invalid audio url, or unsupported audio type
});
```

Body:
As it has been said in comments, the only way to check that a resource points to some playable media, is to actually try to play it.

A MIME type won't tell you much, moreover for audio/video media:

you can't be 100% sure that what the container (which is declared by the MIME type) really contains, it could very well be encoded in a codec that the browser can't decode, even if it wrapped in a container the browser should know.

This means that even though a simple HEAD request could tell you for some URLs what the server would send in the Content-Type headers, that wouldn't tell you exactly if the browser would be able to play it. And given most server won't let you read these headers anyway, that doesn't worth the cost of trying to implement this.

For your case the best is thus to try to play it.

So you can rewrite your code to

const urlParams = new URLSearchParams(window.location.search);
const audioURL = urlParams('audiourl') // get audiourl from query (example.com/?audiourl=https://example.com/audio.wav)

const audio = new Audio(audioURL);
audio.onerror = (evt) => {
  //tell user invalid audio url, or unsupported audio type
};
audio.play();

Note that we could also have bound to the catch() method of the Promise returned by the HTMLMediaElement.play() method, but it could actually fire for an other reason (e.g if the user never did interact with the page before in Chrome, or if this code is not in direct response to an user-gesture in Safari).  If you are sure only invalid URLs could be the reason for a failure to play, then you could do

const audio = new Audio(audioURL);
audio.play().catch( () => {
  //tell user invalid audio url, or unsupported audio type
});


问:
TYPO3 8.7/9.5 pibase $_POST not available?
i am reworking some old typo3 project extensions. the problem is we have to stay on that pibase structure as it is supported by core anyway. so that extension does some simple CRUD operations, in my case an insert based on submitted values via $_POST.  so the old extension just used $_POST directly which is not supported anymore, i guess since the PSR-7 Request/Response implementation.

but now how can i access the submitted values since $_POST is not available anymore and i do not have $this->request either because the extension extends AbstractPlugin.

edit:
also we are not inside main()
the codeblock is within sendMail()

i also have no idea were sendMail gets called from as there is no available documentation for pibase.

help is much appreciated

答:
you can access the GET and POST parameters with \TYPO3\CMS\Core\Utility\GeneralUtility::_GP('name')

but for security reasons that might be filtered away.

we have the concept of cHashes which secure the site against injected parameter. all parameters must be known and are secured aby a hash. TYPO3 remembers the parameter by the cHash. if a cHash is given, the paramters are fetched from database and paramters given to the server are ignored.

for forms (like ext:form or ext:powermail) there are no cHashes generated and the fields of the form can be processed.

if you have 'naked' forms and plain php-files to process, you should change to a form extension where you can use the existing finishers and can add addional finishers (and validators), for these finishers the form data is secured against injection and you do not need to access $_GET or $_POST.

EDIT:

Here is a question/answer how to disable cHash calculation for single form values: TYPO3 - Deactivating cHash in own extension - 8LTS


问:
How to change the directory/file path of a file being served by Firebase?
I am currently hosting a static website through Firebase, but the one file being served (index.html) exists in my Mac computer's Public folder. Since I would like to serve other files, I want to move the index to a project folder that will contain future linked files (e.g. /public/my-project/index.html).

How would I go about updating the file path/directory?

答:
I accidentally stumbled across the answer while tweaking my settings in Terminal, it was a lot simpler than I expected. For future reference to anyone who sees this,

Open Terminal, and enter firebase init (assuming you have node.js and firebase already installed).

Use your arrows keys to navigate down to the ○ Hosting option, press your spacebar to select, and Return/Enter key to proceed.

The question "What do you want to use as your public directory?" will prompt. Type your desired file path (i.e. public/my-project/public) and enter.

The question "Configure as a single-page app (rewrite all urls to /index.html)?" This is your choice and depends on your platform.

If a file named index.html already exists in that location, it will ask if you want to overwrite it and create a new one. Most likely, you will want to keep the existing index you have -- if this is the case, type n.

Make sure to also follow @nicoqh's valuable advice and differentiate between your public and private folders so that not all of your files end up getting deployed by Firebase.


问:
Why 'Using index condition' even though condition within index?
Had a slow query which uses two columns so decided to add a composite index and alter the sorting. It is working great now. Execution time went down from almost a minute to under a second. But the explain output still displays 'Using index condition'. Why?

Query:

```<code>SELECT *
FROM TableA
WHERE source = 'book' AND uuid = 999
ORDER BY uuid ASC;

</code>```

Table columns:

Index:

Explain output:

Explain analyze output:

-> Index lookup on TableA using source_uuid_index (source='book'), with index condition: (table.uuid = 999)  (cost=33679.16 rows=170038) (actual time=57.279..57.384 rows=4 loops=1)

The EXPLAIN data says that it is using the composite index, which makes sense. However, the EXPLAIN ANALYZE also says "with index condition: (table.uuid = 999)".

Why does it use uuid as an 'index condition', being uuid in the index alongside source?

答:
I figured out what's the cause.
The uuid column is type varchar. So I was querying wrongly. This is the right query:

```<code>SELECT *
FROM TableA
WHERE source = 'book' AND uuid = '999'
ORDER BY uuid ASC;
</code>```

Explain output:

Body:
Had a slow query which uses two columns so decided to add a composite index and alter the sorting. It is working great now. Execution time went down from almost a minute to under a second. But the explain output still displays 'Using index condition'. Why?

Query:

SELECT *
FROM TableA
WHERE source = 'book' AND uuid = 999
ORDER BY uuid ASC;

Table columns:

Index:

Explain output:

Explain analyze output:

-> Index lookup on TableA using source_uuid_index (source='book'), with index condition: (table.uuid = 999)  (cost=33679.16 rows=170038) (actual time=57.279..57.384 rows=4 loops=1)

The EXPLAIN data says that it is using the composite index, which makes sense. However, the EXPLAIN ANALYZE also says "with index condition: (table.uuid = 999)".

Why does it use uuid as an 'index condition', being uuid in the index alongside source?

Body:
I figured out what's the cause.
The uuid column is type varchar. So I was querying wrongly. This is the right query:

SELECT *
FROM TableA
WHERE source = 'book' AND uuid = '999'
ORDER BY uuid ASC;

Explain output:


问:
How to create a new string list from a list of strings excluding one variable?
I have a list of strings and I'm trying to iterate through it and create each iteration a new list without one of the strings.
I tried the following:

```<code>tx_list = ['9540a4ff214d6368cc557803e357f8acebf105faad677eb06ab10d1711d3db46', 'dd92415446692593a4768e3604ab1350c0d81135be42fd9581e2e712f11d82ed',....]
for txid in tx_list:
    tx_list_copy = tx_list
    tx_list_without_txid = tx_list_copy.remove(txid)
</code>```

But each iteration the new list is empty.

答:
If you want to create multiple lists then this won't work you'll need to create a dictionary:

```<code>list_box = {}
for txid in tk_list:
    list_box[txid] = tx_list.copy()
    list_box[txid].remove(txid)
</code>```

this will create a new list with name list_box[txid] where txid is  the element that dosen't exists in the list(for better understanding).
Hope it will help!

Body:
I have a list of strings and I'm trying to iterate through it and create each iteration a new list without one of the strings.
I tried the following:

tx_list = ['9540a4ff214d6368cc557803e357f8acebf105faad677eb06ab10d1711d3db46', 'dd92415446692593a4768e3604ab1350c0d81135be42fd9581e2e712f11d82ed',....]
for txid in tx_list:
    tx_list_copy = tx_list
    tx_list_without_txid = tx_list_copy.remove(txid)

But each iteration the new list is empty.

Body:
If you want to create multiple lists then this won't work you'll need to create a dictionary:

list_box = {}
for txid in tk_list:
    list_box[txid] = tx_list.copy()
    list_box[txid].remove(txid)

this will create a new list with name list_box[txid] where txid is  the element that dosen't exists in the list(for better understanding).
Hope it will help!


问:
How to change SignalR maximum message size?
I need to transfer large JSON messages in SignalR, but the maximum message size is limited by default, is there any way to increase that maximum size?

I have also find some relevant links but didn't find any proper solution:

https://learn.microsoft.com/en-us/aspnet/core/signalr/security

https://learn.microsoft.com/en-us/aspnet/core/signalr/configuration

答:
In .Net Core 3+, You can configure SignalR in ConfigureServices method in your startup class.</p>

```<code>services.AddSignalR(o =>
            {
                o.EnableDetailedErrors = true;
                o.MaximumReceiveMessageSize = 10240;
            });
</code>```

Body:
In .Net Core 3+, You can configure SignalR in ConfigureServices method in your startup class.

services.AddSignalR(o =>
            {
                o.EnableDetailedErrors = true;
                o.MaximumReceiveMessageSize = 10240;
            });