text:
Q: How can I create a entity with a list of entities that has already been created I'm trying create a new entity (sale) with its attributes, one of them is a list of products that have already been created. When I try to save the sale with the repository I get a error
org.h2.jdbc.JdbcSQLIntegrityConstraintViolationException: Unique index or primary key violation: "PUBLIC.UK_PENFKDX7890EQY3I2RH0BA4WV_INDEX_4 ON PUBLIC.SALE_PRODUCTS(PRODUCTS_ID NULLS FIRST) VALUES ( /* 7 */ CAST(7 AS BIGINT) )"; SQL statement:
insert into sale_products (sale_id, products_id) values (?, ?) [23505-214]

Therefore, I realize that the error is because spring try to do the relationship between sale and product and sale doesn't has a id (is null). But the repository (SaleRepository) is supposed to generate the id, so I used the   @GeneratedValue(strategy = GenerationType.IDENTITY).
I don't know what I should do, someone know how I can fix it?
code:
sale
@Entity
public class Sale {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String concept;
    @Temporal(TemporalType.DATE)
    private Date created_at;
    private Double price;
    @OneToOne(cascade = CascadeType.REFRESH)
    private Customer customer;
    @OneToMany
    private Set<Product> products;
 public Sale(){}

    public Sale(String concept, Customer customer, Set<Product> products) {
        this.concept = concept;
        this.customer = customer;
        this.products = products;
        this.price=0.0;
        onPrePersist();
    }

    @PrePersist  void onPrePersist() {created_at = new java.util.Date();}

    //get and setter
}

product
@Entity
public class Product {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private String description;
    private Double price;
    private Integer amount;
    private String barCode;
    private String origin;

    public Product(){}

    public Product(String name, String description, Double price, Integer amount, String barCode, String origin) {
        this.name = name;
        this.description = description;
        this.price = price;
        this.amount = amount;
        this.barCode = barCode;
        this.origin = origin;
    }
//get and setter
}

saleServiceImp (method where I create a sale)
   public SaleDTO save(SaleRegistrationRequest saleRegistrationRequest) {
        Sale sale= new Sale(
                saleRegistrationRequest.concept(),
                findCustomerOfSale(saleRegistrationRequest.customerDTO()),
                convertProductsDTOToProduct(saleRegistrationRequest.productsDTO())
        );
        LOGGER.info("SALE: "+sale.toString());
        saleRepository.save(sale);  // HERE FAIL!
        LOGGER.info("Sale saved successfully "+sale.toString() );
        return saleDTOMapper.apply(sale);
    }

    private Customer findCustomerOfSale(CustomerDTO customerDTO){
            return customerRepository.findById(customerDTO.id()).orElse(null);

    }

    private Set<Product> convertProductsDTOToProduct(Set<ProductDTO> productDTOS){

        if(productDTOS ==null || productDTOS.isEmpty())
            return null;

        return productDTOS.stream().map(productDTO -> {
            return iProductService.findProductById(productDTO.id());
        }).collect(Collectors.toSet());
    }

The error
2023-03-01 17:18:15.064 ERROR 8422 --- [nio-8080-exec-2] o.h.engine.jdbc.spi.SqlExceptionHelper   : Unique index or primary key violation: "PUBLIC.UK_PENFKDX7890EQY3I2RH0BA4WV_INDEX_4 ON PUBLIC.SALE_PRODUCTS(PRODUCTS_ID NULLS FIRST) VALUES ( /* 7 */ CAST(7 AS BIGINT) )"; SQL statement:
insert into sale_products (sale_id, products_id) values (?, ?) [23505-214]
2023-03-01 17:18:15.065  INFO 8422 --- [nio-8080-exec-2] o.h.e.j.b.internal.AbstractBatchImpl     : HHH000010: On release of batch it still contained JDBC statements
2023-03-01 17:18:15.086 ERROR 8422 --- [nio-8080-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint ["PUBLIC.UK_PENFKDX7890EQY3I2RH0BA4WV_INDEX_4 ON PUBLIC.SALE_PRODUCTS(PRODUCTS_ID NULLS FIRST) VALUES ( /* 7 */ CAST(7 AS BIGINT) )"; SQL statement:
insert into sale_products (sale_id, products_id) values (?, ?) [23505-214]]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement] with root cause

org.h2.jdbc.JdbcSQLIntegrityConstraintViolationException: Unique index or primary key violation: "PUBLIC.UK_PENFKDX7890EQY3I2RH0BA4WV_INDEX_4 ON PUBLIC.SALE_PRODUCTS(PRODUCTS_ID NULLS FIRST) VALUES ( /* 7 */ CAST(7 AS BIGINT) )"; SQL statement:
insert into sale_products (sale_id, products_id) values (?, ?) [23505-214]
    at org.h2.message.DbException.getJdbcSQLException(DbException.java:508) ~[h2-2.1.214.jar:2.1.214]
    at org.h2.message.DbException.getJdbcSQLException(DbException.java:477) ~[h2-2.1.214.jar:2.1.214]
    at org.h2.message.DbException.get(DbException.java:223) ~[h2-2.1.214.jar:2.1.214]
    at org.h2.message.DbException.get(DbException.java:199) ~[h2-2.1.214.jar:2.1.214]
    at org.h2.index.Index.getDuplicateKeyException(Index.java:525) ~[h2-2.1.214.jar:2.1.214]
    at org.h2.mvstore.db.MVSecondaryIndex.checkUnique(MVSecondaryIndex.java:223) ~[h2-2.1.214.jar:2.1.214]
    at org.h2.mvstore.db.MVSecondaryIndex.add(MVSecondaryIndex.java:184) ~[h2-2.1.214.jar:2.1.214]
    at org.h2.mvstore.db.MVTable.addRow(MVTable.java:519) ~[h2-2.1.214.jar:2.1.214]
    at org.h2.command.dml.Insert.insertRows(Insert.java:174) ~[h2-2.1.214.jar:2.1.214]
    at org.h2.command.dml.Insert.update(Insert.java:135) ~[h2-2.1.214.jar:2.1.214]
    at org.h2.command.dml.DataChangeStatement.update(DataChangeStatement.java:74) ~[h2-2.1.214.jar:2.1.214]
    at org.h2.command.CommandContainer.update(CommandContainer.java:169) ~[h2-2.1.214.jar:2.1.214]
    at org.h2.command.Command.executeUpdate(Command.java:252) ~[h2-2.1.214.jar:2.1.214]
    at org.h2.jdbc.JdbcPreparedStatement.executeUpdateInternal(JdbcPreparedStatement.java:209) ~[h2-2.1.214.jar:2.1.214]
    at org.h2.jdbc.JdbcPreparedStatement.executeUpdate(JdbcPreparedStatement.java:169) ~[h2-2.1.214.jar:2.1.214]
    at com.zaxxer.hikari.pool.ProxyPreparedStatement.executeUpdate(ProxyPreparedStatement.java:61) ~[HikariCP-4.0.3.jar:na]
    at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeUpdate(HikariProxyPreparedStatement.java) ~[HikariCP-4.0.3.jar:na]
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:197) ~[hibernate-core-5.6.12.Final.jar:5.6.12.Final]
    at org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:46) ~[hibernate-core-5.6.12.Final.jar:5.6.12.Final]
    at org.hibernate.persister.collection.AbstractCollectionPersister.recreate(AbstractCollectionPersister.java:1352) ~[hibernate-core-5.6.12.Final.jar:5.6.12.Final]
    at org.hibernate.action.internal.CollectionRecreateAction.execute(CollectionRecreateAction.java:50) ~[hibernate-core-5.6.12.Final.jar:5.6.12.Final]
    at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:604) ~[hibernate-core-5.6.12.Final.jar:5.6.12.Final]
    at org.hibernate.engine.spi.ActionQueue.lambda$executeActions$1(ActionQueue.java:478) ~[hibernate-core-5.6.12.Final.jar:5.6.12.Final]
    at java.base/java.util.LinkedHashMap.forEach(LinkedHashMap.java:721) ~[na:na]
    at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:475) ~[hibernate-core-5.6.12.Final.jar:5.6.12.Final]
    at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:344) ~[hibernate-core-5.6.12.Final.jar:5.6.12.Final]
    at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:40) ~[hibernate-core-5.6.12.Final.jar:5.6.12.Final]
    at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:107) ~[hibernate-core-5.6.12.Final.jar:5.6.12.Final]
    at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1407) ~[hibernate-core-5.6.12.Final.jar:5.6.12.Final]
    at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:489) ~[hibernate-core-5.6.12.Final.jar:5.6.12.Final]
    at org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:3303) ~[hibernate-core-5.6.12.Final.jar:5.6.12.Final]
    at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2438) ~[hibernate-core-5.6.12.Final.jar:5.6.12.Final]
    at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:449) ~[hibernate-core-5.6.12.Final.jar:5.6.12.Final]
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:183) ~[hibernate-core-5.6.12.Final.jar:5.6.12.Final]
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access$300(JdbcResourceLocalTransactionCoordinatorImpl.java:40) ~[hibernate-core-5.6.12.Final.jar:5.6.12.Final]
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:281) ~[hibernate-core-5.6.12.Final.jar:5.6.12.Final]
    at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:101) ~[hibernate-core-5.6.12.Final.jar:5.6.12.Final]
    at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:562) ~[spring-orm-5.3.23.jar:5.3.23]
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:743) ~[spring-tx-5.3.23.jar:5.3.23]
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:711) ~[spring-tx-5.3.23.jar:5.3.23]
    at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:654) ~[spring-tx-5.3.23.jar:5.3.23]
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:407) ~[spring-tx-5.3.23.jar:5.3.23]
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:119) ~[spring-tx-5.3.23.jar:5.3.23]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.23.jar:5.3.23]
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:137) ~[spring-tx-5.3.23.jar:5.3.23]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.23.jar:5.3.23]
    at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:174) ~[spring-data-jpa-2.7.5.jar:2.7.5]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.23.jar:5.3.23]
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:97) ~[spring-aop-5.3.23.jar:5.3.23]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.23.jar:5.3.23]
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:215) ~[spring-aop-5.3.23.jar:5.3.23]
    at jdk.proxy2/jdk.proxy2.$Proxy108.save(Unknown Source) ~[na:na]
    at com.api.store.service.SaleServiceImp.save(SaleServiceImp.java:43) ~[classes/:na]
    at com.api.store.controller.SaleController.save(SaleController.java:21) ~[classes/:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) ~[na:na]
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
    at java.base/java.lang.reflect.Method.invoke(Method.java:568) ~[na:na]
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205) ~[spring-web-5.3.23.jar:5.3.23]
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:150) ~[spring-web-5.3.23.jar:5.3.23]
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:117) ~[spring-webmvc-5.3.23.jar:5.3.23]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895) ~[spring-webmvc-5.3.23.jar:5.3.23]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808) ~[spring-webmvc-5.3.23.jar:5.3.23]
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.3.23.jar:5.3.23]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1071) ~[spring-webmvc-5.3.23.jar:5.3.23]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:964) ~[spring-webmvc-5.3.23.jar:5.3.23]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) ~[spring-webmvc-5.3.23.jar:5.3.23]
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909) ~[spring-webmvc-5.3.23.jar:5.3.23]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:696) ~[tomcat-embed-core-9.0.68.jar:4.0.FR]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) ~[spring-webmvc-5.3.23.jar:5.3.23]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:779) ~[tomcat-embed-core-9.0.68.jar:4.0.FR]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227) ~[tomcat-embed-core-9.0.68.jar:9.0.68]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.68.jar:9.0.68]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.68.jar:9.0.68]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.68.jar:9.0.68]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.68.jar:9.0.68]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-5.3.23.jar:5.3.23]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.23.jar:5.3.23]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.68.jar:9.0.68]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.68.jar:9.0.68]
    at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[spring-web-5.3.23.jar:5.3.23]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.23.jar:5.3.23]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.68.jar:9.0.68]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.68.jar:9.0.68]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-5.3.23.jar:5.3.23]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.23.jar:5.3.23]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.68.jar:9.0.68]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.68.jar:9.0.68]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197) ~[tomcat-embed-core-9.0.68.jar:9.0.68]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97) ~[tomcat-embed-core-9.0.68.jar:9.0.68]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541) ~[tomcat-embed-core-9.0.68.jar:9.0.68]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135) ~[tomcat-embed-core-9.0.68.jar:9.0.68]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) ~[tomcat-embed-core-9.0.68.jar:9.0.68]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78) ~[tomcat-embed-core-9.0.68.jar:9.0.68]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:360) ~[tomcat-embed-core-9.0.68.jar:9.0.68]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:399) ~[tomcat-embed-core-9.0.68.jar:9.0.68]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) ~[tomcat-embed-core-9.0.68.jar:9.0.68]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:893) ~[tomcat-embed-core-9.0.68.jar:9.0.68]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1789) ~[tomcat-embed-core-9.0.68.jar:9.0.68]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) ~[tomcat-embed-core-9.0.68.jar:9.0.68]
    at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191) ~[tomcat-embed-core-9.0.68.jar:9.0.68]
    at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659) ~[tomcat-embed-core-9.0.68.jar:9.0.68]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) ~[tomcat-embed-core-9.0.68.jar:9.0.68]
    at java.base/java.lang.Thread.run(Thread.java:833) ~[na:na]

