问:
Hibernate Spatial 4 error unknown SQL type to be used in insert with org.postgis.PGgeometry
I've a issue when i try to store an hibernate spatial point to o PostgreSQL db with PostGis extensions installed.

Essentially, when I try to insert the record into the table the org.springframework.dao.InvalidDataAccessResourceUsageException is raised explaining that the org.postgis.PGgeometry could not be mapped into a SQL type.

The operating system is Windows 10 64 bit.
The PostgreSQL server Database version is 9.6 64 bit on localhost
The PostGis version is 2.3.2 64 bit
The Tomcat version is 8.5.8
The JVM version is 1.8.0_112-b15
The Spring version is 4.1.4.RELEASE
The Aspectj version is 1.8.4
The Hibernate version is 4.3.5.Final
The PostGis JDBC driver version is 1.5.2
The hibernate dialect has been set to org.hibernate.spatial.dialect.postgis.PostgisDialect
The datasource on Tomcat has been configured in this way:

```<code><Resource name="jdbc/safetyAroundSchool" auth="Container" type="javax.sql.DataSource" maxActive="2" maxIdle="2" maxWait="10000" username="biotope-xxxx" password="xxxxxxxxxx" driverClassName="org.postgis.DriverWrapper" url="jdbc:postgresql_postGIS://localhost:5432/biotope-ssp"/>
</code>```

But I've also used:

```<code><Resource name="jdbc/safetyAroundSchool" auth="Container" type="javax.sql.DataSource" maxActive="2" maxIdle="2" maxWait="10000" username="biotope-xxxx" password="xxxxxxxxxxx" DriverClassName="org.postgresql.Driver" url="jdbc:postgresql://localhost:5432/biotope-ssp"/>
</code>```

This is the the field declaration:

```<code>@Column(columnDefinition = "Geometry", nullable = true)
@Type(type="org.hibernate.spatial.GeometryType")
private Point location;
</code>```

The table is created with the correct geometry type for the column this is the create script:

```<code>CREATE TABLE public.issue
(
    id bigint NOT NULL,
    date timestamp without time zone,
    location geometry,
    longdesc character varying(255) COLLATE pg_catalog."default",
    shortdesc character varying(255) COLLATE pg_catalog."default",
    type bigint,
    userid bigint,
    CONSTRAINT issue_pkey PRIMARY KEY (id)
);
</code>```

And this is the error that i receive when I try to insert a new record.

18:14:11,878  WARN SqlExceptionHelper:144 - SQL Error: 0, SQLState: 07006
  18:14:11,883 ERROR SqlExceptionHelper:146 - Non è possibile identificare il tipo SQL da usare per l'istanza di tipo «org.postgis.PGgeometry». Usare «setObject()» specificando esplicitamente il tipo da usare per questo valore.
  18:14:11,898 ERROR WebApiExceptionProcessor:28 - Internal server error intercepted
  org.springframework.dao.InvalidDataAccessResourceUsageException: could not insert: [it.holonix.safetyAroundSchoold.entity.Issue]; SQL [insert into Issue (date, location, longDesc, shortDesc, type, userId, id) values (?, ?, ?, ?, ?, ?, ?)]; nested exception is org.hibernate.exception.SQLGrammarException: could not insert: [it.holonix.safetyAroundSchoold.entity.Issue]
      at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:231)
      at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:214)
      at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:521)
      at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:757)
      at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:726)
      at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:515)
      at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:291)
      at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
      at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
      at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:653)
      at it.holonix.safetyAroundSchoold.controller.IssueCtrl$$EnhancerBySpringCGLIB$$f6840c31.insertIssue()
      at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
      at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
      at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
      at java.lang.reflect.Method.invoke(Method.java:498)
      at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
      at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
      at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
      at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:777)
      at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:706)
      at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
      at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:943)
      at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877)
      at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
      at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:868)
      at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
      at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
      at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
      at it.holonix.webapi.auth.AuthRequestWrapperFilter.doFilter(AuthRequestWrapperFilter.java:23)
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
      at it.holonix.webapi.util.CorsFilter.doFilterInternal(CorsFilter.java:85)
      at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
      at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
      at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
      at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:108)
      at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
      at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
      at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
      at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:620)
      at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
      at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
      at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:783)
      at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
      at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:789)
      at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1455)
      at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
      at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
      at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
      at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
      at java.lang.Thread.run(Thread.java:745)
  Caused by: org.hibernate.exception.SQLGrammarException: could not insert: [it.holonix.safetyAroundSchoold.entity.Issue]
      at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:123)
      at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
      at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126)
      at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3144)
      at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3581)
      at org.hibernate.action.internal.EntityInsertAction.execute(EntityInsertAction.java:104)
      at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:463)
      at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:349)
      at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:350)
      at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:56)
      at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1222)
      at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:425)
      at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.beforeTransactionCommit(JdbcTransaction.java:101)
      at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.commit(AbstractTransactionImpl.java:177)
      at org.hibernate.jpa.internal.TransactionImpl.commit(TransactionImpl.java:77)
      at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:517)
      ... 54 more
  Caused by: org.postgresql.util.PSQLException: Non è possibile identificare il tipo SQL da usare per l'istanza di tipo «org.postgis.PGgeometry». Usare «setObject()» specificando esplicitamente il tipo da usare per questo valore.
      at org.postgresql.jdbc.PgPreparedStatement.setObject(PgPreparedStatement.java:967)
      at org.apache.tomcat.dbcp.dbcp2.DelegatingPreparedStatement.setObject(DelegatingPreparedStatement.java:188)
      at org.apache.tomcat.dbcp.dbcp2.DelegatingPreparedStatement.setObject(DelegatingPreparedStatement.java:188)
      at org.hibernate.spatial.dialect.AbstractJTSGeometryValueBinder.bind(AbstractJTSGeometryValueBinder.java:48)
      at org.hibernate.spatial.dialect.AbstractJTSGeometryValueBinder.bind(AbstractJTSGeometryValueBinder.java:39)
      at org.hibernate.type.AbstractStandardBasicType.nullSafeSet(AbstractStandardBasicType.java:286)
      at org.hibernate.type.AbstractStandardBasicType.nullSafeSet(AbstractStandardBasicType.java:281)
      at org.hibernate.type.AbstractSingleColumnStandardBasicType.nullSafeSet(AbstractSingleColumnStandardBasicType.java:56)
      at org.hibernate.persister.entity.AbstractEntityPersister.dehydrate(AbstractEntityPersister.java:2843)
      at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3121)
      ... 66 more

The quote in italian could be translated in this way:
It's not possible to identify the SQL type to be used for the instance of type «org.postgis.PGgeometry». Use «setObject()» specifying the type to be used for this value.

Could you help me to solve this issue? Do you need some other information?

Roberto

答:
First, you should check that you actually use the Hibernate Postgis dialect. Normally you should find log messages during start up to that effect. If you let Spring choose the dialect for you, it will not pick the Hibernate Postgis dialect.

Secondly, you don't need any Postgis JDBC driver or driver wrapper. Hibernate Spatial works with the standard JDBC drivers. You may want to follow this tutorial to get a feel for how everything should be set up.

Body:
I've a issue when i try to store an hibernate spatial point to o PostgreSQL db with PostGis extensions installed.

Essentially, when I try to insert the record into the table the org.springframework.dao.InvalidDataAccessResourceUsageException is raised explaining that the org.postgis.PGgeometry could not be mapped into a SQL type.

The operating system is Windows 10 64 bit.
The PostgreSQL server Database version is 9.6 64 bit on localhost
The PostGis version is 2.3.2 64 bit
The Tomcat version is 8.5.8
The JVM version is 1.8.0_112-b15
The Spring version is 4.1.4.RELEASE
The Aspectj version is 1.8.4
The Hibernate version is 4.3.5.Final
The PostGis JDBC driver version is 1.5.2
The hibernate dialect has been set to org.hibernate.spatial.dialect.postgis.PostgisDialect
The datasource on Tomcat has been configured in this way:

<Resource name="jdbc/safetyAroundSchool" auth="Container" type="javax.sql.DataSource" maxActive="2" maxIdle="2" maxWait="10000" username="biotope-xxxx" password="xxxxxxxxxx" driverClassName="org.postgis.DriverWrapper" url="jdbc:postgresql_postGIS://localhost:5432/biotope-ssp"/>

But I've also used:

<Resource name="jdbc/safetyAroundSchool" auth="Container" type="javax.sql.DataSource" maxActive="2" maxIdle="2" maxWait="10000" username="biotope-xxxx" password="xxxxxxxxxxx" DriverClassName="org.postgresql.Driver" url="jdbc:postgresql://localhost:5432/biotope-ssp"/>

This is the the field declaration:

@Column(columnDefinition = "Geometry", nullable = true)
@Type(type="org.hibernate.spatial.GeometryType")
private Point location;

The table is created with the correct geometry type for the column this is the create script:

CREATE TABLE public.issue
(
    id bigint NOT NULL,
    date timestamp without time zone,
    location geometry,
    longdesc character varying(255) COLLATE pg_catalog."default",
    shortdesc character varying(255) COLLATE pg_catalog."default",
    type bigint,
    userid bigint,
    CONSTRAINT issue_pkey PRIMARY KEY (id)
);

And this is the error that i receive when I try to insert a new record.

