text:
Q: org.springframework.security.authentication.InternalAuthenticationServiceException: while authenticate user with oracle db Dears,
I am trying to authenticate user with oracle db.
This is my security context spring 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:security="http://www.springframework.org/schema/security"
    xmlns:jee="http://www.springframework.org/schema/jee"
    xsi:schemaLocation="http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-5.2.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.3.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

      <security:authentication-manager>
        <security:authentication-provider>
            <security:jdbc-user-service data-source-ref="dataSource"
                users-by-username-query="select user_name username, password,   'true' enabled from USERS  where user_name=?"
                authorities-by-username-query="select u.user_name username, ur.authority from USERS u, USERS_ROLES ur where u.user_id = ur.user_id and u.user_name = ?"/>
            <security:password-encoder ref="passwordEncoder" />
        </security:authentication-provider>
      </security:authentication-manager>

    <security:http use-expressions="true">
        <security:intercept-url pattern="/CreateOffer" access="isAuthenticated()"  />
        <security:intercept-url pattern="/docreate" access="isAuthenticated()" />
        <security:intercept-url pattern="/static/**" access="permitAll" />
        <security:intercept-url pattern="/" access="permitAll" />
        <security:intercept-url pattern="/newaccount" access="permitAll" />
        <security:intercept-url pattern="/createaccount" access="permitAll" />
        <security:intercept-url pattern="/createaccountvalidation" access="permitAll" />
        <security:intercept-url pattern="/login" access="permitAll" />
        <security:intercept-url pattern="/ShowOffer" access="permitAll" />
        <security:intercept-url pattern="/**" access="denyAll" />
        <security:form-login login-page="/login"
            login-processing-url="/login" username-parameter="custom_username"
            password-parameter="custom_password"
            authentication-failure-url="/login?error=true" />
    </security:http>

    <jee:jndi-lookup jndi-name="jdbc/myoracle"
        id="dataSource" expected-type="javax.sql.DataSource">
    </jee:jndi-lookup>

    <bean id="passwordEncoder"
        class="org.springframework.security.crypto.password.NoOpPasswordEncoder">
    </bean>
</beans>

User:
Name      Null? Type
--------- ----- -------------
USER_ID         NUMBER(10)
USER_NAME       VARCHAR2(50)
PASSWORD        VARCHAR2(100)
ENABLED         CHAR(1)
EMAIL           VARCHAR2(50)

Users_roles:
Name         Null? Type
------------ ----- ------------
USER_ROLE_ID       NUMBER
USER_ID            NUMBER
AUTHORITY          VARCHAR2(45)

I believe error is coming because it is not able to convert char ( enabled column) to boolean. I have checked but couldn't find any solution. Even I have hardcorded 'true' as the value for enabled but still it is not working.
Caused by: java.sql.SQLException: Fail to convert to internal representation
    at oracle.jdbc.driver.CharCommonAccessor.getBoolean(CharCommonAccessor.java:185)

