text:
Q: JS - Drag&drop files and get file type fails I want to get the file type of pasted data, but an ERROR is thrown in the console:
JSFiddle
Error:
Uncaught TypeError: Cannot read property 'type' of undefined

JS:
var reader = new FileReader();

$(".paste").on('drop', function( e ) {

    e.stopPropagation();
    e.preventDefault();

    var file = e.target.files || (e.dataTransfer && e.dataTransfer.files);

    var legalTypes = ["image/png", "image/jpeg", "image/gif"];

    if(legalTypes.indexOf(file.type) === -1) {

        alert("Please only upload image files!");
        return false;
    }

A: use event.originalEvent to get dataTransfer object.
Also the files object will contain array of files. so you need to loop through them or use first element.
the final code will be:
$(document).ready(function () {

   var reader = new FileReader();

$(".paste").on('drop', function( e ) {

    e.stopPropagation();
    e.preventDefault();

    var files = e.originalEvent.target.files || (e.originalEvent.dataTransfer && e.originalEvent.dataTransfer.files);

    var legalTypes = ["image/png", "image/jpeg", "image/gif"];

    for( i in files ) {

        if(legalTypes.indexOf(files[i].type) < 0 ) {

            alert("Please only upload image files!");
            return false;
        }
    }

    });

   });


text:
Q: Write operations are not allowed in read-only mode (FlushMode.MANUAL) I am really new using Spring
I am developing a simple JEE application with JSF+Hibernate+Spring
I am facing some problems when trying to update values on a DAO
I'm sure the problem is related with the Spring configuration xml file, but I can't find out what is.
This is my configuration file:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:c="http://www.springframework.org/schema/c"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:flow="http://www.springframework.org/schema/webflow-config"
       xmlns:jee="http://www.springframework.org/schema/jee"
       xmlns:jms="http://www.springframework.org/schema/jms"
       xmlns:lang="http://www.springframework.org/schema/lang"
       xmlns:osgi="http://www.springframework.org/schema/osgi"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:util="http://www.springframework.org/schema/util"

       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
          http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
          http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
          http://www.springframework.org/schema/webflow-config http://www.springframework.org/schema/webflow-config/spring-webflow-config-2.0.xsd
          http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
          http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-4.0.xsd
          http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-4.0.xsd
          http://www.springframework.org/schema/osgi http://www.springframework.org/schema/osgi/spring-osgi-1.2.xsd
          http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
          http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd
">

    <context:annotation-config/>
    <context:component-scan base-package="com.javarevolutions"/>

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/revolutions?zeroDateTimeBehavior=convertToNull"/>
        <property name="username" value="netbeans"/>
        <property name="password" value="netbeans"/>
    </bean>

    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource">
            <ref bean="dataSource"/>
        </property>

        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>

        <property name="mappingResources">
            <list>
                <value>/com/javarevolutions/jhs/persistence/Login.hbm.xml</value>
                <value>/com/javarevolutions/jhs/persistence/Alumnos.hbm.xml</value>
                <value>/com/javarevolutions/jhs/persistence/Articulos.hbm.xml</value>
            </list>
        </property>
    </bean>

    <!--DAOS-->
    <bean id="loginDAO" class="com.javarevolutions.jdbc.dao.ImplLogin">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>
    <bean id="alumnoDAO" class="com.javarevolutions.jdbc.dao.ImplAlumno">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>

    <!--BOS-->
    <bean id="loginBO" class="com.javarevolutions.jhs.bo.LoginImplBO">
        <property name="loginDAO" ref="loginDAO"></property>
    </bean>
    <bean id="alumnoBO" class="com.javarevolutions.jhs.bo.AlumnoImplBO">
        <property name="alumnoDAO" ref="alumnoDAO"></property>
    </bean>

</beans>

This is the DAO declaration
/
*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.javarevolutions.jdbc.dao;

import com.javarevolutions.jhs.persistence.Alumnos;
import java.util.List;
import org.springframework.orm.hibernate4.support.HibernateDaoSupport;

/**
 *
 * @author Mol
 */
public class ImplAlumno extends HibernateDaoSupport implements IfaceAlumno{

    @Override
    public void insert(Alumnos obj) {
        //getHibernateTemplate().getSessionFactory().getCurrentSession().setFlushMode(org.hibernate.FlushMode.AUTO);
        getHibernateTemplate().save(obj);
    }

    @Override
    public void delete(Alumnos obj) {
        getHibernateTemplate().delete(obj);
    }

    @Override
    public void update(Alumnos obj) {
        getHibernateTemplate().merge(obj);
    }

    @Override
    public List<Alumnos> getAll() {
        List<Object> lista=getHibernateTemplate().find("from Alumnos");
        return (List<Alumnos>)(Object)lista;
    }

}

This is the error LOG
Información:   Hibernate: select alumnos0_.matricula as matricul1_0_, alumnos0_.usuario as usuario2_0_, alumnos0_.nombre as nombre3_0_, alumnos0_.app as app4_0_, alumnos0_.apm as apm5_0_, alumnos0_.edad as edad6_0_, alumnos0_.sexo as sexo7_0_, alumnos0_.fecha_registro as fecha_re8_0_ from revolutions.alumnos alumnos0_
Advertencia:   #{alumnoBean.insert}: org.springframework.dao.InvalidDataAccessApiUsageException: Write operations are not allowed in read-only mode (FlushMode.MANUAL): Turn your Session into FlushMode.COMMIT/AUTO or remove 'readOnly' marker from transaction definition.
javax.faces.FacesException: #{alumnoBean.insert}: org.springframework.dao.InvalidDataAccessApiUsageException: Write operations are not allowed in read-only mode (FlushMode.MANUAL): Turn your Session into FlushMode.COMMIT/AUTO or remove 'readOnly' marker from transaction definition.
    at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:118)
    at javax.faces.component.UICommand.broadcast(UICommand.java:315)
    at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
    at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
    at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:344)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)
    at org.glassfish.tyrus.servlet.TyrusServletFilter.doFilter(TyrusServletFilter.java:295)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:316)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
    at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:415)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:282)
    at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
    at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:201)
    at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:175)
    at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:284)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:201)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:133)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:112)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:561)
    at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:565)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:545)
    at java.lang.Thread.run(Thread.java:745)
Caused by: javax.faces.el.EvaluationException: org.springframework.dao.InvalidDataAccessApiUsageException: Write operations are not allowed in read-only mode (FlushMode.MANUAL): Turn your Session into FlushMode.COMMIT/AUTO or remove 'readOnly' marker from transaction definition.
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:101)
    at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
    ... 40 more
Caused by: org.springframework.dao.InvalidDataAccessApiUsageException: Write operations are not allowed in read-only mode (FlushMode.MANUAL): Turn your Session into FlushMode.COMMIT/AUTO or remove 'readOnly' marker from transaction definition.
    at org.springframework.orm.hibernate4.HibernateTemplate.checkWriteOperationAllowed(HibernateTemplate.java:1135)
    at org.springframework.orm.hibernate4.HibernateTemplate$12.doInHibernate(HibernateTemplate.java:620)
    at org.springframework.orm.hibernate4.HibernateTemplate$12.doInHibernate(HibernateTemplate.java:617)
    at org.springframework.orm.hibernate4.HibernateTemplate.doExecute(HibernateTemplate.java:340)
    at org.springframework.orm.hibernate4.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:308)
    at org.springframework.orm.hibernate4.HibernateTemplate.save(HibernateTemplate.java:617)
    at com.javarevolutions.jdbc.dao.ImplAlumno.insert(ImplAlumno.java:21)
    at com.javarevolutions.jhs.bo.AlumnoImplBO.insert(AlumnoImplBO.java:41)
    at com.javarevolutions.jsf.bean.BeanAlumno.insert(BeanAlumno.java:159)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at com.sun.el.parser.AstValue.invoke(AstValue.java:289)
    at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:304)
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
    ... 41 more

FATAL:   JSF1073: se ha interceptado javax.faces.FacesException durante el procesamiento de INVOKE_APPLICATION 5 : UIComponent-ClientId=, Mensaje=#{alumnoBean.insert}: org.springframework.dao.InvalidDataAccessApiUsageException: Write operations are not allowed in read-only mode (FlushMode.MANUAL): Turn your Session into FlushMode.COMMIT/AUTO or remove 'readOnly' marker from transaction definition.
FATAL:   #{alumnoBean.insert}: org.springframework.dao.InvalidDataAccessApiUsageException: Write operations are not allowed in read-only mode (FlushMode.MANUAL): Turn your Session into FlushMode.COMMIT/AUTO or remove 'readOnly' marker from transaction definition.
javax.faces.FacesException: #{alumnoBean.insert}: org.springframework.dao.InvalidDataAccessApiUsageException: Write operations are not allowed in read-only mode (FlushMode.MANUAL): Turn your Session into FlushMode.COMMIT/AUTO or remove 'readOnly' marker from transaction definition.
    at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:89)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:344)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)
    at org.glassfish.tyrus.servlet.TyrusServletFilter.doFilter(TyrusServletFilter.java:295)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:316)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
    at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:415)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:282)
    at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
    at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:201)
    at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:175)
    at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:284)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:201)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:133)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:112)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:561)
    at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:565)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:545)
    at java.lang.Thread.run(Thread.java:745)
Caused by: javax.faces.FacesException: #{alumnoBean.insert}: org.springframework.dao.InvalidDataAccessApiUsageException: Write operations are not allowed in read-only mode (FlushMode.MANUAL): Turn your Session into FlushMode.COMMIT/AUTO or remove 'readOnly' marker from transaction definition.
    at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:118)
    at javax.faces.component.UICommand.broadcast(UICommand.java:315)
    at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
    at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
    at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
    ... 36 more
Caused by: javax.faces.el.EvaluationException: org.springframework.dao.InvalidDataAccessApiUsageException: Write operations are not allowed in read-only mode (FlushMode.MANUAL): Turn your Session into FlushMode.COMMIT/AUTO or remove 'readOnly' marker from transaction definition.
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:101)
    at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
    ... 40 more
