问:
mongoDB run queries just like as SQL !
```<code>    public IQueryable<T> GetRecords<T>(System.Linq.Expressions.Expression<Func<T, bool>> expression, int from, int first) where T : class, new()
    {
        first = first == 0 ? 30 : first;
        return _db.GetCollection<T>(collectionName).Linq().Where(expression).Skip(from).Take(first);
    }
    var x = GetRecords<Event>(p => true, 0, 12222);
    string eventJson = new JavaScriptSerializer().Serialize(x);
</code>```

this function get the data from mongoDB.

```<code>    SqlDataReader dr = SqlHelper.ExecuteReader("Select Top(12222)* From NewsFeed");
    string eventJson = new JavaScriptSerializer().Serialize(dr);
</code>```

and this from SQL Server .

I've tried to measure the execute time for each of them and the result was :

 Mongo : 172ms

SQL : 185ms .

but as I know the mongoDB should be too much faster than SQL , right !?!

答:
MongoDB isn't necessarily about out-performing SQL server in a simple query like that; The speed advantage comes in when you have ancillary data.  I don't know what your domain looks like, but a common example is a blog.  In a SQL database, you would have a posts table, a comments table, an authors table, etc.  Your query to retrieve all the data required for a single blog post display would either include a few joins or multiple queries (either way will affect the performance a bit).  In a NoSQL database, there could be a single table, Posts.  One query with no joins will pull back all required data.

Here's a nice blog post talking about the different approaches between a NoSQL type store and a relational store.

Title: mongoDB run queries just like as SQL !

Body:
    public IQueryable<T> GetRecords<T>(System.Linq.Expressions.Expression<Func<T, bool>> expression, int from, int first) where T : class, new()
    {
        first = first == 0 ? 30 : first;
        return _db.GetCollection<T>(collectionName).Linq().Where(expression).Skip(from).Take(first);
    }
    var x = GetRecords<Event>(p => true, 0, 12222);
    string eventJson = new JavaScriptSerializer().Serialize(x);

this function get the data from mongoDB.

    SqlDataReader dr = SqlHelper.ExecuteReader("Select Top(12222)* From NewsFeed");
    string eventJson = new JavaScriptSerializer().Serialize(dr);

and this from SQL Server .

I've tried to measure the execute time for each of them and the result was :

 Mongo : 172ms

SQL : 185ms .

but as I know the mongoDB should be too much faster than SQL , right !?!


来源: stackexchange

问:
Bytes currently in use by a Google Guava cache?
I'd like to find out how many bytes are being using in the cache. This is useful in determining reasonable sizing. What are some good ways to tally the number of bytes used in a Google Guava cache?

The stats method doesn't give what I want; it does not include metrics on the number of bytes in the cache.

The asMap method is the best way I've found so far. After getting this information, one could use some of the techniques shown in In Java, what is the best way to determine the size of an object?. But, frankly, these seem fairly painful, at least from a Clojure codebase. In order to avoid some dependencies, I'm currently using a rough shortcut with Nippy, a Clojure serialization library: (count (nippy/freeze (.asMap cache))). I'm looking for better ways.

I am using Google Guava caching from a Clojure codebase, but my question is not necessarily Clojure specific; Java interop is relatively easy in most cases.

Update: Some context in response to a comment below. First, I'd like to know if I'm overlooking a useful part of the Google Guava caching API. Second, I don't know if the generic approaches I linked (for counting memory usage on the heap) apply well to Guava. More broadly, finding cache size utilization is an important use case, so I'm a little surprised it isn't better documented online.

答:
Java (and by extension Guava) does not provide any easy or meaningful way to measure "bytes used" by an object or data structure. Notably there isn't even a single coherent definition of that concept, since an object can be referenced from multiple other objects and there's no notion of bytes being "owned" by a particular data structure. Other languages like Rust have this notion of ownership, but Java does not.

For example, how many bytes does an instance of MyClass use?

```<code>public class MyClass {
  private static final int[] BIG_ARRAY = new int[1_000_000];
  private final int[] myArray = BIG_ARRAY;
}
</code>```

Clearly the class uses a lot of memory, but each instance only uses up a few bytes in order to reference the statically allocated array. You can create thousands of MyClass instances and see very little memory impact, and even if all instances are GCed BIG_ARRAY will stick around. So it seems wrong to say that an instance of MyClass "uses" the backing array's bytes.

You can determine how many bytes the cache itself uses (e.g. to compare it to using a ConcurrentHashMap or another collection) based on the fields and instances a Cache maintains. Guava links to this helpful resource of data structure memory footprints you can reference, but obviously this won't include the contents of the cache, just its structure.

Needless to say, as Louis Wasserman commented, you should look for a different metric that more directly tells you what you need to know. For instance you might be more interested in the hit rate, which tells you how efficiently you're using whatever data your cache is retaining.

ContentLicense: CC BY-SA 3.0

Body:
Java (and by extension Guava) does not provide any easy or meaningful way to measure "bytes used" by an object or data structure. Notably there isn't even a single coherent definition of that concept, since an object can be referenced from multiple other objects and there's no notion of bytes being "owned" by a particular data structure. Other languages like Rust have this notion of ownership, but Java does not.

For example, how many bytes does an instance of MyClass use?

public class MyClass {
  private static final int[] BIG_ARRAY = new int[1_000_000];
  private final int[] myArray = BIG_ARRAY;
}

Clearly the class uses a lot of memory, but each instance only uses up a few bytes in order to reference the statically allocated array. You can create thousands of MyClass instances and see very little memory impact, and even if all instances are GCed BIG_ARRAY will stick around. So it seems wrong to say that an instance of MyClass "uses" the backing array's bytes.

You can determine how many bytes the cache itself uses (e.g. to compare it to using a ConcurrentHashMap or another collection) based on the fields and instances a Cache maintains. Guava links to this helpful resource of data structure memory footprints you can reference, but obviously this won't include the contents of the cache, just its structure.

Needless to say, as Louis Wasserman commented, you should look for a different metric that more directly tells you what you need to know. For instance you might be more interested in the hit rate, which tells you how efficiently you're using whatever data your cache is retaining.


问:
"Repeated column in mapping for entity" on ID field
I'm making Spring application with Hibernate and I'm just trying to get relations between my entities working. I set up annotations for all foreign keys and now I get "Repeated column in mapping for entity" error. I was trying to find a solution here on SO, but I didn't really understand some of the answers and I don't think they are applicable to my code. I had this problem earlier with another project, where all ID fields were named just id and when I explicitly defined column name by @Column(name = "") and typed that name in @JoinColumn parameters it worked. Now I had the same error, but defining explicit names for ID fields didn't help.

Here's my entity class:

```<code>@Entity
public class Task implements Serializable, Discussable {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "task_id")
    private long id;

    private String name;

    @ManyToMany
    @JoinTable(
            name = "user_task",
            joinColumns = @JoinColumn(name = "task_id"),
            inverseJoinColumns = @JoinColumn(name = "user_id")
    )
    private Set<User> assigneeUsers;

    @Enumerated(EnumType.ORDINAL)
    private Status status; //alt + enter

    private Priority priority;

    private Date deadline;

    private String description;

    @ManyToOne
    @JoinColumn(name = "task_id")
    private Task parentTask;

    @OneToMany(mappedBy = "parentTask")
    private Set<Task> subtasks;

    @Enumerated(EnumType.ORDINAL)
    private Type type;

    @OneToOne(cascade = CascadeType.REMOVE)
    @JoinColumn(name = "channel_id")
    private Channel channel;

    @ManyToOne
    @JoinColumn(name = "project_id")
    private Project project;

// getters, setters and default constructor
</code>```

The result I get when trying to compile is:

```<code>org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1078) ~[spring-context-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:857) ~[spring-context-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543) ~[spring-context-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693) [spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360) [spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:303) [spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1118) [spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1107) [spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
    at com.github.mesayah.assistance.AssistanceApplication.main(AssistanceApplication.java:20) [classes/:na]
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.persistenceException(EntityManagerFactoryBuilderImpl.java:954) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:882) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
    at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:60) ~[spring-orm-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:353) ~[spring-orm-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:370) ~[spring-orm-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:359) ~[spring-orm-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    ... 16 common frames omitted
Caused by: org.hibernate.MappingException: Repeated column in mapping for entity: com.github.mesayah.assistance.model.Task column: task_id (should be mapped with insert="false" update="false")
    at org.hibernate.mapping.PersistentClass.checkColumnDuplication(PersistentClass.java:830) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.mapping.PersistentClass.checkPropertyColumnDuplication(PersistentClass.java:848) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.mapping.PersistentClass.checkColumnDuplication(PersistentClass.java:870) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.mapping.PersistentClass.validate(PersistentClass.java:605) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.mapping.RootClass.validate(RootClass.java:265) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.boot.internal.MetadataImpl.validate(MetadataImpl.java:329) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:443) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:879) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
    ... 22 common frames omitted
</code>```

So I think the problem is with private Task parentTask; or private Set<User> asigneeUsers; because only these members use mapping for "task_id". But I can't figure out what in particular is wrong with this code.

答:
The error that you are seeing:

```
Repeated column in mapping for entity:
com.github.mesayah.assistance.model.Task column: task_id
(should be mapped with insert="false" update="false")
```

This tells you that the column task_id inside the entity Task has been associated with more than one property.

You can associate the same column to multiple properties in a mapping;
however, only one of the mappings can control the persistence behavior while the others are read-only.

As a trivial example:

```<code>public class MyEntity {
  @Column(name = "NAME")
  private String name;
  @Column(name = "NAME", insertable = false, updatable = false)
  private String name2;
}
</code>```

The property name in this example will always be inserted and updated.  This property controls the persistence of the column NAME.  The property name2 will never be inserted nor updated and simply acts as a read-only field for column NAME.

