问:
Issue mapping field from a class to an object from a different database using springboot hibernate
I have a Flight class which has an Aircraft and an Operator field. The Flight is stored in a local database for now, while the other two classes are stored in another database and they are managed by a different application. I've tried multiple approaches to mapping the aircraft and operator fields to the Flight class, but failed every time with different problems causing exceptions.

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@ToString
@Entity
@Table(schema = "app2")
public class Flight implements Serializable {
    @Id
    @GeneratedValue(
            strategy = GenerationType.SEQUENCE,
            generator = "flight_sequence"
    )
    @SequenceGenerator(
            name = "flight_sequence",
            allocationSize = 1
    )
    @Column(nullable = false, updatable = false)
    private Long id;

    private String callsign;
    private Aircraft aircraft;
    private Date date;
    private Operator operator;
    private String origin;
    private Date offBlockTimeEst;
    private String destination;
    private Date arrivalTimeEst;
}
```
<pre class="lang-java prettyprint-override"><code>@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(schema = "app1", indexes = @Index(name = "reg_index", columnList = "registration"))
public class Aircraft implements Serializable {
    @Id
    @GeneratedValue(
            strategy = GenerationType.SEQUENCE,
            generator = "aircraft_sequence"
    )
    @SequenceGenerator(
            name = "aircraft_sequence",
            allocationSize = 1
    )
    @Column(nullable = false, updatable = false)
    private Long id;
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name="operator_id", nullable=false)
    private Operator operator;
    private String registration;
}
</code>```

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(schema = "app1")
public class Operator implements Serializable {
    @Id
    @GeneratedValue(
            strategy = GenerationType.SEQUENCE,
            generator = "operator_sequence"
    )
    @SequenceGenerator(
            name = "operator_sequence",
            allocationSize = 1
    )
    @Column(nullable = false, updatable = false)
    private Long id;
    private String name;
    private String country;
    private String email;
    @OneToMany(fetch = FetchType.LAZY, mappedBy="operator")
    @JsonIgnore
    private Set<Aircraft> aircrafts;
}
```
<p>The database connection configurations are as follows:</p>
<pre class="lang-java prettyprint-override"><code>@Configuration
@PropertySource({"classpath:application.properties"})
@EnableJpaRepositories(
        basePackages = "com.user.project.repository.app2",
        entityManagerFactoryRef = "app2EntityManager",
        transactionManagerRef = "app2TransactionManager")
public class App2DBConfiguration {
    @Autowired
    private Environment env;

    @Primary
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource app2DataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    @Primary
    public LocalContainerEntityManagerFactoryBean app2EntityManager() {
        LocalContainerEntityManagerFactoryBean em
                = new LocalContainerEntityManagerFactoryBean();
        em.setDataSource(app2DataSource());
        em.setPackagesToScan(
                "com.user.project.domain.app2", "com.user.project.domain.app1");

        HibernateJpaVendorAdapter vendorAdapter
                = new HibernateJpaVendorAdapter();
        em.setJpaVendorAdapter(vendorAdapter);
        HashMap<String, Object> properties = new HashMap<>();
        properties.put("hibernate.hbm2ddl.auto",
                env.getProperty("spring.jpa.hibernate.ddl-auto"));
        properties.put("hibernate.dialect",
                env.getProperty("spring.jpa.properties.hibernate.dialect"));
        properties.put("hibernate.dialect.storage_engine",
                env.getProperty("spring.jpa.properties.hibernate.dialect.storage_engine"));
        em.setJpaPropertyMap(properties);

        return em;
    }

    @Primary
    @Bean
    public PlatformTransactionManager app2TransactionManager() {
        JpaTransactionManager transactionManager
                = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(
                app2EntityManager().getObject());
        return transactionManager;
    }
}
</code>```

@Configuration
@PropertySource({"classpath:application.properties"})
@EnableJpaRepositories(
        basePackages = "com.user.project.repository.app1",
        entityManagerFactoryRef = "app1EntityManager",
        transactionManagerRef = "app1TransactionManager")
public class App1DBConfiguration {
    @Autowired
    private Environment env;

    @Bean
    @ConfigurationProperties(prefix = "spring.app1")
    public DataSource app1DataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean app1EntityManager() {
        LocalContainerEntityManagerFactoryBean em
                = new LocalContainerEntityManagerFactoryBean();
        em.setDataSource(app1DataSource());
        em.setPackagesToScan(
                "com.user.project.domain.app1");

        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        em.setJpaVendorAdapter(vendorAdapter);
        HashMap<String, Object> properties = new HashMap<>();
        properties.put("hibernate.hbm2ddl.auto",
                "none");
        properties.put("hibernate.implicit_naming_strategy", "org.springframework.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy");
        properties.put("hibernate.physical_naming_strategy", "org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy");
        em.setJpaPropertyMap(properties);

        return em;
    }