Caused by: org.springframework.dao.InvalidDataAccessApiUsageException: Write operations are not allowed in read-only mode (FlushMode.MANUAL): Turn your Session into FlushMode.COMMIT/AUTO or remove 'readOnly' marker from transaction definition.
    at org.springframework.orm.hibernate4.HibernateTemplate.checkWriteOperationAllowed(HibernateTemplate.java:1135)
    at org.springframework.orm.hibernate4.HibernateTemplate$12.doInHibernate(HibernateTemplate.java:620)
    at org.springframework.orm.hibernate4.HibernateTemplate$12.doInHibernate(HibernateTemplate.java:617)
    at org.springframework.orm.hibernate4.HibernateTemplate.doExecute(HibernateTemplate.java:340)
    at org.springframework.orm.hibernate4.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:308)
    at org.springframework.orm.hibernate4.HibernateTemplate.save(HibernateTemplate.java:617)
    at com.javarevolutions.jdbc.dao.ImplAlumno.insert(ImplAlumno.java:21)
    at com.javarevolutions.jhs.bo.AlumnoImplBO.insert(AlumnoImplBO.java:41)
    at com.javarevolutions.jsf.bean.BeanAlumno.insert(BeanAlumno.java:159)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at com.sun.el.parser.AstValue.invoke(AstValue.java:289)
    at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:304)
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
    ... 41 more

A: I think you should add a transaction manager bean.
<tx:annotation-driven/>

<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
     <property name="sessionFactory" ref="sessionFactory" />
</bean>

and
Add the @Transactional annotation for the methods that should be a transaction.
Hope this helps.

A: Try to change this:
  <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">

With:
 <bean id="sessionFactory" class="org.springframework.orm.hibernate4.HibernateTransactionManager">

A: Once changed the xml configutation file and the DAO
I get the following error:
Grave:   Exception while loading the app
Grave:   Undeployment failed for context /JSFHibernateSpring
Grave:   Exception while loading the app : java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'alumnoBO' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Initialization of bean failed; nested exception is org.springframework.beans.ConversionNotSupportedException: Failed to convert property value of type 'com.sun.proxy.$Proxy273 implementing com.javarevolutions.jdbc.dao.IfaceAlumno,org.springframework.beans.factory.InitializingBean,org.springframework.aop.SpringProxy,org.springframework.aop.framework.Advised' to required type 'com.javarevolutions.jdbc.dao.ImplAlumno' for property 'alumnoDAO'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [com.sun.proxy.$Proxy273 implementing com.javarevolutions.jdbc.dao.IfaceAlumno,org.springframework.beans.factory.InitializingBean,org.springframework.aop.SpringProxy,org.springframework.aop.framework.Advised] to required type [com.javarevolutions.jdbc.dao.ImplAlumno] for property 'alumnoDAO': no matching editors or conversion strategy found

XLM configuration
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:c="http://www.springframework.org/schema/c"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:flow="http://www.springframework.org/schema/webflow-config"
       xmlns:jee="http://www.springframework.org/schema/jee"
       xmlns:jms="http://www.springframework.org/schema/jms"
       xmlns:lang="http://www.springframework.org/schema/lang"
       xmlns:osgi="http://www.springframework.org/schema/osgi"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:util="http://www.springframework.org/schema/util"

       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
          http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
          http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
          http://www.springframework.org/schema/webflow-config http://www.springframework.org/schema/webflow-config/spring-webflow-config-2.0.xsd
          http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
          http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-4.0.xsd
          http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-4.0.xsd
          http://www.springframework.org/schema/osgi http://www.springframework.org/schema/osgi/spring-osgi-1.2.xsd
          http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
          http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd
">

    <context:annotation-config/>
    <context:component-scan base-package="com.javarevolutions"/>

    <tx:annotation-driven/>

    <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/revolutions?zeroDateTimeBehavior=convertToNull"/>
        <property name="username" value="netbeans"/>
        <property name="password" value="netbeans"/>
    </bean>

    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource">
            <ref bean="dataSource"/>
        </property>

        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>

        <property name="mappingResources">
            <list>
                <value>/com/javarevolutions/jhs/persistence/Login.hbm.xml</value>
                <value>/com/javarevolutions/jhs/persistence/Alumnos.hbm.xml</value>
                <value>/com/javarevolutions/jhs/persistence/Articulos.hbm.xml</value>
            </list>
        </property>
    </bean>

    <!--DAOS-->
    <bean id="loginDAO" class="com.javarevolutions.jdbc.dao.ImplLogin">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>
    <bean id="alumnoDAO" class="com.javarevolutions.jdbc.dao.ImplAlumno">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>

    <!--BOS-->
    <bean id="loginBO" class="com.javarevolutions.jhs.bo.LoginImplBO">
        <property name="loginDAO" ref="loginDAO"></property>
    </bean>
    <bean id="alumnoBO" class="com.javarevolutions.jhs.bo.AlumnoImplBO">
        <property name="alumnoDAO" ref="alumnoDAO"></property>
    </bean>

</beans>

DAO
package com.javarevolutions.jdbc.dao;

import com.javarevolutions.jhs.persistence.Alumnos;
import java.util.List;
import org.springframework.orm.hibernate4.support.HibernateDaoSupport;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 * @author Mol
 */
@Transactional
public class ImplAlumno extends HibernateDaoSupport implements IfaceAlumno{

    @Override
    public void insert(Alumnos obj) {
        //getHibernateTemplate().getSessionFactory().getCurrentSession().setFlushMode(org.hibernate.FlushMode.AUTO);
        getHibernateTemplate().save(obj);
    }

    @Override
    public void delete(Alumnos obj) {
        getHibernateTemplate().delete(obj);
    }

    @Override
    public void update(Alumnos obj) {
        getHibernateTemplate().merge(obj);
    }

    @Override
    public List<Alumnos> getAll() {
        List<Object> lista=getHibernateTemplate().find("from Alumnos");
        return (List<Alumnos>)(Object)lista;
    }

}

A: You can resolve the problem in the following ways:

*

*Check all the mandatory data is provided of Bean/Model class at saving time.

*Check the concept of unique constraints is following or not, if not add different data in a unique column.

*If the problem is still not resolved then add @Transaction annotation above the method but to use @Transaction method create an Object of HibernateTransactionManager

@Bean
public HibernateTransactionManager transactionManager() {
           HibernateTransactionManager txManager = new HibernateTransactionManager();
           txManager.setSessionFactory(getLocalSessionFactoryBean().getObject());

return txManager;

  }

A: If you are using Java configuration , simply add @EnableTransactionManagement (org.springframework.transaction.annotation.EnableTransactionManagement)

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I remove the "back to safety" warning on my website using html? I've coded a website and want some people to review it. However, some people have been concerned because a "back to safety" warning pops up for them. I've already gotten an SSL certificate for my website using Let's Encrypt, but the default link is still http. I've tried using the following code in the header of my html:
<meta http-equiv="Refresh" content="0;URL=https://www.yourdomainname.com" />
This was one of the ways some places online said I could redirect traffic to https, since I'm using GitHub pages and I'm not sure how to implement php or make a .htaccess file. There are two problems I have:
First of all, it does redirect people to the https version of the website, but the warning still shows up in the beginning, so my main problem isn't solved.
Second of all, when I use this code, the website refreshes over and over, and I don't think that's good for UX.
Can anybody help me make my website more comfortable for users?
EDIT:
Here's my website if you would like a look at it.

A: if your website has no SSL you cannot remove back to safety it is an indicator of your website security in terms of information gathering, better of get an SSL Security for your site.


text:
Q: как сделать poll или select сервер для приема клиентов? не могу понять как сделать сервер, в котором можно добавить нового клиента в select или poll и получать события. При том ещё и не потерять данные, если в  select или poll будет установлен таймер ( или для сокета сетевые данные буферизируются, пока не закроется сокет? ). вот какой сделал код.
/*
 * server.c - server for game.
 * author: Naidolinskii Dmitrii
 *******************************/
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <pthread.h>
#include <sys/select.h>
#include <sys/time.h>
#include <unistd.h>
#include <poll.h>
#include "config.h"

/* сокет сервера */
static int sockfd;
extern struct conf conf;
struct sockaddr_in in_server;

#define DEFAULT_SIZE_POLL        65535
#define DEFAULT_SIZE_DATA         1024

struct pollfd fds[DEFAULT_SIZE_POLL];
int index_poll;

static void *thread_control_clients ( void *data ) {

    while ( 1 ) {
        int client = poll ( fds, DEFAULT_SIZE_POLL, -1 );
        if ( client == -1 ) {
            perror ( "poll" );
            exit ( EXIT_FAILURE );
        }
        if ( client ) {
            char data[DEFAULT_SIZE_DATA + 1];
            read ( client, data, DEFAULT_SIZE_DATA );
            printf ( "%d: %s\n", client, data );
        }
    }
}

/* создание потока */
void create_thread ( ) {
    pthread_t t;
    pthread_create ( &t, NULL, thread_control_clients, NULL );
}

void wait_client ( ) {
    socklen_t soss = sizeof ( in_server );
    int client = accept ( sockfd, ( struct sockaddr * ) &in_server, &soss );

}

/* конфигурация сокета */
void configure_socket ( ) {
     sockfd = socket ( AF_INET, SOCK_STREAM, 0 );
     if ( sockfd == -1 ) {
         perror ( "socket" );
         exit ( EXIT_FAILURE );
     }

     int ret;
     {
        int opt = 1;
        ret = setsockopt ( sockfd, SOL_SOCKET, SO_REUSEPORT, &opt, sizeof ( opt ) );
        if ( ret == -1 ) {
            perror ( "sock opt SO_REUSEPORT" );
            exit ( EXIT_FAILURE );
        }
     }

     in_server.sin_family = AF_INET;
     in_server.sin_port = htons ( conf.port );
     in_server.sin_addr.s_addr = 0;
     ret = bind ( sockfd, ( struct sockaddr *) &in_server, sizeof ( in_server ) );
     if ( ret == -1 ) {
         perror ( "bind" );
         exit ( EXIT_FAILURE );
     }
     ret = listen ( sockfd, conf.listen );
     if ( ret == -1 ) {
         perror ( "listen" );
         exit ( EXIT_FAILURE );
     }

     for ( int i = 0; i < DEFAULT_SIZE_POLL; i++ ) {

        fds[i].fd = s;
        fds[i].events = POLLIN | POLLOUT;

     }
}

