text:
Q: Hibernate code has no errors, but not creating tables and shows few logging errors I am trying to create a table through Hibenate and i have written code in both DAO and Model classes using annotation, server is running fine, but table is not getting created. I am integrating spring with Hibernate so, would like to know what the error/logs are and where the issue is in the project. Thanks in advance
Here is error thrown by the logger:
ContextLoader - Root WebApplicationContext: initialization started
XmlWebApplicationContext - Refreshing Root WebApplicationContext: startup date [Sun Jan 28 11:21:44 EST 2018]; root of context hierarchy
XmlBeanDefinitionReader - Loading XML bean definitions from class path resource [com/hospital/config/dao-context.xml]
ClassPathBeanDefinitionScanner - JSR-250 'javax.annotation.ManagedBean' found and supported for component scanning
PropertyPlaceholderConfigurer - Loading properties file from class path resource [hibconfig.properties]
DefaultListableBeanFactory - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@5fefc31: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,patientDAO,org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping#0,org.springframework.format.support.FormattingConversionServiceFactoryBean#0,org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter#0,org.springframework.web.servlet.handler.MappedInterceptor#0,org.springframework.beans.factory.config.PropertyPlaceholderConfigurer#0,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0,org.springframework.transaction.interceptor.TransactionInterceptor#0,org.springframework.transaction.config.internalTransactionAdvisor,transactionManager,sessionFactory,dataSource]; root of factory hierarchy
DriverManagerDataSource - Loaded JDBC driver: com.mysql.jdbc.Driver
Version - Hibernate Commons Annotations 3.2.0.Final
Environment - Hibernate 3.6.10.Final
Environment - hibernate.properties not found
Environment - Bytecode provider name : javassist
Environment - using JDK 1.4 java.sql.Timestamp handling
AnnotationBinder - Binding entity from annotated class: com.hospital.model.Patient
EntityBinder - Bind entity com.hospital.model.Patient on table Patient
AnnotationBinder - Binding entity from annotated class: com.hospital.model.InPatient
EntityBinder - Bind entity com.hospital.model.InPatient on table InPatient
AnnotationBinder - Binding entity from annotated class: com.hospital.model.OutPatient
EntityBinder - Bind entity com.hospital.model.OutPatient on table OutPatient
Configuration - Hibernate Validator not found: ignoring
AnnotationSessionFactoryBean - Building new Hibernate SessionFactory
HibernateSearchEventListenerRegister - Unable to find org.hibernate.search.event.FullTextIndexEventListener on the classpath. Hibernate Search is not enabled.
ConnectionProviderFactory - Initializing connection provider: org.springframework.orm.hibernate3.LocalDataSourceConnectionProvider
JDBCExceptionReporter - SQL Error: 1045, SQLState: 28000
JDBCExceptionReporter - Access denied for user 'root'@'localhost' (using password: YES)
SettingsFactory - Could not obtain connection to query metadata
java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1073)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3609)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3541)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:943)
    at com.mysql.jdbc.MysqlIO.secureAuth411(MysqlIO.java:4113)
    at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1308)
    at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2336)
    at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2369)
    at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2153)
    at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:792)
    at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
    at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:381)
    at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:305)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriverManager(DriverManagerDataSource.java:173)
    at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriver(DriverManagerDataSource.java:164)
    at org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnectionFromDriver(AbstractDriverBasedDataSource.java:149)
    at org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnection(AbstractDriverBasedDataSource.java:119)
    at org.springframework.orm.hibernate3.LocalDataSourceConnectionProvider.getConnection(LocalDataSourceConnectionProvider.java:81)
    at org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:113)
    at org.hibernate.cfg.Configuration.buildSettingsInternal(Configuration.java:2863)
    at org.hibernate.cfg.Configuration.buildSettings(Configuration.java:2859)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1870)
    at org.springframework.orm.hibernate3.LocalSessionFactoryBean.newSessionFactory(LocalSessionFactoryBean.java:860)
    at org.springframework.orm.hibernate3.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:779)
    at org.springframework.orm.hibernate3.AbstractSessionFactoryBean.afterPropertiesSet(AbstractSessionFactoryBean.java:211)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1477)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1417)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:844)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:786)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:703)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:474)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:84)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:282)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1074)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:580)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425)
    at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:276)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:197)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:47)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4643)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5105)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1425)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1415)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
    at java.util.concurrent.AbstractExecutorService.submit(Unknown Source)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:941)
    at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:839)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1425)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1415)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
    at java.util.concurrent.AbstractExecutorService.submit(Unknown Source)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:941)
    at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:258)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.StandardService.startInternal(StandardService.java:422)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:770)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:671)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:353)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:493)