2023-03-01 17:23:29.979  INFO 8422 --- [ionShutdownHook] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2023-03-01 17:23:29.979  INFO 8422 --- [ionShutdownHook] .SchemaDropperImpl$DelayedDropActionImpl : HHH000477: Starting delayed evictData of schema as part of SessionFactory shut-down'
2023-03-01 17:23:30.191  INFO 8422 --- [ionShutdownHook] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown initiated...
2023-03-01 17:23:30.195  INFO 8422 --- [ionShutdownHook] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown completed.

Process finished with exit code 130 (interrupted by signal 2: SIGINT)


text:
Q: How can I use a pipeline graph with upsampling when my task is ordered? I have a task where the observation in rows have a date order. I generate a custom resampling scheme that respects this order in all train/test splits.
I also want to adress the unbalanced classes problem by upsampling the minority class. Within the training sets, the time order is not important (and the learner would not use this anyway).
Now, I want to resample this combination of ordered task, graph learner (including upsampling) and time-sensitive custom resampling scheme. But this is problematic.
To show this, I generated the following code. I use a sample task to make this reproducible and I augment this task with a date column to generate an ordered task that is similar to my problem. This code runs only if I omit the problematic lines indicated in the code. But they generate exactly what I have in my real-world problem: An order. So how can I solve this?
(I omit some of the output in the following reprex for readability.)
library(mlr3verse)
#> Warning: Paket 'mlr3verse' wurde unter R Version 4.1.1 erstellt
#> Lade nötiges Paket: mlr3

library(tidyverse)

library(lubridate)

# load sample task

task <- tsk("breast_cancer")

#### start of lines that generate a problem

# add a date column to produce an artificial sample problem with time order of rows specified by a date column
DateColumn <- seq(ymd('2000-04-07'),ymd('2021-03-22'), by = '1 week')
DateColumn <- DateColumn[1:task$nrow]
task$cbind(data.frame(Date = DateColumn[1:task$nrow])) # add date column
task$set_col_roles("Date", roles = "order")

#### end of lines that generate a problem

# Generate a "loo" growing window type resampling scheme, where learner is trained on "earlier" and tested on "later" data  (hopefully - or may it be that the original row order is not preserved?)
# first training window size is 10 weeks

length_first_window <- 10

resampling_grow_win = rsmp("custom")

train_sets = list(1:length_first_window)
test_sets = list(length_first_window+1)

for (testweek in ((length_first_window+2):task$nrow)) {

  train_sets <- append(train_sets, list(c(1:(testweek-1))))
  test_sets <- append(test_sets, list(c(testweek)))

}

resampling_grow_win$instantiate(task, train_sets, test_sets)
resampling_grow_win$id <- paste0("gw_for", task$id)

# now, I define a pipeline for a learner with preceding upsampling:

# oversample or undersample such that the number of cases is equal
# I assume here that the actual number is not really important and
# use approximately the size of the total sample (which will be much larger than the sample size
# for the first growing window resamplings, but I am oversampling anyway)

NrSamplesEach <- 500

po_classbalance = po("classbalancing",
  id = "sample2equal", adjust = "all", shuffle = FALSE, ratio = NrSamplesEach, reference="one")

#create a learner
learner = lrn("classif.ranger", num.trees = 10)

# combine learner with pipeline graph
learner_balanced = as_learner(po_classbalance %>>% learner)

# setup benchmark
rr = resample(task, learner_balanced, resampling_grow_win, store_models = TRUE)
#> INFO  [16:47:10.484] [mlr3] Applying learner 'sample2equal.classif.ranger' on task 'breast_cancer' (iter 111/673)
#> Error: Cannot rbind data to task 'breast_cancer', missing the following mandatory columns: Date
#> This happened PipeOp sample2equal's $train()

# show some results (I am aware that there is only one element in the test set in each iteration, but this is ok for this example)

scored_result <- rr$score(msr("classif.acc"))
#> Error in eval(expr, envir, enclos): Objekt 'rr' nicht gefunden
head(scored_result)
#> Error in head(scored_result): Objekt 'scored_result' nicht gefunden

Created on 2021-12-09 by the reprex package (v2.0.1)

A: Yep sorry I made a mistake. We need to fix the pipeop. However, you can just order the data first and skip the task$set_col_roles("Date", roles = "order") part. Just to be safe, check with task$data(row) that your data is returned in chronological order e.g. task$data(1) returns the first time point.
library(mlr3)
library(mlr3pipelines)
library(data.table)
library(mlr3misc)

task = tsk("breast_cancer")
learner = lrn("classif.rpart")
resampling = rsmp("holdout")

# extract data
data = task$data()

# fake date column
date = sample(seq(task$nrow))
data[, date := date]

# order data in chronological order
setorder(data, date)

# remove date column
data[, date := NULL]

# create task with ordered data
task = as_task_classif(data, target = "class")

# set custom resampling
train_sets = map(seq(10, task$nrow - 1), seq)
test_sets = as.list(seq(11, task$nrow))
resampling = rsmp("custom")
resampling$instantiate(task, train_sets, test_sets)

# learner with upsampling
po_classbalance = po("classbalancing", id = "sample2equal", adjust = "all", shuffle = FALSE, ratio = 500, reference="one")
learner_balanced = as_learner(po_classbalance %>>% learner)

# resample
rr = resample(task, learner_balanced, resampling, store_models = TRUE)

A: You could upsample the data set first and then create the custom resampling splits.
library(mlr3)
library(mlr3misc)
library(lubridate)

task = tsk("breast_cancer")

# set date column
DateColumn = seq(ymd('2000-04-07'),ymd('2021-03-22'), by = '1 week')
DateColumn = DateColumn[1:task$nrow]
task$cbind(data.frame(Date = DateColumn[1:task$nrow]))

# upsample task
po_classbalance = po("classbalancing", id = "sample2equal", adjust = "all", shuffle = FALSE, ratio = NrSamplesEach, reference="one")
task = po_classbalance$train(list(task))[[1]]

# add helper column to indicate position in unordered data table
task$cbind(data.frame(i = 1:task$nrow))

# set order
task$set_col_roles("Date", roles = "order")

# custom resampling
train_sets = map(seq(10, task$nrow - 1), seq)
test_sets = as.list(seq(11, task$nrow))

# map to position of unordered data table
data_ordered = task$data(order = TRUE)
train_sets = map(train_sets, function(x) data_ordered$i[x])
test_sets = map(test_sets, function(x) data_ordered$i[x])

# remove helper column
task$select(setdiff(task$feature_names, "i"))

learner = lrn("classif.rpart")
rr = resample(task, learner, resampling_grow_win, store_models = TRUE)

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to PXE boot a laptop without router? I would like to PXE boot a laptop to install Debian on it.
Normally, I would use a CAT5 cable to connect the laptop to my router as I can't boot from network via Wi-Fi. My router running Tomato would assign the IP address and then point to a VM on my laptop as the next_server, and the VM would serve everything needed to get the OS installed, push configuration via Ansible, etc.
This time, I don't have my router. There is a Wi-Fi network here that I don't control, and the ISP router likely has no configuration to set up any next_server.
When booting the laptop, I was considering connecting it directly to my laptop via a CAT5 cable. (I'm assuming both Ethernet ports support autosensing so I won't need to resort to using a crossover cable.)
I don't want to install a ton of software on my laptop to get this going, but I can settle for some simple packages if needed.
Ultimately, I want this laptop to boot over the network, find the VM on my laptop, and start booting--all without having to reconfigure anything on the ISP router.
The VM runs in Oracle VirtualBox and is currently configured with two network adapters for some reason. I'm flexible on changing these VM settings for this if necessary.
The first adapter is Attached to Bridged Adpater, with Name wlan0.
The second adapter is Attached to Host-only Adapter, with Name vboxnet0.
EDIT: To answer some of the comments and clarify my setup, there are no Windows computers involved.
There is an ISP-provided Wi-Fi router here that I can't control; it has DHCP enabled so wireless devices and laptops get NAT IP addresses, but no next-server value for network booting.
The wireless router is also not suitable for additional Ethernet connections, so I can't plug the new laptop directly into its Ethernet port.
Both laptops have wireless NICs and connect to the wireless router for Internet access. The laptops also have an Ethernet port that rarely gets used.
The second laptop has no OS; the drive is wiped and ready to install an OS.
My physical laptop runs Debian.
My laptop has a Debian VM running in Virtual Box that I use to serve network boot clients. This VM currently assumes the Tomato router will provide DHCP as well as a next-server value pointing to the VM.
The Tomato router is no longer in the mix, only the wireless router mentioned above, which is causing me my current grief.
The VM provides PXE booting so boot clients can boot into System Rescue CD, TRK, Debian installers, Debian live CD, etc.
I typically boot a Debian installer over PXE, and then point to the same VM for Debian preseed configuration as the VM is also running an HTTP server to serve the preseed files.
If I can get to the preseed configuration by booting from a burned CD installer or USB, then I consider this a viable workaround for my situation. More than likely I need to burn a CD, but it would have to be an actual 650 MB or less CD as there are no DVDs around here.
Once the base installation is complete, I run Ansible commands from my physical laptop to push configuration changes to the newly-provisioned hardware.