A: Тот код, что Вы привели, он выглядит довольно....оригинально. На самом деле, существуют определённые (почти) стандарты, для разработки сетевых приложений. Настоятельно рекомендую посмотреть книжку
UNIX: разработка сетевых приложений. 3-е изд.
Стивенс У. Р., Феннер Б., Рудофф Э. M.

https://avidreaders.ru/book/unix-razrabotka-setevyh-prilozheniy-3-e.html
Там всё описано в деталях.

A: Решение с epoll.
/*
 * server.c - server for game.
 * author: Naidolinskii Dmitrii
 *******************************/
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <pthread.h>
#include <sys/epoll.h>
#include <sys/time.h>
#include <unistd.h>
#include <string.h>
#include "config.h"

/* сокет сервера */
static int sockfd;
extern struct conf conf;
struct sockaddr_in in_server;
int epollfd, nfds;

#define DEFAULT_SIZE_POLL        65535
#define DEFAULT_SIZE_DATA         1024

struct epoll_event ev, events[DEFAULT_SIZE_POLL];

static void *thread_control_clients ( void *data ) {

    while ( 1 ) {
        nfds = epoll_wait ( epollfd, events, DEFAULT_SIZE_POLL, -1 );
        printf ( "nfds: %d\n", nfds );
        if ( nfds == 0 ) continue;
        if ( nfds == -1 ) {
            perror ( "poll" );
            exit ( EXIT_FAILURE );
        }
        for ( int i = 0; i < nfds; i++ ) {
            char data[DEFAULT_SIZE_DATA + 1];
            int ret = read ( events[i].data.fd, data, DEFAULT_SIZE_DATA );
            if ( ret == -1 || ret == 0 ) {
                epoll_ctl ( epollfd, EPOLL_CTL_DEL, events[i].data.fd, &events[i] );
                continue;
            }
            char *s = strchr ( data, '\n' );
            if ( s ) *s = 0;
            s = strchr ( data, '\r' );
            if ( s ) *s = 0;
            data[ret] = 0;
            printf ( "%d: %s\n", events[i].data.fd, data );
        }
    }
}

/* создание потока */
void create_thread ( ) {
    epollfd = epoll_create1 ( 0 );
    if ( epollfd == -1 ) {
        perror ( "epoll_create" );
        exit ( EXIT_FAILURE );
    }

    pthread_t t;
    pthread_create ( &t, NULL, thread_control_clients, NULL );
}

void wait_client ( ) {
    socklen_t soss = sizeof ( in_server );
    int client = accept ( sockfd, ( struct sockaddr * ) &in_server, &soss );
    if ( client == -1 ) return;
    printf ( "%d подключен.\n", client );
    ev.events = EPOLLIN;
    ev.data.fd = client;
    if ( epoll_ctl ( epollfd, EPOLL_CTL_ADD, client, &ev ) == -1 ) {
        perror ( "epoll_ctl" );
        exit ( EXIT_FAILURE );
    }
}

/* конфигурация сокета */
void configure_socket ( ) {
     sockfd = socket ( AF_INET, SOCK_STREAM, 0 );
     if ( sockfd == -1 ) {
         perror ( "socket" );
         exit ( EXIT_FAILURE );
     }

     int ret;
     {
        int opt = 1;
        ret = setsockopt ( sockfd, SOL_SOCKET, SO_REUSEPORT, &opt, sizeof ( opt ) );
        if ( ret == -1 ) {
            perror ( "sock opt SO_REUSEPORT" );
            exit ( EXIT_FAILURE );
        }
     }

     in_server.sin_family = AF_INET;
     in_server.sin_port = htons ( conf.port );
     in_server.sin_addr.s_addr = 0;
     ret = bind ( sockfd, ( struct sockaddr *) &in_server, sizeof ( in_server ) );
     if ( ret == -1 ) {
         perror ( "bind" );
         exit ( EXIT_FAILURE );
     }
     ret = listen ( sockfd, conf.listen );
     if ( ret == -1 ) {
         perror ( "listen" );
         exit ( EXIT_FAILURE );
     }

}


text:
Q: How to add horizontal image set in flutter? Hi Im trying to make something like this. All the black balls are png images.

So far I tried this,
final bolabola = ListView(
      shrinkWrap: true,
      //scrollDirection: Axis.horizontal,
      children: <Widget>[
        Container(
            width: 20.0,
            child: Image(
              image: AssetImage("assets/scoreballs/n1.png",),
              height: 25.0,
              width: 25.0,
            ),
        ),

        Container(
          width: 20.0,
          child: Image(
            image: AssetImage("assets/scoreballs/n1.png",),
            height: 25.0,
            width: 25.0,
          ),
        )
      ],

    );

scrollDirection didnt work because I use a another list view to display all my components in the page.
How do I fix this?
Edit: my complete code is below
import 'package:flutter/material.dart';

class Live extends StatefulWidget{
  State<StatefulWidget> createState(){
    return LiveState();
  }
}

class LiveState extends State<Live> {

  @override
  Widget build(BuildContext context) {

    //Live button
    final livestatus = Chip(
        backgroundColor: Colors.red,
        label: Text("LIVE",style: TextStyle(fontSize: 9.0, fontWeight: FontWeight.bold, color: Colors.white), textAlign: TextAlign.center),
    );

    //Status bar
    final status = Text("Richmond College won the toss and elected to bat first", style: TextStyle(fontSize: 12.0, fontWeight: FontWeight.bold), textAlign: TextAlign.center);

    //School Crest
    final crest = Image(
        image: AssetImage("assets/crest.png"),
        height: 79.0,
        width: 64.0,
    );

    final score = Text("182/4", style: TextStyle(fontSize: 73.0, color: Colors.blueAccent, fontWeight: FontWeight.bold), textAlign: TextAlign.center,);

    final overs = Text("23.5 Overs", style:TextStyle(fontSize: 30.0, color: Colors.grey, fontWeight: FontWeight.bold),textAlign: TextAlign.center, );

    final scorecard = Text("Scorecard", style:TextStyle(fontSize: 10.0, color: Colors.black, fontWeight: FontWeight.bold),textAlign: TextAlign.center, );

    final bolabola = ListView(
      shrinkWrap: true,
      //scrollDirection: Axis.horizontal,
      children: <Widget>[
        Container(
            width: 20.0,
            child: Image(
              image: AssetImage("assets/scoreballs/n1.png",),
              height: 25.0,
              width: 25.0,
            ),
        ),

        Container(
          width: 20.0,
          child: Image(
            image: AssetImage("assets/scoreballs/n1.png",),
            height: 25.0,
            width: 25.0,
          ),
        )
      ],

    );

/*
    final scoreballs = Image(
      image: AssetImage("assets/scoreballs/n1.png",),
      height: 25.0,
      width: 25.0,
    );

    */

        return Scaffold(
          backgroundColor: Colors.white,
          body: Center(
            child: ListView(
              shrinkWrap: true,
              children: <Widget>[
                livestatus,
                SizedBox(height: 0.0),
                status,
                SizedBox(height: 10.0),
                crest,
                SizedBox(height: 5.0),
                score,
                overs,
                scorecard,
                bolabola,

              ],
            )
          ),
        );
  }
}

A: Add scrollDirection: Axis.horizontal to ListView object.
When using horizontal scrollDirection the Container object has to have height specified
The following code is from a project where i had to implement horizontal image carousel:
Container(
        margin: EdgeInsets.only(top: 20.0),
        height: 200.0,
        child: ListView(
          padding: EdgeInsets.all(0.0),
          scrollDirection: Axis.horizontal,
          shrinkWrap: true,
          children: <Widget>[
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisSize: MainAxisSize.min,
              children: _imagesWidget // this is a list containing Cards with image
            )
          ]
        ),
      );


text:
Q: How to increase the location accuracy when the object is moving Actually, I am doing a gps application that will measure the distance between two geopoints while moving. However, when my device is static, there will still be distance calculated as the location changed will update the old and new geopoints, then calculate the distance.
Below is the setting I used in my program:
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);

When locationChanged, it will do update the old and new GeoPoint and calculate the distance.
And, I am using network provider for testing indoor.
Please kindly advice as I really need some helps. Thank you.


text:
Q: Explicit loading with DBContext does not work / does not change value I'll try to update my entity after setting a new FOREIGN KEY value.
My (simplified) entities are:
public class FirstEntity
{
    public Guid Id { get; set; }
    public Guid SecondEntityId {get; set;} // <-- this is the FK
    public virtual SecondEntity SecondEntity { get; set; } // <-- this is the navigation property
}

public class SecondEntity
{
    public Guid Id { get; set;}
    public virtual ICollection<FirstEntity> FirstEntity { get; set; }
}

At some point in my code I want to change the reference for an object of type FirstEntity by setting the FK-value to a new value.
var theFirstEntity = DbContext.FirstEntity.Single(f => f.Id == Guid.Parse("5e27bfd3-d65b-4164-a0e4-93623e1b0de0"));
// at this point theFirstEntity.SecondEntityId is 'e06f8909-98f9-4dc6-92ec-49d9a6aac831'

theFirstEntity.SecondEntityId = Guid.Parse("C5AB5CBA-5CD8-40B7-ABFB-C22F17646D44"); // <-- existing Id from database
// now theFirstEntity.SecondEntityId is 'C5AB5CBA-5CD8-40B7-ABFB-C22F17646D44'
// but the reference theFirstEntity.SecondEntity is still pointing the 'old' entity with id 'e06f8909-98f9-4dc6-92ec-49d9a6aac831'
// but it should have id 'C5AB5CBA-5CD8-40B7-ABFB-C22F17646D44

Now I try to load the new reference explicitly using
DbContext.Entry(FirstEntity).Reference(t => t.SecondEntity).Load();

as found here.
But FirstEntity.SecondEntity stays the same System.Data.Entity.DynamicProxies.SecondEntity_XYZ as it was before.
On the other side, when looking at DbContext.Entry(FirstEntity).Reference(t => t.SecondEntity).Query() and the values of the Parameters property, the query seems to be correct by looking after Id = 'C5AB5CBA-5CD8-40B7-ABFB-C22F17646D44'.
Instead it should containt the correct entity of type SecondEntity with the Id 'C5AB5CBA-5CD8-40B7-ABFB-C22F17646D44' and not the 'old' value.