Dialect - Using dialect: org.hibernate.dialect.MySQLDialect
JdbcSupportLoader - Disabling contextual LOB creation as connection was null
TransactionFactoryFactory - Transaction strategy: org.springframework.orm.hibernate3.SpringTransactionFactory
TransactionManagerLookupFactory - No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended)
SettingsFactory - Automatic flush during beforeCompletion(): disabled
SettingsFactory - Automatic session close at end of transaction: disabled
SettingsFactory - Scrollable result sets: disabled
SettingsFactory - JDBC3 getGeneratedKeys(): disabled
SettingsFactory - Connection release mode: auto
SettingsFactory - Maximum outer join fetch depth: 2
SettingsFactory - Default batch fetch size: 1
SettingsFactory - Generate SQL with comments: disabled
SettingsFactory - Order SQL updates by primary key: disabled
SettingsFactory - Order SQL inserts for batching: disabled
SettingsFactory - Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory
ASTQueryTranslatorFactory - Using ASTQueryTranslatorFactory
SettingsFactory - Query language substitutions: {}
SettingsFactory - JPA-QL strict compliance: disabled
SettingsFactory - Second-level cache: enabled
SettingsFactory - Query cache: disabled
SettingsFactory - Cache region factory : org.hibernate.cache.impl.NoCachingRegionFactory
SettingsFactory - Optimize cache for minimal puts: disabled
SettingsFactory - Structured second-level cache entries: disabled
SettingsFactory - Echoing all SQL to stdout
SettingsFactory - Statistics: disabled
SettingsFactory - Deleted entity synthetic identifier rollback: disabled
SettingsFactory - Default entity-mode: pojo
SettingsFactory - Named query checking : enabled
SettingsFactory - Check Nullability in Core (should be disabled when Bean Validation is on): enabled
SessionFactoryImpl - building session factory
BasicTypeRegistry - Type registration [wrapper_characters_clob] overrides previous : org.hibernate.type.CharacterArrayClobType@84b9aec
BasicTypeRegistry - Type registration [clob] overrides previous : org.hibernate.type.ClobType@656ea219
BasicTypeRegistry - Type registration [java.sql.Clob] overrides previous : org.hibernate.type.ClobType@656ea219
BasicTypeRegistry - Type registration [characters_clob] overrides previous : org.hibernate.type.PrimitiveCharacterArrayClobType@3f372405
BasicTypeRegistry - Type registration [blob] overrides previous : org.hibernate.type.BlobType@75b81c7d
BasicTypeRegistry - Type registration [java.sql.Blob] overrides previous : org.hibernate.type.BlobType@75b81c7d
BasicTypeRegistry - Type registration [materialized_blob] overrides previous : org.hibernate.type.MaterializedBlobType@21f064dc
BasicTypeRegistry - Type registration [wrapper_materialized_blob] overrides previous : org.hibernate.type.WrappedMaterializedBlobType@319e7491
BasicTypeRegistry - Type registration [materialized_clob] overrides previous : org.hibernate.type.MaterializedClobType@378f69ab
PojoInstantiator - no default (no-argument) constructor for class: com.hospital.model.InPatient (class must be instantiated by Interceptor)
SessionFactoryObjectFactory - Not binding factory to JNDI, no JNDI name configured
HibernateTransactionManager - Using DataSource [org.springframework.jdbc.datasource.DriverManagerDataSource@30020ae3] of Hibernate SessionFactory for HibernateTransactionManager
ContextLoader - Root WebApplicationContext: initialization completed in 3282 ms
Jan 28, 2018 11:21:47 AM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring FrameworkServlet 'dispatcher'
DispatcherServlet - FrameworkServlet 'dispatcher': initialization started
XmlWebApplicationContext - Refreshing WebApplicationContext for namespace 'dispatcher-servlet': startup date [Sun Jan 28 11:21:47 EST 2018]; parent: Root WebApplicationContext
XmlBeanDefinitionReader - Loading XML bean definitions from ServletContext resource [/WEB-INF/dispatcher-servlet.xml]
ClassPathBeanDefinitionScanner - JSR-250 'javax.annotation.ManagedBean' found and supported for component scanning
DefaultListableBeanFactory - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@dae3613: defining beans [ViewResolver,adminController,databaseErrorHandler,doctorController,loginController,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping#0,org.springframework.format.support.FormattingConversionServiceFactoryBean#0,org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter#0,org.springframework.web.servlet.handler.MappedInterceptor#0]; parent: org.springframework.beans.factory.support.DefaultListableBeanFactory@5fefc31
DefaultAnnotationHandlerMapping - Mapped URL path [/newPatient] onto handler 'adminController'
DefaultAnnotationHandlerMapping - Mapped URL path [/newPatient.*] onto handler 'adminController'
DefaultAnnotationHandlerMapping - Mapped URL path [/newPatient/] onto handler 'adminController'
DefaultAnnotationHandlerMapping - Mapped URL path [/patient] onto handler 'adminController'
DefaultAnnotationHandlerMapping - Mapped URL path [/patient.*] onto handler 'adminController'
DefaultAnnotationHandlerMapping - Mapped URL path [/patient/] onto handler 'adminController'
DefaultAnnotationHandlerMapping - Mapped URL path [/admin] onto handler 'adminController'
DefaultAnnotationHandlerMapping - Mapped URL path [/admin.*] onto handler 'adminController'
DefaultAnnotationHandlerMapping - Mapped URL path [/admin/] onto handler 'adminController'
DefaultAnnotationHandlerMapping - Mapped URL path [/patientdashboard] onto handler 'adminController'
DefaultAnnotationHandlerMapping - Mapped URL path [/patientdashboard.*] onto handler 'adminController'
DefaultAnnotationHandlerMapping - Mapped URL path [/patientdashboard/] onto handler 'adminController'
DefaultAnnotationHandlerMapping - Mapped URL path [/newDoctor] onto handler 'doctorController'
DefaultAnnotationHandlerMapping - Mapped URL path [/newDoctor.*] onto handler 'doctorController'
DefaultAnnotationHandlerMapping - Mapped URL path [/newDoctor/] onto handler 'doctorController'
DefaultAnnotationHandlerMapping - Mapped URL path [/login] onto handler 'loginController'
DefaultAnnotationHandlerMapping - Mapped URL path [/login.*] onto handler 'loginController'
DefaultAnnotationHandlerMapping - Mapped URL path [/login/] onto handler 'loginController'
DefaultAnnotationHandlerMapping - Mapped URL path [/register] onto handler 'loginController'
DefaultAnnotationHandlerMapping - Mapped URL path [/register.*] onto handler 'loginController'
DefaultAnnotationHandlerMapping - Mapped URL path [/register/] onto handler 'loginController'
DispatcherServlet - FrameworkServlet 'dispatcher': initialization completed in 366 ms

hibernate properties file:
 ################### JDBC Configuration ##########################
    jdbc.driverClassName=com.mysql.jdbc.Driver
    jdbc.url=jdbc:mysql://localhost:3306/hospital
    jdbc.username=root
    jdbc.password=Project9

    ################### Hibernate Configuration ##########################
    hibernate.dialect=org.hibernate.dialect.MySQLDialect
    hibernate.show_sql=true
    hibernate.hbm2ddl.auto=update
    hibernate.generate_statistics=true

Mapping DAO-context.xml 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:context="http://www.springframework.org/schema/context"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-3.0.xsd
            http://www.springframework.org/schema/tx
            http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
            http://www.springframework.org/schema/mvc
            http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

    <context:annotation-config></context:annotation-config>
    <context:component-scan base-package="com.hospital.DAO, com.hospital.model, com.hospital.properties"></context:component-scan>

    <mvc:annotation-driven />

    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  <property name="location">
    <value>classpath:/hibconfig.properties</value>
  </property>
</bean>

    <tx:annotation-driven transaction-manager="transactionManager" />

    <bean   id="transactionManager"
            class="org.springframework.orm.hibernate3.HibernateTransactionManager"
            p:sessionFactory-ref="sessionFactory" />

    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="hibernateProperties">
          <props>
                <prop key="hibernate.dialect">${hibernate.dialect}</prop>
                <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
           </props>
        </property>

        <property name="packagesToScan" value="com.hospital.config,com.hospital.Controller,com.hospital.DAO,com.hospital.model"></property>
    </bean>

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"
            p:driverClassName="${jdbc.driverClassName}"
            p:url="${jdbc.url}"
            p:username="${jdbc.username}"
            p:password="${jdbc.password}"/>

</beans>

PATIENT DAO
package com.hospital.DAO;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.hospital.model.Patient;

@Repository
@Transactional
public class PatientDAO {

    @Autowired
    private SessionFactory sessionFactory;

    public int save(Patient patient)
    {
        return (Integer) sessionFactory.getCurrentSession().save(patient);
    }

    /*
    public Patient getId(int id)
    {
        return (Patient) sessionFactory.getCurrentSession().get(Patient.class, id);
    }

    public int save(Patient patient)
    {
        return (Integer) sessionFactory.getCurrentSession().save(patient);
    }
*/
}

Patient Model:
package com.hospital.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.Table;

@Entity
@Table(name="Patient")
@Inheritance(strategy = InheritanceType.JOINED)
public class Patient {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int patientid;
    @Column(name="Patient Name")
    private String pname;
    @Column(name="Age")
    private String age;
    @Column(name="Address")
    private String address;
    @Column(name="Phone Number")
    private String phoneNumber;
    @Column(name="SEX")
    private String patientSEX;
    @Column(name="Disease")
    private String disease;

    public Patient() {
        //super();
    }
    public int getPatientid() {
        return patientid;
    }
    public void setPatientid(int patientid) {
        this.patientid = patientid;
    }
    public String getPname() {
        return pname;
    }
    public void setPname(String pname) {
        this.pname = pname;
    }
    public String getAge() {
        return age;
    }
    public void setAge(String age) {
        this.age = age;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    public String getPhoneNumber() {
        return phoneNumber;
    }
    public void setPhoneNumber(String phoneNumber) {
        this.phoneNumber = phoneNumber;
    }
    public String getPatientSEX() {
        return patientSEX;
    }
    public void setPatientSEX(String patientSEX) {
        this.patientSEX = patientSEX;
    }
    public String getDisease() {
        return disease;
    }
    public void setDisease(String disease) {
        this.disease = disease;
    }
    public Patient(String pname, String age, String address, String phoneNumber, String patientSEX, String disease) {
        super();
        this.pname = pname;
        this.age = age;
        this.address = address;
        this.phoneNumber = phoneNumber;
        this.patientSEX = patientSEX;
        this.disease = disease;
    }

}


text:
Q: Django dynamic admin forms I am having trouble with some django admin functionalities
what I want to do is to have 2 fields in an admin page
and I want to achieve this
field_A
field_B
if field_A == "specific value":
exclude = ("field_B",)
else:
fields = ("field_A","field_B")
Please Help

A: at last I gave up with django manipulating the DOM (which I think it cant do on real time) and made it with a Jquery Script

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to change styles for all numbers in string in Kotlin How to change styles for all numbers in strings (from strings.xml) to (small) and (subscript) and (color.blue)? and where put that in recyclerView adapter (all strings in Array)?
Like this:

A: If you are using Kotlin, use regex to replace all the numbers with HTML formatting.
var text = "This is an example of text[1] formatting."
"\\[[0-9]+\\]".toRegex().findAll(text)
    .flatMap { it.groupValues }
    .forEach {
        val num = it.drop(1).dropLast(1)
        text = text.replace(it, "<sup>[$num]</sup>")
    }

Then use tvMyTextView.setText(Html.fromHtml(text))


text:
Q: How does function getline know newline character there I am curious about principle behind getline function defined in header string, if cin >> operator will never set second operand have any newline character, how does getline work, how does it know it's a new line there?

A: getline uses istream::get() to read one character at a time in a loop. It's then easy for getline to check if the character just read is a newline and break out of the loop.
getline doesn't use operator>>.


text:
Q: What is Sublimes CMD + D equivalent in Xcode? Ive been writing swift for months without this answer, and can't find it online.  CMD + D is too useful a command in sublime to not have an Xcode equivalent.  Can anyone please tell me what it is.

A: From at least Xcode 12.4 and above, this functionality is available as "Select Next Occurrence" in the "Find" menu, and as Option + CMD + E.
Select some text. Hit Option + CMD + E to add the next occurrence, resulting in multiple cursors so you can edit all of them at once.

A: I can't find this feature in Xcode, so I build it as an Xcode extension lol.
Please try! https://github.com/hlung/XcodeExtensions


text:
Q: Where can I find this Inspirational Story? OK this is not exactly a sci-fi story as a matter fact it's not a sci-fi story at all. It's actually an inspirational story which was something I ran across a few years back and for the life of me cannot find it again.
It's a story about a man who visited the Olympian gods and was put to several tests to prove his worth to become a god.  The gods had belittled him but they said that he could prove himself by performing some simple feats.
I don't remember all of them but they were seemingly simple things he was asked to do around the temple, one was to try to lift a pillar is a column another was to drink from a basin of water and then there were several others. The end of the story was that the man left disappointed  because he could not do any of tasks sucessfully but the gods have been shaken because the pillar was actually a corner of the earth  and although he did not lift it he was able to move it.  And the basin was all the seven seas and he had almost drained them  and the others were also hidden as values for other things.
It's a great story that illustrates that the things that we do we sometimes don't know how much of an impact we are making.
If anyone knows the story or better yet know where to find it please let me know I would be grateful.

A: I'm reasonably sure this is actually one of the Norse Eddas, the source tales that deal with Thor, the God of Thunder and his antics. Thor's Journey to the Land of the Giants features all of the aspects you're talking about as well as the twist ending.

I have deluded thee with vain shows; first in the forest, where I met
  you, and where you were unable to untie the wallet because I had bound
  it with iron-thread so that you could not discover where the knot
  could be loosened. After that you gave me three blows with your
  hammer. The first blow, though the lightest, would have killed me had
  it fallen on me, but I put a rock in my place which you did not see.
  In that rocky mountain you will find three dales, one of which is very
  deep, those are the dints made by your hammer. In the other games, I
  have deceived you with illusions. The first one was the match with
  Loki. He was hungry and eat fast, but Logi was Flame, and he consumed
  not only the flesh but the trough with it. When Thjalfi contended with
  Hugi in running, Hugi was my thought, and it was not possible for
  Thjalfi to excel that in swiftness. When you drank of the horn and the
  liquor seemed to get lower so slowly, you did, indeed, so well that
  had I not seen it, I should never have believed it. You did not see
  that one end of the horn was in the sea, but when you come to the
  shore you will see how much the sea has shrunk in consequence of your
  draughts, which have caused what is called the ebb. Nor did you do a
  less wondrous thing when you lifted up the cat, and I can assure you
  all were afraid when you raised one of its paws off the ground. The
  cat was the great Midgard serpent which lies stretched round the whole
  earth, and when you raised it so high then did its length barely
  suffice to enclose the earth between its head and tail.


text:
Q: pgfplots and log scale: bars starting from the bottom of the screen The following MWE
\documentclass{standalone}
\usepackage{tikz}
\usepackage{pgfplots}
\begin{document}
\begin{tikzpicture}
\begin{axis}[ybar,ymode = log]
\addplot coordinates{
(1,1e-15)
(2,1e-14)
(3,1e-13)
};
\end{axis}
\end{tikzpicture}
\end{document}

compiles to this bar chart:

I'd like the bars to start from the bottom of the screen instead of the top, since it makes more sense to visualize my data like that (they are computational errors).
Is there a pgfplots option to achieve that? The manual only says that the bars always start from 0 (and there is no way to change that); clearly, when ymode=log this is interpreted as starting from log(1)=0, which is not what I want here.

A: You can define where the "drawing origin" for logarithmic plots should be by setting log origin to either 0 or infty. If you set it to 0, which is the default, bar plots, comb plots and filled area plots will start from log(1)=0, so in this case the top of the plot. If you set it to infty, the plots will start from the bottom edge of the plot area, which is what you want in this case:

\documentclass{standalone}
\usepackage{tikz}
\usepackage{pgfplots}
\begin{document}
\begin{tikzpicture}
\begin{axis}[ybar,ymode = log, log origin=infty]
\addplot coordinates{
(1,1e-15)
(2,1e-14)
(3,1e-13)
};
\end{axis}
\end{tikzpicture}
\end{document}


text:
Q: Creating lambda inside a loop I am trying to create lambdas inside a loop that iterates over a list of objects:
lambdas_list = []
for obj in obj_list:
   lambdas_list.append(lambda : obj.some_var)

Now, if I iterate over the lambdas list and call them like this:
for f in lambdas_list:
    print(f())

I get the same value. That is the value of the last obj in obj_list since that was the last variable in the block of the list iterator. Any ideas for a good (pythonic) rewrite of the code to make it work?

A: You can do something like that:
def build_lambda(obj):
  return lambda : obj.some_var

lambdas_list = []
for obj in obj_list:
   lambdas_list.append(build_lambda(obj))

A: Use this line instead:
lambdas_list.append(lambda obj=obj: obj.some_var)

A: You either have to capture the variable using default assignments

lambdas_list = [ lambda i=o: i.some_var for o in obj_list ]

or, use closures to capture the variable

lambdas_list = [ (lambda a: lambda: a.some_var)(o) for o in obj_list ]

In both cases the key is to make sure each value in the obj_list list is assigned to a unique scope.
Your solution didn't work because the lexical variable obj is referenced from the parent scope (the for).
The default assignment worked because we reference i from the lambda scope.  We use the default assignment to make "passing" the variable implicit by making it part of the lambda definition and therefore its scope.
The closure solution works because the variable "passing" is explicit, into the outer lambda which is immediately executed, thus creating the binding during the list comprehension and and returning the inner lambda which references that binding.  So when the inner lambda actually executes it will be referencing the binding created in the outer lambda scope.


text:
Q: Why won't Vagrant ssh into my virtual box when I use `Vagrant Up` on Windows 7 command line? Whenever I try to Vagrant Up it will load the box and do most everything right, but because I'm trying to use Puppet to provision this CentOS 6.3 minimal I need SSH to work during Vagrant Up (if I want it as autonomous as possible).
I get the following information from Vagrant's INFO log:
DEBUG virtualbox_4_2:   - [1, "ssh", 2222, 22]
 INFO ssh: Connecting to SSH: 127.0.0.1:2222
 INFO ssh: SSH not up: #<Timeout::Error: execution expired>
 INFO subprocess: Starting process: ["C:\\Program Files\\Oracle\\VirtualBox\\VBoxManage.exe", "showvminfo", "c2e7375d-159f-4014-9bda-ff9914423f4c", "--machinereadable"]
DEBUG subprocess: Selecting on IO
DEBUG subprocess: stdout: name="Vagrant-Apache-Nick_1360372174"

A: During Vagrant Up your Windows system tries to connect to SSH. If you type on your command line:
set VAGRANT_LOG=INFO

You may see it fail and try a couple of times. It looks like this:
INFO ssh: Connecting to SSH: 127.0.0.1:2222

This is happening because the timeout is set to 10. This can be modified by placing the following in your Vagrantfile:
config.ssh.timeout = 300

You can use any number you like but I recommend something above 100.
Sources:

*

*This guy had some useful troubleshooting information.

*Vagrant Docs for Vagrantfiles

*Vagrant Docs for Vagrantfile SSH Timeout

*Vagrant Docs for Debugging

*Hours of Troubleshooting (Keep Smilin')

A: I know I'm WAY late to this post, but I did have nearly the exact same problem for a full day before I simply removed Hyper-V from Windows and it magically solved my issue.
I guess when I was testing with Docker for Windows (not to be confused with docker-machine) it goofed my Hyper-V somehow. Not 100% sure why this tweaked fixed this issue, but it worked like a charm after Docker for Windows seemed to fubar my VirtualBox (Docker for Windows and Local by FlyWheel / VirtualBox conflict with each other).

Hopefully this helps someone out!


text:
Q: Adding array values to a sorted array in C I am measuring Aavin[4] (5 voltage values) in an Array. For every aavin I also measure At[4] (Temperature values). Now to make a calibration function I have to sort the Aavin values from the biggest number to the smallest, but the Temperature varies so I cannot sort it.
I use qsort for aavin. The problem is, when I measured f.e. Aavin[0] = 1; At[0] = 1 and sort the Aavin Array, At[0] will no more be the temperature from Aavin[0] since Aavin[0] is now f.e. Aavin[3].
Does somebody have any idea how I could sort At[] so the value in the column is matched to the column of the sorted Aavin[] array? Or maybe stick the Values of At[] to the associated Aavin[]?
Here is my code:
void sortier(){

qsort(mess.Aavin, 4, sizeof(double),cmpfunc);

//qsort(kali.ApH, 4, sizeof(double),cmpfunc);
}

Here is the problem with the At:
sortier();

for (int i = 0; i<4; i++) && (int a = 4; i>0, i--){
    mess.stc[i] = ((mess.Aavin[a] - mess.Uref) - (mess.Aavin[a-1] - mess.Uref))
            / (kali.ApH[a] - kali.ApH[a-1]);//pHA von simon *******************************
    mess.tcal[i] = (mess.At[a] + 273.1 + mess.At[a-1] + 273.1) / 2;
    mess.Stcal[i] = (double) mess.stc[i] / mess.tcal[i];
}
}

A: Don't sort the array itself, sort a new array with indexes...
int Aavin[4] = {2, 6, 3, 1};
int At[4] = {12, 16, 13, 11};
int indexes[4] = {0, 1, 2, 3};

// sort indexes ==> indexes = {1, 2, 0, 3}
// cannot use qsort (unless you make Aavin a global array [don't do that])
// write your own sort function
for (int k = 0; k < 4; k++) {
    printf("%d, %d\n", Aavin[indexes[k]], At[indexes[k]]);
}


text:
Q: Unique constraint with column from parent table I have a table structure;

The ExternalArticle's are the different order numbers for all Article variations from a Relation.
ExternalArticle has column OrderCode which should be unique for all ExternalArticle's from a Relation.
But Relation is only present in parent table Article not in table ExternalArticle.
Now, how do i create unique constraint RelationId-OrderCode in ExternalArticle?
Do i have to insert a 'redundant' RelationId column in ExternalArticle fro this unique constraint?


text:
Q: Tire returning empty array I am using elasticsearch to make my search fast, but unfortunately i don't know the reason why it is returning an empty array of result. Looking forward a help from you guys.
class Post < ActiveRecord::Base
    include Tire::Model::Search
    include Tire::Model::Callbacks

    has_many :attachments, as: :attachable
    accepts_nested_attributes_for :attachments, allow_destroy: true

    mapping do
        indexes :work_type
        indexes :title
        indexes :location
        indexes :industry_type
        indexes :key_words
        indexes :type
    end

    after_save { update_index }

    def self.search(params)
        tire.search(load: true) do
            query do
                boolean do
                    must   { string                              params[:query] }         if params[:query].present?
                    must   { match :type,          params[:type] }          if params[:type].present? && params[:type] != "all"
                    must   { match :title,         params[:title] }         if params[:title].present?
                    must   { match :industry_type, params[:industry_type] } if params[:industry_type].present?
                    must   { match :key_words,     params[:key_words] }     if params[:key_words].present?
                end
            end

            sort { by :title, 'desc' }
        end
    end

params = {"utf8"=>"✓",
 "type"=>"Job",
 "query"=>"",
 "location"=>"",
 "post"=>{"work_type"=>""},
 "action"=>"index",
 "controller"=>"posts"}


text:
Q: How to prepare for segue and send data from 1 label to another? I am developing a QR code reader application. Here is the code:
var captureSession: AVCaptureSession?
var videoPreviewLayer: AVCaptureVideoPreviewLayer?
var qrCodeframeView: UIView?

@IBOutlet weak var CancelButton: UIButton!
@IBOutlet weak var Label: UILabel!
override func viewDidLoad() {

    CancelButton.hidden = true
    Label.hidden = true

    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

@IBAction func ScanMe(sender: AnyObject) {

    CancelButton.hidden = false
    Label.hidden = false

    let captureDevice = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)

    var error: NSError?
    let input: AnyObject!

    do {
        input = try AVCaptureDeviceInput (device: captureDevice)
    } catch let error1 as NSError{

        error = error1
        input = nil

    }

    if (error != nil){
    print ("\(error?.localizedDescription)")
        return
    }
    captureSession = AVCaptureSession()

    captureSession?.addInput(input as! AVCaptureInput)

    let captureMetadatOutput = AVCaptureMetadataOutput()
    captureSession?.addOutput(captureMetadatOutput)

    captureMetadatOutput.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue())
    captureMetadatOutput.metadataObjectTypes = [AVMetadataObjectTypeQRCode]

    videoPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
    videoPreviewLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill
    videoPreviewLayer?.frame = view.layer.bounds
    view.layer.addSublayer(videoPreviewLayer!)

    captureSession?.startRunning()
    view.bringSubviewToFront(Label)
    view.bringSubviewToFront(CancelButton)

    qrCodeframeView = UIView()
    qrCodeframeView?.layer.borderColor = UIColor.greenColor().CGColor
    qrCodeframeView?.layer.borderWidth = 2
    view.addSubview(qrCodeframeView!)
    view.bringSubviewToFront(qrCodeframeView!)

}

func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!) {

    if metadataObjects == nil || metadataObjects.count == 0 {

        qrCodeframeView?.frame = CGRectZero
        Label.text = "No QR code detected"
        return
    }
    let metadateObj = metadataObjects[0] as! AVMetadataMachineReadableCodeObject

    if metadateObj.type == AVMetadataObjectTypeQRCode {

        let BarcodeObject = videoPreviewLayer?.transformedMetadataObjectForMetadataObject(metadateObj as AVMetadataMachineReadableCodeObject) as! AVMetadataMachineReadableCodeObject
        qrCodeframeView?.frame = BarcodeObject.bounds

        if metadateObj.stringValue != nil {

            Label.text = metadateObj.stringValue

            captureSession?.stopRunning()

 }
  }
 }