A: The selected answer imply creating the USB drive; a real pain.
You can set up a PXE Server and start installing Debian in 15 minutes, w/o touching your already in place DHCP server. See here:
https://www.vercot.com/~serva/an/WindowsPXE1.html
for Debian specifically see here
http://vercot.com/~serva/an/NonWindowsPXE3.html
(I'm related to Serva development)

A: You can use bootp or DHCP protocols to do this. You don't strictly need a router but you do need something to provide those protocols.
Almost any network card auto senses. Its something of a modern myth that you ever need one.
What you want to use is a bridged adapter set it to your ethernet network and connect your laptop up directly. You can also use host-only adaptor and then within Windows bridge its interface with another adaptor.

A: The easiest way is to create a bootable USB stick from the Debian ISO that you already have and connect to the other laptop via manual IP config


text:
Q: Error in parsing value for 'color' (jQuery UI) I am trying to animate a color change (font) with jQuery UI when clicking the element.
I included the files of jQuery UI as descripted on their website.
<script type='text/javascript'>
    $(document).ready(function() {
        $('.benefits').click(function() {
            $(this).animate({color:'#b22425'}, 200);
        });
    });
</script>

It doesn't work. Console says:

Error in parsing value for 'color'.  Declaration dropped.

When I'm adding an animate width change, this works fine but the color error stays.
What am I doing wrong?
Thanks for the help :-)
EDIT
I'm figuring out what's the problem:
I'm include the navigation and the footer with PHP:
<?php
    include('navigation.php');
?>

When I delete this block everything works fine. But when I'm including Navigation and Footer with PHP the parsing error occurs.
Has anybody a solution?
EDIT 2
The Navigation and Footer Documents were "Full-Document", this means they had their own html, head, style, body ... tags. I included this documents in the body-tag of my main-document and so there were 3 complete html-documents in one.
After deleting the unnecessary tags from the navigation and footer documents everything works fine.
I would have seen this earlier -.-'
Thanks anyway for the comments and answers :-)

A: Here is a simple way of doing it
I created a simple html only
I downloaded the jquery colors JQUERY COLORS
and added it to the html file include the jquery library
so it would be loaded like this
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="jquery.color.js"></script>

Here is a simple DEMO CREATED
Hope it helps.!

A: You cannot use animate to animate colors without jQuery UI.

All animated properties should be
  animated to a single numeric value,
  except as noted below; most properties
  that are non-numeric cannot be
  animated using basic jQuery
  functionality. (For example, width,
  height, or left can be animated but
  background-color cannot be, unless the jQuery.Color plugin is used.)

and

The jQuery UI project extends the
  .animate() method by allowing some
  non-numeric styles such as colors to
  be animated. The project also includes
  mechanisms for specifying animations
  through CSS classes rather than
  individual attributes.

source: http://api.jquery.com/animate/


text:
Q: hetzner default nameservers not always resolving I have couple of Hetzner 'root servers' (as they call it - dedicated co-located linux machines) and all of them experience the same problem (which i simply do not fully understand).
The domain www.dnsblchile.org does not want to resolve to an IP (servers are installed from Hetzner own Debian Jessie images). All other domains of course resolve properly (i did not experience any problems before with any other domains resolving - or i did not spot it before).
When i test nslookup -type=A www.dnsblchile.org i get:
;; Got SERVFAIL reply from 213.133.98.98, trying next server
;; Got SERVFAIL reply from 213.133.99.99, trying next server
Server:         213.133.100.100
Address:        213.133.100.100#53

** server can't find www.dnsblchile.org: SERVFAIL

so NO proper answer here, but when i try using 8.8.8.8 (google) as nameserver like nslookup -type=A www.dnsblchile.org 8.8.8.8 i get:
Server:         8.8.8.8
Address:        8.8.8.8#53

Non-authoritative answer:
Name:   www.dnsblchile.org
Address: 66.23.231.212