A: You need to SaveChanges and then explicitly load.
theFirstEntity = myDbContext.FirstEntity.Single(f => f.Id == Guid.Parse("5e27bfd3-d65b-4164-a0e4-93623e1b0de0"));
theFirstEntity.SecondEntityId = Guid.Parse("C5AB5CBA-5CD8-40B7-ABFB-C22F17646D44");

myDbContext.SaveChanges();

DbContext.Entry(theFirstEntity).Reference(t => t.SecondEntity).Load();

But in this case it would be more convenient to just assign a new and already loaded SecondEntity value to the FirstEntity:
var f = myDbContext.Set<FirstEntity>().Include(p => p.SecondEntity)
    .Single(x => x.Id == Guid.Parse("5e27bfd3-d65b-4164-a0e4-93623e1b0de0"));

var s = myDbContext.Set<SecondEntity>()
    .Single(x => x.Id == Guid.Parse("C5AB5CBA-5CD8-40B7-ABFB-C22F17646D44"));

f.SecondEntity = s;

myDbContext.SaveChanges();


text:
Q: fsockopen() is enabled but doesn't work I checked fsockopen using this code and the function is enabled.
<?php
if(function_exists('fsockopen')) {
     echo "fsockopen function is enabled";
}
else {
     echo "fsockopen is not enabled";
}
?>

Below is the code used by the script I need to work with. It is returning error: The fsockopen-function isn't working, error: 110 Connection timed out - FAILED
if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == "on") $url = "https://";
else $url = "http://";
$url .= $HTTP_HOST.$REQUEST_URI;
$querystring = "action=fsockopentest";
if (@strpos($url, "/", 8)) {
    $urlpath = "/".substr($url, strpos($url, "/", 8)+1);
    $urldomain = substr($url, 0, strpos($url, "/", 8));
} else {
    $urlpath = "/";
    $urldomain = $url;
}
$urldomain = str_replace("http://", "", $urldomain);
$postheader = "POST $urlpath HTTP/1.0\r\nHost: $urldomain\r\nContent-Type: application/x-www-form-urlencoded\r\nContent-Length: ".strlen ($querystring)."\r\n\r\n";
$fp = @fsockopen ($urldomain, 80, $errno, $errstr, 10);
$res = "";
if ($fp) {
    fputs ($fp, $postheader.$querystring);
    while (!feof($fp)) $res .= fgets ($fp, 1024);
    fclose ($fp);
}
if (strstr($res,"SUCCESS")) echo "
The fsockopen-function is working - PASSED
";
else echo "
The fsockopen-function isn't working, error: $errno $errstr - FAILED
";

echo "
";

What could be wrong?

A: error: 110 Connection timed out - FAILED

Is a result of the inability of the fsocks function to connect to the server given in the allotted time.
This may be a problem with the URL or you not giving the timeout a lengthy enough time.


text:
Q: Посчитать количество вхождений подстроки в строку У меня есть две переменные: text и text2. Переменной text присваивается та строка, которую вводит пользователь, а text2 присваивается значение строки в самом коде. Нужно посчитать, сколько раз строка text2 входит в строку text.
Вот так выглядят переменные:
String t = reader.readLine();
String t2 = "get out of my swamp";

A: У самого String нет метода count, поэтому используйте самописный:
public static int count(String str, String target) {
    return (str.length() - str.replace(target, "").length()) / target.length();
}

Использование:
// Сколько раз строка t2 встречается в строке t
System.out.println(count(t, t2));

...

String t = "/get out of my swamp/get out of my swamp/";
String t2 = "get out of my swamp";
System.out.println(count(t, t2))
// 2

A: Как один из вариантов тоже может сработать, здесь используются регулярные выражения:
public class Substring {
    public static void main(String[] args) {
        String str = "abcabcabc";
        String substr = "abc";
        Pattern p = Pattern.compile(substr);
        Matcher m = p.matcher(str);
        int counter = 0;
        while (m.find()) {
            counter++;
        }
        str = str.replaceAll("abc", "defg");
        System.out.println(counter);
        System.out.println(str);
    }
}

Либо такой вариант, может, он будет проще, с использованием split:
String symbol = "о";
String text = "Добрый день!";
System.out.println((text + "\0").split(symbol).length - 1);


text:
Q: Hibernate predicate to get children based on parent I have following structure:
@Entity
class Parent {
  @Id
  int id;

  @OneToMany(fetch = FetchType.LAZY)
  List<Child> children;

}

@Entity
public class Child {
  @Id
  int id;

  @ManyToOne
  Parent parent;
}

I want to get children based on a specific parent id. As I want to paginate the result I want to build predicate for children and not just fetch parent and get all the children this way.
So, I imagining predicate like this for the Child query:
builder.equal(root.get("parent.id"), parentId);

But this obviously will not work. So, what is the right way to do it?
Thanks

A: parent.id is not a property name, but a property path. If you read the java doc, you will see that Path#get requires a property name though. So to fix this, use root.get("parent").get("id")


text:
Q: ActiveRecord query: order by a sum on an included model
*

*Project has_many :items

*Item belongs_to :project

I'm trying to get the projects sorted by the total price of their respective items. Something like:
Project.includes(:items).order('SUM(items.price)')

With this code, ActiveRecord returns only the first project. What am I missing?

A: I've not tried the v3 stuff out yet, but I'd assume it would be something like
Product.joins(:items).group('products.id').order('SUM(items.price)')

A: Project.find_by_sql "
  select projects.*
  from projects
  left join (
    select project_id, sum(price) as items_sum
    from items
    group by project_id) as sums on
  project.id = sums.project_id
  order by sums.items_sum

Above SQL should work well on most DB systems (MySQL, PostgreSQL, ...).
AR record includes is mostly used as eager loading solution. And I am not sure if you can use it that way - to order records of parent table.


text:
Q: Properties about $f(n)$ that sums all positive integers that are coprime to $n$ Let $f(n)$ be the function that sums all positive integers that are coprime to $n$. For example, if we take $n=6$, $f(6)=1+5=6$ because $\gcd(1,6)=\gcd(5,6)=1$.
The formula for $f(n)$ is given as $f(n)=n\frac{\phi(n)}{2}$, where $\phi(n)$ denotes the Euler phi function. By this formula and the multiplicativity of $\phi(n)$, we say $f(nm)=2f(n)f(m)$.
My question is, is there a way to obtain $f(nm)=2f(n)f(m)$ without applying $f(n)$'s formula?


text:
Q: Problem with homebrew recipe for ctags I was trying to install ctags using homebrew:
>brew install ctags
==> Downloading http://downloads.sourceforge.net/ctags/ctags-5.8.tar.gz
Already downloaded: /Library/Caches/Homebrew/ctags-5.8.tar.gz
==> Downloading patches

curl: (22) The requested URL returned error: 404
Error: Failure while executing: /usr/bin/curl -f#LA Homebrew\ 0.9.4\ (Ruby\ 1.8.7-358;\ Mac\ OS\ X\ 10.8.5) https://raw.github.com/gist/4010022/8d0697dc87a40e65011e2192439609c17578c5be/ctags.patch -o 000-homebrew.diff

Any idea how I can troubleshoot this?

A: HTTP 404 Error: Not found. This means the URL referenced something that no longer exists at that location. The problem isn't with curl, the problem is with the homebrew recipe for ctags -- it's out of date.
You can see this for yourself by pointing a browser to the patch URL that the homebrew recipe is trying to the URL that curl is trying to download from: https://raw.github.com/gist/4010022/8d0697dc87a40e65011e2192439609c17578c5be/ctags.patch
You get a 404 Not Found error from GitHub.
Try updating your recipes, it's likely the ctags recipe is out of date:
brew update

If that doesn't resolve the problem, report it as an issue for the ctags recipe here: https://github.com/Homebrew/homebrew/issues


text:
Q: javascript constructs to avoid? I have been writing a JS algorithm.  Its blazing fast in chrome and dog slow in FF.  In the chrome profiler, I spend <10% in a method, in FF the same method is 30% of the execution time.  Are there javascript constructs to avoid because they are really slow in one browser or another?
One thing I have noticed is that things like simple variable declaration can be expensive if you do it enough.  I sped up my algorithm noticable by not doing things like
var x = y.x;
dosomthing(x);

and just doing
dosomething(y.x)

for example.

A: As you've found, different things are issues in different implementations. In my experience, barring doing really stupid things, there's not much point worrying about optimizing your JavaScript code to be fast until/unless you run into a specific performance problem when testing on your target browsers. Such simple things as the usual "count down to zero" optimization (for (i = length - 1; i >= 0; --i) instead of for (i = 0; i < length; ++i)) aren't even reliable across implementations. So I tend to stick to writing code that's fairly clear (because I want to be nice to whoever has to maintain it, which is frequently me), and then worry about optimization if and when.
That said, looking through the Google article that tszming linked to in his/her answer reminded me that there are some performance things that I tend to keep in mind when writing code originally. Here's a list (some from that article, some not):

*

*When you're building up a long string out of lots of fragments, surprisingly you usually get better performance if you build up an array of the fragments and then use the Array#join method to create the final string. I do this a lot if I'm building a large HTML snippet that I'll be adding to a page.

*The Crockford private instance variable pattern, though cool and powerful, is expensive. I tend to avoid it.

*with is expensive and easily misunderstood. Avoid it.