@IBAction func Cancel(sender: AnyObject) {
    CancelButton.hidden = true
    Label.hidden = true

    captureSession?.stopRunning()
    qrCodeframeView?.removeFromSuperview()
    videoPreviewLayer?.removeFromSuperlayer()

}

@IBAction func Open(sender: AnyObject) {

}
   override func prepareForSegue(segue: UIStoryboardSegue, sender:   AnyObject?) {
        var PC : SecondSecondViewController = segue.destinationViewController as! SecondSecondViewController
   PC.label1 = Label.text!
  }

  }

When I write the function prepareForSegue, I am trying to send the data from Label.text (the result from the scan) to label1 in my next UIViewController. Unfortunately, Label.text is colored in red (cannot assign value of type String to type UILabel).
Do you have any idea how can I manage that? (I want only to send the scanned information to the other UIViewController)

A: Change in this:
PC.label1.text = Label.text!

You are trying to assign a String to a variable of type UILabel instead of its text value.

A: Try this:
In your destination VC - SecondViewController add this variable:
var labelText : String = ""

in the same class add this line into viewDidLoad() method:
label1.text = labelText

Then you need to access that string variable and put the value in it.
override func prepareForSegue(segue: UIStoryboardSegue, sender:   AnyObject?) {
        var PC : SecondSecondViewController = segue.destinationViewController as! SecondSecondViewController
        PC.labelText = Label.text!
}