so everything is OK here and i get proper IP.
The contents of `/etc/resolv.conf' (default after installation) is:
### Hetzner Online GmbH installimage
# nameserver config
nameserver 213.133.98.98
nameserver 213.133.99.99
nameserver 213.133.100.100

If i add the 8.8.8.8 as a new entry to /etc/resolv.conf all is working just fine as well.
Now - is it something wrong on Hetzner nameservers configuration side or shall i just use 8.8.8.8 nameserver instead (as a good practice)?
I'm talking to Hetzner support for two days already but have no common ground here - hearing that their nameservers are all perfectly fine.
Shall their own nameservers as well properly resolve the www.dnsblchile.org domain?

update from support:

..but as the domain are using nameservers which are not allowing requests from our resolvers the domain can not be resolved. If you want to resolve the domain you have to use other resolvers or maybe own resolvers, which are allowed to request the nameservers of the domain

Now - may their nameservers be 'blocked' like they say (i'm not an expert here)?
As well - is it a common practice (as the answer below suggests) to use e.g. google name server and just skip Hetzner nameservers setup?
Would i just add the google name server to the list (at top or bottom of /etc/resolv.conf file) and shall i remove the Hetzner nameservers (or leave them)?

A: I don't understand why you are still trying to use the Hetzner DNS servers if they are demonstrably not working correctly. Just update your /etc/resolv.conf appropriately and get on with your life.
I usually chuck 8.8.8.8 and 8.8.4.4 (or 2001:4860:4860::8888, 2001:4860:4860::8844) in and forget about it.

A: See also: https://cwiki.apache.org/confluence/display/SPAMASSASSIN/CachingNameserver for a lot of good options to avoid this problem, e.g. by installing a local caching DNS server like: unbound
After you make sure it starts upon reboot make sure to change /etc/resolv.conf to begin with:
nameserver 127.0.0.1
Finally make sure your server is not overwriting this setting (e.g. a dhcp client may overwrite it) by making the file immutable:
sudo chattr +i /etc/resolv.conf
Or the following line in /etc/dhcp/dhclient.conf
supersede domain-name-servers 127.0.0.1;
Or other solutions like described here: https://www.cyberciti.biz/faq/dhclient-etcresolvconf-hooks/
Let's block all spam mails :-)


text:
Q: Custom button to show sidebar Material Design Lite I'm creating an app using the Angular 2 and MDL using maps, and I'm doing a similar component, replacing the header, to the official site maps.google.com. I wanted to create a custom button to display the lateral sidebar MDL.

How do this: I click the own button to show the sidebar on the left?
(I do not know if I was clear on the question)
EDIT1
Works fine:
  ...
  constructor(){
    // for fix "MaterialLayout not found"
    let MaterialLayout:any;
    this.drawer = document.querySelector('.mdl-layout');
  }

  toogleDrawer(){
    this.drawer.MaterialLayout.toggleDrawer();
  }
  ...

A: Works with:
export class MapHeaderBadget{
 constructor(){
    // for fix "MaterialLayout not found"
    let MaterialLayout:any;
    this.drawer = document.querySelector('.mdl-layout');
  }
  // icon click event
  toogleDrawer(){
    this.drawer.MaterialLayout.toggleDrawer();
  }
}


text:
Q: Spring @Autowired messageSource working in Controller but not in other classes? New updates:
Dec 31 2010 8:15 PM
Very dirty fix but this is how I have temporarily made the messageSource to work. I changed my Controller class to pass the 'messageSource' to Message class and am able to retrieve the messages. Please review the class definition below and let me know any more info that you may need to help. I really appreciate all the help you are providing.
Dec 31 2010 3 PM
As I could not succeed in configuring messageSource through annotations, I attempted to configure messageSource injection through servlet-context.xml. I still have messageSource as null. Please let me know if you need any more specific info, and I will provide. Thanks for your help in advance.
servlet-context.xml
<beans:bean id="message"
    class="com.mycompany.myapp.domain.common.message.Message">
    <beans:property name="messageSource" ref="messageSource" />
</beans:bean>

Spring gives the below information message about spring initialization.
INFO : org.springframework.context.annotation.ClassPathBeanDefinitionScanner - JSR-330 'javax.inject.Named' annotation found and supported for component scanning

INFO : org.springframework.beans.factory.support.DefaultListableBeanFactory - Overriding bean definition for bean 'message': replacing [Generic bean: class [com.mycompany.myapp.domain.common.message.Message]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [C:\springsource\tc-server-developer-2.1.0.RELEASE\spring-insight-instance\wtpwebapps\myapp\WEB-INF\classes\com\mycompany\myapp\domain\common\message\Message.class]] with [Generic bean: class [com.mycompany.myapp.domain.common.message.Message]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in ServletContext resource [/WEB-INF/spring/appServlet/servlet-context.xml]]

INFO : org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor - JSR-330 'javax.inject.Inject' annotation found and supported for autowiring

INFO : org.springframework.beans.factory.support.DefaultListableBeanFactory - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@1c7caac5: defining beans [org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping#0,org.springframework.format.support.FormattingConversionServiceFactoryBean#0,org.springframework.validation.beanvalidation.LocalValidatorFactoryBean#0,org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter#0,org.springframework.web.servlet.handler.MappedInterceptor#0,org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter,org.springframework.web.servlet.resource.ResourceHttpRequestHandler#0,org.springframework.web.servlet.handler.SimpleUrlHandlerMapping#0,xxxDao,message,xxxService,jsonDateSerializer,xxxController,homeController,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,tilesViewResolver,tilesConfigurer,messageSource,org.springframework.web.servlet.handler.MappedInterceptor#1,localeResolver,org.springframework.web.servlet.view.ContentNegotiatingViewResolver#0,validator,resourceBundleLocator,messageInterpolator]; parent: org.springframework.beans.factory.support.DefaultListableBeanFactory@4f47af3

I have the below definition for message source in 3 classes. In debug mode, I can see that in class xxxController, messageSource is initialized to org.springframework.context.support.ReloadableResourceBundleMessageSource. I have annotated Message class with @Component and xxxHibernateDaoImpl with @Repository. I also included context namespace definition in servlet-context.xml. But in Message class and xxxHibernateDaoImpl class, the messageSource is still null.
Why is Spring not initializing messageSource in the two other classes though in xxxController classes, it initializes correctly?
@Controller
public class xxxController{
    @Autowired
    private ReloadableResourceBundleMessageSource messageSource;
}

@Component
public class Message{
 @Autowired
 private ReloadableResourceBundleMessageSource messageSource;
}

@Repository("xxxDao")
public class xxxHibernateDaoImpl{
 @Autowired
 private ReloadableResourceBundleMessageSource messageSource;
}

<beans:beans
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

<beans:bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
            <beans:property name="basename" value="/resources/messages/messages" />
</beans:bean>

    <context:component-scan base-package="com.mycompany.myapp"/>
</beans>

A: Spring does not know about those classes that you are getting a null value field from.  You can tell Spring about them by defining them as beans in your app context or annotating the classes as @Component
The reason why your first class is getting autowired correctly is because that class is correctly annotated as @Controller

A: Try to refine your base-package. Don't let spring scan all your application class com.mycompany.myapp , (you will have a better startup time).
Suppose you have your controller class in a package :  com.mycompany.myapp.controller
and your service class (annotated with @component, @repository) in package com.mycompany.myapp.services
Add this to your [servlet-name]-servlet.xml (Dispatcher context file)
<context:component-scan base-package="com.mycompany.myapp.controller" />

In the other hand, open your servlet-context.xml (Supposed to be an application context loaded by contextloaderlistener) and add this :
<context:component-scan base-package="com.mycompany.myapp.services" />

followed by the declaration of your messageSource as you did.
You will have one messageSource injected every where it is autowired. It should work because stuff defined in Dispatcher-context-file can see other beans declared in application-context file(s) but not the opposite


text:
Q: Is it possible check if a variable respect two conditions on different rows? Well, I have a data frame with product sales. One of the variables is the 'Product Identification' and another is the 'Item_Weight'. The 'Item_Weight' have some missing values. So, I want to know if there is any product that have in a row the 'Item_Weight' filled and in other row don't.
The data frame is like this:
 Item_Identifier  Item_Weight Item_Fat_Content  Item_Visibility    Item_Type  \
0           FDA15         9.30          Low Fat         0.016047        Dairy
1           DRC01         5.92          Regular         0.019278  Soft Drinks
2           FDN15        17.50          Low Fat         0.016760         Meat

   Item_MRP Outlet_Identifier  Outlet_Establishment_Year Outlet_Size  \
0  249.8092            OUT049                       1999      Medium
1   48.2692            OUT018                       2009      Medium
2  141.6180            OUT049                       1999      Medium

  Outlet_Location_Type        Outlet_Type  Item_Outlet_Sales
0               Tier 1  Supermarket Type1          3735.1380
1               Tier 3  Supermarket Type2           443.4228
2               Tier 1  Supermarket Type1          2097.2700

So, what I have done so far was creating a new df just with the 'Item_Identifier' and the 'Item_Weight' and fill the missing values with (-1) and all other values with (-2) on the 'Item_Weight':
dfAux = df[['Item_Identifier','Item_Weight']]

dfAux['Item_Weight'].fillna(-1, inplace=True)

dfAux.loc[dfAux['Item_Weight'] > 0, 'Item_Weight'] = -2

After this I tried a lot of things to see if I can find the 'Item_Identifier''s that have the value (-1) and (-2). None of these attempts was successful, so i need your help.
Just you to know I am new to data science and python, but I have tried to find the solution on stackoverflow, during several days. Obviously I lack some technical terms so I have some difficulty in find similar questions to mine. I am sorry for bothering.
Thank you in advance.

A: If you want to get rows with 'Item_Weight' value as -1 or -2 then here is the code you can use to get this task done.
dfAux[(dfAux['Item_Weight']==-1) | (dfAux['Item_Weight']==-2) ]

The above code will return all the rows which has "Item_Weight" value as -1 or -2.
The 'or' and 'and' python statements require truth-values. For pandas these are considered ambiguous so you should use bitwise operators :
| for performing or operation
and
& for performing and operation.


text:
Q: Access SQL can't find table when it exists I have new error Error 3078: The Microsoft Access engine cannot find the table 'tbl_Parameters'....  I have not made any changes in this area of the cod. The same error occurs on a previous version of the application where I did not make any changes at all.
The table tbl_Parameters is local to the database.  I have the same problem with another table that is in a linked database.  The application is able access all the other 20+ tables without any errors.
Here is the code that fails.
strSQL = "SELECT TOP 1 PARAMETER_VALUE FROM tbl_Parameters WHERE PARAMETER_NAME _ ='DATE_LAST_PN_FILE';"
Set db = DBEngine(0)(0)
Set rs = db.OpenRecordset(strSQL, dbOpenForwardOnly)

I run the querySELECT TOP 1 PARAMETER_VALUE FROM tbl_Parameters WHERE PARAMETER_NAME = 'DATE_LAST_PN_FILE'; in the query editor and it runs fine.
Any help to solve this problem is appreciated.


text:
Q: Moving jquery accordion elements from one accordion to another Bit of an odd one, this. I have two jquery accordion entities, and on click of an item in one accordion, I want to dynamically add it to a second accordion, and hide it in the original.
This currently works great moveing from A to B, and on moving back from B to A, BUT when I move an item back to original accordion, any subsequent moves from A to B screw up.
Here's a jsfiddle example of what I mean http://jsfiddle.net/waveydavey/CAYth/ . Note I am compeltely aware that the code is ugly - I'm just learning this stuff. Please feel free to suggest ways that are 10 times better. Do the following:

*

*Run the fiddle.

*Click on the "+" of each item to move to accordion 2

*All move really well.

Now do this:

*

*Run the fiddle.

*Click on any "+" to move to 2nd accordion

*Click on "x" on moved item, it re-appears in first set

*Click on any "+" item to add to second set

*Display completely messes up for accordion item

Any advice would be massively appreciated.
The jsfiddle code is:
    $(function() {
 // create accordion entities
 $('#avAccordion').accordion({
        collapsible: true,
        autoHeight: false,
        active: false
    });
 $('#assignedAccordion').accordion({
        collapsible: true,
        autoHeight: false,
        active: false
    });
 $('.accordionAdd').click(function(){
        // destroy the accordion, prior to rebuilding
        $('#avAccordion').accordion('destroy');
        // get the h3 part and tweak it's contents
        var h3bit = $(this).parent().clone();
        $(h3bit).removeClass('freeContacts').addClass('assignedContacts');
        $(h3bit).children('span').removeClass('ui-icon-circle-plus accordionAdd').addClass('ui-icon-circle-close accordionDel');
        // get the div part after the h3
        var divbit = $(this).parent().next().clone();
        // rebuild original accordion
        $( "#avAccordion" ).accordion({
            collapsible: true,
            autoHeight: false,
            active: false
        });
        // move contents to other accordion
     $('#assignedAccordion').append(h3bit)
         .append(divbit)
         .accordion('destroy')
         .accordion({
            collapsible: true,
            autoHeight: false,
            active: false
        });
        // hide original accordion entry
        $(this).parent().hide();
        //attach click handler to new item
        $('.accordionDel').click(function(){
            dropAssignedContact(this);
            return false;
        })
        return false;
    });

    function dropAssignedContact(obj){
        // unhide right hand object with appropriate data-id attr
        var id = $(obj).parent().attr('data-id');
       // delete myself
        $(obj).parent().remove();
        // unhide original
        $('.freeContacts[data-id='+id+']').show();
        $('#assignedAccordion').accordion('destroy').accordion({
            collapsible: true,
            autoHeight: false,
            active: false
        });
    }
});

A: See this updated fiddle: http://jsfiddle.net/KTWEd/
function dropAssignedContact(obj){
    // unhide right hand object with appropriate data-id attr
    var id = $(obj).parent().attr('data-id');

   // delete myself
    $(obj).parent().next().remove();   // <---   Removes the adjacent div
    $(obj).parent().remove();

    // unhide original
    $('.freeContacts[data-id='+id+']').show();
    $('#assignedAccordion').accordion('destroy').accordion({
        collapsible: true,
        autoHeight: false,
        active: false
    });
 }
});


text:
Q: Is this CPU architecture information from lscpu normal? With command lscpu I have output as follows:
Architecture:          x86_64
CPU op-mode(s):        32-bit, 64-bit
Byte Order:            Little Endian
CPU(s):                4
On-line CPU(s) list:   0-3
Thread(s) per core:    2
Core(s) per socket:    2
Socket(s):             1
NUMA node(s):          1
Vendor ID:             GenuineIntel
CPU family:            6
Model:                 42
Stepping:              7
CPU MHz:               800.000
BogoMIPS:              5587.22
Virtualization:        VT-x
L1d cache:             32K
L1i cache:             32K
L2 cache:              256K
L3 cache:              4096K
NUMA node0 CPU(s):     0-3

Now in L2 cache is shown 256K? Shouldn't it be 4096K too?!

A: Your output of lscpu is normal. L2 cache: 256K is normal output for an Intel dual core processor (2nd generation Sandy Bridge series1 and 3rd generation Ivy Bridge series).
1Wikipedia

A: The smaller L2 cache results in lower latency, and the net result is better performance on the latest dual and quad-core processors.


text:
Q: How to test authentication using mocks? I'm doing an exercise where testing is a task, and I should use mockito to test the methods.
I'm trying to test if the authentication is succesful, but I always get expection, saying
org.mockito.exceptions.misusing.InvalidUseOfMatchersException:

You cannot use argument matchers outside of verification or stubbing.
Examples of correct usage of argument matchers:
    when(mock.get(anyInt())).thenReturn(null);
    doThrow(new RuntimeException()).when(mock).someVoidMethod(any());
    verify(mock).someMethod(contains("foo"))

I'm not sure what it means, or how should I handle this, because I'm a beginner in testing.
The app looks like this:
Tester class:
@ExtendWith(MockitoExtension.class)

public class Tester {

@Mock
Player loggedPlayer =  new Player(null,null,null,BigDecimal.valueOf(200),Currency.EUR);

@InjectMocks
DefaultSportsBettingService service = new DefaultSportsBettingService();

@Test
public void testAuthenticateUserIsSuccesful(){
    DefaultSportsBettingService service = mock(DefaultSportsBettingService.class);
    User user = new User("asd","123");
    Player logged = service.authenticateUser(user);

    when(service.authenticateUser(any(User.class))).thenReturn(any());
    verify(service, times(1)).authenticateUser(user);
    assertNotEquals(null, logged);
}

Service class:
public class DefaultSportsBettingService implements SportsBettingService{

public DummyDataStore dds = new DummyDataStore();
public List <Player> initializedPlayers = dds.getPlayerDatastore();
public List<User> initializedUsers = dds.getUserDataStore();
public List<Outcome> outcomeDatastore = dds.getOutcomeDatastore();
public List<SportEvent> sportEventDataStore = dds.getSportEventDataStore();
public List<Wager> wagerDatastore = dds.getWagerDatastore();
public List<Bet> betsDataStore = dds.getBetDataStore();
public Player loggedPlayer;

@Override
public Player authenticateUser(User login) throws AuthenticationException {
    Player find = new Player();

    for (Player player : initializedPlayers) {
            if (login.getEmail().equals(player.getEmail()) && login.getPassword().equals(player.getPassword())) {
                loggedPlayer = player;

            return loggedPlayer;
            }
    }
    throw new AuthenticationException("Incorrect email and/or password");
}

Player class:
public class Player extends User{
private String name;

private BigDecimal balance;

private Currency currency;

public Player(){

}
public Player(String email, String password, String name, BigDecimal balance, Currency currency) {
    super(email, password);
    this.name = name;
    this.balance = balance;
    this.currency = currency;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public BigDecimal getBalance() {
    return balance;
}

public void setBalance(BigDecimal balance) {
    this.balance = balance;
}

public Currency getCurrency() {
    return currency;
}

public void setCurrency(Currency currency) {
    this.currency = currency;
}

@Override
public String toString() {
    return "Player{" +
            "name='" + name + '\'' +
            ", balance=" + balance +
            ", currency=" + currency +
            '}';
}
}`

