text:
Q: java.lang.IllegalArgumentException: Can not set java.lang.String field package.Class.id to java.lang.String I'm real new to Spring and trying to follow some examples and have gotten past many issues, but can't seem to get past this one.  I'm changing my packages and objects to generic names, not to provide confusion, but to avoid any trouble with the example creators.
This happens when Object2CrudRepository.save( Object2 ) is called.  All values in debugger seem to be as expected (null for id since that will be auto generated, null for createdAt also generated, name has String value, List object_1s has a few items, all as expected.)  The issue seems to be happening when its adding the first Object1 (many-to-many).  "FLTO" is a String id for Object1.
Full Stack Trace+
    Hibernate: call next value for hibernate_sequence
    Hibernate: insert into object2 (created_at, name, id) values (?, ?, ?)
    Hibernate: insert into object2_object1s (object2_id, object1s_id) values (?, ?)
    2020-11-29 10:24:08.602  INFO 21008 --- [nio-8080-exec-1] o.h.e.j.b.internal.AbstractBatchImpl     : HHH000010: On release of batch it still contained JDBC statements
    2020-11-29 10:24:08.604 ERROR 21008 --- [nio-8080-exec-1] 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.orm.jpa.JpaSystemException: Error accessing field [private java.lang.String Object1.id] by reflection for persistent property [Object1#id] : FLTO; nested exception is org.hibernate.property.access.spi.PropertyAccessException: Error accessing field [public java.lang.String Object1.id] by reflection for persistent property [Object1#id] : FLTO] with root cause

    java.lang.IllegalArgumentException: Can not set java.lang.String field Object1.id to java.lang.String
        at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:167) ~[na:1.8.0_261]
        at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:171) ~[na:1.8.0_261]
        at sun.reflect.UnsafeFieldAccessorImpl.ensureObj(UnsafeFieldAccessorImpl.java:58) ~[na:1.8.0_261]
        at sun.reflect.UnsafeObjectFieldAccessorImpl.get(UnsafeObjectFieldAccessorImpl.java:36) ~[na:1.8.0_261]
        at java.lang.reflect.Field.get(Field.java:393) ~[na:1.8.0_261]
        at org.hibernate.property.access.spi.GetterFieldImpl.get(GetterFieldImpl.java:71) ~[hibernate-core-5.4.23.Final.jar:5.4.23.Final]
        at org.hibernate.tuple.entity.AbstractEntityTuplizer.getIdentifier(AbstractEntityTuplizer.java:230) ~[hibernate-core-5.4.23.Final.jar:5.4.23.Final]
        at org.hibernate.persister.entity.AbstractEntityPersister.getIdentifier(AbstractEntityPersister.java:5146) ~[hibernate-core-5.4.23.Final.jar:5.4.23.Final]
        at org.hibernate.persister.entity.AbstractEntityPersister.isTransient(AbstractEntityPersister.java:4846) ~[hibernate-core-5.4.23.Final.jar:5.4.23.Final]
        at org.hibernate.engine.internal.ForeignKeys.isTransient(ForeignKeys.java:294) ~[hibernate-core-5.4.23.Final.jar:5.4.23.Final]
        at org.hibernate.engine.internal.ForeignKeys.getEntityIdentifierIfNotUnsaved(ForeignKeys.java:344) ~[hibernate-core-5.4.23.Final.jar:5.4.23.Final]
        at org.hibernate.type.EntityType.getIdentifier(EntityType.java:507) ~[hibernate-core-5.4.23.Final.jar:5.4.23.Final]
        at org.hibernate.type.EntityType.nullSafeSet(EntityType.java:280) ~[hibernate-core-5.4.23.Final.jar:5.4.23.Final]
        at org.hibernate.persister.collection.AbstractCollectionPersister.writeElement(AbstractCollectionPersister.java:930) ~[hibernate-core-5.4.23.Final.jar:5.4.23.Final]
        at org.hibernate.persister.collection.AbstractCollectionPersister.recreate(AbstractCollectionPersister.java:1352) ~[hibernate-core-5.4.23.Final.jar:5.4.23.Final]
        at org.hibernate.action.internal.CollectionRecreateAction.execute(CollectionRecreateAction.java:52) ~[hibernate-core-5.4.23.Final.jar:5.4.23.Final]
        at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:604) ~[hibernate-core-5.4.23.Final.jar:5.4.23.Final]
        at org.hibernate.engine.spi.ActionQueue.lambda$executeActions$1(ActionQueue.java:478) ~[hibernate-core-5.4.23.Final.jar:5.4.23.Final]
        at java.util.LinkedHashMap.forEach(LinkedHashMap.java:684) ~[na:1.8.0_261]
        at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:475) ~[hibernate-core-5.4.23.Final.jar:5.4.23.Final]
        at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:348) ~[hibernate-core-5.4.23.Final.jar:5.4.23.Final]
        at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:40) ~[hibernate-core-5.4.23.Final.jar:5.4.23.Final]
        at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:102) ~[hibernate-core-5.4.23.Final.jar:5.4.23.Final]
        at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1362) ~[hibernate-core-5.4.23.Final.jar:5.4.23.Final]
        at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:453) ~[hibernate-core-5.4.23.Final.jar:5.4.23.Final]
        at org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:3212) ~[hibernate-core-5.4.23.Final.jar:5.4.23.Final]
        at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2380) ~[hibernate-core-5.4.23.Final.jar:5.4.23.Final]
        at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:447) ~[hibernate-core-5.4.23.Final.jar:5.4.23.Final]
        at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:183) ~[hibernate-core-5.4.23.Final.jar:5.4.23.Final]
        at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access$300(JdbcResourceLocalTransactionCoordinatorImpl.java:40) ~[hibernate-core-5.4.23.Final.jar:5.4.23.Final]
        at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:281) ~[hibernate-core-5.4.23.Final.jar:5.4.23.Final]
        at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:101) ~[hibernate-core-5.4.23.Final.jar:5.4.23.Final]
        at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:562) ~[spring-orm-5.3.1.jar:5.3.1]
        at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:743) ~[spring-tx-5.3.1.jar:5.3.1]
        at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:711) ~[spring-tx-5.3.1.jar:5.3.1]
        at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:637) ~[spring-tx-5.3.1.jar:5.3.1]
        at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:390) ~[spring-tx-5.3.1.jar:5.3.1]
        at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:134) ~[spring-tx-5.3.1.jar:5.3.1]
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.1.jar:5.3.1]
        at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:137) ~[spring-tx-5.3.1.jar:5.3.1]
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.1.jar:5.3.1]
        at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:174) ~[spring-data-jpa-2.4.1.jar:2.4.1]
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.1.jar:5.3.1]
        at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:97) ~[spring-aop-5.3.1.jar:5.3.1]
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.1.jar:5.3.1]
        at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:215) ~[spring-aop-5.3.1.jar:5.3.1]
        at com.sun.proxy.$Proxy129.save(Unknown Source) ~[na:na]
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_261]
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_261]
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_261]
        at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_261]
        at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:344) ~[spring-aop-5.3.1.jar:5.3.1]
        at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:208) ~[spring-aop-5.3.1.jar:5.3.1]
        at com.sun.proxy.$Proxy124.save(Unknown Source) ~[na:na]
        at Object2Controller.processDesign(Object2Controller.java:71) ~[classes/:na]
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_261]
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_261]
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_261]
        at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_261]
        at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:197) ~[spring-web-5.3.1.jar:5.3.1]
        at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:141) ~[spring-web-5.3.1.jar:5.3.1]
        at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106) ~[spring-webmvc-5.3.1.jar:5.3.1]
        at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:893) ~[spring-webmvc-5.3.1.jar:5.3.1]
        at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:807) ~[spring-webmvc-5.3.1.jar:5.3.1]
        at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.3.1.jar:5.3.1]
        at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1061) ~[spring-webmvc-5.3.1.jar:5.3.1]
        at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:961) ~[spring-webmvc-5.3.1.jar:5.3.1]
        at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) ~[spring-webmvc-5.3.1.jar:5.3.1]
        at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909) ~[spring-webmvc-5.3.1.jar:5.3.1]
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:652) ~[tomcat-embed-core-9.0.39.jar:4.0.FR]
        at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) ~[spring-webmvc-5.3.1.jar:5.3.1]
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:733) ~[tomcat-embed-core-9.0.39.jar:4.0.FR]
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-9.0.39.jar:9.0.39]
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.39.jar:9.0.39]
        at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.39.jar:9.0.39]
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.39.jar:9.0.39]
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.39.jar:9.0.39]
        at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-5.3.1.jar:5.3.1]
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.3.1.jar:5.3.1]
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.39.jar:9.0.39]
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.39.jar:9.0.39]
        at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[spring-web-5.3.1.jar:5.3.1]
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.3.1.jar:5.3.1]
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.39.jar:9.0.39]
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.39.jar:9.0.39]
        at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-5.3.1.jar:5.3.1]
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.3.1.jar:5.3.1]
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.39.jar:9.0.39]
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.39.jar:9.0.39]
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) ~[tomcat-embed-core-9.0.39.jar:9.0.39]
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97) [tomcat-embed-core-9.0.39.jar:9.0.39]
        at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542) [tomcat-embed-core-9.0.39.jar:9.0.39]
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143) [tomcat-embed-core-9.0.39.jar:9.0.39]
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) [tomcat-embed-core-9.0.39.jar:9.0.39]
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78) [tomcat-embed-core-9.0.39.jar:9.0.39]
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) [tomcat-embed-core-9.0.39.jar:9.0.39]
        at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:374) [tomcat-embed-core-9.0.39.jar:9.0.39]
        at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) [tomcat-embed-core-9.0.39.jar:9.0.39]
        at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868) [tomcat-embed-core-9.0.39.jar:9.0.39]
        at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1590) [tomcat-embed-core-9.0.39.jar:9.0.39]
        at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-9.0.39.jar:9.0.39]
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_261]
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_261]
        at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-9.0.39.jar:9.0.39]
        at java.lang.Thread.run(Thread.java:748) [na:1.8.0_261]

Object1
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.Id;

@Entity
public class Object1 {

    @Id
    @Column( length=4 )
    private String id;
    private String name;
    @Enumerated( EnumType.STRING )
    private Type type;

    public static enum Type {
        WRAP,
        PROTEIN,
        VEGGIES,
        CHEESE,
        SAUCE
    }
    public Object1( String id, String name, Type type ) {
        this.id = id;
        this.name = name;
        this.type = type;
    }
    protected Object1() {}
    public String getId() {
        return id;
    }
    public String getName() {
        return name;
    }
    public Type getType() {
        return type;
    }
}

*