If I had not included insertable = false, updatable = false on the column mapping, then Hibernate would have given the same error message you're seeing.

Now that you understand the technical reasons of the error message, your problem is as Maciej Kowalski mentions.  You should likely have mapped your parent reference differently:

```<code>@ManyToOne
@Column(name = "parent_task_id")
private Task parentTask;
</code>```

Conceptually, what you're looking for is your child Task which has a column task_id to also have a second column that references the foreign-key to the parent Task.  This foreign key must be stored in a new column, aptly named parent_task_id.

Body:
I'm making Spring application with Hibernate and I'm just trying to get relations between my entities working. I set up annotations for all foreign keys and now I get "Repeated column in mapping for entity" error. I was trying to find a solution here on SO, but I didn't really understand some of the answers and I don't think they are applicable to my code. I had this problem earlier with another project, where all ID fields were named just id and when I explicitly defined column name by @Column(name = "") and typed that name in @JoinColumn parameters it worked. Now I had the same error, but defining explicit names for ID fields didn't help.

Here's my entity class:

@Entity
public class Task implements Serializable, Discussable {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "task_id")
    private long id;

    private String name;

    @ManyToMany
    @JoinTable(
            name = "user_task",
            joinColumns = @JoinColumn(name = "task_id"),
            inverseJoinColumns = @JoinColumn(name = "user_id")
    )
    private Set<User> assigneeUsers;

    @Enumerated(EnumType.ORDINAL)
    private Status status; //alt + enter

    private Priority priority;

    private Date deadline;

    private String description;

    @ManyToOne
    @JoinColumn(name = "task_id")
    private Task parentTask;

    @OneToMany(mappedBy = "parentTask")
    private Set<Task> subtasks;

    @Enumerated(EnumType.ORDINAL)
    private Type type;

    @OneToOne(cascade = CascadeType.REMOVE)
    @JoinColumn(name = "channel_id")
    private Channel channel;

    @ManyToOne
    @JoinColumn(name = "project_id")
    private Project project;

// getters, setters and default constructor

The result I get when trying to compile is:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1078) ~[spring-context-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:857) ~[spring-context-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543) ~[spring-context-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693) [spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360) [spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:303) [spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1118) [spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1107) [spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
    at com.github.mesayah.assistance.AssistanceApplication.main(AssistanceApplication.java:20) [classes/:na]
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.persistenceException(EntityManagerFactoryBuilderImpl.java:954) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:882) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
    at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:60) ~[spring-orm-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:353) ~[spring-orm-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:370) ~[spring-orm-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:359) ~[spring-orm-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    ... 16 common frames omitted
Caused by: org.hibernate.MappingException: Repeated column in mapping for entity: com.github.mesayah.assistance.model.Task column: task_id (should be mapped with insert="false" update="false")
    at org.hibernate.mapping.PersistentClass.checkColumnDuplication(PersistentClass.java:830) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.mapping.PersistentClass.checkPropertyColumnDuplication(PersistentClass.java:848) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.mapping.PersistentClass.checkColumnDuplication(PersistentClass.java:870) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.mapping.PersistentClass.validate(PersistentClass.java:605) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.mapping.RootClass.validate(RootClass.java:265) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.boot.internal.MetadataImpl.validate(MetadataImpl.java:329) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:443) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:879) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
    ... 22 common frames omitted

So I think the problem is with private Task parentTask; or private Set<User> asigneeUsers; because only these members use mapping for "task_id". But I can't figure out what in particular is wrong with this code.

Body:
The error that you are seeing:

Repeated column in mapping for entity:
com.github.mesayah.assistance.model.Task column: task_id
(should be mapped with insert="false" update="false")

This tells you that the column task_id inside the entity Task has been associated with more than one property.

You can associate the same column to multiple properties in a mapping;
however, only one of the mappings can control the persistence behavior while the others are read-only.

As a trivial example:

public class MyEntity {
  @Column(name = "NAME")
  private String name;
  @Column(name = "NAME", insertable = false, updatable = false)
  private String name2;
}

The property name in this example will always be inserted and updated.  This property controls the persistence of the column NAME.  The property name2 will never be inserted nor updated and simply acts as a read-only field for column NAME.

If I had not included insertable = false, updatable = false on the column mapping, then Hibernate would have given the same error message you're seeing.

Now that you understand the technical reasons of the error message, your problem is as Maciej Kowalski mentions.  You should likely have mapped your parent reference differently:

@ManyToOne
@Column(name = "parent_task_id")
private Task parentTask;

Conceptually, what you're looking for is your child Task which has a column task_id to also have a second column that references the foreign-key to the parent Task.  This foreign key must be stored in a new column, aptly named parent_task_id.


问:
SQL -How to recreate this logic using a sql case statement in side a where clause
I'm still in learning phase, please help me in getting the following query resolved:

I got a logic in one query as:

```<code>select val =
                CASE
                    WHEN tbl.ReqNo LIKE '456%'  THEN 'Value A'
                    ELSE 'Value B'
                END
   From tblA tbl
</code>```

Now I need to use this logic to filter another query:

```<code>   SELECT    B.col1, A.col1, A.col2
   FROM
   tblB B
   INNER JOIN tblA A
   ON B.ID = A.ID
   WHERE
   B.BID = 123
   AND B.BName = "sth"
   AND B.Address = "123 St ..."
</code>```

Can anyone help me on how I can use the case statement logic in the second query's WHERE clause to filter the results.

答:
try this </p>

```<code> SELECT    B.col1, A.col1, A.col2
   FROM
   tblB B
   INNER JOIN tblA A
   ON B.ID = A.ID
   WHERE
   B.BID = 123
   AND B.BName = "sth"
   AND B.Address = "123 St ..." and
   ColumnName = CASE
                WHEN tblA.BName LIKE '456%'  THEN 'Value A'
                ELSE 'Value B'
            END
</code>```

<p>but i do not recommend use case in where </p>

Body:
I'm still in learning phase, please help me in getting the following query resolved:

I got a logic in one query as:

select val =
                CASE
                    WHEN tbl.ReqNo LIKE '456%'  THEN 'Value A'
                    ELSE 'Value B'
                END
   From tblA tbl

Now I need to use this logic to filter another query:

   SELECT    B.col1, A.col1, A.col2
   FROM
   tblB B
   INNER JOIN tblA A
   ON B.ID = A.ID
   WHERE
   B.BID = 123
   AND B.BName = "sth"
   AND B.Address = "123 St ..."

Can anyone help me on how I can use the case statement logic in the second query's WHERE clause to filter the results.

Body:
try this

 SELECT    B.col1, A.col1, A.col2
   FROM
   tblB B
   INNER JOIN tblA A
   ON B.ID = A.ID
   WHERE
   B.BID = 123
   AND B.BName = "sth"
   AND B.Address = "123 St ..." and
   ColumnName = CASE
                WHEN tblA.BName LIKE '456%'  THEN 'Value A'
                ELSE 'Value B'
            END

but i do not recommend use case in where


问:
How can I access a single cell from a range of cells stored in a series.xvalues?
The backstory of why I'm trying to do this is because I need to place callout labels at the peaks of local maximas, but the values need to be the x-values and not the y-values.

I have tried doing this multiple way, most recently like this:

```<code>Dim c As Chart

Set c = sht.Shapes.AddChart.Chart

With c
    .ChartType = xlXYScatterLinesNoMarkers
    .SeriesCollection(8).Name = "Data Labels"
    .SeriesCollection(8).XValues = Range(sht.Cells(start, 2), sht.Cells(ender, 2))
    .SeriesCollection(8).Values = Range(sht.Cells(start, 9), sht.Cells(ender, 9))
    .SeriesCollection(8).Format.Line.Visible = msoFalse
End With

For i = 1 To c.SeriesCollection(8).Points.count

    c.SeriesCollection(8).Points(i).HasDataLabel = True
    c.SeriesCollection(8).Points(i).DataLabel.Position = xlLabelPositionAbove
    c.SeriesCollection(8).Points(i).DataLabel.Format.AutoShapeType = msoShapeRectangularCallout
    c.SeriesCollection(8).Points(i).DataLabel.Format.Line.Visible = msoTrue
error--->c.SeriesCollection(8).Points(i).DataLabel.Text = c.SeriesCollection(8).XValues.Cells(i, 1)

Next i
</code>```

This returns an error "Object Required"

I have also tried

```<code>c.SeriesCollection(8).Points(i).DataLabel.Text = c.SeriesCollection(8).XValues(i)
c.SeriesCollection(8).Points(i).DataLabel.Text = c.SeriesCollection(8).XValues(i).value
</code>```

And A few more that I am most likely forgetting off of the top of my head.

What I really want and need is to retrieve the value located in the "i" position of c.SeriesCollection(8).XValues

Thanks for any help.

答:
XValues returns a Variant array (not a Range), but for some reason this throws an error:

```<code>Debug.Print ActiveSheet.ChartObjects(1).Chart.SeriesCollection(1).XValues(1)
</code>```

Run-time error '451':Property let procedure not defined and property
  get procedure did not return an object

Whereas this works just fine:

```<code>Sub Tester()

    Dim v, i
    v = ActiveSheet.ChartObjects(1).Chart.SeriesCollection(1).XValues

    For i = LBound(v) To UBound(v)
        Debug.Print "Point#" & i, v(i)
    Next i

End Sub
</code>```

Body:
The backstory of why I'm trying to do this is because I need to place callout labels at the peaks of local maximas, but the values need to be the x-values and not the y-values.

I have tried doing this multiple way, most recently like this:

Dim c As Chart

Set c = sht.Shapes.AddChart.Chart