    @Bean
    public PlatformTransactionManager app1TransactionManager() {
        JpaTransactionManager transactionManager
                = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(
                app1EntityManager().getObject());
        return transactionManager;
    }
}
```
<p>If the <code>Flight</code> class is set up to store the whole <code>Aircraft</code> or <code>Operator</code> object in the database, then whenever I try to access fields of these two classes I get the following exception:
<code>org.hibernate.LazyInitializationException : could not initialize proxy – no Session</code>.</p>
<p>I've also tried adding a <code>@ManyToOne</code> and a <code>@JoinColumn(name="aircraft_id")</code> but I get the following exception: <code>object references an unsaved transient instance - save the transient instance before flushing</code>. After trying to solve this by adding <code>cascade = CascadeType.ALL</code>, I get the following exception: <code>detached entity passed to persist</code> and it also created an aircraft and an operator table in the database which isn't ideal.</p>
<pre class="lang-java prettyprint-override"><code>org.springframework.dao.InvalidDataAccessApiUsageException: detached entity passed to persist: com.user.project.domain.app1.Aircraft; nested exception is org.hibernate.PersistentObjectException: detached entity passed to persist: com.user.project.domain.app1.Aircraft
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:297)
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:233)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:551)
    at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:61)
    at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:242)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:152)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:174)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:97)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:215)
    at com.sun.proxy.$Proxy132.save(Unknown Source)
    at com.user.project.parser.MessageParseService.parseMessage(MessageParseService.java:62)
    at com.user.project.parser.MessageParseService$$FastClassBySpringCGLIB$$70b64fcd.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218)
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:793)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:763)
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:123)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:388)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:119)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:763)
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:708)
    at com.user.project.parser.MessageParseService$$EnhancerBySpringCGLIB$$6e9c298c.parseMessage(<generated>)
    at com.user.project.connector.QueueConnector.listen(QueueConnector.java:25)
    at sun.reflect.GeneratedMethodAccessor89.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.messaging.handler.invocation.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:169)
    at org.springframework.messaging.handler.invocation.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:119)
    at org.springframework.amqp.rabbit.listener.adapter.HandlerAdapter.invoke(HandlerAdapter.java:75)
    at org.springframework.amqp.rabbit.listener.adapter.MessagingMessageListenerAdapter.invokeHandler(MessagingMessageListenerAdapter.java:262)
    at org.springframework.amqp.rabbit.listener.adapter.MessagingMessageListenerAdapter.invokeHandlerAndProcessResult(MessagingMessageListenerAdapter.java:208)
    at org.springframework.amqp.rabbit.listener.adapter.MessagingMessageListenerAdapter.onMessage(MessagingMessageListenerAdapter.java:147)
    at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.doInvokeListener(AbstractMessageListenerContainer.java:1670)
    at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.actualInvokeListener(AbstractMessageListenerContainer.java:1589)
    at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.invokeListener(AbstractMessageListenerContainer.java:1577)
    at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.doExecuteListener(AbstractMessageListenerContainer.java:1568)
    at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.executeListener(AbstractMessageListenerContainer.java:1512)
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.doReceiveAndExecute(SimpleMessageListenerContainer.java:993)
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.receiveAndExecute(SimpleMessageListenerContainer.java:940)
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.access$1600(SimpleMessageListenerContainer.java:84)
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer$AsyncMessageProcessingConsumer.mainLoop(SimpleMessageListenerContainer.java:1317)
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer$AsyncMessageProcessingConsumer.run(SimpleMessageListenerContainer.java:1223)
    at java.lang.Thread.run(Thread.java:748)
Caused by: org.hibernate.PersistentObjectException: detached entity passed to persist: com.user.project.domain.app1.Aircraft
    at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:120)
    at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:118)
    at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:784)
    at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:752)
    at org.hibernate.engine.spi.CascadingActions$7.cascade(CascadingActions.java:298)
    at org.hibernate.engine.internal.Cascade.cascadeToOne(Cascade.java:510)
    at org.hibernate.engine.internal.Cascade.cascadeAssociation(Cascade.java:434)
    at org.hibernate.engine.internal.Cascade.cascadeProperty(Cascade.java:220)
    at org.hibernate.engine.internal.Cascade.cascade(Cascade.java:153)
    at org.hibernate.event.internal.AbstractSaveEventListener.cascadeBeforeSave(AbstractSaveEventListener.java:427)
    at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:264)
    at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:193)
    at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:135)
    at org.hibernate.event.internal.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:185)
    at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:128)
    at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:55)
    at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:107)
    at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:760)
    at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:746)
    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.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:311)
    at com.sun.proxy.$Proxy120.persist(Unknown Source)
    at org.springframework.data.jpa.repository.support.SimpleJpaRepository.save(SimpleJpaRepository.java:647)
    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.data.repository.core.support.RepositoryMethodInvoker$RepositoryFragmentMethodInvoker.lambda$new$0(RepositoryMethodInvoker.java:289)
    at org.springframework.data.repository.core.support.RepositoryMethodInvoker.doInvoke(RepositoryMethodInvoker.java:137)
    at org.springframework.data.repository.core.support.RepositoryMethodInvoker.invoke(RepositoryMethodInvoker.java:121)
    at org.springframework.data.repository.core.support.RepositoryComposition$RepositoryFragments.invoke(RepositoryComposition.java:530)
    at org.springframework.data.repository.core.support.RepositoryComposition.invoke(RepositoryComposition.java:286)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$ImplementationMethodExecutionInterceptor.invoke(RepositoryFactorySupport.java:640)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.doInvoke(QueryExecutorMethodInterceptor.java:164)
    at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.invoke(QueryExecutorMethodInterceptor.java:139)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:81)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:123)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:388)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:119)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:137)
    ... 41 more
</code>```

A new Flight object is created in the parseMessage method, then saved in the database using a repository which extends JpaRepository:

public void parseMessage(String message){
    //code which cleans up the message removed for simplicity
    Flight flight = createFlightFromMessage(message);
    flightRepository.save(flight);
}

private Flight createFlightFromMessage(String message) {
    //code which sets other fields removed for simplicity
    String registration = getRegistrationFromMessage(message);

    Aircraft aircraft = aircraftRepository.findAircraftByRegistration(registration);
    Operator operator = operatorRepository.findOperatorByCode(codePreviouslyExtractedFromMessage);

    return new Flight(..., aircraft, operator, ...);
}
```
<pre class="lang-java prettyprint-override"><code>public interface FlightRepository extends JpaRepository<Flight, Long> {
}
</code>```

public interface AircraftRepository extends JpaRepository<Aircraft, Long> {
    Aircraft findAircraftByRegistration(String registration);
}
```
<pre class="lang-java prettyprint-override"><code>public interface OperatorRepository extends JpaRepository<Operator, Long> {
    Operator findOperatorByCode(String code);
}
</code>```

The parseMessage method is called from a listen method called from a queue connector:

@Component
public class QueueConnector {
    @Autowired
    private MessageParseService messageParseService;