*Tried adding setters.

*Tried making fields public.

*Tried making fields not final (as seen here.)

Object2
import java.util.List;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.PrePersist;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

@Entity
public class Object2 {
    @Id
    @GeneratedValue( strategy=GenerationType.AUTO )
    private Long id;
    @Size( min=5, message="Name must be at least 5 characters long" )
    @NotNull
    private String name;
    @Size( min=1, message="You must choose at least 1 object1" )
    @ManyToMany( targetEntity=Object1.class )
    private List<String> Object1s;
    private Date createdAt;
    @PrePersist
    void createdAt() {
        this.createdAt = new Date();
    }
    public Object2() {}
    public Object2( String name, List<String> object1s ) {
        this.name = name;
        this.object1s = object1s;
    }
    public String getName() {
        return name;
    }
    public List<String> getObject1s() {
        return object1s;
    }
    public Long getId() {
        return id;
    }
    public Date getCreatedAt() {
        return createdAt;
    }
}

NOTE:  I'm not sure if the @PrePersist annotation is used correctly here, but the current issue doesn't seem to be here.

*

*Tried adding setters.

*Tried making fields public.

Object2CrudRepository (Just to show it's using built in code on save().  Object1 is the same.
package data;

import org.springframework.data.repository.CrudRepository;

import Object2;

public interface Object2CrudRepository extends CrudRepository<Object2, Long> {}

pom.xml - In case it's relevant.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.0</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>ep</groupId>
    <artifactId>example-project</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>example-project</name>
    <description>Example project</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>
        <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

A: You should generate setters and make default constructor public


text:
Q: detecting vertical mouse motion on a horizontal slider I'm using a horizontal slider in WPF, but would like to also perform some action if the mouse is moved vertically (like change the brightness of some control).
I tried responding to MouseMove, but I don't get an update when dragging the slider, if the mouse moves purely vertically - my function only gets called when the slider actually moves.

A: You could attach a handler to the slider's PreviewMouseMove event.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Read variables of Amazon Elastic Beanstalk environment from the Procfile The problem is about the configuration params that the application needs to be executed in the JVM.  I defined the XMX and XMS environment variables but when deployed procfile can't read these variables.
Procfile:

web: java $XMS $XMX  -jar application.jar

If I connect by ssh to the instance, I can't see my variables $ XMX and $ XMS.
What am I doing wrong? Or is there a better way to do it?

A: The solution is to execute a script in the procfile, in that script it reads the environment variables, I still think something is doing wrong, but it works
Procfile:

web: ./run.sh

Script run.sh

exec java $JAVA_OPTS  -jar app.jar

JAVA_OPTS: environment variable defined in instance
Good Luck!


text:
Q: UISplitViewController's Master view loses state after rotation On the iPad, I've noticed that apps like Mail and WebMD keep rows in the final level of the hierarchy of the "Master" (left) view highlighted when tapped. They also remember this state after rotation; if you select an e-mail in landscape and then rotate to portrait, and click the Inbox button to bring up the Master view popover, the correct item is still highlighted, and the list is scrolled to the correct position. Rotate it back to landscape and it's still correct.
I am working on an iPad app similar to Mail. If I launch my app in landscape, select an item from the list, and rotate my iPad, the Master view seems to lose its state; its table is scrolled to the top and no items are highlighted. Even if the device is then returned back to the landscape orientation the list has still forgotten the last item tapped.
Is there some simple/automatic way to get a Master view in a UISplitViewController to save its state? I think I can reproduce this behaviour by storing the NSIndexPath of the last-tapped item and use UITableView's scrollToRowAtIndexPath:atScrollPosition:animated: to jump it to the correct place before/after device rotation, but I am hoping that this is already done automatically on the Apple side of things if I flip the right switch.

A: Turns out it is a "switch" on the Apple side -- specifically, the clearsSelectionOnViewWillAppear property in UITableViewController which is set to YES by default. Setting it to NO lets it remember its state.


text:
Q: Zoom mapview to a region where pins are dropped If I have 3 pins in a mapview, how will I zoom to these pins, when the map loads. That is, when the map loads I need to have a zoomed view, but the view should accomodate all pins dropped in the map. Its working, when the map has just one pin. But I cant handle zoom with multiple pins. Help needed

A: The below method will do that,
- (void)zoomToFitMapAnnotations:(MKMapView *)mapView {
    if ([mapView.annotations count] == 0) return;

    CLLocationCoordinate2D topLeftCoord;
    topLeftCoord.latitude = -90;
    topLeftCoord.longitude = 180;

    CLLocationCoordinate2D bottomRightCoord;
    bottomRightCoord.latitude = 90;
    bottomRightCoord.longitude = -180;

    for(MapAnnotation *annotation in mapView.annotations) {
        topLeftCoord.longitude = fmin(topLeftCoord.longitude, annotation.coordinate.longitude);
        topLeftCoord.latitude = fmax(topLeftCoord.latitude, annotation.coordinate.latitude);
        bottomRightCoord.longitude = fmax(bottomRightCoord.longitude, annotation.coordinate.longitude);
        bottomRightCoord.latitude = fmin(bottomRightCoord.latitude, annotation.coordinate.latitude);
    }

    MKCoordinateRegion region;
    region.center.latitude = topLeftCoord.latitude - (topLeftCoord.latitude - bottomRightCoord.latitude) * 0.5;
    region.center.longitude = topLeftCoord.longitude + (bottomRightCoord.longitude - topLeftCoord.longitude) * 0.5;
    region.span.latitudeDelta = fabs(topLeftCoord.latitude - bottomRightCoord.latitude) * 1.1;

    // Add a little extra space on the sides
    region.span.longitudeDelta = fabs(bottomRightCoord.longitude - topLeftCoord.longitude) * 1.1;

    // Add a little extra space on the sides
    region = [mapView regionThatFits:region];
    [mapView setRegion:region animated:YES];
}

A: I wrote the below code in an App and it is similar to @ElanthiraiyanS Answer
-(void)zoomToFitMapAnnotations:(MKMapView*)mapView insideArray:(NSArray*)anAnnotationArray
{
    // NSLog(@"%s", __FUNCTION__);
    if([mapView.annotations count] == 0) return;

    CLLocationCoordinate2D topLeftCoord;
    topLeftCoord.latitude = -90;
    topLeftCoord.longitude = 180;

CLLocationCoordinate2D bottomRightCoord;
bottomRightCoord.latitude = 90;
bottomRightCoord.longitude = -180;

for(MKPointAnnotation* annotation in anAnnotationArray)
{
    topLeftCoord.longitude = fmin(topLeftCoord.longitude, annotation.coordinate.longitude);
    topLeftCoord.latitude = fmax(topLeftCoord.latitude, annotation.coordinate.latitude);

    bottomRightCoord.longitude = fmax(bottomRightCoord.longitude, annotation.coordinate.longitude);
    bottomRightCoord.latitude = fmin(bottomRightCoord.latitude, annotation.coordinate.latitude);
}

MKCoordinateRegion region;
region.center.latitude = topLeftCoord.latitude - (topLeftCoord.latitude - bottomRightCoord.latitude) * 0.5;
region.center.longitude = topLeftCoord.longitude + (bottomRightCoord.longitude - topLeftCoord.longitude) * 0.5;
region.span.latitudeDelta = fabs(topLeftCoord.latitude - bottomRightCoord.latitude) * 1.1; // Add a little extra space on the sides
region.span.longitudeDelta = fabs(bottomRightCoord.longitude - topLeftCoord.longitude) * 1.1; // Add a little extra space on the sides

region = [mapView regionThatFits:region];
[mapView setRegion:region animated:YES];

}

A: you may calc the center of all pins
- (CLLocationCoordinate2D)centerPointFromAnnotationArray:(NSArray *)array
{
    CLLocationCoordinate2D coorMax = CLLocationCoordinate2DMake(0, 0);
    CLLocationCoordinate2D coorMin = CLLocationCoordinate2DMake(999, 999);

    for ( int i = 0 ; i < [array count] ; ++i )
    {
        LMPoint *a = [array objectAtIndex:i];

        if (  ( a.coordinate.latitude != 0.0f ) || ( a.coordinate.longitude != 0.0f ) )
        {
            if ( a.coordinate.latitude > coorMax.latitude )
            {
                coorMax.latitude = a.coordinate.latitude;
            }
            if ( a.coordinate.longitude > coorMax.longitude )
            {
                coorMax.longitude = a.coordinate.longitude;
            }
            if ( a.coordinate.latitude < coorMin.latitude )
            {
                coorMin.latitude = a.coordinate.latitude;
            }
            if ( a.coordinate.longitude < coorMin.longitude )
            {
                coorMin.longitude = a.coordinate.longitude;
            }
        }
    }

    CLLocationCoordinate2D coorCenter = CLLocationCoordinate2DMake((coorMax.latitude+coorMin.latitude)/2, (coorMax.longitude+coorMin.longitude)/2);

    return coorCenter;
}

then zoom at the point with a proper zoomlevel


text:
Q: Computing $\int_0^{2\pi}\frac{e^{ikt}}{|e^{it}-e^{it_0}|^m}~\text{d}t$, where $k\in\mathbb{Z}$, $t_0\in\mathbb{C}$, and $m=1,3,5,\dots$ I am working on a project on accurate numerical quadrature where I need to compute the following integral in order to find my quadrature weights,
$$
\int_{0}^{2\pi}\frac{{\rm e}^{{\rm i}kt}}{\,\left\vert\,{{\rm e}^{{\rm i}t} - {\rm e}^{{\rm i}t_{0}}}\,\,\right\vert^{\, m}\,}\,{\rm d}t,
$$
where $k\in\mathbb{Z}$, $t_{0}\in\mathbb{C}$, and $m = 1,3,5,\ldots$. The integrand experiences a singularity at $t=t_0$ and $t = \bar{t}_{0}$, and we may assume that $\text{Im}(t_0)\neq 0$. It may also be viewed as finding the Fourier coefficients of $1/|\rm e^{{\rm i}t} - \rm e^{{\rm i}t_{0}}|^m$.
What I am looking for is a closed-form expression of the integral that I hope is relatively cheap to evaluate for a given $t_0$. However, if someone is able to make any progress for e.g. only the case when $m=1$ and $k \geq 0$, it would be of much help.

You may also consider the integral rewritten into a contour integral over the unit circle $S$ by letting $\xi\left(t\right)={\rm e}^{{\rm i}t}$ and $\mu = {\rm e}^{{\rm i}t_0}$,
$$
\frac{1}{i}\oint_{S}\frac{\xi^{k - 1}}{\left\vert\xi-\mu\right\vert^{m}}\,{\rm d}\xi.
$$
I have not been able to make any significant progress on any of the two formulations.


text:
Q: Composition of almost-everywhere differentiable functions $\mathbb{R} \rightarrow \mathbb{R}$ Suppose $g, f : \mathbb{R} \to \mathbb{R}$ are almost-everywhere differentiable. Is $g \circ f$ almost-everywhere differentiable?
(This question deals with a-e. continuity, but the answer does not apply.
This question deals with a-e. differentiability but in higher dimensions; the answers do not apply either.)

A: There exist almost everywhere differentiable functions $f$ and $g$ such that $g\circ f$ is not measurable. One example is given in Ciesielski et al. - $\mathcal{I}$-Density Continuous Functions on page 104. Their construction is as follows:

Consider a perfect nowhere dense set $P\subset\mathbb{R}$ and a nonmeasurable set $S\subset P$. Let $f$ be a homeomorphism s.t. $f^{-1}(C)=P$, where $C$ is a Cantor set of measure $0$, and let $g=1_S\circ f^{-1}$. Then $f$ is a.e. differentiable as a homeomorphism, and $g$ is a.e. differentiable because $g=1_{f(S)}$ and $f(S)\subset C$ has measure $0$. However, $g\circ f=1_S$ is not measurable.


text:
Q: How to read all the files of OneDrive and copy it with Python I am trying to sync my whole OneDrive to AWS S3.
For this purpose, I want to read all the files and folders in OneDrive (so that I can write them in AWS S3).
How do I either get a list of all the files and files in the folders for OneDrive?
I plan to read all files in the form of a data frame and then write it to AWS S3.
The code that I am using right now reads a file from OneDrive that is mentioned explicitly in my code. The code is from this answer
import sys, os, time, requests
import pandas as pd
import urllib.parse

OneDrive_FilePath = 'New Folder/Knox EARNSTSALV2020.xlsx'

OneDrive_FileURL = 'https://graph.microsoft.com/v1.0/me/drive/root:/' + OneDrive_FilePath + ':/content'
OneDrive_FileURL = urllib.parse.quote(OneDrive_FileURL, safe=':/')
print(OneDrive_FileURL)

Client_Id = 'XXXX'
Tenant_Id = 'YYYYY'
Refresh_Token_First = 'ZZZZZ'

PostStr = {'grant_type': 'refresh_token', 'client_id': Client_Id, 'refresh_token': Refresh_Token_First}

Token_Response = requests.post('https://login.microsoftonline.com/' + Tenant_Id + '/oauth2/v2.0/token', data=PostStr)

Access_Token = Token_Response.json()['access_token']
New_Refresh_Token = Token_Response.json()['refresh_token']

if Access_Token is None or New_Refresh_Token is None:
    print('\n> Failed: Access_Token NOT Retrieved')
    sys.exit()

Response = requests.get(OneDrive_FileURL, headers={'Authorization': 'Bearer ' + Access_Token})

if Response.status_code == 200:
    print('\n> Response Success')

    with open('Excel File.xlsx', 'wb') as File:
    File.write(Response.content)
    print('\n> File Downloaded')
else:
    print('\n> Failed:', Response.status_code)
    print(Response.content)
python-3.x azure python-requests

I would like to read all the content instead of just a mentioned file.
How can I do that?

A: According to documentation, you can list the files in a folder and then download:
response = requests.get('/drives/{drive-id}/root:/New Folder/children', headers={'Authorization': 'Bearer ' + Access_Token})

content = json.loads(response.content)
for file in content.values:
    file_response = requests.get(f'/drives/{drive-id}/root:/New Folder/{file.name}/content', headers={'Authorization': 'Bearer ' + Access_Token})
    with open(file.name, 'wb') as dest_file:
        dest_file.write(file_response.content)


text:
Q: Ring buffer in C tail pointer issue (for audio streaming) I am currently writing an embedded application for audio streaming purposes. The embedded app will receive audio packets being sent over wifi, buffer the packets, then send the audio data over to a decoder chip. I have a ring buffer implementation written (with help from an excellent post here on stackoverflow), but am getting some weird behavior sometimes. In terms of audio, I am hearing some parts of the song repeat during playback. I found out that this is due to the tail pointer being set to the beginning of the buffer twice.
(In my implementation, the head pointer marks the end of valid data whereas the tail pointer marks the beginning of valid data)
For example, I see:

*

*Head pointer reset to start of buffer

*Tail pointer reset to start of buffer

*Tail pointer reset to start of buffer <-- this is where I hear audio repeating

*Head pointer reset to start of buffer

Here is the ring buffer implementation:
typedef struct ring_buffer
{
    UINT8 *buffer;      /* data buffer */
    UINT8 *buffer_end;  /* end of data buffer */
    size_t capacity;    /* maximum number of mp3Bytes in the buffer */
    size_t count;       /* number of mp3Bytes in the buffer */
    size_t typesize;    /* size of each mp3Byte in the buffer */
    UINT8 *head;        /* ring buffer head pointer */
    UINT8 *tail;        /* ring buffer tail pointer */
} ring_buffer;

PUBLIC UINT8
AppAudioStream_RingBufInit(ring_buffer *rb, size_t capacity, size_t typesize)
{
    /* alloc buffer of size capacity * typesize */
    rb->buffer = malloc(capacity * typesize);
    if(rb->buffer == NULL)
    {
        printf("ring buffer init fail\r\n");
        return RING_BUF_INIT_FAIL;
    }

    /* init rb buffer to 0 */
    memset(rb->buffer, 0, capacity * typesize);

    /* rb struct element init */
    rb->capacity = capacity;
    rb->buffer_end = rb->buffer + capacity * typesize;
    rb->count = 0;
    rb->typesize = typesize;
    rb->head = rb->buffer;
    rb->tail = rb->buffer;

    return RING_BUF_INIT_DONE;
}

PUBLIC VOID
AppAudioStream_RingBufWrite(ring_buffer *rb, UINT8 *mp3Byte)
{
    /* default: allow overwriting if ring buffer is full */
    memcpy(rb->head, mp3Byte, rb->typesize);
    rb->head = rb->head + rb->typesize;
    if(rb->head == rb->buffer_end) {
        printf("head back to start\r\n");
        rb->head = rb->buffer;
    }

    if(rb->count == rb->capacity) {
        printf("buffer full\r\n");
        if (rb->head > rb->tail)
            rb->tail = rb->tail + rb->typesize;
    } else {
        rb->count++;
    }
}

PUBLIC VOID
AppAudioStream_RingBufRead(ring_buffer *rb, UINT8 *mp3Byte)
{
    /* insert 'comfort noise' if the ring buffer is empty */
    if(rb->count == 0){
        printf("buffer empty\r\n");
        *mp3Byte = NOISE_BYTE;
    } else {
        /* copy data to mp3Byte and increase tail pointer */
        memcpy(mp3Byte, rb->tail, rb->typesize);
        rb->tail = rb->tail + rb->typesize;
        if(rb->tail == rb->buffer_end) {
            printf("TAIL back to start\r\n");
            printf("Tbuffer count: %i\r\n", rb->count);
            rb->tail = rb->buffer;
        }
        rb->count--;
    }
}

Here is how the ring buffer write function is called:
while (1)
{
    AppAudioStream_BufRecv(sd, dataLen, &addr);
}

PUBLIC VOID
AppAudioStream_BufRecv(int sd, INT32 dataLen, struct sockaddr_in *addr)
{
    INT32 addrlen = sizeof(struct sockaddr_in);
    UINT8 j, i = 0;
    UINT8 *audioByte;

    /* listen to incoming audio data packets */
    dataLen = recvfrom(sd, (char *) appRxBuf, sizeof(appRxBuf), 0,
                       (struct sockaddr *)&addr, &addrlen);

    /* set pointer to first element in recieve buffer */
    audioByte = appRxBuf;

    /* buffer received packets into FIFO */
    while (dataLen > 0)
    {
        /* write 1 byte into audio FIFO */
        AppAudioStream_RingBufWrite(&audioFIFO, audioByte);

        /* increase pointer index and update # of bytes left to write */
        audioByte++;
        dataLen--;
    }

    /* wait until buffer is 2/3 full to start decoding */
    if (audioFIFO.count >= FIFO_TWO_THIRD_FULL
        && audioStreamStatus == GSN_STREAM_BUFFERING) {
        audioStreamStatus = GSN_STREAM_START;
        //printf("stream start\r\n");
    }
}

The ring buffer read function is called in a callback which happens every 2 ms (this is basically an ISR):
PRIVATE VOID
AppAudioStream_DecoderCb(UINT32* pDummy, UINT32 TimerHandle)
{
    UINT8 spiWriteCount = 0;
    UINT8 mp3Byte;
    int i = 0;
    GSN_SPI_NUM_T spiPortNumber = GSN_SPI_NUM_0;

    /* read 32 bytes of data from FIFO and write to SPI */
    while (spiWriteCount < DATA_WRITE_AMT)
    {
        /* set stream status to decoding */
        audioStreamStatus = GSN_STREAM_DECODING;

        /* read 1 byte of audio data from FIFO */
        AppAudioStream_RingBufRead(&audioFIFO, &mp3Byte);

        /* write 1 byte of audio data out to VS1053 */
        AppSpi_SdiByteWrite(spiPortNumber, &mp3Byte);

        /* increase byte written count */
        spiWriteCount++;
    }
}

Any help/insight is greatly appreciated. I am sure I am just overlooking something really obvious right now.
Thank you!

A: If you read to this ring buffer from a callback and write to it from elsewhere, then obviously you will get all kind of strange bugs since the ring buffer lacks protection. You need to add a mutex, semaphore, interrupt disable or whatever applies to your particular system.
Also, all variables shared between the callback and the rest of the application should be declared as volatile, to protect against dangerous optimizer bugs (*). In addition to that, such variables may need to be protected with a mutex as well to protect against race conditions.
A good way to stress test if any of the above mentioned bugs is the cause, is to create a multi-thread app. Make 10+ threads that write to the buffer, and 10+ threads that read and print from it. Log the output and see if you get odd values or garbage printed.

(*) (This remark has nothing to do with thread-safety, so please don't come posting comments about volatile not being sufficient for thread-safety, because I never said it was, and I won't have that stupid debate yet again.)


text:
Q: Spark - select multiple columns from array object I have a dataset with following schema
root
 |-- id: string (nullable = true)
 |-- name: string (nullable = true)
 |-- subEntities: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- status: string (nullable = true)
 |    |    |-- subEntityId: long (nullable = true)
 |    |    |-- subEntityName: string (nullable = true)

dataset.select($"id", $"name", $"subEntities.subEntityId", $"subEntities.subEntityName") put subEntityId and subEntityName into separate arrays. How to select multiple columns and put them into single array?

A: If working on Spark >= 2.4 you can use the transform function to generate an array which contains a subset of the original array's fields:
import org.apache.spark.sql.functions.expr

dataset.withColumn("newArray", expr("transform(subEntities, i -> struct(i.subEntityId, i.subEntityName))"))

// or with select
dataset.select(
        $"id",
        $"name",
        expr("transform(subEntities, i -> struct(i.subEntityId, i.subEntityName))").as("newArray")
)

A: *

*.withColumn("status",col("subEntities").getField("status"))

*.withColumn("subEntityId",col("subEntities").getField("subEntityId"))
To extract value out of your array
Below is working example
import org.apache.spark.sql.functions._

object ExplodeArrauy {

  def main(args: Array[String]): Unit = {

    val spark = Constant.getSparkSess

    import spark.implicits._

    val df = List(bean57("1",Array(bean55("aaa",2),bean55("aaa1",21))),
      bean57("2",Array(bean55("bbb",3),bean55("bbb3",31)))).toDF

    df
      .withColumn("status",col("subEntities").getField("status"))
      .withColumn("subEntityId",col("subEntities").getField("subEntityId"))
      .show()

  }

}

case class bean57(id:String,subEntities:Array[bean55])

case class bean55(status: String,subEntityId:Long)


text:
Q: Jquery to change a form's target I want to change the form's target based on the option which is selected.
<form id='post_form' target="targetvalue">

<select id="select" name="select">
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
</select>

    </form>

 <script>
 $("#select").change(function() {
    var targetvalue = $("#select option:selected").text();
    $("#post_form").attr("target", targetvalue);
    });

 </script>

A: *

*If you want to set the target to either Option 1 or Option 2, what you have is correct. However, if you want to set the target to either option1 or option2, you should have:
var targetvalue = $("#select option:selected").val();

which can be simplified to just;
var targetvalue = $(this).val();

*If you're using jQuery > 1.6, you should be using prop() instead of attr(). For more details see StackOverflow: .prop() vs .attr()
$("#select").change(function() {
    var targetvalue = /* which ever you decide */;
    $("#post_form").prop("target", targetvalue);
});

*You shouldn't really be linking to just the latest version in a production environment; if a new version of jQuery gets released with breaking changes, you're screwed. Link to a specific version of jQuery, and test thoroughly before you upgrade to a new release;
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>

*If you're only defining the <script> after the <form> element to be able to target it, realise you can use a $(document).ready() block to define the script anywhere;
<script>
    $(document).ready(function () {
        $('#select').change(function () {
            var targetvalue = /* which ever you decide */;
            $('#post_form').prop("target", targetvalue);
        });
    });
</script>

A: If indeed your HTML page is written as is specified in the question then the script will run after the DOM has been updated with the form you are trying to modify - but if the script is part of a JavaScript file linked in the  then you need to enclose it within the $(document).ready() function ....
Thanks @T.J.Crowder for linking the following article on this -> Document ready event ?
Place your script within the $(document).ready() block - this will ensure the DOM is ready before attemptig to change it :
<script type="text/javascript">
  $(document).ready(function() {
     $("#select").change(function() {
       var targetvalue = $(this).val();
       $("#post_form").prop("target", targetvalue);
     });
  });
</script>


text:
Q: Mertens formulas aren't enough for prime number theorem For the primes it's true that
$$
\sum_{p \le x}\frac{1}{p} = \ln\ln x + M + O(1/\ln x)
$$
where, $M$ is suitable constant, and, moreover, the prime number theorem gives that
$$
\lim_{x\to\infty}\frac{\pi(x)}{x/\ln x}=1
$$
with $\pi(x)$ is the prime counting function. David Speyer gives a nice heuristic here in order to explain why Mertens formulas aren't enough for pnt. However, I'm concerned with finding a series of integer numbers $a$ such that
$$
\sum_{a \le x}\frac{1}{a} = \ln\ln x + C + O(1/\ln x)
$$
with $C$ suitable constant, but it isn't true that
$$
\lim_{x\to\infty}\frac{f(x)}{x/\ln x}=1
$$
where $f$ is the counting function of numbers $a$. This would give a a concrete counterexample for
$$
\text{Mertens}\rightarrow\text{pnt}.
$$

A: Take $a_n\in 0,1$ such that $$\sum_{n\le x} a_n=\frac{x}{\ln x}(1+\frac14 \cos(\ln x))+O(1)$$ then do a partial summation to find the asymptotic of $$\sum_{n\le x} \frac{a_n}{n}$$ And you meant $\sum_{p\le x} \frac1p= \ln\ln x + C + O(1/\ln x)$.


text:
Q: How to separate glossary entries from section references in hyperref I have a document, a glossary and references. I am using the hyperref package to create hyperlinks
\usepackage[colorlinks = true,
        linkcolor = red,
        urlcolor  = green,
        citecolor = blue,
        anchorcolor = blue]{hyperref}

Apparently, linkcolor colors both glossary entries and Section / Table / Figure numbers in red.
Is there a way to split this? (Actually, I'd like blue for links and normal black for glossary entries.)

A: As from glossaries v4.08, the command that performs the actual hyperlink is \glsdohyperlink. The default definition is
\newcommand*{\glsdohyperlink}[2]{\hyperlink{#1}{#2}}

When the hyperlinks are enabled with \glsenablehyper, the internal command that's used for the hyperlinks is set to \glsdohyperlink. (In earlier versions, it was set directly to \hyperlink.) This means that if you want to adjust the hyperlinks, you can redefine \glsdohyperlink and then use \glsenablehyper (rather than having to fiddle with internal commands.) For example:
% arara: pdflatex
% arara: makeglossaries
% arara: pdflatex
% arara: bibtex
% arara: pdflatex
% arara: pdflatex
\documentclass{article}

\usepackage[colorlinks = true,
        linkcolor = red,
        urlcolor  = green,
        citecolor = blue,
        anchorcolor = blue]{hyperref}
\usepackage{glossaries}

\makeglossaries

\newglossaryentry{sample}{name={sample},description={an
example~\cite{article-minimal}}}

\renewcommand*{\glsdohyperlink}[2]{%
 {\hypersetup{linkcolor=black}\hyperlink{#1}{#2}}}

\glsenablehyper

\begin{document}

\section{Sample}
\label{sec:sample}

A \gls{sample} entry in section~\ref{sec:sample}.

\printglossaries

\bibliographystyle{plain}
\bibliography{xampl}

\end{document}

This will work for the other glossary entry commands, such as \glstext or \glslink, but not for the links in the location lists. The above produces:

So the citation link is in blue, the cross-references (including location cross-references) are in red and the glossary entry links are in black.


text:
Q: Set output file name for PDF exporter I am using JasperReports 5.6
I generate pdf using PDFCreator.
My pdf is generated successfully, but i can't set name to that PDF file.
PrintRequestAttributeSet printRequestAttributeSet = new HashPrintRequestAttributeSet();
printRequestAttributeSet.add(MediaSizeName.ISO_A4);
PrintServiceAttributeSet printServiceAttributeSet = new HashPrintServiceAttributeSet();
printServiceAttributeSet.add(new PrinterName("PDFCreator", null));
JRPrintServiceExporter exporter = new JRPrintServiceExporter();
exporter.setExporterInput(new SimpleExporterInput(tempFileName));
SimplePrintServiceExporterConfiguration configuration = new SimplePrintServiceExporterConfiguration();
configuration.setPrintRequestAttributeSet(printRequestAttributeSet);
configuration.setPrintServiceAttributeSet(printServiceAttributeSet);
configuration.setDisplayPageDialog(false);
configuration.setDisplayPrintDialog(false);
exporter.setConfiguration(configuration);
exporter.exportReport();

My pdf name are set using that PDFCreator tool
I want to pass the name to that pdf file.
Since   exporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, "d:/adc.pdf"); method is now deprecated.
Please tell me solution how to set that out file name

A: I don't think there's a way to pass a file name to PDFCreator, because the whole idea is that it is a virtual printer. So to the program that sending the document, it could be being printed on a physical printer somewhere, hence an output file name would be irrelevant.
Whenever I need to output reports as PDFs I use JasperExportManager, which is a much simpler solution. The exportReportToPdfFile method accepts the output file path as a string. Example:
JasperPrint filledReport = JasperFillManager.fillReport("report.jrxml", params);
JasperExportManager.exportReportToPdfFile(filledReport, "report.pdf");

Alternatively, you can keep your code largely the same but change your JRPrintServiceExporter to a JRPdfExporter. The new way to set the output format (now that setParameter is deprecated) is to construct an ExporterOutput and then call setExporterOutput on your exporter.


text:
Q: Referencing external files with a node.js server? I have an Ubuntu 10.04 hosting server which allows me to run node.js off of it.  I'm making an test homepage and I have a few files as follows:
index.html:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>iSuperMario</title>

    <link rel="stylesheet" href="css/reset.css">
    <link rel="stylesheet" href="css/style.css">

            <input type="text" id="text-input">
            <input type="button" value="Send" id="send-button">

reset.css and style.css (which both just contain styling for the index.html page
chat.js (which contains some scripting to implement the barebones chat function for the index.html page)
server.js which is a node.js server utilizing nowjs to serve the index.html page on port 8080 of the Ubuntu server and to implement the chat function:
var fs = require('fs');
var server = require('http').createServer(function(req, response){
  fs.readFile(__dirname+'/index.html', function(err, data){
    response.writeHead(200, {'Content-Type':'text/html'});
    response.write(data);
    response.end();
  });
});
server.listen(8080);
var everyone = require("now").initialize(server);

everyone.connected(function(){
  console.log("Someone has joined!");
});

everyone.disconnected(function(){
  console.log("Someone has left...");
});

everyone.now.distributeMessage = function(message){everyone.now.receiveMessage(message);};

So, when I view the page from the server in a browser, none of the external resources (reset.css, style.css, chat.js, green_pipe_960.png and orange_pipe_960.png) are connected properly.
How should I enable these?  I mean, if I had to, and it simplified the process a great deal, I could always include the external styles and scripts in index.html.  But, the images could never be embedded (at least I think xD).
Thanks!

A: You need to set your file structure as follows
 = main
   = index.html
   = css
     = reset.css
     = style.css
   = js
     = chat.js
   = images
     = green_pipe..
     = orange_pipe..

Alternatively you can change your urls to match your real file structure.
I would like to recommend you use express or something else if you want to server something beyond a very basic prototype.

A: This webpage might help. Serving Static Files from Node.js.


text:
Q: Работа с select и option Нужно при выборе конкретного select'a выводить разный текст.
Мой код

$(document).ready(function() {
    $('input[type=submit]').click(function() {
        selectUser = [$("#selectUser option:selected").val()];
        if (selectUser = 'user1') {
            alert('User 1');
        } else {
            alert ('Other user');
        }
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="" method="GET">
  <select size="4" class="select-user" id="selectUser">
    <option disabled>Пользователи</option>
    <option value="user1">Пользователь 1</option>
    <option value="user2">Пользователь 2</option>
    <option value="user3">Пользователь 3</option>
    <option value="user4">Пользователь 4</option>
    <option value="user5">Пользователь 5</option>
  </select>
  <input type="submit" class="btn" id="btn">
 </form>

Я хочу обращаться к каждому значению selct'a, то бишь value и если выбран нужный value что-то делать. Пока у меня постоянно выводит user1. Как я понимаю, мое условие не сравнивает со значением value, а именно присваивает. Как сделать что бы оно сравнивало?

A: В Javascript в условие if (сюда) {} необходимо класть либо true либо false
Что вы сделали:
Вы положили в условие результат присвоения переменной:
selectUser = 'user1'
if (selectUser) {
    тут какой-то код
} else {
    другой код при else
}

В данном случае javascript попытается привести переменную selectUser к булевой, true или false и на основании этого, сделает блок кода if или else
Если selectUser тут будет равняться строке с текстом, то приведя её к boolean, получится true, если будет пустая строка, то получится false
решение на jQuery:

$(document).ready(function() {
    $('input[type=submit]').click(function(e) {
        e.preventDefault();
        selectUser = $("#selectUser option:selected").val();
        if (selectUser === 'user1') {
            console.log('User 1');
        } else {
            console.log('Other user');
        }
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="" method="GET">
  <select size="4" class="select-user" id="selectUser">
    <option disabled>Пользователи</option>
    <option value="user1">Пользователь 1</option>
    <option value="user2">Пользователь 2</option>
    <option value="user3">Пользователь 3</option>
    <option value="user4">Пользователь 4</option>
    <option value="user5">Пользователь 5</option>
  </select>
  <input type="submit" class="btn" id="btn">
 </form>

Vanilla JavaScript:

const form = document.querySelector('form#formSelectUser');
const selectUser = document.querySelector('select#selectUser.select-user');

form.addEventListener('submit', e => {
  e.preventDefault();
  const value = selectUser.value;
  if (value === 'user1') {
    console.log('Это user1');
  } else if (value === '') {
    console.log('Выберите нужного user');
  } else {
    console.log('Это не user1');
  }
});
<form action="" method="GET" id="formSelectUser">
  <select size="4" class="select-user" id="selectUser">
    <option disabled>Пользователи</option>
    <option value="user1">Пользователь 1</option>
    <option value="user2">Пользователь 2</option>
    <option value="user3">Пользователь 3</option>
    <option value="user4">Пользователь 4</option>
    <option value="user5">Пользователь 5</option>
  </select>
  <input type="submit" class="btn" id="btn">
 </form>

A: Можно получить вот так велью выбранного элемента селекта и внутри события уже писать условия

let select = document.querySelector('.select-user')

select.addEventListener('change', () => {
  console.log(select.options[select.selectedIndex].value)
})
<form action="" method="GET">
  <select size="4" class="select-user" id="selectUser">
    <option disabled>Пользователи</option>
    <option value="user1">Пользователь 1</option>
    <option value="user2">Пользователь 2</option>
    <option value="user3">Пользователь 3</option>
    <option value="user4">Пользователь 4</option>
    <option value="user5">Пользователь 5</option>
  </select>
  <input type="submit" class="btn" id="btn">
 </form>

A: Немного переделал ваш код, теперь он работает правильно) Проблема в том что вы не правильно их сравнивали нужно вместо оператора '=' поставить "===", что означает строгое сравнение.

$(document).ready(function() {
    $('input[type=submit]').on('click', function() {
        selectUser = $("#selectUser option:selected").val();
        if (selectUser === 'user1') {
            alert('User 1');
        } else {
            alert ('Other user');
        }
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="" method="GET">
  <select size="4" class="select-user" id="selectUser">
    <option disabled>Пользователи</option>
    <option value="user1">Пользователь 1</option>
    <option value="user2">Пользователь 2</option>
    <option value="user3">Пользователь 3</option>
    <option value="user4">Пользователь 4</option>
    <option value="user5">Пользователь 5</option>
  </select>
  <input type="submit" class="btn" id="btn">
 </form>


text:
Q: Mocha unit tests are NOT found in NTVS I'm trying to get Mocha unit tests written in TypeScript to work in Visual Studio 2015 Community Edition in Node Tools for Visual Studio. I'm getting this error (in the Output window, Tests section):
------ Discover test started ------
Processing:  <lot of *.js** files>...
Test discovery error: [TypeError: Cannot read property 'replace' of undefined] in C:\Code\ov\BuyCo\test\sellers\testPersistance.js
Test discovery error: [TypeError: Cannot read property 'replace' of undefined] in C:\Code\ov\BuyCo\test\sellers\testUserPersistance.js
...<andsoon>
Processing finished for framework of Mocha
Discovered 0 testcases.
========== Discover test finished: 0 found (0:00:01.4378126) ==========

So it's listing .js files instead of ts, those are already transpiled out, but there is absolutely no replace function in the generated code in those functions. So it's a very strange error. I'm using Typescript 1.7.
The tests are working when run from the command prompt (npm test ...). But I want to be able to set (note I'm testing NodeJS code, e.g. serverside CommonJS).
Note: During analysis I've already simplified down one test file to the default typescript example file, but it raises the same error, so that should NOT be the issue:
import assert = require('assert');

describe("Test Suite 1", () => {
it("Test A", () => {
    assert.ok(true, "This shouldn't fail");
});

it("Test B", () => {
    assert.ok(1 === 1, "This shouldn't fail");
    assert.ok(false, "This should fail ts");
});
});

A: It managed to fix this in the end; thought I'd share:
This issue was caused in my case by NTVS having some weird scoping requirement.
There was some Javascript code in the test file that was not nested inside a function. It's code was then executed within the NTVS context, and the stack trace initiated there. So the mention of replace in the error message was nowhere in my testing code, but elsewhere.
This issue can be solved by moving such code into a function. In this case into a (Mocha) before function. I actually later had the exact same issue again, this time coming from different code. Below is an example of moving some code to fix this issue. Hopefully then NTVS will detect your unit tests correctly again.
Before (error)
import ...

var clearDb = require("mocha-mongoose")(dbUri);     <--- NTVS don't like it

describe("Example unit test", () => {
    before(done => {
        var testSubject = { name: "John Doe" };
    }

    it("throws strange error");
}

After
import ...

describe("Example unit test", () => {
    before(done => {
        var clearDb = require("mocha-mongoose")(dbUri);  <--- Move to here
        var testSubject = { name: "John Doe" };
    }

    it("now works");
}

Note: I'm using ES6 lambda's - () => { ... } - here instead of regular ES5 functions - function() { ... } - , but that is not important for the error.


text:
Q: Pass the value of stage to another controller of javafx class when load the FXML file As per my thinking When the below two lines are executed by Compiler in javaFX,
First line just set the location of ABC.fxml file.
And in second line when execute loader.load() that time Compiler make one object of the Controller of ABC.fxml file and which is ABCcontroller.java. and call it.
  loader.setLocation(MyApplicationClass.class.getResource("/demo/view/ABC.fxml"));
  rootDisplay = (BorderPane) loader.load();

During this time(at loader.load()) I want to pass the stage value from my current class file(mainclass.java) to the this object of ABCcontroller.class. Because i need this  value further.
I have seen like
loader.load(URL Location, ResourceBundle resources,.....)
Can we pass the value of stage by giving the Parameter. I do not not how to call this or what is the use of this parameters.
Please suggest me how to implement in this way or another idea to do this same thing.

A: You can do the following to pass over a parameter to another controller:
Create a method in your controller class that accepts the parameter, for example:
public void initVariables(String variable) {
    this.variable = variable;
}

call the method after the loader.load():
WindowController controller = fxmlLoader.<WindowController>getController();
controller.initVariables("Test");

Replace WindowController with the name of your controller class.


text:
Q: Javascript simulate click without moving viewport I've created a sticky add to cart area on shopify. When clicking in the variations it also clicks the variations on the product page as well so it's coherent when the user scrolls up. I've used the click method to do that, but it moves the viewport on the top of the page to show the button that is actually clicked. Is there a way to prevent this behavior?
Thanks
Javascript on product page
document.querySelectorAll(".product-form__input.sticky label[class='tooltip']").forEach((input) => {
    input.addEventListener('click', function(e){
       document.querySelector("label[for='"+e.target.getAttribute("data-target-option")+"']").click();
    });
    });

variants.js
   class VariantSelects extends HTMLElement {
  constructor() {
    super();
    this.addEventListener('change', this.onVariantChange);
  }

  onVariantChange() {
    this.updateOptions();
    this.updateMasterId();
    this.toggleAddButton(true, '', false);
    this.updatePickupAvailability();
    if (!this.currentVariant) {
      this.toggleAddButton(true, '', true);
      this.setUnavailable();
    } else {
      this.updateMedia();
      this.updateURL();
      this.updateVariantInput();
      this.renderProductInfo();

    }
  }

  updateOptions() {
    this.options = Array.from(this.querySelectorAll('select'), (select) => select.value);
  }

  updateMasterId() {
    this.currentVariant = this.getVariantData().find((variant) => {
      return !variant.options.map((option, index) => {
        return this.options[index] === option;
      }).includes(false);
    });
  }

  updateMedia() {
    if (!this.currentVariant || !this.currentVariant?.featured_media) return;
    const newMedia = document.querySelector(
      `[data-media-id="${this.dataset.section}-${this.currentVariant.featured_media.id}"]`
    );
    if (!newMedia) return;
    const parent = newMedia.parentElement;
    parent.prepend(newMedia);
    $('.slider-for').slick('slickGoTo', newMedia.offsetParent.attributes[1].nodeValue);
    window.setTimeout(() => { parent.scroll(0, 0) });
  }

  updateURL() {
    if (!this.currentVariant) return;
    window.history.replaceState({ }, '', `${this.dataset.url}?variant=${this.currentVariant.id}`);
  }

  updateVariantInput() {
    const productForms = document.querySelectorAll(`#product-form-${this.dataset.section}, #product-form-installment`);
    productForms.forEach((productForm) => {
      const input = productForm.querySelector('input[name="id"]');
      input.value = this.currentVariant.id;
      input.dispatchEvent(new Event('change', { bubbles: true }));
    });
  }

  updatePickupAvailability() {
    const pickUpAvailability = document.querySelector('pickup-availability');
    if (!pickUpAvailability) return;

    if (this.currentVariant?.available) {
      pickUpAvailability.fetchAvailability(this.currentVariant.id);
    } else {
      pickUpAvailability.removeAttribute('available');
      pickUpAvailability.innerHTML = '';
    }
  }

  renderProductInfo() {
    fetch(`${this.dataset.url}?variant=${this.currentVariant.id}&section_id=${this.dataset.section}`)
      .then((response) => response.text())
      .then((responseText) => {
        const id = `price-${this.dataset.section}`;
        const html = new DOMParser().parseFromString(responseText, 'text/html')
        const destination = document.getElementById(id);
        const source = html.getElementById(id);

        if (source && destination) destination.innerHTML = source.innerHTML;

        document.getElementById(`price-${this.dataset.section}`)?.classList.remove('visibility-hidden');
        this.toggleAddButton(!this.currentVariant.available, window.variantStrings.soldOut);

      });
  }

  toggleAddButton(disable = true, text, modifyClass = true) {
    const addButton = document.getElementById(`product-form-${this.dataset.section}`)?.querySelector('[name="add"]');

    if (!addButton) return;

    if (disable) {
      addButton.setAttribute('disabled', true);
      if (text) addButton.textContent = text;
    } else {
      addButton.removeAttribute('disabled');
      addButton.textContent = window.variantStrings.addToCart;
    }

    if (!modifyClass) return;
  }

  setUnavailable() {
    const addButton = document.getElementById(`product-form-${this.dataset.section}`)?.querySelector('[name="add"]');
    if (!addButton) return;
    addButton.textContent = window.variantStrings.unavailable;
    document.getElementById(`price-${this.dataset.section}`)?.classList.add('visibility-hidden');
  }

  getVariantData() {
    this.variantData = this.variantData || JSON.parse(this.querySelector('[type="application/json"]').textContent);
    return this.variantData;
  }
}

customElements.define('variant-selects', VariantSelects);

class VariantRadios extends VariantSelects {
  constructor() {
    super();
  }

  updateOptions() {
    const fieldsets = Array.from(this.querySelectorAll('fieldset'));
    this.options = fieldsets.map((fieldset) => {
      return Array.from(fieldset.querySelectorAll('input')).find((radio) => radio.checked).value;
    });
  }
}

customElements.define('variant-radios', VariantRadios);

A: One should have a look into the documentation of ...

*

*Event constructor,

*UIEvent constructor,

*and into EventTarget.dispatchEvent.
Maybe something similar to the following example does solve the OP's problem ...
document
  .querySelectorAll('.product-form__input.sticky label[class="tooltip"]')
  .forEach(input => {
    input
      .addEventListener('click', ({ target }) => {
        document
          .querySelector('label[for="' + target.dataset.targetOption + '"]')
          ?.dispatchEvent(
            new UIEvent('click', { "bubbles": true })
          );
      });
    });

A: I was able to work around this using the scroll method of the window element.
  document.querySelectorAll(".product-form__input.sticky label[class='tooltip']").forEach((input) => {
    input.addEventListener('click', function(e){
        let currentY = window.scrollY;
        document.querySelector("label[for='"+e.target.getAttribute("data-target-option")+"']").click();
      window.scroll(0,currentY);
    });
    });


text:
Q: Html navigate to same directory I have a directory with 2 files in it
http://domain.com/folder/index.php and
http://domain.com/folder/page.php
On index page I am trying to make a link that redirects to http://domain.com/folder/
if I make a link like this
Go to Index

it won't refresh the page and if I keep it empty like this
Go to Index

it will get link on any page I am in on same folder. If I was here http://domain.com/folder/page.php that link will be like
Go to Index

Then how can I make a link to index page again instead of I put index.php?

A: You have a couple of options:
You can use a relative link:
Go to page.php
or if you are on page.php
Go to index.php
This will look inside the containing folder of the page you are changing from.

You can use a root path like @tilz0R suggested and declare a base href:

//on index.php

  <base href="http://domain.com/folder/" target="_blank">

//on page.php:
Go to Index


text:
Q: Why is volume of cylinder > volume of cube If we have a cylinder with radius 1 and height 1 and cube with side lengths equal to 1
Volume of cube = $r^3 = 1^3 = 1$
Volume of cylinder = $\pi r^2h = \pi 1^2\times1 = \pi$
clearly $\pi > 1$, but if you think about it if you draw a square with side length one and a circle in the square, the circle has less area ( r = 1) e.g.
http://www.kevinhouston.net/blog/wp-content/uploads/2011/03/circle-in-square.png
So does this not imply that if you raise the two shapes the same height the square would be able to hold more water because the cylunder would fit into the square and there would still be space left over?

A: if your cylinder is radius 1, then the diameter is 2, so it should be bigger then a cube with side length 1. A cylinder radius 1/2 would fit inside a cube. This cylinder would have a volume of $\pi(\frac 1 2)^2\times1 = \frac \pi 4$, which is smaller than 1.

A: Food for thought
I think many problems like this compare apples with oranges.  Let's put the cylinder and cube on the same scale by considering their volumes given the same surface area $S$.  The surface area of the cylinder of radius $r$ and height $h$ is
$$2 \pi r h + 2 \pi r^2$$
Because we have two parameters to vary, let's consider the cylinder of maximum volume given surface area $S$.  Then the volume is
$$V(r) = \frac12 S r - \pi r^3$$
We find the maximum by solving $V'(r)=0$ and noting $V''(r)<0$ and get that the max volume is achieved when $r=\sqrt{S/(6 \pi)}$.  Doing the algebra out, i.e., solving for $h$ and computing the volume, I get
$$V_{\text{cyl}} = \frac16 \sqrt{\frac{2}{3 \pi}} S^{3/2}$$
This is the maximum volume of a cylinder of given surface area $S$, which you may verify, by the way, has a square cross-section.  The cube is more straightforward:
$$V_{\text{cube}} = \left ( \frac{S}{6}\right)^{3/2}$$
The ratio is then
$$\frac{V_{\text{cyl}}}{V_{\text{cube}}} = \frac{2}{\sqrt{\pi}} \gt 1$$
which I hope now answers the question.

A: Say, I have a rectangular piece of paper 16x4. I make it into cylinder h=4 first, by connecting edges with a tape, but not overlapping. Then I bang the walls for each to be 4 inch, turning structure into rectangular form. That can not change the volume of the cylinder into some different volume.

A: Your cube formula is wrong. The volume of a cube that fits a cylinder with radius $r$ in it is $(2r)^3=8r^3$.


text:
Q: Algorithm for the following homework You require an algorithm to read in one customer's account balance at the begining of the month, a total of all withdrawals for the month, and a total of all deposits made during the month. A federal tax charge of 1% is applied to all transactions made during the month. The program is to calculate the account balance at end of the month by (1) subtracting the total withdrawals from the account balance at the beginning of the month, (2) adding the total deposits to new balance, (3) calculating the federal tax (1% of total transactions - that is, total withdrawals+total deposits), and (4) subtracting this federal tax from the new balance. After these calculations, print the final end-of-month balance.

A: This will be a straightforward translation into pseudocode. As this is a homework assignment¸ you'll have to do the legwork yourself. Just evaluate each step in turn:
input: accountBalanceStart, totalDeposits, totalWithdrawals
output: accountBalanceEnd

Let's take the first step:
accountBalanceEnd <-- accountBalanceStart - totalWithdrawals

Now the second:
accountBalanceEnd <-- accountBalanceEnd + totalDeposits

Next, compute the tax and subtract it:
accountBalanceEnd <-- accountBalanceEnd - (totalWithdrawals + totalDeposits) * 0.01

Finally, show the result:
print accountBalanceEnd

A: This happens to be the homework problem on www.palinfonet.com/hw_java2008.pdf due April 17th 2008, question #3.

A: I agree with the other posters, that this is neither a question nor is this a place where people are going to do your homework. But just in case you really absolutely have no clue I give a more concrete example.
What you most likely will need to read:
PL/SQL
SQL Quickref
I would probably try something like this. I intendedly haven't tested or commented it and the syntax might also be wrong for mssql.
    CREATE OR REPLACE FUNCTION Calculate_Balance(account_id long, account_balance float, date datetime) RETURNS float AS
    DECLARE
    transactions_sum float;
    fed_tax float;
    new_account_balance float;
BEGIN
    transactions_sum = SELECT SUM(amount) from transactions
        WHERE transactions.account_id = account_id
        AND month(transactions.date) = month(date)
        AND year(transactions.date) = year(date);

    fed_tax = transactions_sum * 0,01;
    transactions_sum = transactions_sum - fed_tax;
    new_account_balance = transactions_sum + account_balance;

    RETURN new_account_balance;
END;


text:
Q: How to change data type in MongoDB using code to pymongo (Python) I upload the csv file to my base. But date and other numeric data are presented as strings. Nowhere can I find information on how to change the field type. Please write an example)
The documents are located in the table in this form
{
    "_id": {
        "$oid": "5f3e76dfaca73bedb23ef8a1"
    },
    "Province/State": null,
    "Country/Region": "Afghanistan",
    "Lat": "33.93911",
    "Long": "67.709953",
    "Date": "2020-08-19",
    "Value": "37599",
    "ISO 3166-1 Alpha 3-Codes": "AFG",
    "Region Code": "142",
    "Sub-region Code": "34",
    "Intermediate Region Code": null
}

A: My guess is when you are parsing the CSV file you get all of the values as strings. Subsequently that's what you end up with in the database.
Most likely you need to manually cast values to the desired type after you loaded them from the CSV file and before inserting into MongoDB.

A: df = pd.read_csv(path, parse_dates=["Date"], dtype={"Lat": "double", "Value": "int32"}, skiprows=[1])
            df = df.fillna({"Region Code": 0, "Sub-region Code": 0, "Intermediate Region Code": 0})
            df = df.astype({"Region Code": int, "Sub-region Code": int, "Intermediate Region Code": int})


text:
Q: How to dynamically generate MYSQL UPDATE statement based on defined variables from HTML FORM I'm using a rather long HTML form to update lots of details relating to a product - for brevity I won't share the form in its entirety. However, for illustrative purposes here's a snippet :
HTML FORM
<form name="form1" method="post" action="update_ac.php">

        <input name="season" type="text"  class="button_select" id="season" value="<?=$rows['season']; ?>" size="10" />
        <input name="restock" type="checkbox" id="restock" value="on" <?php if($rows['restock']=='on') { echo 'checked="checked"'; } ?>/>

      // other fields

</form>

My question is when posting the form to update_ac.php - how can I dynamically generate a MYSQL update statement based on the fields that are completed?
Here's an example of my form action page:
PHP FORM Action
<?php

       foreach ($_POST as $key => $value) {
        $$key = $value;
      }

$sql= mysql_query ("
UPDATE product SET
title='".$title."',
rating='".$rating."',
season='".$season."',
brand_id='".$brand_id."',
category='".$category."',

... etc ");

?>

I don't want to have to declare every single field that could possibly need updating in the UPDATE statement. I would like the UPDATE statement to only address the fields concerned given the presence of defined PHP variables posted from the form.
At the moment, I'm getting lots of NOTICE: Undefined variable x where there have been empty fields when posting the form.
I hope this makes sense - little long winded.
Any advice? Thanks
UPDATE
Following on from @Styphon's answer - I amended it slightly to include the WHERE condition at the end of the query.
$query = "UPDATE product SET";
$comma = " ";
foreach($_POST as $key => $val) {
    if( ! empty($val)) {
        $query .= $comma . $key . " = '" . mysql_real_escape_string(trim($val)) . "'";
        $comma = ", ";
    }
}

$product_id = $_POST['product_id'];

$query = $query . "WHERE product_id = '".$product_id."' ";

A: Assuming that all the field names in the table are the same as the names of your form inputs this is straight forward. You can use this:
$query = "UPDATE product SET";
$comma = " ";
foreach($_POST as $key => $val) {
    if( ! empty($val)) {
        $query .= $comma . $key . " = '" . mysql_real_escape_string(trim($val)) . "'";
        $comma = ", ";
    }
}
$sql = mysql_query($query);

To be more secure you should create a whitelist of accepted parameters, i.e. the columns in your table like this:
$query = "UPDATE product SET";
$comma = " ";
$whitelist = array(
    'title',
    'rating',
    'season',
    'brand_id',
    'cateogry',
    // ...etc
);
foreach($_POST as $key => $val) {
    if( ! empty($val) && in_array($key, $whitelist)) {
        $query .= $comma . $key . " = '" . mysql_real_escape_string(trim($val)) . "'";
        $comma = ", ";
    }
}
$sql = mysql_query($query);

That way your query can only contain parameters you set, and if anyone manages to inject extras (by changing the names of your form inputs for example) it wont be passed to your database.

I'd also recommend you stop using Mysql_*, it's deprecated. You should look at MySQLi or PDO as alternatives.


text:
Q: Why does the 'Edit List' button sometimes open SharePoint Designer 2013 and sometimes navigate to Microsoft Download Centre? When clicking the 'Edit List' button on a SharePoint list from Internet Explorer:

This sometimes opens SharePoint Designer 2013 and sometimes send me to the Microsoft download link for SharePoint Designer 2013. This seems a list-specific behavior. A particularly frustrating one!
What is causing this?


text:
Q: asio::strand vs io_context::strand Since latest versions of boost, asio comes up with its new executors and provides with asio::strand<Executor>. So it is now perfectly possible to use asio::strand<asio::io_context::executor_type> instead of io_context::strand. But they cannot be used interchangeably.

*

*Could someone explain what is the difference in usage with examples?

*Their advantage/inconvenient compared to the other?

A: io_context::strand is "legacy". I assumed it exists for interface compatibility with code that still uses boost::asio::io_service (also deprecated).

As the comments reflect I've since found out that io_context::strand is not actually deprecated, although I see no reason why this is the case, and close reading of the implementation leaves me with the conclusion that

*

*asio::strand<Executor> is strictly better

*mixing both strand services is not the best idea. In fact both services are documented with the same tag line:
 // Default service implementation for a strand.

I can't help feeling there should be only one default :)

Modern strands don't reference an execution context, but wrap an executor.
While being technically different, it is conceptually the same.
The usage is the same for posting tasks:
post(s, task); // where s is either legacy or modern
defer(s, task);
dispatch(s, task);

In fact you may have tasks with an associated executor, see:

*

*When must you pass io_context to boost::asio::spawn? (C++)

*Which io_context does std::boost::asio::post / dispatch use?

You can no longer use the legacy strand to construct IO service objects (like tcp::socket or steady_timer). That's because the legacy strand cannot be type-erased into any_io_executor:
using tcp = boost::asio::ip::tcp;
boost::asio::io_context ioc;

auto modern = make_strand(ioc.get_executor());
tcp::socket sock(modern);

boost::asio::io_context::strand legacy(ioc);
tcp::socket sock(legacy); // COMPILE ERROR

If you really want you can force it by not using any_io_executor:
boost::asio::basic_stream_socket<tcp, decltype(legacy)> sock(legacy);
sock.connect({{}, 8989});


text:
Q: How to authenticate on a users that were made using ASP.NET Forms Authentication My company maintains a legacy ASP.NET webforms application which uses Forms Authentication for access to the site. We are looking to build a mobile application which would utilize a stateless REST API with token based access. The problem is that the user's passwords were generated on the site and are hashed in the User database. I need a way to authenticate against those hashed passwords by somehow accessing the Forms Authentication's "authenticate" method or build some adapter/middlewear to broker the exchange.
We have done much research on this problem and haven't found any viable solutions as of yet. Any help would be very appreciated.

A: You can use ValidateUser for that. It returns a bool. You can then use it in an webservice or api that accepts the two parameters as QueryString.
bool IsValidLogin = Membership.ValidateUser("UserName", "PassWord")


text:
Q: Ethernet Connection Loaded up Ubuntu 20.04.4.
Have static IP configured.
Removed monitor, mouse and keyboard to make a stand alone server.
When I remove the usb items, the network disconnects.
Noticed when the server boots up with everything connected
the ethernet connection will be green for a bit, then nothing and finally red.
Any idea why I am seeing this behavior?
Tom

A: Sounds like you have a driver issue, as if the system thinks the usb devices are external usb nic devices. You might wanna check all your logs.. https://ubuntu.com/server/docs/logwatch - tool I found to be super helpful.


text:
Q: Run script without typing sh on Android I wanna run my script which is located in system/bin and permissions is 755.
With sh myscript there is no problem but myscipt or ./myscript doesn't work even if the pwd output is /system/bin.
On ubuntu I just need to put in /usr/bin and after setting permissions, I can run it easily. I wondered that why I have to put sh in everytime I typed it.
For example I push the aria2 binary file to /system/bin (755) and I can easily run with typing aria2c. I now that this is not script but they are same thing what I tried.
Update
I have hashbang like #!/bin/bash and which sh output is /system/bin/sh

A: To have it answered: Android has different filesystem layout, and bash is at (from linux PoV non-standard location) /system/bin. That's why script was working on linux (Ubuntu) and not on android.
For non-native executables (e.g. bash, python etc.) to work the "hashbang" (#!) has to be updated to contain correct path to interpreter (#!/system/bin/bash).
If there is /usr/bin/env on android, using #!/usr/bin/env bash would make the script portable.


text:
Q: A links in H3 headings appear smaller than the H3 text The a href links I create with CKeditor are part of h3 headings and appear smaller in font-size, from their counterpart non-link h3 text... For example, if the sentence is:
"We provide Google SEO support", and the word "Google" links to google.com, this word will appear smaller than the rest of that text (say 18px instead of 24px for the rest) and looks funny.
What can cause such a problem? what is worth checking in the text? Here is a link with a live example - You could see the problem in the second heading (h2) right away.
Thanks for you advice,

A: Provide CSS which format the  elements as well as headings.Basically I think that your problem comes from assuming that if you format the header element in css it will affect the child elements too, it will not.
You can fix it like this:
h2, h2>a { font-size: 28px; }

This snippet causes all second headers and it's link children to have the same font size.


text:
Q: Powershell: how to turn an array of objects into an array of integers? I create an array of objects that hold the lengths of files with this command:
$lengths = dir -File | Sort-Object -Descending | Select-Object Length -First 5

However, I want this to be an array of integers, not objects, so I can edit the values easily. How can I convert this $lengths object array into an integer array?
Thank You! :)

A: The answer was provided in comments but to give it closure, you can expand the values of the objects using Select-Object -ExpandProperty. It's worth noting that your Sort-Object statement is not actually sorting by Length unless you specify the property to be sorted:
$length = dir -File | Sort-Object Length -Descending | Select-Object -ExpandProperty Length -First 5

Personal preference to expand the values, you can use ForEach-Object, the syntax is far easier in my opinion but there is no -First X here:
$length = dir -File | ForEach-Object Length | Sort-Object -Descending

$length type will be object[] (object array) even though it will contain an array of int64 values, this is default type for arrays in PowerShell, you can however provide a desired output type either by type casting or hard typing. Looking into the Cast Operator [..] is a good starting point.
# type casting
$length = [Int64[]] (dir -File | ....)

# hard typing
[Int64[]] $length = dir -File | ....

For the latter, $length is constrained to be assigned int64 values or values that can be type coerced to int64, i.e.:
[int64[]] $length = 0..10

# can be assigned an `int32` and the array element will be converted to `int64`
$length = 1
$length[0].GetType() # => `int64`

# can be assigned a `string` which contains for example a decimal value
$length = '1.1', 2
# gets converted to int64 (no longer a decimal value)
$length[0] # => 1

# cannot be assigned a `string` which does not contain a type of numeric value
$length = 1, 'hello' # => ...Cannot convert value "hello" to type "System.Int64"...

While the former only enforces the type of the array elements however a new array of different type can be assigned:
$length    = [int64[]] (0..10)
$length[0] = 'hello' # => ...Cannot convert value "hello" to type "System.Int64"...

$length = 'new', 'object', 'array' # succeeds

A: Unfortunately, you can't use Memeber Access Enumeration for Length because it's also a property of the collection (Unlike, for example, (gci -af).LastwriteTime). But another way to obtain your desired array is:
$Length = (gci -af).Foreach({$_.Length}) | sort -Descending

Without casting, $Length is the generic object array:
PS > $Length.GetType()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Object[]

But all its elements are the same type:
PS > ($Length | gm).TypeName | select -Unique
System.Int64


text:
Q: order of insert/erase statements between independent lists causing seg fault What i am implementing is a bit more complicated so i have stripped down the code and made the simplest example possible that replicates the problem:
I have lists A and B, at some point i need to move 1 element from list A to list B. This object memorizes its position (iterator) on the list that is currently on. It works perfectly well for 1 list, inserting and erasing. Nevertheless, when change list B inside an iterative cycle of list A, i found that the order in which i execute the insert and erase instructions determines if i get an seg fault. Here is the code:
typedef struct AO_ {
    int id;
    list<AO_*>::iterator thispos;
} AnObject;

class MyList {
    public:

    list<AnObject*> ll;
    int sizell;

    MyList(){ sizell=0; }

    void insert(AnObject* AnObjecti){
        AnObjecti->thispos= ll.insert(ll.end(),AnObjecti);
        sizell++;
    }

    list<AnObject*>::iterator remove(AnObject* AnObjecti){
        return ll.erase(AnObjecti->thispos);
    }

    void print(){
        cout << "contents:";
        list<AnObject*>::iterator itAux;
        for (itAux=ll.begin(); itAux!=ll.end(); itAux++)
        cout << " " << (*itAux)->id;
        cout << endl;
    }
};

int main(int argc, char *argv[]){

    MyList* listA= new MyList();
    MyList* listB= new MyList();
    AnObject* objAux= new AnObject();

    for(int i=0; i<10; i++){
        objAux= new AnObject();
        objAux->id= i;
        listA->insert(objAux);
    }

    cout << "list A:" << endl; listA->print();

    list<AnObject*>::iterator it= listA->ll.begin();
    while(it!=listA->ll.end()){
        objAux= (*it);
        if(objAux->id==2){
            //listB->insert(objAux); //***THIS CAN GO HERE (seg fault on next cycle)
            it= listA->remove(objAux);
            listB->insert(objAux); //***OR THIS CAN GO HERE (all ok)
        }
        else
            ++it;
    }

    cout << "list A:"; listA->print();
    cout << "list B:"; listB->print();
}

and the output:
list A:
contents: 0 1 2 3 4 5 6 7 8 9
list A:contents: 0 1 3 4 5 6 7 8 9
list B:contents: 2

I get a seg fault if exchange the instructions marked by *
Does someone know why?
Thanks in advance
jose

A: The call to listB->insert modifies objAux->thispos to refer to the new list. Then the call to listA->remove will try to use that iterator in its call to list::erase. Passing an iterator from the wrong container to erase gives undefined behaviour.


text:
Q: GORM scanrows vs scan in a raw query I found out I got different results using ScanRows or Scan.
if I use:
err=models.DB.ScanRows(nodes, &node)

I get empty values in some fields.
If I replace the structure node for all the attributes:
err = nodes.Scan(&node.NodoId, &node.NodoIdPadre, &node.TipoNodo, &node.SubFormulaId, &node.FuncionId, &node.TipoTerminoId, &node.TerminoId,&node.FuncionDesc,  &node.CodFormula, &node.TipoTerminoDesc, &node.DescTipoNodo, &node.OperadorId, &node.Operador )

It does not have any NULL value, I replace these Null values with coalesce function.

This is node struct
type Node struct {
    NodoId          int
    NodoIdPadre     int
    TipoNodo        int
    SubFormulaId    int
    FuncionId       int
    TipoTerminoId   int
    TerminoId       int
    FuncionDesc     string
    CodFormula      int
    TipoTerminoDesc string
    DescTipoNodo    string
    OperadorId      int
    Operador        string
}

Thank you.
PD: Very difficult to past code in this editor, I got a lot of identation error.


text:
Q: Django, Python, trying to  change field values / attributes in object retrieved from DB objects.all call, not working I'm trying to change a specific field from a field in an object that I retrieved from a django db call.
class Dbobject ()
   def __init__(self):
       dbobject = Modelname.objects.all()
   def test (self):
       self.dbobject[0].fieldname = 'some new value'

then I am able to access a specific attribute like so:
objclass = Dbobject()
fieldvalue = dbobject.dbobject[0].fieldname

but I want to be able to use the "test" method of the Dbobject class to try to change the specific value on an object's attribute value, but it isn't changing it. I am stumped by this as this is how I thought I am supposed to change an object's attribute value.

A: I'm not sure if this is the problem or not, but I think you might be missing a save() method.
from models import Person
p = Person.objects.get(pk=100)
p.name = 'Rico'
p.save()      # <== This writes it to the db. Is this what you're missing?

Above is the simple case.  Adapted for what you wrote above, it'd be like:
dbobject.dbobject[0].fieldname = 'some new value'
dbobject.dbobject[0].save()

or, I'd write it more like:
rec = dbobject.dbobject[0]
rec.fieldname = 'some new value'
rec.save()

Also note that depending on whether and how you are using transactions, you may or may not see a change to the database until you commit.

A: I am not totally sure what you are trying to achieve, but shouldn't it be something like:
class Dbobject ():
   def __init__(self):
       self.dbobject = Modelname.objects.all()
   def test (self):
       self.dbobject[0].fieldname = 'some new value'


text:
Q: Order by AND LIKE in Same Cassandra Query I want to execute this query on a cassandra table:
       select query,score,term  from mytable where term
       like '%bottle%'  order by score desc limit 10;

The only columns of the table are query, score, term.
I create the table as follows:
CREATE TABLE mytable( "term" TEXT, "query" TEXT, "score" double,
PRIMARY KEY ("term","score")) WITH CLUSTERING ORDER BY (score desc);

I also have an index:
This gives all sort of crazy errors. The first is:
 InvalidRequest: code=2200 [Invalid query] message="LIKE restriction is
 only supported on properly indexed columns. term LIKE 'bottle' is not valid."

If I replace the LIKE with equals, the query works. But I need the LIKE and the order by. So, after some googling, I thought I would use a SASI index.
CREATE CUSTOM INDEX term_idx2 ON mytable (term) USING
'org.apache.cassandra.index.sasi.SASIIndex' WITH OPTIONS = {
'analyzer_class':
'org.apache.cassandra.index.sasi.analyzer.StandardAnalyzer',
'case_sensitive': 'false'};

This produces another error message:
InvalidRequest: code=2200 [Invalid query] message=
"Cannot create secondary index on partition key column term"

OK. This maybe means that if I want to use LIKE, I should not create a secondary index on "term". Then let's try to query by "query" instead. The query becomes:
       select query,score,term  from mytable where query
       like '%bottle%'  order by score desc limit 10;

Now, this produces the "use ALLOW FILTERING" error. Essentially leading me to create index on query. Even creating the SASI type index on query does not not help.
Is this at all possible?

A:
No! you can't use both like and order by in same query.

As you already know you can't create indexes on primary and clustering keys. However, you can create indexes on other columns e.g: query, by using following command:
CREATE CUSTOM INDEX mytable_query_idx  ON mytable ("query")
USING 'org.apache.cassandra.index.sasi.SASIIndex'
WITH OPTIONS = {'mode': 'CONTAINS',
'analyzer_class': 'org.apache.cassandra.index.sasi.analyzer.StandardAnalyzer',
'case_sensitive': 'false'};

And after that, you make a query like
SELECT * FROM mytable WHERE query LIKE '%abc%';

But you can't use order by and like in same query because

"ORDER BY with 2ndary indexes is not supported."

However, If you really need these functionality Cassandra is not a good choice.


text:
Q: How to repair a MacBook Pro 2007 hard drive bus? Is there a repair I can do to the hard drive bus on a MacBook Pro 2007?
I've changed the SATA cable but it still won't see the drive, which I know is good as it boots externally! Disk Utility doesn't detect it either.

A: If you're certain the drive is known to be good and working and that the cable you're using is also in good condition then the answer is no: there isn't anything you can do to fix a broken controller yourself. You'll need to take it to an authorized Apple Repair Center. These things are usually solved with main board swaps as it's all, more or less, integrated on one board in this case.


text:
Q: Force hibernate to NOT retrieve full object i am given a task at work where I have to use hibernate and some classes which are mapped to views. The task says, that i should create a select on one view which does not return a complete object of the class, but an object with just some attributes of the class initialized. i first thought about creating a constructor which only gets these fields as parameter, but I can't find any solution on the web, which holds both possibilities open (parts of the class and full class). Any suggestion is welcome. If you need any code or further explanation, ask for it.

A: You can create jpql query or use criteria api to select attributes you want.
JPQL tutorial is http://docs.oracle.com/javaee/6/tutorial/doc/bnbtg.html
Criteria is http://docs.oracle.com/javaee/6/tutorial/doc/gjivm.html

A: You can use below code.
You can use native sql query in createQuery() and fetch the parameter which you need only then you can transform your result in appropriate class
Query query =  ((SQLQuery) getSession().createSQLQuery(
                "select First_name,Last_name,email_id,.. from view_name  where customer_id=:customer_id").
                setResultTransformer(Transformers.aliasToBean(CustomerProfile.class))).
                setParameter("customer_id", cutsomer_id)
                ;
        List<CustomerProfile> list = query.list();

Need to to Create   CustomerProfile.class with getter and setter.


text:
Q: Comparing numerals within indexed Elements in an array Javascript given an array like ['8:2', '3:2', …] I want to compare each number within every element of the array. So Index[0] would compare 8 with 3 and so on.
If A is equal than B it should get a certain value, if A is less than B it should get another Value.
I just don't know how I get these numbers within an indexed element to be compared, so that the new values could be stored into a second array.
I tried this :
function check(games) {
var newArr = [];
var value;
//var newArr = [];
  for (var j=0; j<=games.length; j++){
    if (games[j].a === games[j].b ) {
      value = 0;
      newArr.push(value);
      //alert(newArr);
      //return value;
    }
    else if(games[j].a > games[j].b ) {
      value = 2;
      newArr.push(value);
      //alert(newArr);
    }
    alert(newArr.join(''));
  }

}

check(['3:3', '2:1']);

Than I tried it with for… in But it does not work either…
(My code example is shortened)
function check(games) {
var arr = games;
var arrNew = [];
  for (var prop in games) {
    if (a === b) {
    var value = 0;
    arrNew.push(value);
    alert(arrNew.join(''));
    }
  }
}

 check(['3:3', '2:1']);

How can I compare elements which are stored within on index? Like Index[0] = ("3:3') - How do I compare a with b so that I can iterate to the next Index?
Thank you

A: const list = ['8:2', '3:2'];
list.forEach((e) => {
  const [a, b] = e.split(':').map(Number);
  if (a > b) {
    // a is greater than b
  } else if (a < b) {
    // b is greater than a
  } else {
    // a and b are equal
  }
});


text:
Q: Tag links not hidden by spoilers Links to tags are not hidden by spoilers:

tags are issues in spoilers

For a start why? I don't see what purpose being able to see the outline of a tag (it is more visible on other sites) when all other pieces of text are hidden.
It has proved problematic in several cases, especially on Puzzling, where hidden answers are imperative 90% of the time.
Also can this be changed? I don't want to cause a massive fuss, so if this is too big to sort out, then don't worry about it.