With c
    .ChartType = xlXYScatterLinesNoMarkers
    .SeriesCollection(8).Name = "Data Labels"
    .SeriesCollection(8).XValues = Range(sht.Cells(start, 2), sht.Cells(ender, 2))
    .SeriesCollection(8).Values = Range(sht.Cells(start, 9), sht.Cells(ender, 9))
    .SeriesCollection(8).Format.Line.Visible = msoFalse
End With

For i = 1 To c.SeriesCollection(8).Points.count

    c.SeriesCollection(8).Points(i).HasDataLabel = True
    c.SeriesCollection(8).Points(i).DataLabel.Position = xlLabelPositionAbove
    c.SeriesCollection(8).Points(i).DataLabel.Format.AutoShapeType = msoShapeRectangularCallout
    c.SeriesCollection(8).Points(i).DataLabel.Format.Line.Visible = msoTrue
error--->c.SeriesCollection(8).Points(i).DataLabel.Text = c.SeriesCollection(8).XValues.Cells(i, 1)

Next i

This returns an error "Object Required"

I have also tried

c.SeriesCollection(8).Points(i).DataLabel.Text = c.SeriesCollection(8).XValues(i)
c.SeriesCollection(8).Points(i).DataLabel.Text = c.SeriesCollection(8).XValues(i).value

And A few more that I am most likely forgetting off of the top of my head.

What I really want and need is to retrieve the value located in the "i" position of c.SeriesCollection(8).XValues

Thanks for any help.

Body:
XValues returns a Variant array (not a Range), but for some reason this throws an error:

Debug.Print ActiveSheet.ChartObjects(1).Chart.SeriesCollection(1).XValues(1)

Run-time error '451':Property let procedure not defined and property
  get procedure did not return an object

Whereas this works just fine:

Sub Tester()

    Dim v, i
    v = ActiveSheet.ChartObjects(1).Chart.SeriesCollection(1).XValues

    For i = LBound(v) To UBound(v)
        Debug.Print "Point#" & i, v(i)
    Next i

End Sub


问:
Start sleuth tracing at invocation of managed operation
I have a set of microservices but the call chain doesn't start with http. It starts with the invocation of a @ManagedOperation via JMX. The issue with this is that the invocation of this method doesn't start a trace.

Anyone know how to start the trace when a @ManagedOperation is invoked via JMX?

答: This can be accomplished by using @NewSpan on the @ManagedOperation method. I tried to use this previously but STS (spring tool suite) was having issues with the classpath so it wouldn't pull the import.</p>


问:
Manipulate (root) Files from (subdomain)
Domain: domain.com
Subdomain: sub.domain.com

My HTML page on (subdomain) needs to show image from (root) folder "../../../httpdocs/images/".

User can change that image, so he chose new image and submits the form to the PHP script on (subdomain).

PHP script on (subdomain) check's the posted image and resizes it and if all ok...

```<code>if (imagegif($thenewimage,"../../../httpdocs/images/test.gif",100))
{
   header("location: index.php?success=true");
}
</code>```

then it need's to save it to (root) domain.

how to acomplish that? :(

Thanks!

答:
With copy you can copy a file.

http://www.php.net/copy

ContentLicense: CC BY-SA 2.5

Body:
Domain: domain.com
Subdomain: sub.domain.com

My HTML page on (subdomain) needs to show image from (root) folder "../../../httpdocs/images/".

User can change that image, so he chose new image and submits the form to the PHP script on (subdomain).

PHP script on (subdomain) check's the posted image and resizes it and if all ok...

if (imagegif($thenewimage,"../../../httpdocs/images/test.gif",100))
{
   header("location: index.php?success=true");
}

then it need's to save it to (root) domain.

how to acomplish that? :(

Thanks!


问:
Can Visual Studio access TeamCity symbol server if basic auth is rquired?
I have TeamCity symbol server plugin working and can pull symbols & source from VS2017 as expected as long as I allow guest login in TeamCity and guest has appropriate rights.

However, the required rights are quite permissive (allows downloading source code).  This is a private, commercial team, so I don't want to allow public/guest access.  I'd like it to be authenticated, but can't seem to get VS2017 to prompt for credentials or pass them on the URL configured in VS2017's Debugging>Symbols settings (https://user:pass@my.teamcity.com).  The output window always shows "Symbol server authentication failed".

Not sure if it's a limitation of VS or I'm not configuring it properly.  Does anyone know if/how this is possible?

答:
This is now fixed in 15.5.  It's not listed in the release notes as far as I can tell, but a MS rep commented that it was fixed in 15.5, so I gave it a try.

After I installed 15.5, it didn't prompt me for credentials at first.  So I deleted/re-added the symbol server setting and cleaned the symbol cache.  Then on the next run it prompted me for credentials, successfully downloaded the symbols and allowed me to debug the assembly.


问:
Regex to Capture last email Address
I need a regex to capture last email addresss

2017-11-30T17:00:02.596Z,10.1.20.211,RenjuXXX,X.X.X.X,mxa-0003fe01.xx.renjj.com,;250 2.0.0 2ej1k6mass-1 Message accepted for delivery;ClientSubmitTime:,Outbound to Internet,SMTP,SEND,asadasdasd1212,,b4b8c0b5-ce3b-4aca-8335-08d53813c96a,Jose.renj@renj.org,250 2.1.5 Recipient ok,41758,1,,,RE: my CV,renjujacob@renju.com,renjujacob@renju.com,

I tried using this regex below to capture the email ID , but its capturing the first email

((?P(?<=,)[a-zA-Z0-9-.]+@[a-zA-Z0-9-.]+(?=\s*(?:\w+=|,))))

need a regex to capture last email id (renjujacob@renju.com). Any help will be appreciated.

答:
```<code>.*((?<=,)[a-zA-Z0-9-.]+@[a-zA-Z0-9-.]+(?=\s*(?:\w+=|,)))
</code>```

.* matches any character (except for line terminators)

Quantifier — Matches between zero and unlimited times, as many times as possible, giving back as needed (greedy) [this greediness allows to return the LAST occurrence for group 1]

1st Capturing Group ((?<=,)[a-zA-Z0-9-.]+@[a-zA-Z0-9-.]+(?=\s*(?:\w+=|,))) :

Positive Lookbehind (?<=,)

Assert that the Regex below matches

, matches the character , literally (case sensitive)

Match a single character present in the list below [a-zA-Z0-9-.]+

Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)

a-z a single character in the range between a (index 97) and z (index 122) (case sensitive)

A-Z a single character in the range between A (index 65) and Z (index 90) (case sensitive)

0-9 a single character in the range between 0 (index 48) and 9 (index 57) (case sensitive)

-. matches a single character in the list -. (case sensitive)

@ matches the character @ literally (case sensitive)

Match a single character present in the list below [a-zA-Z0-9-.]+:

Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)

a-z a single character in the range between a (index 97) and z (index 122) (case sensitive)

A-Z a single character in the range between A (index 65) and Z (index 90) (case sensitive)

0-9 a single character in the range between 0 (index 48) and 9 (index 57) (case sensitive)

-. matches a single character in the list -. (case sensitive)
Positive Lookahead (?=\s*(?:\w+=|,))

Assert that the Regex below matches:

\s* matches any whitespace character (equal to [\r\n\t\f\v ])

Non-capturing group (?:\w+=|,)

Global pattern flags
g modifier: global. All matches (don't return after the first match)

https://regex101.com/r/nWgDSy/1

Title: Regex to Capture last email Address

Body:
.*((?<=,)[a-zA-Z0-9-.]+@[a-zA-Z0-9-.]+(?=\s*(?:\w+=|,)))

.* matches any character (except for line terminators)

Quantifier — Matches between zero and unlimited times, as many times as possible, giving back as needed (greedy) [this greediness allows to return the LAST occurrence for group 1]

1st Capturing Group ((?<=,)[a-zA-Z0-9-.]+@[a-zA-Z0-9-.]+(?=\s*(?:\w+=|,))) :

Positive Lookbehind (?<=,)

Assert that the Regex below matches

, matches the character , literally (case sensitive)

Match a single character present in the list below [a-zA-Z0-9-.]+

Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)

a-z a single character in the range between a (index 97) and z (index 122) (case sensitive)

A-Z a single character in the range between A (index 65) and Z (index 90) (case sensitive)

0-9 a single character in the range between 0 (index 48) and 9 (index 57) (case sensitive)

-. matches a single character in the list -. (case sensitive)

@ matches the character @ literally (case sensitive)

Match a single character present in the list below [a-zA-Z0-9-.]+:

Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)

a-z a single character in the range between a (index 97) and z (index 122) (case sensitive)

A-Z a single character in the range between A (index 65) and Z (index 90) (case sensitive)

0-9 a single character in the range between 0 (index 48) and 9 (index 57) (case sensitive)

-. matches a single character in the list -. (case sensitive)
Positive Lookahead (?=\s*(?:\w+=|,))

Assert that the Regex below matches:

\s* matches any whitespace character (equal to [\r\n\t\f\v ])

Non-capturing group (?:\w+=|,)