*Memory leaks are, of course, expensive eventually. It's fairly easy to create them on browsers when you're interacting with DOM elements. See the article for more detail, but basically, hook up event handlers using a good library like jQuery, Prototype, Closure, etc. (because that's a particularly prone area and the libraries help out), and avoid storing DOM element references on other DOM elements (directly or indirectly) via expando properties.

*If you're building up a significant dynamic display of content in a browser, innerHTML is a LOT faster in most cases than using DOM methods (createElement and appendChild). This is because parsing HTML into their internal structures efficiently is what browsers do, and they do it really fast, using optimized, compiled code writing directly to their internal data structures. In contrast, if you're building a significant tree using the DOM methods, you're using an interpreted (usually) language talking to an abstraction that the browser than has to translate to match its internal structures. I did a few experiments a while back, and the difference was about an order of magnitude (in favor of innerHTML). And of course, if you're building up a big string to assign to innerHTML, see the tip above — best to build up fragments in an array and then use join.

*Cache the results of known-slow operations, but don't overdo it, and only keep things as long as you need them. Keep in mind the cost of retaining a reference vs. the cost of looking it up again.

*I've repeatedly heard people say that accessing vars from a containing scope (globals would be the ultimate example of this, of course, but you can do it with closures in other scopes) is slower than accessing local ones, and certainly that would make sense in a purely interpreted, non-optimized implementation because of the way the scope chain is defined. But I've never actually seen it proved to be a sigificant difference in practice. (Link to simple quick-and-dirty test) Actual globals are special because they're properties of the window object, which is a host object and so a bit different than the anonymous objects used for other levels of scope. But I expect you already avoid globals anyway.
Here's an example of #6. I actually saw this in a question related to Prototype a few weeks back:
for (i = 0; i < $$('.foo').length; ++i) {
    if ($$('.foo')[i].hasClass("bar")) { // I forget what this actually was
        $$('.foo')[i].setStyle({/* ... */});
    }
}

In Prototype, $$ does an expensive thing: It searches through the DOM tree looking for matching elements (in this case, elements with the class "foo"). The code above is searching the DOM three times on each loop: First to check whether the index is in bounds, then when checking whether the element has the class "bar", and then when setting the style.
That's just crazy, and it'll be crazy regardless of what browser it's running on. You clearly want to cache that lookup briefly:
list = $$('.foo');
for (i = 0; i < list.length; ++i) {
    if (list[i].hasClass("bar")) { // I forget what this actually was
        list[i].setStyle({/* ... */});
    }
}

...but taking it further (such as working backward to zero) is pointless, it may be faster on one browser and slower on another.

A: Here you go:
http://code.google.com/intl/zh-TW/speed/articles/optimizing-javascript.html

A: I don't think this is really a performance thing, but something to avoid for sure unless you really know what's happening is:
var a = something.getArrayOfWhatever();
for (var element in a) {
  // aaaa! no!!  please don't do this!!!
}

In other words, using the for ... in construct on arrays should be avoided. Even when iterating through object properties it's tricky.
Also, my favorite thing to avoid is to avoid omission of var when declaring local variables!


text:
Q: Intersection between two lists F# I am looking for a function that takes the intersection between two lists and creates a new list, I have this function: let intersect x y = Set.intersect (Set.ofList x) (Set.ofList y) that do what I ant but I dont want to use any of the inbuilt functions in F#

A: It is best to use the library stuff, but if you can't
If we assume that the input lists are sorted (use List.sort or write your own) :
let rec intersect a b =
    match a with
    |h::t -> match b with
             |h2::t2 ->
                 if h=h2 then h::(intersect t t2)
                 else if h>h2 then intersect t b else intersect a t2
             |[] -> []
    |[] -> []

A: I agree that converting lists to sets is not good in this case.
Here is another alternative that works without conversion to sets but uses the inbuilt Enumerable.Intersect function:
open System.Linq

let intersect (xs:'a seq) (ys: 'a seq) = xs.Intersect(ys)

You can call this function with FSharpList.


text:
Q: How to make Mysql Queries not case-sensitive? I have table which contain [Username, Email] and I'm checking them for non repeating any of them,
but It's case-sensitive , so if there is user that's Username is "SelvsterTP", if other user typed it, he won't be able to register, but if he type "selvstertp" for example, no errors face him! ,
I think of making extra column called 'UsernameCheck' and upload to it Username 'lowercase' , then check on that column (same with Email) ,
but it seems to me not the best code for that situation, so any ideas or suggestions?
Original code
$CheckusernameRow =
RowCountDB("Id","users","Username",$Username); //function
to get rows

My Idea
 $CheckusernameRow =
 RowCountDB("Id","users","UsernameCheck",strtolower($Username));

A: Did you try the LOWER() selector?
$lowerUsername = strtolower($Username);
$query = "SELECT id FROM users WHERE LOWER(Username) LIKE '$lowerUsername'";


text:
Q: How to get join data if using columns? I have two tables, ProductGroup and ProductGroupTranslation which are joined together.
In ProductGroup I have id and in translation table I have title.
Now I want to get all ProductGroups:
$categories = ProductGroup::find(array(
    "product_group_id IS NULL",
    "order" => "id DESC"
) );

This works and I can access translation via $categories->productgrouptranslation->getTitle();
But how do I access joined table if I fetch only columns out:
$categories = ProductGroup::find(array(
   "columns" => "id",
    "product_group_id IS NULL",
    "order" => "id DESC"
) );

A: This is a limitation of the technology you are using. If you specify the columns you want to retrieve data from, then those are the only columns you are going to have access to.
If you are asking "what columns do I need to specify to only get the id and title out of a joined result set", then I suspect the answer is to pass an array of columns into columns with the column name preceded with the table name:
$categories = ProductGroup::find(array(
   "columns" => "ProductGroup.id,ProductGroupTranslation.title",
   "product_group_id IS NULL",
   "order" => "id DESC"
) );

Replace the above table names with the actual table names.


text:
Q: Checkbox to change button actionlistener I'm trying to make in a small program I'm creating that when one checkbox is selected the action performed for a specific button to be changed to another action performed, let's say the button action performed gives the result of 1+2, I want when I check the checkbox to make the button action performed be 1-3 just for example.
Here is my code
import java.awt.*;

public class frame extends JFrame { // Declaring the frame class

public frame() { // crating a constructor
    getContentPane().setLayout(new GridLayout(5,2)); // Creating 5 lines and 2 rows
    // first label for adding the first number
    JLabel label = new JLabel("First Number");
    getContentPane().add(label);
    label.setHorizontalAlignment(SwingConstants.CENTER);
    // first text field
    final JTextField text = new JTextField(8);
    getContentPane().add(text);
    text.setHorizontalAlignment(SwingConstants.CENTER);
    // second label for adding second number
    JLabel label1 = new JLabel("Second Number");
    getContentPane().add(label1);
    label1.setHorizontalAlignment(SwingConstants.CENTER);
    // second text field
    final JTextField text1 = new JTextField();
    getContentPane().add(text1);
    text1.setHorizontalAlignment(SwingConstants.CENTER);
    // third label for the result
    JLabel label2 = new JLabel("Result is");
    getContentPane().add(label2);
    label2.setHorizontalAlignment(SwingConstants.CENTER);
    // third text field to show the result
    final JTextField text2 = new JTextField();
    getContentPane().add(text2);
    text2.setHorizontalAlignment(SwingConstants.CENTER);
    text2.setEditable(false);
    // Calculation button
    JButton btn = new JButton("Calculate");
    btn.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            String number1, number2, result, ans;
            try {
                /*number1 = Double.parseDouble(text.getText());
                number2 = Double.parseDouble(text1.getText());
                result = number1*number2;
                text2.setText(Double.toString(result));*/
                if (text.getText().isEmpty() || text1.getText().isEmpty()) {
                    throw new Exception();
                }

                number1 = text.getText();
                number2 = text1.getText();
                result = number1.concat(number2);
                text2.toString();
                text2.setText(result);

            } catch (Exception e1) {
                JOptionPane.showMessageDialog(null, "Please add a letter");
            }
        }
    });
    getContentPane().add(btn);
    // Clear button
    JButton clear = new JButton("Clear");
    getContentPane().add(clear);

    final JCheckBox chckbxNewCheckBox = new JCheckBox("New check box");
    getContentPane().add(chckbxNewCheckBox);

    final JCheckBox chckbxNewCheckBox_1 = new JCheckBox("New check box");
    getContentPane().add(chckbxNewCheckBox_1);

    chckbxNewCheckBox.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (chckbxNewCheckBox.isSelected()) {
                chckbxNewCheckBox_1.setSelected(false);
            }
        }
    });

    chckbxNewCheckBox_1.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (chckbxNewCheckBox_1.isSelected()) {
                chckbxNewCheckBox.setSelected(false);
            }
        }
    });

    clear.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                text.setText("");
                text1.setText("");
                text2.setText("");
            } catch(Exception e1) {
            }
        }
    });

    //setVisible(true);
    //setSize(400,200);
    //setResizable(false);
    //setLocationRelativeTo(null);
    //setTitle("Calculator");
}

public static void main (String args[]) { // Creating the main method
    frame frame = new frame(); // creating an object of the ShowGridLayout class, object is frame.
    frame.setVisible(true);
    frame.setSize(400, 200);
    frame.setResizable(false);
    frame.setLocationRelativeTo(null);
    frame.setTitle("Calculator");
    frame.setDefaultCloseOperation(EXIT_ON_CLOSE);;
}

}

A: It can be solved in multiple ways.

*

*You can have a integer field (member variable or static) and update it's value on selection of different check boxes. Define different method for each kind of action you want to perform and call them in button action listener by looking at the value of the static integer.

OR

*Keep a reference to the ActionListener added to the button and on selection of the checkbox remove existing action listener from button and add the new one and update the reference to new listener.