18:14:11,878  WARN SqlExceptionHelper:144 - SQL Error: 0, SQLState: 07006
  18:14:11,883 ERROR SqlExceptionHelper:146 - Non è possibile identificare il tipo SQL da usare per l'istanza di tipo «org.postgis.PGgeometry». Usare «setObject()» specificando esplicitamente il tipo da usare per questo valore.
  18:14:11,898 ERROR WebApiExceptionProcessor:28 - Internal server error intercepted
  org.springframework.dao.InvalidDataAccessResourceUsageException: could not insert: [it.holonix.safetyAroundSchoold.entity.Issue]; SQL [insert into Issue (date, location, longDesc, shortDesc, type, userId, id) values (?, ?, ?, ?, ?, ?, ?)]; nested exception is org.hibernate.exception.SQLGrammarException: could not insert: [it.holonix.safetyAroundSchoold.entity.Issue]
      at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:231)
      at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:214)
      at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:521)
      at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:757)
      at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:726)
      at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:515)
      at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:291)
      at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
      at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
      at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:653)
      at it.holonix.safetyAroundSchoold.controller.IssueCtrl$$EnhancerBySpringCGLIB$$f6840c31.insertIssue()
      at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
      at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
      at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
      at java.lang.reflect.Method.invoke(Method.java:498)
      at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
      at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
      at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
      at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:777)
      at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:706)
      at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
      at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:943)
      at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877)
      at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
      at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:868)
      at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
      at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
      at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
      at it.holonix.webapi.auth.AuthRequestWrapperFilter.doFilter(AuthRequestWrapperFilter.java:23)
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
      at it.holonix.webapi.util.CorsFilter.doFilterInternal(CorsFilter.java:85)
      at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
      at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
      at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
      at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:108)
      at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
      at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
      at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
      at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:620)
      at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
      at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
      at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:783)
      at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
      at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:789)
      at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1455)
      at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
      at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
      at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
      at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
      at java.lang.Thread.run(Thread.java:745)
  Caused by: org.hibernate.exception.SQLGrammarException: could not insert: [it.holonix.safetyAroundSchoold.entity.Issue]
      at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:123)
      at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
      at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126)
      at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3144)
      at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3581)
      at org.hibernate.action.internal.EntityInsertAction.execute(EntityInsertAction.java:104)
      at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:463)
      at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:349)
      at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:350)
      at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:56)
      at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1222)
      at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:425)
      at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.beforeTransactionCommit(JdbcTransaction.java:101)
      at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.commit(AbstractTransactionImpl.java:177)
      at org.hibernate.jpa.internal.TransactionImpl.commit(TransactionImpl.java:77)
      at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:517)
      ... 54 more
  Caused by: org.postgresql.util.PSQLException: Non è possibile identificare il tipo SQL da usare per l'istanza di tipo «org.postgis.PGgeometry». Usare «setObject()» specificando esplicitamente il tipo da usare per questo valore.
      at org.postgresql.jdbc.PgPreparedStatement.setObject(PgPreparedStatement.java:967)
      at org.apache.tomcat.dbcp.dbcp2.DelegatingPreparedStatement.setObject(DelegatingPreparedStatement.java:188)
      at org.apache.tomcat.dbcp.dbcp2.DelegatingPreparedStatement.setObject(DelegatingPreparedStatement.java:188)
      at org.hibernate.spatial.dialect.AbstractJTSGeometryValueBinder.bind(AbstractJTSGeometryValueBinder.java:48)
      at org.hibernate.spatial.dialect.AbstractJTSGeometryValueBinder.bind(AbstractJTSGeometryValueBinder.java:39)
      at org.hibernate.type.AbstractStandardBasicType.nullSafeSet(AbstractStandardBasicType.java:286)
      at org.hibernate.type.AbstractStandardBasicType.nullSafeSet(AbstractStandardBasicType.java:281)
      at org.hibernate.type.AbstractSingleColumnStandardBasicType.nullSafeSet(AbstractSingleColumnStandardBasicType.java:56)
      at org.hibernate.persister.entity.AbstractEntityPersister.dehydrate(AbstractEntityPersister.java:2843)
      at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3121)
      ... 66 more

The quote in italian could be translated in this way:
It's not possible to identify the SQL type to be used for the instance of type «org.postgis.PGgeometry». Use «setObject()» specifying the type to be used for this value.

Could you help me to solve this issue? Do you need some other information?

Roberto


来源: stackexchange

问:
Assert is function not passed in parameter is called
Let's say I have a function like that:

```<code>def foo():
  bar()
</code>```

Is there any way I could test if bar is called, when I'm not passing bar as parameter? My team use Python 3.6 and 3.5

答:
You should use patch for that:

```<code>@patch('path.to.bar')
def test_foo(self, mock_bar):
    foo()
    self.assertTrue(mock_bar.called)
</code>```

You can also test with which values the function was called like this:

```<code>mock_bar.assert_called_with('some_param')
</code>```

Hope it helps.

ContentLicense: CC BY-SA 3.0

Body:
Let's say I have a function like that:

def foo():
  bar()

Is there any way I could test if bar is called, when I'm not passing bar as parameter? My team use Python 3.6 and 3.5

Body:
You should use patch for that:

@patch('path.to.bar')
def test_foo(self, mock_bar):
    foo()
    self.assertTrue(mock_bar.called)

You can also test with which values the function was called like this:

mock_bar.assert_called_with('some_param')

Hope it helps.


问:
Change the value of the list object in the recursion function
```<code>def divide(alist):
    # when the list have only one element, it should return the 0
    if len(alist) == 1:
        alist[:] = list([0])

    else:
        middle = len(alist) / 2
        divide(alist[:middle])
        divide(alist[middle:])
temp = [1, 2, 3, 4, 5, 6]
divide(temp)
print temp
</code>```

In my function, after the recursion, i want to get the [0, 0, 0, 0, 0, 0],but  temp is still the [1, 2, 3, 4, 5, 6]. And i also use alist[:] = list([0])to ensure the alist to be re-assigned.

Why? Is there something wrong with the reference?

答:
Please mention your intented goal next time you ask a question. My guess was that you didn't need both recursion and in-place modification of your list.

So my first answer was to propose in-place modification without recursion :

```<code>def set_to_zero(alist):
    alist[:] = [0 for _ in alist]

temp = [1, 2, 3, 4, 5, 6]
set_to_zero(temp)
print(temp)
# [0, 0, 0, 0, 0, 0]
</code>```

It turns out that you need recursion without in-place modification, because you want to write a merge sort.

Merge sort's most common implementation does not sort in place;[5]
  therefore, the memory size of the input must be allocated for the
  sorted output to be stored in (see below for versions that need only
  n/2 extra spaces).

Here's a clean implementation of the sort, with some debug lines. Here's a related question on SO (Mergesort python) with many implementations.

Body:
def divide(alist):
    # when the list have only one element, it should return the 0
    if len(alist) == 1:
        alist[:] = list([0])

    else:
        middle = len(alist) / 2
        divide(alist[:middle])
        divide(alist[middle:])
temp = [1, 2, 3, 4, 5, 6]
divide(temp)
print temp

In my function, after the recursion, i want to get the [0, 0, 0, 0, 0, 0],but  temp is still the [1, 2, 3, 4, 5, 6]. And i also use alist[:] = list([0])to ensure the alist to be re-assigned.

Why? Is there something wrong with the reference?

Body:
Please mention your intented goal next time you ask a question. My guess was that you didn't need both recursion and in-place modification of your list.

So my first answer was to propose in-place modification without recursion :

def set_to_zero(alist):
    alist[:] = [0 for _ in alist]

temp = [1, 2, 3, 4, 5, 6]
set_to_zero(temp)
print(temp)
# [0, 0, 0, 0, 0, 0]

It turns out that you need recursion without in-place modification, because you want to write a merge sort.

Merge sort's most common implementation does not sort in place;[5]
  therefore, the memory size of the input must be allocated for the
  sorted output to be stored in (see below for versions that need only
  n/2 extra spaces).

Here's a clean implementation of the sort, with some debug lines. Here's a related question on SO (Mergesort python) with many implementations.


问:
How to reduce space between PagerTabStrip indicator elements
I am developing an application using android viewPager with tabs as you can see on this screenshot:

my issue concerns the two indicators Page 0 and Page 1. I want to center them on my viewpager and whenever i click on or swipe, it will display the content.

here is my XML layout:

```<code> <android.support.v4.view.ViewPager
            android:id="@+id/vpPager"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <android.support.v4.view.PagerTabStrip
                android:id="@+id/pager_header"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="top"
                android:paddingBottom="4dp"
                android:paddingTop="4dp" />

  </android.support.v4.view.ViewPager>
</code>```

Thank you

答:
I'm not sure its supported in android.support.v4.view.PagerTabStrip.
But I can recommend you to use another library for the same effect.
I am using:

PagerSlidingTabStrip by astuetz

It works well.

After you add the lib to your project, set pstsShouldExpand to true and it will fill the tabs.

Body:
I am developing an application using android viewPager with tabs as you can see on this screenshot:

my issue concerns the two indicators Page 0 and Page 1. I want to center them on my viewpager and whenever i click on or swipe, it will display the content.

here is my XML layout:

 <android.support.v4.view.ViewPager
            android:id="@+id/vpPager"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <android.support.v4.view.PagerTabStrip
                android:id="@+id/pager_header"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="top"
                android:paddingBottom="4dp"
                android:paddingTop="4dp" />

  </android.support.v4.view.ViewPager>