Global pattern flags
g modifier: global. All matches (don't return after the first match)

https://regex101.com/r/nWgDSy/1


问:
Zendframework 3 - Overwrite CSRF Validator
I try to migrate from ZF2 to ZF3 but many viewHelpers and validators do not work. But only the ones who overwrite ZendFrameworks viewhelpers / validators do not work...

I want f.e. to overwrite the CSRF validator to allow a higher timeout by default.

I have the following application configuration:

```<code>$config = array(
// This should be an array of module namespaces used in the application.
'modules' => array(
    'Zend\Cache',
    'Zend\Db',
    'Zend\Log',
    'Zend\Mail',
    'Zend\Mvc\Console',
    'Zend\Mvc\I18n',
    'Zend\I18n',
    'Zend\Mvc\Plugin\FilePrg',
    'Zend\Form',
    'Zend\Hydrator',
    'Zend\InputFilter',
    'zend\Form',
    'Zend\Filter',
    'Zend\Mvc\Plugin\FlashMessenger',
    'Zend\Mvc\Plugin\Identity',
    'Zend\Mvc\Plugin\Prg',
    'Zend\Navigation',
    'Zend\Paginator',
    'Zend\Serializer',
    'Zend\ServiceManager\Di',
    'Zend\Session',
    'Zend\Router',
    'Zend\Validator',
    'DoctrineModule',
    'DoctrineORMModule',
    'TwbBundle',
    'AssetManager',
    #'Reliv\ElFinder',
    'ZfcUser', //https://github.com/ZF-Commons/ZfcUser
    'ZfcUserDoctrineORM',
    'BjyAuthorize', // https://github.com/bjyoungblood/BjyAuthorize
    'Base',
    'Product',
    'Blog',
    'Admin'
),

// These are various options for the listeners attached to the ModuleManager
'module_listener_options' => array(
    // This should be an array of paths in which modules reside.
    // If a string key is provided, the listener will consider that a module
    // namespace, the value of that key the specific path to that module's
    // Module class.
    'module_paths' => array(
        './module',
        './vendor',
    ),

    // An array of paths from which to glob configuration files after
    // modules are loaded. These effectively override configuration
    // provided by modules themselves. Paths may use GLOB_BRACE notation.
    'config_glob_paths' => array(
        'config/autoload/{,*.}{global,local}.php',
    ),

    // Whether or not to enable a configuration cache.
    // If enabled, the merged configuration will be cached and used in
    // subsequent requests.
    // 'config_cache_enabled' => true,

    // The key used to create the configuration cache file name.
    //'config_cache_key' => $stringKey,

    // Whether or not to enable a module class map cache.
    // If enabled, creates a module class map cache which will be used
    // by in future requests, to reduce the autoloading process.
    // 'module_map_cache_enabled' => true,

    // The key used to create the class map cache file name.
    #'module_map_cache_key' => $stringKey,

    // The path in which to cache merged configuration.
    'cache_dir' => "data/cache/",

    // Whether or not to enable modules dependency checking.
    // Enabled by default, prevents usage of modules that depend on other modules
    // that weren't loaded.
    // 'check_dependencies' => true,
),

// Used to create an own service manager. May contain one or more child arrays.
//'service_listener_options' => array(
//     array(
//         'service_manager' => $stringServiceManagerName,
//         'config_key'      => $stringConfigKey,
//         'interface'       => $stringOptionalInterface,
//         'method'          => $stringRequiredMethodName,
//     ),
// )

// Initial configuration with which to seed the ServiceManager.
// Should be compatible with Zend\ServiceManager\Config.
// 'service_manager' => array(),
);
</code>```

Module config of Base module:

```<code>namespace Base;
...
return [
    ...
    'validators' => array(
        'invokables' => [
            \Zend\Validator\Csrf::class => Validator\Csrf::class
        ]
    )
    ...
]
</code>```

Base\Validator\Csrf:

```<code><?php

namespace Base\Validator;

class Csrf extends \Zend\Validator\Csrf
{
    protected $timeout = 1;

    public function __construct($options = [])
    {
        parent::__construct($options);

        die("THIS DOES NOT GETTING PRINTED! NOR DOES THE BREAKPOINT HIT.");
    }
}
</code>```

EDIT: Added autoload config

composer.json:

```<code>"autoload": {
    "psr-4": {
      "Base\\": "module/Base/src/"
    }
  }
</code>```

EDIT 2: Possible bug in implementation of \Zend\Form\Element\Csrf ?

Interesting, the CsrfValidator just gets directly instantiated here...

```<code>/**
 * Get CSRF validator
 *
 * @return CsrfValidator
 */
public function getCsrfValidator()
{
    if (null === $this->csrfValidator) {
        $csrfOptions = $this->getCsrfValidatorOptions();
        $csrfOptions = array_merge($csrfOptions, ['name' => $this->getName()]);
        $this->setCsrfValidator(new CsrfValidator($csrfOptions));
    }
    return $this->csrfValidator;
}
</code>```

Stacktrace (breakpoint in \Zend\Validator\Csrf __construct())

StaticPage is another module of mine.

I also debugged with xdebug and set a break point in the CsrfFactory (return statement) to see, if it is used (but it isn't).
I thought I can overwrite services / validators etc. easily in ZF3... Did I miss something?

答:
You can use a delegator to change the validator attached to the form element when the element is instantiated.  Essentially a delegator allows you (in this case) to modify the form element after it has been constructed - the idea is explained well here.

In your case you would create a class:

```<code><?php

namespace Base\Delegator;

use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\ServiceManager\DelegatorFactoryInterface;
use Zend\Validator\Csrf as CsrfValidator;

class CsrfDelegatorFactory implements DelegatorFactoryInterface
{
    public function createDelegatorWithName(ServiceLocatorInterface $serviceLocator, $name, $requestedName, $callback)
    {
        // construct the Csrf form element
        $element = call_user_func($callback);

        // set the validator with chosen timeout and other options
        $element->setCsrfValidator(new CsrfValidator(
            [
                // ...
                'timeout' => 10000
            ]
        ));

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

Then map the delegator to Zend\Form\Element\Csrf in your application module.config.php:

```<code>'form_elements' => [
    // ...
    'delegators' => [
        \Zend\Form\Element\Csrf::class => [
            0 => \Base\Delegator\CsrfDelegatorFactory::class
        ],
    ]
],
</code>```

Note that this is only changing the validator assigned by default to a Zend\Form\Element\Csrf and a csrf validator obtained by other means will not be affected.

Body:
I try to migrate from ZF2 to ZF3 but many viewHelpers and validators do not work. But only the ones who overwrite ZendFrameworks viewhelpers / validators do not work...

I want f.e. to overwrite the CSRF validator to allow a higher timeout by default.

I have the following application configuration:

$config = array(
// This should be an array of module namespaces used in the application.
'modules' => array(
    'Zend\Cache',
    'Zend\Db',
    'Zend\Log',
    'Zend\Mail',
    'Zend\Mvc\Console',
    'Zend\Mvc\I18n',
    'Zend\I18n',
    'Zend\Mvc\Plugin\FilePrg',
    'Zend\Form',
    'Zend\Hydrator',
    'Zend\InputFilter',
    'zend\Form',
    'Zend\Filter',
    'Zend\Mvc\Plugin\FlashMessenger',
    'Zend\Mvc\Plugin\Identity',
    'Zend\Mvc\Plugin\Prg',
    'Zend\Navigation',
    'Zend\Paginator',
    'Zend\Serializer',
    'Zend\ServiceManager\Di',
    'Zend\Session',
    'Zend\Router',
    'Zend\Validator',
    'DoctrineModule',
    'DoctrineORMModule',
    'TwbBundle',
    'AssetManager',
    #'Reliv\ElFinder',
    'ZfcUser', //https://github.com/ZF-Commons/ZfcUser
    'ZfcUserDoctrineORM',
    'BjyAuthorize', // https://github.com/bjyoungblood/BjyAuthorize
    'Base',
    'Product',
    'Blog',
    'Admin'
),

// These are various options for the listeners attached to the ModuleManager
'module_listener_options' => array(
    // This should be an array of paths in which modules reside.
    // If a string key is provided, the listener will consider that a module
    // namespace, the value of that key the specific path to that module's
    // Module class.
    'module_paths' => array(
        './module',
        './vendor',
    ),

    // An array of paths from which to glob configuration files after
    // modules are loaded. These effectively override configuration
    // provided by modules themselves. Paths may use GLOB_BRACE notation.
    'config_glob_paths' => array(
        'config/autoload/{,*.}{global,local}.php',
    ),

    // Whether or not to enable a configuration cache.
    // If enabled, the merged configuration will be cached and used in
    // subsequent requests.
    // 'config_cache_enabled' => true,

    // The key used to create the configuration cache file name.
    //'config_cache_key' => $stringKey,

    // Whether or not to enable a module class map cache.
    // If enabled, creates a module class map cache which will be used
    // by in future requests, to reduce the autoloading process.
    // 'module_map_cache_enabled' => true,

    // The key used to create the class map cache file name.
    #'module_map_cache_key' => $stringKey,

    // The path in which to cache merged configuration.
    'cache_dir' => "data/cache/",

    // Whether or not to enable modules dependency checking.
    // Enabled by default, prevents usage of modules that depend on other modules
    // that weren't loaded.
    // 'check_dependencies' => true,
),

// Used to create an own service manager. May contain one or more child arrays.
//'service_listener_options' => array(
//     array(
//         'service_manager' => $stringServiceManagerName,
//         'config_key'      => $stringConfigKey,
//         'interface'       => $stringOptionalInterface,
//         'method'          => $stringRequiredMethodName,
//     ),
// )

// Initial configuration with which to seed the ServiceManager.
// Should be compatible with Zend\ServiceManager\Config.
// 'service_manager' => array(),
);

Module config of Base module:

namespace Base;
...
return [
    ...
    'validators' => array(
        'invokables' => [
            \Zend\Validator\Csrf::class => Validator\Csrf::class
        ]
    )
    ...
]

Base\Validator\Csrf:

<?php

namespace Base\Validator;

class Csrf extends \Zend\Validator\Csrf
{
    protected $timeout = 1;

    public function __construct($options = [])
    {
        parent::__construct($options);

        die("THIS DOES NOT GETTING PRINTED! NOR DOES THE BREAKPOINT HIT.");
    }
}

EDIT: Added autoload config

composer.json:

"autoload": {
    "psr-4": {
      "Base\\": "module/Base/src/"
    }
  }

EDIT 2: Possible bug in implementation of \Zend\Form\Element\Csrf ?

Interesting, the CsrfValidator just gets directly instantiated here...

/**
 * Get CSRF validator
 *
 * @return CsrfValidator
 */
public function getCsrfValidator()
{
    if (null === $this->csrfValidator) {
        $csrfOptions = $this->getCsrfValidatorOptions();
        $csrfOptions = array_merge($csrfOptions, ['name' => $this->getName()]);
        $this->setCsrfValidator(new CsrfValidator($csrfOptions));
    }
    return $this->csrfValidator;
}

Stacktrace (breakpoint in \Zend\Validator\Csrf __construct())

StaticPage is another module of mine.

I also debugged with xdebug and set a break point in the CsrfFactory (return statement) to see, if it is used (but it isn't).
I thought I can overwrite services / validators etc. easily in ZF3... Did I miss something?

Body:
You can use a delegator to change the validator attached to the form element when the element is instantiated.  Essentially a delegator allows you (in this case) to modify the form element after it has been constructed - the idea is explained well here.

In your case you would create a class:

<?php

namespace Base\Delegator;

use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\ServiceManager\DelegatorFactoryInterface;
use Zend\Validator\Csrf as CsrfValidator;

class CsrfDelegatorFactory implements DelegatorFactoryInterface
{
    public function createDelegatorWithName(ServiceLocatorInterface $serviceLocator, $name, $requestedName, $callback)
    {
        // construct the Csrf form element
        $element = call_user_func($callback);

        // set the validator with chosen timeout and other options
        $element->setCsrfValidator(new CsrfValidator(
            [
                // ...
                'timeout' => 10000
            ]
        ));

        return $element;
    }
}

Then map the delegator to Zend\Form\Element\Csrf in your application module.config.php:

'form_elements' => [
    // ...
    'delegators' => [
        \Zend\Form\Element\Csrf::class => [
            0 => \Base\Delegator\CsrfDelegatorFactory::class
        ],
    ]
],

Note that this is only changing the validator assigned by default to a Zend\Form\Element\Csrf and a csrf validator obtained by other means will not be affected.


问:
Access attributes of objects in a list
I'm using a book called Python for Absolute Beginners and am doing a challenge in the book's chapter 8 (Software Objects). My  code works but I want to add another capability to the code; What code do I need to add to feed/play/talk with a specific critter?

In choice #7 of my code (7 - Feed a specific critter), I have written some code but it doesn't work. How might I access/change the attributes of a specific object that the user selects?

Also, any feedback to improve/shorten the code?

```<code># Critter Caretaker
# A virtual pet to care for
class Critter(object):
    import random
    """A virtual pet"""
    def __init__(self, name, hunger = random.randint(0,9), boredom = random.randint(0,11)):
        self.name = name
        self.hunger = hunger
        self.boredom = boredom

    def __pass_time(self):
        self.hunger +=1
        self.boredom +=1

    def __str__(self):

        m = "name is: {}, hunger is: {}, boredom is: {}".format(self.name, self.hunger,self.boredom)

        return m

    @property
    def mood(self):
        unhappiness = self.hunger + self.boredom
        if unhappiness <5:
            m = "happy"
        elif 5 <= unhappiness <=10:
            m = "okay"
        elif 11 <= unhappiness <=15:
            m = "frustrated"
        else:
            m= "mad"
        return m

    def talk(self):
        print("I'm", self.name, "and I feel", self.mood, "now.\n")
        self.__pass_time()

    def eat(self, food=3):
        print("Yummy! Thank you.")
        self.hunger -=food
        if self.hunger <0:
            self.hunger = 0
        self.__pass_time()

    def play(self, fun=4):

        print("That was fun! Thanks")
        self.boredom -=fun
        if self.boredom <0:
            self.boredom = 0
        self.__pass_time()

def main():
    noc = []
    noc.append(Critter("Chicken"))
    print("An critter named Chicken has been created")
    choice = None
    while choice != "0":
        print \
        ("""
        Critter Caretaker

        0 - Quit
        1 - Listen to all your critters
        2 - Feed all your critters
        3 - Play with all your critters
        4 - Create a new critter
        5 - Show a list of critters
        6 - Delete a critter
        7 - Feed a specific critter
        """)

        choice = input("Choice: ")
        print()

        # exit
        if choice == "0":
            print("Good-bye.")

        # listen to critters
        elif choice == "1":
            if len(noc) != 0:
                i.talk()
            else:
                print("No critters exist")
        # feed your critters
        elif choice == "2":
            if len(noc) != 0:
                for i in noc:
                    print(i.name, "says:", end = " ")
                    i.eat()
        # play with your critters
        elif choice == "3":
            if len(noc) != 0:
                for i in noc:
                    print(i.name, "says:", end = " ")
                    i.play()
            else:
                print("No critter exists")
        # Create a new critter
        elif choice == "4":
            noc.append(Critter(input("Enter a name for your new critter: ")))
        # Show critters
        elif choice =="5":
            b = 0
            if len(noc) != 0:
                for i in noc:
                    b +=1
                    print(b, "." ,i.name)
            else:
                print("No critter exists")
        # delete a critter
        elif choice == "6":
            a = int(input("Enter the serial number of critter you want to delete: "))
            a = a -1
            del noc[a]

        # feed a specific critter
        elif choice == "7":
            sctd = input("Enter name of critter you want to feed: ")
            if sctd in noc:
                noc.eat()
            else:
                print("That critter doesn't exists")

        # print attributes of critters
        elif choice == "919":
            for i in noc:
                print(i)
        else:
            print("\nSorry, but", choice, "isn't valid.")

main()
("\n\nPress the enter key to exit.")
</code>```

答: Just a small note is that I think the convention something like import random should probably be placed at the start rather than inside the class which also gets rid of the problem raised by @nthall which is that your docstring is currently not the first object.

Title: Access attributes of objects in a list

Body:
I'm using a book called Python for Absolute Beginners and am doing a challenge in the book's chapter 8 (Software Objects). My  code works but I want to add another capability to the code; What code do I need to add to feed/play/talk with a specific critter?

In choice #7 of my code (7 - Feed a specific critter), I have written some code but it doesn't work. How might I access/change the attributes of a specific object that the user selects?

Also, any feedback to improve/shorten the code?

# Critter Caretaker
# A virtual pet to care for
class Critter(object):
    import random
    """A virtual pet"""
    def __init__(self, name, hunger = random.randint(0,9), boredom = random.randint(0,11)):
        self.name = name
        self.hunger = hunger
        self.boredom = boredom

    def __pass_time(self):
        self.hunger +=1
        self.boredom +=1

    def __str__(self):

        m = "name is: {}, hunger is: {}, boredom is: {}".format(self.name, self.hunger,self.boredom)

        return m

    @property
    def mood(self):
        unhappiness = self.hunger + self.boredom
        if unhappiness <5:
            m = "happy"
        elif 5 <= unhappiness <=10:
            m = "okay"
        elif 11 <= unhappiness <=15:
            m = "frustrated"
        else:
            m= "mad"
        return m

    def talk(self):
        print("I'm", self.name, "and I feel", self.mood, "now.\n")
        self.__pass_time()

    def eat(self, food=3):
        print("Yummy! Thank you.")
        self.hunger -=food
        if self.hunger <0:
            self.hunger = 0
        self.__pass_time()

    def play(self, fun=4):

        print("That was fun! Thanks")
        self.boredom -=fun
        if self.boredom <0:
            self.boredom = 0
        self.__pass_time()

def main():
    noc = []
    noc.append(Critter("Chicken"))
    print("An critter named Chicken has been created")
    choice = None
    while choice != "0":
        print \
        ("""
        Critter Caretaker

        0 - Quit
        1 - Listen to all your critters
        2 - Feed all your critters
        3 - Play with all your critters
        4 - Create a new critter
        5 - Show a list of critters
        6 - Delete a critter
        7 - Feed a specific critter
        """)

        choice = input("Choice: ")
        print()

        # exit
        if choice == "0":
            print("Good-bye.")

        # listen to critters
        elif choice == "1":
            if len(noc) != 0:
                i.talk()
            else:
                print("No critters exist")
        # feed your critters
        elif choice == "2":
            if len(noc) != 0:
                for i in noc:
                    print(i.name, "says:", end = " ")
                    i.eat()
        # play with your critters
        elif choice == "3":
            if len(noc) != 0:
                for i in noc:
                    print(i.name, "says:", end = " ")
                    i.play()
            else:
                print("No critter exists")
        # Create a new critter
        elif choice == "4":
            noc.append(Critter(input("Enter a name for your new critter: ")))
        # Show critters
        elif choice =="5":
            b = 0
            if len(noc) != 0:
                for i in noc:
                    b +=1
                    print(b, "." ,i.name)
            else:
                print("No critter exists")
        # delete a critter
        elif choice == "6":
            a = int(input("Enter the serial number of critter you want to delete: "))
            a = a -1
            del noc[a]

        # feed a specific critter
        elif choice == "7":
            sctd = input("Enter name of critter you want to feed: ")
            if sctd in noc:
                noc.eat()
            else:
                print("That critter doesn't exists")

        # print attributes of critters
        elif choice == "919":
            for i in noc:
                print(i)
        else:
            print("\nSorry, but", choice, "isn't valid.")

main()
("\n\nPress the enter key to exit.")


问:
C++ polymorphic ring buffer
Is there a library that would allow me to store objects of common base type in a buffer supporting enqueue and dequeue? That's really all I need, I don't need O(1) access to each element. It would be allowed that each object can have a different size (a polymorphic ring buffer).
I could use vector of pointers of base type, but that seems to me as an overkill. If I use this sort of a ring buffer, I won't have to allocate separate memory for each object.

答:
As mentioned by @JTejedor, boost poly collection solves your problem quite directly.

If for some reason you don't like boost, a simplistic solution with std::variant can be concocted

```<code>template<typename Base, typename... Derived>
struct poly
{
    std::variant<Base, Derived...> var;

    template<typename... Args>
    poly(Args&&... args) : var{std::forward<Args>(args)...} {}

    auto& get()
    {
        auto id = [](auto& v) -> Base& { return v; };
        return std::visit(id, var);
    }

    operator Base&() { return get(); }
};
</code>```

And use it as

```<code>struct B {};
struct D1 : B {};
struct D2 : B { int i; };

void foo()
{
    using poly_t = poly<B, D1, D2>;

    std::vector<poly_t> vec;
    vec.push_back(B{});
    vec.push_back(D1{});
    vec.push_back(D2{});

    B& ref = vec.back();
}
</code>```

Live

Title: C++ polymorphic ring buffer

Body:
As mentioned by @JTejedor, boost poly collection solves your problem quite directly.

If for some reason you don't like boost, a simplistic solution with std::variant can be concocted

template<typename Base, typename... Derived>
struct poly
{
    std::variant<Base, Derived...> var;

    template<typename... Args>
    poly(Args&&... args) : var{std::forward<Args>(args)...} {}

    auto& get()
    {
        auto id = [](auto& v) -> Base& { return v; };
        return std::visit(id, var);
    }

    operator Base&() { return get(); }
};

And use it as

struct B {};
struct D1 : B {};
struct D2 : B { int i; };

void foo()
{
    using poly_t = poly<B, D1, D2>;

    std::vector<poly_t> vec;
    vec.push_back(B{});
    vec.push_back(D1{});
    vec.push_back(D2{});

    B& ref = vec.back();
}

Live


问:
Limiting the scope of a transaction in Apache Camel
I have a transacted Camel route with a number of processors

```<code>from(Constant.RouteA)
   .transacted()
   .process(processor1)
   .process(processor2)
   .process(processor3)
   .wireTap(Constant.RouteB)
   .wireTap(Constant.RouteC)
   .end()
</code>```

My problem is that I don't want the final part of the route (the wiretaps) to be part of the transaction i.e. I want them to be executed once processor3 has finished and the transaction committed.

Initially I looked at using onCompletion() but it doesn't seem to work together with transacted().

So I found another way which requires using policy() to limit the transaction scope i.e.

```<code>from(Constant.RouteA)
   .policy("PROPAGATION_REQUIRED")
      .process(processor1)
      .process(processor2)
      .process(processor3)
   .end()
   .wireTap(Constant.RouteB)
   .wireTap(Constant.RouteC)
   .end()
</code>```

The problem is that this solution requires to define the SpringTransactionPolicy in the Spring configuration, but the software I'm working on doesn't use Spring. Transactions are managed by Bitronix and everything works just by using the transacted() method, which as far as I can tell doesn't allow you to limit the scope of a transaction.

Is there a simple way to achieve my goal? Hopefully without bringing Spring into the picture. Thank you!

答:
Try to create two routes. For example:

```<code>from(direct:startRoute)
      .to(Constant.RouteA)
      .wireTap(Constant.RouteB)
      .wireTap(Constant.RouteC);

from(Constant.RouteA)
      .transacted()
      .process(processor1)
      .process(processor2)
      .process(processor3);
</code>```

Once route "Constant.RouteA" is finished all changes will committed.

Body:
I have a transacted Camel route with a number of processors

from(Constant.RouteA)
   .transacted()
   .process(processor1)
   .process(processor2)
   .process(processor3)
   .wireTap(Constant.RouteB)
   .wireTap(Constant.RouteC)
   .end()

My problem is that I don't want the final part of the route (the wiretaps) to be part of the transaction i.e. I want them to be executed once processor3 has finished and the transaction committed.

Initially I looked at using onCompletion() but it doesn't seem to work together with transacted().

So I found another way which requires using policy() to limit the transaction scope i.e.

from(Constant.RouteA)
   .policy("PROPAGATION_REQUIRED")
      .process(processor1)
      .process(processor2)
      .process(processor3)
   .end()
   .wireTap(Constant.RouteB)
   .wireTap(Constant.RouteC)
   .end()

The problem is that this solution requires to define the SpringTransactionPolicy in the Spring configuration, but the software I'm working on doesn't use Spring. Transactions are managed by Bitronix and everything works just by using the transacted() method, which as far as I can tell doesn't allow you to limit the scope of a transaction.

Is there a simple way to achieve my goal? Hopefully without bringing Spring into the picture. Thank you!

Body:
Try to create two routes. For example:

from(direct:startRoute)
      .to(Constant.RouteA)
      .wireTap(Constant.RouteB)
      .wireTap(Constant.RouteC);

from(Constant.RouteA)
      .transacted()
      .process(processor1)
      .process(processor2)
      .process(processor3);

Once route "Constant.RouteA" is finished all changes will committed.


问:
select dropdown value matching to be case insensitive when prefilled
In Html template

```<code><select [(ngModel)]="modelName">
  <option *ngFor="let ele of elements" [value]="element">{{ele}}</option>
</select>
</code>```

In .ts file

```<code>this.elements = ['ABCd', 'mnOp'];
this.modelName = 'Abcd';
</code>```

I Expect the value of the modelName 'ABCd' to be preselected from the list.

Currently nothing is displayed in the Select box though the modelName contains value 'Abcd'

答:
The select's value is undefined because element is undefined so it is not able to match to the string 'Abcd'. To make the values lowcase I would map your element values to an object.

Should be:

```<code><select [(ngModel)]="modelName">
    <option *ngFor="let ele of elements" [value]="ele.value">{{ele.label}}</option>
</select>
</code>```

In the component:

this.elements = ['ABCd', 'mnOp'].map((v) => ({ value: v.toLowerCase(), label: v }));

this.modelName = 'abcd';
```

Body:
In Html template

<select [(ngModel)]="modelName">
  <option *ngFor="let ele of elements" [value]="element">{{ele}}</option>
</select>

In .ts file

this.elements = ['ABCd', 'mnOp'];
this.modelName = 'Abcd';

I Expect the value of the modelName 'ABCd' to be preselected from the list.

Currently nothing is displayed in the Select box though the modelName contains value 'Abcd'

Body:
The select's value is undefined because element is undefined so it is not able to match to the string 'Abcd'. To make the values lowcase I would map your element values to an object.

Should be:

<select [(ngModel)]="modelName">
    <option *ngFor="let ele of elements" [value]="ele.value">{{ele.label}}</option>
</select>

In the component:

this.elements = ['ABCd', 'mnOp'].map((v) => ({ value: v.toLowerCase(), label: v }));

this.modelName = 'abcd';


问:
How can I call a function of a C++ DLL that accepts a parameter of type stringstream from C#?
I want to import an unmanaged C++ DLL and call a function that takes stringstream as a parameter. In C#, there is no stringstream class, so can anyone tell me how to call such a function from a C# program?

答: You are trying to bind native C++ code to managed code in C#. Best way of doing that in general is to introduce middle layer in managed C++ that will provide interface to calls from C#.</p>


问:
infinite recursion on new InitialContext()
I am trying to setup JNDI for a Java SE console application.

I have the following code:

```<code>public class FooMain {

    public static void main (String args[]) throws NamingException {
        Context context = new InitialContext();
        context.bind("foo", "bar");
    }
}
</code>```

… and the context factory is defined as:

```<code>public class MyContextFactory implements InitialContextFactory {

    private static Hashtable store = new Hashtable();

    @Override
    public Context getInitialContext(Hashtable environment) throws NamingException {
        return new InitialContext() {

            @Override
            public void bind(String name, Object obj) {
                store.put(name, obj);
            }

            @Override
            public Object lookup(String name) {
                return store.get(name);
            }
        };
    }
}
</code>```

When I invoke my FooMain class using:

```<code>java -Djava.naming.factory.initial=MyContextFactory -cp ... FooMain
</code>```

I get infinite recursion and an eventual StackOverflow Exception:

```<code>Exception in thread "main" java.lang.StackOverflowError
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.naming.internal.VersionHelper12.getContextClassLoader(VersionHelper12.java:185)
at com.sun.naming.internal.ResourceManager.getApplicationResources(ResourceManager.java:549)
at com.sun.naming.internal.ResourceManager.getInitialEnvironment(ResourceManager.java:244)
at javax.naming.InitialContext.init(InitialContext.java:240)
at javax.naming.InitialContext.<init>(InitialContext.java:192)
at MyContextFactory$1.<init>(MyContextFactory.java:20)
at MyContextFactory.getInitialContext(MyContextFactory.java:20)
at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:684)
at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:313)
at javax.naming.InitialContext.init(InitialContext.java:244)
at javax.naming.InitialContext.<init>(InitialContext.java:192)
at MyContextFactory$1.<init>(MyContextFactory.java:20)
at MyContextFactory.getInitialContext(MyContextFactory.java:20)
at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:684)
at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:313)
at javax.naming.InitialContext.init(InitialContext.java:244)
at javax.naming.InitialContext.<init>(InitialContext.java:192)
at MyContextFactory$1.<init>(MyContextFactory.java:20)
at MyContextFactory.getInitialContext(MyContextFactory.java:20)
at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:684)
at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:313)
at javax.naming.InitialContext.init(InitialContext.java:244)
at javax.naming.InitialContext.<init>(InitialContext.java:192)
...
</code>```

I can make the code work by creating an "environment" Hashtable, placing the name of the MyContextFactory class there (under the "java.naming.factory.initial" key) and then creating the InitialContext using the constructor that accepts a Hashtable environment:

```<code>Context context = new InitialContext(environment);
</code>```

But my question is: how can I make this work using the no-args constructor and supplying the name of the factory class using "-Djava.naming.factory.initial" at the invocation of the JVM ?

答:
Thanks to the suggestion by Jim Garrison, here's the answer.
The crux of the matter is the call super(true); in the constructor of the MyContext class.

```<code>class MyContext extends InitialContext {

    private Hashtable store;

    public MyContext(Hashtable store) throws NamingException {
        super(true);
        this.store = store;
    }

    @Override
    public void bind(String name, Object obj) {
        store.put(name, obj);
    }

    @Override
    public Object lookup(String name) {
        return store.get(name);
    }

}

public class FooMain {

    private static final int    ANSWER    = 42;
    private static final String JNDI_NAME = "/config/theAnswerToEverything";

    public static void main (String args[]) throws NamingException {
        Context context = new InitialContext();
        putInContext(                    JNDI_NAME, ANSWER);

        int answer = retrieveFromContext(JNDI_NAME);
        Assert.assertEquals(ANSWER, answer);
        System.out.printf("%d\n", answer);
    }

    private static void putInContext(final String key, final Object value) throws NamingException {
        Context context = new InitialContext();
        context.bind(key, value);
    }

    private static int retrieveFromContext(final String key) throws NamingException {
        Context context = new InitialContext();
        return (int) context.lookup(key);
    }
}

public class MyContextFactory implements InitialContextFactory {

    private static Hashtable store = new Hashtable();

    /*
      Do not confuse [store] with [environment]. They serve different
      purposes.
     */

    @Override
    public Context getInitialContext(Hashtable environment) throws NamingException {
        return new MyContext(store);
    }
}
</code>```

Invoke from the command line:

```<code>$ java -Djava.naming.factory.initial=MyContextFactory -cp [actual classpath] FooMain
42
</code>```

Body:
I am trying to setup JNDI for a Java SE console application.

I have the following code:

public class FooMain {

    public static void main (String args[]) throws NamingException {
        Context context = new InitialContext();
        context.bind("foo", "bar");
    }
}

… and the context factory is defined as:

public class MyContextFactory implements InitialContextFactory {

    private static Hashtable store = new Hashtable();

    @Override
    public Context getInitialContext(Hashtable environment) throws NamingException {
        return new InitialContext() {

            @Override
            public void bind(String name, Object obj) {
                store.put(name, obj);
            }

            @Override
            public Object lookup(String name) {
                return store.get(name);
            }
        };
    }
}

When I invoke my FooMain class using:

java -Djava.naming.factory.initial=MyContextFactory -cp ... FooMain

I get infinite recursion and an eventual StackOverflow Exception:

Exception in thread "main" java.lang.StackOverflowError
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.naming.internal.VersionHelper12.getContextClassLoader(VersionHelper12.java:185)
at com.sun.naming.internal.ResourceManager.getApplicationResources(ResourceManager.java:549)
at com.sun.naming.internal.ResourceManager.getInitialEnvironment(ResourceManager.java:244)
at javax.naming.InitialContext.init(InitialContext.java:240)
at javax.naming.InitialContext.<init>(InitialContext.java:192)
at MyContextFactory$1.<init>(MyContextFactory.java:20)
at MyContextFactory.getInitialContext(MyContextFactory.java:20)
at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:684)
at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:313)
at javax.naming.InitialContext.init(InitialContext.java:244)
at javax.naming.InitialContext.<init>(InitialContext.java:192)
at MyContextFactory$1.<init>(MyContextFactory.java:20)
at MyContextFactory.getInitialContext(MyContextFactory.java:20)
at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:684)
at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:313)
at javax.naming.InitialContext.init(InitialContext.java:244)
at javax.naming.InitialContext.<init>(InitialContext.java:192)
at MyContextFactory$1.<init>(MyContextFactory.java:20)
at MyContextFactory.getInitialContext(MyContextFactory.java:20)
at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:684)
at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:313)
at javax.naming.InitialContext.init(InitialContext.java:244)
at javax.naming.InitialContext.<init>(InitialContext.java:192)
...