I hope it helps.
EDIT 1 : it's better to use radio buttons if you just want to have one selection at a time.
Edit 2:
Here it is how you can do it using radio buttons and by removing and adding listener.
    public class frame extends JFrame { // Declaring the frame class
        final JTextField text;
        final JTextField text1;
        final JTextField text2;

        public frame() { // crating a constructor
            getContentPane().setLayout(new GridLayout(5, 2)); // Creating 5 lines and 2 rows
            // first label for adding the first number
            JLabel label = new JLabel("First Number");
            getContentPane().add(label);
            label.setHorizontalAlignment(SwingConstants.CENTER);
            // first text field
            text = new JTextField(8);
            getContentPane().add(text);
            text.setHorizontalAlignment(SwingConstants.CENTER);
            // second label for adding second number
            JLabel label1 = new JLabel("Second Number");
            getContentPane().add(label1);
            label1.setHorizontalAlignment(SwingConstants.CENTER);
            // second text field
            text1 = new JTextField();
            getContentPane().add(text1);
            text1.setHorizontalAlignment(SwingConstants.CENTER);
            // third label for the result
            JLabel label2 = new JLabel("Result is");
            getContentPane().add(label2);
            label2.setHorizontalAlignment(SwingConstants.CENTER);
            // third text field to show the result
            text2 = new JTextField();
            getContentPane().add(text2);
            text2.setHorizontalAlignment(SwingConstants.CENTER);
            text2.setEditable(false);

            final AddValuesActionListener actionListener = new AddValuesActionListener();
            // Calculation button
            final JButton btn = new JButton("Calculate");
            btn.addActionListener(actionListener);

            final JRadioButton addRadioButton = new JRadioButton("Add", true);
            addRadioButton.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    btn.removeActionListener(actionListener);
                    btn.addActionListener(new AddValuesActionListener());
                }
            });

            final JRadioButton subtractRadioButton = new JRadioButton("Subtract", true);
            subtractRadioButton.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    btn.removeActionListener(actionListener);
                    btn.addActionListener(new SubtractValuesActionListener());
                }
            });

            getContentPane().add(btn);
            // Clear button
            JButton clear = new JButton("Clear");
            getContentPane().add(clear);

            ButtonGroup radioButtons = new ButtonGroup();
            radioButtons.add(addRadioButton);
            radioButtons.add(subtractRadioButton);
            getContentPane().add(addRadioButton);
            getContentPane().add(subtractRadioButton);
        }

        public static void main(String args[]) { // Creating the main method
            frame frame = new frame(); // creating an object of the ShowGridLayout class, object is frame.
            frame.setVisible(true);
            frame.setSize(400, 200);
            frame.setResizable(false);
            frame.setLocationRelativeTo(null);
            frame.setTitle("Calculator");
            frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
            ;
        }

        private class AddValuesActionListener implements ActionListener {
            public void actionPerformed(ActionEvent e) {
                text2.setText(text.getText() + "+" + text1.getText());  //Create add values method
            }
        }

        private class SubtractValuesActionListener implements ActionListener {
            public void actionPerformed(ActionEvent e) {
                text2.setText(text.getText() + "-" + text1.getText());  //Create add values method
            }
        }
    }

And here is how you could simply do by checking radio button selection as suggested by @JeriesHG
    public class frame extends JFrame { // Declaring the frame class
        final JTextField text;
        final JTextField text1;
        final JTextField text2;

        public frame() { // crating a constructor
            getContentPane().setLayout(new GridLayout(5, 2)); // Creating 5 lines and 2 rows
            // first label for adding the first number
            JLabel label = new JLabel("First Number");
            getContentPane().add(label);
            label.setHorizontalAlignment(SwingConstants.CENTER);
            // first text field
            text = new JTextField(8);
            getContentPane().add(text);
            text.setHorizontalAlignment(SwingConstants.CENTER);
            // second label for adding second number
            JLabel label1 = new JLabel("Second Number");
            getContentPane().add(label1);
            label1.setHorizontalAlignment(SwingConstants.CENTER);
            // second text field
            text1 = new JTextField();
            getContentPane().add(text1);
            text1.setHorizontalAlignment(SwingConstants.CENTER);
            // third label for the result
            JLabel label2 = new JLabel("Result is");
            getContentPane().add(label2);
            label2.setHorizontalAlignment(SwingConstants.CENTER);
            // third text field to show the result
            text2 = new JTextField();
            getContentPane().add(text2);
            text2.setHorizontalAlignment(SwingConstants.CENTER);
            text2.setEditable(false);

            final JRadioButton addRadioButton = new JRadioButton("Add", true);
            final JRadioButton subtractRadioButton = new JRadioButton("Subtract", true);

            // Calculation button
            final JButton btn = new JButton("Calculate");
            btn.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                  if (addRadioButton.isSelected()) {
                      text2.setText(text.getText() + "+" + text1.getText());  //Create add values method
                  }     else if (subtractRadioButton.isSelected()) {
                      text2.setText(text.getText() + "-" + text1.getText());  //Create subtract values method
                  }
                }
            });

            getContentPane().add(btn);
            // Clear button
            JButton clear = new JButton("Clear");
            getContentPane().add(clear);

            ButtonGroup radioButtons = new ButtonGroup();
            radioButtons.add(addRadioButton);
            radioButtons.add(subtractRadioButton);
            getContentPane().add(addRadioButton);
            getContentPane().add(subtractRadioButton);
        }

        public static void main(String args[]) { // Creating the main method
            frame frame = new frame(); // creating an object of the ShowGridLayout class, object is frame.
            frame.setVisible(true);
            frame.setSize(400, 200);
            frame.setResizable(false);
            frame.setLocationRelativeTo(null);
            frame.setTitle("Calculator");
            frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
            ;
        }

    }

A: Let me see if I understand completely, the action of a button depends in a checkbox? If this is correct, then you could have a boolean for the checkbox value or just check the "isSelected" function and in the action performed method, I would just do a boolean check and execute the method I need.
JButton btn = new JButton("Calculate");
btn.addActionListener(new ActionListener() {
 if(chckbxNewCheckBox.isSelected()){
  //do something here
 }else{
  //do this
 }
}

EDIT:
I would also have the "action performed" of a button in a separated method, in order to re-use the code. (in the case I require to use this same method in another button or something like this).


text:
Q: Help with $\sum_{w=0}^{n} {n \choose w}(q-1)^w=q^n$ This comes from coding theory by Freudenberger et al. p33
$\sum_{w=0}^{n} {n \choose w}(q-1)^w=q^n$
So my start:
$$\sum_{w=0}^{n} {n \choose w}\sum_{x=0}^{w}{w\choose x}(q)^x(-1)^{w-x}$$
now the first term could cancel 1 term from the inner sum using $\binom{n}{a}\binom{n-a}{b-a} = \binom{n}{b}\binom{b}{a}$ but I'm not sure this helps with the all the other terms. What's the quick solution that I don't see?

A: Hint
You have that
$$q^n=((q-1)+1)^n.$$


text:
Q: cakephp paginate model with multiple association I have three tables : Units, Offers and Agents with following associations

*

*Unit hasMany Offers

*Offer belongsTo Agent

When I paginate Unit table I get all the units and all the corresponding Offers for each unit , but not the Agent that offer belongs to. Ex:
- Unit1
  - offer1
  - offer2
- Unit2
  - offer1
  - offer2
  - offer3

And I want to have something like this:
- Unit1
  - offer1
    - agent1
  - offer2
    - agent2
- Unit2
  - offer1
    - agent1
  - offer2
    - agent2
  - offer3
    - agent3

How to do it?

A: The easiest solution is to increase the recursive of the Model before calling the paginage.
$this->Unit->recursive = 1; //or more

But you should be very careful, because you could call the same Model twice. Extra advice here: Try to unbind Unnecessary models before using this. Again - be very careful, because this could slowdown the app.

A: Using the Containable behaviour should get you there. I never use recursive now.
Alternatively, it can sometimes be helpful to create a database view across the tables of interest. This will make paging a lot simpler and will allow you to specify exactly what data you require (avoiding unnecessary data transfer).


text:
Q: Change color of shiny sliderInput with range I'd like to change the color of my shiny app sliders using css. It all works fine when I apply the suggestion of the this answer:
Changing the color of the sliderInput in Shiny walkthrough
However, as soon as I change the slider to two values with value=range(x,y), the color of both sliders doesn't change anymore.
Here is a minimal example:
   library(shiny)
   ui<-shinyUI(fluidPage(
   theme = "bootstrap.css",
   navbarPage("",
   tabPanel("Diagramm",
   headerPanel("Sliders"),
   sidebarPanel(
   sliderInput("decimal", "Decimal:",
   min = 0, max = 1, value=range(0.1,0.9),step= 0.1)
   ),
   mainPanel(
   tableOutput("values")
   )
   ))
   ))

   server<-shinyServer(function(input, output) {
  })
shinyApp(ui = ui, server = server)

and the bootstrap.css (located in www folder) is
.js-irs-0 .irs-bar {
border-top-color: #d01010;
border-bottom-color: #d01010;
}

.js-irs-0 .irs-bar-edge {
border-color: #d01010;
}

.js-irs-0 .irs-single, .js-irs-0 .irs-bar-edge, .js-irs-0 .irs-bar {
background: #a00;
}

The output gives
output, but I want the blue sliders also to be in purple.
Does anyone know how to change the color of both sliders when using a range?
Thanks.

A: You want the following added in as well:
.js-irs-0 .irs-to,.js-irs-0 .irs-from


text:
Q: How to make Windows Timer running in background thread Question : How do you make a timer tick in the background? That is the thread that create the timer thread can still do something else while clock is ticking.
Attempt:
-Using _beginthreadex() --> It seems to have race condition
class Timer{
 ...
 static unsigned __stdcall tick(void *param){
    while(1){
        Timer::timer++;
        Sleep(Timer::timer*1000);
    }
    return 1;
}
}

.....
HANDLE time_thread = (HANDLE) _beginthreadex(0, 0, &Timer::tick,0,0,NULL);
...
//test for 20 seconds
//want to do something while the clock is not 20 seconds
//the mainthread here still has to receive input
//What is the proper way to do it?

while (Timer::getTime() != 20){
   cout << Timer::getTime()
}

CloseHandle(time_thread);
...

NOTE: Iam using Visual Studio 2008, not 11 so I do not have C++11 support.

A: I'm not sure what's wrong with what you have here.  You've created a thread that updates a member variable timer forever and your main use of it is a tight/fast loop that prints (presumably) that time until it reaches 20.  What is it not doing?  Technically there's a race condition of incrementing that value versus checking it in another thread, but for the purposes of this example it should be fine...
EDIT:  try this for non-blocking input with full input control:
HANDLE hStdIn = GetStdHandle( STD_INPUT_HANDLE );
while ( true ) {
    if ( WAIT_OBJECT_0 == WaitForSingleObject( hStdIn, 1000 ) ) {
        // read input
        INPUT_RECORD inputRecord;
        DWORD events;
        if ( ReadConsoleInput( hStdIn, &inputRecord, 1, &events ) ) {
            if ( inputRecord.EventType == KEY_EVENT ) {
                printf( "got char %c %s\n",
                    inputRecord.Event.KeyEvent.uChar.AsciiChar,
                    inputRecord.Event.KeyEvent.bKeyDown ? "down" : "up" );
            }
        }
    }
    printf( "update clock\n" );
}

A: I'm afraid you've misunderstood how the system timers work and how to use them - the whole point is that they automatically run in the background, so you don't have to do your own thread management.
This has examples and explanations of Windows timers in general, and you can use it if you're trying to roll your own Timer class: Timers Tutorial
This is the Timer class that comes with Windows.NET, with a code example at the bottom: Timer Class
Edited to add:
Here's a version of the Win32 timer example (from the turorial page) adapted for a non-MFC app:
int nTimerID;

void Begin(HWND hWindow_who_gets_the_tick)
{
    // create the timer to alert your window:
    nTimerID = SetTimer(hWindow_who_gets_the_tick, uElapse, NULL);
}

void Stop()
{
    // destroy the timer
    KillTimer(nTimerID);
}

See MSDN: Timer functions for details.
Then inside your window procedure, you get the WM_TIMER message and respond as you like.
Alternatively, the timer can call a user-defined procedure. See SetTimer function for details.


text:
Q: What would happen if an incredibly high energy photon passed through a human body? What would happen if an incredibly high energy photon passed through a human body (or any other material)?  When I say incredibly high energy photon, I mean higher than any known energy scales... higher than electronic energy scales, higher than nuclear transition energies, etc...
In my mind, I pictured the photon tearing apart whatever it passed through.  However, browsing Wikipedia's article on the Photoelectric Effect, I noticed that the cross section went as $1/E^p$, where I think $E$ is energy and $p$ is some number.  So, the probability of an atom being ionized by a high energy photon actually drops with the photon energy (although I don't know what approximations went into this calculation... first order perturbation theory?).  If the other light-matter interaction processes also have cross sections of the form $1/E^p$, then an incredibly high energy photon would pass through us without harming us!
Or maybe this question is unanswerable because we don't yet understand physics at such high energy scales.  What are your thoughts on this?  What do you think would happen if an incredibly high energy photon passed through a human body?