Thank you


问:
"SyntaxError: Unexpected token )" in Node.js
I keep getting a SyntaxError: Unexpected token )' error for the following code:

```<code>passport.use(
  'local-signup',
  new LocalStrategy({
      usernameField: 'email',
      passwordField: 'password',
      passReqToCallback: true, // pass back req to callback
    },
    (req, email, password, done) => {
      // ...
    },
  ),
);
</code>```

It really only started after I put arrow functions in. I think I'm missing something syntax-wise. I'm using the airbnb style guide & linter btw. Running Node.js LTS. VS Code doesn't give any parsing errors either in the editor itself.
The code works when transpiled to ES2015 via Babel. I'm still curious why it isn't working with the ES6 syntax.

答:
The problem is that in two places you're using a trailing comma in function syntax, i.e. a comma after the last argument of a function.

```<code>passport.use(
  'local-signup',
  new LocalStrategy({
      usernameField: 'email',
      passwordField: 'password',
      passReqToCallback: true, // pass back req to callback
    },
    (req, email, password, done) => {
      // ...
    },
//   ^
  ),
// ^
);
</code>```

This syntax is part of ECMAScript 2017, and is not supported by Node.js before version 8.0.0, but can be transpiled using Babel.

Body:
I keep getting a SyntaxError: Unexpected token )' error for the following code:

passport.use(
  'local-signup',
  new LocalStrategy({
      usernameField: 'email',
      passwordField: 'password',
      passReqToCallback: true, // pass back req to callback
    },
    (req, email, password, done) => {
      // ...
    },
  ),
);

It really only started after I put arrow functions in. I think I'm missing something syntax-wise. I'm using the airbnb style guide & linter btw. Running Node.js LTS. VS Code doesn't give any parsing errors either in the editor itself.
The code works when transpiled to ES2015 via Babel. I'm still curious why it isn't working with the ES6 syntax.

Body:
The problem is that in two places you're using a trailing comma in function syntax, i.e. a comma after the last argument of a function.

passport.use(
  'local-signup',
  new LocalStrategy({
      usernameField: 'email',
      passwordField: 'password',
      passReqToCallback: true, // pass back req to callback
    },
    (req, email, password, done) => {
      // ...
    },
//   ^
  ),
// ^
);

This syntax is part of ECMAScript 2017, and is not supported by Node.js before version 8.0.0, but can be transpiled using Babel.


问:
automatically c++ source code formatting in Visual Studio 2013
how can I format or align with Visual Studio 2013 several c++ source codes in all projects?

Is there a opportunity for an individual template which I can use across projects?

An example with the actual code:

```<code>for(int i= 0; i<(n+  m) ;  i++){
}
</code>```

An example how the desired code look like:

```<code>for ( int i = 0; i < (n + m); i++ )
{
}
</code>```

I use the formating with CTRL+K -> CTRL+D for the actual document and CTRL+K -> CTRL+F for the actual selection. But this doesn't satisfy my individual requirements. How can I configure this for my own requierements?

If there is not an opportunity with available tools on visual studio 2013, I will look for plugins.

答:
Try the AStyle plugin: https://marketplace.visualstudio.com/items?itemName=Lukamicoder.AStyleExtension

Set it to format on save and then ctrl+s becomes the format command (if you want it to format frequently).  Plus, with it using AStyle, you can heavily customize to your formatting conventions.

We also use a astyle config file and have a build server that periodically executes formatting on the repo.  You can do the same using a batch file:

```<code>:: This script can be setup to run on a daily or weekly basis to clean up code commits

:: TODO : add directories and options for formatting
astyle --options=config.astyle -r ..\..\Source\*.cpp

:: TODO : add directories and messages for committing.
svn commit -m "[AUTO] Astyle Autoformatting" ..\..\Source\
</code>```

Where the config.astyle looks like:

```<code>--suffix=none # do not retain a backup of the original file

--style=allman

--indent=spaces=4
--convert-tabs

--indent-switches
--pad-oper

--align-pointer=type
--align-reference=type

--max-instatement-indent=40

--keep-one-line-blocks
--keep-one-line-statements
</code>```

To your taste.

Body:
how can I format or align with Visual Studio 2013 several c++ source codes in all projects?

Is there a opportunity for an individual template which I can use across projects?

An example with the actual code:

for(int i= 0; i<(n+  m) ;  i++){
}

An example how the desired code look like:

for ( int i = 0; i < (n + m); i++ )
{
}

I use the formating with CTRL+K -> CTRL+D for the actual document and CTRL+K -> CTRL+F for the actual selection. But this doesn't satisfy my individual requirements. How can I configure this for my own requierements?

If there is not an opportunity with available tools on visual studio 2013, I will look for plugins.

Body:
Try the AStyle plugin: https://marketplace.visualstudio.com/items?itemName=Lukamicoder.AStyleExtension

Set it to format on save and then ctrl+s becomes the format command (if you want it to format frequently).  Plus, with it using AStyle, you can heavily customize to your formatting conventions.

We also use a astyle config file and have a build server that periodically executes formatting on the repo.  You can do the same using a batch file:

:: This script can be setup to run on a daily or weekly basis to clean up code commits

:: TODO : add directories and options for formatting
astyle --options=config.astyle -r ..\..\Source\*.cpp

:: TODO : add directories and messages for committing.
svn commit -m "[AUTO] Astyle Autoformatting" ..\..\Source\

Where the config.astyle looks like:

--suffix=none # do not retain a backup of the original file

--style=allman

--indent=spaces=4
--convert-tabs

--indent-switches
--pad-oper

--align-pointer=type
--align-reference=type

--max-instatement-indent=40

--keep-one-line-blocks
--keep-one-line-statements

To your taste.


问:
sh_none is not a member of 'std::basic_filebuf<_Elem,_Traits>'
I am trying to use the Microsoft Specific filebuf::sh_none variable to open an fstream in an exclusive mode (another Microsoft specific function). I am getting the above error. I am importing <fstream>. How can I fix this error?

UPDATE: I found this thread, where it was suggested that I try _SH_DENYNO instead. The code compiles, I am testing it now. This doesn't make any sense to me, as this isn't documented in the function.

答:
What version of Visual C++ are you using?

The Visual C++ 6 documentation you linked to is the pre-standard version of iostreams, from #include <fstream.h>.  It's no longer available, and even in Visual C++ 6.0 was only there for backward compatibility.

Also, _SH_DENYNO is the opposite of exclusive mode.  You want _SH_DENYRW to get the same behavior as sh_none.  Here is the new documentation: http://msdn.microsoft.com/en-us/library/44cs32f9.aspx, which ends up directing you to http://msdn.microsoft.com/en-us/library/8f30b0db.aspx for details on the third parameter.

ContentLicense: CC BY-SA 2.5


问:
What does "JPRT" means in OpenJDK
I'm looking for where the version information is stored in OpenJDK source tree and noticed the file "make/jprt.properties" has some relevant information there.
What does JPRT means in that context?</p>

答:
My guess is that "jprt" is a regression testing tool / cluster used for regression testing the Java platform.

(A Google search for "jprt" includes hits with oblique references to a "jprt" command, and to JPRT machines.)

ContentLicense: CC BY-SA 4.0

Title: What does "JPRT" means in OpenJDK


问:
IF/ELSE $(document).ready Statement
I'm trying to write some jQuery to remove the default selected option of a select box once. Currently the $("#edit-field option:selected").remove(); removed = true;}; Works, but I'm having trouble putting it into a if/else statement.

```<code>$(document).ready (function remove() {
"use strict";
var removed = false;
if (removed = false) {
$("#edit-field option:selected").remove(); removed = true;}; else {
remove();}}
</code>```

Can anyone see anything wrong with my code?

答:
Your error is a very common beginner error.

= always assigns a value, you cannot use it in comparisons. Use == or === to compare values. So the simple fix would be:

```<code>if(removed === false)
</code>```

BUT... comparisons like if (x == true) ... or if (x == false) ... are an anti-pattern. Don't do that. if (x) ... or if (!x) ... is enough.

Also, your entire code is superfluous. Don't keep a global variable that stores whether you have removed something. That's not necessary.

jQuery will not produce an error when you try to remove something twice, or try to remove something that is not there at all. This is much better:

```<code>$(document).ready(function remove() {
    $("#edit-field option:selected").remove();
});
</code>```

Title: IF/ELSE $(document).ready Statement

Body:
I'm trying to write some jQuery to remove the default selected option of a select box once. Currently the $("#edit-field option:selected").remove(); removed = true;}; Works, but I'm having trouble putting it into a if/else statement.