I can make the code work by creating an "environment" Hashtable, placing the name of the MyContextFactory class there (under the "java.naming.factory.initial" key) and then creating the InitialContext using the constructor that accepts a Hashtable environment:

Context context = new InitialContext(environment);

But my question is: how can I make this work using the no-args constructor and supplying the name of the factory class using "-Djava.naming.factory.initial" at the invocation of the JVM ?

Body:
Thanks to the suggestion by Jim Garrison, here's the answer.
The crux of the matter is the call super(true); in the constructor of the MyContext class.

class MyContext extends InitialContext {

    private Hashtable store;

    public MyContext(Hashtable store) throws NamingException {
        super(true);
        this.store = store;
    }

    @Override
    public void bind(String name, Object obj) {
        store.put(name, obj);
    }

    @Override
    public Object lookup(String name) {
        return store.get(name);
    }

}

public class FooMain {

    private static final int    ANSWER    = 42;
    private static final String JNDI_NAME = "/config/theAnswerToEverything";

    public static void main (String args[]) throws NamingException {
        Context context = new InitialContext();
        putInContext(                    JNDI_NAME, ANSWER);

        int answer = retrieveFromContext(JNDI_NAME);
        Assert.assertEquals(ANSWER, answer);
        System.out.printf("%d\n", answer);
    }