Complete Error message:
 Aug 23, 2020 12:09:12 PM org.apache.catalina.startup.VersionLoggerListener log
    INFO: Server version name:   Apache Tomcat/9.0.37
    Aug 23, 2020 12:09:12 PM org.apache.catalina.startup.VersionLoggerListener log
    INFO: Server built:          Jun 30 2020 20:09:49 UTC
    Aug 23, 2020 12:09:12 PM org.apache.catalina.startup.VersionLoggerListener log
    INFO: Server version number: 9.0.37.0
    Aug 23, 2020 12:09:12 PM org.apache.catalina.startup.VersionLoggerListener log
    INFO: OS Name:               Windows 10
    Aug 23, 2020 12:09:12 PM org.apache.catalina.startup.VersionLoggerListener log
    INFO: OS Version:            10.0
    Aug 23, 2020 12:09:12 PM org.apache.catalina.startup.VersionLoggerListener log
    INFO: Architecture:          amd64
    Aug 23, 2020 12:09:12 PM org.apache.catalina.startup.VersionLoggerListener log
    INFO: Java Home:             C:\Program Files\Java\jdk-12.0.2
    Aug 23, 2020 12:09:12 PM org.apache.catalina.startup.VersionLoggerListener log
    INFO: JVM Version:           12.0.2+10
    Aug 23, 2020 12:09:12 PM org.apache.catalina.startup.VersionLoggerListener log
    INFO: JVM Vendor:            Oracle Corporation
    Aug 23, 2020 12:09:12 PM org.apache.catalina.startup.VersionLoggerListener log
    INFO: CATALINA_BASE:         D:\projects\.metadata\.plugins\org.eclipse.wst.server.core\tmp0
    Aug 23, 2020 12:09:12 PM org.apache.catalina.startup.VersionLoggerListener log
    INFO: CATALINA_HOME:         C:\Program Files\Apache Software Foundation\Tomcat 9.0
    Aug 23, 2020 12:09:12 PM org.apache.catalina.startup.VersionLoggerListener log
    INFO: Command line argument: -Dcatalina.base=D:\projects\.metadata\.plugins\org.eclipse.wst.server.core\tmp0
    Aug 23, 2020 12:09:12 PM org.apache.catalina.startup.VersionLoggerListener log
    INFO: Command line argument: -Dcatalina.home=C:\Program Files\Apache Software Foundation\Tomcat 9.0
    Aug 23, 2020 12:09:12 PM org.apache.catalina.startup.VersionLoggerListener log
    INFO: Command line argument: -Dwtp.deploy=D:\projects\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps
    Aug 23, 2020 12:09:12 PM org.apache.catalina.startup.VersionLoggerListener log
    INFO: Command line argument: -Dfile.encoding=Cp1252
    Aug 23, 2020 12:09:12 PM org.apache.catalina.core.AprLifecycleListener lifecycleEvent
    INFO: The Apache Tomcat Native library which allows using OpenSSL was not found on the java.library.path: [C:\Program Files\Java\jdk-12.0.2\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:/Program Files/Java/jdk-12.0.2/bin/server;C:/Program Files/Java/jdk-12.0.2/bin;c:\app\Sanjay\product\11.2.0\dbhome_1\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\System32\OpenSSH\;C:\Program Files\Java\jdk-12.0.2\bin;C:\Program Files\Apache Software Foundation\apache-maven-3.6.3-bin\apache-maven-3.6.3\bin;C:\Program Files\Apache Software Foundation\apache-maven-3.6.3-bin\apache-maven-3.6.3\bin;C:\Users\Sanjay\AppData\Local\Microsoft\WindowsApps;;C:\WINDOWS\system32;;.]
    Aug 23, 2020 12:09:13 PM org.apache.coyote.AbstractProtocol init
    INFO: Initializing ProtocolHandler ["http-nio-8686"]
    Aug 23, 2020 12:09:13 PM org.apache.catalina.startup.Catalina load
    INFO: Server initialization in [782] milliseconds
    Aug 23, 2020 12:09:13 PM org.apache.catalina.core.StandardService startInternal
    INFO: Starting service [Catalina]
    Aug 23, 2020 12:09:13 PM org.apache.catalina.core.StandardEngine startInternal
    INFO: Starting Servlet engine: [Apache Tomcat/9.0.37]
    Aug 23, 2020 12:09:13 PM org.apache.catalina.util.SessionIdGeneratorBase createSecureRandom
    WARNING: Creation of SecureRandom instance for session ID generation using [SHA1PRNG] took [153] milliseconds.
    Aug 23, 2020 12:09:15 PM org.apache.tomcat.dbcp.dbcp2.BasicDataSourceFactory getObjectInstance
    WARNING: Name = myoracle Property maxActive is not used in DBCP2, use maxTotal instead. maxTotal default value is 8. You have set value of "20" for "maxActive" property, which is being ignored.
    Aug 23, 2020 12:09:15 PM org.apache.tomcat.dbcp.dbcp2.BasicDataSourceFactory getObjectInstance
    WARNING: Name = myoracle Property maxWait is not used in DBCP2 , use maxWaitMillis instead. maxWaitMillis default value is -1. You have set value of "-1" for "maxWait" property, which is being ignored.
    Aug 23, 2020 12:09:15 PM org.apache.jasper.servlet.TldScanner scanJars
    INFO: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
    Aug 23, 2020 12:09:15 PM org.apache.catalina.core.ApplicationContext log
    INFO: No Spring WebApplicationInitializer types detected on classpath
    Aug 23, 2020 12:09:15 PM org.apache.catalina.core.ApplicationContext log
    INFO: Initializing Spring DispatcherServlet 'offer'
    Aug 23, 2020 12:09:15 PM org.springframework.web.servlet.FrameworkServlet initServletBean
    INFO: Initializing Servlet 'offer'
    Aug 23, 2020 12:09:15 PM org.springframework.security.core.SpringSecurityCoreVersion performVersionChecks
    INFO: You are running with Spring Security Core 5.2.6.RELEASE
    Aug 23, 2020 12:09:15 PM org.springframework.security.config.SecurityNamespaceHandler <init>
    INFO: Spring Security 'config' module version is 5.2.6.RELEASE
    Aug 23, 2020 12:09:15 PM org.springframework.security.config.http.FilterInvocationSecurityMetadataSourceParser parseInterceptUrlsForFilterInvocationRequestMap
    INFO: Creating access control expression attribute 'isAuthenticated()' for /CreateOffer
    Aug 23, 2020 12:09:15 PM org.springframework.security.config.http.FilterInvocationSecurityMetadataSourceParser parseInterceptUrlsForFilterInvocationRequestMap
    INFO: Creating access control expression attribute 'isAuthenticated()' for /docreate
    Aug 23, 2020 12:09:15 PM org.springframework.security.config.http.FilterInvocationSecurityMetadataSourceParser parseInterceptUrlsForFilterInvocationRequestMap
    INFO: Creating access control expression attribute 'permitAll' for /static/**
    Aug 23, 2020 12:09:15 PM org.springframework.security.config.http.FilterInvocationSecurityMetadataSourceParser parseInterceptUrlsForFilterInvocationRequestMap
    INFO: Creating access control expression attribute 'permitAll' for /
    Aug 23, 2020 12:09:15 PM org.springframework.security.config.http.FilterInvocationSecurityMetadataSourceParser parseInterceptUrlsForFilterInvocationRequestMap
    INFO: Creating access control expression attribute 'permitAll' for /newaccount
    Aug 23, 2020 12:09:15 PM org.springframework.security.config.http.FilterInvocationSecurityMetadataSourceParser parseInterceptUrlsForFilterInvocationRequestMap
    INFO: Creating access control expression attribute 'permitAll' for /createaccount
    Aug 23, 2020 12:09:15 PM org.springframework.security.config.http.FilterInvocationSecurityMetadataSourceParser parseInterceptUrlsForFilterInvocationRequestMap
    INFO: Creating access control expression attribute 'permitAll' for /createaccountvalidation
    Aug 23, 2020 12:09:15 PM org.springframework.security.config.http.FilterInvocationSecurityMetadataSourceParser parseInterceptUrlsForFilterInvocationRequestMap
    INFO: Creating access control expression attribute 'permitAll' for /login
    Aug 23, 2020 12:09:15 PM org.springframework.security.config.http.FilterInvocationSecurityMetadataSourceParser parseInterceptUrlsForFilterInvocationRequestMap
    INFO: Creating access control expression attribute 'permitAll' for /ShowOffer
    Aug 23, 2020 12:09:16 PM org.springframework.security.config.http.FilterInvocationSecurityMetadataSourceParser parseInterceptUrlsForFilterInvocationRequestMap
    INFO: Creating access control expression attribute 'denyAll' for /**
    Aug 23, 2020 12:09:16 PM org.springframework.security.config.http.HttpSecurityBeanDefinitionParser checkFilterChainOrder
    INFO: Checking sorted filter chain: [Root bean: class [org.springframework.security.web.context.SecurityContextPersistenceFilter]; scope=; abstract=false; lazyInit=null; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null, order = 200, Root bean: class [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter]; scope=; abstract=false; lazyInit=null; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null, order = 400, Root bean: class [org.springframework.security.web.header.HeaderWriterFilter]; scope=; abstract=false; lazyInit=null; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null, order = 500, Root bean: class [org.springframework.security.web.csrf.CsrfFilter]; scope=; abstract=false; lazyInit=null; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null, order = 700, <org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter#0>, order = 1200, Root bean: class [org.springframework.security.web.savedrequest.RequestCacheAwareFilter]; scope=; abstract=false; lazyInit=null; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null, order = 1900, Root bean: class [null]; scope=; abstract=false; lazyInit=null; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.security.config.http.HttpConfigurationBuilder$SecurityContextHolderAwareRequestFilterBeanFactory#0; factoryMethodName=getBean; initMethodName=null; destroyMethodName=null, order = 2000, Root bean: class [org.springframework.security.web.authentication.AnonymousAuthenticationFilter]; scope=; abstract=false; lazyInit=null; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null, order = 2300, Root bean: class [org.springframework.security.web.session.SessionManagementFilter]; scope=; abstract=false; lazyInit=null; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null, order = 2400, Root bean: class [org.springframework.security.web.access.ExceptionTranslationFilter]; scope=; abstract=false; lazyInit=null; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null, order = 2500, <org.springframework.security.web.access.intercept.FilterSecurityInterceptor#0>, order = 2600]
    Aug 23, 2020 12:09:16 PM org.hibernate.validator.internal.util.Version <clinit>
    INFO: HV000001: Hibernate Validator 6.1.5.Final
    Aug 23, 2020 12:09:17 PM org.springframework.security.provisioning.JdbcUserDetailsManager initDao
    INFO: No authentication manager set. Reauthentication of users when changing passwords will not be performed.
    Aug 23, 2020 12:09:17 PM org.springframework.security.web.DefaultSecurityFilterChain <init>
    INFO: Creating filter chain: any request, [org.springframework.security.web.context.SecurityContextPersistenceFilter@299c86f0, org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@4fbed6fc, org.springframework.security.web.header.HeaderWriterFilter@1b1d93e9, org.springframework.security.web.csrf.CsrfFilter@129b0ed, org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter@4ccf1d3e, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@75ff2b6d, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@20a7ce0, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@4ee80a94, org.springframework.security.web.session.SessionManagementFilter@7afac89a, org.springframework.security.web.access.ExceptionTranslationFilter@76d220eb, org.springframework.security.web.access.intercept.FilterSecurityInterceptor@276eafad]
    Aug 23, 2020 12:09:17 PM org.springframework.security.config.http.DefaultFilterChainValidator checkLoginPageIsntProtected
    INFO: Checking whether login URL '/login' is accessible with your configuration
    Aug 23, 2020 12:09:17 PM org.springframework.web.servlet.FrameworkServlet initServletBean
    INFO: Completed initialization in 2225 ms
    Aug 23, 2020 12:09:17 PM org.apache.coyote.AbstractProtocol start
    INFO: Starting ProtocolHandler ["http-nio-8686"]
    Aug 23, 2020 12:09:17 PM org.apache.catalina.startup.Catalina start
    INFO: Server startup in [4343] milliseconds
    Aug 23, 2020 12:09:25 PM org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter doFilter
    SEVERE: An internal error occurred while trying to authenticate the user.
    org.springframework.security.authentication.InternalAuthenticationServiceException: PreparedStatementCallback; uncategorized SQLException for SQL [select user_name username, password, 'true' enabled from USERS where user_name=?]; SQL state [99999]; error code [17059]; Fail to convert to internal representation; nested exception is java.sql.SQLException: Fail to convert to internal representation
        at org.springframework.security.authentication.dao.DaoAuthenticationProvider.retrieveUser(DaoAuthenticationProvider.java:123)
        at org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider.authenticate(AbstractUserDetailsAuthenticationProvider.java:144)
        at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:175)
        at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:195)
        at org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter.attemptAuthentication(UsernamePasswordAuthenticationFilter.java:95)
        at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:212)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
        at org.springframework.security.web.csrf.CsrfFilter.doFilterInternal(CsrfFilter.java:141)
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
        at org.springframework.security.web.header.HeaderWriterFilter.doHeadersAfter(HeaderWriterFilter.java:92)
        at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:77)
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
        at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56)
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
        at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
        at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215)
        at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178)
        at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:358)
        at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:271)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
        at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
        at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:690)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
        at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:373)
        at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
        at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)
        at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1589)
        at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
        at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
        at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
        at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
        at java.base/java.lang.Thread.run(Thread.java:835)
    Caused by: org.springframework.jdbc.UncategorizedSQLException: PreparedStatementCallback; uncategorized SQLException for SQL [select user_name username, password, 'true' enabled from USERS where user_name=?]; SQL state [99999]; error code [17059]; Fail to convert to internal representation; nested exception is java.sql.SQLException: Fail to convert to internal representation
        at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:89)
        at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:81)
        at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:81)
        at org.springframework.jdbc.core.JdbcTemplate.translateException(JdbcTemplate.java:1443)
        at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:633)
        at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:669)
        at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:700)
        at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:712)
        at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:763)
        at org.springframework.security.provisioning.JdbcUserDetailsManager.loadUsersByUsername(JdbcUserDetailsManager.java:150)
        at org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl.loadUserByUsername(JdbcDaoImpl.java:181)
        at org.springframework.security.authentication.dao.DaoAuthenticationProvider.retrieveUser(DaoAuthenticationProvider.java:108)
        ... 41 more
    Caused by: java.sql.SQLException: Fail to convert to internal representation
        at oracle.jdbc.driver.CharCommonAccessor.getBoolean(CharCommonAccessor.java:185)
        at oracle.jdbc.driver.T4CCharAccessor.getBoolean(T4CCharAccessor.java:697)
        at oracle.jdbc.driver.OracleResultSetImpl.getBoolean(OracleResultSetImpl.java:640)
        at org.apache.tomcat.dbcp.dbcp2.DelegatingResultSet.getBoolean(DelegatingResultSet.java:358)
        at org.apache.tomcat.dbcp.dbcp2.DelegatingResultSet.getBoolean(DelegatingResultSet.java:358)
        at org.springframework.security.provisioning.JdbcUserDetailsManager.lambda$loadUsersByUsername$0(JdbcUserDetailsManager.java:155)
        at org.springframework.jdbc.core.RowMapperResultSetExtractor.extractData(RowMapperResultSetExtractor.java:94)
        at org.springframework.jdbc.core.RowMapperResultSetExtractor.extractData(RowMapperResultSetExtractor.java:61)
        at org.springframework.jdbc.core.JdbcTemplate$1.doInPreparedStatement(JdbcTemplate.java:679)
        at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:617)
        ... 48 more

Thanks in advance for your help.

A: I was using char as enabled datatype and char is converted to java.lang.String or oracle.sql.CHAR.
I changed it to number as number can be converted to boolean and it worked fine.
Please use the below link for complete reference:
https://docs.oracle.com/cd/E11882_01/java.112/e16548/apxref.htm#JJDBC28906


text:
Q: How to register a embed handler as a fallback to a oEmbed handler? Testing this with the Embed Gutenberg Block. In the backend it actually shows the video so this seems wrong that it behaves differently there.
Registering embed handlers causes the to take priority over the (default) WordPress oEmebed handlers even when priority is set to PHP_INT_MAX. I like to trigger them after the oembed handlers in case they fail. How can I do this?
This code is inside a mu-plugin, but I have more complicated code in my main plugin that has the same issue.
<?php
namespace Nextgenthemes\Debug;

disable_oembed_cache();

add_action( 'init', function() {

    wp_embed_register_handler(
        'arve_dailymotion',
        '#https?://(www\.)?(dai\.ly|dailymotion\.com/video)/(?<id>[a-z0-9]+)#i',
        __NAMESPACE__ . '\dailymotion_embed_handler',
        PHP_INT_MAX
    );
} );

function dailymotion_embed_handler( array $matches, array $attr, $url, array $rawattr ) {
    return print_r( $matches );
}

function disable_oembed_cache() {

    add_action( 'init', function() {
        $GLOBALS['wpdb']->query( "DELETE FROM {$GLOBALS['wpdb']->postmeta} WHERE meta_key LIKE '%_oembed_%'" );
    } );

    add_action( 'template_redirect', function() {
        $GLOBALS['wpdb']->query( "DELETE FROM {$GLOBALS['wpdb']->postmeta} WHERE meta_key LIKE '%_oembed_%'" );
        $GLOBALS['wp_embed']->cache_oembed( get_queried_object_id() );
    } );

    add_filter( 'oembed_ttl', function( $ttl ) {
      return 1;
    } );
}

Sidenote: In my local testing with the Dailymotion oEmbed I get it to work only every 2nd/3rd time or so. Maybe because I deactivate the cache but its not happening for YouTube.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How not to allow validation for a specific action in Rails 4 I have this password validation in my user.model.rb:
class User < ActiveRecord::Base

  validates :password, presence: true, confirmation: true,
            format: {:with => /^(?=.*[0-9])(?=.*[A-Z])(?=.*[&%$#@*])[a-zA-Z0-9&%$#@*]{8,}$/,
            :multiline => true, :message => I18n.t('invalid_password')}
end

I want this validation to be called in each and every method but not in my update action.
I have a users_controller.rb that has a create and update action. I want it to check in the create action but not in the update action.
I also have a password_resets_controller.rb in which I want it to check in both create and update actions but not in users_controller update action. I am using the authlogic gem. Both controllers use the same model.
Please guide me on how to do this. Thanks in advance.

A: validates :password, :presence => {:on => :create}

OR
##here new_user is a method that you can create and use condionally
## or validates_presence_of :password, :if => :new_user?
validates_presence_of :password, :unless => :new_user?

def new_user?
  //your code
end

OR Using with_options
class User < ActiveRecord::Base
  has_many :roles

  # Normal Validations
  validates_presence_of   :password

  with_options :if => :customer? do |customer|
    customer.validates_presence_of :password
  end

  def customer?
    roles.any? { |role| role.name == "customer" }
  end
end

A: Probably the most close answer can be:
class User < ActiveRecord::Base
   validates :password, presence: true, if: :not_persisted?

   def not_persisted?
     !self.persisted?
   end
end

This code will actually trigger the validation only if the object is not persisted (on create)


text:
Q: Sorted list of random repeated numbers to sorted list of repeated and continuos numbers in google sheets I think the best way to show the problem is with an example. Column A is what i have now, and column B is what I would want.

A
B

1
1

1
1

2
2

2
2

5
3

5
3

5
3

8
4

8
4

9
5

9
5

14
6

14
6

17
7

17
7

17
7

A: Update: Based on your comment, use this formula
=ArrayFormula(IF(ISNUMBER(A1:A), VLOOKUP(A1:A, {UNIQUE(A1:A), ArrayFormula(RANK(UNIQUE(A1:A), UNIQUE(A1:A), 1))}, 2, 0), ""))

Previous answer: Have you already used the SORT formula?
Try =SORT(A1:A, 1, 1) in cell B1

A: Assuming your data starts at row 2 through row 10 column A. In B2 :
=arrayformula(1/COUNTIF($A$2:$A$10,$A$2:$A$10))

in C2
=sumproduct(($B$1:$B1)*($A$1:$A1<A2))+1


text:
Q: Sanity check: prime ideals in number fields Work in $\mathbb{Q}(\zeta_m)/\mathbb{Q}$. If $P$ is a prime ideal of norm $N(P)=p \hspace{1mm}\not \vert m$, does it follow that $p \equiv 1 \text{ mod }m$? I am sure this is not true, but am bad at generating counterexamples.

A: There are no counterexamples, indeed if the norm of an ideal $P$ in $\mathbb  Q(\zeta_m)$ is $p$ and $p \not\vert m$ then $p \equiv 1 \pmod{m}$.
Here is the argument, the hypothesis implies that $\zeta_m$ is congruent to an integer $\mod P$, otherwise not all the integers $k-\zeta_m (k=0,\dots,p-1)$ would be incongruent $\mod P$, and so $P$ would divide the difference of two of them, say $$P \vert (a-\zeta_m)-(b-\zeta_m)=a-b = k <p $$
so
    $$ p = N(P) \vert  k^{\varphi(m)} $$
but $(p, k)=1$, a contradiction.
So $\zeta_m$ is congruent to an integer $\pmod{P}$ say $t$, then
    $$ \Phi_m(t) = \prod_k' (t-\zeta_m^k) \equiv 0 \pmod{P} $$
where $\Phi_m(x)$ is the $m$-th cyclotomic polynomial and the product is over all the integers $k$ coprime with $m$ and smaller than $m$. As the left hand side is an integer we have also
    $$ \Phi_m(t) \equiv 0 \pmod{p} $$
but $\Phi_m(x)$ is a divisor of the polynomial $x^m-1$, this implies that $t^m\equiv 1 \pmod{p}$ that is the order of $t$ is a divisor of $m$. We are going to show that it is exactly equal to $m$.
Suppose otherwise that the order of $t$ is $n$, with $n\vert m$, $n<m$, we use the the fact that
   $$ x^m-1 = \prod_{d\vert m} \Phi_d(x) = \Phi_m(x) \times (x^n-1) \times Q(x) $$
for some polynomial $Q$, but then $x^m-1$ has at least a double root at $t$ mod $p$, and this means that it's derivative is zero at $t$ say
  $$ m t^{m-1} \equiv 0 \pmod{p} $$
a contradiction.
This means that the order of $t$ mod $p$ is $m$ and so $m \vert p-1$ ie
   $$ p \equiv 1 \pmod{m} $$


text:
Q: T-SQL XML nodes are interleaved I need the following XML structure
<root>
    <lkz>12345</lkz>
    <styles>
        <style>
            <productNo>
            ..
            </productNo>
        </style>
        <style>
            <productNo>
            ..
            </productNo>
        </style>
    </styles>
</root>

The table that I use
lkz   | productNo
------+----------------
12345 | 123456-789
12345 | 1213456-788

lkz is always the same
My T-SQL code:
DECLARE @xmlData XML

SET @xmlData = (SELECT productNo
                FROM dbo.otto
                FOR XML PATH ( 'Style' ), ROOT ('Styles'), ELEMENTS)

SELECT @xmlData

Result
<Styles>
  <Style>
    <productNo>123456-789</productNo>
  </Style>
  <Style>
    <productNo>123456-788</productNo>
  </Style>
</Styles>

Questions (sorry for my English):

*

*How can I get  about "everything"

*How can I get <lkz> only second line as simple node
THANKS for help !

A: Do group by on lkz in the main query and get the corresponding productNo values in a sub-query.
select O1.lkz,
       (
       select O2.productNo
       from dbo.Otto as O2
       where O1.lkz = O2.lkz
       for xml path('style'), root('styles'), type
       )
from dbo.otto as O1
group by O1.lkz
for xml path(''), root('root');

A: my table
lkz|stylesNo|ClassOfGoods|ClusterAttribute1
12345|123456-789|test1|Herren
12345|123456-788|test2|Damen

to need xml
<root>
<LKZ>12345</LKZ>
<Styles>
<Style>
<StyleNo>123456-789</StyleNo>
<ClassOfGoods>test1</ClassOfGoods>
<ClusterAttribute1 CountryIsoCode="DE"><![CDATA[Herren]]></ClusterAttribute1>

my t-sql
SET @xmlData =
    (select O1.lkz,
                (
                select O2.stylesNo
                ,O2.ClassOfGoods

                ,(SELECT
                                1 as Tag,
                                0 as Parent,
                                'DE' as [ClusterAttribute1!1!CountryIsoCode],
                                ClusterAttribute1 as [ClusterAttribute1!1!!CDATA]
                    FROM
                    dbo.otto as O3
                    --where O1.stylesNo = O3.stylesNo
                    FOR XML EXPLICIT, type
                    )

                from dbo.otto as O2
                where O1.lkz = O2.lkz
                for xml path('style'), root('styles'), type
                )
    from dbo.otto as O1
    group by O1.lkz
    for xml path(''), root('ottopartner')
    )

SELECT @xmlData

result
<root>
  <lkz>12345</lkz>
  <styles>
    <style>
      <stylesNo>123456-789</stylesNo>
      <ClassOfGoods>test1</ClassOfGoods>
      <ClusterAttribute1 CountryIsoCode="DE">Herren</ClusterAttribute1>
      <ClusterAttribute1 CountryIsoCode="DE">Damen</ClusterAttribute1>
    </style>
    <style>
      <stylesNo>123456-788</stylesNo>
      <ClassOfGoods>test2</ClassOfGoods>
      <ClusterAttribute1 CountryIsoCode="DE">Herren</ClusterAttribute1>
      <ClusterAttribute1 CountryIsoCode="DE">Damen</ClusterAttribute1>
    </style>
  </styles>
</root>


text:
Q: jQuery UI: tooltip works fine, but datepicker function not recognized EDIT: It started working after I deletd all the jQuery-related jS-files/packages in my Scripts folder, then simply added the online versions of the important files in the head section of the HTML, like so:
<script src='https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js' type="text/javascript"></script>
<script src="http://code.jquery.com/ui/1.12.0/jquery-ui.js" type="text/javascript"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css" />

Of course I still don't understand exactly WHY it didn't work earlier. It's true that I noticed some different jQuery-versions (i.e., basically the same files but with different version numbers) in my Scripts folder, but even after I removed the doubles the datepicker still didn't work. It only started working after I deletd all the relevant files in my Scripts folder, then added the above links in my HTML. At least it's working now, and I don't have time to look further into this. But may have to come back to this later, as this is not really a nice solution.
I also found this question: jQuery UI " $("#datepicker").datepicker is not a function". But although I feel my issue may be similar to the one described there, I couldn't really apply the solutions/approaches presented there to my own case.
What follows is the original question:
I have this:
<script>
    $('#testTooltip').tooltip();
    $('#testDatepicker').datepicker();
</script>

<p id="testTooltip" title="These words will appear in the tooltip">
Hello, I'm testing the tooltip
</p>

<input id="testDatepicker" type="text" />

Surprisingly, the tooltip works fine, but the datepicker does nothing. In fact, for the datepicker I get the error message:

TypeError: $(...).datepicker is not a function

I'm working in the ASP.NET / MVC framework, which should mean that the required jQuery files are in the right place and are automatically included in my files without me having to add script tags for that purpose. But anyway, as far as I'm aware, the code for both the tooltip and the datepicker resides in jquery-ui.js (a file which I haven't changed or touched of course). So if the tooltip works, meaning that the call to function tooltip() works fine, how can it be that the function datepicker() isn't recognised as well?
Thanks.

A: You can use type = "date". Sample
<input id="testDatepicker" type="date" />


text:
Q: Void pointer as template argument in C++ The following does not compile:
template<void *p>
class X {
// ...
};

int r;

int main()
{
    X<&r> x;

    return 0;
}

The error message is

x.cc:10:6: error: could not convert template argument '& r' to 'void*'

Explicitly casting &r to (void *) doesn't help either. The error message becomes:

x.cc:10:14: error: could not convert template argument '(void*)(& r)' to 'void*'

Which part of the standard specifies that behaviour?
The GCC version is gcc version 5.2.1 20151003 (Ubuntu 5.2.1-21ubuntu2)
Edit:
Please note that using e.g. int * instead of void * works as expected.
Edit: (answering myself)
It does not work with gcc HEAD 6.0.0 20151016 (experimental) when specifying -std=c++1z, neither with implicit nor with explicit casting to "void *".
It does work with clang HEAD 3.8.0 (trunk 250513) and has been since (at least) clang 3.6.0 (tags/RELEASE_360/final) when specifying --std=c++1z and explicitly casting to *void *".
Without the explicit cast, clang complains as follows:

x.cc:10:7: error: conversion from 'int *' to 'void *' is not allowed in a converted constant expression

Responsible for fixing this bug in the c++ language specification is N4268 which clang already implements.

A: I can't quote you the chapter and verse off the top of my head (edits are welcome), but what you are trying to do is not allowed in c++.
Template parameters must be known at compile time. Pointers are only resolved at link time unless:

*

*they are defaulted using = nullptr in the template argument list.

*they are member function pointers (which are known at compile time since they are merely offsets).
for example, this will compile:
template<void * = nullptr>
class X {
    // ...
};

int r;

int main()
{
    X<nullptr> x;

    return 0;
}

A: Normally, there is a conversion allowed for any pointer to void*.

[C++11, 4.10/2] A prvalue of type "pointer to cv T," where T is an
  object type, can be converted to a prvalue of type "pointer to cv
  void". The result of converting a "pointer to cv T" to a "pointer to
  cv void" points to the start of the storage location where the object
  of type T resides, as if the object is a most derived object (1.8) of
  type T (that is, not a base class subobject). The null pointer value
  is converted to the null pointer value of the destination type.

However, for non-type template arguments, certain conversions are specified:

[C++11, 14.3.2/5] The following conversions are performed on each
  expression used as a non-type template-argument. If a non-type
  template-argument cannot be converted to the type of the corresponding
  template-parameter then the program is ill-formed.
[...]
— for a non-type template-parameter of type pointer to object,
  qualification conversions (4.4) and the array-to-pointer conversion
  (4.2) are applied; if the template-argument is of type std::nullptr_t,
  the null pointer conversion (4.10) is applied. [...]

By omission, we can reason this conversion is simply not allowed.


text:
Q: How to create this algebraic equation encoding basic choice? Given 2 non negative, ordered real variables $x, y$ such that we know:

*

*$x\geqslant y$

*$x - y = d$

*$x+y=1$
Given another variable $k$ such that either:

*

*$k=0$ or

*$k=d^2-d$
The objective is to construct a single algebraic equation such that:

*

*The equation outputs $d$ when value of $k$ is non zero i.e. $k=d^2-d$.

*It outputs 0 when $k$ is 0.

Essentially we are trying to encode a logical constraint in a simple mathematical equation. The simple approach is to take $d^2-d$ or 0 as the constant and solve the quadratic equation $x^2-x=k$ but it will give 2 results in each case:

*

*$d$ and $1-d$

*0 and 1

How do we enforce the logic/selection using basic mathematical operations [+, - , *, /, abs()]. We are not allowed to use any logical operations or operations that internally use logic or require if/else kind of tests at any level as that defeats the original purpose and makes the problem trivial.
Been struggling with it for days can someone please help?


text:
Q: Changed LAMP WWW directory to Dropbox, now getting 403 Forbidden I wan to use my Dropbox/Web directory as the server directory for LAMP. I cahnged /etc/apache2/sites-available/default
DocumentRoot /home/me/Dropbox/Web #changed from /etc/www
<Directory />
    Options FollowSymLinks
    AllowOverride None
</Directory>
<Directory /home/me/Dropbox/Web/> #changed from /etc/www
    Options Indexes FollowSymLinks MultiViews
    AllowOverride None
    Order allow,deny
    allow from all
</Directory>

And now I get
Forbidden

You don't have permission to access / on this server.

Apache/2.2.22 (Ubuntu) Server at localhost Port 80

A: Apache probably can't read from your Dropbox directory. In Ubuntu, Apache is configured to run as user www-data. Make sure you set the permissions on your filesystem to allow Apache reading the whole path.
To test whether this is really your issue, try in a terminal
sudo su -l www-data -s /bin/bash

and then cd step by step to your Dropbox folder:
cd /home
cd me
cd Dropbox
cd Web

Fix the permissions, e.g.

*

*chmod o+rx on directories and chmod o+r on files, or

*change groups on files/directories chgrp www-data and allow only the www-data group to read/access: chmod g+r for files and chmod g+rx for directories.

A: www-data, the group/user Apache runs is not allowed to read in your home directory.
You can use regular permissions to change that as gertvdijk explained in its answer.
I would consider using acl instead of regular permissions, allowing to add permission to apache instead of replacing the group in home directory or making the directory world readable.
For that, you need to install acl:
sudo apt-get install acl

You can use man setfacl to have more info.
To add permissions to apache:
sudo setfacl -m d:g:www-data:X,g:www-data:X /home/me
sudo setfacl -m d:g:www-data:X,g:www-data:X /home/me/Dropbox
sudo setfacl -Rm d:g:www-data:rX,g:www-data:rX /home/me/Dropbox/Web

1st and 2nd commands will allow Apache (www-data) to change directory only through the path (without allowing other subdirectories) in your home.  They are probably not needed if you are using default config but if you already changed permissions (or will change in the future) to disalow other users to read in your home, they are needed.
The 3rd one is the command that will allow Apache to read and change directories in Dropbox/web and sub-directories).
Obs: uppercase X will act only on directories instead of lowercase x that would act on both files and directories (this way apache user is only able to change directories, not executing files).


text:
Q: How to tone down Gitlab logging for small installation Repost from the Gitlab forum, still looking for an answer:
So I'm trying to set up a Gitlab instance for personal use on my Synology NAS. I got it up and running using docker pretty easily, but there is a snag: in the default configuration continually generates log output every couple of seconds. This consumes about 2 MB per hour. The diskspace is actually not my main concern, the constant log output prevents the NAS from going into sleep mode.
According to the documentation I can set the log level using an environment variable. I tried setting it to "warn" but that has very little effect, if any.
Any tips how I can get Gitlab to restrict logging to the time periods when I'm actually using it would be appreciated.
Here is the docker command I use to start gitlab:
export GITLAB_HOME=/volume1/docker/gitlab

sudo docker run --detach \
  --hostname gitlab.shire.lan \
  --publish 30443:443 --publish 30080:80 --publish 30022:22 \
  --name gitlab \
  --restart always \
  --volume $GITLAB_HOME/config:/etc/gitlab \
  --volume $GITLAB_HOME/logs:/var/log/gitlab \
  --volume $GITLAB_HOME/data:/var/opt/gitlab \
  --shm-size 256m \
  --env GITLAB_LOG_LEVEL=warn \
  --env GITLAB_ROOT_PASSWORD=secret \
  --env GITLAB_HOST=http://gitlab.shire.lan \
  gitlab/gitlab-ce:latest


text:
Q: Run bash command on jenkins pipeline Inside a groovy script (for a jenkins pipeline): How can I run a bash command instead of a sh command?
I have tried the following:
Call "#!/bin/bash" inside the sh call:
stage('Setting the variables values') {
    steps {
         sh '''
            #!/bin/bash
            echo "hello world"
         '''
    }
}

Replace the sh call with a bash call:
stage('Setting the variables values') {
    steps {
         bash '''
            #!/bin/bash
            echo "hello world"
         '''
    }
}

Additional Info:
My command is more complex than a echo hello world.

A: If you want to change your default shell to bash for all projects on Jenkins, you can do so in the Jenkins config through the web portal:
Manage Jenkins > Configure System (Skip this clicking if you want by just going to https://{YOUR_JENKINS_URL}/configure.)
Fill in the field marked 'Shell executable' with the value /bin/bash and click 'Save'.

A: According to this document, you should be able to do it like so:
node {
    sh "#!/bin/bash \n" +
       "echo \"Hello from \$SHELL\""
}

A: The Groovy script you provided is formatting the first line as a blank line in the resultant script. The shebang, telling the script to run with /bin/bash instead of /bin/sh, needs to be on the first line of the file or it will be ignored.
So instead, you should format your Groovy like this:
stage('Setting the variables values') {
    steps {
         sh '''#!/bin/bash
                 echo "hello world"
         '''
    }
}

And it will execute with /bin/bash.

A: For multi-line shell scripts or those run multiple times, I would create a new bash script file (starting from #!/bin/bash), and simply run it with sh from Jenkinsfile:
sh 'chmod +x ./script.sh'
sh './script.sh'

A: I'm sure that the above answers work perfectly. However, I had the difficulty of adding the double quotes as my bash lines where closer to 100. So, the following way helped me. (In a nutshell, no double quotes around each line of the shell)
Also, when I had "bash '''#!/bin/bash" within steps, I got the following error java.lang.NoSuchMethodError: No such DSL method '**bash**' found among steps
pipeline {
    agent none

    stages {

        stage ('Hello') {
            agent any

            steps {
                echo 'Hello, '

                sh '''#!/bin/bash

                    echo "Hello from bash"
                    echo "Who I'm $SHELL"
                '''
            }
        }
    }
}

The result of the above execution is

A: In my case, I had to execute a Shell script in bash via jenkinsfile. Here's what worked for me :
sh 'core_devops/automation/scripts/ecs_initialize.sh'
And the first line in the script had
#!/bin/bash

A: The problem is indeed that the shebang is ignored if it doesn't start at the very beginning of the file.
As an alternative to mangling the formatting for Jenkinsfile readers, I've taken to using this:
sh label: 'Run fancy bash script',
   script: '''
       #!/usr/bin/env  bash

       echo "Hello ${SHELL}!"
   '''.stripIndent().stripLeading()

Note that stripIndent() is not strictly necessary for it to work, but Jenkins logs are a lot nicer with it.

A: In my case event
sh '''#!/bin/bash
      echo "Hello ${SHELL}!"
'''

return "Hello /bin/sh"...
after some search I found "sh" was "dash" instead of bash on another terminal
Ubuntu22 :
jenkins@ubuntu22:~$ command -v sh
/usr/bin/sh
jenkins@ubuntu22:~$ ls -l /usr/bin/sh
lrwxrwxrwx 1 root root 4 Mar 23  2022 /usr/bin/sh -> dash
jenkins@ubuntu22:~$ command -v dash
/usr/bin/dash

on my old Red Hat 7.4 :
[jenkins@RH7.4 ~]$ command -v sh
/usr/bin/sh
[jenkins@RH7.4 ~]$ ls -l /usr/bin/sh
lrwxrwxrwx 1 root root 4 Sep  6  2018 /usr/bin/sh -> bash
[jenkins@RH7.4 ~]$ command -v bash
/usr/bin/bash
[jenkins@RH7.4 ~]$ ls -l /usr/bin/bash
-rwxr-xr-x 1 root root 960632 Aug  3  2017 /usr/bin/bash


text:
Q: Estimating a sum related to a short Euler product The Question
Is $$\sum_{\substack{n>y\\ p\mid n\Rightarrow p\leq y}}\frac{\Lambda(n)}{n^s\log n}=O(1/\log T)$$ where $y=(\log T)^{100}$ and $T$ is large?

Background
Assume that $$\log\zeta(\sigma+it)=\sum_{n=2}^y\frac{\Lambda(n)}{n^{\sigma+it}\log n}+O\left(y^{(1/2-\sigma)/2}(\log T)^3\right)$$ for $\frac{1}{2}<\sigma\leq1$, $T$ sufficiently large, and $e^2\log T\leq y\leq (\log T)(\log\log T)^4$. Let $$\zeta(s;z)=\prod_{p\leq z}\left(1-\frac{1}{p^s}\right)^{-1}$$ and put $z=(\log T)^{100}$. I have been trying to prove that $$\zeta(1+it)=\zeta(1+it;z)(1+O(1/\log T)).$$
This comes from a paper that I've been reading through lately. I've cracked most of the proofs, but this one has me confused. I tried to start with $\zeta(1+it)=\exp(\log\zeta(1+it))$, apply the assumption to get $$\zeta(1+it)=\exp\left(\sum_{n=2}^z\frac{\Lambda(n)}{n^{1+it}\log n}\right)\cdot\exp\left(O(\log T^{-22}))\right).\tag{1}$$At this point, I wanted to check if the factor on the left is really all that I needed; unfortunately, what I have found is that $$\log\zeta(s;z)=\sum_{\substack{n=2\\p\mid n\Rightarrow p\leq y}}^\infty\frac{\Lambda(n)}{n^s\log n}=\sum_{n=2}^y\frac{\Lambda(n)}{n^s\log n}+\sum_{\substack{n=y+1\\ p\mid n\Rightarrow p\leq y}}^\infty\frac{\Lambda(n)}{n^s\log n}.$$ Thus, I can subtract the rightmost term over and substitute into $(1)$ to get $$\zeta(1+it)=\zeta(1+it;z)\exp\left(O(\log T^{-22})-\sum_{\substack{n>y\\ p\mid n\Rightarrow p\leq y}}\frac{\Lambda(n)}{n^{1+it}\log n}\right).$$Now I just need to analyze the sum inside the error term, which is the question posted above. Any criticisms of my above work and suggestions will be very welcome.

A: I was trying to prove this. This is what I obtained.

We will work on the expression with $\sigma\geq 1$ and $y$ not a prime. We rewrite the expression as
$$
\sum_{\substack{n>y\\ p\mid n\Rightarrow p<y}}\frac{\Lambda(n)}{n^\sigma\log n}=\sum_{p<y}\sum_{\substack{k\\p^k>y}}\frac{\Lambda(p^k)}{p^{\sigma k}\log p^k}=\sum_{p<y}\sum_{k>\frac{\log y}{\log p}}\frac{1}{kp^{\sigma k}}\tag{1}
$$
The inner sum will be bounded by the integral in the following way: set $r=r(p)=\log y/\log p$ then
$$
\begin{align*}
\Sigma_1:=\sum_{k>r}\frac{1}{kp^{\sigma k}}&\leq \frac{1}{p^{\sigma(r+1)}(r+1)}+\int_{r+1}^\infty\frac{1}{p^{\sigma t}t}\, dt.\\
&=\frac{1}{p^\sigma y^\sigma\left(\frac{\log y}{\log p}+1\right)}+\int_{\sigma (r+1)\log p}^{\infty}\frac{1}{e^u u}\, du.\\
&\leq \frac{1}{p^\sigma y^\sigma\left(\frac{\log y}{\log p}+1\right)}+\operatorname{E}_1(\sigma \log y+\sigma\log p)
\end{align*}
$$
We use the estimate $\operatorname{E}_1(x)<e^{-x}\log\left(1+\frac{1}{x}\right)$ for $x>0$ to obtain
$$
\begin{align*}
\Sigma_1<\frac{1}{p^\sigma y^\sigma\left(\frac{\log y}{\log p}+1\right)}+p^{-\sigma}y^{-\sigma}\log\left(1+\frac{1}{\sigma \log y+\sigma\log p}\right)
\end{align*}
$$
Replacing on the equation $(1)$ we get
$$
\begin{align*}
\sum_{\substack{n>y\\ p\mid n\Rightarrow p\leq y}}\frac{\Lambda(n)}{n^\sigma\log n}&<\sum_{p<y}\left(\frac{1}{p^\sigma y^\sigma\left(\frac{\log y}{\log p}+1\right)}+p^{-\sigma}y^{-\sigma}\log\left(1+\frac{1}{\sigma \log y+\sigma\log p}\right)\right)\\
&=\sum_{p<y}\frac{1}{p^\sigma y^\sigma\left(\frac{\log y}{\log p}+1\right)}+y^{-\sigma}\sum_{p<y}p^{-\sigma}\log\left(1+\frac{1}{\sigma\log yp}\right)\tag{2}\\
&\ll\frac{1}{y^\sigma}\sum_{p<y}\frac{1}{p^\sigma\left(\frac{\log y}{\log p}+1\right)}+y^{-\sigma}\sum_{p<y}\frac{p^{-\sigma}}{\sigma\log py}\tag{3}\\
&\ll\frac{1}{y^\sigma}+\frac{y^{-\sigma}}{\sigma}\tag{4}\\
&\ll\frac{1}{y}
\end{align*}
$$
To go from $(2)$ to $(3)$ we use Taylor series for $\log(1+x)$. To go from $(3)$ to $(4)$: set $\sigma=1$ (the largest possible case) in both sums. For the first sum we factorize $\log y/\log p$ in the denominator and use the fact $\sum_{p<y}(\log p)/p=\log y+O(1)$. The second follows comparing with the integral. If need more details of some computations please ask me.
Also, any mistake or miscalculation please comment it.


text:
Q: Rewriting SQL query to get record id and customer number Sample data
+-------------------+-------------+-----------------+---------------------+
| RECORD_ID         | CUST_NO     | IsAccntClosed   | Code                |
+-------------------+-------------+-----------------+---------------------+
|159045             |   2439123   | N               |   13                |
+-------------------+-------------+-----------------+---------------------+
|159048             |   6376150   | Y               |   13                |
+-------------------+-------------+-----------------+---------------------+
|159048             |   9513035   | N               |   13                |
+-------------------+-------------+-----------------+---------------------+
|159049             |   2398524   | N               |   12                |
+-------------------+-------------+-----------------+---------------------+
|159049             |   6349269   | Y               |   12                |
+-------------------+-------------+-----------------+---------------------+
|159049             |   6350690   | Y               |   12                |
+-------------------+-------------+-----------------+---------------------+
|159049             |   6372163   | Y               |   12                |
+-------------------+-------------+-----------------+---------------------+
|159049             |   6393810   | Y               |   12                |
+-------------------+-------------+-----------------+---------------------+
|159049             |   6402062   | Y               |   12                |
+-------------------+-------------+-----------------+---------------------+
|159050             |   2677512   | Y               |   12                |
+-------------------+-------------+-----------------+---------------------+
|159050             |   6349382   | Y               |   12                |
+-------------------+-------------+-----------------+---------------------+
|159050             |   6378137   | Y               |   12                |
+-------------------+-------------+-----------------+---------------------+
|159051             |   2336197   | N               |   12                |
+-------------------+-------------+-----------------+---------------------+
|159051             |   6349293   | N               |   12                |
+-------------------+-------------+-----------------+---------------------+
|159051             |   6350682   | N               |   12                |
+-------------------+-------------+-----------------+---------------------+
|159051             |   6367895   | N               |   12                |
+-------------------+-------------+-----------------+---------------------+
|159060             |   yyyyyy    | Y               |   12                |
+-------------------+-------------+-----------------+---------------------+

IsAccntClosed column indicates if the account is Open (Y) or account is closed (Y).
I need to select Record_ID and cust_no for only those rows for which which Record_Id satisfies one of the below condition :
1. Only one cust account is open , there might be one or multiple closed customers
2. No open customer and only one closed customer
Expected output :
159045 2439123
159048 9513035
159049 2398524
159060 yyyyyy
A query like this would take each row as a single group and the count will come as 1
select RECORD_ID, CUST_NO, IsAccntClosed, count(IsAccntClosed), Code
  from table1
 group by RECORD_ID, CUST_NO, IsAccntClosed, Code

Any suggestions on how this query could be written to get the expected output?

A: In the below I added another record:
insert into tbl values (159060, 'zzzzzz', 'N', 12);

to illustrate what would happen if a record_id has just one open cust_no and just one closed cust_no. Note how in the result the cust_no returned is the zzzzz one, because that account is open, which you mentioned wanting to take precendence over closed, in the event of a tie 1:1 (zzzzzz should take over yyyyyy in this case, because yyyyyy is closed whereas zzzzzz is open)
Fiddle: http://sqlfiddle.com/#!4/5cb60/1/0
with one_open as
 (select record_id
    from tbl
   where IsAccntClosed = 'N'
   group by record_id
  having count(distinct cust_no) = 1),
one_closed as
 (select record_id
    from tbl
   where IsAccntClosed = 'Y'
   group by record_id
  having count(distinct cust_no) = 1),
bothy as
 (select record_id from one_open intersect select record_id from one_closed)
select *
  from tbl
 where (record_id in (select record_id from one_open) and
       IsAccntClosed = 'N')
    or (record_id not in (select record_id from one_open) and
       record_id in (select record_id from one_closed) and
       IsAccntClosed = 'Y' and
       record_id not in (select record_id from bothy))

A: Being IsAccntClosed a CHAR column, you should be able to get what you want with a query like this:
SELECT a.record_id,
  (CASE
     WHEN a.CountOpen=1 THEN a.CustNoOpen
     ELSE                    a.CustNoClosed
  END) AS cust_no
FROM (
  SELECT b.record_id,
    MAX(CASE WHEN b.IsAccntClosed='N' THEN b.cust_no ELSE NULL END) AS CustNoOpen  ,
    SUM(CASE WHEN b.IsAccntClosed='N' THEN 1         ELSE 0    END) AS CountOpen   ,
    MAX(CASE WHEN b.IsAccntClosed='Y' THEN b.cust_no ELSE NULL END) AS CustNoClosed,
    SUM(CASE WHEN b.IsAccntClosed='Y' THEN 1         ELSE 0    END) AS CountClosed
  FROM table1 b
  GROUP BY b.record_id
) a
WHERE a.CountOpen=1 OR (a.CountOpen=0 AND a.CountClosed=1)

The inner query is grouping the table. It counts the open and closed accounts and takes one (random) cust_no of any of the closed accounts and one (random) of any of the open accounts, per group.
The outer query filters the data and cleans everything up, placing the open or closed cust_no in the output result column.
Notice that the WHERE condition of the outer query has the collateral effect that, since you are looking for records that have just a single open or a single closed account, those random cust_no which have been selected by the inner query, are now significant.
EDIT: I fixed the query and tested it on SQLFiddle.

A: select
  record_id,
  cust_no
from (
  select
    record_id,
    cust_no,
    count(case when isAccntClosed='Y' then 1 else null end)
      over (partition by record_id) closed_accounts,
    count(case when isAccntClosed='N' then 1 else null end)
      over (partition by record_id) open_accounts
  from
    table1
  )
where (open_accounts = 1)
   or (open_accounts = 0 and closed_accounts = 1)

A: You can do this with conditional aggregation:
select RECORD_ID,
       (case when sum(case when IsAccntClosed = 'N' then 1 else 0 end) = 1
             then max(case when IsAccntClosed = 'N' then max(CUST_NO) end)
             else max(CUST_NO)
        end) as cust_no
from table1
group by RECORD_ID
having sum(case when IsAccntClosed = 'N' then 1 else 0 end) = 1 or
       (sum(case when IsAccntClosed = 'N' then 1 else 0 end) = 0 and
        sum(case when IsAccntClosed = 'Y' then 1 else 0 end) = 1
       )

It is probably easier to understand the logic using subqueries:
select recordId,
       (case when numOpen > 0 then OpenCustNo else closedCustNo end) as CustNo
from (select t1.RecordId, sum(case when IsAccntClosed = 'N' then 1 else 0 end) as numOpen,
             sum(case when IsAccntOpen = 'N' then 1 else 0 end) as numClosed,
             max(case when IsAccntClosed = 'N' then cust_no end) as OpenCustNo,
             max(case when IsAccntClosed = 'Y' then cust_no end) as ClosedCustNo
      from table1 t1
      group by record_id
     ) r
where numOpen = 1 or numOpen = 0 and numClosed = 1;


text:
Q: Sharing on instagram with bypassing the instagram menu (Swift) I am developing an app, where I am able to share to instagram, but I want to share directly to the instagram story.
At the moment, when I am trying to share the picture, it is opening the instagram story menu and then I have to click again to share.
Is there a way to bypass this section.
Code:
private let instagramStoriesURL = URL(string: "instagram-stories://share")

   public func postToInstagramStories(image: UIImage, backgroundTopColorHex: String, backgroundBottomColorHex: String, deepLink: String) {

        DispatchQueue.main.async {

                guard let urlScheme = self.instagramStoriesURL else {
                    self.delegate?.error(message: "URL not valid")
                    return
                }

                let pasteboardItems = ["com.instagram.sharedSticker.stickerImage": image,
                                       "com.instagram.sharedSticker.backgroundTopColor" : backgroundTopColorHex,
                                       "com.instagram.sharedSticker.backgroundBottomColor" : backgroundBottomColorHex,
                                       "com.instagram.sharedSticker.contentURL": deepLink] as [String : Any]

                if #available(iOS 10.0, *) {
                    let pasteboardOptions = [UIPasteboard.OptionsKey.expirationDate : NSDate().addingTimeInterval(60 * 5)]
                    UIPasteboard.general.setItems([pasteboardItems], options: pasteboardOptions)

                } else {
                    UIPasteboard.general.items = [pasteboardItems]
                }
                if #available(iOS 10.0, *) {
                    UIApplication.shared.open(urlScheme, options: [:], completionHandler: { (success) in
                        self.delegate?.success()
                    })
                } else {
                    UIApplication.shared.openURL(urlScheme)
                    self.delegate?.success()
                }
        }
    }


text:
Q: Wordpress - Woocommerece remove "Added to Cart" message I'm looking to remove the wording and area that says "Product Successfully Added to Cart" after I add an item to the cart.  I just want there to be nothing, no message and no space for the message.
Here's the site: http://www.tinytreasurehunts.com
The code is in woocommerece-functions.php
Any thoughts?

A: To solve this at PHP level, add the following template file (and structure) to your theme:
/wp-content/themes/YOUR-THEME/woocommerce/shop/messages.php:
<?php
/**
 * Show messages
 *
 * @author      brasofilo
 * @package     WooCommerce/Templates
 * @version     1.6.4
 */