$(document).ready (function remove() {
"use strict";
var removed = false;
if (removed = false) {
$("#edit-field option:selected").remove(); removed = true;}; else {
remove();}}

Can anyone see anything wrong with my code?

Body:
Your error is a very common beginner error.

= always assigns a value, you cannot use it in comparisons. Use == or === to compare values. So the simple fix would be:

if(removed === false)

BUT... comparisons like if (x == true) ... or if (x == false) ... are an anti-pattern. Don't do that. if (x) ... or if (!x) ... is enough.

Also, your entire code is superfluous. Don't keep a global variable that stores whether you have removed something. That's not necessary.

jQuery will not produce an error when you try to remove something twice, or try to remove something that is not there at all. This is much better:

$(document).ready(function remove() {
    $("#edit-field option:selected").remove();
});


问:
Why language change required app to restart in Objective C
I am new in iOS and I am facing problem in language conversion

For English I am using code like this

```<code> [[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObjects:@"en", nil] forKey:@"AppleLanguages"];
            [[NSUserDefaults standardUserDefaults]synchronize];

            //to set the selected language at runtime (dynamically)
            NSLog(@"Language set=Malay");
            [NSBundle setLanguage:@"en"];
            MenuScreen *menu=[[MenuScreen alloc] initWithNibName:@"MenuScreen" bundle:nil];
            [self.navigationController pushViewController:menu animated:YES];
</code>```

For Thai Language I used code like this

```<code>[[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObjects:@"th-TH", nil] forKey:@"AppleLanguages"];
            [[NSUserDefaults standardUserDefaults]synchronize];

            //to set the selected language at runtime (dynamically)
            NSLog(@"Language set=Malay");
            [NSBundle setLanguage:@"th-TH"];
            MenuScreen *menu=[[MenuScreen alloc] initWithNibName:@"MenuScreen" bundle:nil];
            [self.navigationController pushViewController:menu animated:YES];
</code>```

But every time it required to restart app. Is there is any solution for this or any thing I am doing wrong.
Thanks in Advance!

答:
Hi in ios we have bundle for to store the localization files..
When we switch the language using
[[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObjects:@"th-TH", nil] forKey:@"AppleLanguages"];
            [[NSUserDefaults standardUserDefaults]synchronize];

it just change the locale of current application not the bundle of localization.

To change the language inApp you need to change the language bundle for that.
To change language inApp you need to use

BundleLocalization

https://github.com/cmaftuleac/BundleLocalization

[BundleLocalization sharedInstance].language = @"de";
NSLog(@"Application language: %@", [BundleLocalization sharedInstance].language);

Body:
I am new in iOS and I am facing problem in language conversion

For English I am using code like this

 [[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObjects:@"en", nil] forKey:@"AppleLanguages"];
            [[NSUserDefaults standardUserDefaults]synchronize];

            //to set the selected language at runtime (dynamically)
            NSLog(@"Language set=Malay");
            [NSBundle setLanguage:@"en"];
            MenuScreen *menu=[[MenuScreen alloc] initWithNibName:@"MenuScreen" bundle:nil];
            [self.navigationController pushViewController:menu animated:YES];

For Thai Language I used code like this

[[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObjects:@"th-TH", nil] forKey:@"AppleLanguages"];
            [[NSUserDefaults standardUserDefaults]synchronize];

            //to set the selected language at runtime (dynamically)
            NSLog(@"Language set=Malay");
            [NSBundle setLanguage:@"th-TH"];
            MenuScreen *menu=[[MenuScreen alloc] initWithNibName:@"MenuScreen" bundle:nil];
            [self.navigationController pushViewController:menu animated:YES];

But every time it required to restart app. Is there is any solution for this or any thing I am doing wrong.
Thanks in Advance!


问:
Cyclic Barrier Exception Handling
I am facing an issue with Cyclic barrier, please look in to the code below -

MeetingPoint1.java

```<code>public class MeetingPoint1 implements Runnable{

    @Override
    public void run() {
        System.out.println(" MeetingPoint1 one cleared... ");
    }

}
</code>```

MeetingPoint2.java

```<code>public class MeetingPoint2 implements Runnable{

    @Override
    public void run() {
        System.out.println(" MeetingPoint Two cleared... ");
    }

}
</code>```

VehicalRunnable.java

```<code>import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * @author chouhan_r
 *
 */
public class VehicleRunnable implements Runnable {

    private CyclicBarrier barrier1;
    private CyclicBarrier barrier2;

    public VehicleRunnable(CyclicBarrier barrier1, CyclicBarrier barrier2) {
        this.barrier1 = barrier1;
        this.barrier2 = barrier2;
    }

    /* (non-Javadoc)
     * @see java.lang.Runnable#run()
     */
    @Override
    public void run() {
        try {
            Thread.sleep(1000);
            System.out.println(Thread.currentThread().getName() +" Waiting at Meeting Point 1");
            if(Thread.currentThread().getName().equalsIgnoreCase("Car")){
                throw new RuntimeException("something weird happened");
            }
            barrier1.await();
            Thread.sleep(1000);
            System.out.println(Thread.currentThread().getName() +" Waiting at Meeting Point 2");
            barrier2.await();

        } catch(BrokenBarrierException | RuntimeException | InterruptedException e){
            e.printStackTrace();
        }

    }

}
</code>```

CyclicBarrierMain.java

```<code>import java.util.concurrent.CyclicBarrier;

/**
 * @author chouhan_r
 *
 */
public class CyclicBarrierMain {

    /**
     * @param args
     */
    public static void main(String[] args) {
        MeetingPoint1 meetingPoint1 = new MeetingPoint1();
        MeetingPoint2 meetingPoint2 = new MeetingPoint2();

        CyclicBarrier barrier1 = new CyclicBarrier(3, meetingPoint1);
        CyclicBarrier barrier2 = new CyclicBarrier(3, meetingPoint2);

        VehicleRunnable car = new VehicleRunnable(barrier1, barrier2);
        VehicleRunnable bike = new VehicleRunnable(barrier1, barrier2);
        VehicleRunnable bus= new VehicleRunnable(barrier1, barrier2);
        new Thread(car,"Car").start();
        new Thread(bike,"Bike").start();
        new Thread(bus,"Bus").start();
    }

}
</code>```

When the thread throws some exception all other threads wait at the barrier1 is there any way to run the waiting threads till barrier2 ?? Is it a better Idea to put the barrier.await() method inside the finally block ??

答:
Ideally you should be using the timeout version of the await. If one of the threads are blocked for a very long time; then this gives a chance for all the barriers to exit.

```<code>try {
   leader = barrier.await(10, TimeUnit.MILLISECONDS); // waits for 10 millis - throws exception if timed out or throws BarrierBrokenExcepion if Barrier is Broker
} catch (TimeoutException e) {

  if (barrier.isBroken()) { //on timeout checks if barrier is broken and exits
    System.out.println("BARRIER is broken "+Thread.currentThread().getName());
    break;
  }

} catch (BrokenBarrierException e){
   e.printStackTrace();
   break;
}
</code>```

You could also call reset() on the thread where the barrier was missed / threw an Exception. This will cause the an BarrierBrokenException on the other two hanging threads. The rest is implementation details.

Title: Cyclic Barrier Exception Handling

Body:
I am facing an issue with Cyclic barrier, please look in to the code below -

MeetingPoint1.java

public class MeetingPoint1 implements Runnable{

    @Override
    public void run() {
        System.out.println(" MeetingPoint1 one cleared... ");
    }

}

MeetingPoint2.java

public class MeetingPoint2 implements Runnable{

    @Override
    public void run() {
        System.out.println(" MeetingPoint Two cleared... ");
    }

}

VehicalRunnable.java

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * @author chouhan_r
 *
 */
public class VehicleRunnable implements Runnable {

    private CyclicBarrier barrier1;
    private CyclicBarrier barrier2;

    public VehicleRunnable(CyclicBarrier barrier1, CyclicBarrier barrier2) {
        this.barrier1 = barrier1;
        this.barrier2 = barrier2;
    }

    /* (non-Javadoc)
     * @see java.lang.Runnable#run()
     */
    @Override
    public void run() {
        try {
            Thread.sleep(1000);
            System.out.println(Thread.currentThread().getName() +" Waiting at Meeting Point 1");
            if(Thread.currentThread().getName().equalsIgnoreCase("Car")){
                throw new RuntimeException("something weird happened");
            }
            barrier1.await();
            Thread.sleep(1000);
            System.out.println(Thread.currentThread().getName() +" Waiting at Meeting Point 2");
            barrier2.await();

        } catch(BrokenBarrierException | RuntimeException | InterruptedException e){
            e.printStackTrace();
        }

    }

}

CyclicBarrierMain.java

import java.util.concurrent.CyclicBarrier;

/**
 * @author chouhan_r
 *
 */
public class CyclicBarrierMain {

    /**
     * @param args
     */
    public static void main(String[] args) {
        MeetingPoint1 meetingPoint1 = new MeetingPoint1();
        MeetingPoint2 meetingPoint2 = new MeetingPoint2();

        CyclicBarrier barrier1 = new CyclicBarrier(3, meetingPoint1);
        CyclicBarrier barrier2 = new CyclicBarrier(3, meetingPoint2);

        VehicleRunnable car = new VehicleRunnable(barrier1, barrier2);
        VehicleRunnable bike = new VehicleRunnable(barrier1, barrier2);
        VehicleRunnable bus= new VehicleRunnable(barrier1, barrier2);
        new Thread(car,"Car").start();
        new Thread(bike,"Bike").start();
        new Thread(bus,"Bus").start();
    }

}

When the thread throws some exception all other threads wait at the barrier1 is there any way to run the waiting threads till barrier2 ?? Is it a better Idea to put the barrier.await() method inside the finally block ??

Body:
Ideally you should be using the timeout version of the await. If one of the threads are blocked for a very long time; then this gives a chance for all the barriers to exit.

try {
   leader = barrier.await(10, TimeUnit.MILLISECONDS); // waits for 10 millis - throws exception if timed out or throws BarrierBrokenExcepion if Barrier is Broker
} catch (TimeoutException e) {

  if (barrier.isBroken()) { //on timeout checks if barrier is broken and exits
    System.out.println("BARRIER is broken "+Thread.currentThread().getName());
    break;
  }

} catch (BrokenBarrierException e){
   e.printStackTrace();
   break;
}

You could also call reset() on the thread where the barrier was missed / threw an Exception. This will cause the an BarrierBrokenException on the other two hanging threads. The rest is implementation details.


问:
Transaction management in EJB 3.0 and hibernate
I am trying to understand the transactions management and try to use its power in my already existing application developed in Struts 2, EJB 3 and hibernate 5.2.
Now I have ejb in my business layer like below

```<code>   @Stateless
    @TransactionManagement(TransactionManagementType.CONTAINER)
    public class MyEJb implements ejbxyz {

    @Override
    public void method(){
          Dao dao=new Dao() //Dao class is simple java class
          dao.fooMethod();  //this method updates some record
          dao.barMethod();  // this method updates some other record
        }
    }

    public class Dao{
         fooMethid(){
         Session session=sessFactory.openSession();
          session.beginTransaction();
         session.update(x);
              }
         barMethod(){
              try{
                   Session session=sessFactory.getCurrentSession();
                    session.getNamedQuery("xyz").executeUpdate();

                }catch(HibernateException ex){
                    session.getTransaction.rollback();
                }
             }
           }
</code>```

I understand that Transaction management should be done at service layer(at ejb in my case). But how can I achieve this over there. ?

Now the dependency is if barMethod() fails to update the record then I need to rollback the changes made in fooMethod. So basically I need both the methods to be done in one transaction.
When I execute the application it throws the below exception

```<code>Exception while barMethod getNamedQuery is not valid without active transaction
</code>```

Its because I am not beginning any transaction in barMethod. But then I really dont want to start a new transaction and want to continue with the older transaction started in fooMethod.

答:
Container managed transactions are indeed suported out of the box for EJB beans. However, your Dao class is not a managed bean - it is a regular pojo that you instantiate manualy - therefore it does not participate in any transaction started by your other ejb.
So move your Dao to separate file, annotate it with @Stateless and then inject it into your service using @EJB private Dao dao;

There is more to transactions in Ejb container though. You can control the transaction support on method level via @TransactionAttribute annotation, that specifies how should the container invoke your method with regard to transaction. That way you can control, whether your method requires its own transaction, or  if it shall participate in a transaction initiated by the caller(e.g. when invoked from ejb bean).  For more info have a look at official Java EE tutorial

Body:
I am trying to understand the transactions management and try to use its power in my already existing application developed in Struts 2, EJB 3 and hibernate 5.2.
Now I have ejb in my business layer like below

   @Stateless
    @TransactionManagement(TransactionManagementType.CONTAINER)
    public class MyEJb implements ejbxyz {

    @Override
    public void method(){
          Dao dao=new Dao() //Dao class is simple java class
          dao.fooMethod();  //this method updates some record
          dao.barMethod();  // this method updates some other record
        }
    }

    public class Dao{
         fooMethid(){
         Session session=sessFactory.openSession();
          session.beginTransaction();
         session.update(x);
              }
         barMethod(){
              try{
                   Session session=sessFactory.getCurrentSession();
                    session.getNamedQuery("xyz").executeUpdate();

                }catch(HibernateException ex){
                    session.getTransaction.rollback();
                }
             }
           }

I understand that Transaction management should be done at service layer(at ejb in my case). But how can I achieve this over there. ?

Now the dependency is if barMethod() fails to update the record then I need to rollback the changes made in fooMethod. So basically I need both the methods to be done in one transaction.
When I execute the application it throws the below exception

Exception while barMethod getNamedQuery is not valid without active transaction

Its because I am not beginning any transaction in barMethod. But then I really dont want to start a new transaction and want to continue with the older transaction started in fooMethod.


问:
C# Access Database Update Syntax Error
Is there something wrong with this query?

```<code>"UPDATE tb_EmployeeMasterList SET [EmployeeID] = " + txt_EmpId.Text +", [LastName] = '" + txt_LN.Text + "', [FirstName] = '" + txt_FN.Text + "', [MiddleName] = '" + txt_MN.Text + "', [PositionOrSkill] = '" + txt_PorS.Text + "', [BasicSalary] = " + txt_Basic.Text + ", [Allowance] = " + txt_Allow.Text + ", [Total] = " + total + ", [EPAproposedBonus] = " + txt_Bonus.Text + ", [Remarks] = '" + txt_Remarks.Text + "' WHERE ([LastName] = '" + LN + "' AND [FirstName] = '" + FN + "');"
</code>```

I keep on Getting syntax error on that query alone.

答:
There seems to be a pair of single quotes missing:

```<code>"UPDATE tb_EmployeeMasterList SET [EmployeeID] = " + txt_EmpId.Text +",
</code>```

Should be:

```<code>"UPDATE tb_EmployeeMasterList SET [EmployeeID] = '" + txt_EmpId.Text +"',
</code>```

Title: C# Access Database Update Syntax Error

Body:
Is there something wrong with this query?

"UPDATE tb_EmployeeMasterList SET [EmployeeID] = " + txt_EmpId.Text +", [LastName] = '" + txt_LN.Text + "', [FirstName] = '" + txt_FN.Text + "', [MiddleName] = '" + txt_MN.Text + "', [PositionOrSkill] = '" + txt_PorS.Text + "', [BasicSalary] = " + txt_Basic.Text + ", [Allowance] = " + txt_Allow.Text + ", [Total] = " + total + ", [EPAproposedBonus] = " + txt_Bonus.Text + ", [Remarks] = '" + txt_Remarks.Text + "' WHERE ([LastName] = '" + LN + "' AND [FirstName] = '" + FN + "');"

I keep on Getting syntax error on that query alone.

Body:
There seems to be a pair of single quotes missing:

"UPDATE tb_EmployeeMasterList SET [EmployeeID] = " + txt_EmpId.Text +",

Should be:

"UPDATE tb_EmployeeMasterList SET [EmployeeID] = '" + txt_EmpId.Text +"',


问:
GAE Datastore: Multitenancy for organization
We are now developing an application that uses GAE Datastore and trying to implement Multitenancy.
Our customers are companies, so we are going to create namespaces on a per-company basis.

My question is how should we treat company mergers and separations.

For example, when two of our customers are merged, data under two namespaces should be migrated into a single namespace. When our customer is separated into two company, some of data should be migrated into another namespace. This takes a lot of effort and we would like to avoid these operations.

How can we treat these cases smoothly? Or is namespace suitable for per-company basis? If not, how should we implement per-company based multitenancy?

答:
The general way this is handled is by creating a job that handles mergers as a batch process by read-write-delete the old to new keys as part of a transaction. Generally you'll have a bunch of business rules you throw in as part of the processing as well as the basic rekeying. For example, how will you handle 2 users having the same username?

Using Cloud Dataflow (Java & Python connectors available) is a good tool to do this.

Mergers are messy when it comes to data in most cases, so it isn't really namespaces that prevent a simpler solution.


问:
Extra margin in canvas
I'm trying to make a canvas that fits perfectly in a square browser. The problem is keep getting this extra margin at the top and left of the screen  and I'm unable to get rid of it. Any idea how I can fix this?

Code

```<code><!DOCTYPE HTML>
<html>
<head>
    <meta charset="utf-8">
</head>
<style type="text/css">

#gameCanvas {
    background-color: blue;
}

</style>

<canvas id="gameCanvas"></canvas>
<script type="text/javascript">
    var canvas = document.getElementById("gameCanvas");
    canvas.width = window.innerWidth;
    canvas.height = window.innerWidth;
</script>
<script src="cocos2d.js"></script>
</body>
</html>
</code>```

答:
Browsers have default stylesheets that include margins, padding, and more. Try this:

```<code>body {
    padding: 0;
}
</code>```

In general, CSS resets come in handy when overriding default styles.

Title: Extra margin in canvas

Body:
I'm trying to make a canvas that fits perfectly in a square browser. The problem is keep getting this extra margin at the top and left of the screen  and I'm unable to get rid of it. Any idea how I can fix this?

Code

<!DOCTYPE HTML>

    <meta charset="utf-8">

<canvas id="gameCanvas"></canvas>

Body:
Browsers have default stylesheets that include margins, padding, and more. Try this:

body {
    padding: 0;
}

In general, CSS resets come in handy when overriding default styles.


问:
Android text veiw in linear layout
I am having trouble placing two textveiw below each other. I tried using
android:Layout_below="@+id/title" but the second textview always gets placed far off and not below first text view. How do I place the two textveiws exactly below each other?

```<code><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:map="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="top"
        android:orientation="vertical">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="#453b4da7"
            android:orientation="horizontal">

            <ImageButton
                android:id="@+id/ThumbnailView"
                android:layout_width="50dp"
                android:layout_height="50dp"
                android:layout_margin="0dp"
                android:background="@drawable/ic_launcher" />

            <TextView
                android:id="@+id/title"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignTop="@+id/ThumbnailView"
                android:layout_toRightOf="@+id/ThumbnailView"
                android:text="loading City"
                android:textColor="#FF040404"
                android:textSize="15dip"
                android:textStyle="bold"
                android:typeface="sans" />

            <TextView
                android:id="@+id/location"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/title"
                android:layout_marginTop="20dip"
                android:layout_toRightOf="@+id/ThumbnailView"
                android:text="Loading Locality"
                android:textColor="#343434"
                android:textSize="10dip" />

        </LinearLayout>

    </LinearLayout>

</FrameLayout>
</code>```

答:
This will do the trick:</p>

```<code><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:map="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="top"
        android:orientation="vertical">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="#453b4da7"
            android:orientation="horizontal">

            <ImageButton
                android:id="@+id/ThumbnailView"
                android:layout_width="50dp"
                android:layout_height="50dp"
                android:layout_margin="0dp"
                android:background="@drawable/ic_launcher" />

            <TextView
                android:id="@+id/title"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignTop="@+id/ThumbnailView"
                android:layout_toRightOf="@+id/ThumbnailView"
                android:text="loading City"
                android:textColor="#FF040404"
                android:textSize="15dip"
                android:textStyle="bold"
                android:typeface="sans" />

            <TextView
                android:id="@+id/location"
                android:layout_width="fill_parent"

                android:layout_height="wrap_content"
                android:layout_below="@+id/title"
                android:layout_marginTop="20dip"
                android:layout_toRightOf="@+id/ThumbnailView"
                android:text="Loading Locality"
                android:textColor="#343434"
                android:textSize="10dip" />

        </RelativeLayout>

    </LinearLayout>

</FrameLayout>
</code>```

Title: Android text veiw in linear layout

Body:
I am having trouble placing two textveiw below each other. I tried using
android:Layout_below="@+id/title" but the second textview always gets placed far off and not below first text view. How do I place the two textveiws exactly below each other?

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:map="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="top"
        android:orientation="vertical">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="#453b4da7"
            android:orientation="horizontal">

            <ImageButton
                android:id="@+id/ThumbnailView"
                android:layout_width="50dp"
                android:layout_height="50dp"
                android:layout_margin="0dp"
                android:background="@drawable/ic_launcher" />

            <TextView
                android:id="@+id/title"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignTop="@+id/ThumbnailView"
                android:layout_toRightOf="@+id/ThumbnailView"
                android:text="loading City"
                android:textColor="#FF040404"
                android:textSize="15dip"
                android:textStyle="bold"
                android:typeface="sans" />

            <TextView
                android:id="@+id/location"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/title"
                android:layout_marginTop="20dip"
                android:layout_toRightOf="@+id/ThumbnailView"
                android:text="Loading Locality"
                android:textColor="#343434"
                android:textSize="10dip" />

        </LinearLayout>

    </LinearLayout>

</FrameLayout>

Body:
This will do the trick:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:map="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="top"
        android:orientation="vertical">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="#453b4da7"
            android:orientation="horizontal">

            <ImageButton
                android:id="@+id/ThumbnailView"
                android:layout_width="50dp"
                android:layout_height="50dp"
                android:layout_margin="0dp"
                android:background="@drawable/ic_launcher" />

            <TextView
                android:id="@+id/title"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignTop="@+id/ThumbnailView"
                android:layout_toRightOf="@+id/ThumbnailView"
                android:text="loading City"
                android:textColor="#FF040404"
                android:textSize="15dip"
                android:textStyle="bold"
                android:typeface="sans" />

            <TextView
                android:id="@+id/location"
                android:layout_width="fill_parent"

                android:layout_height="wrap_content"
                android:layout_below="@+id/title"
                android:layout_marginTop="20dip"
                android:layout_toRightOf="@+id/ThumbnailView"
                android:text="Loading Locality"
                android:textColor="#343434"
                android:textSize="10dip" />

        </RelativeLayout>

    </LinearLayout>

</FrameLayout>


问:
scanf(), field width, inf and nan
Per the C standard from 1999, scanf() and strtod() should accept infinity and NaN as inputs (if supported by the implementation).

The descriptions of both functions have peculiar language, which may be open to interpretations.

scanf():

An input item is defined as the longest sequence of input characters
  which does not exceed any specified field width and which is, or is a
  prefix of, a matching input sequence.

strtod():

The subject sequence is defined as the longest initial subsequence of
  the input string, starting with the first non-white-space character,
  that is of the expected form.

While the latter excerpt appears to be strict in requiring the specific forms of "INF", "INFINITY", "NAN" or "NAN(n-char-sequence-opt)", the former isn't and one would think that the following code should produce infinity and NaN because the field width covers prefixes of matching input sequences:

```<code>int r;
double d;
d = 0; r = sscanf("inf", "%2le", &d);
printf("%d %e\n", r, d);
d = 0; r = sscanf("nan", "%2le", &d);
printf("%d %e\n", r, d);
</code>```

There's also this bit on scanf():

a,e,f,g Matches an optionally signed floating-point number, infinity,
  or NaN, whose format is the same as expected for the subject sequence
  of the strtod function. The corresponding argument shall be a pointer
  to floating.

Is this simply a failure to document that a field width of 2, which is shorter than the expected shortest forms ("inf" or "nan"), does not make the otherwise matching prefixes "in" and "na" valid matches?

答:
There is no need to document this specific case because it's covered already in one of your quotes from the standard:

An input item is defined as the longest sequence of input characters
  which does not exceed any specified field width and which is, or is a
  prefix of, a matching input sequence.

Consider this simple case:

```<code>int ch;
int res;
const char *input_fmt;

ch = 0;
input_fmt = "%*d%c";
res = sscanf("123456789012345678901234567890abc", input_fmt, &ch);
printf("%d\t%c\n", res, ch);

// 1      a
</code>```

Because there is no field width for the %d conversion specification, it will match infinitely many characters 0-9, which is why ch=='a' after scanning is finished; the value of n is unimportant here. Contrast that with the output using input_fmt="%*2d%c":

```<code>1      3
</code>```

The field width for the first conversion specification was limited to 2 characters, resulting in %c matching 3. This is where the "prefix" bit comes in. 12 is a prefix of 123456..., which would match the %d conversion specification. Another example:

```<code>input_fmt = "%*2d%c";
res = sscanf("1a3456789012345678901234567890bc", input_fmt, &ch);
printf("%d\t%c\n", res, ch);

// 1      a
</code>```

The field width limited the number of characters matching %d to 2, but the matching input sequence had length 1 since a isn't a decimal integer.

The field width limiting matched input is what's going on with inf and nan in your case:

```<code>double d;
int r;
char s[10];

// 0       0.000000        ""
*s = 0; d = 0; r = sscanf("infinity", "%2le%9s", &d, s);
printf("%d\t%f\t\"%s\"\n", r, d, s);

// 2       inf             "inity"
*s = 0; d = 0; r = sscanf("infinity", "%3le%9s", &d, s);
printf("%d\t%f\t\"%s\"\n", r, d, s);

// 0       0.000000        ""
*s = 0; d = 0; r = sscanf("-infinity", "%3le%9s", &d, s);
printf("%d\t%f\t\"%s\"\n", r, d, s);

// 2       -inf             "inity"
*s = 0; d = 0; r = sscanf("-infinity", "%4le%9s", &d, s);
printf("%d\t%f\t\"%s\"\n", r, d, s);
</code>```

The field width limits the number of characters in the input sequence, which may potentially prevent special forms like -inf and nan from being recognized. The behavior is documented, but it's also not immediately able to be fully understood.

Title: scanf(), field width, inf and nan

Body:
Per the C standard from 1999, scanf() and strtod() should accept infinity and NaN as inputs (if supported by the implementation).

The descriptions of both functions have peculiar language, which may be open to interpretations.

scanf():

An input item is defined as the longest sequence of input characters
  which does not exceed any specified field width and which is, or is a
  prefix of, a matching input sequence.

strtod():

The subject sequence is defined as the longest initial subsequence of
  the input string, starting with the first non-white-space character,
  that is of the expected form.

While the latter excerpt appears to be strict in requiring the specific forms of "INF", "INFINITY", "NAN" or "NAN(n-char-sequence-opt)", the former isn't and one would think that the following code should produce infinity and NaN because the field width covers prefixes of matching input sequences:

int r;
double d;
d = 0; r = sscanf("inf", "%2le", &d);
printf("%d %e\n", r, d);
d = 0; r = sscanf("nan", "%2le", &d);
printf("%d %e\n", r, d);

There's also this bit on scanf():

a,e,f,g Matches an optionally signed floating-point number, infinity,
  or NaN, whose format is the same as expected for the subject sequence
  of the strtod function. The corresponding argument shall be a pointer
  to floating.

Is this simply a failure to document that a field width of 2, which is shorter than the expected shortest forms ("inf" or "nan"), does not make the otherwise matching prefixes "in" and "na" valid matches?

Body:
There is no need to document this specific case because it's covered already in one of your quotes from the standard:

An input item is defined as the longest sequence of input characters
  which does not exceed any specified field width and which is, or is a
  prefix of, a matching input sequence.

Consider this simple case:

int ch;
int res;
const char *input_fmt;

ch = 0;
input_fmt = "%*d%c";
res = sscanf("123456789012345678901234567890abc", input_fmt, &ch);
printf("%d\t%c\n", res, ch);

// 1      a

Because there is no field width for the %d conversion specification, it will match infinitely many characters 0-9, which is why ch=='a' after scanning is finished; the value of n is unimportant here. Contrast that with the output using input_fmt="%*2d%c":

1      3

The field width for the first conversion specification was limited to 2 characters, resulting in %c matching 3. This is where the "prefix" bit comes in. 12 is a prefix of 123456..., which would match the %d conversion specification. Another example:

input_fmt = "%*2d%c";
res = sscanf("1a3456789012345678901234567890bc", input_fmt, &ch);
printf("%d\t%c\n", res, ch);

// 1      a

The field width limited the number of characters matching %d to 2, but the matching input sequence had length 1 since a isn't a decimal integer.

The field width limiting matched input is what's going on with inf and nan in your case:

double d;
int r;
char s[10];

// 0       0.000000        ""
*s = 0; d = 0; r = sscanf("infinity", "%2le%9s", &d, s);
printf("%d\t%f\t\"%s\"\n", r, d, s);

// 2       inf             "inity"
*s = 0; d = 0; r = sscanf("infinity", "%3le%9s", &d, s);
printf("%d\t%f\t\"%s\"\n", r, d, s);

// 0       0.000000        ""
*s = 0; d = 0; r = sscanf("-infinity", "%3le%9s", &d, s);
printf("%d\t%f\t\"%s\"\n", r, d, s);

// 2       -inf             "inity"
*s = 0; d = 0; r = sscanf("-infinity", "%4le%9s", &d, s);
printf("%d\t%f\t\"%s\"\n", r, d, s);

The field width limits the number of characters in the input sequence, which may potentially prevent special forms like -inf and nan from being recognized. The behavior is documented, but it's also not immediately able to be fully understood.


问:
How to interact with Telegram API
I'm really confused as I'm trying to use Telegram's APIs after reading a lot of the documentation on http://core.telegram.org.

I have registered my app and got a hash_id and all of that stuff. But I'm not sure where to begin with.

I had worked with Spotify's API before, and was able to interact with it using http://api.spotify.com/v1/method?params:values form.

I can't find the URL for Telegram's API. I also searched a lot on the internet but couldn't find any useful examples.

Does anyone know anything about getting started to work with Telegram's API?
Any help would be appreciated.

答:
I was looking for a quick solution to interact with Telegram API (not bot API which is limited) and integrate it with a python project. Found the following python client implementation which was a big help. Hope it helps someone. As others have mentioned, telegram API is complicated to understand, but you can get going with Telethon in a very short time without pre knowledge about the telegram API protocol.

https://github.com/LonamiWebs/Telethon

To install telethon just type:

```<code>pip install telethon
</code>```

Here is a short code demonstrating how easy you can get to use the API to print recent chats:

The example taken from telethon github page.

Title: How to interact with Telegram API

Body:
I was looking for a quick solution to interact with Telegram API (not bot API which is limited) and integrate it with a python project. Found the following python client implementation which was a big help. Hope it helps someone. As others have mentioned, telegram API is complicated to understand, but you can get going with Telethon in a very short time without pre knowledge about the telegram API protocol.

https://github.com/LonamiWebs/Telethon

To install telethon just type:

pip install telethon

Here is a short code demonstrating how easy you can get to use the API to print recent chats:

The example taken from telethon github page.


问:
Applying `const` CV-qualifier to decaying array-style `T arr[]` function parameter (intended to decay to `T * const arr`)
I'll start by pointing out that this question is purely out of curiosity, in so hoping to avoid discussions such as

"Consider staying away from new/dynamic arrays, and use fit-for-purpose stdlib containers instead, e.g. std::vector."

or

"Why would you want to use int arr[] parameter syntax on the first place? I always thought that it is considered to be one of the confusing abominations."

Decaying an array-style function parameter to T * const arr?

If I'm not wrong, the function signatures in the two following functions–intended to be called with a dynamically allocated C-style array–are equivalent due to decay, the first argument being (explicitly or by decay) a raw pointer to int.

```<code>// A) mutable raw ptr to mutable elements
void foo(int * arr, unsigned n)
{
  // ...
  arr = nullptr; // legal
}

// B) mutable raw ptr to mutable elements
void foo(int arr[], unsigned n)
      /* decays to int * arr */
{
  // ...
  arr = nullptr; // legal
}

// ... used e.g. as
int * arr = new int[3]{1, 2, 3}; // c++11
foo(arr, 3);
delete[] arr;
</code>```

Now, let's say for some reason we would like the raw pointer (which has been passed to the function as a copy by value) to be a const pointer (e.g. for correctness). For A), this is straight-forward:

```<code>// A') const raw ptr to mutable elements
void foo(int * const arr, unsigned n)
{
  arr = nullptr; // illegal, OK!
  // ...
}
</code>```

For B) however, I haven't been able to perform this modification.