    private static void putInContext(final String key, final Object value) throws NamingException {
        Context context = new InitialContext();
        context.bind(key, value);
    }

    private static int retrieveFromContext(final String key) throws NamingException {
        Context context = new InitialContext();
        return (int) context.lookup(key);
    }
}

public class MyContextFactory implements InitialContextFactory {

    private static Hashtable store = new Hashtable();

    /*
      Do not confuse [store] with [environment]. They serve different
      purposes.
     */

    @Override
    public Context getInitialContext(Hashtable environment) throws NamingException {
        return new MyContext(store);
    }
}

Invoke from the command line:

$ java -Djava.naming.factory.initial=MyContextFactory -cp [actual classpath] FooMain
42


问:
Getting an error while trying to run my project on android studio
This my java code :

```<code>protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    setContentView(R.layout.activity_main);

}
</code>```

and this xml file :

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.khanousse.lite.MainActivity"
tools:layout_editor_absoluteX="8dp"
tools:layout_editor_absoluteY="25dp">

<TextView
    android:id="@+id/textView"
    android:layout_width="298dp"
    android:layout_height="182dp"
    android:text="Hello World"
    android:textSize="30sp" />
   </android.support.constraint.ConstraintLayout>
</code>```

I don't why i get this error :

Error:Execution failed for task ':app:transformDexArchiveWithExternalLibsDexMergerForDebug'.
  >java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING at line 1 column 1 path $

答:
I had this problem earlier days, i resolved it by just

Clean your project build>clean

Rebuild project build>rebuild

ContentLicense: CC BY-SA 4.0

Body:
This my java code :

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    setContentView(R.layout.activity_main);

}

and this xml file :

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.khanousse.lite.MainActivity"
tools:layout_editor_absoluteX="8dp"
tools:layout_editor_absoluteY="25dp">

<TextView
    android:id="@+id/textView"
    android:layout_width="298dp"
    android:layout_height="182dp"
    android:text="Hello World"
    android:textSize="30sp" />
   </android.support.constraint.ConstraintLayout>

I don't why i get this error :

Error:Execution failed for task ':app:transformDexArchiveWithExternalLibsDexMergerForDebug'.
  >java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING at line 1 column 1 path $


问:
Collection.find({key: any_value in an array }) matching multiple values with mongoose

Hi, I have a "Tweets" Schema, which has a key of "author" and I would like to find all tweets whose author is any value in an array of people. For instance,

if I could do something like:

let people = ['josh','bob','tim'];

```<code>Tweet.find({ author: [people] }).then((tweets) => {
      // tweets = all tweets that have any of the following authors: josh, bob, or time
})
</code>```

Essentially, is there a mongoose specific way to do:

```<code>people.forEach((person)=> {
   Tweet.find({ author: person})
})
</code>```

Also note that the 'people' array changes per user that is logged in/session user.

答:
```<code>Tweet.find({ author: {$in:  people }},(err,tweets)=>{
      //code
})
</code>```

Body:
Hi, I have a "Tweets" Schema, which has a key of "author" and I would like to find all tweets whose author is any value in an array of people. For instance,

if I could do something like:

let people = ['josh','bob','tim'];

Tweet.find({ author: [people] }).then((tweets) => {
      // tweets = all tweets that have any of the following authors: josh, bob, or time
})

Essentially, is there a mongoose specific way to do:

people.forEach((person)=> {
   Tweet.find({ author: person})
})

Also note that the 'people' array changes per user that is logged in/session user.


问:
Storing date and hour (without minutes and seconds) in MySQL
I need to store dates with hours, but without minutes or seconds. That's because I want the data to be grouped by hour, and be able to insert with ON DUPLICATE KEY UPDATE... if two events happen in the same hour.

I've seen some applications using a DATETIME field, and inserting with

date("Y-m-d H") . ':00:00'

is this the best practice or are there better solutions?

答:
From my best of know it will better to store date in integer format like epoch time because
1. it will store every thing like date month year hours minutes seconds.
2. While searching using epoch time it will faster because integer comparison is faster than string comparison.

Use of epochtime in MySQL


问:
How to force jQuery.text() working even after manual updating the TEXTAREA value?
I've just noticed, that the jQuery text(...) method only sets the content of a TEXTAREA, if if has not been updated manually. For example (also on jsFiddle):

$('#myButton').click(function() {
   $('#myText').text(Date.now);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><textarea id="myText"></textarea>
<button id="myButton">Go!</button>

<script src="//code.jquery.com/jquery-2.1.0.js"></script></code>```