A: PC.label1  unable to load data set PC.label1.text
try this way
override func prepareForSegue(segue: UIStoryboardSegue, sender:   AnyObject?) {
            var PC : SecondSecondViewController = segue.destinationViewController as! SecondSecondViewController
       PC.label1.text = Label.text!
      }

A: add PC.label1.text = Label.text!


text:
Q: FFmpeg, Icecast and metadata I use FFmpeg streaming to the Icecast server on my Windows machine in the following way (sound card line in):
ffmpeg -f dshow -channels 2 -i audio="Line In" -codec:a libmp3lame -b:a 128k -legacy_icecast 1 -content_type audio/mpeg -ice_name "Radio test 1" -ice_description "This is Radio test 1" -ice_genre "Rock" -ice_url "http://www.radiotest.com" -f mp3 icecast://source:password@ip:port/mountpoint

This works ok.
But I noticed an Icecast statistics that FFmpeg do not send "audio_info" metadata to Icecast while than edcast/altacast etc send it. And edcast/altacast do not send "user_agent" while FFmpeg is forced to send it.
Do I get FFmpeg to send "audio_info" metadata to Icecast?

A: There's no way to have it send the per-track metadata from FFmpeg.  You'll have to send metadata updates out-of-band using another script.

A: For MP3 this can't work as MP3 streaming does not support proper metadata. You will need an extra script that calls Icecasts metadata update endpoint.
For Ogg this can work but afaik not with FFmpeg as there is no way to trigger it to add metadata and start a new chained Ogg "segment".

A: Can't comment but here is a start..
/**
 * Please be aware. This gist requires at least PHP 5.4 to run correctly.
 * Otherwise consider downgrading the $opts array code to the classic "array" syntax.
 */
function getmp3StreamTitle($streamingUrl, $interval = 19200)
{
    $needle = 'StreamTitle=';
    $ua = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.110 Safari/537.36';
    $opts = array('http' => array(
        'method' => 'GET',
        'header' => 'Icy-MetaData: 1',
        'user_agent' => $ua
    ));

    $context = stream_context_create($opts);

    $stream = fopen($streamingUrl, 'r', false, $context);
    if(!$stream) throw new Exception("Unable to open stream [{$streamingUrl}]");

    while(true) {
        $buffer = stream_get_contents($stream, $interval);
        if($buffer === false) throw new Exception('Could not read from stream.');

        if(strpos($buffer, $needle) !== false)
        {
            $text = explode($needle, $buffer)[1];
            $songtext = substr($text, 1, strpos($text, ';') - 2);
            break;
        }
    }

    fclose($stream);

    return $songtext;
}

ini_set('display_errors', 1);
header('Content-type: application/json');


text:
Q: Problemas com menu dropdown Estou fazendo um site e utilizando o dropdown , porém, eu não consigo usar 2 dropdowns em uma página, só consigo usar 1.
Já pesquisei e encontrei algo sobre usar classes, mas não sei como isso funciona e nem como aplicar ao código. Alguém poderia me ajudar ??
ATUALIZADO:15:52 [16/07]
Então, mudei o código, consegui fazer aparecer os dois dropdowns, só que fica um embaixo do outro e eu quero que eles fiquem lado-a-lado. Já tentei usar o float(inclusiva está no código), mas não está influenciando no código.
CSS:
#mainnav ul li  {
margin: 0;
padding: 0;
list-style: none;
width: 230px;
}

.wrapper-menu {
    float:left
    position: relative;
    }

.dropdown {
    position: absolute;
    left: 220px;
    top: 300;
    display: none;
    }

ul li a {
    display: block;
    text-decoration: none;
    color: #CCC;
    background: #006;
    padding: 5px;
    border: 0px solid #ccc;
}

li:hover ul {
     display: block ;
            }

ul li a:hover{
    text-decoration:underline;
    font-weight: bold;
    background: #006;
    -webkit-box-shadow:0 3px 10px 0 #FFF;
text-shadow:0px 0px 5px #000;

}

#pai {
width:90%;
margin:auto;
#esquerda {
width:70%;
float:left;
}

#esquerda {
width:230px;
float:left;
}

#direita {
width:300px;
float:right;
}

#clear {
clear:both;
}

HTML:

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Untitled Document</title>

    <link href="../css/dropdown2(classes).css" rel="stylesheet" type="text/css" />

    <link href="../css/dropdown.css" rel="stylesheet" type="text/css" />

TEXTO1

texto2

texto3

texto4

texto5

TEXTO6

texto7

texto8

texto9

texto10

A: Veja se é isso que precisa. Seria legal vc colocar seu html na sua pergunta. Vc apenas colocou os links para sua folha de estilos.

<!DOCTYPE html>

    Dropdown1

      Link 1
      Link 2
      Link 3

News

    Dropdown2

      Link 1
      Link 2
      Link 3

Se alguma das respostas estiver correta, poderia validar, clicando na validação abaixo das setas de avaliação.

Qualquer dúvida comenta que agente ajusta.
Fonte w3schools

A: Bom dia, seria interessante vc postar também o html, mas de uma olhada no bootstrap que vc vai entender melhor olhe por exemplo este link http://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_navbar_dropdown&stacked=h
exemplo:

      WebSiteName

Home

Page 1

Page 1-1

Page 1-2

Page 1-3

Page 2

Page 1
2-1

Page 2-2

Page 2-3

Page 3


text:
Q: How to pass an image in Secondary Tile in windows phone 8 I'm looking for a way to pass an image as the string and covert it to image type BitmapImage on the next page since I know that we could not pass an image itself to the next page or trying to serialize imageSource by any phone state, it will give an error. What I have been trying is passing it as part of uri parameter and get it by using NavigationContext.QueryString but the data I got out of it is always "{System.Windows.Media.Imaging.BitmapImage}"; therefore, no image display on the page. Understanding that I could use "PhoneApplicationService.Current.State as BitmapImage" to show the image, but in my application, I want to use Secondary Tile which is linked directly to the pinned page and passby all its previous pages; therefore, the when the application is launched from secondary tile, the PhoneApplication.Current.State is not populated as expected. So, I don't reply completely on any phone state for Secondary Tile.
Is there any alternative to overcome this, could you advise by showing an example?
My current code: Product Detail.xaml.cs
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            /***
             *
             *  Trying to get image from uri parameter and covert it to BitmapImage using getImage(string) method in App.xaml.cs
             *
             *   public ImageSource getImage(string p)
                {
                    return new BitmapImage(new Uri(p, UriKind.Relative));

                }
             *
             * */

            item_image.Source = ((App)Application.Current).getImage(NavigationContext.QueryString["pro_image"]);

            if (!(IsolatedStorageSettings.ApplicationSettings.Contains("item_name")))
            {
                IsolatedStorageSettings.ApplicationSettings.Add("item_name", PhoneApplicationService.Current.State["pro_name"]);

            }

            ShellTile secondaryTile = this.FindTile(SecondaryTileUriSource);

            if (secondaryTile != null)
            {

                // *****************************************************      tile.Delete();

                txtb_product_name.Text = PhoneApplicationService.Current.State["pro_name"] as string;

                txtb_product_name.Text = PhoneApplicationService.Current.State["pro_name"] as string;

            }
        }