Question:

Is it possible to specify an "array-type" function parameter (intended for a dynamic array argument) that decays into T * const arr?

(I'm naturally happy to receive a proper duplicate target that answers this; I wasn't able to find one myself. The closest one I found doesn't quite answer the above, as far as I can tell).

答:
Even more confusion with array syntax:</p>

```<code>using t_arrp = int *;

void foop(t_arrp const arr, unsigned n)
{
//  arr = nullptr; // illegal
}

using t_arr = int[];

void fooa(t_arr const arr, unsigned n)
{
    arr = nullptr; // fine
}
</code>```

Body:
I'll start by pointing out that this question is purely out of curiosity, in so hoping to avoid discussions such as

"Consider staying away from new/dynamic arrays, and use fit-for-purpose stdlib containers instead, e.g. std::vector."

or

"Why would you want to use int arr[] parameter syntax on the first place? I always thought that it is considered to be one of the confusing abominations."

Decaying an array-style function parameter to T * const arr?

If I'm not wrong, the function signatures in the two following functions–intended to be called with a dynamically allocated C-style array–are equivalent due to decay, the first argument being (explicitly or by decay) a raw pointer to int.

// A) mutable raw ptr to mutable elements
void foo(int * arr, unsigned n)
{
  // ...
  arr = nullptr; // legal
}

// B) mutable raw ptr to mutable elements
void foo(int arr[], unsigned n)
      /* decays to int * arr */
{
  // ...
  arr = nullptr; // legal
}

// ... used e.g. as
int * arr = new int[3]{1, 2, 3}; // c++11
foo(arr, 3);
delete[] arr;

Now, let's say for some reason we would like the raw pointer (which has been passed to the function as a copy by value) to be a const pointer (e.g. for correctness). For A), this is straight-forward:

// A') const raw ptr to mutable elements
void foo(int * const arr, unsigned n)
{
  arr = nullptr; // illegal, OK!
  // ...
}

For B) however, I haven't been able to perform this modification.