if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

if ( ! $messages ) return;

foreach ( $messages as $message ) :
    // The message does not contain the "add to cart" string, so print the message
    // http://stackoverflow.com/q/4366730/1287812
    if ( strpos( $message, 'added to your cart' ) === false ) :
        ?>

<?php echo wp_kses_post( $message ); ?>

        <?php
    endif;
endforeach;

See: Template Structure + overriding templates via a theme

A: Use one of these:
Older version
$woocommerce->clear_messages();

Version 2.3
wc_clear_notices();

A: Just use simple CSS:
.single-product .woocommerce-message {
    display: none !important;
}

Or, if you're familiar with functions.php, this is a better solution:
add_filter( 'wc_add_to_cart_message_html', '__return_null' );

Source is here, together with a way to edit such message in case you wish to print your own version instead

A: Use CSS and set the display to none for the ID or associated class.

.page-id-522 .woocommerce_message {
     display: none;
}

This is specific to page id 522. Make sure this doesn't also hide other useful messages like credit card declines, etc.

A: Add this code to your themes functions.php file. It will remove only that message. It should trigger on just the pages where it is likely to occur.
function remove_added_to_cart_notice()
{
    $notices = WC()->session->get('wc_notices', array());

    foreach( $notices['success'] as $key => &$notice){
        if( strpos( $notice, 'has been added' ) !== false){
            $added_to_cart_key = $key;
            break;
        }
    }
    unset( $notices['success'][$added_to_cart_key] );

    WC()->session->set('wc_notices', $notices);
}
add_action('woocommerce_before_single_product','remove_added_to_cart_notice',1);
add_action('woocommerce_shortcode_before_product_cat_loop','remove_added_to_cart_notice',1);
add_action('woocommerce_before_shop_loop','remove_added_to_cart_notice',1);