Now when I click on Go!, the content of the TEXTAREA gets updated with the current timestamp. I also can do it multiple times. Working. But if I manually change the text (e.g. by deleting or adding a character), it stops working.

I also tried out the val(...) method. It works as expected, regardless of manual changes on the text field.

How to get jQuery.text(...) working after manual changes?

答:
Your question seems to suggest you know you can use val but are choosing not to. So I tried various options, but I don't think you can reliably use text to set a textarea.

So, since the correct way to set the value of a textarea is to use val, use val. :-) If you do that, it works regardless of whether the textarea is edited by the user:

$('#myButton').click(function() {
   $('#myText').val(Date.now);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><textarea id="myText"></textarea>
<button id="myButton">Go!</button>

<script src="//code.jquery.com/jquery-2.1.0.js"></script></code>```

Body:
I've just noticed, that the jQuery text(...) method only sets the content of a TEXTAREA, if if has not been updated manually. For example (also on jsFiddle):

$('#myButton').click(function() {
   $('#myText').text(Date.now);
});

<textarea id="myText"></textarea>
<button id="myButton">Go!</button>

Now when I click on Go!, the content of the TEXTAREA gets updated with the current timestamp. I also can do it multiple times. Working. But if I manually change the text (e.g. by deleting or adding a character), it stops working.

I also tried out the val(...) method. It works as expected, regardless of manual changes on the text field.

How to get jQuery.text(...) working after manual changes?

Body:
Your question seems to suggest you know you can use val but are choosing not to. So I tried various options, but I don't think you can reliably use text to set a textarea.

So, since the correct way to set the value of a textarea is to use val, use val. :-) If you do that, it works regardless of whether the textarea is edited by the user:

$('#myButton').click(function() {
   $('#myText').val(Date.now);
});

<textarea id="myText"></textarea>
<button id="myButton">Go!</button>

<script src="//code.jquery.com/jquery-2.1.0.js"></script>


问:
Android button or TextView vertical align
i am trying to vertically align a button or a textview, but i can't.
Neither android:layout_gravity="center_vertical|center_horizontal" nor android:gravity="center_vertical|center_horizontal" works. Not even android:gravity="center" does the trick.
They only aligns the object horizontally. How can i align it to the center or bottom of the view?

答: Depends on the parent layout. If you're using a RelativeLayout, you can simply use layout_alignParentBottom="true", although layout_gravity="bottom" should work as well. Keep in mind the size of this parent layout as well. You can't use alignParentBottom if the RelativeLayout is set to wrap_content for height. It should be set to fill_parent. You should post the rest of your XML if you're still having issues.


问:
Set class to active on additional li elements upon navbar click
I have the following side bar menu code. Upon click on any of the nav items it highlights / makes the class active.

```<code>$(document).ready(function() {
  $(".nav li").click(function() {
    if ($(".nav li").removeClass("active")) {
      $(this).removeClass("active");
    }
    $(this).addClass("active");
  });

});

<ul class="nav">
  <li class="nav-item">
    <a data-target="#system-settings" data-toggle="pill" class="nav-link" href="#system-settings" id="system-settings">System Settings</a>
  </li>
  <li class="nav-item">
    <a class="nav-link" href="#hosts" id="hosts" data-parent="#hosts">Hosts</a>
  </li>
  <li class="nav-item ">
    <a class="nav-link" href="#card-range" id="card-range">Cards</a>
  </li>
  <li class="nav-item">
    <a class="nav-link" id="pinpads" href="#pinpads">Printer</a>
  </li>
  <li class="nav-item">
    <a class="nav-link" id="xmls" href="#xmls">Pinpad</a>
  </li>

</ul>
</code>```

Now I have similar items at the top of the page presented as a connected circle:

```<code><div class="connected-line">
  <ul>
    <li class="active">1
      <p> System </p>
    </li>
    <li id="hosts">2
      <p> Hosts </p>
    </li>
    <li>3
      <p> Cards </p>
    </li>
    <li>4
      <p> Devices </p>
    </li>
  </ul>
</div>
</code>```

See jsfiddle:
https://jsfiddle.net/vk3qw09f/345/

Now if the user clicks on the side bar menu, it should also set corresponding  class as active on the "connected-line" list elements.

For eg: Cliking on navbar "System Settings" should also add a class 'active' to the li item inside the circled li "System"

I know it's not recommednded to have the same 2 ids on the same page. So looking for a smarter way to achieve this.

EDIT: my current code will only make that class active: $(this).addClass("active");

I probably want to make all classes that share the same name active

答:
I assume this is what you're looking for.

$(document).ready(function() {
  $(".nav li a").click(function(e) {
    e.preventDefault();
    $(".nav li").removeClass("active");
    $(".connected-line li").removeClass("active");
    $($(this).attr('href')).addClass('active');
    $(this).addClass("active");
  });
});
```

Full working snippet here. Haven't added snippet in answer because:

a) SO doesn't yet support SCSS,

 b) i'm lazy.