Here is the produt list.xaml.cs where a list of products is listed for user to select one, and all related information about this selected product it will be show at Product Detail.xaml page.
Product list.xaml.cs
  private void lst_product_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (lst_product.SelectedItem != null)
            {
                PhoneApplicationService.Current.State["pro_name"] = (lst_product.SelectedItem as ProductsDry).ItemDryName;
                PhoneApplicationService.Current.State["pro_id"] = (lst_product.SelectedItem as ProductsDry).ItemDryId;
              PhoneApplicationService.Current.State["pro_image"] = (lst_product.SelectedItem as ProductsDry).ItemDryImage;
                PhoneApplicationService.Current.State["ItemDryIngridient"] = (lst_product.SelectedItem as ProductsDry).ItemDryIngredients;
                PhoneApplicationService.Current.State["ItemDryUse"] = (lst_product.SelectedItem as ProductsDry).ItemDryUse;
                PhoneApplicationService.Current.State["ItemDryDesc1"] = (lst_product.SelectedItem as ProductsDry).ItemDryDesc1;
                PhoneApplicationService.Current.State["ItemDryDesc2"] = (lst_product.SelectedItem as ProductsDry).ItemDryDesc2;
                PhoneApplicationService.Current.State["ItemDryUse"] = (lst_product.SelectedItem as ProductsDry).ItemDryUse;

                IsolatedStorageSettings.ApplicationSettings.Clear();
                NavigationService.Navigate(new Uri("/All Files/Product Files/Dry/Product Detail.xaml?&pro_name=" + (lst_product.SelectedItem as ProductsDry).ItemDryName + "&pro_image=" + (lst_product.SelectedItem as ProductsDry).ItemDryImage, UriKind.Relative));
            }
            else return;
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);
            IsolatedStorageSettings.ApplicationSettings.Clear();
        }

On the product detail page, user can pin the page for his favorite product, at here I have problem with image that send from product list to product detail.
Let me know if you need further information, thanks.


text:
Q: Failed to copy list of files to another folder I have a text file called "list.txt" that contain all the directories of the files that need to be copied to a new folder (dir_newfolder). I wrote the code like below:
for file in $(cat list.txt);  do cp ${file} dir_newfolder;  done
I got list of errors: cp:"file_name":No such file or directory. The file_names are the lines pulled out from the "list.txt". But when I copy each file_names from the error message and use cp to copy to the new folder. There is no error.
I am using mac os terminal.
Thanks in advance.

A: Copy a file or folder locally
In the Terminal app  on your Mac, use the cp command to make a copy of a file.
For example, to copy a folder named Expenses in your Documents folder to another volume named Data:
% cp -R ~/Documents/Expenses /Volumes/Data/Expenses

The -R flag causes cp to copy the folder and its contents. Note that the folder name does not end with a slash, which would change how cp copies the folder.
in your case:
make sure you are providing correct path list.txt and the correct path for destiny folder, also i mentioned how to access file variable in double quotes , try this code it's working for me
for file in $(cat ~/Documents/list.txt);  do cp "$file" ~/dir_newfolder;  done


text:
Q: Why is a wave function time dependent? Why is a wave function time dependent? And what does it physically mean when the probability density density function is varying with time. I'm not getting how to physically interpret that. Will taking example of a particle in 1d box with superposition state two energy levels help? Because it's simplest system(I can think of) whose probability density is time dependent.
Edit: I'm not looking for a proof or a mathematical explanation of how it depends on time but I'm questioning why should the wavefunction depend on time. I am getting answers derived from time dependent Schrodinger's equation but then we are already assuming that wave function time dependent. So to be more clear my intent was question "where is the time dependence of Schrodinger's equation coming from? Where did the time dependence come from?"
Edit: I actually started questioning about why the probability density of superposition of states is time dependent, on second look I realised it came from the time dependence of wave function and that again was because of time dependence term in Schrodinger's equation.
Probability density<--wave function<---schrodingers equation<--- [???????]
Is it the end or any more layers are there?
Please go down as many layers as possible.

A: Any equation claiming to describe fundamental process has to have time. We know that in nature system changes with time. They are not static. For example, absorption of a photon by a hydrogen atom is a dynamic process and we need to have a theory which can predict this dynamical process in time. Since Schrodinger equation is supposed to be an equation describing nature, time needs to get involved somewhere.
The question then is why did Schrodinger choose this particular equation? There is no rigorous argument to that. If you read Schrodinger's original paper, you will see that Schrodinger used Hamilton Jacobi Equation, $H(q,\frac{\partial S}{\partial q})-\frac{\partial S}{\partial t}=0$. He replaced action $S$ by, $$\psi=e^{KS},$$
where $K$ is some constant with the dimension of action (seems familiar?). He then postulates that integral of the left-hand side of above equation should be extremized. This leads to Schrodinger Equation. The factor of time derivative in Schrodinger equation comes from the term $\frac{\partial S}{\partial t}$ in Hamilton Jacobi Equation.
Above procedure may seem, and is, ad-hoc. But he was able to calculate energy spectrum of Hydrogen atom successfully with it. He also wrote a paper in which he sort of gives motivation for this procedure. He used the geometrical formulation of Hamilton Jacobi Equation and argued that quantum physics differ from classical in the same way wave optics differ from geometric optics.
In short, we require wave function to have time dependence if it has to describe nature. The way this dependence was introduced by Schrodinger is little bit shaky but not entirely bogus. I would suggest you to read his original papers if you want to understand his motivation.

A: Wavefunctions can be time-dependent because the time-dependent Schrodinger equation is linear: the sum of two time-dependent solutions is also a solution.   Thus the general solution will be a sum of time-dependent solutions
$$
\Psi(x,t)=\sum_k a_k\psi_k(x)e^{-i E_k t/\hbar} \tag{1}
$$
where the coefficients $a_k$ are determined from the initial conditions.
In many practical situations, the states of interest are not eigenstates of the Hamiltonian because of initial conditions (or alternatively because of measurements).  A famous example is the tunnelling of nitrogen atoms through the hydrogen plane in an ammonia molecule (see this discussion of ammonia inversion).  In this case the nitrogen atom is found to oscillate "above" or "below" the hydrogen plane: the probability density is certainly time-dependent.
For a particle in a box, an example might be a system described at $t=0$ by a wave function initially heavily concentrated in the left half of the well of width $L=1$:
$$
\Psi(x,0)= \sqrt{858}x(x-1)^5\,  ,\tag{2}
$$
with initial probability distribution given by the figure below:

Expanding (1) in eigenstates of the square well will produce a sum of the type (1).  The first few $a_k$'s are
$$
\begin{array}{l}
a_1=-\frac{20 \sqrt{429} \left(\pi ^2-12\right)^2}{\pi ^7}=-0.622487\, ,
\\
a_2=-\frac{5 \sqrt{429} \left(\pi ^2-6\right)}{2 \pi ^5}=-0.654766\, , \\
a_3=-\frac{20
   \sqrt{\frac{143}{3}} \left(4-3 \pi ^2\right)^2}{81 \pi ^7}=-0.370154\, ,\\
   a_4=-\frac{5 \sqrt{429} \left(2 \pi ^2-3\right)}{32 \pi^5}=-0.177025\, ,\\
   a_5=-\frac{4 \sqrt{429} \left(12-25 \pi ^2\right)^2}{15625 \pi ^7}=-0.0967373\, .
   \end{array}
$$
The sum of (1) extends to $\infty$ but already the sum
$\sum_{k=1}^4 a_k^2=0.985$ indicating that all other eigenstates have a small contribution to the full wavefunction and thus do not affect much the evolution of the full wavefunction.


text:
Q: Asymptotics of unrooted labeled forests It is well known that the number of unrooted labeled trees on vertex set
$[n]={1,2,...,n}$ is $n^{n-2}$. Let $U(z)$ be the exponential generating function of the sequence of these numbers. Then $F(z)=\text{exp}(U(z))$ is the exponential generating function for the number of unrooted forests of $[n]$.
My question is, how do you prove that $n![z^n]F(z) \sim e^{1/2} n^{n-2}$.
In other words, that is the asymptotic  number of unrooted forests on $[n]$. I found this result on page 406 of the Flajolet-Sedgewick book, without proof.
If that helps, $U(z)= T(z) - T(z)^2 /2$ , where $T(z)$ is the exponential generating function for the numbers of rooted trees. But while $T(z)$ satisfies the relation $T=z \ \text{exp}(T)$, I could not find such a relation for F.

A: The idea in the book by Flajolet-Sedgewick is to use singularity analysis. The generating function $F(z)=\exp(U(z))$ with $U=T-T^2/2$ inherits the dominant singularity $e^{-1}$ of $T(z)=-W(-z)$, where $W$ is the Lambert $W$ function. From the local expansion of $T(z)$
$$T(z)=1-\sqrt{2}\sqrt{1-ze}+\frac{2}{3}(1-ze)-\frac{11\sqrt{2}}{36}(1-ze)^{3/2}+O((1-ze)^2),\quad z\rightarrow e^{-1}$$
follows that of $F$:
$$F(z)=e^{1/2}\left(1-(1-ze)+\frac{2\sqrt{2}}{3}(1-ze)^{3/2}+O((1-ze)^2)\right).$$
From there, singularity analysis is straightforward. The asymptotic behaviour of the coefficients comes from the term in $(1-ze)^{3/2}$, leading to
$$[z^n]F(z)\sim \frac{e^{1/2}}{\sqrt{2\pi}}n^{-5/2}e^{n}.$$
That coefficient is the number of unrooted labeled trees divided by $n!$, so that multiplying by Stirling's formula gives the desired $e^{1/2}n^{n-2}$.