A: Thinking about the basic types of ionising radiation, we have alpha particles, beta particles and gamma rays: the alpha/beta are far more ionising, but a lot less penetrating - whereas the gamma (high energy photons) can easily pass through most materials. Along with UV and X-Rays, Gamma radiation is just at a higher frequency and energy (which is what this photon would be). Even for Ultra-high-energy gamma rays, the highest detected is only about 0.16J (a LOT for a photon, but compared to the whole human body not huge). If it hit something it would probably cause damage, but it's very small. Beyond that, it is very theoretical - however this question might be of interest, basing a (very) small wavelength for a photon on the Planck length: What is the minimum wavelength of electromagnetic radiation?

A: As far as i can see, the high energy of the photon (if we depict that itl only be given out or seen as its KE) will simply pass through us
the apparently small size that it has, itl be like shooting a bullet through a football net (a not-to-scale example) even if it passes through us, itl pass through the sub-atomic particles and the ones that itl hit, itl simply lose its energy to them probably pushing them off course a little (seeing how high the energy you stated it has) but the momentum will be fairly less owing to its negligible mass, so in conclusion itl either pass through us or even if it does hit any part of us it will just be an elastic collision with fair amounts of energy loss off the photon and at the end it just might not even be able to pass through
, but if it does, itl lose most of its KE and because of its small size if it doesnt encounter any much of the atomic particles itl pass through us with nearly the same KE as before with just about no damage to us


text:
Q: IIS changing website physical location does nothing I'm updating a .net app, and in IIS Manager running on an Azure Windows Server VM.
I changed the physical path of my site to a new folder (renaming the old folder).
However, after restarting the page / app pool / IIS / server, the old site is still being served.
Even stopping the application doesn't bring it down.  What do I need to do to make the new version of the site "take?"

A: Thanks to everyone who thought about this question.
I had a few problems, actually:

*