Question:

Is it possible to specify an "array-type" function parameter (intended for a dynamic array argument) that decays into T * const arr?

(I'm naturally happy to receive a proper duplicate target that answers this; I wasn't able to find one myself. The closest one I found doesn't quite answer the above, as far as I can tell).

Body:
Even more confusion with array syntax:

using t_arrp = int *;

void foop(t_arrp const arr, unsigned n)
{
//  arr = nullptr; // illegal
}

using t_arr = int[];

void fooa(t_arr const arr, unsigned n)
{
    arr = nullptr; // fine
}


问:
Format table in C# console application with strings of varying length
I looked through the website, couldn't find anything that specifically addressed the issue.

I have a console app that loops through, finds strings between 7-20 characters, plus date/time, plus a Flag, plus the file.

```<code>    Console.Write("=========================================================================");
Console.WriteLine("Start time: " + DateTime.UtcNow);
Console.Write("=========================================================================");
Console.WriteLine("All times in UTC.");
Console.Write("=========================================================================");
Console.WriteLine(String.Format("{0,-8}{1,17}{2,37}{3,13}", "Time", "File:Offset", "F", "String"));
Console.Write("=========================================================================");
</code>```

The problem is the string and filename+path can be varying length.  The Output uses the same string format, but depending on the length of the filename, the formatting is off.

Is there a way to have the console write items starting at a fixed position everytime.

So Time starts at 0, file:offsett starts at 17, F starts at 37, and String starts at 40.  That way it formats properly.  Also, this may be a bit more advanced, but can it truncate anything that won't fit in the column?

Thanks!

答:
You could use the PadLeft string function in c# to achieve what you want

more info here http://msdn.microsoft.com/en-us/library/system.string.padleft(v=vs.71).aspx

Body:
I looked through the website, couldn't find anything that specifically addressed the issue.

I have a console app that loops through, finds strings between 7-20 characters, plus date/time, plus a Flag, plus the file.

    Console.Write("=========================================================================");
Console.WriteLine("Start time: " + DateTime.UtcNow);
Console.Write("=========================================================================");
Console.WriteLine("All times in UTC.");
Console.Write("=========================================================================");
Console.WriteLine(String.Format("{0,-8}{1,17}{2,37}{3,13}", "Time", "File:Offset", "F", "String"));
Console.Write("=========================================================================");

The problem is the string and filename+path can be varying length.  The Output uses the same string format, but depending on the length of the filename, the formatting is off.

Is there a way to have the console write items starting at a fixed position everytime.

So Time starts at 0, file:offsett starts at 17, F starts at 37, and String starts at 40.  That way it formats properly.  Also, this may be a bit more advanced, but can it truncate anything that won't fit in the column?

Thanks!


问:
Adding Data to multiple tables with a single form Laravel
I am trying to insert a blog post on db, I do have two tables posts and tags tables. When I insert the create the post I want to be able to insert the data from the form in those two different tables.

create.blade.php;

```<code><div class="account_grid">

<div class="col-md-6 login-right wow fadeInRight col-md-offset-3" data-wow-delay="0.4s">
    <h3>CREATE A BLOG POST</h3>
    <p>Please fill out the required fields *</p>
    <form method="post" action="/posts"  enctype="multipart/form-data">
         {{csrf_field()}}
        <div>
            <span>Title:<label>*</label></span>
            <input type="text" id="title" name="title"  >
        </div>
        <div>
            <span>Body<label>*</label></span>
            <textarea id="body" name="body" rows="14"  ></textarea>
        </div>
        <div>
            <span>Tags:<label>*</label></span>
            <input type="text" id="tags" name="tags">
        </div>
        <div>
            <span>Image<label>*</label></span>
            <input type="file" name="image" id="image"  >
        </div>
        <input type="submit" value="Publish">

    </form>

@include('layouts.errors')
</div>
<div class="clearfix"> </div>
</div>
</code>```

On my route file I have the path that leads to PostsController.php which has a store method like below:

PostsController.php

```<code>    public function store(Request $request){

        $this->validate($request, [

            'title' =>'required|max:48',
            'body'=>'required',
            'image'=>'required',
            'tags' =>'required|max:200'
        ]);

        $post = new Post;

        $destination ='uploads';
        $image = $request->file('image');
        $filename = $image->getClientOriginalName();
        $image->move($destination, $filename);
        $location=$destination.'/'.$filename;
        $tags = request('tags');

           Post::create([
            'title'=>request('title'),
            'body' =>request('body'),
            'user_id'=>auth()->id(),
            'image' =>$destination.'/'.$filename

        ]);

        $tag = new Tag;

        Tag::create([

            'name' => $tags
        ]);

        return redirect('/blog');
    }
}
</code>```

The thing is that when I call the method I want the form data to be saved on two different tables, I have tried like below but I am getting ERROR:

MassAssignmentException in Model.php line 232:
name

I did research the issue but no luck; and yes I do have the 'name' listed in the protected $fillable array. Any suggestion on how to store data in two different tables or what type of relationship should i use.

On post.php model i do have a relationship specified. Tags belongsToMany as well as on my tag.php model Post belongsToMany

p.s New to Laravel.

tag.php model:

```<code><?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Tag extends Model
{
    //

        public function posts(){

        return $this->belongsToMany(Post::class);
    }

    public function getRouteKeyName(){

        return 'name';

    }
}
</code>```

Post.php model:

```<code><?php

namespace App;
use Carbon\Carbon;
class Post extends Model
{

    public function comments(){

        return $this->hasMany(Comment::class);
    }

    public function addComment($body, $name, $email, $user_id){

        $this->comments()->create(compact('body','name','email', 'user_id'));
    }

    public function user(){ // $comment->user->name

        return $this->belongsTo(User::class);
    }

    public function scopeFilter($query, $filters){

        if($month =$filters['month']){
//
            $query->whereMonth('created_at', Carbon::parse($month)->month);
        }

        if($year = $filters['year']){

            $query->whereYear('created_at',$year );
        }
    }

    public static function archives(){
        return static:: selectRaw('year(created_at)year, monthname(created_at)month, count(*) published')
       ->groupBy('year','month')
       ->orderByRaw('min(created_at) desc')
       ->get()
       ->toArray();
    }

    public function tags(){

        return $this->belongsToMany(Tag::class);
    }

}
</code>```

答:
Step 1:
Check your model and database. See the Tag struct table, if it has the column name.

Step 2:
To insert data with Eloquent::create you need to create one variable called fillable, in which you pass the fields that you want created in your table. Look at the example:

```<code>class Flight extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['name'];
}
</code>```

With that you can insert in your database, you can use other approach to insert
 which goes something like this

```<code>$your_table = new YourTable();
$your_table->attr = "hello world";
$your_table->save();
</code>```

Also, you don't need to create the variable new Post and after call Post::create. You can call only Post::create.

See the Laravel Eloquent doc: https://laravel.com/docs/5.4/eloquent

Body:
I am trying to insert a blog post on db, I do have two tables posts and tags tables. When I insert the create the post I want to be able to insert the data from the form in those two different tables.

create.blade.php;

CREATE A BLOG POST

Please fill out the required fields *

    <form method="post" action="/posts"  enctype="multipart/form-data">
         {{csrf_field()}}

            Title:*
            <input type="text" id="title" name="title"  >

            Body*
            <textarea id="body" name="body" rows="14"  ></textarea>

            Tags:*
            <input type="text" id="tags" name="tags">

            Image*
            <input type="file" name="image" id="image"  >

        <input type="submit" value="Publish">

    </form>

@include('layouts.errors')

On my route file I have the path that leads to PostsController.php which has a store method like below:

PostsController.php

    public function store(Request $request){

        $this->validate($request, [

            'title' =>'required|max:48',
            'body'=>'required',
            'image'=>'required',
            'tags' =>'required|max:200'
        ]);

        $post = new Post;

        $destination ='uploads';
        $image = $request->file('image');
        $filename = $image->getClientOriginalName();
        $image->move($destination, $filename);
        $location=$destination.'/'.$filename;
        $tags = request('tags');

           Post::create([
            'title'=>request('title'),
            'body' =>request('body'),
            'user_id'=>auth()->id(),
            'image' =>$destination.'/'.$filename

        ]);

        $tag = new Tag;

        Tag::create([

            'name' => $tags
        ]);

        return redirect('/blog');
    }
}