    @RabbitListener(queues = "myqueue")
    public void listen(String delivery) {
        String message = new String(delivery.getBytes(StandardCharsets.UTF_8));
        try{
            messageParseService.parseMessage(message);
        }
        catch (Exception e){
            e.printStackTrace();
        }
    }
}
```

What would be the correct approach to map the Aircraft and Operator which are managed in a different database by another application without getting any exceptions?

Body:
I have a Flight class which has an Aircraft and an Operator field. The Flight is stored in a local database for now, while the other two classes are stored in another database and they are managed by a different application. I've tried multiple approaches to mapping the aircraft and operator fields to the Flight class, but failed every time with different problems causing exceptions.

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@ToString
@Entity
@Table(schema = "app2")
public class Flight implements Serializable {
    @Id
    @GeneratedValue(
            strategy = GenerationType.SEQUENCE,
            generator = "flight_sequence"
    )
    @SequenceGenerator(
            name = "flight_sequence",
            allocationSize = 1
    )
    @Column(nullable = false, updatable = false)
    private Long id;

    private String callsign;
    private Aircraft aircraft;
    private Date date;
    private Operator operator;
    private String origin;
    private Date offBlockTimeEst;
    private String destination;
    private Date arrivalTimeEst;
}

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(schema = "app1", indexes = @Index(name = "reg_index", columnList = "registration"))
public class Aircraft implements Serializable {
    @Id
    @GeneratedValue(
            strategy = GenerationType.SEQUENCE,
            generator = "aircraft_sequence"
    )
    @SequenceGenerator(
            name = "aircraft_sequence",
            allocationSize = 1
    )
    @Column(nullable = false, updatable = false)
    private Long id;
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name="operator_id", nullable=false)
    private Operator operator;
    private String registration;
}

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(schema = "app1")
public class Operator implements Serializable {
    @Id
    @GeneratedValue(
            strategy = GenerationType.SEQUENCE,
            generator = "operator_sequence"
    )
    @SequenceGenerator(
            name = "operator_sequence",
            allocationSize = 1
    )
    @Column(nullable = false, updatable = false)
    private Long id;
    private String name;
    private String country;
    private String email;
    @OneToMany(fetch = FetchType.LAZY, mappedBy="operator")
    @JsonIgnore
    private Set<Aircraft> aircrafts;
}

The database connection configurations are as follows:

@Configuration
@PropertySource({"classpath:application.properties"})
@EnableJpaRepositories(
        basePackages = "com.user.project.repository.app2",
        entityManagerFactoryRef = "app2EntityManager",
        transactionManagerRef = "app2TransactionManager")
public class App2DBConfiguration {
    @Autowired
    private Environment env;

    @Primary
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource app2DataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    @Primary
    public LocalContainerEntityManagerFactoryBean app2EntityManager() {
        LocalContainerEntityManagerFactoryBean em
                = new LocalContainerEntityManagerFactoryBean();
        em.setDataSource(app2DataSource());
        em.setPackagesToScan(
                "com.user.project.domain.app2", "com.user.project.domain.app1");

        HibernateJpaVendorAdapter vendorAdapter
                = new HibernateJpaVendorAdapter();
        em.setJpaVendorAdapter(vendorAdapter);
        HashMap<String, Object> properties = new HashMap<>();
        properties.put("hibernate.hbm2ddl.auto",
                env.getProperty("spring.jpa.hibernate.ddl-auto"));
        properties.put("hibernate.dialect",
                env.getProperty("spring.jpa.properties.hibernate.dialect"));
        properties.put("hibernate.dialect.storage_engine",
                env.getProperty("spring.jpa.properties.hibernate.dialect.storage_engine"));
        em.setJpaPropertyMap(properties);

        return em;
    }

    @Primary
    @Bean
    public PlatformTransactionManager app2TransactionManager() {
        JpaTransactionManager transactionManager
                = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(
                app2EntityManager().getObject());
        return transactionManager;
    }
}

@Configuration
@PropertySource({"classpath:application.properties"})
@EnableJpaRepositories(
        basePackages = "com.user.project.repository.app1",
        entityManagerFactoryRef = "app1EntityManager",
        transactionManagerRef = "app1TransactionManager")
public class App1DBConfiguration {
    @Autowired
    private Environment env;

    @Bean
    @ConfigurationProperties(prefix = "spring.app1")
    public DataSource app1DataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean app1EntityManager() {
        LocalContainerEntityManagerFactoryBean em
                = new LocalContainerEntityManagerFactoryBean();
        em.setDataSource(app1DataSource());
        em.setPackagesToScan(
                "com.user.project.domain.app1");

        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        em.setJpaVendorAdapter(vendorAdapter);
        HashMap<String, Object> properties = new HashMap<>();
        properties.put("hibernate.hbm2ddl.auto",
                "none");
        properties.put("hibernate.implicit_naming_strategy", "org.springframework.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy");
        properties.put("hibernate.physical_naming_strategy", "org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy");
        em.setJpaPropertyMap(properties);

        return em;
    }

    @Bean
    public PlatformTransactionManager app1TransactionManager() {
        JpaTransactionManager transactionManager
                = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(
                app1EntityManager().getObject());
        return transactionManager;
    }
}

If the Flight class is set up to store the whole Aircraft or Operator object in the database, then whenever I try to access fields of these two classes I get the following exception:
org.hibernate.LazyInitializationException : could not initialize proxy – no Session.

I've also tried adding a @ManyToOne and a @JoinColumn(name="aircraft_id") but I get the following exception: object references an unsaved transient instance - save the transient instance before flushing. After trying to solve this by adding cascade = CascadeType.ALL, I get the following exception: detached entity passed to persist and it also created an aircraft and an operator table in the database which isn't ideal.

org.springframework.dao.InvalidDataAccessApiUsageException: detached entity passed to persist: com.user.project.domain.app1.Aircraft; nested exception is org.hibernate.PersistentObjectException: detached entity passed to persist: com.user.project.domain.app1.Aircraft
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:297)
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:233)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:551)
    at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:61)
    at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:242)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:152)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:174)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:97)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:215)
    at com.sun.proxy.$Proxy132.save(Unknown Source)
    at com.user.project.parser.MessageParseService.parseMessage(MessageParseService.java:62)
    at com.user.project.parser.MessageParseService$$FastClassBySpringCGLIB$$70b64fcd.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218)
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:793)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:763)
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:123)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:388)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:119)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:763)
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:708)
    at com.user.project.parser.MessageParseService$$EnhancerBySpringCGLIB$$6e9c298c.parseMessage(<generated>)
    at com.user.project.connector.QueueConnector.listen(QueueConnector.java:25)
    at sun.reflect.GeneratedMethodAccessor89.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.messaging.handler.invocation.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:169)
    at org.springframework.messaging.handler.invocation.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:119)
    at org.springframework.amqp.rabbit.listener.adapter.HandlerAdapter.invoke(HandlerAdapter.java:75)
    at org.springframework.amqp.rabbit.listener.adapter.MessagingMessageListenerAdapter.invokeHandler(MessagingMessageListenerAdapter.java:262)
    at org.springframework.amqp.rabbit.listener.adapter.MessagingMessageListenerAdapter.invokeHandlerAndProcessResult(MessagingMessageListenerAdapter.java:208)
    at org.springframework.amqp.rabbit.listener.adapter.MessagingMessageListenerAdapter.onMessage(MessagingMessageListenerAdapter.java:147)
    at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.doInvokeListener(AbstractMessageListenerContainer.java:1670)
    at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.actualInvokeListener(AbstractMessageListenerContainer.java:1589)
    at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.invokeListener(AbstractMessageListenerContainer.java:1577)
    at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.doExecuteListener(AbstractMessageListenerContainer.java:1568)
    at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.executeListener(AbstractMessageListenerContainer.java:1512)
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.doReceiveAndExecute(SimpleMessageListenerContainer.java:993)
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.receiveAndExecute(SimpleMessageListenerContainer.java:940)
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.access$1600(SimpleMessageListenerContainer.java:84)
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer$AsyncMessageProcessingConsumer.mainLoop(SimpleMessageListenerContainer.java:1317)
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer$AsyncMessageProcessingConsumer.run(SimpleMessageListenerContainer.java:1223)
    at java.lang.Thread.run(Thread.java:748)
Caused by: org.hibernate.PersistentObjectException: detached entity passed to persist: com.user.project.domain.app1.Aircraft
    at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:120)
    at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:118)
    at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:784)
    at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:752)
    at org.hibernate.engine.spi.CascadingActions$7.cascade(CascadingActions.java:298)
    at org.hibernate.engine.internal.Cascade.cascadeToOne(Cascade.java:510)
    at org.hibernate.engine.internal.Cascade.cascadeAssociation(Cascade.java:434)
    at org.hibernate.engine.internal.Cascade.cascadeProperty(Cascade.java:220)
    at org.hibernate.engine.internal.Cascade.cascade(Cascade.java:153)
    at org.hibernate.event.internal.AbstractSaveEventListener.cascadeBeforeSave(AbstractSaveEventListener.java:427)
    at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:264)
    at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:193)
    at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:135)
    at org.hibernate.event.internal.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:185)
    at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:128)
    at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:55)
    at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:107)
    at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:760)
    at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:746)
    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.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:311)
    at com.sun.proxy.$Proxy120.persist(Unknown Source)
    at org.springframework.data.jpa.repository.support.SimpleJpaRepository.save(SimpleJpaRepository.java:647)
    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.data.repository.core.support.RepositoryMethodInvoker$RepositoryFragmentMethodInvoker.lambda$new$0(RepositoryMethodInvoker.java:289)
    at org.springframework.data.repository.core.support.RepositoryMethodInvoker.doInvoke(RepositoryMethodInvoker.java:137)
    at org.springframework.data.repository.core.support.RepositoryMethodInvoker.invoke(RepositoryMethodInvoker.java:121)
    at org.springframework.data.repository.core.support.RepositoryComposition$RepositoryFragments.invoke(RepositoryComposition.java:530)
    at org.springframework.data.repository.core.support.RepositoryComposition.invoke(RepositoryComposition.java:286)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$ImplementationMethodExecutionInterceptor.invoke(RepositoryFactorySupport.java:640)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.doInvoke(QueryExecutorMethodInterceptor.java:164)
    at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.invoke(QueryExecutorMethodInterceptor.java:139)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:81)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:123)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:388)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:119)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:137)
    ... 41 more

A new Flight object is created in the parseMessage method, then saved in the database using a repository which extends JpaRepository:

public void parseMessage(String message){
    //code which cleans up the message removed for simplicity
    Flight flight = createFlightFromMessage(message);
    flightRepository.save(flight);
}

private Flight createFlightFromMessage(String message) {
    //code which sets other fields removed for simplicity
    String registration = getRegistrationFromMessage(message);

    Aircraft aircraft = aircraftRepository.findAircraftByRegistration(registration);
    Operator operator = operatorRepository.findOperatorByCode(codePreviouslyExtractedFromMessage);

    return new Flight(..., aircraft, operator, ...);
}

public interface FlightRepository extends JpaRepository<Flight, Long> {
}

public interface AircraftRepository extends JpaRepository<Aircraft, Long> {
    Aircraft findAircraftByRegistration(String registration);
}

public interface OperatorRepository extends JpaRepository<Operator, Long> {
    Operator findOperatorByCode(String code);
}

The parseMessage method is called from a listen method called from a queue connector:

@Component
public class QueueConnector {
    @Autowired
    private MessageParseService messageParseService;

    @RabbitListener(queues = "myqueue")
    public void listen(String delivery) {
        String message = new String(delivery.getBytes(StandardCharsets.UTF_8));
        try{
            messageParseService.parseMessage(message);
        }
        catch (Exception e){
            e.printStackTrace();
        }
    }
}

What would be the correct approach to map the Aircraft and Operator which are managed in a different database by another application without getting any exceptions?


来源: stackexchange

问:
Why am i getting a timeliness error from an API request?
below is my Python code to query data from an API. when I execute the code, I get the following error:

"{'code': 40000, 'message': 'Timeliness error. Please check the
request header X-Timestamp', 'data': None}"

does anyone know what I'm doing wrong? this is the link to the API docs: https://docs.apis.iobscan.io/

```<code>import requests
import json
import hmac
import hashlib
import base64
import time