I've pasted this answer from my own answer at Remove/Hide Woocommerce Added to Cart Message but Keep/Display Coupon Applied Message

A: Update for WooCommerce Version 2.1.6
The template is located in a new directory and file. Same code and solution as above.
/wp-content/plugins/woocommerce/templates/notices/success.php

A: Use .post .woocommerce_message{display:none;} at the end of your theme files or in your child theme.


text:
Q: One definition of strong convexity (from textbook of Prof. Bertsekas in 2015) In strong convexity, there are a few definitions, one of them is:
$f$ is strongly convex over $\mathcal{C}$ with coefficient $\sigma$ if $\forall x,y \in \mathcal{C}$ and all $\alpha \in [0,1]$, we have
$$f(\alpha x+(1-\alpha)y)+ \frac{\sigma}{2}\alpha(1-\alpha)\|x-y\|^2\leq\alpha f(x)+(1-\alpha)f(y)$$
In the textbook Convex Optimization Algorithms, Bersekas p.471
, it says:
There exists a unique $x^* \in \mathcal{C}$ minimizing $f$ over $\mathcal{C}$, and by applying the definition above with $y=x^*$ and letting $\alpha \rightarrow 0$, we have
$$f(x) \geq f(x^*)+\frac{\sigma}{2} \|x-x^*\|^2$$
I am questioning if the conclusion is correct since if $\alpha \rightarrow 0$, there should be no the term $\frac{\sigma}{2} \|x-x^*\|^2$.
How to get this result?