The thing is that when I call the method I want the form data to be saved on two different tables, I have tried like below but I am getting ERROR:

MassAssignmentException in Model.php line 232:
name

I did research the issue but no luck; and yes I do have the 'name' listed in the protected $fillable array. Any suggestion on how to store data in two different tables or what type of relationship should i use.

On post.php model i do have a relationship specified. Tags belongsToMany as well as on my tag.php model Post belongsToMany

p.s New to Laravel.

tag.php model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Tag extends Model
{
    //

        public function posts(){

        return $this->belongsToMany(Post::class);
    }

    public function getRouteKeyName(){

        return 'name';

    }
}

Post.php model:

<?php

namespace App;
use Carbon\Carbon;
class Post extends Model
{

    public function comments(){

        return $this->hasMany(Comment::class);
    }

    public function addComment($body, $name, $email, $user_id){

        $this->comments()->create(compact('body','name','email', 'user_id'));
    }

    public function user(){ // $comment->user->name

        return $this->belongsTo(User::class);
    }

    public function scopeFilter($query, $filters){

        if($month =$filters['month']){
//
            $query->whereMonth('created_at', Carbon::parse($month)->month);
        }

        if($year = $filters['year']){

            $query->whereYear('created_at',$year );
        }
    }

    public static function archives(){
        return static:: selectRaw('year(created_at)year, monthname(created_at)month, count(*) published')
       ->groupBy('year','month')
       ->orderByRaw('min(created_at) desc')
       ->get()
       ->toArray();
    }