A: Here's a proof, following section 4.3 of J.W. Moon's book "Counting Labelled Trees".
First, we have the following formula of Rényi (see this post for a proof and reference) for $f_k(n)$, the number of forests on $n$ vertices consisting of $k$ unrooted trees.
$$ f_k(n)= \binom nk \sum_{i=0}^k  \left(-\frac12\right)^i (k+i)\,i!\, \binom{k}{i}\binom{n-k}{i} n^{n-k-i-1}.$$
Note that $U^k/k!$ is the generating function for forests of $k$ trees, so we have:
\begin{align}
\sum_{n=k}^\infty f_k(n)\frac{x^n}{n!} &= \frac{U^k}{k!}\\
&=\frac{1}{k!}(T-T^2/2)^k\\
&=\frac{1}{k!}\sum_{i=0}^k\binom{k}{i}(-1/2)^iT^{k+i}.
\end{align}
Thus $f_k(n)$ is the coefficient of $x^n$ on the right hand side. This can be determined using the following formula:
$$\frac{T^k}{k!} = \sum_{n=k}^\infty\binom{n}{k}kn^{n-k-1}\frac{x^n}{n!}.$$
To prove this, apply the Lagrange–Bürmann formula to $f(x)=T(x)$, $\phi(x)=e^T$, and $H(T)=T^k$ (see also section 4.2 of Moon's book).
To determine asymptotics, we only need to compute the coefficient of $n^{n-h}$ in the formula for $f_k(n)$. Denote this by $c(k,h)$. Then "after some simplification":
$$c(k,1)=\frac{1}{k!}\sum_{i=0}^k(-1/2)^i\binom{k}{i}(k+i)=0,$$
and
$$c(k,2)=-\frac{1}{k!}\sum_{i=0}^k(-1/2)^i(k+i)\binom{k}{i}\binom{k+i}{2}=\frac{(1/2)^{k-1}}{(k-1)!}.$$
Thus $\lim_{n\rightarrow\infty}\frac{f_k(n)}{n^{n-2}}=\frac{(1/2)^{k-1}}{(k-1)!}.$
The result follows after applying Tannery's theorem to sum these limits over all $k$:
$$\lim_{n\rightarrow\infty}\frac{N(n)}{n^{n-2}}=\sum_{k=1}^\infty\frac{(1/2)^{k-1}}{(k-1)!}=e^{1/2},$$
where $N(n)$ is the total number of rooted forests on $n$ nodes, as desired.


text:
Q: Flutter - 'onSurface' is deprecated and shouldn't be used. Use disabledForegroundColor and disabledBackgroundColor instead In flutter version 3.3.0 ElevatedButton onSurface is deprecated i am confused which property should i use instead onSurface. should i use disabledForegroundColor or disabledBackgroundColor or Both?

A: If you need to change both text and button color for disabled state, you should use both disabledForegroundColor and disabledBackgroundColor.
But
using normally only the disabledBackgroundColor should be enough for the button.

A: Use foregroundColor and disabledForegroundColor instead of  onSurface.
style: ElevatedButton.styleFrom(
  foregroundColor:Colors.red,
  disabledForegroundColor:Colors.green,


text:
Q: Font size becomes small when the text is too long in kartik/mpdf of Yii framework 2. How to fix that? Working with Yii framework 2, I use kartik\mpdf\Pdf class to response my HTML page in PDF format to the browser. Below is my configuration.
$pdf = new kartik\mpdf\Pdf([
                // set to use core fonts only
                'mode' => Pdf::MODE_CORE,
                // A4 paper format
                'format' => Pdf::FORMAT_A4,
                // portrait orientation
                'orientation' => Pdf::ORIENT_PORTRAIT,
                // stream to browser inline
                'destination' => Pdf::DEST_BROWSER,
                // your html content input
                'content' => $htmlContent,
                // format content from your own css file if needed or use the
                // enhanced bootstrap css built by Krajee for mPDF formatting
                'cssFile' => '@vendor/kartik-v/yii2-mpdf/assets/kv-mpdf-bootstrap.min.css',
                // any css to be embedded if required
                'cssInline' => '.kv-heading-1{font-size:18px} .page-break{ page-break-after:always; } li { list-style:none; }',
                 // set mPDF properties on the fly
                'options' => ['title' => 'My title'],
                 // call mPDF methods on the fly
                'methods' => [
                    'SetHeader'=>['My_header_ ' . date('d-m-Y')],
                    'SetFooter'=>['{PAGENO}'],
                ],
 ]);

 // return the pdf output as per the destination setting
 return $pdf->render();

Everything works perfectly, except when there is a variable inside my HTML page, which returns a long string, that text becomes small. How can I solve it?

A: mPDF resizes too large tables to fit a page. To prevent this, either add
'options' => ['shrink_tables_to_fit' => 0];

to your kartik\mpdf\Pdf constructor call OR set a custom HTML attribute
<table autosize="0">

Also see mPDF manual on tables.


text:
Q: Good technique for connections with PostgreSQL I am using Npgsql to access PostgreSQL via .NET. I am concerned about the right way to perform connections to the database, since in my opinion this is an expensive operation to open a connection and then close it every single time I want to perform some transaction.
So here is the general idea:
public class PostgreSQL
{
    private NpgsqlConnection conn; // <- one connection for this object, open all the time

    public PostgreSQL(string connString)
    {
        conn = new NpgsqlConnection(connString);
        conn.Open();
    }

    // ...here making some queries...

    public void Close() => conn.Close(); // <- use this in the very end of the program
}

As you can see above, I have one connection for an instance of PostgreSQL class.
My question:
Is this approach right? Or should I open and close connection every single time I want to make a transaction - open as late as possible and close as soon as possible?
If I should open and close connections every single time - should I write a queue that would limit the amount of concurrent connections? Or PostgreSQL will handle it itself - and, theoretically, I can open 200 connections and it will be alright.
Please share your experience with me ^^
EDIT:
I will run 100-200 queries a second.

A: PostgreSQL supports connections pooling (pool size is customizable) so the common pattern:
using (NpgsqlConnection conn = new NpgsqlConnection(...))
{
...
}

should be the better choice.

A: In my opinion you should open a connection at the moment you need it, and close it right after it. This will prevent a lot of connections on the server to be kept alive.
In my experience, opening a connection doesn't take that much time (a few milliseconds, usually a fraction of your execution time), so you don't have to worry too much.


text:
Q: STRIPE.JS Error Stripe.js
Trying to implement Stripe in a project and i keep getting this error
Any idea what should i do ???
Stripe is not defined fix or add /global $/
----->   "stripe_card_token"=>"undefined"}}   <------
 $(document).ready(function() {
  Stripe.setPublishableKey($('meta[name="stripe-key"]').attr('content'));
  // Watch for a form submission:
  $("#form-submit-btn").click(function(event) {
    event.preventDefault();
    $('input[type=submit]').prop('disabled', true);
    var error = false;
    var ccNum = $('#card_number').val(),
        cvcNum = $('#card_code').val(),
        expMonth = $('#card_month').val(),
        expYear = $('#card_year').val();

    if (!error) {
      // Get the Stripe token:
      Stripe.createToken({
        number: ccNum,
        cvc: cvcNum,
        exp_month: expMonth,
        exp_year: expYear
      }, stripeResponseHandler);
    }
    return false;
  }); // form submission

  function stripeResponseHandler(status, response) {
    // Get a reference to the form:
    var f = $("#new_user");

    // Get the token from the response:
    var token = response.id;

    // Add the token to the form:
    f.append('<input type="hidden" name="user[stripe_card_token]" value="' + token + '" />');

    // Submit the form:
    f.get(0).submit();
  }
});

A: I think your first error is from the linter you're using. You can add /* global Stripe */ as the first line (depending on the linter you use).


text:
Q: How many even four-digit numbers can be formed from the digits $0, 1, 2, 5, 6,$ and $9$ if each digit can be used only once? First, I know this was posted first here but I reposted because the answer wasn't clear for me and the question is 8 years old so it's not getting any activity.
I don't understand the reason of the split, I first solved the problem in the following way:
Last digit: we have $3$ options: $0,2,6$ since we need the number to be even.
First digit: we have $4$ options: all minus $0$ and digit picked previously
Third digit: we have $4$ options: all minus the one picked in the previous $2$ digits.
Second digit: we have $3$ options: all minus previous $3$ digits.
so we get $3*3*4*4$
However I have a logical problem here, if I start analyzing in a different order (for example last digit to first) then it seems like I am getting different result (example:last digit has $3$ options and third one has $5$, etc...)
Moreover, I don't understand the solution and why they split it into these $2$ cases.

A: If we chose $0$ as the last digit, "the digit $0$" and "the digit picked previously" are the same digit, meaning that in this case, you have $5$ options for the first digit.
This is the reason for the split.


text:
Q: php include adds spaces to the beginning of the block I have simple page, like:
...

<?php include 'somefile.php' ?>

...

'somefile.php'-file contains
Lorium ipsum...

The browser adds spaces to the beginning of the block? look image:
http://s44.radikal.ru/i104/1209/95/87e6c2438700.jpg
And this test page http://new.arsltd.ru/test.php

A: Most likely somefile.php has spaces or other unprintable characters (such as a BOM) before the PHP start tag.
Update: Indeed, your file begins with an UTF-8 BOM (the bytes EF BB BF). Use your text editor to save it without a BOM; you will see the file size go down by 3 bytes as confirmation.