A: Setting $y=x^*$ gives you after a small rearrangement
$$
f(x^*+\alpha(x-x^*))-f(x^*)\le\alpha\left[-\frac{\sigma}{2}(1-\alpha)\|x-x^*\|^2+f(x)-f(x^*)\right].
$$
The left hand side is non-negative due to the assumption that $x^*$ is the minimum, that is
$$
0\le-\frac{\sigma}{2}(1-\alpha)\|x-x^*\|^2+f(x)-f(x^*).
$$
Now let $\alpha\to 0$.


text:
Q: How to automate new gmail UI to send email by using Selenium IDE? The current gmail UI has changed, it opens in a pop up DIV and the ID parameters are changing for each new compose window. Can anyone try to give me the code?

A: You can do all using XPath (find using By.xpath("xpath expression")):

*

*Open the gmail page

*Login as usual

*Click on compose button (its XPath expression: "//div[text()='COMPOSE']")

*(The email dialog will pop up)

*Type (send keys) the addesses in the "To" text area: "//textarea[@name='to']"

*Type (send keys) the subject to the "Subject" input: "//input[@name='subjectbox']"

*Type (send keys) the email content to the editable div: "//div[@class='gmail_default']" (or "//div[@aria-label='Message Body']"), as it seems they changed their HTML recently)