    public function tags(){

        return $this->belongsToMany(Tag::class);
    }

}

Body:
Step 1:
Check your model and database. See the Tag struct table, if it has the column name.

Step 2:
To insert data with Eloquent::create you need to create one variable called fillable, in which you pass the fields that you want created in your table. Look at the example:

class Flight extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['name'];
}

With that you can insert in your database, you can use other approach to insert
 which goes something like this

$your_table = new YourTable();
$your_table->attr = "hello world";
$your_table->save();

Also, you don't need to create the variable new Post and after call Post::create. You can call only Post::create.

See the Laravel Eloquent doc: https://laravel.com/docs/5.4/eloquent


问:
Eclipse is not opening in Mac
I am trying to open Eclipse through the "Open package contents".
In the terminal after this its showing:

```<code>186590d10a33:~ mshikher$ /Users/mshikher/Downloads/eclipse/Eclipse.app/Contents/MacOS/eclipse ; exit;
objc[9445]: Class JavaLaunchHelper is implemented in both /Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/MacOS/libjli.dylib (0x100541480) and /Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/jre/lib/libinstrument.dylib (0x1005a34e0). One of the two will be used. Which one is undefined.
Error opening zip file or JAR manifest missing : ../Eclipse/lombok.jar
Error occurred during initialization of VM
agent library failed to init: instrument
logout
Saving session...
...copying shared history...
...saving history...truncating history files...
...completed.

[Process completed]
</code>```

I am using jdk-8u131-macrosx-x64.
How can I open my eclipse?

答: You must add the -javaagent:../Eclipse/lombok.jar in eclipse.ini file. It is in /Users/mshikher/Downloads/eclipse/Eclipse.app/Contents/Eclipse/eclipse.ini

Title: Eclipse is not opening in Mac

Body:
I am trying to open Eclipse through the "Open package contents".
In the terminal after this its showing:

186590d10a33:~ mshikher$ /Users/mshikher/Downloads/eclipse/Eclipse.app/Contents/MacOS/eclipse ; exit;
objc[9445]: Class JavaLaunchHelper is implemented in both /Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/MacOS/libjli.dylib (0x100541480) and /Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/jre/lib/libinstrument.dylib (0x1005a34e0). One of the two will be used. Which one is undefined.
Error opening zip file or JAR manifest missing : ../Eclipse/lombok.jar
Error occurred during initialization of VM
agent library failed to init: instrument
logout
Saving session...
...copying shared history...
...saving history...truncating history files...
...completed.

[Process completed]

I am using jdk-8u131-macrosx-x64.
How can I open my eclipse?