Pipe output of grep to a variable – apple.stackexchange.com
I need to be able to write whether the test for a grep is either TRUE or
FALSE to a variable so I can use it later For the following, if I run
defaults read com.apple.Finder | grep ...
Monday, 30 September 2013
Points and Coordinates
Points and Coordinates
If $P$ is $(1,2,-2)$, find vector $P$ (from the origin) and the angles
which vector $P$ makes with the coordinate axes $x, y,$ and $z$.
If $P$ is $(1,2,-2)$, find vector $P$ (from the origin) and the angles
which vector $P$ makes with the coordinate axes $x, y,$ and $z$.
Error creating bean with name 'org.springframework.security.filterChains' Spring + Hibernate + UserDetailService
Error creating bean with name 'org.springframework.security.filterChains'
Spring + Hibernate + UserDetailService
I just started to learn Spring Security and have some trouble. I want to
configure User login on page with password and username which stored in
database during registration. I use Hibernate.
My error stack:
INFO : org.springframework.web.context.ContextLoader - Root
WebApplicationContext: initialization started
INFO : org.springframework.web.context.support.XmlWebApplicationContext -
Refreshing Root WebApplicationContext: startup date [Mon Sep 30 16:16:07
EDT 2013]; root of context hierarchy
INFO : org.springframework.beans.factory.xml.XmlBeanDefinitionReader -
Loading XML bean definitions from ServletContext resource
[/WEB-INF/spring/spring-context.xml]
INFO : org.springframework.beans.factory.xml.XmlBeanDefinitionReader -
Loading XML bean definitions from ServletContext resource
[/WEB-INF/spring/root-context.xml]
INFO : org.springframework.beans.factory.xml.XmlBeanDefinitionReader -
Loading XML bean definitions from ServletContext resource
[/WEB-INF/spring/security-context.xml]
INFO :
org.springframework.beans.factory.support.DefaultListableBeanFactory -
Overriding bean definition for bean 'guestBookDAOImpl': replacing [Generic
bean: class [demidov.pkg.persistence.GuestBookDAOImpl]; scope=;
abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0;
autowireCandidate=true; primary=false; factoryBeanName=null;
factoryMethodName=null; initMethodName=null; destroyMethodName=null;
defined in ServletContext resource [/WEB-INF/spring/spring-context.xml]]
with [Generic bean: class [demidov.pkg.persistence.GuestBookDAOImpl];
scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0;
autowireCandidate=true; primary=false; factoryBeanName=null;
factoryMethodName=null; initMethodName=null; destroyMethodName=null;
defined in ServletContext resource [/WEB-INF/spring/security-context.xml]]
INFO :
org.springframework.beans.factory.support.DefaultListableBeanFactory -
Pre-instantiating singletons in
org.springframework.beans.factory.support.DefaultListableBeanFactory@11dab12:
defining beans
[dataSource,sessionFactory,guestBookDAOImpl,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0,org.springframework.transaction.interceptor.TransactionInterceptor#0,org.springframework.transaction.config.internalTransactionAdvisor,transactionManager,org.springframework.security.filterChains,org.springframework.security.filterChainProxy,org.springframework.security.web.DefaultSecurityFilterChain#0,org.springframework.security.web.DefaultSecurityFilterChain#1,org.springframework.security.web.PortMapperImpl#0,org.springframework.security.web.PortResolverImpl#0,org.springframework.security.config.authentication.AuthenticationManagerFactoryBean#0,org.springframework.security.authentication.ProviderManager#0,org.springframework.security.web.context.HttpSessionSecurityContextRepository#0,org.springframework.security.web.authentication.session.SessionFixationProtectionStrategy#0,org.springframework.
security.web.savedrequest.HttpSessionRequestCache#0,org.springframework.security.access.vote.AffirmativeBased#0,org.springframework.security.web.access.intercept.FilterSecurityInterceptor#0,org.springframework.security.web.access.DefaultWebInvocationPrivilegeEvaluator#0,org.springframework.security.authentication.AnonymousAuthenticationProvider#0,org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint#0,org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter#0,org.springframework.security.userDetailsServiceFactory,org.springframework.security.web.DefaultSecurityFilterChain#2,org.springframework.security.authentication.dao.DaoAuthenticationProvider#0,org.springframework.security.authentication.DefaultAuthenticationEventPublisher#0,org.springframework.security.authenticationManager];
root of factory hierarchy
WARN : org.hibernate.internal.util.xml.DTDEntityResolver - HHH000223:
Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/.
Use namespace http://www.hibernate.org/dtd/ instead. Refer to Hibernate
3.6 Migration Guide!
WARN : org.hibernate.internal.util.xml.DTDEntityResolver - HHH000223:
Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/.
Use namespace http://www.hibernate.org/dtd/ instead. Refer to Hibernate
3.6 Migration Guide!
ERROR: org.hibernate.tool.hbm2ddl.SchemaUpdate - HHH000388: Unsuccessful:
create table USER_DESC (ID bigint not null auto_increment, USER_NAME
varchar(255), USER_PASS varchar(255), USER_PRIV varchar(255) default
ROLE_USER, USER_EMALE varchar(255), USER_GENDER varchar(255), primary key
(ID))
ERROR: org.hibernate.tool.hbm2ddl.SchemaUpdate - You have an error in your
SQL syntax; check the manual that corresponds to your MySQL server version
for the right syntax to use near 'ROLE_USER, USER_EMALE varchar(255),
USER_GENDER varchar(255), primary key (ID))' at line 1
INFO :
org.springframework.beans.factory.support.DefaultListableBeanFactory -
Destroying singletons in
org.springframework.beans.factory.support.DefaultListableBeanFactory@11dab12:
defining beans
[dataSource,sessionFactory,guestBookDAOImpl,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0,org.springframework.transaction.interceptor.TransactionInterceptor#0,org.springframework.transaction.config.internalTransactionAdvisor,transactionManager,org.springframework.security.filterChains,org.springframework.security.filterChainProxy,org.springframework.security.web.DefaultSecurityFilterChain#0,org.springframework.security.web.DefaultSecurityFilterChain#1,org.springframework.security.web.PortMapperImpl#0,org.springframework.security.web.PortResolverImpl#0,org.springframework.security.config.authentication.AuthenticationManagerFactoryBean#0,org.springframework.security.authentication.ProviderManager#0,org.springframework.security.web.context.HttpSessionSecurityContextRepository#0,org.springframework.security.web.authentication.session.SessionFixationProtectionStrategy#0,org.springframework.
security.web.savedrequest.HttpSessionRequestCache#0,org.springframework.security.access.vote.AffirmativeBased#0,org.springframework.security.web.access.intercept.FilterSecurityInterceptor#0,org.springframework.security.web.access.DefaultWebInvocationPrivilegeEvaluator#0,org.springframework.security.authentication.AnonymousAuthenticationProvider#0,org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint#0,org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter#0,org.springframework.security.userDetailsServiceFactory,org.springframework.security.web.DefaultSecurityFilterChain#2,org.springframework.security.authentication.dao.DaoAuthenticationProvider#0,org.springframework.security.authentication.DefaultAuthenticationEventPublisher#0,org.springframework.security.authenticationManager];
root of factory hierarchy
ERROR: org.springframework.web.context.ContextLoader - Context
initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating
bean with name 'org.springframework.security.filterChains': Cannot resolve
reference to bean
'org.springframework.security.web.DefaultSecurityFilterChain#2' while
setting bean property 'sourceList' with key [2]; nested exception is
org.springframework.beans.factory.BeanCreationException: Error creating
bean with name
'org.springframework.security.web.DefaultSecurityFilterChain#2': Cannot
resolve reference to bean
'org.springframework.security.web.access.intercept.FilterSecurityInterceptor#0'
while setting constructor argument with key [10]; nested exception is
org.springframework.beans.factory.BeanCreationException: Error creating
bean with name
'org.springframework.security.web.access.intercept.FilterSecurityInterceptor#0':
Invocation of init method failed; nested exception is
java.lang.IllegalArgumentException: Unsupported configuration attributes:
[hasRole('ROLE_USER')]
at
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:329)
at
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:107)
at
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveManagedList(BeanDefinitionValueResolver.java:353)
at
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:154)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1387)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1128)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
at
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
at
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
at
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
at
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:610)
at
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
at
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
at
org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:389)
at
org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:294)
at
org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:112)
at
org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4701)
at
org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5204)
at
org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5199)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:724)
Caused by: org.springframework.beans.factory.BeanCreationException: Error
creating bean with name
'org.springframework.security.web.DefaultSecurityFilterChain#2': Cannot
resolve reference to bean
'org.springframework.security.web.access.intercept.FilterSecurityInterceptor#0'
while setting constructor argument with key [10]; nested exception is
org.springframework.beans.factory.BeanCreationException: Error creating
bean with name
'org.springframework.security.web.access.intercept.FilterSecurityInterceptor#0':
Invocation of init method failed; nested exception is
java.lang.IllegalArgumentException: Unsupported configuration attributes:
[hasRole('ROLE_USER')]
at
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:329)
at
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:107)
at
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveManagedList(BeanDefinitionValueResolver.java:353)
at
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:154)
at
org.springframework.beans.factory.support.ConstructorResolver.resolveConstructorArguments(ConstructorResolver.java:615)
at
org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:148)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1045)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:949)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:487)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
at
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
at
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
at
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
at
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:323)
... 24 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error
creating bean with name
'org.springframework.security.web.access.intercept.FilterSecurityInterceptor#0':
Invocation of init method failed; nested exception is
java.lang.IllegalArgumentException: Unsupported configuration attributes:
[hasRole('ROLE_USER')]
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1482)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:521)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
at
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
at
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
at
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
at
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:323)
... 38 more
Caused by: java.lang.IllegalArgumentException: Unsupported configuration
attributes: [hasRole('ROLE_USER')]
at
org.springframework.security.access.intercept.AbstractSecurityInterceptor.afterPropertiesSet(AbstractSecurityInterceptor.java:156)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1541)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1479)
... 45 more
Sep 30, 2013 4:16:09 PM org.apache.catalina.core.StandardContext
listenerStart
SEVERE: Exception sending context initialized event to listener instance
of class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanCreationException: Error creating
bean with name 'org.springframework.security.filterChains': Cannot resolve
reference to bean
'org.springframework.security.web.DefaultSecurityFilterChain#2' while
setting bean property 'sourceList' with key [2]; nested exception is
org.springframework.beans.factory.BeanCreationException: Error creating
bean with name
'org.springframework.security.web.DefaultSecurityFilterChain#2': Cannot
resolve reference to bean
'org.springframework.security.web.access.intercept.FilterSecurityInterceptor#0'
while setting constructor argument with key [10]; nested exception is
org.springframework.beans.factory.BeanCreationException: Error creating
bean with name
'org.springframework.security.web.access.intercept.FilterSecurityInterceptor#0':
Invocation of init method failed; nested exception is
java.lang.IllegalArgumentException: Unsupported configuration attributes:
[hasRole('ROLE_USER')]
at
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:329)
at
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:107)
at
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveManagedList(BeanDefinitionValueResolver.java:353)
at
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:154)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1387)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1128)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
at
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
at
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
at
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
at
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:610)
at
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
at
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
at
org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:389)
at
org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:294)
at
org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:112)
at
org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4701)
at
org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5204)
at
org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5199)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:724)
Caused by: org.springframework.beans.factory.BeanCreationException: Error
creating bean with name
'org.springframework.security.web.DefaultSecurityFilterChain#2': Cannot
resolve reference to bean
'org.springframework.security.web.access.intercept.FilterSecurityInterceptor#0'
while setting constructor argument with key [10]; nested exception is
org.springframework.beans.factory.BeanCreationException: Error creating
bean with name
'org.springframework.security.web.access.intercept.FilterSecurityInterceptor#0':
Invocation of init method failed; nested exception is
java.lang.IllegalArgumentException: Unsupported configuration attributes:
[hasRole('ROLE_USER')]
at
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:329)
at
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:107)
at
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveManagedList(BeanDefinitionValueResolver.java:353)
at
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:154)
at
org.springframework.beans.factory.support.ConstructorResolver.resolveConstructorArguments(ConstructorResolver.java:615)
at
org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:148)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1045)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:949)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:487)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
at
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
at
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
at
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
at
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:323)
... 24 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error
creating bean with name
'org.springframework.security.web.access.intercept.FilterSecurityInterceptor#0':
Invocation of init method failed; nested exception is
java.lang.IllegalArgumentException: Unsupported configuration attributes:
[hasRole('ROLE_USER')]
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1482)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:521)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
at
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
at
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
at
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
at
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:323)
... 38 more
Caused by: java.lang.IllegalArgumentException: Unsupported configuration
attributes: [hasRole('ROLE_USER')]
at
org.springframework.security.access.intercept.AbstractSecurityInterceptor.afterPropertiesSet(AbstractSecurityInterceptor.java:156)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1541)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1479)
... 45 more
I can not get access any jsp pages after I add Spring Security.
My spring-context.xml
<security:http pattern="/guestbook" security="none" />
<security:http pattern="/regestration" security="none" />
<security:http auto-config="true">
<security:intercept-url pattern="/user/*"
access="hasRole('ROLE_USER')"/>
</security:http>
<security:authentication-manager>
<security:authentication-provider
user-service-ref="guestBookDAOImpl"/>
</security:authentication-manager>
<bean id="guestBookDAOImpl"
class="demidov.pkg.persistence.GuestBookDAOImpl"/>
My dao impl implemented with UserDetailsService from Spring Security:
@Transactional
public class GuestBookDAOImpl implements GuestBookDAOIF, UserDetailsService {
public SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
@SuppressWarnings("unchecked")
@Override
public User fetchAllUsers(String userName) {
return(User)sessionFactory.getCurrentSession().createQuery("select
user from User user where user.userName=:name")
.setParameter("name",
userName)
.uniqueResult();
}
@Override
public UserDetails loadUserByUsername(String userName)
throws UsernameNotFoundException {
org.springframework.security.core.userdetails.User user;
Set<GrantedAuthority> userroles = new HashSet<GrantedAuthority>();
User myuser = fetchAllUsers(userName);
userroles.add(myuser);
user = new
org.springframework.security.core.userdetails.User(myuser.getUserName(),
myuser.getUserPassword(), true, true, true, true, userroles);
return user;
}
My User entity:
public class User implements Serializable, GrantedAuthority {
private static final long serialVersionUID = -1576600424405883465L;
private long userId;
public long getUserId() {
return userId;
}
public void setUserId(long userId) {
this.userId = userId;
}
private String userName;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
private String userPassword;
public String getUserPassword() {
return userPassword;
}
public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
}
private String userRole;
public String getUserRole() {
return userRole;
}
public void setUserRole(String userRole) {
this.userRole = userRole;
}
private String userEmale;
public String getUserEmale() {
return userEmale;
}
public void setUserEmale(String userEmale) {
this.userEmale = userEmale;
}
private String userGender;
public String getUserGender() {
return userGender;
}
public void setUserGender(String userGender) {
this.userGender = userGender;
}
private Set<UserMessage> userMessageList = new HashSet<UserMessage>();
public Set<UserMessage> getUserMessageList() {
return userMessageList;
}
public void setUserMessageList(Set<UserMessage> userMessageList) {
this.userMessageList = userMessageList;
}
@Override
public String getAuthority() {
return getUserRole();
}
}
Hibernate mapping xml fro user entity:
<hibernate-mapping>
<class name="demidov.pkg.domain.User" table="USER_DESC">
<!-- Primary key ID will be generated depends on database
configuration -->
<id name="userId" column="ID">
<generator class="native"></generator>
</id>
<property name="userName" column="USER_NAME" unique="true" />
<property name="userPassword" column="USER_PASS"/>
<property name="userRole" >
<column name="USER_PRIV" default="ROLE_USER"/>
</property>
<property name="userEmale" column="USER_EMALE" unique="true"/>
<property name="userGender" column="USER_GENDER" />
<!-- User is owner of relationships, all changes on user will
effect UserMessage entity -->
<set name="userMessageList" inverse="true" lazy="false"
fetch="select" cascade="all">
<key>
<column name="USER_ID" not-null="true"/>
</key>
<one-to-many class="demidov.pkg.domain.UserMessage" />
</set>
</class>
</hibernate-mapping>
Please help me. I'm confused what is what: GrantedAuthority, UserDetails,
User and how they work with xml configuration of Spring Security.
Thanks.
Spring + Hibernate + UserDetailService
I just started to learn Spring Security and have some trouble. I want to
configure User login on page with password and username which stored in
database during registration. I use Hibernate.
My error stack:
INFO : org.springframework.web.context.ContextLoader - Root
WebApplicationContext: initialization started
INFO : org.springframework.web.context.support.XmlWebApplicationContext -
Refreshing Root WebApplicationContext: startup date [Mon Sep 30 16:16:07
EDT 2013]; root of context hierarchy
INFO : org.springframework.beans.factory.xml.XmlBeanDefinitionReader -
Loading XML bean definitions from ServletContext resource
[/WEB-INF/spring/spring-context.xml]
INFO : org.springframework.beans.factory.xml.XmlBeanDefinitionReader -
Loading XML bean definitions from ServletContext resource
[/WEB-INF/spring/root-context.xml]
INFO : org.springframework.beans.factory.xml.XmlBeanDefinitionReader -
Loading XML bean definitions from ServletContext resource
[/WEB-INF/spring/security-context.xml]
INFO :
org.springframework.beans.factory.support.DefaultListableBeanFactory -
Overriding bean definition for bean 'guestBookDAOImpl': replacing [Generic
bean: class [demidov.pkg.persistence.GuestBookDAOImpl]; scope=;
abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0;
autowireCandidate=true; primary=false; factoryBeanName=null;
factoryMethodName=null; initMethodName=null; destroyMethodName=null;
defined in ServletContext resource [/WEB-INF/spring/spring-context.xml]]
with [Generic bean: class [demidov.pkg.persistence.GuestBookDAOImpl];
scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0;
autowireCandidate=true; primary=false; factoryBeanName=null;
factoryMethodName=null; initMethodName=null; destroyMethodName=null;
defined in ServletContext resource [/WEB-INF/spring/security-context.xml]]
INFO :
org.springframework.beans.factory.support.DefaultListableBeanFactory -
Pre-instantiating singletons in
org.springframework.beans.factory.support.DefaultListableBeanFactory@11dab12:
defining beans
[dataSource,sessionFactory,guestBookDAOImpl,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0,org.springframework.transaction.interceptor.TransactionInterceptor#0,org.springframework.transaction.config.internalTransactionAdvisor,transactionManager,org.springframework.security.filterChains,org.springframework.security.filterChainProxy,org.springframework.security.web.DefaultSecurityFilterChain#0,org.springframework.security.web.DefaultSecurityFilterChain#1,org.springframework.security.web.PortMapperImpl#0,org.springframework.security.web.PortResolverImpl#0,org.springframework.security.config.authentication.AuthenticationManagerFactoryBean#0,org.springframework.security.authentication.ProviderManager#0,org.springframework.security.web.context.HttpSessionSecurityContextRepository#0,org.springframework.security.web.authentication.session.SessionFixationProtectionStrategy#0,org.springframework.
security.web.savedrequest.HttpSessionRequestCache#0,org.springframework.security.access.vote.AffirmativeBased#0,org.springframework.security.web.access.intercept.FilterSecurityInterceptor#0,org.springframework.security.web.access.DefaultWebInvocationPrivilegeEvaluator#0,org.springframework.security.authentication.AnonymousAuthenticationProvider#0,org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint#0,org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter#0,org.springframework.security.userDetailsServiceFactory,org.springframework.security.web.DefaultSecurityFilterChain#2,org.springframework.security.authentication.dao.DaoAuthenticationProvider#0,org.springframework.security.authentication.DefaultAuthenticationEventPublisher#0,org.springframework.security.authenticationManager];
root of factory hierarchy
WARN : org.hibernate.internal.util.xml.DTDEntityResolver - HHH000223:
Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/.
Use namespace http://www.hibernate.org/dtd/ instead. Refer to Hibernate
3.6 Migration Guide!
WARN : org.hibernate.internal.util.xml.DTDEntityResolver - HHH000223:
Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/.
Use namespace http://www.hibernate.org/dtd/ instead. Refer to Hibernate
3.6 Migration Guide!
ERROR: org.hibernate.tool.hbm2ddl.SchemaUpdate - HHH000388: Unsuccessful:
create table USER_DESC (ID bigint not null auto_increment, USER_NAME
varchar(255), USER_PASS varchar(255), USER_PRIV varchar(255) default
ROLE_USER, USER_EMALE varchar(255), USER_GENDER varchar(255), primary key
(ID))
ERROR: org.hibernate.tool.hbm2ddl.SchemaUpdate - You have an error in your
SQL syntax; check the manual that corresponds to your MySQL server version
for the right syntax to use near 'ROLE_USER, USER_EMALE varchar(255),
USER_GENDER varchar(255), primary key (ID))' at line 1
INFO :
org.springframework.beans.factory.support.DefaultListableBeanFactory -
Destroying singletons in
org.springframework.beans.factory.support.DefaultListableBeanFactory@11dab12:
defining beans
[dataSource,sessionFactory,guestBookDAOImpl,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0,org.springframework.transaction.interceptor.TransactionInterceptor#0,org.springframework.transaction.config.internalTransactionAdvisor,transactionManager,org.springframework.security.filterChains,org.springframework.security.filterChainProxy,org.springframework.security.web.DefaultSecurityFilterChain#0,org.springframework.security.web.DefaultSecurityFilterChain#1,org.springframework.security.web.PortMapperImpl#0,org.springframework.security.web.PortResolverImpl#0,org.springframework.security.config.authentication.AuthenticationManagerFactoryBean#0,org.springframework.security.authentication.ProviderManager#0,org.springframework.security.web.context.HttpSessionSecurityContextRepository#0,org.springframework.security.web.authentication.session.SessionFixationProtectionStrategy#0,org.springframework.
security.web.savedrequest.HttpSessionRequestCache#0,org.springframework.security.access.vote.AffirmativeBased#0,org.springframework.security.web.access.intercept.FilterSecurityInterceptor#0,org.springframework.security.web.access.DefaultWebInvocationPrivilegeEvaluator#0,org.springframework.security.authentication.AnonymousAuthenticationProvider#0,org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint#0,org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter#0,org.springframework.security.userDetailsServiceFactory,org.springframework.security.web.DefaultSecurityFilterChain#2,org.springframework.security.authentication.dao.DaoAuthenticationProvider#0,org.springframework.security.authentication.DefaultAuthenticationEventPublisher#0,org.springframework.security.authenticationManager];
root of factory hierarchy
ERROR: org.springframework.web.context.ContextLoader - Context
initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating
bean with name 'org.springframework.security.filterChains': Cannot resolve
reference to bean
'org.springframework.security.web.DefaultSecurityFilterChain#2' while
setting bean property 'sourceList' with key [2]; nested exception is
org.springframework.beans.factory.BeanCreationException: Error creating
bean with name
'org.springframework.security.web.DefaultSecurityFilterChain#2': Cannot
resolve reference to bean
'org.springframework.security.web.access.intercept.FilterSecurityInterceptor#0'
while setting constructor argument with key [10]; nested exception is
org.springframework.beans.factory.BeanCreationException: Error creating
bean with name
'org.springframework.security.web.access.intercept.FilterSecurityInterceptor#0':
Invocation of init method failed; nested exception is
java.lang.IllegalArgumentException: Unsupported configuration attributes:
[hasRole('ROLE_USER')]
at
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:329)
at
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:107)
at
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveManagedList(BeanDefinitionValueResolver.java:353)
at
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:154)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1387)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1128)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
at
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
at
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
at
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
at
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:610)
at
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
at
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
at
org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:389)
at
org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:294)
at
org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:112)
at
org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4701)
at
org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5204)
at
org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5199)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:724)
Caused by: org.springframework.beans.factory.BeanCreationException: Error
creating bean with name
'org.springframework.security.web.DefaultSecurityFilterChain#2': Cannot
resolve reference to bean
'org.springframework.security.web.access.intercept.FilterSecurityInterceptor#0'
while setting constructor argument with key [10]; nested exception is
org.springframework.beans.factory.BeanCreationException: Error creating
bean with name
'org.springframework.security.web.access.intercept.FilterSecurityInterceptor#0':
Invocation of init method failed; nested exception is
java.lang.IllegalArgumentException: Unsupported configuration attributes:
[hasRole('ROLE_USER')]
at
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:329)
at
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:107)
at
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveManagedList(BeanDefinitionValueResolver.java:353)
at
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:154)
at
org.springframework.beans.factory.support.ConstructorResolver.resolveConstructorArguments(ConstructorResolver.java:615)
at
org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:148)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1045)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:949)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:487)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
at
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
at
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
at
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
at
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:323)
... 24 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error
creating bean with name
'org.springframework.security.web.access.intercept.FilterSecurityInterceptor#0':
Invocation of init method failed; nested exception is
java.lang.IllegalArgumentException: Unsupported configuration attributes:
[hasRole('ROLE_USER')]
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1482)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:521)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
at
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
at
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
at
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
at
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:323)
... 38 more
Caused by: java.lang.IllegalArgumentException: Unsupported configuration
attributes: [hasRole('ROLE_USER')]
at
org.springframework.security.access.intercept.AbstractSecurityInterceptor.afterPropertiesSet(AbstractSecurityInterceptor.java:156)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1541)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1479)
... 45 more
Sep 30, 2013 4:16:09 PM org.apache.catalina.core.StandardContext
listenerStart
SEVERE: Exception sending context initialized event to listener instance
of class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanCreationException: Error creating
bean with name 'org.springframework.security.filterChains': Cannot resolve
reference to bean
'org.springframework.security.web.DefaultSecurityFilterChain#2' while
setting bean property 'sourceList' with key [2]; nested exception is
org.springframework.beans.factory.BeanCreationException: Error creating
bean with name
'org.springframework.security.web.DefaultSecurityFilterChain#2': Cannot
resolve reference to bean
'org.springframework.security.web.access.intercept.FilterSecurityInterceptor#0'
while setting constructor argument with key [10]; nested exception is
org.springframework.beans.factory.BeanCreationException: Error creating
bean with name
'org.springframework.security.web.access.intercept.FilterSecurityInterceptor#0':
Invocation of init method failed; nested exception is
java.lang.IllegalArgumentException: Unsupported configuration attributes:
[hasRole('ROLE_USER')]
at
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:329)
at
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:107)
at
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveManagedList(BeanDefinitionValueResolver.java:353)
at
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:154)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1387)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1128)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
at
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
at
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
at
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
at
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:610)
at
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
at
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
at
org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:389)
at
org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:294)
at
org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:112)
at
org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4701)
at
org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5204)
at
org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5199)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:724)
Caused by: org.springframework.beans.factory.BeanCreationException: Error
creating bean with name
'org.springframework.security.web.DefaultSecurityFilterChain#2': Cannot
resolve reference to bean
'org.springframework.security.web.access.intercept.FilterSecurityInterceptor#0'
while setting constructor argument with key [10]; nested exception is
org.springframework.beans.factory.BeanCreationException: Error creating
bean with name
'org.springframework.security.web.access.intercept.FilterSecurityInterceptor#0':
Invocation of init method failed; nested exception is
java.lang.IllegalArgumentException: Unsupported configuration attributes:
[hasRole('ROLE_USER')]
at
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:329)
at
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:107)
at
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveManagedList(BeanDefinitionValueResolver.java:353)
at
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:154)
at
org.springframework.beans.factory.support.ConstructorResolver.resolveConstructorArguments(ConstructorResolver.java:615)
at
org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:148)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1045)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:949)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:487)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
at
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
at
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
at
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
at
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:323)
... 24 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error
creating bean with name
'org.springframework.security.web.access.intercept.FilterSecurityInterceptor#0':
Invocation of init method failed; nested exception is
java.lang.IllegalArgumentException: Unsupported configuration attributes:
[hasRole('ROLE_USER')]
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1482)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:521)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
at
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
at
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
at
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
at
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:323)
... 38 more
Caused by: java.lang.IllegalArgumentException: Unsupported configuration
attributes: [hasRole('ROLE_USER')]
at
org.springframework.security.access.intercept.AbstractSecurityInterceptor.afterPropertiesSet(AbstractSecurityInterceptor.java:156)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1541)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1479)
... 45 more
I can not get access any jsp pages after I add Spring Security.
My spring-context.xml
<security:http pattern="/guestbook" security="none" />
<security:http pattern="/regestration" security="none" />
<security:http auto-config="true">
<security:intercept-url pattern="/user/*"
access="hasRole('ROLE_USER')"/>
</security:http>
<security:authentication-manager>
<security:authentication-provider
user-service-ref="guestBookDAOImpl"/>
</security:authentication-manager>
<bean id="guestBookDAOImpl"
class="demidov.pkg.persistence.GuestBookDAOImpl"/>
My dao impl implemented with UserDetailsService from Spring Security:
@Transactional
public class GuestBookDAOImpl implements GuestBookDAOIF, UserDetailsService {
public SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
@SuppressWarnings("unchecked")
@Override
public User fetchAllUsers(String userName) {
return(User)sessionFactory.getCurrentSession().createQuery("select
user from User user where user.userName=:name")
.setParameter("name",
userName)
.uniqueResult();
}
@Override
public UserDetails loadUserByUsername(String userName)
throws UsernameNotFoundException {
org.springframework.security.core.userdetails.User user;
Set<GrantedAuthority> userroles = new HashSet<GrantedAuthority>();
User myuser = fetchAllUsers(userName);
userroles.add(myuser);
user = new
org.springframework.security.core.userdetails.User(myuser.getUserName(),
myuser.getUserPassword(), true, true, true, true, userroles);
return user;
}
My User entity:
public class User implements Serializable, GrantedAuthority {
private static final long serialVersionUID = -1576600424405883465L;
private long userId;
public long getUserId() {
return userId;
}
public void setUserId(long userId) {
this.userId = userId;
}
private String userName;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
private String userPassword;
public String getUserPassword() {
return userPassword;
}
public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
}
private String userRole;
public String getUserRole() {
return userRole;
}
public void setUserRole(String userRole) {
this.userRole = userRole;
}
private String userEmale;
public String getUserEmale() {
return userEmale;
}
public void setUserEmale(String userEmale) {
this.userEmale = userEmale;
}
private String userGender;
public String getUserGender() {
return userGender;
}
public void setUserGender(String userGender) {
this.userGender = userGender;
}
private Set<UserMessage> userMessageList = new HashSet<UserMessage>();
public Set<UserMessage> getUserMessageList() {
return userMessageList;
}
public void setUserMessageList(Set<UserMessage> userMessageList) {
this.userMessageList = userMessageList;
}
@Override
public String getAuthority() {
return getUserRole();
}
}
Hibernate mapping xml fro user entity:
<hibernate-mapping>
<class name="demidov.pkg.domain.User" table="USER_DESC">
<!-- Primary key ID will be generated depends on database
configuration -->
<id name="userId" column="ID">
<generator class="native"></generator>
</id>
<property name="userName" column="USER_NAME" unique="true" />
<property name="userPassword" column="USER_PASS"/>
<property name="userRole" >
<column name="USER_PRIV" default="ROLE_USER"/>
</property>
<property name="userEmale" column="USER_EMALE" unique="true"/>
<property name="userGender" column="USER_GENDER" />
<!-- User is owner of relationships, all changes on user will
effect UserMessage entity -->
<set name="userMessageList" inverse="true" lazy="false"
fetch="select" cascade="all">
<key>
<column name="USER_ID" not-null="true"/>
</key>
<one-to-many class="demidov.pkg.domain.UserMessage" />
</set>
</class>
</hibernate-mapping>
Please help me. I'm confused what is what: GrantedAuthority, UserDetails,
User and how they work with xml configuration of Spring Security.
Thanks.
how can i retrieve same column with two different alias?
how can i retrieve same column with two different alias?
I have one table called 'answers' with four column wherein adding answers
with positive and negative rankings and i want to retrieve answer with
different aliasing for answer with positive ranks and answer with negative
ranks. is there any way to retrieve same column with two different aliases
?
id answer rank question_id
1 Yes 1 1
2 No 2 1
3 True -2 2
4 False -1 2
I have one table called 'answers' with four column wherein adding answers
with positive and negative rankings and i want to retrieve answer with
different aliasing for answer with positive ranks and answer with negative
ranks. is there any way to retrieve same column with two different aliases
?
id answer rank question_id
1 Yes 1 1
2 No 2 1
3 True -2 2
4 False -1 2
Sunday, 29 September 2013
captureScreenshotOnFailure not working, broken
captureScreenshotOnFailure not working, broken
I can't get these screenshots working for the life of me:
The directories exist
The test executes (and fails) as expected
I've read everything I can find:
http://www.devinzuczek.com/2011/08/taking-a-screenshot-with-phpunit-and-selenium-rc/
PHPUnit Selenium captureScreenshotOnFailure does not work?
lots of others
Should be pretty simple, but there's no error messages, nothing. Can
anyone shed some light?
class ScreenshotTest extends PHPUnit_Extensions_Selenium2TestCase {
protected $captureScreenshotOnFailure = TRUE;
protected $screenshotPath = 'C:\\';
protected $screenshotUrl = 'http://127.0.0.1/';
protected function setUp()
{
$this->setBrowser('firefox');
$this->setBrowserUrl('http://127.0.0.1/');
}
public function testTitle()
{
$this->url('http://127.0.0.1');
$this->assertEquals('foobarbaz', $this->title());
} }
I can't get these screenshots working for the life of me:
The directories exist
The test executes (and fails) as expected
I've read everything I can find:
http://www.devinzuczek.com/2011/08/taking-a-screenshot-with-phpunit-and-selenium-rc/
PHPUnit Selenium captureScreenshotOnFailure does not work?
lots of others
Should be pretty simple, but there's no error messages, nothing. Can
anyone shed some light?
class ScreenshotTest extends PHPUnit_Extensions_Selenium2TestCase {
protected $captureScreenshotOnFailure = TRUE;
protected $screenshotPath = 'C:\\';
protected $screenshotUrl = 'http://127.0.0.1/';
protected function setUp()
{
$this->setBrowser('firefox');
$this->setBrowserUrl('http://127.0.0.1/');
}
public function testTitle()
{
$this->url('http://127.0.0.1');
$this->assertEquals('foobarbaz', $this->title());
} }
MVVM Light Portable Class Library Navigation
MVVM Light Portable Class Library Navigation
I am making a Windows Phone 8 app using the MVVM architecture and a
portable class library. I am currently using MVVM light messages to
navigate to a new page. Is there a different approach that I can use
instead of messages because I always have to put code in the code behind.
I am making a Windows Phone 8 app using the MVVM architecture and a
portable class library. I am currently using MVVM light messages to
navigate to a new page. Is there a different approach that I can use
instead of messages because I always have to put code in the code behind.
knockout "with" binding: each property to multiple controls
knockout "with" binding: each property to multiple controls
Within "with" binding div, I tried to bind 5 properties of a model to 2
different types of controls, namely textbox and label. However, only the
first property on the list is bound to two controls, the rest are only
bound to textbox:
<div data-bind="with: Object">
<input type= "text" data-bind="value: property1" /> <br />
<input type= "text" data-bind="value: property2" /> <br />
<input type= "text" data-bind="value: property3" /> <br />
<input type= "text" data-bind="value: property4" /> <br />
<input type= "text" data-bind="value: property5" /> <br />
<label data-bind="value: property1" /> <br />
<label data-bind="value: property2" /> <br />
<label data-bind="value: property3" /> <br />
<label data-bind="value: property4" /> <br />
<label data-bind="value: property5" /> <br />
</div>
Object is populated dynamically, meaning its properties are assigned
dynamically. In my view model, I have Object = ko.observable() . And once
user clicked some button, I have Object(createModel1()) executed, where
createModel1 returns a new Model1. Model1 has properties defined as
ko.observable.
I don't know whether this is not supposed to work or am I doing something
else wrong (barking at the wrong tree) Please help! Thank you!!!
Within "with" binding div, I tried to bind 5 properties of a model to 2
different types of controls, namely textbox and label. However, only the
first property on the list is bound to two controls, the rest are only
bound to textbox:
<div data-bind="with: Object">
<input type= "text" data-bind="value: property1" /> <br />
<input type= "text" data-bind="value: property2" /> <br />
<input type= "text" data-bind="value: property3" /> <br />
<input type= "text" data-bind="value: property4" /> <br />
<input type= "text" data-bind="value: property5" /> <br />
<label data-bind="value: property1" /> <br />
<label data-bind="value: property2" /> <br />
<label data-bind="value: property3" /> <br />
<label data-bind="value: property4" /> <br />
<label data-bind="value: property5" /> <br />
</div>
Object is populated dynamically, meaning its properties are assigned
dynamically. In my view model, I have Object = ko.observable() . And once
user clicked some button, I have Object(createModel1()) executed, where
createModel1 returns a new Model1. Model1 has properties defined as
ko.observable.
I don't know whether this is not supposed to work or am I doing something
else wrong (barking at the wrong tree) Please help! Thank you!!!
SQL Select data if only data exist
SQL Select data if only data exist
I created a register form and logging form with html, and I created a
database for it, but when I insert invalid data (data that doesn't exist
in database) to the logging form, It doesn't show an error, I want an
error msg when I insert invalid data (data that doesn't exist in
database), how i do it?
I created a register form and logging form with html, and I created a
database for it, but when I insert invalid data (data that doesn't exist
in database) to the logging form, It doesn't show an error, I want an
error msg when I insert invalid data (data that doesn't exist in
database), how i do it?
Saturday, 28 September 2013
Having trouble with linked list functions
Having trouble with linked list functions
I'm having trouble using a member function of a pointer to a video object.
My code is as follows:
vlist.h:
5 #ifndef VLIST_H
6 #define VLIST_H
7
8 #include<iostream>
9 using namespace std;
10
11 #include<string>
12 #include"video.h"
13
14 class Vlist
15 {
16 public:
17 Vlist();
18 // ~Vlist();
19 void insert(Video *vid);
20 // void insert_alphabetical(Video *vid);
21 void print();
22 // void length();
23 bool lookup(string title);
24 bool remove(string title);
25 private:
26 class Node
27 {
28 public:
29 Node(Video *vid, Node *next)
30 {m_vid = vid; m_next = next;}
31 Video *m_vid;
32 Node *m_next;
33 };
34 Node *m_head;
35 };
36
37
I'm having trouble using a member function of a pointer to a video object.
My code is as follows:
vlist.h:
5 #ifndef VLIST_H
6 #define VLIST_H
7
8 #include<iostream>
9 using namespace std;
10
11 #include<string>
12 #include"video.h"
13
14 class Vlist
15 {
16 public:
17 Vlist();
18 // ~Vlist();
19 void insert(Video *vid);
20 // void insert_alphabetical(Video *vid);
21 void print();
22 // void length();
23 bool lookup(string title);
24 bool remove(string title);
25 private:
26 class Node
27 {
28 public:
29 Node(Video *vid, Node *next)
30 {m_vid = vid; m_next = next;}
31 Video *m_vid;
32 Node *m_next;
33 };
34 Node *m_head;
35 };
36
37
form variables not passing to php
form variables not passing to php
I'm using php version 5.5.1 and Apache server if this information helps I
have a simple form and I'm trying to pass the form variable to php and
output the value. I am a beginner in php so please excuse me if this is
something obvious, I have tried to solve this myself with the almighty
google but wasn't successful. The html form code is as follows
<html>
<head>
<title>Form</title>
</head>
<body>
<form method="post" action="test1.php">
<input type="text" name="username">
<input type="submit">
</form>
</body>
</html>
Then the php to handle the form is:
<html>
<head>
<title>Form</title>
</head>
<body>
<?php
echo "<h1>Hello " . $_POST["username"] . "</h1>";
?>
</body>
</html>
The output I'm getting no matter what I type into the html form is , Hello
" . $_POST["username"] . ""; ?>
I don't know why it also outputs the ending semi colon and ending php tag
also, maybe this is evidence of what's going wrong here?
Any and all help is appreciated! Thank You.
I'm using php version 5.5.1 and Apache server if this information helps I
have a simple form and I'm trying to pass the form variable to php and
output the value. I am a beginner in php so please excuse me if this is
something obvious, I have tried to solve this myself with the almighty
google but wasn't successful. The html form code is as follows
<html>
<head>
<title>Form</title>
</head>
<body>
<form method="post" action="test1.php">
<input type="text" name="username">
<input type="submit">
</form>
</body>
</html>
Then the php to handle the form is:
<html>
<head>
<title>Form</title>
</head>
<body>
<?php
echo "<h1>Hello " . $_POST["username"] . "</h1>";
?>
</body>
</html>
The output I'm getting no matter what I type into the html form is , Hello
" . $_POST["username"] . ""; ?>
I don't know why it also outputs the ending semi colon and ending php tag
also, maybe this is evidence of what's going wrong here?
Any and all help is appreciated! Thank You.
How do I make an emualator for a certain device?
How do I make an emualator for a certain device?
So I'm trying to make a new emulator in "Virtual Devcice Manager" in
Eclipse. I want it to be the same as a certain device (same screen size,
same android version installed as it is by default on that device etc.).
The device I'm trying to "re-create" as an emulator is Sony Xperia Z. I
searched for the phone's specs and this is what I found:
Android 4.1
12.7cm (5") screen
I then tried to create a new virtual device in eclipse and I don't have
any of these options. The closest Android version that Eclipse lets you
use for Virtual device is 4.1.2 and the closest screen size is 5.1" WVGA
If I created a virtual device like this, would it be good? Would an
application that I ran on this virtual device behave the exact same way as
on actual Sony Xperia Z?
So I'm trying to make a new emulator in "Virtual Devcice Manager" in
Eclipse. I want it to be the same as a certain device (same screen size,
same android version installed as it is by default on that device etc.).
The device I'm trying to "re-create" as an emulator is Sony Xperia Z. I
searched for the phone's specs and this is what I found:
Android 4.1
12.7cm (5") screen
I then tried to create a new virtual device in eclipse and I don't have
any of these options. The closest Android version that Eclipse lets you
use for Virtual device is 4.1.2 and the closest screen size is 5.1" WVGA
If I created a virtual device like this, would it be good? Would an
application that I ran on this virtual device behave the exact same way as
on actual Sony Xperia Z?
In R, how to add the fitted value column to the original dataframe?
In R, how to add the fitted value column to the original dataframe?
I got a multiple regression model. And I want to add the fitted values and
residuals to the original dataframe as a two new column, how can I achieve
that? Thanks in advance.
I got a multiple regression model. And I want to add the fitted values and
residuals to the original dataframe as a two new column, how can I achieve
that? Thanks in advance.
Friday, 27 September 2013
File Encoding Format : ANSI_134_1968 and UTF : 8 Diffrence?
File Encoding Format : ANSI_134_1968 and UTF : 8 Diffrence?
i would like to know what is diffrence between File Encoding Format :
ANSI_134_1968 and UTF : 8.
please let me know your suggection's
thank you.
tousif shaikh
i would like to know what is diffrence between File Encoding Format :
ANSI_134_1968 and UTF : 8.
please let me know your suggection's
thank you.
tousif shaikh
Incorrect Casting
Incorrect Casting
For some reason I am getting a precision error when I try to compile my
code. The precision error comes in the return of my second method where I
am trying to calculate the circumference. What am I doing incorrectly?
public class Methods2
{
public static final double PI = 3.14;
public static double calcCirc(double x)
{
return PI*x;
}
public static int calcCirc(int x)
{
return (2*(double) x)*PI;
}
public static void main(String[]args)
{
System.out.println(calcCirc(10.2));
System.out.println(calcCirc(4));
}
}
For some reason I am getting a precision error when I try to compile my
code. The precision error comes in the return of my second method where I
am trying to calculate the circumference. What am I doing incorrectly?
public class Methods2
{
public static final double PI = 3.14;
public static double calcCirc(double x)
{
return PI*x;
}
public static int calcCirc(int x)
{
return (2*(double) x)*PI;
}
public static void main(String[]args)
{
System.out.println(calcCirc(10.2));
System.out.println(calcCirc(4));
}
}
Ajax call returns data with "/n" tags
Ajax call returns data with "/n" tags
Hey All I've been searching around for awhile and haven't much luck
finding the reasoning behind this so hopefully somebody can help me. I
don't understand why it is returning newline characters
$('#tbl tr td').click(function () {
// Here selection =" 710-610A " spaces are included
var selection = $(this).text();
alert(selection)
$.ajax({
type: "Post",
url: "/Home/Index/",
dataType: "json",
data: { grpCode: selection },
success: function (ResponseData) {},
error: function (errorResponse) {
alert('AJAX Call Failed');
}
// When passed grpCode = "\n 710-610A\n "
I dnt understand why theres so many spaces along with it
[HttpPost]
public ActionResult Index(string grpCode)
{
// do something
}
I'm thinking it has something to do with the way I'm displaying my table
in the View
<table id="tbl">
<tr>
<th>
Groups
</th>
</tr>
@foreach (var item in Model.groupCodesList.Select(m=>
m.Group_Code).Distinct())
{
<tr>
<td>
@item
</td>
</tr>
}
</table>
I am using EF Code First to retrieve Data
Hey All I've been searching around for awhile and haven't much luck
finding the reasoning behind this so hopefully somebody can help me. I
don't understand why it is returning newline characters
$('#tbl tr td').click(function () {
// Here selection =" 710-610A " spaces are included
var selection = $(this).text();
alert(selection)
$.ajax({
type: "Post",
url: "/Home/Index/",
dataType: "json",
data: { grpCode: selection },
success: function (ResponseData) {},
error: function (errorResponse) {
alert('AJAX Call Failed');
}
// When passed grpCode = "\n 710-610A\n "
I dnt understand why theres so many spaces along with it
[HttpPost]
public ActionResult Index(string grpCode)
{
// do something
}
I'm thinking it has something to do with the way I'm displaying my table
in the View
<table id="tbl">
<tr>
<th>
Groups
</th>
</tr>
@foreach (var item in Model.groupCodesList.Select(m=>
m.Group_Code).Distinct())
{
<tr>
<td>
@item
</td>
</tr>
}
</table>
I am using EF Code First to retrieve Data
Precision timing using DateTime possible?
Precision timing using DateTime possible?
I would like to test the time required by certain methods and SQL queries
in my code. I've tried doing the following:
DateTime start = DateTime.Now;
//Do something
DateTime end = DateTime.Now;
TimeSpan ts = end - start;
int millis = ts.Milliseconds;
But I just don't feel that this is the right way of doing it. I often get
back a value of 1 for some methods and values like 200 for others, are
there any accurate ways to measure and record this kind of thing?
I would like to test the time required by certain methods and SQL queries
in my code. I've tried doing the following:
DateTime start = DateTime.Now;
//Do something
DateTime end = DateTime.Now;
TimeSpan ts = end - start;
int millis = ts.Milliseconds;
But I just don't feel that this is the right way of doing it. I often get
back a value of 1 for some methods and values like 200 for others, are
there any accurate ways to measure and record this kind of thing?
How to restrict foreign keys in Rails' update controller action?
How to restrict foreign keys in Rails' update controller action?
In my Rails app I have invoices which in turn can have many projects.
model:
class Invoice < ActiveRecord::Base
attr_accessible :project_id
end
controller:
class InvoicesController < ApplicationController
before_filter :authorized_user, :only => [ :show, :edit, :destroy ]
before_filter :authorized_project, :only => [ :create, :update ]
def create # safe
@invoice = @project.invoices.build(params[:invoice])
if @invoice.save
flash[:success] = "Invoice saved."
redirect_to edit_invoice_path(@invoice)
else
render :new
end
end
def update # not safe yet
if @invoice.update_attributes(params[:invoice])
flash[:success] = "Invoice updated."
redirect_to edit_invoice_path(@invoice)
else
render :edit
end
end
private
def authorized_user
@invoice = Invoice.find(params[:id])
redirect_to root_path unless current_user?(@invoice.user)
end
def authorized_project
@project = Project.find(params[:invoice][:project_id])
redirect_to root_path unless current_user?(@project.user)
end
end
My biggest concern is that a malicious user might, one day, create an
invoice that belongs to the project of another user.
Now thanks to the help of some people on this board I managed to come up
with a before_filter that makes sure that this won't happen when a project
is created.
The problem is I don't understand how to apply this filter to the update
action as well.
Since the update action does not make use of Rails' build function, I
simply don't know how to get my @project in there.
Can anybody help?
In my Rails app I have invoices which in turn can have many projects.
model:
class Invoice < ActiveRecord::Base
attr_accessible :project_id
end
controller:
class InvoicesController < ApplicationController
before_filter :authorized_user, :only => [ :show, :edit, :destroy ]
before_filter :authorized_project, :only => [ :create, :update ]
def create # safe
@invoice = @project.invoices.build(params[:invoice])
if @invoice.save
flash[:success] = "Invoice saved."
redirect_to edit_invoice_path(@invoice)
else
render :new
end
end
def update # not safe yet
if @invoice.update_attributes(params[:invoice])
flash[:success] = "Invoice updated."
redirect_to edit_invoice_path(@invoice)
else
render :edit
end
end
private
def authorized_user
@invoice = Invoice.find(params[:id])
redirect_to root_path unless current_user?(@invoice.user)
end
def authorized_project
@project = Project.find(params[:invoice][:project_id])
redirect_to root_path unless current_user?(@project.user)
end
end
My biggest concern is that a malicious user might, one day, create an
invoice that belongs to the project of another user.
Now thanks to the help of some people on this board I managed to come up
with a before_filter that makes sure that this won't happen when a project
is created.
The problem is I don't understand how to apply this filter to the update
action as well.
Since the update action does not make use of Rails' build function, I
simply don't know how to get my @project in there.
Can anybody help?
Resizing Bitmap to fit other Bitmap
Resizing Bitmap to fit other Bitmap
I have problem with displaying bitmaps. I have bitmap (maker) that is
loaded from resource and placed on the map and i download bitmap (avatar)
from the server with specific dimensions and I place the avatar in the
center of the marker. The result is that on one phone every thing works
fine but on other the avatar is larger then maker. What should I do?
I have problem with displaying bitmaps. I have bitmap (maker) that is
loaded from resource and placed on the map and i download bitmap (avatar)
from the server with specific dimensions and I place the avatar in the
center of the marker. The result is that on one phone every thing works
fine but on other the avatar is larger then maker. What should I do?
CSS how to keep text always inline with a paragraph
CSS how to keep text always inline with a paragraph
I have a block of text with unknown width and I would like to place
another text right after it that would always stick to the last word. If
the first block is one line then setting them both to 'inline' or
'inline-block' is enough, but if the first block is more than one line,
the second block always goes to the next line.
Code:
<div id="text">sit amet, consectetur adipiscing elit. Donec facilisis eros
arcu, sed dictum lorem consequat a. Duis sodales rhoncus felis at
convallis.</div>
<div id="new">New</div>
div {
float: left;
display: inline-block;
}
http://jsfiddle.net/nmuUd/1/
'New' needs to always stick to the last word of the previous block. How
can I do this?
I have a block of text with unknown width and I would like to place
another text right after it that would always stick to the last word. If
the first block is one line then setting them both to 'inline' or
'inline-block' is enough, but if the first block is more than one line,
the second block always goes to the next line.
Code:
<div id="text">sit amet, consectetur adipiscing elit. Donec facilisis eros
arcu, sed dictum lorem consequat a. Duis sodales rhoncus felis at
convallis.</div>
<div id="new">New</div>
div {
float: left;
display: inline-block;
}
http://jsfiddle.net/nmuUd/1/
'New' needs to always stick to the last word of the previous block. How
can I do this?
Thursday, 26 September 2013
PHP Pagination query not working
PHP Pagination query not working
In my controller I have the following code:
if($action=='shipping_list'){
$numrows=inquire_row(); //Get number of rows in query
$pages= new Paginator('10', 'p'); //create object
$pages->set_total($numrows);
$shipping=shipping_list(); //Goes to model
include('shipping_list.php');
}
In my model I these codes:
function shipping_list(){
global $MEMS;
global $pages;
$query = "SELECT * FROM Inventory" .$pages->get_limit()
."WHERE Yield >=320 AND (Q = 'Pass' OR Q='No Q') AND shipdate = ' '
ORDER BY Wafer ASC, RC ASC";
echo $query;
$shipping = $MEMS -> query($query);
var_dump($shipping);
return $shipping;
}
When I echo $query, I get
SELECT * FROM Inventory LIMIT 0, 20 WHERE Yield >=320 AND (Q = 'Pass' OR
Q='No Q') AND shipdate = ' ' ORDER BY Wafer ASC, RC ASC
So I know everything is right up to that point. However, when I var_dump
$shipping, I get bool(false). Why isn't my query returning the right
results?
In my controller I have the following code:
if($action=='shipping_list'){
$numrows=inquire_row(); //Get number of rows in query
$pages= new Paginator('10', 'p'); //create object
$pages->set_total($numrows);
$shipping=shipping_list(); //Goes to model
include('shipping_list.php');
}
In my model I these codes:
function shipping_list(){
global $MEMS;
global $pages;
$query = "SELECT * FROM Inventory" .$pages->get_limit()
."WHERE Yield >=320 AND (Q = 'Pass' OR Q='No Q') AND shipdate = ' '
ORDER BY Wafer ASC, RC ASC";
echo $query;
$shipping = $MEMS -> query($query);
var_dump($shipping);
return $shipping;
}
When I echo $query, I get
SELECT * FROM Inventory LIMIT 0, 20 WHERE Yield >=320 AND (Q = 'Pass' OR
Q='No Q') AND shipdate = ' ' ORDER BY Wafer ASC, RC ASC
So I know everything is right up to that point. However, when I var_dump
$shipping, I get bool(false). Why isn't my query returning the right
results?
Wednesday, 25 September 2013
Visual Studio Load Test Support for (.Net, C#, WPF , WCF, Silverlight)
Visual Studio Load Test Support for (.Net, C#, WPF , WCF, Silverlight)
I need your help to find out Visual Studio Credibility, pros and cons. Can
you please answer me following question with reference links: 1.
Reputation of tool and its results in market? 2. Which companies are
currently using Visual Studio 2010 load testing tool? 3. Reputation w.r.t
the technologies (.Net, C#, WPF , WCF, Silverlight)? 4. What is the market
share of Visual studio 2010 load testing tool?
Thank you in advance.
Regards, Atif Abbas
I need your help to find out Visual Studio Credibility, pros and cons. Can
you please answer me following question with reference links: 1.
Reputation of tool and its results in market? 2. Which companies are
currently using Visual Studio 2010 load testing tool? 3. Reputation w.r.t
the technologies (.Net, C#, WPF , WCF, Silverlight)? 4. What is the market
share of Visual studio 2010 load testing tool?
Thank you in advance.
Regards, Atif Abbas
Thursday, 19 September 2013
c++ : the game of life?
c++ : the game of life?
i really need your help and really fast. i've been working on this project
where i am supposed to create a simulation of conway's game of life.
A cell can only be in one of two states: alive or dead. There are two
kinds of cells: ConwayCells and FredkinCells.
Live ConwayCells are denoted with an asterisk, "*", and dead cells are
denoted with a period, "." A ConwayCell has 8 neighbours, if it's an
interior cell, 5 neighbours, if it's an edge cell, and 3 neighbours, if
it's a corner cell
ConwayCells do not have the notion of age, FredkinCells do. A
FredkinCells' age is initially zero and only increments by one if the cell
is alive and stays alive. Live FredkinCells are denoted with their age, if
their age is less than 10, otherwise denoted with a plus, "+", and dead
cells are denoted with a minus, "-". A FredkinCell has 4 neighbours, if
it's an interior cell, 3 neighbours, if it's an edge cell, and 2
neighbours, if it's a corner cell.
The rules for going from one generation to the next for ConwayCells are:
a dead cell becomes a live cell, if exactly 3 neighbours are alive
a live cell becomes a dead cell, if less than 2 or more than 3 neighbours
are alive
The rules for going from one generation to the next for FredkinCells are:
a dead cell becomes a live cell, if 1 or 3 neighbours are alive
a live cell becomes a dead cell, if 0, 2, or 4 neighbours are alive
I have to create 5 classes: *Cell class(abstract) from which two are
derived ConwayCell and FredkinCell where each of these cells knows how to
print itself, whether it is alive or not and how many neighbours are
alive. *Life class(abstract) from which two others are derived :
fredkinLife and conwayLife.the subclasses should have functions that keeps
track of the grid (2d dynamic array) and generation , that plays life ,
that evolves , and that prints itself.
And a LifeFactory class that would shoose between creating a fredkinLife
or a ConwayLife.
To push Life forward one generation (evolve), traverse the grid of cells,
only notice the live cells, and for each of them, visit the neighbours and
increment their respective neighbour counts. Remember that the two kinds
of cells have different definitions of neighbour. Traverse the grid a
second time, set the next state, and zero out the neighbour count.
Remember that the two kinds of cells have different rules for the next
state.
In a main program, you will read in initial board states from an input
file and iterate through several generations of the game of life.
#include <iostream>
#include <fstream>
using namespace std;
const int _rows = 109;
const int _columns = 69;
const int maxRows = 20;
const int maxColumns = 20;
class Cell{
protected:
char cell;
int count; // nb of neighbors alive
public:
Cell( char unit = NULL , int n = 0 ){
cell = unit;
count = n;
}
int get_count(){
return count;
}
virtual bool is_live()=0;
virtual int _neighbors()=0;
virtual void print();
};
class ConwayCell : public Cell {
public:
ConwayCell( char unit = NULL , int n = 0 ){
count = n;
cell = unit;;
}
bool is_live(){
if( cell = '*' )
return true;
else if( cell = '.' )
return false;
}
int _neighbors(){
char c[_rows][_columns] = {0};
for( int i=0; i<_rows ; ++i){
for( int j=0; j<_columns ; ++j){
//if( (i == 0 && j == 0) || ( i == _rows - 1 && j ==
_columns - 1 ) || (i == 0 && j == _columns - 1 ) || (i ==
_rows && j == 0) ){
if( c[ i + 1][j] == '*')
count++;
if( c[i][j+1] == '*')
count++;
if( c[i+1][j+1] == '*')
count++;
if( c[i-1][j] == '*')
count++;
if( c[i-1][j-1] == '*')
count++;
if( c[i][j-1] == '*')
count++;
if( c[i-1][j+1] == '*')
count++;
if( c[i+1][j-1] == '*')
count++;
}
}
return count;
}
void print(){
if( ConwayCell::is_live())
cout << '*' ;
else
cout << '.' ;
}
};
class FredkinCell : public Cell {
int cellAge;
public:
FredkinCell( char unit = NULL , int n = 0 , int age = 0 ){
count = n;
cell = unit;
cellAge = age;
if(cell == '+')
cellAge = 10;
else if (cell != '-')
age = (cell - '0');
}
int get_age(){
return cellAge;
}
bool is_live(){
switch (cell){
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '+':
return true;
break;
default:
return false;
}
}
char age(){
if(!FredkinCell::is_live())
return '-';
else if(cellAge>9)
return '+';
return cellAge + '0';
}
int _neighbors(){
char c[maxRows][maxColumns];
for( int i=0; i<maxRows ; ++i){
for( int j = 0; j<maxColumns ; ++j){
if( (c[i+1][j] >= '0' && c[i+1][j] < '10') || c[i+1][j]
== '+' )
count++;
if( (c[i][j+1] >= '0' && c[i][j+1] < '10') || c[i][j+1]
== '+')
count++;
if( (c[i+1][j+1] >= '0' && c[i+1][j+1] < '10') ||
c[i+1][j+1] == '+')
count++;
if( (c[i-1][j] >= '0' && c[i-1][j] < '10') || c[i-1][j]
== '+')
count++;
if( (c[i-1][j-1] >= '0' && c[i-1][j-1] < '10') ||
c[i-1][j-1] == '+')
count++;
if( (c[i][j-1] >= '0' && c[i][j-1] < '10') || c[i][j-1]
== '+')
count++;
if( (c[i-1][j+1] >= '0' && c[i-1][j+1] < '10') ||
c[i-1][j+1] == '+')
count++;
if( (c[i+1][j-1] >= '0' && c[i+1][j-1] < '10') ||
c[i+1][j-1] == '+')
count++;
}
}
return count;
}
void print(){
for( int i=0; i < maxRows ; ++i){
for( int j=0; j< maxColumns; ++j){
if(!FredkinCell::is_live())
cout << "-" ;
else
cout << cell ;
}
}
}
};
class Life {
Cell ** c;
int generation;
int population;
public:
Life(Cell **cell = NULL, int g=0, int p=0){
cell = c;
generation = g;
population = p;
}
virtual void grid() = 0;
virtual void evolve() = 0;
virtual void play() =0;
virtual void print() =0;
};
class ConwayLife {
public:
ConwayLife(){
c = new char * [_rows];
for( int i=0; i< _rows ; ++i)
c[i] = new char[_columns];
}
void grid();
void play();
void evolve();
void print (){
for( int i=0; i< _rows; ++i){
for( int j=0; j< _columns ; ++j){
cout << c[i][j] << " ";
}
cout << endl;
}
}
~ConwayLife(){
for( int i=0; i< _rows;++i)
delete [] c[i];
delete [] c;
}
};
class FredkinLife {
public:
FredkinLife(){
c = new char * [_rows];
for( int i=0; i< _rows ; ++i)
c[i] = new char[_columns];
}
void grid();
void play();
void evolve();
void print (){
for( int i=0; i< maxRows; ++i){
for( int j=0; j< maxColumns ; ++j){
cout << c[i][j] << " ";
}
cout << endl;
}
}
~FredkinLife(){
for( int i=0; i< maxRows;++i)
delete [] c[i];
delete [] c;
}
};
basically what i am asking for is someone to check if my code is correct
and to help me implement gthe other functions in class Life (no code is
required) just detailed explanation
i really need your help and really fast. i've been working on this project
where i am supposed to create a simulation of conway's game of life.
A cell can only be in one of two states: alive or dead. There are two
kinds of cells: ConwayCells and FredkinCells.
Live ConwayCells are denoted with an asterisk, "*", and dead cells are
denoted with a period, "." A ConwayCell has 8 neighbours, if it's an
interior cell, 5 neighbours, if it's an edge cell, and 3 neighbours, if
it's a corner cell
ConwayCells do not have the notion of age, FredkinCells do. A
FredkinCells' age is initially zero and only increments by one if the cell
is alive and stays alive. Live FredkinCells are denoted with their age, if
their age is less than 10, otherwise denoted with a plus, "+", and dead
cells are denoted with a minus, "-". A FredkinCell has 4 neighbours, if
it's an interior cell, 3 neighbours, if it's an edge cell, and 2
neighbours, if it's a corner cell.
The rules for going from one generation to the next for ConwayCells are:
a dead cell becomes a live cell, if exactly 3 neighbours are alive
a live cell becomes a dead cell, if less than 2 or more than 3 neighbours
are alive
The rules for going from one generation to the next for FredkinCells are:
a dead cell becomes a live cell, if 1 or 3 neighbours are alive
a live cell becomes a dead cell, if 0, 2, or 4 neighbours are alive
I have to create 5 classes: *Cell class(abstract) from which two are
derived ConwayCell and FredkinCell where each of these cells knows how to
print itself, whether it is alive or not and how many neighbours are
alive. *Life class(abstract) from which two others are derived :
fredkinLife and conwayLife.the subclasses should have functions that keeps
track of the grid (2d dynamic array) and generation , that plays life ,
that evolves , and that prints itself.
And a LifeFactory class that would shoose between creating a fredkinLife
or a ConwayLife.
To push Life forward one generation (evolve), traverse the grid of cells,
only notice the live cells, and for each of them, visit the neighbours and
increment their respective neighbour counts. Remember that the two kinds
of cells have different definitions of neighbour. Traverse the grid a
second time, set the next state, and zero out the neighbour count.
Remember that the two kinds of cells have different rules for the next
state.
In a main program, you will read in initial board states from an input
file and iterate through several generations of the game of life.
#include <iostream>
#include <fstream>
using namespace std;
const int _rows = 109;
const int _columns = 69;
const int maxRows = 20;
const int maxColumns = 20;
class Cell{
protected:
char cell;
int count; // nb of neighbors alive
public:
Cell( char unit = NULL , int n = 0 ){
cell = unit;
count = n;
}
int get_count(){
return count;
}
virtual bool is_live()=0;
virtual int _neighbors()=0;
virtual void print();
};
class ConwayCell : public Cell {
public:
ConwayCell( char unit = NULL , int n = 0 ){
count = n;
cell = unit;;
}
bool is_live(){
if( cell = '*' )
return true;
else if( cell = '.' )
return false;
}
int _neighbors(){
char c[_rows][_columns] = {0};
for( int i=0; i<_rows ; ++i){
for( int j=0; j<_columns ; ++j){
//if( (i == 0 && j == 0) || ( i == _rows - 1 && j ==
_columns - 1 ) || (i == 0 && j == _columns - 1 ) || (i ==
_rows && j == 0) ){
if( c[ i + 1][j] == '*')
count++;
if( c[i][j+1] == '*')
count++;
if( c[i+1][j+1] == '*')
count++;
if( c[i-1][j] == '*')
count++;
if( c[i-1][j-1] == '*')
count++;
if( c[i][j-1] == '*')
count++;
if( c[i-1][j+1] == '*')
count++;
if( c[i+1][j-1] == '*')
count++;
}
}
return count;
}
void print(){
if( ConwayCell::is_live())
cout << '*' ;
else
cout << '.' ;
}
};
class FredkinCell : public Cell {
int cellAge;
public:
FredkinCell( char unit = NULL , int n = 0 , int age = 0 ){
count = n;
cell = unit;
cellAge = age;
if(cell == '+')
cellAge = 10;
else if (cell != '-')
age = (cell - '0');
}
int get_age(){
return cellAge;
}
bool is_live(){
switch (cell){
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '+':
return true;
break;
default:
return false;
}
}
char age(){
if(!FredkinCell::is_live())
return '-';
else if(cellAge>9)
return '+';
return cellAge + '0';
}
int _neighbors(){
char c[maxRows][maxColumns];
for( int i=0; i<maxRows ; ++i){
for( int j = 0; j<maxColumns ; ++j){
if( (c[i+1][j] >= '0' && c[i+1][j] < '10') || c[i+1][j]
== '+' )
count++;
if( (c[i][j+1] >= '0' && c[i][j+1] < '10') || c[i][j+1]
== '+')
count++;
if( (c[i+1][j+1] >= '0' && c[i+1][j+1] < '10') ||
c[i+1][j+1] == '+')
count++;
if( (c[i-1][j] >= '0' && c[i-1][j] < '10') || c[i-1][j]
== '+')
count++;
if( (c[i-1][j-1] >= '0' && c[i-1][j-1] < '10') ||
c[i-1][j-1] == '+')
count++;
if( (c[i][j-1] >= '0' && c[i][j-1] < '10') || c[i][j-1]
== '+')
count++;
if( (c[i-1][j+1] >= '0' && c[i-1][j+1] < '10') ||
c[i-1][j+1] == '+')
count++;
if( (c[i+1][j-1] >= '0' && c[i+1][j-1] < '10') ||
c[i+1][j-1] == '+')
count++;
}
}
return count;
}
void print(){
for( int i=0; i < maxRows ; ++i){
for( int j=0; j< maxColumns; ++j){
if(!FredkinCell::is_live())
cout << "-" ;
else
cout << cell ;
}
}
}
};
class Life {
Cell ** c;
int generation;
int population;
public:
Life(Cell **cell = NULL, int g=0, int p=0){
cell = c;
generation = g;
population = p;
}
virtual void grid() = 0;
virtual void evolve() = 0;
virtual void play() =0;
virtual void print() =0;
};
class ConwayLife {
public:
ConwayLife(){
c = new char * [_rows];
for( int i=0; i< _rows ; ++i)
c[i] = new char[_columns];
}
void grid();
void play();
void evolve();
void print (){
for( int i=0; i< _rows; ++i){
for( int j=0; j< _columns ; ++j){
cout << c[i][j] << " ";
}
cout << endl;
}
}
~ConwayLife(){
for( int i=0; i< _rows;++i)
delete [] c[i];
delete [] c;
}
};
class FredkinLife {
public:
FredkinLife(){
c = new char * [_rows];
for( int i=0; i< _rows ; ++i)
c[i] = new char[_columns];
}
void grid();
void play();
void evolve();
void print (){
for( int i=0; i< maxRows; ++i){
for( int j=0; j< maxColumns ; ++j){
cout << c[i][j] << " ";
}
cout << endl;
}
}
~FredkinLife(){
for( int i=0; i< maxRows;++i)
delete [] c[i];
delete [] c;
}
};
basically what i am asking for is someone to check if my code is correct
and to help me implement gthe other functions in class Life (no code is
required) just detailed explanation
Yii order/search related model in bootstrap.widgets.TbGridView
Yii order/search related model in bootstrap.widgets.TbGridView
there is 3 tables article, author and university
I'm making a grid for table article. Every article belongs to one author
and every author belongs to one university. I need to show University.name
| Author.name | Article.*
At admin view
$gridWidget=$this->widget('bootstrap.widgets.TbGridView',array(
'id'=>'dados-cd-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
'author_name'=>array(
'name' => 'author_name',
'value' => '$data->author->name'
),
'university_name'=>array(
'name' => 'university_name',
'value' => '$data->university->author->nome'
),
...
array(
'class'=>'bootstrap.widgets.TbButtonColumn',
),
),
));
And at article model I have
public $author_name;
public $university_name;
public function rules()
{
...
return array(
array('author.name, university.name, ... , 'safe', 'on'=>'searc
h'),
...
);
}
public function search()
{
$criteria=new CDbCriteria;
$criteria->with = array( 'author','author.university' );
$criteria->compare('author.name',$this->author_name,true);
$criteria->compare('university.name',$this->university_name,true);
...
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
'sort'=>array(
'attributes'=>array(
'author_name'=>array(
'asc'=>'author.name',
'desc'=>'author.name DESC',
),
'university_name'=>array(
'asc'=>'university.name',
'desc'=>'university.name DESC',
),
'*',
),
),
));
}
The grid is working perfect fine. However when I try to search or order by
author_name I got a error message. I'll try to translate the error message
from portuguese but I don't know if it is like that in english: "Undefined
table:7 Error: missing entry for table author"
The funny part is that the university search and order is working just
fine. And I can't see the diference between they.
Anyone can help me?
there is 3 tables article, author and university
I'm making a grid for table article. Every article belongs to one author
and every author belongs to one university. I need to show University.name
| Author.name | Article.*
At admin view
$gridWidget=$this->widget('bootstrap.widgets.TbGridView',array(
'id'=>'dados-cd-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
'author_name'=>array(
'name' => 'author_name',
'value' => '$data->author->name'
),
'university_name'=>array(
'name' => 'university_name',
'value' => '$data->university->author->nome'
),
...
array(
'class'=>'bootstrap.widgets.TbButtonColumn',
),
),
));
And at article model I have
public $author_name;
public $university_name;
public function rules()
{
...
return array(
array('author.name, university.name, ... , 'safe', 'on'=>'searc
h'),
...
);
}
public function search()
{
$criteria=new CDbCriteria;
$criteria->with = array( 'author','author.university' );
$criteria->compare('author.name',$this->author_name,true);
$criteria->compare('university.name',$this->university_name,true);
...
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
'sort'=>array(
'attributes'=>array(
'author_name'=>array(
'asc'=>'author.name',
'desc'=>'author.name DESC',
),
'university_name'=>array(
'asc'=>'university.name',
'desc'=>'university.name DESC',
),
'*',
),
),
));
}
The grid is working perfect fine. However when I try to search or order by
author_name I got a error message. I'll try to translate the error message
from portuguese but I don't know if it is like that in english: "Undefined
table:7 Error: missing entry for table author"
The funny part is that the university search and order is working just
fine. And I can't see the diference between they.
Anyone can help me?
Regex pattern for Validating phone number in C#
Regex pattern for Validating phone number in C#
I have a input string ("My phone number is 860-678 - 2345"). From the
input string I need to validate phone number using Regex and need to
replace the phone number with (xxxxxxxxxx).
I am using the below pattern but it doesn't work if the phone number
contains white Space in it.
[(]?[2-9]{1}[0-9]{2}[)-. ,]?[2-9]{1}[0-9]{2}[-. ,]?[0-9]{4}
Thanks.
I have a input string ("My phone number is 860-678 - 2345"). From the
input string I need to validate phone number using Regex and need to
replace the phone number with (xxxxxxxxxx).
I am using the below pattern but it doesn't work if the phone number
contains white Space in it.
[(]?[2-9]{1}[0-9]{2}[)-. ,]?[2-9]{1}[0-9]{2}[-. ,]?[0-9]{4}
Thanks.
Math.round is not working as i want to
Math.round is not working as i want to
Whenever a double is returned from the calculateVolume() it gets a value
for example 1.0, this need to be displayed as 1.00 (2 decimals instead of
1). It's probably quite easy but i'm not seeing what i'm doing wrong right
now. Can someone help me out and give a short explanation. Thanks a lot!
public class Block extends Shape {
private double length;
private double width;
private double height;
public Block(double length, double width, double height){
this.length = length;
this.width = width;
this.height = height;
}
@Override
public double calculateVolume(){
return Math.round((length * width * height)* 100.0) / 100.0;
}
Whenever a double is returned from the calculateVolume() it gets a value
for example 1.0, this need to be displayed as 1.00 (2 decimals instead of
1). It's probably quite easy but i'm not seeing what i'm doing wrong right
now. Can someone help me out and give a short explanation. Thanks a lot!
public class Block extends Shape {
private double length;
private double width;
private double height;
public Block(double length, double width, double height){
this.length = length;
this.width = width;
this.height = height;
}
@Override
public double calculateVolume(){
return Math.round((length * width * height)* 100.0) / 100.0;
}
Search through multidimentional array JavaScript
Search through multidimentional array JavaScript
I got stuck trying to retrive array items. So here is the deal. I have a
two dimentional array which has value and key so example of my data is:
[
Object { css="SS", title="Apple"},
Object { css="SS", title="Orange"},
Object { css="SS", title="Banana"}
]
I want to see if an object exists in the array above. And I have no idea
why its not working, here is my code to find the object:
jQuery.inArray("Apple", fruits["title"]); //this returns -1 why?
Any ideas how to search two dimentional array?
I got stuck trying to retrive array items. So here is the deal. I have a
two dimentional array which has value and key so example of my data is:
[
Object { css="SS", title="Apple"},
Object { css="SS", title="Orange"},
Object { css="SS", title="Banana"}
]
I want to see if an object exists in the array above. And I have no idea
why its not working, here is my code to find the object:
jQuery.inArray("Apple", fruits["title"]); //this returns -1 why?
Any ideas how to search two dimentional array?
Network condition monitoring, in android native voip SDK
Network condition monitoring, in android native voip SDK
I have developed an android VOIP client using the native Android VOIP SDK,
I have been asked to display the status of the network during the active
phone call, e.g. The App says Expect good,bad or fair phone call in real
time while the user is talking, just like Skype or Viber.
Perhaps I could not find the solution myself because I presumed that Viber
or Skype implemented it from within their VOIP stack, While in the reality
It is just a separate software-networking function.
I have developed an android VOIP client using the native Android VOIP SDK,
I have been asked to display the status of the network during the active
phone call, e.g. The App says Expect good,bad or fair phone call in real
time while the user is talking, just like Skype or Viber.
Perhaps I could not find the solution myself because I presumed that Viber
or Skype implemented it from within their VOIP stack, While in the reality
It is just a separate software-networking function.
How to resolve a NameError in my 'rock, paper, scissors' function
How to resolve a NameError in my 'rock, paper, scissors' function
I just started programming in python 2.7.x. and had to put a programm for
rock, paper and scissors into a function. In the programm itself I asked
the user for an input and now I have to change it to just using parameters
only and using return instead of 'print'. Its a simple piece of code but I
just keep getting the NameError: name 'x' is not defined.
So I run the function into shell and then I type in: rps(rock, paper).
Some hints on how to resolve this or advice on my code would be great.
Here's the code.
def rps(player1, player2): if (player1 != 'rock' and player1 != 'scissors'
and player1 != 'paper'): return 'This is not a valid object selection'
if (player2 != 'rock' and
player2 != 'scissors' and
player2 != 'paper'):
return 'This is not a valid object selection'
if (player1 == 'rock' and
player2 == 'scissors'):
return 'Player 1 wins.'
if (player1 == 'rock' and
player2 == 'rock'):
return 'There is a tie.'
if (player1 == 'rock' and
player2 == 'paper'):
return 'Player 2 wins.'
if (player1 == 'scissors' and
player2 == 'scissors'):
return 'There is a tie.'
if (player1 == 'scissors' and
player2 == 'rock'):
return 'Player 2 wins.'
if (player1 == 'scissors' and
player2 == 'paper'):
return 'Player 1 wins.'
if (player1 == 'paper' and
player2 == 'rock'):
return 'Player 1 wins.'
if (player1 == 'paper' and
player2 == 'paper'):
return 'There is a tie.'
if (player1 == 'paper' and
player2 == 'scissors'):
return 'Player 2 wins.'
I just started programming in python 2.7.x. and had to put a programm for
rock, paper and scissors into a function. In the programm itself I asked
the user for an input and now I have to change it to just using parameters
only and using return instead of 'print'. Its a simple piece of code but I
just keep getting the NameError: name 'x' is not defined.
So I run the function into shell and then I type in: rps(rock, paper).
Some hints on how to resolve this or advice on my code would be great.
Here's the code.
def rps(player1, player2): if (player1 != 'rock' and player1 != 'scissors'
and player1 != 'paper'): return 'This is not a valid object selection'
if (player2 != 'rock' and
player2 != 'scissors' and
player2 != 'paper'):
return 'This is not a valid object selection'
if (player1 == 'rock' and
player2 == 'scissors'):
return 'Player 1 wins.'
if (player1 == 'rock' and
player2 == 'rock'):
return 'There is a tie.'
if (player1 == 'rock' and
player2 == 'paper'):
return 'Player 2 wins.'
if (player1 == 'scissors' and
player2 == 'scissors'):
return 'There is a tie.'
if (player1 == 'scissors' and
player2 == 'rock'):
return 'Player 2 wins.'
if (player1 == 'scissors' and
player2 == 'paper'):
return 'Player 1 wins.'
if (player1 == 'paper' and
player2 == 'rock'):
return 'Player 1 wins.'
if (player1 == 'paper' and
player2 == 'paper'):
return 'There is a tie.'
if (player1 == 'paper' and
player2 == 'scissors'):
return 'Player 2 wins.'
Wednesday, 18 September 2013
How to detect of tap gesture is from uiwebview or self.view?
How to detect of tap gesture is from uiwebview or self.view?
Hello everyone I have a uitapgesture on my view using the following code :
UITapGestureRecognizer *tap= [[UITapGestureRecognizer alloc]
initWithTarget:self action:@selector(TAPGestureRecognizer)];
tap.numberOfTapsRequired=1;
tap.delegate = self;
[self.view addGestureRecognizer:tap];
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer
shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer
*)otherGestureRecognizer
{
return YES;
}
And I have a uiwebview as a subview in my UIview. The problem is that on
the uivewview HTML it had a onclick(); which in turn is calling the
tapgesture. Any help?
Hello everyone I have a uitapgesture on my view using the following code :
UITapGestureRecognizer *tap= [[UITapGestureRecognizer alloc]
initWithTarget:self action:@selector(TAPGestureRecognizer)];
tap.numberOfTapsRequired=1;
tap.delegate = self;
[self.view addGestureRecognizer:tap];
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer
shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer
*)otherGestureRecognizer
{
return YES;
}
And I have a uiwebview as a subview in my UIview. The problem is that on
the uivewview HTML it had a onclick(); which in turn is calling the
tapgesture. Any help?
Jenkins - NUnit/MSTest Code Coverage Graph
Jenkins - NUnit/MSTest Code Coverage Graph
Is it possible to produce a graph of code coverage v time in Jenkins for
NUnit/MSTest?
I can produce a code coverage report with OpenCover and ReportGenerator. I
would prefer to be able to visualise this with a graph. The NUnit plugin
only produces of a graph of tests run or test failures over time.
On a separate note, does anyone know how to get OpenCover to set the
%ERRORLEVEL% batch variable is a test fails during code coverage
calculation?
Is it possible to produce a graph of code coverage v time in Jenkins for
NUnit/MSTest?
I can produce a code coverage report with OpenCover and ReportGenerator. I
would prefer to be able to visualise this with a graph. The NUnit plugin
only produces of a graph of tests run or test failures over time.
On a separate note, does anyone know how to get OpenCover to set the
%ERRORLEVEL% batch variable is a test fails during code coverage
calculation?
How to programmatically display HTML5 client-side form validation error bubbles?
How to programmatically display HTML5 client-side form validation error
bubbles?
I'm trying to use HTML5 client-side validation (i.e. inside a form), but
cannot see how to display the validation error bubbles programatically.
Consider the following:
<form id="myForm">
<input type="text" id="number" min="1" max="10" step="3" required>
</form>
If there is a canonical submit button (i.e <input type="submit">), and
there are validation errors, the user-agent will halt the submit and show
UI to the user:
But, if instead of a using a submit input, the user is clicking an anchor
that executes javascript (i.e. ASP.net Webforms):
<a href='javascript:SaveChanges()'>Save Quantity</a>
<script>
function SaveChanges()
{
var form = document.getElementById('myForm');
if (form === null) return;
if (!form.checkValidity())
{
//We reach here, but no UI is displayed
return;
}
form.submit();
</script>
The issue is that while
form.checkValidity();
does check the form's validity (returning false if it's not valid), it
does not trigger the UI displays.
And now we have our question. Submitting through
<input type="submit"> works (halts and shows UI)
<button type="submit> works (halts and shows UI)
form.submit doesn't work (doesn't halt; doesn't show UI)
form.checkValidity() doesn't work (doesn't show UI)
How to programmatically display HTML5 client-side form validation error
bubbles?
jsFiddle for all of the above
See also
How to programmatically display HTML5 client-side validation error bubbles?
bubbles?
I'm trying to use HTML5 client-side validation (i.e. inside a form), but
cannot see how to display the validation error bubbles programatically.
Consider the following:
<form id="myForm">
<input type="text" id="number" min="1" max="10" step="3" required>
</form>
If there is a canonical submit button (i.e <input type="submit">), and
there are validation errors, the user-agent will halt the submit and show
UI to the user:
But, if instead of a using a submit input, the user is clicking an anchor
that executes javascript (i.e. ASP.net Webforms):
<a href='javascript:SaveChanges()'>Save Quantity</a>
<script>
function SaveChanges()
{
var form = document.getElementById('myForm');
if (form === null) return;
if (!form.checkValidity())
{
//We reach here, but no UI is displayed
return;
}
form.submit();
</script>
The issue is that while
form.checkValidity();
does check the form's validity (returning false if it's not valid), it
does not trigger the UI displays.
And now we have our question. Submitting through
<input type="submit"> works (halts and shows UI)
<button type="submit> works (halts and shows UI)
form.submit doesn't work (doesn't halt; doesn't show UI)
form.checkValidity() doesn't work (doesn't show UI)
How to programmatically display HTML5 client-side form validation error
bubbles?
jsFiddle for all of the above
See also
How to programmatically display HTML5 client-side validation error bubbles?
Is it possible to do an inline "else if"?
Is it possible to do an inline "else if"?
This is really unnecessary, but I'm curious... can you do an inline "else
if" much like you would do a standard inline if/then/else? A few minutes
of googling did not return an answer.
Example:
if (n == 1) {
alert("The variable is 1!")
} else {
alert("The variable is not 1!")
}
is the same as:
n == 1 ? alert("The variable is 1!") : alert("The variable is not 1!")
But is there a way to do this using similar syntax?
if (n == 1) {
alert("The variable is 1!")
} else if (n == 2) {
alert("The variable is 2!")
} else {
alert("The variable is not 1 or 2!")
}
I tried the following, but it did not seem to work:
n == 1 ? alert("The variable is 1!") : (n == 2 ? alert("The variable is
2!") : alert("The variable is not 1 or 2!"))
This is really unnecessary, but I'm curious... can you do an inline "else
if" much like you would do a standard inline if/then/else? A few minutes
of googling did not return an answer.
Example:
if (n == 1) {
alert("The variable is 1!")
} else {
alert("The variable is not 1!")
}
is the same as:
n == 1 ? alert("The variable is 1!") : alert("The variable is not 1!")
But is there a way to do this using similar syntax?
if (n == 1) {
alert("The variable is 1!")
} else if (n == 2) {
alert("The variable is 2!")
} else {
alert("The variable is not 1 or 2!")
}
I tried the following, but it did not seem to work:
n == 1 ? alert("The variable is 1!") : (n == 2 ? alert("The variable is
2!") : alert("The variable is not 1 or 2!"))
Javascript if value is in array else in next array
Javascript if value is in array else in next array
I have found a few posts on here with similar questions but not entirely
the same as what I am trying. I am currently using a simple if statement
that checks the data the user enters then checks to see if it starts with
a number of different values. I am doing this with the following:
var value = string;
var value = value.toLowerCase();
country = "NONE";
county = "NONE";
if (value.indexOf('ba1 ') == 0 || value.indexOf('ba2 ') == 0 ||
value.indexOf('ba3 ') == 0) { //CHECK AVON (MAINLAND UK) UK.AVON
country = "UK";
county = "UK.AVON";
}
I have about 20-30 different if, else statements that are basically
checking the post code entered and finding the county associated. However
some of these if statements are incredibly long so I would like to store
the values inside an array and then in the if statement simply check
value.indexOf() for each of the array values.
So in the above example I would have an array as follows for the statement:
var avon = new Array('ba1 ','ba 2','ba3 ');
then inside the indexOf() use each value
Would this be possible with minimal script or am I going to need to make a
function for this to work? I am ideally wanting to keep the array inside
the if statement instead of querying for each array value.
Edit:
just found a post on here mentioning the following JQuery:
$.inArray(value, array) am going to have a play around with this
I have found a few posts on here with similar questions but not entirely
the same as what I am trying. I am currently using a simple if statement
that checks the data the user enters then checks to see if it starts with
a number of different values. I am doing this with the following:
var value = string;
var value = value.toLowerCase();
country = "NONE";
county = "NONE";
if (value.indexOf('ba1 ') == 0 || value.indexOf('ba2 ') == 0 ||
value.indexOf('ba3 ') == 0) { //CHECK AVON (MAINLAND UK) UK.AVON
country = "UK";
county = "UK.AVON";
}
I have about 20-30 different if, else statements that are basically
checking the post code entered and finding the county associated. However
some of these if statements are incredibly long so I would like to store
the values inside an array and then in the if statement simply check
value.indexOf() for each of the array values.
So in the above example I would have an array as follows for the statement:
var avon = new Array('ba1 ','ba 2','ba3 ');
then inside the indexOf() use each value
Would this be possible with minimal script or am I going to need to make a
function for this to work? I am ideally wanting to keep the array inside
the if statement instead of querying for each array value.
Edit:
just found a post on here mentioning the following JQuery:
$.inArray(value, array) am going to have a play around with this
line between textbox and lable wpf
line between textbox and lable wpf
I need to create something like this:
I was thinking to use a label and a textbox, but I don't know how to put
that line between them. All that I need is good idea how to do it. Are
there other tools to do that?
I need to create something like this:
I was thinking to use a label and a textbox, but I don't know how to put
that line between them. All that I need is good idea how to do it. Are
there other tools to do that?
Find the best solution for read file and call web service
Find the best solution for read file and call web service
I have a text file which has about 100,000 records of identifier.
I must read all of record, each record i do request to web service and
receive the result from web service, the result i write to another file.
I'm confuse between two solution: - Read identifier file to a list of
identifier, iterate this list, call web service, .... - Read identifier
line on each line, call web service, .....
Do you think what solution will be better ? program will do faster ?
Thanks for all.
I have a text file which has about 100,000 records of identifier.
I must read all of record, each record i do request to web service and
receive the result from web service, the result i write to another file.
I'm confuse between two solution: - Read identifier file to a list of
identifier, iterate this list, call web service, .... - Read identifier
line on each line, call web service, .....
Do you think what solution will be better ? program will do faster ?
Thanks for all.
is there any alternates to merge two datasets in SAS apart from Proc Sql and Merge statement?
is there any alternates to merge two datasets in SAS apart from Proc Sql
and Merge statement?
i want to merge two datasets, but without using merge statement and Proc
sql,can i do this? is there any way to do the same
and Merge statement?
i want to merge two datasets, but without using merge statement and Proc
sql,can i do this? is there any way to do the same
Tuesday, 17 September 2013
Python module pseudo compiler idea.
Python module pseudo compiler idea.
Say I work for a python project, in folder myfolder/
it has a library file "Mylibrary.py" and a script file "myscript.py"
and in myscript.py I imported Mylibrary.py, is there a program such that
it will replace "import Mylibrary" by my library file literally and
replace all function call "Mylibrary.myfunction" by "myfunction"? It kind
of like "compile" multiple python scripts into one. Or this would be a
terrible solution
The reason is that I want to use myscript as an executable in other
folders without having to copy multiple files or making a package.
Say I work for a python project, in folder myfolder/
it has a library file "Mylibrary.py" and a script file "myscript.py"
and in myscript.py I imported Mylibrary.py, is there a program such that
it will replace "import Mylibrary" by my library file literally and
replace all function call "Mylibrary.myfunction" by "myfunction"? It kind
of like "compile" multiple python scripts into one. Or this would be a
terrible solution
The reason is that I want to use myscript as an executable in other
folders without having to copy multiple files or making a package.
Create a list out of the output in loop
Create a list out of the output in loop
We are tasked to print out the values in the pascal triangle in this manner
(pascal 2)
(1 2 1)
(pascal 0)
(1)
I copied the code for the binomial thereom somewhere in the internet
defined as follows:
(defun choose(n k)
(labels ((prod-enum (s e)
(do ((i s (1+ i)) (r 1 (* i r))) ((> i e) r)))
(fact (n) (prod-enum 1 n)))
(/ (prod-enum (- (1+ n) k) n) (fact k))))
Now I'm trying to create a list out of the values here in my pascal function:
(defun pascal (start end)
(do ((i start (+ i 1)))
((> i end) )
(print (choose end i) ))
)
The function produces 1 2 1 NIL if I test it with (pascal 0 2). How can I
eliminate the NIL and create the list.
We are tasked to print out the values in the pascal triangle in this manner
(pascal 2)
(1 2 1)
(pascal 0)
(1)
I copied the code for the binomial thereom somewhere in the internet
defined as follows:
(defun choose(n k)
(labels ((prod-enum (s e)
(do ((i s (1+ i)) (r 1 (* i r))) ((> i e) r)))
(fact (n) (prod-enum 1 n)))
(/ (prod-enum (- (1+ n) k) n) (fact k))))
Now I'm trying to create a list out of the values here in my pascal function:
(defun pascal (start end)
(do ((i start (+ i 1)))
((> i end) )
(print (choose end i) ))
)
The function produces 1 2 1 NIL if I test it with (pascal 0 2). How can I
eliminate the NIL and create the list.
What are the orgins of the terms "parse" in java?
What are the orgins of the terms "parse" in java?
In java I noticed there are methods associated with conversion of strings
and those methods sometimes use the word "parse" in the name of the
method. For example the static method,
static int parseInt(String str)
is used to convert a string into int. My question is this. Is "parse"
short for another word? Is is just a random word or did it come from
somewhere else in some other context?
In java I noticed there are methods associated with conversion of strings
and those methods sometimes use the word "parse" in the name of the
method. For example the static method,
static int parseInt(String str)
is used to convert a string into int. My question is this. Is "parse"
short for another word? Is is just a random word or did it come from
somewhere else in some other context?
Matlab remoteParallelFunction and Mex file Error
Matlab remoteParallelFunction and Mex file Error
I'm trying to validate the default local matlab parallel configuration,
but I get the following error:
Validation Details
Configuration: "local" Type: local
-------------------------------------- Stage: Find Resource
Status: Passed Description: Validation passed
Command Line Output: (none)
-------------------------------------- Stage: Distributed Job
Status: Passed Description: Validation passed
Command Line Output: (none)
-------------------------------------- Stage: Parallel Job
Status: Passed Description: Validation passed
Command Line Output: (none)
-------------------------------------- Stage: Matlabpool
Status: Failed Description: Encountered a problem while trying to run code
in the matlabpool.
Command Line Output: Starting matlabpool using the 'local' configuration
... connected to 8 labs.
Error Report: Error using ==> parallel_function at 598 Error in remote
execution of remoteParallelFunction : RUNTIME_ERROR
Debug Log: (none)
And if I actually try to run the code, I receive the following error:
??? Invalid MEX-file
'/usr/local/matlab/R2010a/toolbox/distcomp/private/dctRegisterMpiFunctions.mexa64':
/usr/local/matlab/R2010a/toolbox/distcomp/private/../../../../../bin/glnxa64/libmwmpi.so:
undefined symbol: _ZN9MathWorks6System9Condition9signalAllEv.
Error in ==> remoteParallelFunction at 51
dctRegisterMpiFunctions('mwmpi');
??? Error using ==> parallel_function at 598
Error in remote execution of remoteParallelFunction : RUNTIME_ERROR
Error in ==> InterpCorrectionPar at 53
parfor n=1:size(Image,3)
Error in ==> InterleaveDetCor at 119
FixedImage=InterpCorrectionPar(ImStack,Int,Tr,varargin{Ctrl});
Error in ==> MainCompareProgram at 25
InterleaveDetCor(FilePath,SavePath,RunCorrection,'FiltShift','Cubic','Spline','Linear','Sinc');
I'm running matlab 2010a on a gnome 2.28.2 linux "server" (really just a
computer with 400Gigs of memory and 32 processors used for intensive
computation). The code I'm running is just a few parfor loops that I've
run on my local machine before. I'm actually running the program on the
server computer locally through vcn. Can anyone please suggest what the
problem may be?
I'm trying to validate the default local matlab parallel configuration,
but I get the following error:
Validation Details
Configuration: "local" Type: local
-------------------------------------- Stage: Find Resource
Status: Passed Description: Validation passed
Command Line Output: (none)
-------------------------------------- Stage: Distributed Job
Status: Passed Description: Validation passed
Command Line Output: (none)
-------------------------------------- Stage: Parallel Job
Status: Passed Description: Validation passed
Command Line Output: (none)
-------------------------------------- Stage: Matlabpool
Status: Failed Description: Encountered a problem while trying to run code
in the matlabpool.
Command Line Output: Starting matlabpool using the 'local' configuration
... connected to 8 labs.
Error Report: Error using ==> parallel_function at 598 Error in remote
execution of remoteParallelFunction : RUNTIME_ERROR
Debug Log: (none)
And if I actually try to run the code, I receive the following error:
??? Invalid MEX-file
'/usr/local/matlab/R2010a/toolbox/distcomp/private/dctRegisterMpiFunctions.mexa64':
/usr/local/matlab/R2010a/toolbox/distcomp/private/../../../../../bin/glnxa64/libmwmpi.so:
undefined symbol: _ZN9MathWorks6System9Condition9signalAllEv.
Error in ==> remoteParallelFunction at 51
dctRegisterMpiFunctions('mwmpi');
??? Error using ==> parallel_function at 598
Error in remote execution of remoteParallelFunction : RUNTIME_ERROR
Error in ==> InterpCorrectionPar at 53
parfor n=1:size(Image,3)
Error in ==> InterleaveDetCor at 119
FixedImage=InterpCorrectionPar(ImStack,Int,Tr,varargin{Ctrl});
Error in ==> MainCompareProgram at 25
InterleaveDetCor(FilePath,SavePath,RunCorrection,'FiltShift','Cubic','Spline','Linear','Sinc');
I'm running matlab 2010a on a gnome 2.28.2 linux "server" (really just a
computer with 400Gigs of memory and 32 processors used for intensive
computation). The code I'm running is just a few parfor loops that I've
run on my local machine before. I'm actually running the program on the
server computer locally through vcn. Can anyone please suggest what the
problem may be?
When can DECLARE EXIT HANDLER FOR SQLEXCEPTION ROLLBACK have an effect?
When can DECLARE EXIT HANDLER FOR SQLEXCEPTION ROLLBACK have an effect?
DECLARE EXIT HANDLER FOR SQLEXCEPTION ROLLBACK is "supposed" to be used
before a transaction, to explicitly set the value on failure.
However, the documentation states that this is more or less the default
behavior anyway?
If a condition occurs for which no handler has been declared, the action
taken depends on the condition class:
For SQLEXCEPTION conditions, the stored program terminates at the
statement that raised the condition, as if there were an EXIT handler. If
the program was called by another stored program, the calling program
handles the condition using the handler selection rules applied to its own
handlers.
But that means COMMIT is never called, so, same effect as having no handler.
I'm not sure how to interpret that. It sounds like the "obvious" thing to
do is exit the stored program, but if a calling program has handlers
telling to do otherwise - perhaps a DECLARE EXIT HANDLER FOR SQLEXCEPTION
CONTINUE - it's not clear to me whether the inside stored program
continues or not, or what the "handler selection rules" are in general.
If this (strange to me) interpretation is the case, then that means if
hypothetically a stored program could assume it was never called by
another stored program, the handler is extraneous, but it ensures
consistent behavior
DECLARE EXIT HANDLER FOR SQLEXCEPTION ROLLBACK is "supposed" to be used
before a transaction, to explicitly set the value on failure.
However, the documentation states that this is more or less the default
behavior anyway?
If a condition occurs for which no handler has been declared, the action
taken depends on the condition class:
For SQLEXCEPTION conditions, the stored program terminates at the
statement that raised the condition, as if there were an EXIT handler. If
the program was called by another stored program, the calling program
handles the condition using the handler selection rules applied to its own
handlers.
But that means COMMIT is never called, so, same effect as having no handler.
I'm not sure how to interpret that. It sounds like the "obvious" thing to
do is exit the stored program, but if a calling program has handlers
telling to do otherwise - perhaps a DECLARE EXIT HANDLER FOR SQLEXCEPTION
CONTINUE - it's not clear to me whether the inside stored program
continues or not, or what the "handler selection rules" are in general.
If this (strange to me) interpretation is the case, then that means if
hypothetically a stored program could assume it was never called by
another stored program, the handler is extraneous, but it ensures
consistent behavior
Clear data option in android application
Clear data option in android application
If we select clear data option in android program, It'll clear application
database.As I know we cannot prevent this action if we install application
database in default location.Is there any method to prevent this action by
saving application database in a hidden location which will not be able to
access by users.Please provide me any solution regarding this matter.
If we select clear data option in android program, It'll clear application
database.As I know we cannot prevent this action if we install application
database in default location.Is there any method to prevent this action by
saving application database in a hidden location which will not be able to
access by users.Please provide me any solution regarding this matter.
Sunday, 15 September 2013
Not able to filter the model using the Ember.Select in Ember.js
Not able to filter the model using the Ember.Select in Ember.js
The use case is I am trying to filter the model using the Ember.Select,
whenever the user clicks the button, the model gets filtered on the basis
of the 'Designation' property.
Here's my Ember.Select:
{{view Ember.Select
contentBinding="designations"
optionValuePath="content.id"
optionLabelPath="content.designation"
selectionBinding="roles.selectedDesignation"}}
<button {{action 'filter'}}>Filter</button>
And Here's what I am doing in App.js,
App.TwodController = Ember.Controller.extend({
filteredContent : Ember.computed.oneWay("content"),
selectedDesignation : null,
designations : [{
designation : "Design",
id : 1
}, {
designation : "Writer",
id : 2
}],
actions : {
filter : function() {
var designation = this.get('roles.selectedDesignation');
var filtered =
this.get('content').filterProperty('designation',
designation);
this.set("filteredContent", filtered);
}
}
});
Here's the full JSBin, http://jsbin.com/IkiVIJU/1/
What I might be missing here?
The use case is I am trying to filter the model using the Ember.Select,
whenever the user clicks the button, the model gets filtered on the basis
of the 'Designation' property.
Here's my Ember.Select:
{{view Ember.Select
contentBinding="designations"
optionValuePath="content.id"
optionLabelPath="content.designation"
selectionBinding="roles.selectedDesignation"}}
<button {{action 'filter'}}>Filter</button>
And Here's what I am doing in App.js,
App.TwodController = Ember.Controller.extend({
filteredContent : Ember.computed.oneWay("content"),
selectedDesignation : null,
designations : [{
designation : "Design",
id : 1
}, {
designation : "Writer",
id : 2
}],
actions : {
filter : function() {
var designation = this.get('roles.selectedDesignation');
var filtered =
this.get('content').filterProperty('designation',
designation);
this.set("filteredContent", filtered);
}
}
});
Here's the full JSBin, http://jsbin.com/IkiVIJU/1/
What I might be missing here?
Does using a sub-domain for static resources improve performance even if network latency is introduced?
Does using a sub-domain for static resources improve performance even if
network latency is introduced?
We are working to switch our web infrastructure to use a single sub-domain
for static resources as per Yahoo's web standards advice. This is
theoretically supposed to improve performance because it will allow
browsers to make requests asynchronously to grab the static resources that
are needed. We are using Cloudflare as a CDN and I'm a little bit worried
that the additional latency that will be added with DNS pointing to
Cloudflare's any casted IP range (while only 15ms) may defeat any
performance benefits that would be gained by switching to a static
sub-domain.
I'm still struggling to see why going over the network and making another
HTTP request could be faster in any way than using I/O inside the
web-server to directly reference the static file. Is this really
beneficial?
network latency is introduced?
We are working to switch our web infrastructure to use a single sub-domain
for static resources as per Yahoo's web standards advice. This is
theoretically supposed to improve performance because it will allow
browsers to make requests asynchronously to grab the static resources that
are needed. We are using Cloudflare as a CDN and I'm a little bit worried
that the additional latency that will be added with DNS pointing to
Cloudflare's any casted IP range (while only 15ms) may defeat any
performance benefits that would be gained by switching to a static
sub-domain.
I'm still struggling to see why going over the network and making another
HTTP request could be faster in any way than using I/O inside the
web-server to directly reference the static file. Is this really
beneficial?
Problems with resizing window
Problems with resizing window
My problem is when i resize the window(smaller) One of my divs just go
through and on top of my navigation bar... Which is annoying, but i
believe there is a easy way to fix it. I can give you the code, but should
test it in your editor program - and then resize, youll see what i mean.
HTML CODE HERE:
<!DOCTYPE html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="WorkFieldStartpage.css"/>
</head>
<body>
<div id="upperblock">
</div>
div class="topbar"></div>
<div id="pageContainer">
<div id="pageContainer2">
<div>
<div id="leftnavigation">
<ul>
<li> <h4> Navigation </h4> </li>
<li>Test text</li>
<li>Test text</li>
<li>Test text</li>
</ul>
</div>
<div id="mainContainer">
<div id="newsfeed"></div>
</div>
</div>
</div>
</div>
</body>
</html>
CSS CODE HERE:
body {
color: #333;
line-height: 1.28;
text-align: left;
direction: ltr;
}
div {
display: block;
}
.topbar {
font-family: sans-serif;
font-size:12px;
font-weight: bold;
background-color: #11BD83;
height: px;
width: 100%;
position:fixed;
left: 0px;
top: 0px;
}
#pageContainer {
margin: 0 auto;
position: relative;
zoom: 1;
min-height: 600px;
}
#pageContainer2 {
margin: 0;
outline: none;
padding: 0;
width: auto;
}
ul {
list-style-type: none;
}
h4 {
text-decoration:underline;
}
#mainContainer {
display: block;
width: 620px;
border-right: 1px solid #ccc;
border-left: 1px solid #ccc;
min-height: 800px;
margin-left: auto ;
margin-right: auto ;
margin-top: 58px;
}
#leftnavigation {
float: left;
height: 300px;
width: 120.5px;
text-align: left;
font-family: sans-serif;
font-size: 15px;
padding-right: 30px;
display:block;
}
My problem is when i resize the window(smaller) One of my divs just go
through and on top of my navigation bar... Which is annoying, but i
believe there is a easy way to fix it. I can give you the code, but should
test it in your editor program - and then resize, youll see what i mean.
HTML CODE HERE:
<!DOCTYPE html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="WorkFieldStartpage.css"/>
</head>
<body>
<div id="upperblock">
</div>
div class="topbar"></div>
<div id="pageContainer">
<div id="pageContainer2">
<div>
<div id="leftnavigation">
<ul>
<li> <h4> Navigation </h4> </li>
<li>Test text</li>
<li>Test text</li>
<li>Test text</li>
</ul>
</div>
<div id="mainContainer">
<div id="newsfeed"></div>
</div>
</div>
</div>
</div>
</body>
</html>
CSS CODE HERE:
body {
color: #333;
line-height: 1.28;
text-align: left;
direction: ltr;
}
div {
display: block;
}
.topbar {
font-family: sans-serif;
font-size:12px;
font-weight: bold;
background-color: #11BD83;
height: px;
width: 100%;
position:fixed;
left: 0px;
top: 0px;
}
#pageContainer {
margin: 0 auto;
position: relative;
zoom: 1;
min-height: 600px;
}
#pageContainer2 {
margin: 0;
outline: none;
padding: 0;
width: auto;
}
ul {
list-style-type: none;
}
h4 {
text-decoration:underline;
}
#mainContainer {
display: block;
width: 620px;
border-right: 1px solid #ccc;
border-left: 1px solid #ccc;
min-height: 800px;
margin-left: auto ;
margin-right: auto ;
margin-top: 58px;
}
#leftnavigation {
float: left;
height: 300px;
width: 120.5px;
text-align: left;
font-family: sans-serif;
font-size: 15px;
padding-right: 30px;
display:block;
}
Advantages of using SQL Server database over MySQL and Oracle? [on hold]
Advantages of using SQL Server database over MySQL and Oracle? [on hold]
In what circumstances do businesses prefer using SQL Server database over
MySQL and Oracle?
In what circumstances do businesses prefer using SQL Server database over
MySQL and Oracle?
integrating validation module in node.js
integrating validation module in node.js
I am using the following node module for validation:
https://github.com/chriso/node-validator
Now, suppose I want to check on an user input like this
check('abc').isInt(); I noticed that it basically throws an error!
I am pretty new with node.js but it seems to me that having to use
try{}catch(e){} blocks every time I need to check on a user input is a bit
on an overkill.
wouldn't it make more sense to have something like
if (check('abc').isInt()) {
// Do things here
next(null, stuff_I_want_to_return)
} else next(error);
instead of
try{
check('abc').isInt()
next(null, stuff_I_want_to_return)
} catch(e) { next(e); }
?? I have no idea, please clarify on what is the best approach to have in
this case. Thanks in advance.
I am using the following node module for validation:
https://github.com/chriso/node-validator
Now, suppose I want to check on an user input like this
check('abc').isInt(); I noticed that it basically throws an error!
I am pretty new with node.js but it seems to me that having to use
try{}catch(e){} blocks every time I need to check on a user input is a bit
on an overkill.
wouldn't it make more sense to have something like
if (check('abc').isInt()) {
// Do things here
next(null, stuff_I_want_to_return)
} else next(error);
instead of
try{
check('abc').isInt()
next(null, stuff_I_want_to_return)
} catch(e) { next(e); }
?? I have no idea, please clarify on what is the best approach to have in
this case. Thanks in advance.
How do I calculate the subtotal for a column from the other subtotals of the other columns
How do I calculate the subtotal for a column from the other subtotals of
the other columns
I have in the underlying database a column computed from other values in
the same row. In ssas all these columns are automatically summed to
provide the subtotals as I drill down hierarchies.
However, rather than summing the computed column values I need to perform
the computation again in ssas using the subtotals of the other summed
columns.
I am new to ssas but I have a sense that this is probably a common problem
with a generic answer but I cannot find an example of how to do this.
the other columns
I have in the underlying database a column computed from other values in
the same row. In ssas all these columns are automatically summed to
provide the subtotals as I drill down hierarchies.
However, rather than summing the computed column values I need to perform
the computation again in ssas using the subtotals of the other summed
columns.
I am new to ssas but I have a sense that this is probably a common problem
with a generic answer but I cannot find an example of how to do this.
Getting 'Invalid Column Index' error in oracle
Getting 'Invalid Column Index' error in oracle
Getting invalid column error in the following code , in oracle. But when I
am executing the query assigned to the cursor separately, it works just
fine. Please let me know what is the mistake I am doing :
CREATE OR REPLACE PROCEDURE etl_mergeEmployeeAttendee
(
v_EmployeeNumber IN VARCHAR2 DEFAULT NULL ,
v_AttendeeName OUT NVARCHAR2,
v_EmployeeAttendeeId OUT NUMBER,
v_AttendeeTitle OUT NVARCHAR2,
v_Company OUT NVARCHAR2,
v_Relationship OUT NVARCHAR2,
v_Operation OUT NUMBER,
v_Error OUT NUMBER
)
AS
v_Employee_AttendeeId NUMBER(10,0);
v_Employee_Id NUMBER(10,0);
v_Attendee_Name NVARCHAR2(50);
v_Attendee_Title NVARCHAR2(50);
v_Com_pany NVARCHAR2(50);
v_Relation_ship NVARCHAR2(50);
CURSOR sel_prod_attendee_csr
IS SELECT a.EmployeeAttendeeId ,
a.EmployeeId ,
a.AttendeeName ,
a.AttendeeTitle ,
a.Company ,
a.Relationship
FROM EmployeeAttendee a,
Employee b
WHERE b.EmployeeNumber = v_EmployeeNumber
AND a.EmployeeId = b.EmployeeId;
BEGIN
OPEN sel_prod_attendee_csr;
FETCH sel_prod_attendee_csr INTO
v_Employee_AttendeeId,v_Employee_Id,v_Attendee_Name,v_Attendee_Title,v_Com_pany,v_Relation_ship;
IF sel_prod_attendee_csr%FOUND= true THEN
/* found */ BEGIN
v_Operation := 1 ;
v_AttendeeTitle := v_Attendee_Title ;
v_Company := v_Com_pany ;
v_Relationship := v_Relation_ship ;
v_AttendeeName :=v_Attendee_Name;
END; ELSE v_Operation := 2 ;-- Insert END IF; CLOSE sel_prod_attendee_csr;
END;**
Getting invalid column error in the following code , in oracle. But when I
am executing the query assigned to the cursor separately, it works just
fine. Please let me know what is the mistake I am doing :
CREATE OR REPLACE PROCEDURE etl_mergeEmployeeAttendee
(
v_EmployeeNumber IN VARCHAR2 DEFAULT NULL ,
v_AttendeeName OUT NVARCHAR2,
v_EmployeeAttendeeId OUT NUMBER,
v_AttendeeTitle OUT NVARCHAR2,
v_Company OUT NVARCHAR2,
v_Relationship OUT NVARCHAR2,
v_Operation OUT NUMBER,
v_Error OUT NUMBER
)
AS
v_Employee_AttendeeId NUMBER(10,0);
v_Employee_Id NUMBER(10,0);
v_Attendee_Name NVARCHAR2(50);
v_Attendee_Title NVARCHAR2(50);
v_Com_pany NVARCHAR2(50);
v_Relation_ship NVARCHAR2(50);
CURSOR sel_prod_attendee_csr
IS SELECT a.EmployeeAttendeeId ,
a.EmployeeId ,
a.AttendeeName ,
a.AttendeeTitle ,
a.Company ,
a.Relationship
FROM EmployeeAttendee a,
Employee b
WHERE b.EmployeeNumber = v_EmployeeNumber
AND a.EmployeeId = b.EmployeeId;
BEGIN
OPEN sel_prod_attendee_csr;
FETCH sel_prod_attendee_csr INTO
v_Employee_AttendeeId,v_Employee_Id,v_Attendee_Name,v_Attendee_Title,v_Com_pany,v_Relation_ship;
IF sel_prod_attendee_csr%FOUND= true THEN
/* found */ BEGIN
v_Operation := 1 ;
v_AttendeeTitle := v_Attendee_Title ;
v_Company := v_Com_pany ;
v_Relationship := v_Relation_ship ;
v_AttendeeName :=v_Attendee_Name;
END; ELSE v_Operation := 2 ;-- Insert END IF; CLOSE sel_prod_attendee_csr;
END;**
Saturday, 14 September 2013
PrimeFaces: how to make the theme dynamic
PrimeFaces: how to make the theme dynamic
I need to make the theme dynamic by the different users, currently, I find
the guide in http://www.developer.am/primefaces/?page=Applying%20a%20Theme
It says: In case you'd like to make the theme dynamic, define an EL
expression as the param value.
<context-param>
<param-name>primefaces.THEME</param-name>
<param-value>#{loggedInUser.preferences.theme}</param-value>
</context-param>
In my understanding, the theme will be changed by the different users,
right? Even I change the theme in preferences for the user, I have no need
to restart the middleware, the theme will be changed at once, right?
Please guide me, thanks in advance.
I need to make the theme dynamic by the different users, currently, I find
the guide in http://www.developer.am/primefaces/?page=Applying%20a%20Theme
It says: In case you'd like to make the theme dynamic, define an EL
expression as the param value.
<context-param>
<param-name>primefaces.THEME</param-name>
<param-value>#{loggedInUser.preferences.theme}</param-value>
</context-param>
In my understanding, the theme will be changed by the different users,
right? Even I change the theme in preferences for the user, I have no need
to restart the middleware, the theme will be changed at once, right?
Please guide me, thanks in advance.
TypeScript Compiler was given an empty configurations string
TypeScript Compiler was given an empty configurations string
I am getting a Warning in the Error List of Visual Studio when building my
TypeScript project.
The TypeScript Compiler was given an empty configurations string, which is
unusual and suspicious.
I am getting a Warning in the Error List of Visual Studio when building my
TypeScript project.
The TypeScript Compiler was given an empty configurations string, which is
unusual and suspicious.
How to use resemble.js?
How to use resemble.js?
I was looking through resemble.js's demos and tried to use it with the
following code:
resemble("https://www.google.com/images/srpr/logo4w.png").compareTo("https://www.google.com/images/srpr/logo4w.png").onComplete(function(data){
if(data.misMatchPercentage == 0){
alert("hello");
}
});
For some reason it never alerts hello. What could I be doing wrong? Do the
arguments have to be canvas or image objects?
I was looking through resemble.js's demos and tried to use it with the
following code:
resemble("https://www.google.com/images/srpr/logo4w.png").compareTo("https://www.google.com/images/srpr/logo4w.png").onComplete(function(data){
if(data.misMatchPercentage == 0){
alert("hello");
}
});
For some reason it never alerts hello. What could I be doing wrong? Do the
arguments have to be canvas or image objects?
How to develop an application like Zune or Plex on Linux?
How to develop an application like Zune or Plex on Linux?
I've been trying to find a good approach to C++ (or otherwise) development
of GUIs for programs on Linux but so far all that's seemed appropriate is
GTK or QT, and neither of these seem to provide the tools to create
something as elegant as the Zune or Plex applications. Any ideas on how
those Software were developed on Linux, or any libraries etc. I should be
looking into? Thanks.
I've been trying to find a good approach to C++ (or otherwise) development
of GUIs for programs on Linux but so far all that's seemed appropriate is
GTK or QT, and neither of these seem to provide the tools to create
something as elegant as the Zune or Plex applications. Any ideas on how
those Software were developed on Linux, or any libraries etc. I should be
looking into? Thanks.
Including a link in a text field in Jquery
Including a link in a text field in Jquery
I'm using a lightbox jquery script to display some tect when you click on
an image. I'm very new to jquery, so i'm going in blindly - but i've
managed to find the text section i want to edit, only I want to add a link
in that space but am having trouble incorporating it.
I want to add the link where I have written "Inquire about these items".
Any help would be greatly appreciated. Thanks!
(function(){var b,d,c;b=jQuery;c=(function(){function
b(){this.fadeDuration=200;this.fitImagesInViewport=true;this.resizeDuration=700;this.showImageNumberLabel=true;this.wrapAround=false}b.prototype.albumLabel=function(b,c){return"Inquire
about these items "};return b})();d=(function(){function
c(b){this.options=b;this.album=[];this.currentImageIndex=void
0;this.init()}c.prototype.init=function(){this.enable();return this.build
I'm using a lightbox jquery script to display some tect when you click on
an image. I'm very new to jquery, so i'm going in blindly - but i've
managed to find the text section i want to edit, only I want to add a link
in that space but am having trouble incorporating it.
I want to add the link where I have written "Inquire about these items".
Any help would be greatly appreciated. Thanks!
(function(){var b,d,c;b=jQuery;c=(function(){function
b(){this.fadeDuration=200;this.fitImagesInViewport=true;this.resizeDuration=700;this.showImageNumberLabel=true;this.wrapAround=false}b.prototype.albumLabel=function(b,c){return"Inquire
about these items "};return b})();d=(function(){function
c(b){this.options=b;this.album=[];this.currentImageIndex=void
0;this.init()}c.prototype.init=function(){this.enable();return this.build
How to enable Panini keypad to work on emulator as well
How to enable Panini keypad to work on emulator as well
I have to create an Android application in which user can type in all
Indian languages. So for this I think to give user an link in my
application from where user could download IME from which he want to type
in EditText. I think that it's better to provide user Panini Keypad App
link so that user could download his native language IME.(As Panini Keypad
is available in all Indian languages.)
But I have to test it in my emulator as well whether it's working or not.
But Panini Keypad IME not works on emulator it gives blank boxes.
So please help me how do I type in my emulator as well using Panini
keypad(Actually I am not having actual device on which I could test it).
I have successfully install Panini Keypad and also enable it in setting
for typing.
I have to create an Android application in which user can type in all
Indian languages. So for this I think to give user an link in my
application from where user could download IME from which he want to type
in EditText. I think that it's better to provide user Panini Keypad App
link so that user could download his native language IME.(As Panini Keypad
is available in all Indian languages.)
But I have to test it in my emulator as well whether it's working or not.
But Panini Keypad IME not works on emulator it gives blank boxes.
So please help me how do I type in my emulator as well using Panini
keypad(Actually I am not having actual device on which I could test it).
I have successfully install Panini Keypad and also enable it in setting
for typing.
MVC and SignalR - avoid duplicating template
MVC and SignalR - avoid duplicating template
I am using MVC to display a table of data using Razor and html in my View.
To make it more "real time" I added a SignalR Hub that refreshes the table
with new rows and deletes the old ones. (not all rows are changed)
Problems is: now I've got a duplicate of row template. both in Html-Razor
and in JavaScript, I also had to hook on button handlers and other logic
twice.
Is there any better design for this?
I am using MVC to display a table of data using Razor and html in my View.
To make it more "real time" I added a SignalR Hub that refreshes the table
with new rows and deletes the old ones. (not all rows are changed)
Problems is: now I've got a duplicate of row template. both in Html-Razor
and in JavaScript, I also had to hook on button handlers and other logic
twice.
Is there any better design for this?
Friday, 13 September 2013
onTouchEvent not fire in DroidGap
onTouchEvent not fire in DroidGap
I have been develop with Phonegap 2.9. In Manactivity.java (i extend
DroidGap) i use event onTouchEvent but it not fire when i touch. When
Manactivity.java (i extend Activity) then it working. Anyone can help me.
Thank you very much.
public class MainActivity extends DroidGap{
private static final String DEBUG_TAG = "onTouchListener";
@SuppressLint("NewApi")
@Override
public void onCreate(Bundle savedInstanceState) {
CookieManager.setAcceptFileSchemeCookies(true);
super.onCreate(savedInstanceState);
super.loadUrl("file:///android_asset/www/viewer.html");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
//It not fire when touch
public boolean onTouchEvent(MotionEvent e) {
int num = e.getPointerCount();
for (int a = 0; a < num; a++) {
int x = (int) e.getX(e.getPointerId(a));
int y = (int) e.getY(e.getPointerId(a));
Toast.makeText(this, "x = " + x + ", y = " + y,
Toast.LENGTH_LONG).show();
Log.d(DEBUG_TAG, "pointer_" + e.getPointerId(a) + ": x = " + x
+ ", y = " + y);
}
return false;
}
I have been develop with Phonegap 2.9. In Manactivity.java (i extend
DroidGap) i use event onTouchEvent but it not fire when i touch. When
Manactivity.java (i extend Activity) then it working. Anyone can help me.
Thank you very much.
public class MainActivity extends DroidGap{
private static final String DEBUG_TAG = "onTouchListener";
@SuppressLint("NewApi")
@Override
public void onCreate(Bundle savedInstanceState) {
CookieManager.setAcceptFileSchemeCookies(true);
super.onCreate(savedInstanceState);
super.loadUrl("file:///android_asset/www/viewer.html");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
//It not fire when touch
public boolean onTouchEvent(MotionEvent e) {
int num = e.getPointerCount();
for (int a = 0; a < num; a++) {
int x = (int) e.getX(e.getPointerId(a));
int y = (int) e.getY(e.getPointerId(a));
Toast.makeText(this, "x = " + x + ", y = " + y,
Toast.LENGTH_LONG).show();
Log.d(DEBUG_TAG, "pointer_" + e.getPointerId(a) + ": x = " + x
+ ", y = " + y);
}
return false;
}
HTML data attributes and jQuery
HTML data attributes and jQuery
Okay, so I'm building a portfolio plugin for WordPress. Users will be able
to insert a shortcode into their content and display a portfolio.
Each Portfolio will use jQuery Isotope, with custom settings for each one.
I want to be able to display multiple portfolios on one page, and have
their respective Isotope jQuery arguments initialized.
So I went about adding data attributes with the settings to each portfolio
container, with a common class on each of them.
Then I set up a JS file with the following (simplified):
var $container = jQuery('.portfolio-listing');
var $eachContainer = jQuery('#' + $container.data('portfolio-id'));
$eachContainer.imagesLoaded( function(){
$eachContainer.isotope({
// options
itemSelector : '.portfolio-item.item-' +
$eachContainer.data('portfolio-id'),
layoutMode : $eachContainer.data('layout'),
});
});
And here's my HTML (simplified):
<div id="test" class="portfolio-listing" data-layout="masonry"
data-portfolio-id="test">
<div class="portfolio-item item-test">
... inner portfolio stuff
</div>
</div>
This results in the first portfolio on the page getting the correct
arguments, and then the rest of them just mimicking the first portfolio's
arguments.
Anyone have any ideas for me?
Okay, so I'm building a portfolio plugin for WordPress. Users will be able
to insert a shortcode into their content and display a portfolio.
Each Portfolio will use jQuery Isotope, with custom settings for each one.
I want to be able to display multiple portfolios on one page, and have
their respective Isotope jQuery arguments initialized.
So I went about adding data attributes with the settings to each portfolio
container, with a common class on each of them.
Then I set up a JS file with the following (simplified):
var $container = jQuery('.portfolio-listing');
var $eachContainer = jQuery('#' + $container.data('portfolio-id'));
$eachContainer.imagesLoaded( function(){
$eachContainer.isotope({
// options
itemSelector : '.portfolio-item.item-' +
$eachContainer.data('portfolio-id'),
layoutMode : $eachContainer.data('layout'),
});
});
And here's my HTML (simplified):
<div id="test" class="portfolio-listing" data-layout="masonry"
data-portfolio-id="test">
<div class="portfolio-item item-test">
... inner portfolio stuff
</div>
</div>
This results in the first portfolio on the page getting the correct
arguments, and then the rest of them just mimicking the first portfolio's
arguments.
Anyone have any ideas for me?
How to convert a csv file to a txt file with one line for each data line?
How to convert a csv file to a txt file with one line for each data line?
So I have a .csv file that I would like to convert into a .txt file. How
can I convert the .csv such that in the .txt file there is a new line for
each data line?
Right now if I rename the csv into txt I get it all bunched up together
with no new line which makes it impossible for me to analyze the data with
another program. Preferably there would be some sort of library that could
handle this in Java?
So I have a .csv file that I would like to convert into a .txt file. How
can I convert the .csv such that in the .txt file there is a new line for
each data line?
Right now if I rename the csv into txt I get it all bunched up together
with no new line which makes it impossible for me to analyze the data with
another program. Preferably there would be some sort of library that could
handle this in Java?
MVC 4 Retreive db id from newly created entry
MVC 4 Retreive db id from newly created entry
If I create a entry in a database such as this (cvmCasefile has all info
needed to create the casefile):
Casefile casefile = cvm.Casefile;
casefile.ClientId = cvm.Client.ClientId;
casefile.DateSubmitted = DateTime.Now;
db.Casefiles.Add(casefile);
db.SaveChanges();
Immediately after the save call I try to retrieve this entries ID number
from the database with:
int casefileId = db.Casefiles.Where(u => u.UserProfileId ==
casefile.UserProfileId)
.Where(c => c.ClientId == casefile.ClientId)
.Single(d => d.DateSubmitted ==
casefile.DateSubmitted).CasefileId;
This returns null when it is executed. I've stepped through the program
and all casefile values are populated and the database has the required
row inserted with a valid ID#. Is there an easier way to get the ID from
the database or where did is screw-up the call to the database?
If I create a entry in a database such as this (cvmCasefile has all info
needed to create the casefile):
Casefile casefile = cvm.Casefile;
casefile.ClientId = cvm.Client.ClientId;
casefile.DateSubmitted = DateTime.Now;
db.Casefiles.Add(casefile);
db.SaveChanges();
Immediately after the save call I try to retrieve this entries ID number
from the database with:
int casefileId = db.Casefiles.Where(u => u.UserProfileId ==
casefile.UserProfileId)
.Where(c => c.ClientId == casefile.ClientId)
.Single(d => d.DateSubmitted ==
casefile.DateSubmitted).CasefileId;
This returns null when it is executed. I've stepped through the program
and all casefile values are populated and the database has the required
row inserted with a valid ID#. Is there an easier way to get the ID from
the database or where did is screw-up the call to the database?
Unused variables from superclass
Unused variables from superclass
class ABC {
private int[] variable;
public int[] getVariable() {
return variable;
}
public ABC() {
variable = new int[123456];
}
}
class DEF extends ABC {
public int[] getVariable() {
return new int[0];
}
}
variable is used in ABC, but completely unused and needless in DEF. But I
can't see any proper way to prevent creating this big array in DEF,
because always some constructor of superclass has to be executed. I see
only one, inelegant way: new, "fake" constructor for ABC:
protected ABC(boolean whatever) {}
Then in DEF I can write:
public DEF() {
super(true);
}
and it works - variable isn't initialized.
But, my question is - can I solve this more properly?
Maybe if variable is unused, compiler automatically deletes her? It's
quite often situation, when such feature could be useful.
class ABC {
private int[] variable;
public int[] getVariable() {
return variable;
}
public ABC() {
variable = new int[123456];
}
}
class DEF extends ABC {
public int[] getVariable() {
return new int[0];
}
}
variable is used in ABC, but completely unused and needless in DEF. But I
can't see any proper way to prevent creating this big array in DEF,
because always some constructor of superclass has to be executed. I see
only one, inelegant way: new, "fake" constructor for ABC:
protected ABC(boolean whatever) {}
Then in DEF I can write:
public DEF() {
super(true);
}
and it works - variable isn't initialized.
But, my question is - can I solve this more properly?
Maybe if variable is unused, compiler automatically deletes her? It's
quite often situation, when such feature could be useful.
is that possible to "addr2line" a shared library compiled in another machine?
is that possible to "addr2line" a shared library compiled in another machine?
compiled a shared library with symbols in machine A, and copy this
"###.so" file to machine B(with same source code), then call the command
addr2line ###### -e ###.so in B, I got wrong lines, even the source code
in A and B placed in same directory structure. please, what is the reason?
compiled a shared library with symbols in machine A, and copy this
"###.so" file to machine B(with same source code), then call the command
addr2line ###### -e ###.so in B, I got wrong lines, even the source code
in A and B placed in same directory structure. please, what is the reason?
Thursday, 12 September 2013
Set Background Color on in Loop
Set Background Color on in Loop
I want to set a Same Background Color on Multiple tr's. So that each ROW
looks separated from the other one.
Please take a look at this Image. I want to perform same:
Check this DEMO:
http://jsfiddle.net/RkVsp/3/
I want to set a Same Background Color on Multiple tr's. So that each ROW
looks separated from the other one.
Please take a look at this Image. I want to perform same:
Check this DEMO:
http://jsfiddle.net/RkVsp/3/
CSS multi line Labels align
CSS multi line Labels align
How could I align 2 labels with bottom alignments. if one label has
multiple lines, the label next to it will appear from the top. could I
align it to the bottom?
http://jsfiddle.net/ghkJC/3/
<div class="field">
<div class="label">labl 1:</div>
<div class="value">Some text</div>
<br />
<br />
</div>
<div class="field">
<div class="label">this is a really really long label:</div>
<div class="value">right after":" from previous label</div>
<br />
</div>
.label {
background: purple;
float: left;
width: 100px;
display: inline;
vertical-align: 500px;
}
.value {
background: red;
width: 300px;
float: right;
}
many thanks :)
How could I align 2 labels with bottom alignments. if one label has
multiple lines, the label next to it will appear from the top. could I
align it to the bottom?
http://jsfiddle.net/ghkJC/3/
<div class="field">
<div class="label">labl 1:</div>
<div class="value">Some text</div>
<br />
<br />
</div>
<div class="field">
<div class="label">this is a really really long label:</div>
<div class="value">right after":" from previous label</div>
<br />
</div>
.label {
background: purple;
float: left;
width: 100px;
display: inline;
vertical-align: 500px;
}
.value {
background: red;
width: 300px;
float: right;
}
many thanks :)
Subscribe to:
Comments (Atom)