*CSS Isolation broke the Release version but not the Debug version on the local machine (I'm not sure why).  This is probably something that happened in not updating from .net 5 to .net 6 properly.  I've removed CSS isolation for now, and made a clean upgrade to .net 7, and the site is running great.

*I was running my Blazor site as an app in my old WebForms site, but also had the app listed as a separate site, and they were pointed at different folders.

*For SOME reason, the security certificates for the site got reset, leading to a total failure to connect (this took me a LONG time to find, because I never manually deselected the certificates, and it just timed out instead of throwing a no-certificate warning).
Finding the problem was really painful, tbh.  It was only after inspecting the live site / release and debug versions carefully and noticing differences in the [idlabel] markups that I realized the problem.


text:
Q: Show that the solution to the Neumann problem is $u(x,y)=c+\frac{1}{2\pi}\int_{-\infty}^{\infty}{f(\xi)\ln[y^2+(x-\xi)^2]} d\xi$ Show that the solution to the following Neumann problem
\begin{cases}
u_{xx} + u_{yy} =0 \hspace{0.5cm} -\infty <x<\infty, y>0\\
u_{y}(x,0) = f(x), \hspace{0.5cm} -\infty <x<\infty\\
u(x,y)\hspace{0.3cm} \text{and}\hspace{0.3cm}u_{y}(x,y) \to 0 \hspace{0.3cm}\text{as}\hspace{0.3cm} (x^2 + y^) \to \infty
\end{cases}
where the function $f$ is piecewise smooth and absolutely integrable in $(-\infty , \infty)$ , can be written as $$u(x,y) = c + \frac{1}{2\pi}\int_{-\infty}^{\infty}{f(\xi)\ln[y^2 + (x-\xi)^2]} d\xi$$ where $c$ is an arbitrary constant.
My attempt:
Applying Fourier transform on the variable $x$ to the PDE $u_{xx}+u_{yy} =0$ and using the property of linearity, we have
$$\mathcal{F}[u_{xx}] + \mathcal{F}[u_{yy}] =0$$
it follows that
$$\frac{d^2}{dy^2}\hat{u} - \xi^2 \hat{u} =0$$
We then have the problem of ODE
\begin{cases}
\frac{d^2}{dy^2}\hat{u} - \xi^2 \hat{u} =0\\
\frac{d}{dy}\hat{u}(\xi,0) = \hat{f}(\xi)
\end{cases}
The general solution to this problem is
$$\hat{u}(\xi,y) = A(\xi)e^{\xi y} + B(\xi)e^{-\xi y}$$
Since $u$ is bounded when $y \to \infty$, its transform must be bounded when $y \to \infty$. This implies that $A(\xi) = 0$ for $\xi> 0$. If $\xi <0$ then $B(\xi) = 0$. So $$ \hat{u}(\xi,y) = Ke^{-|\xi| y} \hspace{0.3cm} \text{where $K$ is a constant}$$ Then
$$\frac{d}{dy}\hat{u}(\xi,y) = -K|\xi|e^{-|\xi|y}$$
$$\Rightarrow \frac{d}{dy}\hat{u}(\xi,0) = -K|\xi| = \hat{f}(\xi) \Rightarrow K = -\frac{\hat{f}(\xi)}{|\xi|}$$
$$\therefore \hat{u}(\xi,y) = -\frac{\hat{f}(\xi)}{|\xi|}e^{-|\xi|y} = -\frac{1}{\sqrt{2\pi}}\int_{-\infty}^{\infty}{\frac{f(x)e^{-|\xi|y}e^{-i\xi x}}{|\xi|}}dx$$
Now, applying inverse transform to both sides, we have
\begin{align}
u(x,y) &= \frac{1}{\sqrt{2 \pi}}\int_{-\infty}^{\infty}{\left[- \frac{1}{\sqrt{2\pi}}\int_{-\infty}^{\infty}{\frac{f(\tau)e^{-|\xi|y}e^{-i\xi \tau}}{|\xi|}}d\tau  \right]e^{i\xi x}}d\xi\\ &= \frac{1}{2\pi}\int_{-\infty}^{\infty}{f(\tau)}\int_{-\infty}^{\infty}{\frac{-e^{\left(\xi \left[i(x-\tau)\right]-|\xi|y\right)}}{|\xi|}}d\xi d\tau
\end{align}
However, I have not been able to obtain the expression mentioned in the statement. How can I get that? Have I made a mistake? Any help is appreciated


text:
Q: Every time I try to install Ruby 3.1.2 via Ubuntu for WSL, my computer crashes Every time I try to install Ruby 3.1.2 using RBENV and the Ubuntu app for windows, my computer crashes.  When I look carefully, it appears to be some type of 'kernel error'.  What's going on?

A: You need to do a kernel update to WSL.
You can do it here: https://aka.ms/wsl2kernel
Go to the link above and then click that link you see in the photo below.  It will download the package and update the kernel files.
https://gyazo.com/c4a11557da1a77bd694eb8db778bb7e7
Then, make sure your system is set to WSL2 (just keep following the instructions).
If you run into other errors, here are some other helpful links:
https://learn.microsoft.com/en-us/windows/wsl/install-manual#step-4---download-the-linux-kernel-update-package
https://learn.microsoft.com/en-us/windows/wsl/install
https://askubuntu.com/questions/1417663/error-installing-ubuntu-22-04-on-wsl
https://gorails.com/setup/windows/10


text:
Q: WPF performance issue when trying to update listbox real-time based on user input I'm new in Windows Phone development and i'm trying to develop a dictionary app.
I have a textbox to allow user input the word and a listbox to show all words which match the user input in real-time, so I'm used the textchanged event as below:
private void searchTextBox_TextChanged(object sender, TextChangedEventArgs e)
    {
            wordNeedToDefine = searchTextBox.Text;
            if (!(wordNeedToDefine == null || wordNeedToDefine.Equals("")))
            {
                var items = (from words in wordAndIndexList where words[0].StartsWith(wordNeedToDefine) select words[0]);
            }
            this.Dispatcher.BeginInvoke(() =>
            {
                wordsListBox.ItemsSource = items;
            });
    }

Everything is working fine but there are issues about performance, it's laggy when user input the text and listbox update the items.
Can someone tell me what i need to do to increase the performance. I'm also trying the AutoCompleteBox but it's have same problem.
Thanks in advance.

A: You'll get better performance if you use a CollectionViewSource to do the filtering and the more characters you have to filter will make it faster. i.e. Only start filtering once the user has entered at least 3 characters.


text:
Q: Is every simplicial map $\Phi:K(A, n) \to K(A', n)$ a simplicial homomorphism of groups? I have posted a few questions on MSE, most notably this one, which revolve around the same issue and have received no answers, so I decided to ask the same here.
In the following, $K(A, n)$ is the minimal Eilenberg-MacLane Kan complex given by $$K(A, n)_q=\{\text{normalized $n$-cocycles } \Delta^q \to A\}.$$ This is constructed via the Dold-Kan correspondence, which applies to show that $\mathsf{sAb}(K(A, n), K(A', n))
\cong \mathsf{Ab}(A, A')$. In light of proving the existence of an isomorphism $\mathsf{sSet}(K(A, n), K(A', n))\cong \mathsf{Ab}(A, A')$, the following issue arises.
Is every simplicial map $\Phi:K(A, n) \to K(A', n)$ a simplicial homomorphism of groups? May in his book Simplicial objects in Algebraic Topology, Lemma 25.1, claims that the answer is positive and I know no other reference for this result. The proof is by induction: in degrees $q<n$, $K(A, n)_q=\{\ast\}=K(A', n)_q$ and there is nothing to prove. By minimality, $K(A, n)_n=\pi_n(K(A, n))$ and $\pi_n(\Phi)=\Phi_n$, hence $\Phi_n$ is a homomorphism. Now come the problems: suppose for $q\ge n+1$ that we have proven that $\Phi_{q-1}$ is homomorphism. Consider $\Phi_q(x+y)$ and $\Phi_q(x)+ \Phi_q(y)$. These two elements of $K(A', n)$ have the same boundary by the induction hypothesis. May concludes that they are homotopic. Why this? We know that $\pi_q(K(A', n)\cong 0$, but $\Phi_q(x+y)$ and $\Phi_q(x)+ \Phi_q(y)$ need not determine elements of $\pi_q(Y)$, since there is no reason why their boundary should be constant at the base-point. If we accept that they are homotopic relative their boundary, then they are equal by minimality and the argument is concluded. I don't want to sound skeptical about May's proof, but I am not convinced, and I even don't know if the result itself is true.
Why I doubt this is true:

*

*It is well-known that $[K(A, n), K(A', n)]\cong H^n(K(A, n), A')\cong \mathsf{Ab}(A, A')$. If the isomorphism above holds true, then we get an isomorphism $[K(A, n), K(A', n)] \cong \mathsf{sSet}(K(A, n), K(A', n))$. (And this groups can be finite.) Using the explicit form of the involved isomorphisms, this essentially says that two homotopic maps $K(A, n) \to K(A', n)$ are equal, which I highly doubt to be true, even using minimality of the codomain.

*The only other place I know in literature where something similar is
treated is a book (in German) by Lamotke, Semisimpliziale
Algebraische Topologie. In Theorem (Satz) VIII.3.11, he proves that
every simplicial map $K(A, n) \to K(A', n)$ is homotopic to a
homomorphism and every two homotopic homomorphisms are equal. Although this
does not rule out the possibility that every simplicial map $K(A, n)
   \to K(A', n)$ be a homomorphism on the nose, if this is true, why not
saying it?

So, my question boils down to: is this fact true, and if yes, why?
[Edit: I have now removed the question on MSE.]

A: Denote by $$\def\U{{\sf U}}\def\sSet{{\sf sSet}}\def\sAb{{\sf sAb}}\def\Ch{{\sf Ch}}\def\N{{\sf N}}\U\colon \sAb→\sSet$$ the forgetful functor,
which is the right adjoint of $$\def\Z{{\bf Z}}\Z\colon\sSet→\sAb$$
and by $$Γ\colon \Ch→\sAb$$ the Dold–Kan functor given by the right adjoint of the normalized chains functor $$\N\colon\sAb→\Ch.$$
Thus $$\def\K{{\sf K}}\K(A,n)=\U Γ(A[n]).$$
We have a chain of isomorphisms of sets
$$\sSet(\K(A,n),\K(A',n))≅\sSet(\U Γ A[n], \U Γ A'[n])≅\Ch(\N\Z\U Γ A[n],A'[n])$$
(by adjunctions $\Z⊣\U$, $\N⊣Γ$),
$$\def\Hom{\mathop{\sf Hom}}\def\H{{\sf H}}\Ch(\N\Z\U Γ A[n],A'[n])≅\Hom(\H_n(\N\Z\U Γ A[n]),A')$$
(since both chain complexes vanish below degree $n$),
and if $n>0$, we have
$$\Hom(\H_n(\N\Z\U Γ A[n]),A')≅\Hom(A,A')$$
(by the Hurewicz theorem).
This proves the desired isomorphism
$$\sSet(\K(A,n),\K(A',n))≅\Hom(A,A').$$
(If $n=0$, then $\Hom$ refers to maps of sets, not groups.)
The same argument also proves that
$$\sSet(\K(A,m),\K(A',n))≅0$$
(i.e., the only simplicial map factors through the basepoint) if $m>n>0$.
If $m<n$, then the Hurewicz theorem is not applicable, and in this case we have nontrivial cohomology operations.


text:
Q: How effective is Wikipedia for first line of attack? I am learning some pretty disconnected concepts of mathematics for a project I am working on. I was reading about matrices and suddenly had to know about Markov Chains and that lead me to read about Multivariate Expectations and so on.
I was initially spending time in the library with the main book and everytime I encountered a problem, I'd go looking for a book which I thought would explain it, read it and return to the main one. Just as an experiment, I tried using Wikipedia to understand the concepts and then did google searches with 'site:.edu' references to look for coursenotes and then browsed through some of those till I felt comfortable and went back to main book.
For mathematics, is Wikipedia a good first line of attack?

A: I use it sometimes as a first choice.  Other times I start with Google and the first hit will be a Wikipedia page.  My experience is mainly with statistics and probability but I sometimes also use it for other topics.  My children were taught in school to never use wikipedia as a direct reference in their reports.  The issue to keep in mind is that there is free access to publish in Wikipedia and so many items may not be thoroughly check for validity.  But my experience as a professional statistician is that most articles are statistical topics were posted or edited by trained professionals and the article are very accurate to the point and informative.  They also avoid specialized jargon that the public is unaware of.  Most article site reputable reference sources.  After you read the Wikipedia article you should check out some of these references and make sure that the authors of the Wikipedia article have said things that are consistent with reputable sources.
Sometimes when answering questions on this site and CV I go to Wikipedia to refresh my memory on a topic or to provide a formula I forgot how to produce exactly.

A: Wikipedia has to  be taken with some grain of salt. Most of the mathematics is correct, but even then you might get concepts in a form that are either too general or not general enough. Wikipedia is a useful starting point for looking something up, provided you already have a solid foundation and the means to look something up in an actual library.
But in order to get the foundations, I would suggest that you use actual books or lecture notes that are at your level. You might look something up from time to time to fill small gaps, but there is a logical structure to mathematics that needs to be followed. You use results to prove further results and to actually understand them all, you have to start at the beginning.
I think that if you read about matrices and need to know about Markov chains first, your book on matrices is likely to be too advanced for you.


text:
Q: accessing entries in a list I am trying to find optimal combinations (pairings) of players for a golf hobby project. I have as many as 40 players that need to be grouped into unique combinations of 4 players. The number of unique solutions is astronomical - something like 4^40th/10! (factorial). That is not a problem I can solve on a pc in a reasonable period of time
Instead I am using what I have been told is a greedy algorithm - I look for optimal results (pairs that have played the least previously) for the best twosome, throw away the higher scoring results, then re-pair the best twosome solutions with all of the twosome pairs, re-score and find the best solutions available. This approach results in a manageable number of possibilities. While I may miss the optimal solution, I will find very good answers.
When I use the combinations routine from itertools the first time I get answers in pairs in a list array [(1,2),(3,4)...etc. When I generate combinations from that list I get a result that looks like [[((1, 2), (1, 3)), ((1, 2), (1, 4)), etc. Since I need to eliminate duplicates (in the first item shown, player 1 appears twice) I need to be able to examine each component of the foursome (sorry if my terminology is off - self taught) and I don't know how to do that. So specifically, in the first entry in my list called foursome_list, how would I refer to each of the four positions (first entry = ((1,2),(1,3)) ). Thanks in advance for any help you can provide. Here is my sample code (proof of concept with only 8 players to keep the numbers down for now).
Thanks in advance
from itertools import combinations

players  = [1,2,3,4]

pairs = combinations(players,2)

pairs_list = []
for i in list(pairs):
    pairs_list.append(i)

print("Pairs list =", pairs_list)

foursome = combinations(pairs_list,2)

foursome_list=[]
for i in list(foursome):
    foursome_list.append(i)

print ("Foursome list =", foursome_list)
print("length =", len(foursome_list))
print(foursome_list[0][0])
print(foursome_list[0][1])


text:
Q: Serialize object using specific type I am using Jsonserializer.SerializeObject trying to convert a byte[] into a specific object.
The class structure of message is following:
public class ProjectMessageQueueMessage
{
    public ProjectMessageQueueMessage();
    public byte[] MessageData { get; set; }
    public string MessageID { get; set; }
    public string MessageType { get; set; }
}

And when I try and serialize it into a specific class, like so
byte[] output = JsonSerializer.SerializeObject<ExtendedScanMessage>(message.MessageData);

I get the following error:

Cannot convert from byte[] to ExtendedScanMessage

I can remove the type, like so:
byte[] output = JsonSerializer.SerializeObject(message.MessageData);

But then output will not be serialized to my class.
Am I missing something?

A: depending on encoding you use you should write something like in code below
var outputString = Encoding.Default.GetString(message.MessageData);
var output = JsonConvert.DeserializeObject<ExtendedScanMessage>(outputString);

depending on your encoding you may use some of folowing:
Encoding.Default Encoding.ASCII Encoding.BigEndianUnicode Encoding.UTF32 Encoding.UTF7 Encoding.UTF8 Encoding.Unicode