base_url = 'https://apis.iobscan.io/'

params = {'chain': 'cosmoshub',
          'channel': 'channel-141',
          'port': 'transfer'
}

# Get the current timestamp, in seconds
timestamp = time.time()

# Format the timestamp as a string
timestamp_str = str(timestamp)

# Print the timestamp string
print(timestamp_str)

signing_string = f"X-Timestamp: {timestamp_str}\nURI: https://apis.iobscan.io/\nBody: requests.get('https://apis.iobscan.io/')"

secret = b"MYAPISECRET"

# Compute the HMAC-SHA256 digest of the signing string
digest = hmac.new(secret, signing_string.encode("utf-8"), hashlib.sha256).digest()

# Encode the digest as a base64 string
signature = base64.b64encode(digest)
print(signature)

headers = {'X-Api-Key': 'MYAPIKEY',
          'X-Timestamp': timestamp_str,
          'X-Signature': signature.decode("utf-8")
}

r = requests.get(base_url, params=params, headers=headers)
print(r.json())
</code>```

ContentLicense: CC BY-SA 4.0

Body:
below is my Python code to query data from an API. when I execute the code, I get the following error:

"{'code': 40000, 'message': 'Timeliness error. Please check the
request header X-Timestamp', 'data': None}"

does anyone know what I'm doing wrong? this is the link to the API docs: https://docs.apis.iobscan.io/

import requests
import json
import hmac
import hashlib
import base64
import time

base_url = 'https://apis.iobscan.io/'

params = {'chain': 'cosmoshub',
          'channel': 'channel-141',
          'port': 'transfer'
}

# Get the current timestamp, in seconds
timestamp = time.time()

# Format the timestamp as a string
timestamp_str = str(timestamp)

# Print the timestamp string
print(timestamp_str)

signing_string = f"X-Timestamp: {timestamp_str}\nURI: https://apis.iobscan.io/\nBody: requests.get('https://apis.iobscan.io/')"

secret = b"MYAPISECRET"

# Compute the HMAC-SHA256 digest of the signing string
digest = hmac.new(secret, signing_string.encode("utf-8"), hashlib.sha256).digest()

# Encode the digest as a base64 string
signature = base64.b64encode(digest)
print(signature)

headers = {'X-Api-Key': 'MYAPIKEY',
          'X-Timestamp': timestamp_str,
          'X-Signature': signature.decode("utf-8")
}

r = requests.get(base_url, params=params, headers=headers)
print(r.json())


问:
Time clock using built in RTC of STM32 bluebill
I am new in STM32 development and trying to built RTC clock that display's time on oled display.

But on screen some  random unidentified symbols are displaying by the below code.

```<code> while(1){
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
        HAL_RTC_GetTime(&hrtc, &sTime, RTC_FORMAT_BIN);
        HAL_RTC_GetDate(&hrtc, &sDate, RTC_FORMAT_BIN);
        uint8_t *a = sTime.Hours;
         char* buffer2;
          int i;

          buffer2 = malloc(9);
          if (!buffer2)
                 break;

          buffer2[8] = 0;
          for (i = 0; i <= 7; i++)
            buffer2[7 - i] = (((*a) >> i) & (0x01)) + '0';

          puts(buffer2);

//      sprintf(date,"Date: %02d.%02d.%02d\t",sDate.Date,sDate.Month,sDate.Year);
//      sprintf(time,"Time: %02d.%02d.%02d\r\n",sTime.Hours,sTime.Minutes,sTime.Seconds);
               SSD1306_GotoXY (0,0);
                   SSD1306_Puts (buffer2, &Font_11x18, 1);
                   SSD1306_GotoXY (0, 30);
                   SSD1306_Puts ("CLOCK", &Font_11x18, 1);
                   SSD1306_UpdateScreen();
                   HAL_Delay (1000);

     }
</code>```

Here is my clock configuration

Body:
I am new in STM32 development and trying to built RTC clock that display's time on oled display.

But on screen some  random unidentified symbols are displaying by the below code.

 while(1){
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
        HAL_RTC_GetTime(&hrtc, &sTime, RTC_FORMAT_BIN);
        HAL_RTC_GetDate(&hrtc, &sDate, RTC_FORMAT_BIN);
        uint8_t *a = sTime.Hours;
         char* buffer2;
          int i;

          buffer2 = malloc(9);
          if (!buffer2)
                 break;

          buffer2[8] = 0;
          for (i = 0; i <= 7; i++)
            buffer2[7 - i] = (((*a) >> i) & (0x01)) + '0';

          puts(buffer2);

//      sprintf(date,"Date: %02d.%02d.%02d\t",sDate.Date,sDate.Month,sDate.Year);
//      sprintf(time,"Time: %02d.%02d.%02d\r\n",sTime.Hours,sTime.Minutes,sTime.Seconds);
               SSD1306_GotoXY (0,0);
                   SSD1306_Puts (buffer2, &Font_11x18, 1);
                   SSD1306_GotoXY (0, 30);
                   SSD1306_Puts ("CLOCK", &Font_11x18, 1);
                   SSD1306_UpdateScreen();
                   HAL_Delay (1000);

     }

Here is my clock configuration


问:
How to rollback evolutions in scala + play framework?
I'm looking to dial back evolutions that I've previously written !Downs procedures for, how can I trigger that from the command line?


问:
I have a question about decimal division in Java
I used Java to get the ratio and added it all, but I didn't get 1.

A
B
C
D
SUM

0.3
0.33
0.333
0.3333
1.2963

0.231427910205971
0.254570701226568
0.256884980328628
0.257116408238834
1

In Google Spreadsheet, if you find the ratio and add it all up, you get 1.

However, in Java, no matter which rounding mode is selected, 1 does not come out when all the ratios are added.

How does Google Spreadsheet perform Bigdecimal operations?

How can I add all the ratios and get 1 in Java?

```<code>import org.junit.jupiter.api.Test;

import java.math.BigDecimal;
import java.math.RoundingMode;

public class TestTest {