*Hit send: "//div[text()='Send']"

A: I found the below solution:

setTimeout
3000

< !--open command usually waits for 30 secs, so we are now asking it to wait for only 3 secs-->

open
/mail/u/0/?shva=1#inbox?compose=new

type
//table/tbody/tr[1]/td[2]/div/div/textarea
McKiran@example.com

type
name=subjectbox
Test

type
class=editable LW-avf
Hi All
Hope the test is successful.

 Lovingly,
McKiran.

click
class=T-I J-J5-Ji aoO T-I-atl L3

A: Use selenium webdrier
go throw the below link
http://ngowda.blogspot.in/2014/01/uploading-file-in-e-commerce-site-using.html

A: public static void main(String[] args) throws InterruptedException {
        System.setProperty("webdriver.chrome.driver","D:\Selenium\SeleniumWork\seleniumDrivers\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.manage().window().maximize();
        driver.get("https://accounts.google.com/ServiceLogin?service=mail&continue=https://mail.google.com/mail/#identifier");
        if(driver.findElement(By.xpath(".//[@id='Email']")).isEnabled())
        {
        driver.findElement(By.xpath(".//[@id='Email']")).sendKeys("youremailid");
        driver.findElement(By.xpath(".//*[@id='next']")).click();
        }
        Thread.sleep(5000);
        WebElement menu = driver.findElement(By.xpath(".//input[@type='password']"));
        if(menu.isEnabled())
        {
        System.out.println("Hello world");
         menu.sendKeys("emailidpassword");
        driver.findElement(By.xpath(".//*[@id='signIn']")).click();
    }
     Thread.sleep(5000);
     driver.findElement(By.xpath(".//div[contains(text(),'COMPOSE')]")).click();
     Thread.sleep(5000);
     driver.findElement(By.xpath("//textarea[@name='to']")).sendKeys("@gmail.com");
 driver.findElement(By.xpath("//input[@name='subjectbox']")).sendKeys("Sample");

driver.findElement(By.xpath("//div[@aria-label='Message Body']")).sendKeys("HI this is simple message");
         driver.findElement(By.xpath("//div[text()='Send']")).click();
}


text:
Q: Android notification message at a particular time why it is repeated every time the app launched I would like to make the app send a notification at specific time of a day, I need to use alarm manger with notification as what described by this tutorial.
The code is working well, and send the notification at the specified time even if the app is not running however the notification is send also any time I run the app which is very weird.. below is the code, thanks for any hint.
inside onCreate() in MainActivity
Calendar calendar = Calendar.getInstance();

calendar.set(Calendar.MONTH, Calendar.MAY);
calendar.set(Calendar.YEAR, 2014);
calendar.set(Calendar.DAY_OF_MONTH, 27);

calendar.set(Calendar.HOUR_OF_DAY,10);
calendar.set(Calendar.MINUTE, 33);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.AM_PM,Calendar.AM);

Intent myIntent = new Intent(this, MyReceiver.class);
pendingIntent = PendingIntent.getBroadcast(this, 0, myIntent,0);

AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);

MyReceiver.java
public class MyReceiver extends BroadcastReceiver
{

@Override
public void onReceive(Context context, Intent intent)
{
   Intent service1 = new Intent(context, MyAlarmService.class);
   context.startService(service1);

}

}

MyAlarmService
public class MyAlarmService extends Service
{

   private NotificationManager mManager;

    @Override
    public IBinder onBind(Intent arg0)
    {
       // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void onCreate()
    {
       // TODO Auto-generated method stub
       super.onCreate();
    }

   @SuppressWarnings({ "static-access"})
   @Override
   public void onStart(Intent intent, int startId)
   {

       mManager = (NotificationManager) getSystemService(getApplicationContext().NOTIFICATION_SERVICE);
       Intent intent1 = new Intent(this.getApplicationContext(),MainActivity.class);

       intent1.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP| Intent.FLAG_ACTIVITY_CLEAR_TOP);

      PendingIntent pendingNotificationIntent = PendingIntent.getActivity( this.getApplicationContext(),0, intent1,PendingIntent.FLAG_ONE_SHOT);

      NotificationCompat.Builder mBuilder =
            new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_launcher)
            .setContentTitle("Today 27-5-2014")
            .setContentText(" You have your last final exam ")
            .setContentIntent(pendingNotificationIntent);

       mManager.notify(0, mBuilder.build());

    }

    @Override
    public void onDestroy()
    {
        // TODO Auto-generated method stub
        super.onDestroy();
    }

}

EDIT:
please note that my requirement is to send notification at particular time say At 10:00 Am..
The code above succeed in sending the notification at 10:00 AM,
My problem is that the notification is still fired every time I run the app even if it is not 10:00 AM

A: Try out following code..
public class MainActivity extends Activity {

Calendar calendar;
private PendingIntent alarmIntent;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    calendar = Calendar.getInstance();
    Long time = new GregorianCalendar().getTimeInMillis()+60*06*24*1000;

    Intent intentAlarm = new Intent(this, AlarmReceiver.class);

    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    alarmIntent=PendingIntent.getBroadcast(this, 1, intentAlarm, 0);

    alarmManager.set(AlarmManager.RTC_WAKEUP,time, alarmIntent);

    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),1000 * 60*60*24, alarmIntent);
}
}

AlarmReceiver.java
public class AlarmReceiver extends BroadcastReceiver{
private static final int MY_NOTIFICATION_ID=1;
Intent in;
PendingIntent pendingIntent;
Notification mBuilder;

@Override
public void onReceive(Context context, Intent intent)
{
    in=new Intent(context,MainActivity.class);
    in.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    pendingIntent=PendingIntent.getActivity(context, 0, in, 0);

    mBuilder=new NotificationCompat.Builder(context)
        .setSmallIcon(R.drawable.ic_launcher)
        .setContentTitle("Your Title")
        .setContentText("Your Text")
        .setContentIntent(pendingIntent)
        .setAutoCancel(true)
        .build();

    NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

    mNotificationManager.notify(1, mBuilder);
    mNotificationManager.notify(MY_NOTIFICATION_ID, mBuilder);
}
}