User class:
public class User{
private String email;
private String password;

public User(){

}

public User(String email, String password) {
    this.email = email;
    this.password = password;
}

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

public String getPassword() {
    return password;
}

public void setPassword(String password) {
    this.password = password;
}

@Override
public String toString() {
    return "User{" +
            "email='" + email + '\'' +
            ", password='" + password + '\'' +
            '}';
}
}

How can I solve this problem? Can someone explain how it works, please?
EDIT:
Currently, I'm using this logic:
 @Test
public void testAuthenticateUserIsSuccesful(){
    DefaultSportsBettingService service = new DefaultSportsBettingService();
    User user = new User("asd","123");
    Player logged = service.authenticateUser(user);
    assertNotEquals(null, logged);
}


text:
Q: Add Archive Page Template via Plugin So, I'm in the process of writing a plugin for a specific site.
I understand WordPress picks the page template from the theme, with php script names according to the chart below. However, I'd like to write a script for my plugin and have WordPress include my script when it searches for the page template.
I know this is typically the job of the theme. I also know child themes are used to override this behavior. Is this something plugins can do as well?

A: WordPress has a template_include filter which you can use.
// Add a filter to 'template_include' hook
add_filter( 'template_include', 'wpse_force_template' );
function wpse_force_template( $template ) {
    // If the current url is an archive of any kind
    if( is_archive() ) {
        // Set this to the template file inside your plugin folder
        $template = WP_PLUGIN_DIR .'/'. plugin_basename( dirname(__FILE__) ) .'/archive.php';
    }
    // Always return, even if we didn't change anything
    return $template;
}

It would be wise to allow your users to decide which archives are affected. Many sites have custom post types and may not want those archives affected like other post types. You can add an options page that dynamically pulls all post types on the current site and allows them to toggle your plugin on or off for each. Once you have that, you'll need to again dynamically pull all post types, and then dynamically build "if" statements for each one. For example, if(is_archive('event') && $eventtoggle == true - if it's an archive of this specific type and the user toggled the plugin on for this specific type.

A: In addition to the correct answer above, let's say you have a custom post type called "links".
WordPress automatically requests an archive called "archive-links.php". Either in your plugin or in your theme, plus the page for the single instance of an CPT entry.
<?php
// Template Logic
function cc_links_init_template_logic($original_template) {
    // Check Theme Template or Plugin Template for archive-links.php

    $file = trailingslashit(get_template_directory()) . 'archive-links.php';

    if(is_post_type_archive('links')) {
    // some additional logic goes here^.
        if(file_exists($file)) {
            return trailingslashit(get_template_directory()).'archive-links.php';
        } else {
            return plugin_dir_path(__DIR__) . 'templates/archive-links.php';
        }
    } elseif(is_singular('links')) {
        if(file_exists(get_template_directory_uri() . '/single-links.php')) {
            return get_template_directory_uri() . '/single-links.php';
        } else {
            return plugin_dir_path(__DIR__) . 'templates/single-links.php';
        }
    }

    return $original_template;
}
add_action('template_include', 'cc_links_init_template_logic');

A: //add_filter( 'archive_template', 'get_custom_post_type_template' ) ;
add_filter('archive_template', 'yourplugin_get_custom_archive_template');
function yourplugin_get_custom_archive_template($template) {
    global $wp_query;
    if (is_post_type_archive('articles')) {
        $templates[] = 'archive-articles.php';
        $template = yourplugin_locate_plugin_template($templates);
    }
    return $template;
}
function yourplugin_locate_plugin_template($template_names, $load = false, $require_once = true) {
    if (!is_array($template_names)) {
        return '';
    }
    $located = '';
    $this_plugin_dir = WP_PLUGIN_DIR . '/' . str_replace(basename(__FILE__), "", plugin_basename(__FILE__));
    foreach ($template_names as $template_name) {
        if (!$template_name) continue;
        if (file_exists(STYLESHEETPATH . '/' . $template_name)) {
            $located = STYLESHEETPATH . '/' . $template_name;
            break;
        } elseif (file_exists(TEMPLATEPATH . '/' . $template_name)) {
            $located = TEMPLATEPATH . '/' . $template_name;
            break;
        } elseif (file_exists($this_plugin_dir . '/templates/' . $template_name)) {
            $located = $this_plugin_dir . '/templates/' . $template_name;
            break;
        }
    }
    if ($load && $located != '') {
        load_template($located, $require_once);
    }
    return $located;
}


text:
Q: SQL query error REGEXP_INSTR with parenthesis in expression I'm having an issue with my query where I have a parenthesis in the regular expression. My editor is associating the parenthesis in the expression with another parenthesis outside of the expression.
I'm wondering if this is causing the ORA-00907: missing right parenthesis error I'm receiving, or if it's something else?
WITH Stats AS
(
    SELECT
        column1, column2
    FROM TABLE1
    UNION ALL
    SELECT
        column1, column2
    FROM TABLE2
),
Newest AS
(
    SELECT s.*
    ROW_NUMBER() OVER
    (
        PARTITION BY
        column1, column2
        REPLACE(REPLACE('%(param)s', '5', '6'), '7', '8')
        ORDER BY colum2 DESC
    )   PRIORITY
    CASE WHEN REGEXP_INSTR('%(param)s', '/(//')
    > 0 AND REGEXP_LIKE(column1, '%(param)s')
    THEN 'Y' END PARAM_MATCH,
    CASE WHEN REGEXP_INSTR('%(param)s', '/(//')
    = 0 AND column1 LIKE '%(param)s' THEN 'Y'
    END LIKE_MATCH,
    FROM Stats s
    WHERE (REGEXP_INSTR('%(param)s', '/(//') > 0
    AND REGEXP_LIKE(column1,'%(param)s')) OR
    (REGEXP_INSTR('%(param)s', '/(//') = 0 AND
    REGEXP_LIKE'%(param)s')) OR
    '%(param)s' IS NULL
)

A: Zillion of errors; noted in comments:
WITH Stats AS
(
    SELECT
        column1, column2
    FROM TABLE1
    UNION ALL
    SELECT
        column1, column2
    FROM TABLE2
),
Newest AS
(
    SELECT s.*                                      --> missing comma
    ROW_NUMBER() OVER
    (
        PARTITION BY
        column1, column2                            --> missing comma
        REPLACE(REPLACE('%(param)s', '5', '6'), '7', '8')
        ORDER BY colum2 DESC
    )   PRIORITY                                    --> missing comma
    CASE WHEN REGEXP_INSTR('%(param)s', '/(//')
    > 0 AND REGEXP_LIKE(column1, '%(param)s')
    THEN 'Y' END PARAM_MATCH,
    CASE WHEN REGEXP_INSTR('%(param)s', '/(//')
    = 0 AND column1 LIKE '%(param)s' THEN 'Y'
    END LIKE_MATCH,                                 --> superfluous comma
    FROM Stats s
    WHERE (REGEXP_INSTR('%(param)s', '/(//') > 0
    AND REGEXP_LIKE(column1,'%(param)s')) OR
    (REGEXP_INSTR('%(param)s', '/(//') = 0 AND
    REGEXP_LIKE'%(param)s')) OR                     --> what is REGEXP_LIKE?
    '%(param)s' IS NULL
)
                                                    --> missing SELECT statement

This is now correct as far as syntax is concerned. Once again, as in your previous question: be more careful when you write queries as this is getting absurd.
WITH Stats
     AS (SELECT column1, column2 FROM TABLE1
         UNION ALL
         SELECT column1, column2 FROM TABLE2),
     Newest
     AS (SELECT s.*,
                ROW_NUMBER ()
                OVER (
                   PARTITION BY column1,
                                column2,
                                REPLACE (REPLACE ('%(param)s', '5', '6'),
                                         '7',
                                         '8')
                   ORDER BY colum2 DESC)
                   PRIORITY,
                CASE
                   WHEN     REGEXP_INSTR ('%(param)s', '/(//') > 0
                        AND REGEXP_LIKE (column1, '%(param)s')
                   THEN
                      'Y'
                END
                   PARAM_MATCH,
                CASE
                   WHEN     REGEXP_INSTR ('%(param)s', '/(//') = 0
                        AND column1 LIKE '%(param)s'
                   THEN
                      'Y'
                END
                   LIKE_MATCH
           FROM Stats s
          WHERE    (    REGEXP_INSTR ('%(param)s', '/(//') > 0
                    AND REGEXP_LIKE (column1, '%(param)s'))
                OR (    REGEXP_INSTR ('%(param)s', '/(//') = 0
                    AND REGEXP_LIKE ('???', '%(param)s'))
                OR '%(param)s' IS NULL)
SELECT *
  FROM newest;