    @Test
    public void testI() {
        RatioTest a = new RatioTest("0.3");
        RatioTest b = new RatioTest("0.33");
        RatioTest c = new RatioTest("0.333");
        RatioTest d = new RatioTest("0.3333");

        BigDecimal sum = a.getAmount().add(b.getAmount()).add(c.getAmount()).add(d.getAmount());
        System.out.println("sum : " + sum);
        a.setRatio(a.amount.divide(sum, 15, RoundingMode.FLOOR));
        b.setRatio(b.amount.divide(sum, 15, RoundingMode.FLOOR));
        c.setRatio(c.amount.divide(sum, 15, RoundingMode.FLOOR));
        d.setRatio(d.amount.divide(sum, 15, RoundingMode.FLOOR));

        System.out.println("a : " + a);
        System.out.println("b : " + b);
        System.out.println("c : " + c);
        System.out.println("d : " + d);
        System.out.println("ratio sum : " + a.getRatio().add(b.getRatio()).add(c.getRatio()).add(d.getRatio()));
    }

    private static class RatioTest {
        private BigDecimal amount;
        private BigDecimal ratio;

        public RatioTest(String amount) {
            this.amount = new BigDecimal(amount);
        }

        public BigDecimal getAmount() {
            return amount;
        }

        public BigDecimal getRatio() {
            return ratio;
        }

        public void setRatio(BigDecimal ratio) {
            this.ratio = ratio;
        }

        @Override
        public String toString() {
            return "RatioTest{" +
                    "amount=" + amount +
                    ", ratio=" + ratio +
                    '}';
        }
    }

}
</code>```

a.amount.divide(sum, 15, RoundingMode.FLOOR)
No matter which RoundingMode is used, the sum does not equal 1.

Body:
I used Java to get the ratio and added it all, but I didn't get 1.

A
B
C
D
SUM

0.3
0.33
0.333
0.3333
1.2963

0.231427910205971
0.254570701226568
0.256884980328628
0.257116408238834
1

In Google Spreadsheet, if you find the ratio and add it all up, you get 1.

However, in Java, no matter which rounding mode is selected, 1 does not come out when all the ratios are added.

How does Google Spreadsheet perform Bigdecimal operations?

How can I add all the ratios and get 1 in Java?

import org.junit.jupiter.api.Test;

import java.math.BigDecimal;
import java.math.RoundingMode;

public class TestTest {

    @Test
    public void testI() {
        RatioTest a = new RatioTest("0.3");
        RatioTest b = new RatioTest("0.33");
        RatioTest c = new RatioTest("0.333");
        RatioTest d = new RatioTest("0.3333");

        BigDecimal sum = a.getAmount().add(b.getAmount()).add(c.getAmount()).add(d.getAmount());
        System.out.println("sum : " + sum);
        a.setRatio(a.amount.divide(sum, 15, RoundingMode.FLOOR));
        b.setRatio(b.amount.divide(sum, 15, RoundingMode.FLOOR));
        c.setRatio(c.amount.divide(sum, 15, RoundingMode.FLOOR));
        d.setRatio(d.amount.divide(sum, 15, RoundingMode.FLOOR));

        System.out.println("a : " + a);
        System.out.println("b : " + b);
        System.out.println("c : " + c);
        System.out.println("d : " + d);
        System.out.println("ratio sum : " + a.getRatio().add(b.getRatio()).add(c.getRatio()).add(d.getRatio()));
    }

    private static class RatioTest {
        private BigDecimal amount;
        private BigDecimal ratio;

        public RatioTest(String amount) {
            this.amount = new BigDecimal(amount);
        }

        public BigDecimal getAmount() {
            return amount;
        }

        public BigDecimal getRatio() {
            return ratio;
        }

        public void setRatio(BigDecimal ratio) {
            this.ratio = ratio;
        }

        @Override
        public String toString() {
            return "RatioTest{" +
                    "amount=" + amount +
                    ", ratio=" + ratio +
                    '}';
        }
    }

}

a.amount.divide(sum, 15, RoundingMode.FLOOR)
No matter which RoundingMode is used, the sum does not equal 1.


问:
deploy node api to vercel
I'm trying to deploy a node express backend on Vercel, but I'm always getting 404 or 500.

I have a folder on the root of the project named "handlers", inside of it, there're multiple folders with the routes and um index.js file that gets all promises and send to the index.js file on the root of the project.

I'm not so sure how the vercel.config should be.

handler/index.js
folders structure

[handler/*.js example]

```<code>const { exec } = require("child_process");
const { promisify } = require("util");
/**
 * @param {*} event
 * @param {*} models
 * @returns
 */

module.exports.handler = async function (event, models) {

    const execPromise = promisify(exec);

    const pythonReturn = await execPromise("python3 app.py");

    const result = JSON.parse(pythonReturn.stdout)

      return {
        statusCode: 200,
        body: JSON.stringify(result),
      };

  };

  module.exports.path = "/getSurebets";
  module.exports.method = "GET";

</code>```

[server.js]

```<code>'use strict'

const express = require('express')
const bodyParser = require('body-parser')
const cors = require('cors')
const app = express()
const router = express.Router()
const aliveTime = new Date().getTime()
const PORT = process.env.PORT || 3002;
const Handler = require("./index")

router.use(cors())
router.use(bodyParser.json())
router.use(bodyParser.urlencoded({ extended: true }))

router.get('/', (req, res) => {
  req.json({ aliveTime })
})

router.use(async function(req, res){
  const event = {
    "resource": req.path,
    "path": req.path,
    "httpMethod": req.method,
    "headers": req.headers,
    "queryStringParameters": req.query,
    "pathParameters": req.params,
    "stageVariables": null,
    "body": JSON.stringify(req.body),
    "isBase64Encoded": false,
    "requestContext": {
      "authorizer": {}
    }
  }

  try{
    const response = await Handler.handler(event)
    res
      .set(response.headers)
      .status(response.statusCode)

    const data = response.body

    if(req.path.indexOf("render") < 0){
      res.send(JSON.parse(data))
    }else{
      res.send(data)
    }

  }catch(e){
    console.error(e)
    res.status(500).send(e)
  }
})

app.use('/v1/', router)
app.listen(PORT)

console.log(`Listen on http://0.0.0.0:${PORT}`)
module.exports = app
</code>```

root/index.js

```<code>const fns = require("./handlers")
const cors = require('./lib/cors')
const models = require("./models");

const extractPathValues = (pathExpression, httpPath) => {
  const pathExpressionPattern = pathExpression.replace(/{[\w]+}|:[\w]+/g, '([^/]+)')
  const pathValueRegex = new RegExp(`^${pathExpressionPattern}$`)
  const pathValues = pathValueRegex.exec(httpPath)
  return pathValues && pathValues.length > 0 ? pathValues.slice(1) : null
}

const extractPathNames = (pathExpression) => {
  const pathExpressionPattern = pathExpression?.replace(/{[\w.]+}|:[\w.]+/g, '[:{]([\\w]+)}?');
  const pathNameRegex = new RegExp(`^${pathExpressionPattern}$`)
  const pathNames = pathNameRegex.exec(pathExpression)
  return pathNames && pathNames.length > 0 ? pathNames.slice(1) : null
}

const getRouterHandler = (event) => {
  const routesByMethod = fns.filter(r => r.method === event.httpMethod)
  for(const route of routesByMethod) {
    const pathPartNames = extractPathNames(route.path)
    const pathValues = extractPathValues(route.path, event.path)
    if (pathValues && pathPartNames) {
      const params = {}
      let keyIndex = 0;
      for(const key of pathPartNames) {
        params[ key ] = pathValues[ keyIndex ]
        keyIndex++;
      }
      return {route, params}
    }
  }
}

const getHandler = async (event) => {
  return getRouterHandler(event)
}