A: There is most likely a padding or margin style directive on one of your elements. Browsers disregard whitespace when parsing HTML (as they should).
The space you see in the HTML source may be caused by a newline at the beginning of the included .php file for example (note: this still doesn't affect the way the code is rendered).

A: somefile.php contains a text wrapped in
 paragraph, and most certain that paragraph has a margin or a padding.
the problem in in your test.php it starts with an invisible unicode character.

 // between
 and
 there is an unicode character

A: What is the content of 'somefile.php' ? Try changing the encoding of that file in UTF-8 without BOM with Notepad++ or other IDE/Text Editor


text:
Q: ffmpeg: How to get the same filename for the outfile automatically With ffmpeg -i inName.mp3 outName.avi I can create an avi-outfile from a single-mp3-infile.
But how can I get the same filename for the outfile automatically (here this would be inName.avi)?
Hint: at a loop this works with
ffmpeg for %i in (*.mp3) do ffmpeg -i "%i" "%~ni.avi"
But I do not know how to use the 'auto-filename' at a single file.

A: I do not know how to use the 'auto-filename' at a single file.

ffmpeg for %i in (*.mp3) do ffmpeg -i "%i" "%~ni.avi"

You can just loop over a single file:
for %i in (inName.mp3) do ffmpeg -i "%i" "%~ni.avi"


text:
Q: How to create a footer on powerpoint slide using R packages officedown and officer Revised a second time!!
There is an example .rmd that comes with the officedown package and in that are chunks that show how you can use the officer package placeholder ("ph") tags within the chunk options, which is great. Here is a minimum reproducible example:
---
title: YAML Title
output:
  officedown::rpptx_document
---

```{r echo=FALSE}
library(officedown)
```

## Slide 1 Title
```{r echo=FALSE, layout="Title and Content", ph=officer::ph_location_type(type="ftr")}
test <- data.frame(1)
test
```

The problem now is that if I try to insert a string instead of a data frame in the footer ("ftr"), then that string is instead placed in the body of the pptx slide, please see the example below.
---
title: YAML Title
output:
  officedown::rpptx_document
---

```{r echo=FALSE}
library(officedown)
```

## Slide 1 Title
```{r echo=FALSE, layout="Title and Content", ph=officer::ph_location_type(type="ftr")}
"Some footer text"
```

And so now I'm very close but need help to get a string to appear in the footer. I tried a hack of making a single cell data frame with the string I want in that cell but that did not work either.
Thank you for reading!
Revised thanks to commenters!
I am trying to use officedown combined with the officer package to write out a footer to a slide. I thought to create a code chunk in the .Rmd with code that I know works in a .R script using officer.
Using the example code below, it successfully creates 2 slides. However, on the second slide I would like to have a footer with the text "a footer". Instead on the second slide only the title appears. Is there a way to insert a footer using officedown?
The reasons I thought it might be possible was after reading this on the officedown page: "The package also enhances PowerPoint productions with R Markdown by providing a mechanism for placing results according to the slide template contained in the PowerPoint document used as "reference_doc" " - https://davidgohel.github.io/officedown/
Thank you for taking a look and here is the revised example code.
---
title: YAML Title
output:
  officedown::rpptx_document
---

```{r setup, include=FALSE}
library(officedown)
library(officer)
```

## Slide 1 Title
```{r echo=FALSE}
my_pres <- read_pptx()
my_pres <- add_slide(my_pres, layout = "Title and Content", master = "Office Theme")
my_pres <- ph_with(my_pres, value = "a footer", location = ph_location_type(type = "ftr"))
```


text:
Q: How to check for installed package in Puppet? I'm downloading a RPM using wget and I want to check if the package is installed before I download it. I'm not using a RPM repo, so I can't just do
package { ...
  ensure => installed
}

How can I do something like:
if HOW_TO_CHECK_IF_PACKAGE_X_IS_INSTALLED
   ... do wget etc.

Before someone asks, this didn't work for me: Puppet - test if a package already defined?

A: If you're downloading an RPM and installing it, you could do so like this:
package { 'foo':
  ensure   => installed,
  provider => 'rpm',
  source   => 'http://example.com/foo.rpm',
}

A: The solution was a custom facter:
require"puppet"
module Puppet::Parser::Functions
  newfunction(:package_installed, :type => :rvalue) do |args|
    packageName = args[0]
    return system "rpm --quiet -q #{packageName}"
  end
end


text:
Q: (K)Ubuntu 18.10 boots into emergency mode I finally switched from Wndows to Kubuntu because it seemed pretty stable, compared to, KDE Neon, Manjaro and Netrunner, Kaos, and Chakra (yes, I wanted the KDE desktop by default as you can see), for 3-4 days everything worked fine, (except some problems with the NVIDIA drivers that I managed to fix on my own). Recently every time that I boot my machine normally enters in this mode. I managed to make a workaround booting to ubuntu's recovery mode, selecting any option (tried with 3), and resuming the boot.
After that everything works fine, and I am writing this on Kubuntu even.
I made my own research and I already tried the following:

*

*fsck on LiveCD (No errors, forced it (with -y -f) to repair, clean)

*Tried to read the journalctr (Didn't see anything in special, It's
also pretty hard to read)

*Switched kernels

*fsck on recovery (same as above)

*Update grub from inside the working environment, recovery and
emergency mode

Some thing that I noticed, is using this order  "journalctl -p err -b" shows me (clearly) some errors:

*

*Polymouth couldn't boot

*And the fsck on boot, fails with code 4

I only used the command stated above once. Some "fishy things" that I done before that could be the cause:

*

*Used grub customizer to edit the timeout time

*Made a "sdd" folder on my sdd that is / , and changed the ownership because I needed the speed. (/home is on a different hard drive)

*While the Nvidia installation I rolled back with timeshift a long number of times after breaking.

*I edited (and restored the backup after all of this) of fstab trying to optimize the sdd load.

*Installed in a completely different partition on the sdd Windows 7 in case of I needed some program and Wine fails me (not at the moment) (the error showed some days after, used grub customizer again to add to grub Windows 7)

Thanks for reading.
Edit: After some testing, after booting in the recovery mode way depicted above, I get stuck on a black screen if I try to boot at the normal way, I had to reboot the computer, to get the next time the same error on normal boot.


text:
Q: Python script acts differently when ran in console and when ran from other file I have two python files, when I run "python downloader.py todownload" it downloads images from todownload.txt file, but when I run it indirectly (calling function of downloader.py via other python file) I don't get the images downloaded.
I tried debugging and printing what arguments are sent to function "download_all_images(args)" when I call it both ways, and the object args match.
downloader.py
import argparse
from concurrent import futures
import os
import re
import sys

import boto3
import botocore
import tqdm

BUCKET_NAME = 'open-images-dataset'
REGEX = r'(test|train|validation|challenge2018)/([a-fA-F0-9]*)'

def check_and_homogenize_one_image(image):
  split, image_id = re.match(REGEX, image).groups()
  yield split, image_id

def check_and_homogenize_image_list(image_list):
  for line_number, image in enumerate(image_list):
    try:
      yield from check_and_homogenize_one_image(image)
    except (ValueError, AttributeError):
      raise ValueError(
          f'ERROR in line {line_number} of the image list. The following image '
          f'string is not recognized: "{image}".')

def read_image_list_file(image_list_file):
  with open(image_list_file, 'r') as f:
    for line in f:
      yield line.strip().replace('.jpg', '')

def download_one_image(bucket, split, image_id, download_folder):
  try:
    bucket.download_file(f'{split}/{image_id}.jpg',
                         os.path.join(download_folder, f'{image_id}.jpg'))
  except botocore.exceptions.ClientError as exception:
    sys.exit(
        f'ERROR when downloading image `{split}/{image_id}`: {str(exception)}')

def download_all_images(args):
  print(type(args))
  print(args)
  """Downloads all images specified in the input file."""
  bucket = boto3.resource(
      's3', config=botocore.config.Config(
          signature_version=botocore.UNSIGNED)).Bucket(BUCKET_NAME)

  download_folder = args['download_folder'] or os.getcwd()

  if not os.path.exists(download_folder):
    os.makedirs(download_folder)

  try:
    image_list = list(
        check_and_homogenize_image_list(
            read_image_list_file(args['image_list'])))
  except ValueError as exception:
    sys.exit(exception)

  progress_bar = tqdm.tqdm(
      total=len(image_list), desc='Downloading images', leave=True)
  with futures.ThreadPoolExecutor(
      max_workers=args['num_processes']) as executor:
    all_futures = [
        executor.submit(download_one_image, bucket, split, image_id,
                        download_folder) for (split, image_id) in image_list
    ]
    for future in futures.as_completed(all_futures):
      future.result()
      progress_bar.update(1)
  progress_bar.close()

if __name__ == '__main__':
  parser = argparse.ArgumentParser(
      description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
  parser.add_argument(
      'image_list',
      type=str,
      default=None,
      help=('Filename that contains the split + image IDs of the images to '
            'download. Check the document'))
  parser.add_argument(
      '--num_processes',
      type=int,
      default=5,
      help='Number of parallel processes to use (default is 5).')
  parser.add_argument(
      '--download_folder',
      type=str,
      default=None,
      help='Folder where to download the images.')
  download_all_images(vars(parser.parse_args()))

imagegatherer.py
import pandas as pd
import argparse
from concurrent import futures
import os
import re
import sys

import boto3
import botocore
import tqdm

import downloader

labels = pd.read_csv('class-descriptions-boxable.csv', header=None)
labels.columns = ['id', 'name']

classified = pd.read_csv('train-annotations-human-imagelabels-boxable.csv', nrows=2500)

classes = ['Apple', 'Motorcycle', 'Snowman']
ids = labels[labels['name'].isin(classes)]

for entry in ids.iterrows():
    id = entry[1][0]
    name = entry[1][1]

    good = classified.loc[classified['LabelName'] == id]['ImageID'].tolist()

    with open('todownload.txt', 'w') as file:
        for img in good:
            file.write('train/' + img + '\n')

        args = dict()
        args['image_list'] = 'todownload.txt'
        args['num_processes'] = 5
        args['download_folder'] = None

        downloader.download_all_images(args)

todownload.txt content that should download 4 images:
train/0000048549557964
train/000023aa04ab09ed
train/00002f4ff380c64c
train/000037c2dd414b46


text:
Q: Soundcloud error 500 on playlist api I'm trying, via api, to get my playlists.
I set up the requests via PHP and every time I send this request (translated for testability)
https://api.soundcloud.com/users/radio-pnr/playlists.json?consumer_key=XXXXX
The server returns

HTTP/1.1 500 Internal Server Error
Date: Mon, 27 Feb 2017 13:25:17 GMT
Content-Length: 0 Via: 1.1
  008ae64ab7020a9aecc4c202669805d4.cloudfront.net (CloudFront)
X-Amz-Cf-Id: OFnsjEnoSzB5CtgGJ0eyJn9v4yWOp9PSzPBKZIbwr4fwz3rX9GEi-g==
Connection: keep-alive
X-Cache: Error from cloudfront
Server:  am/2

A: I see the same error using curl at the command-line. Looking at that user, I think the number of playlists and tracks per playlist could be causing timeouts on the server-side.


text:
Q: using 64 bits Informix CSDK with gcc in AIX? I don't think this configuration is supported (maybe gcc isn't supported at all) because the esql script uses xlc options only.
But I want to know if other people are using this configuration gcc and informix 64 bits in AIX.

A: You can get ESQL/C (a part of ClientSDK or CSDK) to use GCC, but it isn't completely trivial.  In principle, what I do is:

*

*Make a copy of the original esql script.

*Modify the original script to supply the GCC options on demand.

If you only want to use GCC, then this is sufficient.  If you want to use both GCC and sometimes XLC (the native compiler), then it is harder.
I have a single script called esql in my private bin directory (which is always on my PATH ahead of things like $INFORMIXDIR/bin).  It works out which version of ESQL/C I'm currently using, and runs the appropriate pre-patched version which is stored in a separate directory.  And it automatically creates new versions of that script for me so if I work with CSDK 3.00.UC2 one minute and then CSDK 3.50.FC3 the next, it handles the switchover automatically.
Here's the patch applied to ESQL/C 3.50 on Solaris - you'll need to adapt it to AIX.
# @(#)$Id: patch.300.64,v 1.2 2007/09/02 21:46:55 jleffler Exp $
# GCC Patch for esql from CSDK 3.00.FC1

--- esql        2007-09-02 14:44:18.739067000 -0700
+++ esql.new    2007-09-02 14:44:26.812149000 -0700
@@ -23,10 +23,33 @@
 INFDIR=${INFORMIXDIR=/usr/informix}
 DB2CLIDIR=${INSTHOME=/usr/db2}
 PREPCC=${INFDIR}/lib/esql/esqlc
-CC="${INFORMIXC=cc} -xarch=v9"
-CC_TH="${INFORMIXC=cc} -xarch=v9"
-CPP="${INFORMIXCPP=CC} -xarch=v9"
-CPP_TH="${INFORMIXCPP=CC} -xarch=v9"
+
+: ${INFORMIXC:=cc}
+: ${INFORMIXCPP:=CC}
+case "$INFORMIXC" in
+*perl*esqlcc*)  # Building DBD::Informix
+    case "$ESQLCC" in
+    *gcc*|*g++)
+        CC_ARCHFLAGS="-m64"
+        ;;
+    *cc*|*CC*)
+        CC_ARCHFLAGS="-xarch=v9"
+        ;;
+    esac
+    ;;
+*gcc*|*g++*)
+    CC_ARCHFLAGS="-m64"
+    ;;
+# Beware - this normally needs to be last - because things like esqlcc and gcc match too!
+*cc*|*CC*)
+    CC_ARCHFLAGS="-xarch=v9"
+    ;;
+esac
+
+CC="$INFORMIXC $CC_ARCHFLAGS"
+CC_TH="$INFORMIXC $CC_ARCHFLAGS"
+CPP="$INFORMIXCPP $CC_ARCHFLAGS"
+CPP_TH="$INFORMIXCPP $CC_ARCHFLAGS"
 STATICFLAGS=""

 CP=${INFORMIXCP="$CC -E -C"}                    # cpp which runs before esqlc