text:
Q: Is it possible to use nodejs express with any jquery library like datatables? I want to be able to use nodejs with jquery without having to execute an npm install as I want to use jquery strictly on the client side. I know this is not possible with the Jade templating engine as its syntax is completely different, but is it possible with some other templating engine? I would prefer not to have a bunch of HTML to haml just to make nodejs happy.

A: It is certainly possible to use jQuery or any other JavaScript client-side library with Jade. You'll need to figure out the syntax to include a JavaScript file and JavaScript code with whatever engine you use. With Jade you can use script() to include an external file (like the jQuery library) and then script to code your specific calls. Take a look at the Jade documentation here: https://github.com/visionmedia/jade#readme
Below is an example of a Jade file that (1) includes jQuery and then (2) updates an HTML element ("message") through jQuery:
doctype 5
html
  head
    title= title
    link(rel='stylesheet', href='/stylesheets/style.css')
    script(src='http://code.jquery.com/jquery-1.8.1.js')
  body
    h1= title
    p#container Welcome to #{title}
    p#message (to be filled in)
    script
      alert('hello world');
      $("#message").html("message set through jquery")

A: Don't think of Jade as a different language or something that is in any way incompatible with your existing HTML/JS stack - it's just a shorthand way to write HTML which allows you to inject server-side data as a byproduct.
For my personal stack I use express + jade on the server side and then angularjs, jquery and twitter bootstrap on the client side. I use require.js to manage all of my imports, and in my jade template I just have a single script() reference that points to the main.js file that has all of my require.js logic in it.
But, as far as express/jade go - the key is to make sure that you understand that it's not there to complicate your life, it's there to make your life easier. If you feel like it's confusing, switch to a different templating engine or simply have express serve up static html pages with nothing injected and set up AJAX services to get the server-side data you need.


text:
Q: Minimum IAM Permissions for writing to a BigQuery table? I'd like to have a job write to a single BigQuery table. I thought the IAM permissions would be simple, granting BigQuery Jobs User role to the Service Account on the respective table, but I'm getting the error.
Access Denied: Project <your-project>: User does not have bigquery.jobs.create permission in project <your-project>
Is there a way to avoid granting a Service Account access to an entire project, when you only want to grant access to a single table in a single dataset? How does one apply the Principle of Least Privilege in GCP BigQuery?
Code making the query:
const bigquery = new BigQuery({projectId});
await bigquery
  .dataset(datasetId)
  .table(tableId, {location: DATASET_LOCATION})
  .load(fileRef);

A: I think it's a missing piece of the NodeJS library. I didn't find a workaround to achieve what I want (In the same time, I'm very bad in NodeJS).
In GO, I found what you need
    bq,err := bigquery.NewClient(ctx, "myRunningProject")
    bq.DatasetInProject("targetProject", "dataset").Table("table").LoaderFrom(...)

You initiate the client in your billable project, where you are Job User. And when you build your dataset/table path, you use a different project.
You can open a feature request on the BigQuery NodeJS library.

A: You can grant access at Table level if needed. However, the issue you are facing is that the Service Account or any user in general need to have a proper permission to actually create a job. In other words, the queries run in projects that are linked to a Billing account. Someone needs to pay for it.
The role "BigQuery Job User" provides permissions to run jobs, including queries, within the project. But doesn't give you access to data.
You have to give bigquery.jobUser at project level, and then bigquery.dataViewer to the specific dataset or table. More information about BQ access control in here.


text:
Q: Passed Variable wont submit to Database (PHP) I have a form that is spread over 2 pages.
Step 1 is to search for dublicate in the database if there are no dublicates.. you'll be sent to the second page. And in the second page what you've searched for is in a disabled form input. so that you cant edit it. But the problem is that this input wont be submitted to the database and i get an error.
PAGE 1:
    <form class="form-horizontal" id="form" method="POST">
    <fieldset>

    <input type="search" id="hiddenField" name="SkoleNavn" class="form-control input-lg" placeholder="f.eks. Aarhus Universitet" required="">

    <button class="btn btn-primary btn-lg ladda-button" data-style="zoom-out" data-size="l" type="submit"></button>

    </fieldset>
</form>
<?php
if(isset($_POST['SkoleNavn'])) {
if ( $schoolExist ) {

echo "";
}

else {

echo "<form action=\"http://localhost/Vurderskole/add-step2.php\" method=\"POST\">
      <input id=\"SkoleNavn\" name=\"SkoleNavn\" type=\"hidden\" value=\"$SkoleNavn\" class=\"form-control input-md\">
      <button class=\"btn btn-primary btn-lg ladda-button\" data-style=\"zoom-out\" data-size=\"l\" type=\"submit\">Tilføj $SkoleNavn</button>
      </form>
     ";
}
}
?>

Page 2:

  Skole Navn

  <input id="disabled" name="SkoleNavn" type="text" value="<?php echo $_POST['SkoleNavn']; ?>" class="form-control input-md" disabled>

Input.php
<?php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="**********"; // Database name
$tbl_name="*********"; // Table name

// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");

// Get values from form
$persNavn       = $_POST['persNavn'];
$persMail       = $_POST['persMail'];
$persTel        = $_POST['persTel'];
$SkoleNavn      = $_POST['SkoleNavn'];
$SkoleAdresse   = $_POST['SkoleAdresse'];
$SkoleBy        = $_POST['SkoleBy'];
$SkolePostNr    = $_POST['SkolePostNr'];

// Insert data into mysql
$sql="INSERT INTO $tbl_name(SkoleNavn, persNavn, persMail, persTel, skoleAdresse, skolePostNr, skoleBy) VALUES
                           ('$SkoleNavn','$persNavn','$persMail','$persTel','$SkoleAdresse','$SkolePostNr','$SkoleBy')";
$result=mysql_query($sql);

// if successfully insert data into database, displays message "Successful".
if($result){
echo "Tak For Din Ansøgning - Du vil modtage en mail på om din ansøgning er godkendt eller ej.";
}

else {
echo "Der er desværre sket en fejl. Prøv igen eller kontakt os for yderligere hjælp.";
}
?>

<?php
// close connection
mysql_close();
?>

EDIT: Added Check_input.php
    <?php

if(isset($_POST['SkoleNavn']))
{
    $SkoleNavn = $_POST['SkoleNavn'];
} else {
    $SkoleNavn = "";
}

$res = mysql_query("SELECT * FROM school WHERE SkoleNavn='{$SkoleNavn}'");
if (!$res) {
    die("error! " . mysql_error());
}

if (mysql_num_rows($res)) {
    $schoolExist = true;
} else {
    $schoolExist = false;
}
?>

I keep getting an error that the form is empty. What am i doing wrong? Thanks.

A: <input id="disabled" name="SkoleNavn" type="text" value="<?php echo $_POST['SkoleNavn']; ?>" class="form-control input-md" disabled>

dont use "disable" attribute, use "readonly" attribute instead.
<input id="disabled" name="SkoleNavn" type="text" value="<?php echo $_POST['SkoleNavn']; ?>" class="form-control input-md" readonly/>

$_POST will get nothing from input have disable attribute so if (isset()) in ur Check_input.php file gonna past into $SkoleNavn = "";
also change all your $_Post var like this to prevent query error 'cause of special char as '. If get some query error, success message still print but add nothing to your database
$persNavn       = str_replace("'","''",$_POST['persNavn']);


text:
Q: Unity iOS OpenGL app crash I have an iOS Unity Game developed. In order to help tester to track the bug, I have added one more module which will take the snapshot and then show a view to the tester to Annotate it. I am using Apple's GLPaint example : https://developer.apple.com/library/ios/samplecode/GLPaint/Introduction/Intro.html .
When I start annotating, I pause the Unity game and resume when the annotation is over. But there is one problem, when I try to resume the unity game, the app crashes weirdly with some error GL_INVALID_OPERATION
Check the trace log

A: Never used Unity, but it smells like the current GL context changes when you bring up the annotation view, and isn't restored properly when you return to the game. Give saving/restoring Unity's GL context a shot (see: EAGLContext +currentContext & +setCurrentContext:).


text:
Q: how to put image to pdf using itextsharp with asp.net 3.5 i just want to add image to pdf document using itextSharp in asp.net 3.5.
here is my code:
//Photo
            try
            {
                if ((Byte[])dr["Image"] != null)
                {
                    Byte[] bytes1 = (Byte[])dr["Image"];
                    iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(bytes1);
                    Chunk imageChunk = new Chunk(image, 0, 0);
                    phrase.Add(imageChunk);
                    document.Add(table);
                }
                else
                {
                    cell = ImageCell("../images/my_photo.gif", 30f, PdfPCell.ALIGN_CENTER);
                    table.AddCell(cell);
                    document.Add(table);
                }
            }
            catch
            {
                cell = ImageCell("../images/my_photo.gif", 30f, PdfPCell.ALIGN_CENTER);
                table.AddCell(cell);
                document.Add(table);
            }

how ever pdf created successfully but image didn't appeared.
please help me....

A: ya i found soln there is one statement that i omits.
document.add(image);


text:
Q: DDD + node.js: Where should domain logic go I am trying to institute DDD into a node.js application using es6.  I am using mongoose for my data access layer.  I noticed that mongoose has a ".methods" property tied to the model schema.  In terms of adding business logic to an entity, would this be an ideal place to add business logic or should I consider creating another object that holds the business logic that mirrors the model schema object and just copy the data from one to the other?  If I were using sequalize, what would be the preferred approach here?

A: I don't think there is really a definitive answer to this, but I'll give you some opinions.
A number of DDD related concepts and instruments are built around features exposed by OOP languages (in-particular: interfaces & IOC). In the JavaScript world, things tend to be a little different, particularly when leveraging the module system. That said, it's not impossible, but compromises might need to be made.
One of the more important points in DDD is that your models are "plain". They are completely ignorant of any persistence mechanisms, etc, they are simply just data and logic. By defining your models using Mongoose, you pretty much lose that; your business logic is being attached to a Mongoose schema object. But perhaps that is where you can compromise, it very much depends on how puristic you wish to be about it. Now, you can do mapping, as you suggested. If you do decide to go ahead with that idea, something like AutoMapper could help. I've been involved in a project that used ES7 decorators from cerialize for a terser approach (we weren't using schemas, however).


text:
Q: jQuery row.child missing on second page I created a table using jQuery. I added a row.child which shall be shown after each parent row. On the first page this works fine. But on the second page it is missing.
function format(d) {
    return '' +

            '<i style=";color:#9b9b9b; font-size:10px; Padding-left:50px"> Vertragsart - ' + d[4] + '  |   Intensität - ' + d[5] + '</i>' +
            '';
}

var $j = jQuery.noConflict();