exports.handler = async (event, context) => {
  if(event.Records) return tRender(event, context, models)
  if(process.env.NODE_ENV!=='test') console.log(event)
  const HANDLER = await getHandler(event)
  if(!HANDLER) return { statusCode: 404, body: JSON.stringify({ message: 'Not Found' }) }
  const { route, params } = HANDLER
  if(!event.pathParameters || !Object.keys(event.pathParameters).length) {
    event.pathParameters = params
  }

  if((process.env.NODE_ENV || '').trim() !== 'test') console.debug({ event })

  const response = cors(
    await route.handler(event, models, context).catch(err => {
      console.error(err)
      if(!err.statusCode || !err.body ) {
        return Promise.reject(err)
      }
      return Promise.resolve(err)
    })
  )
  return response
}

</code>```

[vercel.config]

```<code>{
    "version": 2,
    "name": "omnes-api",
    "builds": [
       { "src": "index.js", "use": "@vercel/node" }
    ],
    "routes": [
        {
          "src": "handlers/index.js",
          "dest": "index.js"
        }
      ]
 }
</code>```

Error:

Title: deploy node api to vercel

Body:
I'm trying to deploy a node express backend on Vercel, but I'm always getting 404 or 500.

I have a folder on the root of the project named "handlers", inside of it, there're multiple folders with the routes and um index.js file that gets all promises and send to the index.js file on the root of the project.

I'm not so sure how the vercel.config should be.

handler/index.js
folders structure

[handler/*.js example]

const { exec } = require("child_process");
const { promisify } = require("util");
/**
 * @param {*} event
 * @param {*} models
 * @returns
 */

module.exports.handler = async function (event, models) {

    const execPromise = promisify(exec);

    const pythonReturn = await execPromise("python3 app.py");

    const result = JSON.parse(pythonReturn.stdout)

      return {
        statusCode: 200,
        body: JSON.stringify(result),
      };

  };

  module.exports.path = "/getSurebets";
  module.exports.method = "GET";

[server.js]

'use strict'

const express = require('express')
const bodyParser = require('body-parser')
const cors = require('cors')
const app = express()
const router = express.Router()
const aliveTime = new Date().getTime()
const PORT = process.env.PORT || 3002;
const Handler = require("./index")

router.use(cors())
router.use(bodyParser.json())
router.use(bodyParser.urlencoded({ extended: true }))

router.get('/', (req, res) => {
  req.json({ aliveTime })
})

router.use(async function(req, res){
  const event = {
    "resource": req.path,
    "path": req.path,
    "httpMethod": req.method,
    "headers": req.headers,
    "queryStringParameters": req.query,
    "pathParameters": req.params,
    "stageVariables": null,
    "body": JSON.stringify(req.body),
    "isBase64Encoded": false,
    "requestContext": {
      "authorizer": {}
    }
  }

  try{
    const response = await Handler.handler(event)
    res
      .set(response.headers)
      .status(response.statusCode)

    const data = response.body

    if(req.path.indexOf("render") < 0){
      res.send(JSON.parse(data))
    }else{
      res.send(data)
    }

  }catch(e){
    console.error(e)
    res.status(500).send(e)
  }
})

app.use('/v1/', router)
app.listen(PORT)

console.log(`Listen on http://0.0.0.0:${PORT}`)
module.exports = app

root/index.js

const fns = require("./handlers")
const cors = require('./lib/cors')
const models = require("./models");

const extractPathValues = (pathExpression, httpPath) => {
  const pathExpressionPattern = pathExpression.replace(/{[\w]+}|:[\w]+/g, '([^/]+)')
  const pathValueRegex = new RegExp(`^${pathExpressionPattern}$`)
  const pathValues = pathValueRegex.exec(httpPath)
  return pathValues && pathValues.length > 0 ? pathValues.slice(1) : null
}

const extractPathNames = (pathExpression) => {
  const pathExpressionPattern = pathExpression?.replace(/{[\w.]+}|:[\w.]+/g, '[:{]([\\w]+)}?');
  const pathNameRegex = new RegExp(`^${pathExpressionPattern}$`)
  const pathNames = pathNameRegex.exec(pathExpression)
  return pathNames && pathNames.length > 0 ? pathNames.slice(1) : null
}

const getRouterHandler = (event) => {
  const routesByMethod = fns.filter(r => r.method === event.httpMethod)
  for(const route of routesByMethod) {
    const pathPartNames = extractPathNames(route.path)
    const pathValues = extractPathValues(route.path, event.path)
    if (pathValues && pathPartNames) {
      const params = {}
      let keyIndex = 0;
      for(const key of pathPartNames) {
        params[ key ] = pathValues[ keyIndex ]
        keyIndex++;
      }
      return {route, params}
    }
  }
}

const getHandler = async (event) => {
  return getRouterHandler(event)
}

exports.handler = async (event, context) => {
  if(event.Records) return tRender(event, context, models)
  if(process.env.NODE_ENV!=='test') console.log(event)
  const HANDLER = await getHandler(event)
  if(!HANDLER) return { statusCode: 404, body: JSON.stringify({ message: 'Not Found' }) }
  const { route, params } = HANDLER
  if(!event.pathParameters || !Object.keys(event.pathParameters).length) {
    event.pathParameters = params
  }

  if((process.env.NODE_ENV || '').trim() !== 'test') console.debug({ event })

  const response = cors(
    await route.handler(event, models, context).catch(err => {
      console.error(err)
      if(!err.statusCode || !err.body ) {
        return Promise.reject(err)
      }
      return Promise.resolve(err)
    })
  )
  return response
}

[vercel.config]

{
    "version": 2,
    "name": "omnes-api",
    "builds": [
       { "src": "index.js", "use": "@vercel/node" }
    ],
    "routes": [
        {
          "src": "handlers/index.js",
          "dest": "index.js"
        }
      ]
 }

Error:


问:
BotDetect:WebFormsCaptcha after adding Content Security Policy inline issue is showing in console
after adding Content Security Policy in web.config, inline style are adding and  console errors are coming. Please suggest any solution for this issue.enter image description here