Include following code in your manifest file
 <application>
    ....
    <receiver android:name=".AlarmReceiver"/>
  </application>

Easy Tutorial of AlarmManager here...

A: I tried the code below to produce alarm every 24 hours. It works fine but when you launch the App the first time you will see the notification. But later on it wont produce notification when you open the App.
pendingIntent = PendingIntent.getBroadcast(this, 0, myIntent, PendingIntent.FLAG_NO_CREATE);

        boolean testval = (pendingIntent == null);

        if(testval)
        {
            pendingIntent = PendingIntent.getBroadcast(this, 0, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
            alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);

        }


text:
Q: Extract RDD[(Array[String]) from RDD[(String, Array[String]) [Spark/scala] I have this prbolem, I have one of this kind  RDD[(String, Array[String]), and I would like extract from it a RDD[Array[String]] that contains the values grouped by key:
e.g:
val x :RDD[(String, Array[String]) =
RDD[(a, Array[ "ra", "re", "ri"]),
(a, Array[ "ta", "te", "ti"]),
(b, Array[ "pa", "pe", "pi"])]

I would like get:
val result: RDD[(String, RDD[Array[String]]) =
RDD[(a, RDD[Array[("ra", "re", "ri"),( "ta", "te", "ti")]]),
(b,  RDD[Array[("pa", "pe", "pi"),...]])
,...]

A: A simple reduceByKey should solve your issue
x.reduceByKey((prev, next)=> (prev ++ next))

A: As far as I know, Spark doesn't support nested RDDs (see this StackOverflow discussion).
In case nested arrays are good for what you need, a simple groupByKey will do:
val x = sc.parallelize(Seq(
  ("a", Array( "ra", "re", "ri" )),
  ("a", Array( "ta", "te", "ti" )),
  ("b", Array( "pa", "pe", "pi" ))
))

val x2 = x.groupByKey

x2.collect.foreach(println)
(a,CompactBuffer([Ljava.lang.String;@75043e31, [Ljava.lang.String;@18656538))
(b,CompactBuffer([Ljava.lang.String;@2cf30d2e))

x2.collect.foreach{ case (a, b) => println(a + ": " + b.map(_.mkString(" "))) }
a: List(ra re ri, ta te ti)
b: List(pa pe pi)


text:
Q: Is it possible to use Web API model validation on query parameters? I am currently trying to write a Web API application where one of the parameters I'd like to validate is a query parameter (that is, I wish to pass it in in the form /route?offset=0&limit=100):
[HttpGet]
public async Task<HttpResponseMessage> GetItems(
    int offset = 0,
    int limit = 100)
{
    if (!ModelState.IsValid)
    {
        // Handle error
    }

    // Handle request
}

In particular, I want to ensure that "offset" is greater than 0, since a negative number will cause the database to throw an exception.
I went straight for the logical approach of attaching a ValidationAttribute to it:
[HttpGet]
public async Task<HttpResponseMessage> GetItems(
    [Range(0, int.MaxValue)] int offset = 0,
    int limit = 100)
{
    if (!ModelState.IsValid)
    {
        // Handle error
    }

    // Handle request
}

This does not cause any errors at all.
After a lot of painful debugging into ASP.NET, it appears to me that this may be simply impossible. In particular, because the offset parameter is a method parameter rather than a field, the ModelMetadata is created using GetMetadataForType rather than GetMetadataForProperty, which means that the PropertyName will be null. In turn, this means that AssociatedValidatorProvider calls GetValidatorsForType, which uses an empty list of attributes even though the parameter had attributes on it.
I don't even see a way to write a custom ModelValidatorProvider in such a way as to get at that information, because the information that this was a function parameter seems to have been lost long ago. One way to do that might be to derive from the ModelMetadata class and use a custom ModelMetadataProvider as well but there's basically no documentation for any of this code so it would be a crapshoot that it actually works correctly, and I'd have to duplicate all of the DataAnnotationsModelValidatorProvider logic.
Can someone prove me wrong? Can someone show me how to get validation to work on a parameter, similar to how the BindAttribute works in MVC? Or is there an alternative way to bind query parameters that will allow the validation to work correctly?

A: You can create a view request model class with those 2 properties and apply your validation attributes on the properties.
public class Req
{
    [Range(1, Int32.MaxValue, ErrorMessage = "Enter number greater than 1 ")]
    public int Offset { set; get; }

    public int Limit { set; get; }
}

And in your method, use this as the parameter
public HttpResponseMessage Post(Req model)
{
    if (!ModelState.IsValid)
    {
       // to do  :return something. May be the validation errors?
        var errors = new List<string>();
        foreach (var modelStateVal in ModelState.Values.Select(d => d.Errors))
        {
            errors.AddRange(modelStateVal.Select(error => error.ErrorMessage));
        }
        return Request.CreateResponse(HttpStatusCode.OK, new { Status = "Error",
                                                                       Errors = errors });
    }
    // Model validation passed. Use model.Offset and Model.Limit as needed
    return Request.CreateResponse(HttpStatusCode.OK);
}

When a request comes, the default model binder will map the request params(limit and offset, assuming they are part of the request) to an object of Req class and you will be able to call ModelState.IsValid method.

A: For .Net 5.0 and validating query parameters:
using System.ComponentModel.DataAnnotations;

namespace XXApi.Models
{
    public class LoginModel
    {
        [Required]
        public string username { get; set; }
        public string password { get; set; }
    }
}

namespace XXApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class LoginController : ControllerBase
    {
        [HttpGet]
        public ActionResult login([FromQuery] LoginModel model)
        {
             //.Net automatically validates model from the URL string
             //and gets here after validation succeeded
        }
    }
}

A:   if (Offset < 1)
        ModelState.AddModelError(string.Empty, "Enter number greater than 1");
    if (ModelState.IsValid)
    {
    }


text:
Q: Core Data Object IDs vs Permanent Object ID This question might look like it's been asked many times before, but I'm not sure I've aggregated the answer correctly.  So here goes.
ObjectIDs are described by Apple (WWDC 2012 Session 214) as context-safe, thread-safe.  So I spent some time converting my code to take advantage of that.  However, it doesn't appear to be as context-safe as they make it sound, because as discussed here Core Data: Do child contexts ever get permanent objectIDs for newly inserted objects? and elsewhere, there is the existence of something called Permanent IDs.
With regards to this permanent ID business, I looked in NSManagedObjectContext.h:
/* Converts the object IDs of the specified objects to permanent IDs.  This implementation
will convert the object ID of each managed object in the specified array to a permanent
ID.  Any object in the target array with a permanent ID will be ignored;  additionally,
any managed object in the array not already assigned to a store will be assigned, based on
the same rules Core Data uses for assignment during a save operation (first writable store
supporting the entity, and appropriate for the instance and its related items.)  Although
the object will have a permanent ID, it will still respond positively to -isInserted until
it is saved.  If an error is encountered obtaining an identifier, the return value will be
NO.
*/

- (BOOL)obtainPermanentIDsForObjects:(NSArray *)objects error:(NSError **)error NS_AVAILABLE(10_5, 3_0);

So I've been having trouble with this in my code.  I have a hierarchy of NSManagedObjectContexts (say, B and C), and only 1 of them is actually linked to a persistent store (call is A).  So, C is child of B, B is child of A.  If I create an NSManagedObject from C, and then call obtainPermanentIDsForObjects, is it actually permanent?  Because the .h file comments reads like it only looks up the hierarchy to B (first writeable store supporting the entity, and in the child-parent setup, changes are only pushed up 1 level) , not A.
Thanks in advance.

A: Yes, if you call obtainPermanentIDsForObjects then the IDs you receive are supposed to be permanent (barring any implementation bugs in the framework, which seem unlikely for something this core at this point).


text:
Q: Copy text from Vim 7.2 running in xterm to windows clipboard I'm using Vim 7.2 , compiled with +xterm_clipboard , in a xterm through putty . I've put set clipboard=unnamed in .vimrc , and from what i've read in other threads , this should put all yanks/deletes to the system clipboard. However , when I'm trying to paste whatever i've yanked to a MS app like notepad, its not working.
When I select text in vim using mouse , it automatically gets copied to the system(MS clipboard). I'd like to have the same functionality while using keyboard commands like 3yy .
Can anyone tell me what I'm doing wrong ?

A: Try
"+3yy
"*3yy

"+p
"*p

A: If you were running vim locally, then either
"+p
"*p

would work, as mentioned by hacker.  Since you're sshed into another box, these will just copy text to the clipboard of the box you're sshed into.
What you need is the putty method of copying text, which is just highlighting the text you want to copy with the mouse.
While sshed into vim though, I usually use ALT + highlight with the mouse (for block selection), as I usually have line numbers on.
Hope this helps!

A: I'm trying to figure out how to get vim inside PuTTY (no xterm involved) to interact with the Windows clipboard.
My research so far indicates it's not possible.  xterm has clipboard-interaction terminal escape sequences, but they're disabled by default in xterm.  They're probably not implemented at all in PuTTY.  This is probably for security reasons: you don't want a remote system to have full access to your clipboard.
I'm not sure if that's what vim's xterm_clipboard feature is supposed to use, anyway.  My searching so far only turns up people complaining about it not being enabled, or talking about how to get a vim that has it enabled, not how it's actually implemented.  The best I've found is this guide which mentions it, but doesn't say anything that would pin it down to escape sequences vs. X selection vs. X clipboard.  (Yes, X11 has a selection and a separate clipboard.  Some ways of copying only set one or the other.)

Vim's clipboard support talks directly to the X server.  On a Linux desktop, with vim in a terminal (Konsole in my case) :"*dd does put the lines into the clipboard.
With
(unset DISPLAY; strace -s256 -o /dev/pts/18 vim some_file.txt)

vim doesn't have an X server to talk to.  (pts18 is the tty of another terminal window.)  I thought vim might use xterm escape sequences to set the clipboard, but it doesn't.  There is no write(1, ...) system call with the whole region, so it's clearly not trying to use an escape sequence to put the region in the clipboard via xterm.
I ran this inside a Konsole with TERM=xterm, on Ubuntu 15.04.  I also tried inside a real xterm.
Oh, xterm disables GetSelection/SetSelection by default.  Maybe with this enabled, vim would try to use it?  IDK if this helps, though, because PuTTY would also have to support it, which is unlikely.


text:
Q: How to integrate set of vector in multiple data.frame into one without duplication? I have position index vector in data.frame objects, but in each data.frame object, the order of position index vector are very different. However, I want to integrate/ merge these data.frame object object in one common data.frame with very specific order and not allow to have duplication in it. Does anyone know any trick for doing this more easily? Can anyone propose possible approach how to accomplish this task?
data
v1 <- data.frame(
  foo=c(1,2,3),
  bar=c(1,2,2),
  bleh=c(1,3,0))

v2 <-  data.frame(
  bar=c(1,2,3),
  foo=c(1,2,0),
  bleh=c(3,3,4))

v3 <-  data.frame(
  bleh=c(1,2,3,4),
  foo=c(1,1,2,0),
  bar=c(0,1,2,3))

initial output after integrating them:
initial_output <- data.frame(
  foo=c(1,2,3,1,2,0,1,1,2,0),
  bar=c(1,2,2,1,2,3,0,1,2,3),
  bleh=c(1,3,0,3,3,4,1,2,3,4)
)

remove duplication
rmDuplicate_output <- data.frame(
  foo=c(1,2,3,1,0,1,1),
  bar=c(1,2,2,1,3,0,1),
  bleh=c(1,3,0,3,4,1,2)
)

final desired output:
final_output <- data.frame(
  foo=c(1,1,1,1,2,3,0),
  bar=c(0,1,1,1,2,2,3),
  bleh=c(1,1,2,3,3,0,4)
)

How can I get my final desired output easily? Is there any efficient way for doing this sort of manipulation for data.frame object? Thanks

A: You could also use use mget/ls combo in order to get your data frames programmatically (without typing individual names) and then use data.tables rbindlist and unique functions/method for great efficiency gain (see here and here)
library(data.table)
unique(rbindlist(mget(ls(pattern = "v\\d+")), use.names = TRUE))
#    foo bar bleh
# 1:   1   1    1
# 2:   2   2    3
# 3:   3   2    0
# 4:   1   1    3
# 5:   0   3    4
# 6:   1   0    1
# 7:   1   1    2

As a side note, it usually better to keep multiple data.frames in a single list so you could have better control over them

A: Here is a solution:
# combine dataframes
df = rbind(v1, v2, v3)

# remove duplicated
df = df[! duplicated(df),]

# sort by 'bar' column
df[order(df$bar),]
    foo bar bleh
7   1   0    1
1   1   1    1
4   1   1    3
8   1   1    2
2   2   2    3
3   3   2    0
6   0   3    4

A: We can use bind_rows from dplyr, remove the duplicates with distinct and arrange by 'bar'
library(dplyr)
bind_rows(v1, v2, v3) %>%
             distinct %>%
             arrange(bar)
#    foo bar bleh
#1   1   0    1
#2   1   1    1
#3   1   1    3
#4   1   1    2
#5   2   2    3
#6   3   2    0
#7   0   3    4


text:
Q: Remove all the elements before the given one from the array Hi im trying to solve this question:
Not all of the elements are important. What you need to do here is to remove from the list all of the elements before the given one.
exemple:
remove_all_before([1, 2, 3, 4, 5], 3) == [3, 4, 5]

remove_all_before([1, 1, 2, 2, 3, 3], 2) == [2, 2, 3, 3]

remove_all_before([1, 1, 2, 4, 2, 3, 4], 2) == [2, 4, 2, 3, 4]

remove_all_before([1, 1, 5, 6, 7], 2) == [1, 1, 5, 6, 7]

remove_all_before([], 0) == []

remove_all_before([7, 7, 7, 7, 7, 7, 7, 7, 7], 7) == [7, 7, 7, 7, 7, 7, 7, 7, 7]

For the illustration we have a list [3, 4, 5] and we need to remove all elements that go before 3 - which is 1 and 2.
We have two edge cases here: (1) if a cutting element cannot be found, then the list shoudn't be changed. (2) if the list is empty, then it should remain empty.
def remove_all_before(items: list, border: int) -> Iterable:
limit = border
item_list = items

for i in item_list:
    if i < limit:
        return items[i+1:]
    elif limit not in item_list:
        return items

this is my code so far...and im stuck.
thanks for the help

A: this can be solved by using the index method of list and try and except command. here is the solution-
def remove_all_before(item, border):
    try:
    #search for the item
        index = item.index(border)
        print(f'the border is found at index {index}')
        return item[index:]
    except ValueError:
        print('border not present')
        return item

A: def remove_all_before(items: list, border: int) -> Iterable:
# your code here
for i in range(0, len(items)):
    if (items[i] == border):
        return items[i:]

return items

A: in my opinion this is the best solution, in this one you have the verification if border is in items
def remove_all_before(items, border):
    result1 = []
    result2 = []
    for i in range(len(items)):
        if (items[i] == border):
            result1 = items[i:]
            return result1

        result2.append(items[i])

    if (result1 == []):
        return result2
    else:
        return result1


text:
Q: Redirecting persistent HTTP requests and responses using sockets I wish to create a router of some sort to redirect HTTP requests from an HTTP client to a servlet (they preform a negotation process. More background: I wish to do an auth from windows to windows server, going throug a redirective Unix web server).
My servlet is on http://localhost:8080
and my redirector is on 8081
So, I wrote this:
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Redirect {

    /**
     * @param args
     * @throws IOException
     * @throws InterruptedException
     */
    public static void main(String[] args) throws IOException, InterruptedException {
        ServerSocket ss = new ServerSocket(8081);
        Socket s = new Socket("localhost", 8080);
        Socket l = ss.accept();
        l.setKeepAlive(true);
        s.setKeepAlive(true);
        OutputStream os = s.getOutputStream();
        InputStream is = l.getInputStream();
        Thread t1 = new Thread(new MyReader(is, os,"#1"));
        t1.start();
        InputStream is2 = s.getInputStream();
        OutputStream os2 = l.getOutputStream();
        Thread t2 = new Thread(new MyReader(is2, os2,"#2"));
        t2.start();
    }

    public static class MyReader implements Runnable {
        private InputStream _i;
        private OutputStream _o;
        private String _id;

        public MyReader(InputStream i, OutputStream o, String id) {
            _i = i;
            _o = o;
            _id = id;
        }

        @Override
        public void run() {
            try {
                int x;
                x = _i.read();
                while (x != -1) {
                    System.out.println(_id);
                    _o.write(x);
                    _o.flush();
                    x = _i.read();
                }
                System.out.println(x);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

It works fine for most servlets! So what's my problem? My servlet is a persistent one http://en.wikipedia.org/wiki/HTTP_persistent_connection, that is it does connection=keep-alive and does a whole back and forth messaging dance.
What am I doing wrong? I thought I could run two MyReader threads and that they will block until new information comes, but instead they keep blocking.
This is my client:
public class Client {
    public static void main(String[] args) throws IOException {
        URL u = new URL("http://localhost:8081/Abc/Def");
        HttpURLConnection huc = (HttpURLConnection)u.openConnection();
        huc.setRequestMethod("GET");
        huc.setDoOutput(true);
        huc.connect();
        InputStream is = huc.getInputStream();//The all auth process is done here
             //and HttpUrlConnection support it. If I change 8081 to 8080, it works

}

A: try adding an infinite wait loop after starting t2 thread as shown below
              while ( true) {
                  sleep(1000);
              }


text:
Q: Could not load file or assembly 'Microsoft.AI.Agent.Intercept' or one of its dependencies I had to copy all of my ASP>NET MVC5 project to a new project and after that when i try to run it i am getting this error

Could not load file or assembly 'Microsoft.AI.Agent.Intercept' or one
  of its dependencies. The located assembly's manifest definition does
  not match the assembly reference. (Exception from HRESULT: 0x80131040)

I have done some research but could not find anything about it also i deleted the content of whole bin file, cleaned the project and done rebuild but it didnt work. I am new to MVC5 and dont know what to do. Any help would be appreciated.

A: Did you manually removed Microsoft appInsights dlls from your project and tried to add it back?. You need to also install Microsoft ApplicationInsights Instrumenation Intercept Extension nuget package where that dll is contained.


text:
Q: purpose of the max number in php & mysql What is the main purpose for the maximum limit for number in php and mysql?
Does this means that we can/cannot process or store numbers that is larger than the limit?
I echo PHP_INT_MAX and it shows 2147483647.
I multiply by 1000000000000000000000 and get answers like 2.147483647E+30 which i think is already over the limit?
Please advise.
Many thanks for guidance.
This question arise when I'm thinking about validating the user form input. I want to make sure that the user input is according to our defined number format and not something else.
Then i do some online search for best practices and come to aware of this "limits" but do not know how to handle it correctly when using PHP & MYSQL. Pls advise:
Step 1: trim and convert user form input "string number" to number.
Step 2: validate the number is in positive integer format.
Step 3: validate the number does not exceed my "max limit".
Since php limit (2,147,483,647) is smaller than mysql limit (18,446,744,073,709,500,000)? i'll take php as my max limit.
Step 4: perform some calculations...
Step 5: validate my result does not exceed my max limit.
Step 6: store the result in mysql.

A: It's hardware limit of the CPU. You can still use bc math function to work with larger numbers. In mysql it is about aligning bytes, so it knows at which offset is which column.
The multiply result is converted to float.

A: PHP_INT_MAX is the constant of the largest integer you can use on this build of PHP (32 bit in your case). If your OS and CPU support 64 bit, you can use a 64 bit build of PHP to support a much larger number in an integer. (This causes problems where developers have designed their code around the limits of a 64 bit build and is then used on 32 bit builds, assuming the type matters.)
When you multiply the number by a larger one, PHP recognises this new value is not going to fit in an integer and converts the type to a long or float. In the latter case, you would lose some precision, so it's important you're careful when considering how your code affects variable types. In some languages, you would receive an error for trying to set a value larger than was allowed by that type, because the language would refuse to change the type automatically for you. In this way, PHP is a more basic programming language to use.
<?php
$my_number = PHP_INT_MAX;
var_dump(gettype($my_number), $my_number);
$my_number = $my_number * 1000000000000000000000;
var_dump(gettype($my_number), $my_number);

Output:
string(7) "integer"
int(2147483647)
string(6) "double"
float(2.147483647E+30)

A: In the world of computing, there are many limits based upon the mathematical model of the computer hardware we use.
For instance, if we decided to represent an integer number in 1 bit of memory, then we would be able to represent the numbers 0 and 1.
If we were to increase that to the more common values of 8, 16, 32 or 64 bits then we can represent the following number of distinct values:

*

*2^8 - 256,

*2^16 - 65,536,

*2^32 - 4,294,967,296,

*or 2^64 - 18,446,744,073,709,551,616.

Of course, if we wish to be able to represent negative numbers then we can sign the integer (use one bit to indicate negative or positive). In the case of a 32 bit signed integer this would allow us to represent the numbers: −(2^31) to 2^31 − 1 or -2,147,483,648 to +2,147,483,647 (the same upper limit as the number in your question).
Integers are arguably the simplest form of number representation in a computer system (beyond straight binary), but because of the inherent limits of the system, we will often need to use other systems for larger numbers that we cannot represent with an integer. PHP will switch from using an integer to using floating point numbers when the limit is exceeded.
The limit you are seeing in PHP is compiled in, and will depend upon the architecture of the compiler. It looks as if your PHP was compiled as 32 bits.
You can read up far more on computer number systems on Wikipedia.


text:
Q: PayPal sandbox account with limited card balance I want to simulate bank refusal(PayPal sandbox account) when attached card does not have enough money in it.
PayPal account with 0 balance.
Card with balance of 300 money(PayPal have no idea it is so).
I make payment, exceed this amount, PayPal refuses payment after I click "Pay Now".
Currently if test card is attached to PayPal account, it does have unlimited funding.
Of course, one of options is to create/use LIVE account on LIVE environment with card that have almost no balance and buy product that exceeds balance, but I would not prefer that.
Any experiences/ideas?
Thank you.

A: Take a look at the PayPal documentation:  Testing Error Conditions with Negative Testing
You basically enable the negative testing on your sandbox account, and then you can trigger specific error codes by sending the amount that matches the error code.
For example, to trigger error code 10755 you would use 107.55 for the amount in your payment request.