$j('document').ready(function () {
    var oTable = $j('#position_list').DataTable({
        "order": [[0, "desc"]],
        "iDisplayLength": 50,
        "oLanguage": {
            "sLengthMenu": "Zeige _MENU_ Einträge",
            "sSearch": "Suche:",
            "sInfo": "Zeige _START_ bis _END_ von _TOTAL_ Einträgen",
            "sInfoEmpty": "Zeige _START_ bis _END_ von _TOTAL_ Einträgen",
            "sInfoFiltered": "(gefiltert aus _MAX_ Datensätzen)",
            "oPaginate": {
                "sNext": "Nächste",
                "sPrevious": "Vorherige"
            },
        },
    });

    $j('.parentrow').closest('tr').each(function () {
        var row = oTable.row(this);
        var data = format(row);
        row.child(format(row.data())).show();
    });
});

A: Use drawCallback option or draw event to call your code every time the table is redrawn.
For example:
$j('#position_list').on('draw.dt', function(){
    $j('.parentrow').closest('tr').each(function(){
        var row = oTable.row(this);
        var data = format(row);
        row.child(format(row.data())).show();
    });
});

A: The problem is that you are using jQuery to select the rows, but jQuery only has access to the rows currently on the DOM. As it was said in the comments, only the  rows of the current page are in the DOM at any given moment, so those are the only rows your code will manipulate.
To run a jQuery selector through the whole table, Datatables API has the $() method. It accepts a jQuery selector that will be run on all tr elements on the table and their descendant elements, returning a jQuery object like jQuery(selector) does.
So you only need to change your jQuery selector for oTable.$(...):
oTable.$('.parentrow').closest('tr').each(function () {
    var row = oTable.row(this);
    var data = format(row);
    row.child(format(row.data())).show();
});


text:
Q: bootstrap table in mobile view I have created the Desktop view for my website. However, I need to modify the bootstrap table for my mobile view. I need to merge two rows into one and make it a single row.

HTML CODE FOR DESKTOP VIEW:

            1 Part
            2 Parts
            Additional Parts

            $10.00
            $20.00
            $30.00

A: Using flexbox (no library)

[flex-row] {
  display: flex;
  max-width: 800px;
  margin: 0 auto;
}

[flex-col] {
  flex-grow: 1;
  text-align: center;
  padding: 15px;
  border: 1px solid #eee;
}

@media (max-width: 767px) {
  [flex-row] {
    flex-wrap: wrap;
  }
  [flex-col] {
    flex: 1 0 95%;
  }
}

1 Part

$10.00

2 Parts

$10.00

Additional Parts

$30.00

Using Bootstrap:

.my-display [class^="col-"] {
  border: 1px solid #eee;
  padding: 15px;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

1 Part

$10.00

2 Parts

$10.00

Additional Parts

$30.00

A: Plnkr

                    1 part

                    10

                    2 parts

                    20

                    Additional parts

                    30


text:
Q: OpenLayers: IE: SCRIPT5: Access is denied I am working on a project using OpenLayers. And I get the "Access is denied" error on IE only. I know there are some solutions to (maybe) easier problems:
SCRIPT5: Access is denied in IE9 on xmlhttprequest
Access denied to jQuery script on IE
But my restriction is that I cannot modify any library that I am using. But since this is a common problem, maybe OpenLayers has some solution ready and I just cannot find the right syntax to use it.
        var sundials = new OpenLayers.Layer.Vector("KML", {
            projection: map.displayProjection,
            strategies: [new OpenLayers.Strategy.Fixed()],
            protocol: new OpenLayers.Protocol.HTTP({
                url: "london_shapes.kml",
                format: new OpenLayers.Format.KML({
                    extractStyles: true,
                    extractAttributes: true
                })
            })
        });

        map.addLayers([wms]);
        map.addLayers([sundials]);//if you comment this, the error disappears
        //so it is obvious that the script cannot load london_shapes.kml under IE.

http://jsfiddle.net/dt1510/huepP/5/
Question: Is there an OpenLayers standard way to get rid of the IE problem?
EDIT:
Here is a simpler demonstration of my problem:
The following web page works both in IE and Firefox: http://www.openlayers.org/dev/examples/kml-layer.html
However if I download it, it works only in Firefox, IE7 and not in IE8/IE9. I need the web page work when it is on the client's computer and not online.

A: I solved it changing the jQuery library version 1.8.0 by 1.8.1


text:
Q: Why do Javascript functions return "undefined" on creation? I understand the difference between undefined and null as a type; I'm just not grasping the following event:
function x() {
    return 0;
}

undefined

Why does this happen? What is going on under the hood that is causing the environment to return an "undefined" value?
UPDATE: I'm not invoking the function in the example above, just defining it and the console returns this "undefined" value.

A: This fuction definition is a statement. In JS, statements don't return values, which, in JS, is an undefined value.
In JS, assignments with var are statements too, but assignments without var behave as expressions : their whole value is the value being assigned.
Therefore, in the console :
> x=function() {return 0;}
< ƒ () {return 0;}

A:
What is going on under the hood that is causing the environment to return an "undefined" value?

In this case, undefined represents the lack of a value.
You haven't run any expression, so there is no value to arise from it.


text:
Q: Set edit control text value from custom action with WIX How can I change text value of an "edit" <Control /> from a C# custom action?
I can populate a "combobox" control but I can't find a way to change an "edit" control value.

A: If you are dealing with a file browser dialog or folder browser dialog (Will work for your case as well), publish the changed property after executing the custom action. Best if you reset before calling the custom action. See following example
  <Control Id="editLocation"  Type="Edit" X="45" Y="174" Height="18" Width="220" Property="YOUR_PROPERTY" Text="[YOUR_PROPERTY]"/>
  <Control Id="btnEditLocation" Type="PushButton" X="270" Y="175" Width="56" Height="17" Text="Browse" Property="YOUR_PROPERTY">
  <Publish Event="Reset" Value="1">1</Publish>
  <Publish Event="DoAction" Value="YOUR_CUSTOM_ACTION"><![CDATA[1]]></Publish>
  <Publish Property="YOUR_PROPERTY" Value="[YOUR_PROPERTY]"><![CDATA[1]]></Publish>
  </Control>

A: As well as linking the properties as suggested by Nilaksha Perera, my approach is to move the Reset action to the C# custom action. That way, we can choose to call it only when the custom action is about to complete successfully. This has the advantage of not clearing the value of the edit control unless a replacement value has been specified.
An example custom control:
public static ActionResult FileBrowser(Session session)
{
    try
    {
        // Call your file browser here.

        session[VALUE] = "New value";

        session.DoAction("Reset");
        return ActionResult.Success;
    }
    catch (Exception ex)
    {
        session.Log($"Unable to launch the file browser: {ex.Message}");
        return ActionResult.Failure;
    }
}

A: The Control element has a Property attribute. This attribute holds the name of the property, which defines the value of the control, in your case, Edit control. When you change the value of this linked property, the control starts displaying this new value.
However, the dialog should "refresh" in order for the changes to become visible. As long as Windows Installer UI is quite limited and doesn't expose a big variety of events, you should work it around somehow.
For instance, let's say that you need to change the value in the edit control when the dialog it is placed on is just loaded. You can achieve this in the following way: on a previous dialog, assign a DoAction event on the Next button click, and run your custom action by this event. Hence, when the next dialog is loaded the edit control will display the desired value.
Side note: it might turn out that you don't need a C# custom action - the SetProperty might be enough. If that's the case, use it wherever possible.


text:
Q: Can Elastic APM track Java Garbage Collection? Is there a way for me to track garbage collection of my Java application using Elastic APM and the associated Java APM agent?
I'm using Spring Boot, if that makes a difference.
Out-of-the-box I'm able to see the heap and non-heap memory utilization, but I'm not sure if there is also a way to view garbage collection.

A: The JVM GC metrics tracked right now are jvm.gc.alloc, jvm.gc.time, and jvm.gc.count.
If you are looking for additional ones, which ones would those be? And could you open an issue with the details.

A: Please import from saved objects option - https://github.com/elastic/apm-contrib/blob/master/apm-agent-java/dashboards/java_metrics_dashboard_7.x.json


text:
Q: Is IronRuby being actively developed? I am planning to use Ruby and RoR 3.x on .Net was wondering if IronRuby is being actively developed, last I heard over the grapevine about year ago was Microsoft withdrew support for it. Can anyone confirm the state ?

A: Although this question is not code related :), I still want to say something.
Jim and another guy were the only two members in Microsoft that were working on IronRuby. After Microsoft takes the thing they want, they "unpurposely" cut down the support for IronRuby (and IronPython), and Jim's boss asked him if he want to do anything else other than Ruby. He sensed it, and left Microsoft. Soon Microsoft claimed they would donate IronRuby to open communities, and they cut off the financial support after about a year. This project is still ongoing, but little code was contributed in the past year due to lack of support on Microsoft .Net and little usage from user end (Ruby is still not so popular)
I wouldn't say IronRuby is discontinued, but it is not so active as you would expect. Try some other Ruby implementation. I personally do not like .Net anyway.

A: According to Wikipedia their last stable release was 22 months ago. They had a preview release 11 months ago. It looks like as of 2010 they have one member of the IronRuby team on staff at Microsoft (may not still be the case).
I'd be quite hesitant to rely on it for any longstanding project.
I would check out RubyInstaller. It's probably not going to be viable if you need .net though.


text:
Q: Addto* - deleteobject - addto* will throw error Basically I insert a row, delete that row, then insert a new row with the same key again.  It will throw an exception on the last line savechanges:  "AcceptChanges cannot continue because the object's key values conflict with another object in the ObjectStateManager. Make sure that the key values are unique before calling AcceptChanges." I confirmed the deleteobject call works.  How do I let the objectstatemanager know that the record is gone and can be reinserted?
        Maps _newMaps = new Maps();

        _newMaps.map_page = "BLA";
        _newMaps.descr = "BLA test";
        opendb.AddToMaps(_newMaps);

        opendb.SaveChanges(true);

        foreach (var mapsrec in opendb.Maps)
        {
            opendb.DeleteObject(mapsrec);
        }
        opendb.SaveChanges(true);

        Maps _sameMaps = new Maps();

        _sameMaps.map_page = "BLA";
        _sameMaps.descr = "BLA test";
        opendb.AddToMaps(_sameMaps);

        opendb.SaveChanges(true);