问:
using requestId as AddRequestHeader parameter
Spring Cloud Gateway is using "requestId" for identifying each request, but I cannot find enough information about it. (https://github.com/spring-cloud/spring-cloud-gateway/issues/1885 says that it is not even generated by Spring Cloud Gateway.)

```<code>{
"timestamp":"2020-08-04T14:50:59.340+0000",
"path":"/some-api-path",
"status":404,
"error":"Not Found",
"requestId":"f580065b-2"
}
</code>```

I'd like use this value as GUID(globally unique identifier) in my cloud service with single gateway, by adding it as a header to downstream service request for logging.

Is uniqueness guaranteed? (If not, at least within uptime of the gateway.)

Is there a way to use it as AddRequestHeader filter parameter in Spring Cloud Gateway YAML file, or should I create a custom filter class for it?

Body:
Spring Cloud Gateway is using "requestId" for identifying each request, but I cannot find enough information about it. (https://github.com/spring-cloud/spring-cloud-gateway/issues/1885 says that it is not even generated by Spring Cloud Gateway.)

{
"timestamp":"2020-08-04T14:50:59.340+0000",
"path":"/some-api-path",
"status":404,
"error":"Not Found",
"requestId":"f580065b-2"
}

I'd like use this value as GUID(globally unique identifier) in my cloud service with single gateway, by adding it as a header to downstream service request for logging.

Is uniqueness guaranteed? (If not, at least within uptime of the gateway.)

Is there a way to use it as AddRequestHeader filter parameter in Spring Cloud Gateway YAML file, or should I create a custom filter class for it?


问:
How to preserve whitespace relative to the start of a block?
lstrip and trim options are used

Since an example is worth a thousand words:

Input template:

```<code>{% if True %}
    Lorem
    {% for i in range(3) %}
        {{ i }}
    {% endfor %}
    Ipsum
{% endif %}
</code>```

Of course this produce:

```<code>    Lorem
        0
        1
        2
    Ipsum
</code>```

My question is, what must be used to have this output:

```<code>
Lorem
    0
    1
    2
Ipsum

</code>```

I tried varying the strip and trim options, and using the + and - modifier.

Body:
lstrip and trim options are used

Since an example is worth a thousand words:

Input template:

{% if True %}
    Lorem
    {% for i in range(3) %}
        {{ i }}
    {% endfor %}
    Ipsum
{% endif %}

Of course this produce:

    Lorem
        0
        1
        2
    Ipsum

My question is, what must be used to have this output:

Lorem
    0
    1
    2
Ipsum

I tried varying the strip and trim options, and using the + and - modifier.


问:
Get Input fields of a form equal to the value entered by the user
I want the input fields in form equal to the number entered by the user in react. But I am not sure how to do that I know that it will require looping but i can't figure out the approach.
Here is the code for my form

```<code>
import React, { useEffect, useState } from "react";
import './roominfo.css';
import { ImBin } from 'react-icons/im';
import { useNavigate } from 'react-router-dom'
import RoomInfoService from '../services/RoomInfoService';

const RoomInfo = () => {

    const [rooms, setRooms] = useState('');
    const [updated, setUpdated] = useState(rooms)

    const handleInput = (event) =>{
        setRooms(event.target.value);
    }

    const handleClick = () =>{
        setUpdated(rooms);
    }

    return (
        <>
            <div className='heading'>
                <h1 style={{ marginBottom: '50px' }}>Enter Your PG Room Details</h1>
            </div>
            <form>

            <div className="form-inline" style={{ marginBottom: '50px' }}>
                <label>Enter total number of rooms:    </label>
                <input type="number" name="total_no_of_rooms" id= "myText" style={{ width: '90px'}} onChange={handleInput} />
                <button type="button" className="button add" value={rooms} onClick={handleClick}>Get Rooms</button>
                <p>Total Rooms:{updated}</p>
            </div>
            </form>
            <div>
                <form>

                        <div className="form-inline" style={{ borderBottom: '1px solid black' }}>
                            <label>Sharing Number</label>
                            <select id="shared_no" name="shared_no" title="no of shared rooms"  >
                                <option value="">---Select---</option>
                                <option value="1">Single Sharing</option>
                                <option value="2">Two Bed Sharing</option>
                                <option value="3">Three Bed Sharing</option>
                                <option value="4">Four Bed Sharing</option>
                                <option value="5">Five Bed Sharing</option>
                            </select>

                            <label>   No of Rooms:</label>
                            <input type="number" name="no_of_rooms" ></input>

                            <label>   Rent per month:</label>
                            <input type="number" style={{ width: '100px' }} name="rent_per_month"></input>

                            <label>   Total Capacity:</label>
                            <input type="number" style={{ width: '50px' }} name="total_capacity" ></input>

                            <label>   Vacancy:</label>
                            <input type="number" style={{ width: '50px' }} name="vacancy"></input>
                        </div>
                    <div className="button-section">
                        <button className="button add" type="button">Add</button>
                        <button className="button submit" type="submit">Submit</button>
                    </div>
                </form>
            </div>
        </>
    )
}

export default RoomInfo

</code>```

Can Please someone help me

Should I map it like
formValues.map((element,rooms) =>(
//form details)}

Also how to uniquely submit them. Thank you

Body:
I want the input fields in form equal to the number entered by the user in react. But I am not sure how to do that I know that it will require looping but i can't figure out the approach.
Here is the code for my form

import React, { useEffect, useState } from "react";
import './roominfo.css';
import { ImBin } from 'react-icons/im';
import { useNavigate } from 'react-router-dom'
import RoomInfoService from '../services/RoomInfoService';

const RoomInfo = () => {

    const [rooms, setRooms] = useState('');
    const [updated, setUpdated] = useState(rooms)

    const handleInput = (event) =>{
        setRooms(event.target.value);
    }

    const handleClick = () =>{
        setUpdated(rooms);
    }

    return (
        <>

Enter Your PG Room Details

            <form>

                Enter total number of rooms:
                <input type="number" name="total_no_of_rooms" id= "myText" style={{ width: '90px'}} onChange={handleInput} />
                <button type="button" className="button add" value={rooms} onClick={handleClick}>Get Rooms</button>

Total Rooms:{updated}

            </form>

                <form>

                            Sharing Number
                            <select id="shared_no" name="shared_no" title="no of shared rooms"  >
                                <option value="">---Select---</option>
                                <option value="1">Single Sharing</option>
                                <option value="2">Two Bed Sharing</option>
                                <option value="3">Three Bed Sharing</option>
                                <option value="4">Four Bed Sharing</option>
                                <option value="5">Five Bed Sharing</option>
                            </select>

                               No of Rooms:
                            <input type="number" name="no_of_rooms" ></input>

                               Rent per month:
                            <input type="number" style={{ width: '100px' }} name="rent_per_month"></input>

                               Total Capacity:
                            <input type="number" style={{ width: '50px' }} name="total_capacity" ></input>

                               Vacancy:
                            <input type="number" style={{ width: '50px' }} name="vacancy"></input>

                        <button className="button add" type="button">Add</button>
                        <button className="button submit" type="submit">Submit</button>

                </form>

        </>
    )
}

export default RoomInfo

Can Please someone help me

Should I map it like
formValues.map((element,rooms) =>(
//form details)}

Also how to uniquely submit them. Thank you


问:
replacing google play console appbundle .aab with one with the same version number
I uploaded my app to play store recently as .aab bundle with version code 3.6، after full rollout my app is succssfully published on play store, now my problem is that after publishing I discovered that the app is not working correctly with some locals eg "Arabic, Hebrew" so I created another aab file to fix the problem but unfortunately I forget to change the version number, to make the issue worse my workstation got corrupted hard drive and it's refusing to boot and my upload signing keys are not part of source control so I can't create new aab with 3.7 as version.
usually when the app is not published I can delete the release and then delete the appbundle from bundle explorer and reupload with same version.

Can I as desperate resort delete the app completely and reupload the same aab after creating new app?

Can I talk to google play store support and ask them to remove the release?

I tried to revert to a previous release 3.5 so that I can delete
the currently active one but with no luck
google play says I cannot revert to 3.5 because it doesn't allow users to upgrade!

Update: I just contacted google play support and asked them to change my upload signing keys, I had to wait for 48 hours until the keys became active.


问:
I can not connect to swagger with spring boot
I have added open-api-ui dependency but it gives me "Failed to load remote configuration." Error message in http://localhost:8080/swagger-ui/index.html. I am sharing my pom.xml file. If Another file needed tell me to share please.

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>2.7.5</version>
      <relativePath/> <!-- lookup parent from repository -->
   </parent>
   <groupId>NortWind.Spring.Projects</groupId>
   <artifactId>NortWind</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <name>NortWind</name>
   <description>Demo project for Spring Boot</description>
   <properties>
      <java.version>17</java.version>
   </properties>
   <dependencies>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-data-jpa</artifactId>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-validation</artifactId>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-web</artifactId>
      </dependency>

      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-devtools</artifactId>
         <scope>runtime</scope>
         <optional>true</optional>
      </dependency>
      <dependency>
         <groupId>org.postgresql</groupId>
         <artifactId>postgresql</artifactId>
         <scope>runtime</scope>
      </dependency>
      <dependency>
         <groupId>org.projectlombok</groupId>
         <artifactId>lombok</artifactId>
         <optional>true</optional>
      </dependency>
      <dependency> <groupId>org.springdoc</groupId>
         <artifactId>springdoc-openapi-ui</artifactId>
         <version>1.6.6</version>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-test</artifactId>
         <scope>test</scope>
      </dependency>
   </dependencies>

   <build>
      <plugins>
         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>
               <excludes>
                  <exclude>
                     <groupId>org.projectlombok</groupId>
                     <artifactId>lombok</artifactId>
                  </exclude>
               </excludes>
            </configuration>
         </plugin>
      </plugins>
   </build>

</project>
</code>```

i just added this dependency for connect swagger. And my spring boot version is 2.7.5 and i know that it is suitable for swagger

```<code><dependency> <groupId>org.springdoc</groupId>
   <artifactId>springdoc-openapi-ui</artifactId>
   <version>1.6.6</version>
</dependency>
</code>```

Body:
I have added open-api-ui dependency but it gives me "Failed to load remote configuration." Error message in http://localhost:8080/swagger-ui/index.html. I am sharing my pom.xml file. If Another file needed tell me to share please.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>2.7.5</version>
      <relativePath/>
   </parent>
   <groupId>NortWind.Spring.Projects</groupId>
   <artifactId>NortWind</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <name>NortWind</name>
   <description>Demo project for Spring Boot</description>
   <properties>
      <java.version>17</java.version>
   </properties>
   <dependencies>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-data-jpa</artifactId>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-validation</artifactId>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-web</artifactId>
      </dependency>

      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-devtools</artifactId>
         <scope>runtime</scope>
         <optional>true</optional>
      </dependency>
      <dependency>
         <groupId>org.postgresql</groupId>
         <artifactId>postgresql</artifactId>
         <scope>runtime</scope>
      </dependency>
      <dependency>
         <groupId>org.projectlombok</groupId>
         <artifactId>lombok</artifactId>
         <optional>true</optional>
      </dependency>
      <dependency> <groupId>org.springdoc</groupId>
         <artifactId>springdoc-openapi-ui</artifactId>
         <version>1.6.6</version>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-test</artifactId>
         <scope>test</scope>
      </dependency>
   </dependencies>

   <build>
      <plugins>
         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>
               <excludes>
                  <exclude>
                     <groupId>org.projectlombok</groupId>
                     <artifactId>lombok</artifactId>
                  </exclude>
               </excludes>
            </configuration>
         </plugin>
      </plugins>
   </build>

</project>

i just added this dependency for connect swagger. And my spring boot version is 2.7.5 and i know that it is suitable for swagger

<dependency> <groupId>org.springdoc</groupId>
   <artifactId>springdoc-openapi-ui</artifactId>
   <version>1.6.6</version>
</dependency>


问:
How to predict data after saving the machine learning model
I am building a recommendation system using cosine similarity. I have already trained my model but now I'm not sure how to make prediction after saving the model.

```<code>captions = data["Caption"].tolist()

vectorizer = TfidfVectorizer()
uni_tfidf = vectorizer.fit_transform(captions)

uni_sim =  cosine_similarity(uni_tfidf[0:1], uni_tfidf).flatten()

similarity = uni_sim.argsort()[:-5:-1]
for sim in similarity:
    print(captions[sim])

</code>```

this is what I have implemented using posts caption, but this model is predicting values based on the data in the dataset. I want to know after I save this model will it take the input and how will it take it and which line will help me predict the model [I'm new to Machine Learning so its difficult to understand even some basic concept]

Thanks in advance

Body:
I am building a recommendation system using cosine similarity. I have already trained my model but now I'm not sure how to make prediction after saving the model.

captions = data["Caption"].tolist()

vectorizer = TfidfVectorizer()
uni_tfidf = vectorizer.fit_transform(captions)

uni_sim =  cosine_similarity(uni_tfidf[0:1], uni_tfidf).flatten()

similarity = uni_sim.argsort()[:-5:-1]
for sim in similarity:
    print(captions[sim])

this is what I have implemented using posts caption, but this model is predicting values based on the data in the dataset. I want to know after I save this model will it take the input and how will it take it and which line will help me predict the model [I'm new to Machine Learning so its difficult to understand even some basic concept]

Thanks in advance


问:
Consistently getting `None` for the `gdb.Field.name` for a C++ function's parameters
I'm trying to use gdb's Python API to extract C++'s function parameters' names, and am consistently getting None when I query the name attribute of function parameters as gdb.Field objects.

On a higher level, I need to distinguish between named and anonymous parameters in a function whilst knowing the exact order of the parameters going into the function, so other methods like info args or looping over gdb.Blocks won't work, as they don't include anonymous parameters.

As a simple run, I have the following compiled under debug:

```<code>// library.h
auto named(int a, int b) -> int;

// library.cpp
auto named(int a, int b) -> int {
  return 0;
}
</code>```

Putting a breakpoint in gdb results in

(gdb) python named = gdb.parse_and_eval("named")
(gdb) python print(named.type)
int (int, int)
(gdb) python print(named.type.fields())
[<gdb.Field object at 0x7f79663f29d0>, <gdb.Field object at 0x7f79663f2a10>]
(gdb) python print(named.type.fields()[0].name)
None
(gdb) python print(named.type.fields()[1].name)
None
```

According to https://sourceware.org/gdb/onlinedocs/gdb/Types-In-Python.html#Types-In-Python,

Function: Type.fields ()

...

Function and method types have one field per parameter. The base types of C++ classes are also represented as fields.

...

Each field is a gdb.Field object, with some pre-defined attributes:

...

name

The name of the field, or None for anonymous fields.

I expected print(named.type.fields()[...].name) to show 'a' and 'b', rather than None, as I've explicitly declared the parameters a and b in both the definition and the declaration; they aren't prototypes.

Am I missing something about gdb.Field.name? Is this attribute only  meaningful for gdb.Types which represent C++ classes/structs?

Executed under GDB versions:

12.1 (apt release)

13.0.90.20230102 (weekly snapshot)

Body:
I'm trying to use gdb's Python API to extract C++'s function parameters' names, and am consistently getting None when I query the name attribute of function parameters as gdb.Field objects.

On a higher level, I need to distinguish between named and anonymous parameters in a function whilst knowing the exact order of the parameters going into the function, so other methods like info args or looping over gdb.Blocks won't work, as they don't include anonymous parameters.

As a simple run, I have the following compiled under debug:

// library.h
auto named(int a, int b) -> int;

// library.cpp
auto named(int a, int b) -> int {
  return 0;
}

Putting a breakpoint in gdb results in

(gdb) python named = gdb.parse_and_eval("named")
(gdb) python print(named.type)
int (int, int)
(gdb) python print(named.type.fields())
[<gdb.Field object at 0x7f79663f29d0>, <gdb.Field object at 0x7f79663f2a10>]
(gdb) python print(named.type.fields()[0].name)
None
(gdb) python print(named.type.fields()[1].name)
None

According to https://sourceware.org/gdb/onlinedocs/gdb/Types-In-Python.html#Types-In-Python,

Function: Type.fields ()

...

Function and method types have one field per parameter. The base types of C++ classes are also represented as fields.

...

Each field is a gdb.Field object, with some pre-defined attributes:

...

name

The name of the field, or None for anonymous fields.

I expected print(named.type.fields()[...].name) to show 'a' and 'b', rather than None, as I've explicitly declared the parameters a and b in both the definition and the declaration; they aren't prototypes.

Am I missing something about gdb.Field.name? Is this attribute only  meaningful for gdb.Types which represent C++ classes/structs?

Executed under GDB versions:

12.1 (apt release)

13.0.90.20230102 (weekly snapshot)