@@ -51,9 +74,6 @@
 then
 CC="$CC $CC_AMD32"
 CPP="$CPP $CC_AMD32"
-else
-CC=$CC
-CPP=$CPP
 fi

 : '
@@ -922,7 +942,7 @@
                # Set the linker to CPP
                # Set the source files to objects
                #
-               CC=$CPP
+               CC="$CPP"
                A="$AO $CPPOPTS"
        fi
 fi

Lemme know if you want the controlling esql script that I use (see my profile).  I have 9 32-bit scripts and 8 64-bit scripts, created by a set of 12 different patch files (all for Solaris, I'm afraid).  The versions range from ESQL/C 5.20 (for OnLine 5.20) via ESQL/C 7.2x (long dead officially) through various versions of CSDK.


text:
Q: How do I get IIS to render Mercurial (Python Module) static content? (ie, images, styles) I'm trying to setup an IIS server to expose my Mercurial repositories. I've followed a number of tutorials, but seem to be getting the same issue.
Basically, I'm able to get Python installed and mapped correctly in IIS, as well as (from what I can tell) the  Mercurial module. However, none of the static content that I expect to see in the Mercurial web application is properly rendered. (For example, the Mercurial logo from the static directory isn't rendered). I know that the Python/CGI processing is configured correctly because my actual repositories are exposed properly.
Is there something that I'm missing?

A: You need to copy the content from templates directory of the mercurial Python module into your mapped web application directory.
For example, at the default installation paths, you'll want to copy the contents of
C:\Python26\Lib\site-packages\mercurial\templates

into where you've defined your Mercurial application in IIS, i.e.,
C:\inetpub\wwwroot\hg


text:
Q: Почему возникает такая ошибка при использовании foreach с объектом вот код
foreach ($serId as $catS) {
   $idSer[]=  $catS->id_serial;}
var_dump( $idSer);

получаю такой массив
[0]=> int(5) [1]=> int(7) [2]=> int(13)
[3]=> int(14) [4]=> int(7) [5]=> int(60) [6]=> int(70) [7]=> int(77)

делаю так
foreach ($serId as $catS) {
    if($catS->id_serial) {
        $idSer['id'] = $catS->id_serial;
        $idSer['nesting'] = 'serial';
    }
 var_dump( $idSer);

получаю
array(2) { ["id"]=> int(17) ["nesting"]=> string(6) "serial" }

как мне получить id всех объектов в массив  с условием что id_serial не равно null

A: Если я правильно понял задачу, правильный код должен быть таким:
foreach ($serId as $catS) {
    if($catS->id_serial) {
        $idSer[] = [
            'id' => $catS->id_serial,
            'nesting' => 'serial'
        ];
    }
}
var_dump($idSer);


text:
Q: Extracting row with highest value in a column while also calculating averages by group I have been tasked with taking the following data and creating two permanent data sets from it. One of these permanent data sets is supposed to contain the average of the "value" column for each group (meaning there should only be four rows in the end, with a new column that represents the average of respective values for A, B, C, and D). Averages should exclude missing values, meaning that if category A has a missing value, it should be divided by 3, not 4. The second permanent data set needs to be the one row with the highest overall value in the "value" column (in this case, the row with D 09JUL2021 951 should be the only row exported). I am having a tough time extracting that single row for the second data set. If you know of a way to perform these operations simultaneously, please let me know. Thank you for your time!
Example data:
data work.have;
  input type $ date DATE9. value;
datalines;
A 08JUL2021 .
A 09JUL2021 20
A 20JUL2021 55
A 20JUL2021 2
B 02JUL2021 9
B 22JUL2021 6
B 04JUL2021 8
B 07JUL2021 406
C 01JUL2021 215
C 28JUL2021 63
C 30JUL2021 78
C 21JUL2021 80
D 18JUL2021 951
D 09JUL2021 .
D 14JUL2021 54
D 08JUL2021 73
;

Here is what I tried:
data mylib.data1(keep=type date value value_avg) mylib.data2;
    set work.have;
    by type;
    if value ne . then NotMissing=1; else NotMissing=0;
    if first.type then call missing(of value_avg);
        value_avg+value;
    if first.type then call missing(of num_per_cat);
        num_per_cat+NotMissing;
    Avg=divide((value_avg+value),(num_per_cat+NotMissing));
    if last.type then output mylib.data1;
run;

This was successful for me with calculating averages, but I have no idea how to extract the row with the highest value in the "value" column to a second data set.

A: Both sets are easelly done by proc sql.
First one:
proc sql;
    create table want1 as
        select distinct type, max(value) as Max_value, mean(value) as Average_value
            from have
            group by type
    ;
quit;

Second one:
proc sql;
    create table want2 as
        select *
            from have
                having value = max(value)
    ;
quit;

A: data work.have;
  input type $ date DATE9. value;
datalines;
A 08JUL2021 .
A 09JUL2021 20
A 20JUL2021 55
A 20JUL2021 2
B 02JUL2021 9
B 22JUL2021 6
B 04JUL2021 8
B 07JUL2021 406
C 01JUL2021 215
C 28JUL2021 63
C 30JUL2021 78
C 21JUL2021 80
D 18JUL2021 951
D 09JUL2021 .
D 14JUL2021 54
D 08JUL2021 73
;

proc summary data = have nway;
   class type;
   var value;
   output out = want_mean(drop = _:) mean = ;
run;

proc summary data = have nway;
   class type;
   var value;
   output out = want_max(drop = _:) max = ;
run;


text:
Q: Area of a quadrilateral in which a circle can be inscribed using algebraic geometry $\Delta POR $ has vertices $P(0,12),R(5,0)$ and $O(0,0)$. There exists a line $l$ cutting $PR$ and $OP$ at $A$ and $B$ respectively such that circles can be inscribed in $\Delta PAB$ and quadrilateral $ORAB$. Also, these circles are tangent to the line $l$ at the same point. If line $l$ passes through the point $(0,8)$, the find the area of the quadrilateral $ORAB$.
I tried using the condition for a quadrilateral having an inscribed circle. I am not able to use the tangent at same point condition. Though I am not sure if my approach is the way to start. Any help is appreciated. Thanks.

A:
I am not able to use the tangent at same point condition.

This answer does not use the condition that the two circles are tangent to $l$ at the same point because $A$ is determined only by the condition that $ORAB$ possesses an incircle. (After knowing $A$, I see that the two circles are tangent to $l$ at $(18/5,16/5)$.)

The center and the radius of the circle inscribed in $ORAB$ can be written as $(r,r),r$ respectively where $r\lt 5$.
Since the distance between $PR: 12x+5y-60=0$ and $(r,r)$ is $r$,
$$r=\frac{|12r+5r-60|}{\sqrt{12^2+5^2}}\implies r=2$$
Also, since the distance between $l:bx-y+8=0$ and $(2,2)$ is $r=2$,
$$2=\frac{|2b-2+8|}{\sqrt{b^2+1}}\implies b=-\frac 43$$
Finally, $A$ is the intersection point of $l$ and $PR$, so $A(15/4,3)$ from which we get that the area of $ORAB$ is $\color{red}{45/2}$.


text:
Q: Angular JS validation not Working in CSHTML(Razor) I am trying to validate input controls in cshtml using AngularJS. It is not working in CSHTML, but it does work in normal HTML pages. Is there any way to solve the issue?
My code is something like the following:
  <form ng-app novalidate ng-submit="addRow()">

        Email

            <input type="email" name="email" class="form-control" ng-model="email" required />
            Required
            Invalid email

A: //try this
<form name="myForm" novalidate ng-submit="addRow()">
   Email

      <input type="email" name="email" class="form-control" ng-model="email" required />
      Required.

</form>