A: Further research shows that you have to Detach() the object (record) you added to the state manager for it to truly forget about it even after doing a DeleteObject().  So code that would let you add a rec, delete it, add record with same keys would look like:
    Maps _newMaps = new Maps();

    _newMaps.map_page = "BLA";
    _newMaps.descr = "BLA test";
    opendb.AddToMaps(_newMaps);

    opendb.SaveChanges(true);

    foreach (var mapsrec in opendb.Maps)
    {
        opendb.DeleteObject(mapsrec);
        opendb.Detach(_newMapt);
        opendb.SaveChanges(true);
    }

    Maps _sameMaps = new Maps();

    _sameMaps.map_page = "BLA";
    _sameMaps.descr = "BLA test";
    opendb.AddToMaps(_sameMaps);

    opendb.SaveChanges(true);


text:
Q: Turning radius of a vehicle What's the minimum turning radius of a vehicle, rectangular in shape, with length l units and width w units? One key point to consider, would be  that, the inclination of the front wheels can be varied continuously(from 0 to 45 degrees - in both directions) while taking a turn(expert drivers do that all the time and can turn a vehicle in a very short space.).
This is not a homework problem. It's a problem that popped in my head, due to my own parking woes! As such, I am not sure, that the data given would be enough to solve it. So readers are welcome to improve the question(i.e they can suggest additional constraints or data that needs to be given).
While I've previously taken an analytic geometry course in high school, I've never attempted a problem like this. In college,(being an electrical engineering student) my analytical geometry education was not as comprehensive as that of a mechanical or civil engineering student. So I've no idea how to proceed.
This is the first in a series of parking problems, that popped in my head! Some of the other problems require more careful wording, so I've delayed their posting.
PS: When I say turning radius, I am referring to the wall to wall turning radius, as defined in the wikipedia entry on 'Turning Radius'. Also see this - http://firechief.com/apparatus/firefighting_turning_circles
EDIT: In case you can solve this question for any particular set of costraints, do proceed. Just make sure that you mention what those constraints are. Hopefully, someone else might be able to generalize. In case you need additional data, you can assume that data - again just state your data assumptions, so that others can understand.


text:
Q: java convert from double/bigDecimal/float to string with 4decimals approximation I need precision math of maximum 4 decimals that need to be converted to string in order to proceed further with the result in my code and in case the result has more that 4decimals I would like to get the result approximation.
Ex: for 3.3333333333 -> 3.3334
My current code is quite messy, but works. Is there is an easier way around this?
...............
Double rez = (Double) engine.eval(foo); // some rezult as double from the rest of code
        //convert foo to my string

 String implem = String.valueOf(rez);
 rezultat = implem;                     // rezultat -> is the string returned of the function

 if(implem.contains(".")){

 String []splitter =implem.split("\\.");
                                        //   System.out.println(splitter[0]+" length:"+splitter[0].length());
                                        //   System.out.println(splitter[1]+" length:"+splitter[1].length());
 if(splitter[1].length()>4){
 String ceva=splitter[1].substring(0,4);

     byte subb[]=ceva.getBytes();
     char c = (char)subb[3];
                                        //    System.out.println((char)subb[0]+">"+(char)subb[1]+">"+(char)subb[2]+">"+(char)subb[3]+" :those are the splits");
if(subb[0]==subb[1] && subb[1]==subb[2] && subb[2]==subb[3] && (char) subb[0]=='9'){
//in case of 9999

long numer = Long.parseLong(splitter[0]);
numer++;
splitter[0]=String.valueOf(numer);
rezultat = splitter[0];
return rezultat;                        // program returns next Long value (without decimals)

}

                                        //   System.out.println(subb[0]+"+"+subb[1]+"+"+subb[2]+"+"+subb[3]+" value of subb[3]:"+c);
    if(c!='0'){
        int kappa = Integer.parseInt(ceva);
        kappa++;

        String partCeva = String.valueOf(kappa);                            //in case of integer<1000 -- add 0's
        while(partCeva.length()<4){
        partCeva= "0"+partCeva;
        }
           ceva=partCeva;
    }
    Double fin = Double.parseDouble(splitter[0]+"."+ceva);                  //do this to remove unwanted 0
     rezultat = fin.toString();

 }
 else{
    rezultat = splitter[0]+"."+splitter[1];
 }
...........
return rezultat ; }

A: You can do
double x = (Double) engine.eval(foo);

To round to a String using double or float.
return String.format("%4f", x);

To round to a String using BigDecimal
return BigDecimal.valueOf(x).setScale(4, RoundingMode.HALF_UP).toString();

The value 3.3333333333 is usually rounded to 3.3333 however there is a mode which rounds up to the next value.


text:
Q: SQL joining and counting 3 tables and including NULL Link to relevant schema in question
For SQL. Making a query to show All employees who have helped customers and showing the count of their invoices. My issue was that I could get employees count and ID to show, but I could not get ALL employees to show from the query.
Output should look something like
ID - Last - First - COUNT(invoices)
Name should show up if NULL as well.
I tried:
SELECT e.EmployeeId,e.LastName, e.FirstName, COUNT() as NUM_INVOICE
FROM employees AS e
LEFT OUTER JOIN customers as c ON e.EmployeeId=c.SupportRepId
INNER JOIN invoices as i ON c.CustomerId =i.CustomerId
GROUP BY e.EmployeeId
ORDER BY NUM_INVOICE DESC

And it gave : Output from my best attempt
The problem was that this did not show the remaining id's that did not have any invoices connected through the customers table and to the invoices table. It is missing 5 names from the employee table and they should show NULL for the count. I would think that a Left inner join would solve this and "bring" the names from the employees table but they are dropped.

A:
The problem was that this did not show the remaining id's that did not have any invoices connected through the customers table and to the invoices table.

Then, use a LEFT JOIN:
SELECT
    e.EmployeeId, e.LastName, e.FirstName, COUNT(i.CustomerId) AS NUM_INVOICE
FROM employees AS e
LEFT JOIN customers AS c ON e.EmployeeId = c.SupportRepId
LEFT JOIN invoices AS i ON c.CustomerId = i.CustomerId
GROUP BY e.EmployeeId
ORDER BY NUM_INVOICE DESC

A: Just to show an alternative: I prefer aggregating data before joining it. Here, I would join the invoice count to the employees:
select e.employeeid, e.lastname, e.firstname, coalesce(ic.cnt, 0) as num_invoice
from employees as e
left outer join
(
  select c.supportrepid, count(*) as cnt
  from customers as c
  inner join invoices as i on i.customerid = c.customerid
  group by c.supportrepid
) ic on ic.supportrepid = e.employeeid
order by num_invoice desc;


text:
Q: Setting body text of mailto from asp.net code behind method I have an ASP.NET button. If the user clicks this button, then it calls mailto, which opens the outlook mail window. I have done this by adding the following line into the ASP.net button control tag.
window.open('mailto: abc def<abc.def@ex.com>?subject= exSub &body= exBody');
Now I want to set the body text (in the above example it is exBody) dynamically in my code behind method. How can I do that?

A: You can register script in Click event of button in codebehind following way:
 string mailBody = getMailBody(); //// Get the content for email body
 ClientScript.RegisterStartupScript(this.GetType(), "mailto",
        "window.open('mailto: abc def<abc.def@ex.com>?subject= exSub &body= "+ mailBody +"');", true);

A: Bind it to a page property, and use the property to construct the mailto attribute (URL-encoded):
<asp:Button RunAt = "Server"
    onclick = <%#
        "window.open('mailto: abc def<abc.def@ex.com>?subject= exSub &body="
        + Server.UrlEncode(MailToBody ?? "") + "');"
    %>
/>

Then set the MailToBody property from your code-behind as needed.


text:
Q: Counting distinct nodes in path I have a graph with customers, transactions, and merchants with connections that look as follows:
(Customer)->(Transaction)->(Merchant).
I'm trying to effectively return a new graph that connects the various merchants by the number of shared distinct customers (customers that have transacted with both merchants), which can be interpreted as the number of distinct customer nodes in all paths between a first Merchant node to a second Merchant node. Unfortunately, from what I can tell this is prohibitively expensive to do in Neo4j. To give you an idea of what I'm trying to do, here are some queries that I've tried using to get this done:
MATCH (m1:Merchant)<-[:TRANSACTION_WITH_MERCHANT]-()<-[:CUSTOMER_MADE_TRANSACTION]-(c)-[:CUSTOMER_MADE_TRANSACTION]->()-[:TRANSACTION_WITH_MERCHANT]->(m2:Merchant)
RETURN m1, m2, count(distinct c)

MATCH (m1:Merchant), (m2:Merchant)
WHERE id(m1)<id(m2)
MATCH p=(m1)<-[:TRANSACTION_WITH_MERCHANT]-()<-[:CUSTOMER_MADE_TRANSACTION]-(c)-[:CUSTOMER_MADE_TRANSACTION]->()-[:TRANSACTION_WITH_MERCHANT]->(m2)
RETURN m1, m2, count(distinct c) as n_connections

I realize these queries are pretty nasty because of all the cartesian products, and the huge number of paths that need to be explored when customers have a lot of transactions. Are there any tricks to avoid exploring paths that pass through the same customer? Would creating a graph going directly from customer to merchants they've transacted with be best?
I appreciate any suggestions.

A: Solved my problem well enough to execute the query (although I'm sure there are better solutions. Long story short, I did two things:

*

*Created a relationship directly between customers and merchants with a property indicating how many transactions that customer has with that merchant.

*Removed merchants that had a low number of transactions in order to make the cross product more manageable (didn't see a way around this).
Creating an edge between customers and merchants (already only including merchants with more than 40 transactions).
match (m:Merchant)<-[t:TRANSACTION_WITH_MERCHANT]-()
with m, count(t) as nr_trans
where nr_trans > 40
match (c: Customer)-[:CUSTOMER_MADE_TRANSACTION]->(t:Transaction)-[:TRANSACTION_WITH_MERCHANT]->(m)
with c, m, count(t) as nr_transactions_with_merchant
merge (c)-[:CUSTOMER_TRANSACTED_WITH_MERCHANT {nr_transactions:nr_transactions_with_merchant}]->(m);

Dropping edges and merchants with a low number of transactions:
match (m:Merchant)<-[:TRANSACTION_WITH_MERCHANT]-(t:Transaction)
with m, count(t) as nr_transactions_with_merchant
where nr_transactions_with_merchant <= 40
match (m)<-[e]-()
delete e
delete m;

New query that runs!
MATCH (m1:Merchant), (m2:Merchant)
WHERE id(m1)<id(m2)
MATCH p=(m1)<-[:CUSTOMER_TRANSACTED_WITH_MERCHANT]-(c)-[:CUSTOMER_TRANSACTED_WITH_MERCHANT]->(m2)
RETURN m1, m2, count(c) as n_connections


text:
Q: Make function on ARM assembly /Android NDK I want make an ARM assembly function using Android NDK:

*

*How make it?

*Can I return a value no using registers?

*How to call this function in C++

*Can I call this function directly from Java? How?

(sorry for my English)