Also note I made minor mods to your CSS and markup. Another note: duplicate ids are illegal in HTML. You have them? Expect your JavaScript to break. It's as simple as that.

Body:
I have the following side bar menu code. Upon click on any of the nav items it highlights / makes the class active.

$(document).ready(function() {
  $(".nav li").click(function() {
    if ($(".nav li").removeClass("active")) {
      $(this).removeClass("active");
    }
    $(this).addClass("active");
  });

});

    System Settings

    Hosts

    Cards

    Printer

    Pinpad

Now I have similar items at the top of the page presented as a connected circle:

1

 System

2

 Hosts

3

 Cards

4

 Devices

See jsfiddle:
https://jsfiddle.net/vk3qw09f/345/

Now if the user clicks on the side bar menu, it should also set corresponding  class as active on the "connected-line" list elements.

For eg: Cliking on navbar "System Settings" should also add a class 'active' to the li item inside the circled li "System"

I know it's not recommednded to have the same 2 ids on the same page. So looking for a smarter way to achieve this.

EDIT: my current code will only make that class active: $(this).addClass("active");

I probably want to make all classes that share the same name active

Body:
I assume this is what you're looking for.

$(document).ready(function() {
  $(".nav li a").click(function(e) {
    e.preventDefault();
    $(".nav li").removeClass("active");
    $(".connected-line li").removeClass("active");
    $($(this).attr('href')).addClass('active');
    $(this).addClass("active");
  });
});

Full working snippet here. Haven't added snippet in answer because:

a) SO doesn't yet support SCSS,

 b) i'm lazy.

Also note I made minor mods to your CSS and markup. Another note: duplicate ids are illegal in HTML. You have them? Expect your JavaScript to break. It's as simple as that.


问:
What would be the maximum value of PHP rand() function , if we provide no parameters to it ??
I want to know what maximum value and minimum value PHP rand() function returns if we don't provide any parameter like min and max
e.g.</p>

```<code>//what will be maximum and minimum output of this
echo rand();
</code>```

答:
The minimal value of rand() without arguments is 0.

The maximum value is platform dependent, but you can use getrandmax() to see the largest possible random value on your machine.

Body:
I want to know what maximum value and minimum value PHP rand() function returns if we don't provide any parameter like min and max
e.g.

//what will be maximum and minimum output of this
echo rand();


问:
laravel eloquent where in query not working on both array
How to use $a variable in wherein properly? My code is as follows:

```<code>$color = json_decode($request -> color); //["2","3"] from jquery ajax
$a;

foreach($color as $k){
    $a[] = $k;
}

$b =[2,3];
$query = $query->whereIn('color', $a);
</code>```

When I put $a array in whereIn, only one record is fetched. But if i add $b array then all records are fetched. I don't know what is the issue of both arrays.

答:
Try parsing your array values to integer</p>

```<code> foreach($color as $k){
        $a[]= (int) $k;
    }
</code>```

Body:
How to use $a variable in wherein properly? My code is as follows:

$color = json_decode($request -> color); //["2","3"] from jquery ajax
$a;

foreach($color as $k){
    $a[] = $k;
}

$b =[2,3];
$query = $query->whereIn('color', $a);

When I put $a array in whereIn, only one record is fetched. But if i add $b array then all records are fetched. I don't know what is the issue of both arrays.

Body:
Try parsing your array values to integer

 foreach($color as $k){
        $a[]= (int) $k;
    }


问:
How to fix WARNING: clj-refactor and refactor-nrepl are out of sync?
I'm using clojure-maven-plugin. When I do a cider-connect I get this "WARNING: clj-refactor and refactor-nrepl are out of sync. Their versions are 2.4.0-SNAPSHOT (package: 20171117.317) and n/a, respectively." Is there anything I can do to my pom.xml to make this warning go away? I've tried adding refactor-nrepl 2.4.0-SNAPSHOT as a dependency.</p>

答:
Cider-connect needs some dependencies (cider and clj-refactor nrepl-middleware).

The following links explain how to add the dependencies for boot or lein.

https://github.com/clojure-emacs/refactor-nrepl

http://cider.readthedocs.io/en/latest/installation/#ciders-nrepl-middleware

Example boot: .boot/profile.boot

```<code>(require 'boot.repl)

(swap! boot.repl/*default-dependencies*
       concat '[[cider/cider-nrepl "0.15.1"]
                [refactor-nrepl "2.3.1"]])

(swap! boot.repl/*default-middleware*
       concat '[cider.nrepl/cider-middleware
                refactor-nrepl.middleware/wrap-refactor])
</code>```

Body:
Cider-connect needs some dependencies (cider and clj-refactor nrepl-middleware).

The following links explain how to add the dependencies for boot or lein.

https://github.com/clojure-emacs/refactor-nrepl

http://cider.readthedocs.io/en/latest/installation/#ciders-nrepl-middleware

Example boot: .boot/profile.boot

(require 'boot.repl)

(swap! boot.repl/*default-dependencies*
       concat '[[cider/cider-nrepl "0.15.1"]
                [refactor-nrepl "2.3.1"]])

(swap! boot.repl/*default-middleware*
       concat '[cider.nrepl/cider-middleware
                refactor-nrepl.middleware/wrap-refactor])