Programs & Examples On #Jdb

The Java Debugger, jdb, is a simple command-line debugger for Java classes.

Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'

The driver is automatically registered via SPI and manual loading of the driver class is usually unnecessary. Just change "com.mysql.cj.jdbc.Driver"

How to resolve Unable to load authentication plugin 'caching_sha2_password' issue

May be you are using wrong mysql_connector.

Use connector of same mysql version

Connection Java-MySql : Public Key Retrieval is not allowed

I found this issue frustrating because I was able to interact with the database yesterday, but after coming back this morning, I started getting this error.

I tried adding the allowPublicKeyRetrieval=true flag, but I kept getting the error.

What fixed it for me was doing Project->Clean in Eclipse and Clean on my Tomcat server. One (or both) of those fixed it.

I don't understand why, because I build my project using Maven, and have been restarting my server after each code change. Very irritating...

After Spring Boot 2.0 migration: jdbcUrl is required with driverClassName

I also read the Spring docs, as lapkritinis suggested - and luckily this brought me on the right path! But I don´t think, that the Spring docs explain this good right now. At least for me, they aren´t consistent IMHO.

The original problem/question is on what to do, if you upgrade an existing Spring Boot 1.5.x application to 2.0.x, which is using PostgreSQL/Hibernate. The main reason, you get your described error, is that Spring Boot 2.0.x uses HikariCP instead of Tomcat JDBC pooling DataSource as a default - and Hikari´s DataSource doesn´t know the spring.datasource.url property, instead it want´s to have spring.datasource.jdbc-url (lapkritinis also pointed that out).

So far so good. BUT the docs also suggest - and that´s the problem here - that Spring Boot uses spring.datasource.url to determine, if the - often locally used - embedded Database like H2 has to back off and instead use a production Database:

You should at least specify the URL by setting the spring.datasource.url property. Otherwise, Spring Boot tries to auto-configure an embedded database.

You may see the dilemma. If you want to have your embedded DataBase like you´re used to, you have to switch back to Tomcat JDBC. This is also much more minimally invasive to existing applications, as you don´t have to change source code! To get your existing application working after the Spring Boot 1.5.x --> 2.0.x upgrade with PostgreSQL, just add tomcat-jdbc as a dependency to your pom.xml:

    <dependency>
        <groupId>org.apache.tomcat</groupId>
        <artifactId>tomcat-jdbc</artifactId>
    </dependency>

And then configure Spring Boot to use it accordingly inside application.properties:

spring.datasource.type=org.apache.tomcat.jdbc.pool.DataSource

Hope to help some folks with this, was quite a time consuming problem. I also hope my beloved Spring folks update the docs - and the way new Hikari pool is configured - to get a more consistent Spring Boot user experience :)

Hibernate Error executing DDL via JDBC Statement

I guess you are using an old version of hibernate. You can download the latest version, 5.2, from here.

Caused by: org.flywaydb.core.api.FlywayException: Validate failed. Migration Checksum mismatch for migration 2

What I did when faced this issue, was connect to DB and update the checksum field correspondent to the mistaken version, putting there the value resolved locally by FlyWay.

For the following error:

nested exception is org.flywaydb.core.api.FlywayException: Validate failed.
Migration Checksum mismatch for migration 1.12
    -> Applied to database : 1029320280
    -> Resolved locally    : -236187247

I simply did this:

UPDATE schema_version SET checksum = -236187247 WHERE version_rank = 12 AND checksum = 1029320280;

And problem solved..

NOTE: You have to be sure your schema is actually correct, check your tables and their structure, if everything is OK, then you can apply this solution; otherwise, you should repair your schema manually first using plain and native SQL.

Error creating bean with name 'entityManagerFactory' defined in class path resource : Invocation of init method failed

In my case I got this error when trying to make Proguard + Spring Boot 2 work.

Adding -dontusemixedcaseclassnames to proguard.conf fixes it.

Unknown lifecycle phase "mvn". You must specify a valid lifecycle phase or a goal in the format <plugin-prefix>:<goal> or <plugin-group-id>

Try without command mvn in the command line. Example:

From:

mvn clean install jetty:run

To:

clean install jetty:run

JPA Hibernate Persistence exception [PersistenceUnit: default] Unable to build Hibernate SessionFactory

The issue is that you are not able to get a connection to MYSQL database and hence it is throwing an error saying that cannot build a session factory.

Please see the error below:

 Caused by: java.sql.SQLException: Access denied for user ''@'localhost' (using password: NO) 

which points to username not getting populated.

Please recheck system properties

dataSource.setUsername(System.getProperty("root"));

some packages seems to be missing as well pointing to a dependency issue:

package org.gjt.mm.mysql does not exist

Please run a mvn dependency:tree command to check for dependencies

Failed to load ApplicationContext (with annotation)

In my case, I had to do the following while running with Junit5

@SpringBootTest(classes = {abc.class}) @ExtendWith(SpringExtension.class

Here abc.class was the class that was being tested

Disable all Database related auto configuration in Spring Boot

I was getting this error even if I did all the solutions mentioned above.

 by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfig ...

At some point when i look up the POM there was this dependency in it

<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>

And the Pojo class had the following imports

import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id;

Which clearly shows the application was expecting a datasource.

What I did was I removed the JPA dependency from pom and replaced the imports for the pojo with the following once

import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document;

Finally I got SUCCESSFUL build. Check it out you might have run into the same problem

disabling spring security in spring boot app

Try this. Make a new class

@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.authorizeRequests().antMatchers("/").permitAll();
}

}

Basically this tells Spring to allow access to every url. @Configuration tells spring it's a configuration class

Using env variable in Spring Boot's application.properties

This is in response to a number of comments as my reputation isn't high enough to comment directly.

You can specify the profile at runtime as long as the application context has not yet been loaded.

// Previous answers incorrectly used "spring.active.profiles" instead of
// "spring.profiles.active" (as noted in the comments).
// Use AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME to avoid this mistake.

System.setProperty(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME, environment);
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("/META-INF/spring/applicationContext.xml");

java.lang.RuntimeException: Unable to instantiate org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient

just open the hive terminal from the hive folder,after editing (bashrc) and (hive-site.xml) files. Steps-- open hive folder where it is installed. now open terminal from folder.

How to manage exceptions thrown in filters in Spring?

After reading through different methods suggested in the above answers, I decided to handle the authentication exceptions by using a custom filter. I was able to handle the response status and codes using an error response class using the following method.

I created a custom filter and modified my security config by using the addFilterAfter method and added after the CorsFilter class.

@Component
public class AuthFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    //Cast the servlet request and response to HttpServletRequest and HttpServletResponse
    HttpServletResponse httpServletResponse = (HttpServletResponse) response;
    HttpServletRequest httpServletRequest = (HttpServletRequest) request;

    // Grab the exception from the request attribute
    Exception exception = (Exception) request.getAttribute("javax.servlet.error.exception");
    //Set response content type to application/json
    httpServletResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);

    //check if exception is not null and determine the instance of the exception to further manipulate the status codes and messages of your exception
    if(exception!=null && exception instanceof AuthorizationParameterNotFoundException){
        ErrorResponse errorResponse = new ErrorResponse(exception.getMessage(),"Authetication Failed!");
        httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        PrintWriter writer = httpServletResponse.getWriter();
        writer.write(convertObjectToJson(errorResponse));
        writer.flush();
        return;
    }
    // If exception instance cannot be determined, then throw a nice exception and desired response code.
    else if(exception!=null){
            ErrorResponse errorResponse = new ErrorResponse(exception.getMessage(),"Authetication Failed!");
            PrintWriter writer = httpServletResponse.getWriter();
            writer.write(convertObjectToJson(errorResponse));
            writer.flush();
            return;
        }
        else {
        // proceed with the initial request if no exception is thrown.
            chain.doFilter(httpServletRequest,httpServletResponse);
        }
    }

public String convertObjectToJson(Object object) throws JsonProcessingException {
    if (object == null) {
        return null;
    }
    ObjectMapper mapper = new ObjectMapper();
    return mapper.writeValueAsString(object);
}
}

SecurityConfig class

    @Configuration
    public class JwtSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    AuthFilter authenticationFilter;
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.addFilterAfter(authenticationFilter, CorsFilter.class).csrf().disable()
                .cors(); //........
        return http;
     }
   }

ErrorResponse class

public class ErrorResponse  {
private final String message;
private final String description;

public ErrorResponse(String description, String message) {
    this.message = message;
    this.description = description;
}

public String getMessage() {
    return message;
}

public String getDescription() {
    return description;
}}

Warning about SSL connection when connecting to MySQL database

I found this warning too then I fixed it by using SSL=false suffix to the connection string like this example code.

Example:

connectionString = "jdbc:mysql://{server-name}:3306/%s?useUnicode=yes&characterEncoding=UTF-8&useSSL=false"

HikariCP - connection is not available

I managed to fix it finally. The problem is not related to HikariCP. The problem persisted because of some complex methods in REST controllers executing multiple changes in DB through JPA repositories. For some reasons calls to these interfaces resulted in a growing number of "freezed" active connections, exhausting the pool. Either annotating these methods as @Transactional or enveloping all the logic in a single call to transactional service method seem to solve the problem.

Hibernate-sequence doesn't exist

in hibernate 5.x, you should add set hibernate.id.new_generator_mappings to false in hibernate.cfg.xml

<session-factory>
    ......
    <property name="show_sql">1</property>
    <property name="hibernate.id.new_generator_mappings">false</property>
     ......
 </session-factory>

java.lang.IllegalStateException: Error processing condition on org.springframework.boot.autoconfigure.jdbc.JndiDataSourceAutoConfiguration

This is caused by non-matching Spring Boot dependencies. Check your classpath to find the offending resources. You have explicitly included version 1.1.8.RELEASE, but you have also included 3 other projects. Those likely contain different Spring Boot versions, leading to this error.

Spring - No EntityManager with actual transaction available for current thread - cannot reliably process 'persist' call

I had the same problem and I annotated the method as @Transactional and it worked.

UPDATE: checking the spring documentation it looks like by default the PersistenceContext is of type Transaction, so that's why the method has to be transactional (http://docs.spring.io/spring/docs/current/spring-framework-reference/html/orm.html):

The @PersistenceContext annotation has an optional attribute type, which defaults to PersistenceContextType.TRANSACTION. This default is what you need to receive a shared EntityManager proxy. The alternative, PersistenceContextType.EXTENDED, is a completely different affair: This results in a so-called extended EntityManager, which is not thread-safe and hence must not be used in a concurrently accessed component such as a Spring-managed singleton bean. Extended EntityManagers are only supposed to be used in stateful components that, for example, reside in a session, with the lifecycle of the EntityManager not tied to a current transaction but rather being completely up to the application.

Rails: Address already in use - bind(2) (Errno::EADDRINUSE)

To kill the puma process first run

    lsof -wni tcp:3000 

to show what is using port 3000. Then use the PID that comes with the result to run the kill process.

For example after running lsof -wni tcp:3000 you might get something like

    COMMAND  PID  USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
    ruby    3366 dummy    8u  IPv4  16901      0t0  TCP 127.0.0.1:3000 (LISTEN)

Now run the following to kill the process. (where 3366 is the PID)

kill -9 3366

Should resolve the issue

How do I enable logging for Spring Security?

Assuming you're using Spring Boot, another option is to put the following in your application.properties:

logging.level.org.springframework.security=DEBUG

This is the same for most other Spring modules as well.

If you're not using Spring Boot, try setting the property in your logging configuration, e.g. logback.

Here is the application.yml version as well:

logging:
  level:
    org:
      springframework:
        security: DEBUG

Spring Boot Configure and Use Two DataSources

I used mybatis - springboot 2.0 tech stack, solution:

//application.properties - start
    sp.ds1.jdbc-url=jdbc:mysql://localhost:3306/mydb?useSSL=false
    sp.ds1.username=user
    sp.ds1.password=pwd
    sp.ds1.testWhileIdle=true
    sp.ds1.validationQuery=SELECT 1
    sp.ds1.driverClassName=com.mysql.jdbc.Driver


    sp.ds2.jdbc-url=jdbc:mysql://localhost:4586/mydb?useSSL=false
    sp.ds2.username=user
    sp.ds2.password=pwd
    sp.ds2.testWhileIdle=true
    sp.ds2.validationQuery=SELECT 1
    sp.ds2.driverClassName=com.mysql.jdbc.Driver

//application.properties - end

//configuration class

    @Configuration
    @ComponentScan(basePackages = "com.mypkg")
    public class MultipleDBConfig {


        public static final String SQL_SESSION_FACTORY_NAME_1 = "sqlSessionFactory1";
        public static final String SQL_SESSION_FACTORY_NAME_2 = "sqlSessionFactory2";

        public static final String MAPPERS_PACKAGE_NAME_1 = "com.mypg.mymapper1";
        public static final String MAPPERS_PACKAGE_NAME_2 = "com.mypg.mymapper2";


        @Bean(name = "mysqlDb1")
        @Primary
        @ConfigurationProperties(prefix = "sp.ds1")
        public DataSource dataSource1() {
            System.out.println("db1 datasource");
            return DataSourceBuilder.create().build();
        }

        @Bean(name = "mysqlDb2")
        @ConfigurationProperties(prefix = "sp.ds2")
        public DataSource dataSource2() {
            System.out.println("db2 datasource");
            return  DataSourceBuilder.create().build();
        }

        @Bean(name = SQL_SESSION_FACTORY_NAME_1)
        @Primary
        public SqlSessionFactory sqlSessionFactory1(@Qualifier("mysqlDb1") DataSource dataSource1) throws Exception {
            System.out.println("sqlSessionFactory1");
            SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
            sqlSessionFactoryBean.setTypeHandlersPackage(MAPPERS_PACKAGE_NAME_1);
            sqlSessionFactoryBean.setDataSource(dataSource1);
            SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBean.getObject();
            sqlSessionFactory.getConfiguration().setMapUnderscoreToCamelCase(true);
            sqlSessionFactory.getConfiguration().setJdbcTypeForNull(JdbcType.NULL);
            return sqlSessionFactory;
        }

        @Bean(name = SQL_SESSION_FACTORY_NAME_2)
        public SqlSessionFactory sqlSessionFactory2(@Qualifier("mysqlDb2") DataSource dataSource2) throws Exception {
            System.out.println("sqlSessionFactory2");
            SqlSessionFactoryBean diSqlSessionFactoryBean = new SqlSessionFactoryBean();
            diSqlSessionFactoryBean.setTypeHandlersPackage(MAPPERS_PACKAGE_NAME_2);
            diSqlSessionFactoryBean.setDataSource(dataSource2);
            SqlSessionFactory sqlSessionFactory = diSqlSessionFactoryBean.getObject();
            sqlSessionFactory.getConfiguration().setMapUnderscoreToCamelCase(true);
            sqlSessionFactory.getConfiguration().setJdbcTypeForNull(JdbcType.NULL);
            return sqlSessionFactory;
        }

        @Bean
        @Primary
        public MapperScannerConfigurer mapperScannerConfigurer1() {
            System.out.println("mapperScannerConfigurer1");
            MapperScannerConfigurer configurer = new MapperScannerConfigurer();
            configurer.setBasePackage(MAPPERS_PACKAGE_NAME_1);
            configurer.setSqlSessionFactoryBeanName(SQL_SESSION_FACTORY_NAME_1);
            return configurer;
        }

        @Bean
        public MapperScannerConfigurer mapperScannerConfigurer2() {
            System.out.println("mapperScannerConfigurer2");
            MapperScannerConfigurer configurer = new MapperScannerConfigurer();
            configurer.setBasePackage(MAPPERS_PACKAGE_NAME_2);
            configurer.setSqlSessionFactoryBeanName(SQL_SESSION_FACTORY_NAME_2);
            return configurer;
        }



    }

Note : 1)@Primary -> @primary

2)---."jdbc-url" in properties -> After Spring Boot 2.0 migration: jdbcUrl is required with driverClassName

How to log SQL statements in Spring Boot?

Log in to standard output

Add to application.properties

### to enable
spring.jpa.show-sql=true
### to make the printing SQL beautify
spring.jpa.properties.hibernate.format_sql=true

This the simplest way to print the SQL queries though it doesn't log the parameters of prepared statements. And its is not recommended since its not such as optimized logging framework.

Using Logging Framework

Add to application.properties

### logs the SQL queries
logging.level.org.hibernate.SQL=DEBUG
### logs the prepared statement parameters
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE
### to make the printing SQL beautify
spring.jpa.properties.hibernate.format_sql=true

By specifying above properties, logs entries will be sent to the configured log appender such as log-back or log4j.

UnsatisfiedDependencyException: Error creating bean with name 'entityManagerFactory'

Well, you're getting a java.lang.NoClassDefFoundError. In your pom.xml, hibernate-core version is 3.3.2.GA and declared after hibernate-entitymanager, so it prevails. You can remove that dependency, since will be inherited version 3.6.7.Final from hibernate-entitymanager.

You're using spring-boot as parent, so no need to declare version of some dependencies, since they are managed by spring-boot.

Also, hibernate-commons-annotations is inherited from hibernate-entitymanager and hibernate-annotations is an old version of hibernate-commons-annotations, you can remove both.

Finally, your pom.xml can look like this:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.elsys.internetprogramming.trafficspy.server</groupId>
    <artifactId>TrafficSpyService</artifactId>
    <version>0.1.0</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.2.3.RELEASE</version>
    </parent>

    <dependencies>
        <!-- Spring -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cloud-connectors</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>org.eclipse.persistence</groupId>
            <artifactId>javax.persistence</artifactId>
            <version>2.0.0</version>
        </dependency>

        <!-- Hibernate -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-pool</groupId>
            <artifactId>commons-pool</artifactId>
        </dependency>

        <!-- MySQL -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
    </dependencies>

    <properties>
        <java.version>1.7</java.version>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>spring-releases</id>
            <url>https://repo.spring.io/libs-release</url>
        </repository>

        <repository>
            <id>codehaus</id>
            <url>http://repository.codehaus.org/org/codehaus</url>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>spring-releases</id>
            <url>https://repo.spring.io/libs-release</url>
        </pluginRepository>
    </pluginRepositories>

</project>

Let me know if you have a problem.

Can't Autowire @Repository annotated interface in Spring Boot

I had a similar issue with Spring Data MongoDB: I had to add the package path to @EnableMongoRepositories

Configure DataSource programmatically in Spring Boot

I customized Tomcat DataSource in Spring-Boot 2.

Dependency versions:

  • spring-boot: 2.1.9.RELEASE
  • tomcat-jdbc: 9.0.20

May be it will be useful for somebody.

application.yml

spring:
    datasource:
        driver-class-name: org.postgresql.Driver
        type: org.apache.tomcat.jdbc.pool.DataSource
        url: jdbc:postgresql://${spring.datasource.database.host}:${spring.datasource.database.port}/${spring.datasource.database.name}
        database:
            host: localhost
            port: 5432
            name: rostelecom
        username: postgres
        password: postgres
        tomcat:
            validation-query: SELECT 1
            validation-interval: 30000           
            test-on-borrow: true
            remove-abandoned: true
            remove-abandoned-timeout: 480
            test-while-idle: true
            time-between-eviction-runs-millis: 60000
            log-validation-errors: true
            log-abandoned: true

Java

@Bean
@Primary
@ConfigurationProperties("spring.datasource.tomcat")
public PoolConfiguration postgresDataSourceProperties() {
    return new PoolProperties();
}

@Bean(name = "primaryDataSource")
@Primary
@Qualifier("primaryDataSource")
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource primaryDataSource() {
    PoolConfiguration properties = postgresDataSourceProperties();
    return new DataSource(properties);
}

The main reason why it had been done is several DataSources in application and one of them it is necessary to mark as a @Primary.

Spring Boot - Error creating bean with name 'dataSource' defined in class path resource

From the looks of things you haven't passed enough data to Spring Boot to configure the datasource

Create/In your existing application.properties add the following

spring.datasource.driverClassName=
spring.datasource.url=
spring.datasource.username=
spring.datasource.password=

making sure you append a value for each of properties.

How to use Spring Boot with MySQL database and JPA?

Your code is in the default package, i.e. you have source all files in src/main/java with no custom package. I strongly suggest u to create package n then place your source file in it.

Ex-
 src->
     main->
          java->
                com.myfirst.example
                   Example.java
                com.myfirst.example.controller
                   PersonController.java
                com.myfirst.example.repository
                  PersonRepository.java
                com.myfirst.example.model
                   Person.java

I hope it will resolve your problem.

Spring Boot Multiple Datasource

Use multiple datasource or realizing the separation of reading & writing. you must have a knowledge of Class AbstractRoutingDataSource which support dynamic datasource choose.

Here is my datasource.yaml and I figure out how to resolve this case. You can refer to this project spring-boot + quartz. Hope this will help you.

dbServer:
  default: localhost:3306
  read: localhost:3306
  write: localhost:3306
datasource:
  default:
    type: com.zaxxer.hikari.HikariDataSource
    pool-name: default
    continue-on-error: false
    jdbc-url: jdbc:mysql://${dbServer.default}/schedule_job?useSSL=true&verifyServerCertificate=false&useUnicode=true&characterEncoding=utf8
    username: root
    password: lh1234
    connection-timeout: 30000
    connection-test-query: SELECT 1
    maximum-pool-size: 5
    minimum-idle: 2
    idle-timeout: 600000
    destroy-method: shutdown
    auto-commit: false
  read:
    type: com.zaxxer.hikari.HikariDataSource
    pool-name: read
    continue-on-error: false
    jdbc-url: jdbc:mysql://${dbServer.read}/schedule_job?useSSL=true&verifyServerCertificate=false&useUnicode=true&characterEncoding=utf8
    username: root
    password: lh1234
    connection-timeout: 30000
    connection-test-query: SELECT 1
    maximum-pool-size: 5
    minimum-idle: 2
    idle-timeout: 600000
    destroy-method: shutdown
    auto-commit: false
  write:
    type: com.zaxxer.hikari.HikariDataSource
    pool-name: write
    continue-on-error: false
    jdbc-url: jdbc:mysql://${dbServer.write}/schedule_job?useSSL=true&verifyServerCertificate=false&useUnicode=true&characterEncoding=utf8
    username: root
    password: lh1234
    connection-timeout: 30000
    connection-test-query: SELECT 1
    maximum-pool-size: 5
    minimum-idle: 2
    idle-timeout: 600000
    destroy-method: shutdown
    auto-commit: false

Unable to get spring boot to automatically create database schema

to connect to mysql with springboot as well as creating table automatically into database: spring.datasource.url=jdbc:mysql://localhost:3306/solace spring.datasource.username=root spring.datasource.password=root spring.jpa.generate-ddl=true spring.jpa.hibernate.ddl-auto=update

org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set

In spring boot for jpa java config you need to extend JpaBaseConfiguration and implement it's abstract methods.

@Configuration
public class JpaConfig extends JpaBaseConfiguration {

    @Override
    protected AbstractJpaVendorAdapter createJpaVendorAdapter() {
        final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        return vendorAdapter;
    }

    @Override
    protected Map<String, Object> getVendorProperties() {
        Map<String, Object> properties = new HashMap<>();
        properties.put("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect");
    }

}

MySQL JDBC Driver 5.1.33 - Time Zone Issue

I had the same problem when I try to work with spring boot project on windows.

Datasource url should be:

spring.datasource.url=jdbc:mysql://localhost/database?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC

How do I configure HikariCP in my Spring Boot app in my application.properties files?

I was facing issues and the problem was a whitespace at the end of spring.datasource.type = com.zaxxer.hikari.HikariDataSource

Spring Boot, Spring Data JPA with multiple DataSources

I checked the source code you provided on GitHub. There were several mistakes / typos in the configuration.

In CustomerDbConfig / OrderDbConfig you should refer to customerEntityManager and packages should point at existing packages:

@Configuration
@EnableJpaRepositories(
    entityManagerFactoryRef = "customerEntityManager",
    transactionManagerRef = "customerTransactionManager",
    basePackages = {"com.mm.boot.multidb.repository.customer"})
public class CustomerDbConfig {

The packages to scan in customerEntityManager and orderEntityManager were both not pointing at proper package:

em.setPackagesToScan("com.mm.boot.multidb.model.customer");

Also the injection of proper EntityManagerFactory did not work. It should be:

@Bean(name = "customerTransactionManager")
public PlatformTransactionManager transactionManager(EntityManagerFactory customerEntityManager){

}

The above was causing the issue and the exception. While providing the name in a @Bean method you are sure you get proper EMF injected.

The last thing I have done was to disable to automatic configuration of JpaRepositories:

@EnableAutoConfiguration(exclude = JpaRepositoriesAutoConfiguration.class)

And with all fixes the application starts as you probably expect!

Oracle listener not running and won't start

1.Check the Environment variables (must be set for System and not for user):

ORACLE_HOME = C:\oraclexe\app\oracle\product\11.2.0\server
ORACLE_SID = XE

2.Check if you have the right definition in listener.ora

XE =
  (DESCRIPTION_LIST =
    (DESCRIPTION =
      (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1))
      (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))
    )
  )

DEFAULT_SERVICE_LISTENER = (XE)

3.Restart the service (Services > OracleServiceXE)

After that you may see a new service called OracleXETNSListenerXE.
There is already an old OracleXETNSListener.

I started both and then I was able to make a successful connection.

Edit:

If everything is running but you still can't connect, check if there is no error: ORA-12557: TNS:protocol adapter not loadable.

To correct the error go back to the Environment variables and this time edit the one called: Path. Be sure that C:\oraclexe\app\oracle\product\11.2.0\server\bin is somewhere at the beginning, definitely before any other path pointing to a different version of the Oracle DB.

Spring Hibernate - Could not obtain transaction-synchronized Session for current thread

Add transaction-manager to your <annotation-driven/> in spring-servlet.xml:

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

No found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations:

I added @Service before impl class and the error is gone.

@Service
public class FCSPAnalysisImpl implements FCSPAnalysis
{}

Problems with local variable scope. How to solve it?

You have a scope problem indeed, because statement is a local method variable defined here:

protected void createContents() {
    ...
    Statement statement = null; // local variable
    ...
     btnInsert.addMouseListener(new MouseAdapter() { // anonymous inner class
        @Override
        public void mouseDown(MouseEvent e) {
            ...
            try {
                statement.executeUpdate(query); // local variable out of scope here
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            ...
    });
}

When you try to access this variable inside mouseDown() method you are trying to access a local variable from within an anonymous inner class and the scope is not enough. So it definitely must be final (which given your code is not possible) or declared as a class member so the inner class can access this statement variable.

Sources:


How to solve it?

You could...

Make statement a class member instead of a local variable:

public class A1 { // Note Java Code Convention, also class name should be meaningful   
    private Statement statement;
    ...
}

You could...

Define another final variable and use this one instead, as suggested by @HotLicks:

protected void createContents() {
    ...
    Statement statement = null;
    try {
        statement = connect.createStatement();
        final Statement innerStatement = statement;
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    ...
}

But you should...

Reconsider your approach. If statement variable won't be used until btnInsert button is pressed then it doesn't make sense to create a connection before this actually happens. You could use all local variables like this:

btnInsert.addMouseListener(new MouseAdapter() {
   @Override
   public void mouseDown(MouseEvent e) {
       try {
           Class.forName("com.mysql.jdbc.Driver");
           try (Connection connect = DriverManager.getConnection(...);
                Statement statement = connect.createStatement()) {

                // execute the statement here

           } catch (SQLException ex) {
               ex.printStackTrace();
           }

       } catch (ClassNotFoundException ex) {
           e.printStackTrace();
       }
});

Spring-Boot: How do I set JDBC pool properties like maximum number of connections?

Based on your application type/size/load/no. of users ..etc - u can keep following as your production properties

spring.datasource.tomcat.initial-size=50
spring.datasource.tomcat.max-wait=20000
spring.datasource.tomcat.max-active=300
spring.datasource.tomcat.max-idle=150
spring.datasource.tomcat.min-idle=8
spring.datasource.tomcat.default-auto-commit=true

Where can I download mysql jdbc jar from?

If you have WL server installed, pick it up from under
\Oracle\Middleware\wlserver_10.3\server\lib\mysql-connector-java-commercial-5.1.17-bin.jar

Otherwise, download it from:
http://www.java2s.com/Code/JarDownload/mysql/mysql-connector-java-5.1.17-bin.jar.zip

Missing artifact com.oracle:ojdbc6:jar:11.2.0 in pom.xml

I had the same issue. Jenkins's build was falling because of this error..after long hours troubleshooting.

Link to download ojdbc as per your requirement - https://www.oracle.com/database/technologies/maven-central-guide.html

I have downloaded in my maven/bin location and executed the below command.

mvn install:install-file -Dfile=ojdbc8-12.2.0.1.jar -DgroupId=com.oracle -DartifactId=ojdbc8 -Dversion=12.2.0.1 -Dpackaging=jar

POM.xml

<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc8</artifactId>
<version>12.2.0.1</version>
</dependency>

How to create JNDI context in Spring Boot with Embedded Tomcat Container

In SpringBoot 2.1, I found another solution. Extend standard factory class method getTomcatWebServer. And then return it as a bean from anywhere.

public class CustomTomcatServletWebServerFactory extends TomcatServletWebServerFactory {

    @Override
    protected TomcatWebServer getTomcatWebServer(Tomcat tomcat) {
        System.setProperty("catalina.useNaming", "true");
        tomcat.enableNaming();
        return new TomcatWebServer(tomcat, getPort() >= 0);
    }
}

@Component
public class TomcatConfiguration {
    @Bean
    public ConfigurableServletWebServerFactory webServerFactory() {
        TomcatServletWebServerFactory factory = new CustomTomcatServletWebServerFactory();

        return factory;
    }

Loading resources from context.xml doesn't work though. Will try to find out.

Spring Boot default H2 jdbc connection (and H2 console)

I had only below properties in /resources/application.properties. After running spring boot, using this URL(http://localhost:8080/h2-console/), the table in H2 console was visible and read to view the table data, also you can run simple SQL commands. One thing, in your java code, while fetching data, the column names are upper-case, even though schema.sql is using lower-case names :)

spring.datasource.initialize=true
spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=- 1;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.h2.console.enabled=true

Spring data jpa- No bean named 'entityManagerFactory' is defined; Injection of autowired dependencies failed

I think this is related to the newer version of spring boot plus using spring data JPA just replace @Bean annotation above public LocalContainerEntityManagerFactoryBean entityManagerFactory() to @Bean(name="entityManagerFactory")

Determining the name of bean should solve the issue

Which is best data type for phone number in MySQL and what should Java type mapping for it be?

  1. String
  2. Varchar

This is my opinion for my database as recommended by my mentor

java.lang.ClassNotFoundException: org.springframework.core.io.Resource

I received same error despite jar being in lib directory & added to deployment assembly in Eclipse.

So I doubted two things ,

1.Some Weblogic cache issue - as this app was deployed before & I was trying to redeploy after some changes

2.Jar itself is corrupt due to partial download etc

So I re downloaded the jar & deleted everything in directory - ..\Oracle_Home\user_projects\domains\base_domain\lib and redeployed again & all went well.

DB2 SQL error: SQLCODE: -206, SQLSTATE: 42703

That only means that an undefined column or parameter name was detected. The errror that DB2 gives should point what that may be:

DB2 SQL Error: SQLCODE=-206, SQLSTATE=42703, SQLERRMC=[THE_UNDEFINED_COLUMN_OR_PARAMETER_NAME], DRIVER=4.8.87

Double check your table definition. Maybe you just missed adding something.

I also tried google-ing this problem and saw this:

http://www.coderanch.com/t/515475/JDBC/databases/sql-insert-statement-giving-sqlcode

Spring Boot - Cannot determine embedded database driver class for database type NONE

Use this below dependency.

<dependency>
   <groupId>com.h2database</groupId>
   <artifactId>h2</artifactId>
   <scope>runtime</scope>
</dependency>

Spring boot Security Disable security

What also seems to work fine is creating a file application-dev.properties that contains:

security.basic.enabled=false
management.security.enabled=false

If you then start your Spring Boot app with the dev profile, you don't need to log on.

What is the difference between Hibernate and Spring Data JPA

There are 3 different things we are using here :

  1. JPA : Java persistence api which provide specification for persisting, reading, managing data from your java object to relations in database.
  2. Hibernate: There are various provider which implement jpa. Hibernate is one of them. So we have other provider as well. But if using jpa with spring it allows you to switch to different providers in future.
  3. Spring Data JPA : This is another layer on top of jpa which spring provide to make your life easy.

So lets understand how spring data jpa and spring + hibernate works-


Spring Data JPA:

Let's say you are using spring + hibernate for your application. Now you need to have dao interface and implementation where you will be writing crud operation using SessionFactory of hibernate. Let say you are writing dao class for Employee class, tomorrow in your application you might need to write similiar crud operation for any other entity. So there is lot of boilerplate code we can see here.

Now Spring data jpa allow us to define dao interfaces by extending its repositories(crudrepository, jparepository) so it provide you dao implementation at runtime. You don't need to write dao implementation anymore.Thats how spring data jpa makes your life easy.

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'MyController':

Exception clearly indicates the problem.

CompteDAOHib: No default constructor found

For spring to instantiate your bean, you need to provide a empty constructor for your class CompteDAOHib.

getting error HTTP Status 405 - HTTP method GET is not supported by this URL but not used `get` ever?

The problem is that you mapped your servlet to /register.html and it expects POST method, because you implemented only doPost() method. So when you open register.html page, it will not open html page with the form but servlet that handles the form data.

Alternatively when you submit POST form to non-existing URL, web container will display 405 error (method not allowed) instead of 404 (not found).

To fix:

<servlet-mapping>
    <servlet-name>Register</servlet-name>
    <url-pattern>/Register</url-pattern>
</servlet-mapping>

org.hibernate.MappingException: Unknown entity: annotations.Users

In my case it resolves by adding configuration.addAnnotatedClass(com.myApp.model.Example.class); after Configuration configuration = new Configuration().configure(HibernateUtil.class.getResource("/hibernate.cfg.xml")); in hibernateUtill class. It Read a mapping from the class annotation metadata . Read more about addAnnotatedClass() from here.

How to set up datasource with Spring for HikariCP?

You can create a datasource bean in servlet context as:

<beans:bean id="dataSource"
    class="com.zaxxer.hikari.HikariDataSource" destroy-method="close">
    <beans:property name="dataSourceClassName"
        value="com.mysql.jdbc.jdbc2.optional.MysqlDataSource" />
    <beans:property name="maximumPoolSize" value="5" />
    <beans:property name="maxLifetime" value="30000" />
    <beans:property name="idleTimeout" value="30000" />
    <beans:property name="dataSourceProperties">
        <beans:props>
            <beans:prop key="url">jdbc:mysql://localhost:3306/exampledb</beans:prop>
            <beans:prop key="user">root</beans:prop>
            <beans:prop key="password"></beans:prop>
            <beans:prop key="prepStmtCacheSize">250</beans:prop>
            <beans:prop key="prepStmtCacheSqlLimit">2048</beans:prop>
            <beans:prop key="cachePrepStmts">true</beans:prop>
            <beans:prop key="useServerPrepStmts">true</beans:prop>
        </beans:props>
    </beans:property>
</beans:bean>

Create a simple Login page using eclipse and mysql

You Can simply Use One Jsp Page To accomplish the task.

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="java.sql.*"%>
<!DOCTYPE html>
<html>
   <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSP Page</title>
</head>
<body>
    <%
        String username=request.getParameter("user_name");
        String password=request.getParameter("password");
        String role=request.getParameter("role");
        try
        {
            Class.forName("com.mysql.jdbc.Driver");
            Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/t_fleet","root","root");
            Statement st=con.createStatement();
            String query="select * from tbl_login where user_name='"+username+"' and password='"+password+"' and role='"+role+"'";
            ResultSet rs=st.executeQuery(query);
            while(rs.next())
            {
                session.setAttribute( "user_name",rs.getString(2));
                session.setMaxInactiveInterval(3000);
                response.sendRedirect("homepage.jsp");
            }
            %>



        <%}
        catch(Exception e)
        {
            out.println(e);
        }
    %>

</body>

I have use username, password and role to get into the system. One more thing to implement is you can do page permission checking through jsp and javascript function.

org.hibernate.hql.internal.ast.QuerySyntaxException: table is not mapped

Other persons that are using mapping classes for Hibernate, make sure that have addressed correctly to model package in sessionFactory bean declaration in the following part:

public List<Book> list() {
    List<Book> list=SessionFactory.getCurrentSession().createQuery("from book").list();
    return list;
}

The mistake I did in the above snippet is that I have used the table name foo inside createQuery. Instead, I got to use Foo, the actual class name.

public List<Book> list() {                                                                               
    List<Book> list=SessionFactory.getCurrentSession().createQuery("from Book").list();
    return list;
}

java.lang.ClassNotFoundException: sun.jdbc.odbc.JdbcOdbcDriver Exception occurring. Why?

in JDK 8, jdbc odbc bridge is no longer used and thus removed fro the JDK. to use Microsoft Access database in JAVA, you need 5 extra JAR libraries.

1- hsqldb.jar

2- jackcess 2.0.4.jar

3- commons-lang-2.6.jar

4- commons-logging-1.1.1.jar

5- ucanaccess-2.0.8.jar

add these libraries to your java project and start with following lines.

Connection conn=DriverManager.getConnection("jdbc:ucanaccess://<Path to your database i.e. MS Access DB>");
Statement s = conn.createStatement();

path could be like E:/Project/JAVA/DBApp

and then your query to be executed. Like

ResultSet rs = s.executeQuery("SELECT * FROM Course");
while(rs.next())
    System.out.println(rs.getString("Title") + " " + rs.getString("Code") + " " + rs.getString("Credits"));

certain imports to be used. try catch block must be used and some necessary things no to be forgotten.

Remember, no need of bridging drivers like jdbc odbc or any stuff.

Spring Boot JPA - configuring auto reconnect

As some people already pointed out, spring-boot 1.4+, has specific namespaces for the four connections pools. By default, hikaricp is used in spring-boot 2+. So you will have to specify the SQL here. The default is SELECT 1. Here's what you would need for DB2 for example: spring.datasource.hikari.connection-test-query=SELECT current date FROM sysibm.sysdummy1

Caveat: If your driver supports JDBC4 we strongly recommend not setting this property. This is for "legacy" drivers that do not support the JDBC4 Connection.isValid() API. This is the query that will be executed just before a connection is given to you from the pool to validate that the connection to the database is still alive. Again, try running the pool without this property, HikariCP will log an error if your driver is not JDBC4 compliant to let you know. Default: none

Name [jdbc/mydb] is not bound in this Context

You need a ResourceLink in your META-INF/context.xml file to make the global resource available to the web application.

 <ResourceLink name="jdbc/mydb"
             global="jdbc/mydb"
              type="javax.sql.DataSource" />

java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/dbname

try this

String url = "jdbc:mysql://localhost:3306/<dbname>";
String user = "<username>";
String password = "<password>";
conn = DriverManager.getConnection(url, user, password); 

SEVERE: Unable to create initial connections of pool - tomcat 7 with context.xml file

I use sprint-boot (2.1.1), and mysql version is 8.0.13. I add dependency in pom, solve my problem.

 <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.13</version>
 </dependency>

MySQL Connector/J » 8.0.13 link: https://mvnrepository.com/artifact/mysql/mysql-connector-java/8.0.13
MySQL Connector/J » All the version link: https://mvnrepository.com/artifact/mysql/mysql-connector-java

Mapping a JDBC ResultSet to an object

If you don't want to use any JPA provider such as OpenJPA or Hibernate, you can just give Apache DbUtils a try.

http://commons.apache.org/proper/commons-dbutils/examples.html

Then your code will look like this:

QueryRunner run = new QueryRunner(dataSource);

// Use the BeanListHandler implementation to convert all
// ResultSet rows into a List of Person JavaBeans.
ResultSetHandler<List<Person>> h = new BeanListHandler<Person>(Person.class);

// Execute the SQL statement and return the results in a List of
// Person objects generated by the BeanListHandler.
List<Person> persons = run.query("SELECT * FROM Person", h);

Manipulating an Access database from Java without ODBC

UCanAccess is a pure Java JDBC driver that allows us to read from and write to Access databases without using ODBC. It uses two other packages, Jackcess and HSQLDB, to perform these tasks. The following is a brief overview of how to get it set up.

 

Option 1: Using Maven

If your project uses Maven you can simply include UCanAccess via the following coordinates:

groupId: net.sf.ucanaccess
artifactId: ucanaccess

The following is an excerpt from pom.xml, you may need to update the <version> to get the most recent release:

  <dependencies>
    <dependency>
        <groupId>net.sf.ucanaccess</groupId>
        <artifactId>ucanaccess</artifactId>
        <version>4.0.4</version>
    </dependency>
  </dependencies>

 

Option 2: Manually adding the JARs to your project

As mentioned above, UCanAccess requires Jackcess and HSQLDB. Jackcess in turn has its own dependencies. So to use UCanAccess you will need to include the following components:

UCanAccess (ucanaccess-x.x.x.jar)
HSQLDB (hsqldb.jar, version 2.2.5 or newer)
Jackcess (jackcess-2.x.x.jar)
commons-lang (commons-lang-2.6.jar, or newer 2.x version)
commons-logging (commons-logging-1.1.1.jar, or newer 1.x version)

Fortunately, UCanAccess includes all of the required JAR files in its distribution file. When you unzip it you will see something like

ucanaccess-4.0.1.jar  
  /lib/
    commons-lang-2.6.jar  
    commons-logging-1.1.1.jar  
    hsqldb.jar  
    jackcess-2.1.6.jar

All you need to do is add all five (5) JARs to your project.

NOTE: Do not add loader/ucanload.jar to your build path if you are adding the other five (5) JAR files. The UcanloadDriver class is only used in special circumstances and requires a different setup. See the related answer here for details.

Eclipse: Right-click the project in Package Explorer and choose Build Path > Configure Build Path.... Click the "Add External JARs..." button to add each of the five (5) JARs. When you are finished your Java Build Path should look something like this

BuildPath.png

NetBeans: Expand the tree view for your project, right-click the "Libraries" folder and choose "Add JAR/Folder...", then browse to the JAR file.

nbAddJar.png

After adding all five (5) JAR files the "Libraries" folder should look something like this:

nbLibraries.png

IntelliJ IDEA: Choose File > Project Structure... from the main menu. In the "Libraries" pane click the "Add" (+) button and add the five (5) JAR files. Once that is done the project should look something like this:

IntelliJ.png

 

That's it!

Now "U Can Access" data in .accdb and .mdb files using code like this

// assumes...
//     import java.sql.*;
Connection conn=DriverManager.getConnection(
        "jdbc:ucanaccess://C:/__tmp/test/zzz.accdb");
Statement s = conn.createStatement();
ResultSet rs = s.executeQuery("SELECT [LastName] FROM [Clients]");
while (rs.next()) {
    System.out.println(rs.getString(1));
}

 

Disclosure

At the time of writing this Q&A I had no involvement in or affiliation with the UCanAccess project; I just used it. I have since become a contributor to the project.

Sonar properties files

Do the build job on Jenkins first without Sonar configured. Then add Sonar, and run a build job again. Should fix the problem

Ansible - read inventory hosts and variables to group_vars/all file

Just in case if the problem is still there, You can refer to ansible inventory through ‘hostvars’, ‘group_names’, and ‘groups’ ansible variables.

Example:

To be able to get ip addresses of all servers within group "mygroup", use the below construction:

- debug: msg="{{ hostvars[item]['ansible_eth0']['ipv4']['address'] }}" 
  with_items:
     - "{{ groups['mygroup'] }}"

Data truncation: Data too long for column 'logo' at row 1

You are trying to insert data that is larger than allowed for the column logo.

Use following data types as per your need

TINYBLOB   :     maximum length of 255 bytes  
BLOB       :     maximum length of 65,535 bytes  
MEDIUMBLOB :     maximum length of 16,777,215 bytes  
LONGBLOB   :     maximum length of 4,294,967,295 bytes  

Use LONGBLOB to avoid this exception.

insert data into database using servlet and jsp in eclipse

In your JSP at line <form> tag, try this code

<form name="registrationform" action="Register" method="post">

Spring @PropertySource using YAML

Spring-boot has a helper for this, just add

@ContextConfiguration(initializers = ConfigFileApplicationContextInitializer.class)

at the top of your test classes or an abstract test superclass.

Edit: I wrote this answer five years ago. It doesn't work with recent versions of Spring Boot. This is what I do now (please translate the Kotlin to Java if necessary):

@TestPropertySource(locations=["classpath:application.yml"])
@ContextConfiguration(
        initializers=[ConfigFileApplicationContextInitializer::class]
)

is added to the top, then

    @Configuration
    open class TestConfig {

        @Bean
        open fun propertiesResolver(): PropertySourcesPlaceholderConfigurer {
            return PropertySourcesPlaceholderConfigurer()
        }
    }

to the context.

JDBC ResultSet: I need a getDateTime, but there is only getDate and getTimeStamp

The solution I opted for was to format the date with the mysql query :

String l_mysqlQuery = "SELECT DATE_FORMAT(time, '%Y-%m-%d %H:%i:%s') FROM uld_departure;"
l_importedTable = fStatement.executeQuery( l_mysqlQuery );
System.out.println(l_importedTable.getString( timeIndex));

I had the exact same issue. Even though my mysql table contains dates formatted as such : 2017-01-01 21:02:50

String l_mysqlQuery = "SELECT time FROM uld_departure;"
l_importedTable = fStatement.executeQuery( l_mysqlQuery );
System.out.println(l_importedTable.getString( timeIndex));

was returning a date formatted as such : 2017-01-01 21:02:50.0

Error creating bean with name 'entityManagerFactory

This sounds like a ClassLoader conflict. I'd bet you have the javax.persistence api 1.x on the classpath somewhere, whereas Spring is trying to access ValidationMode, which was only introduced in JPA 2.0.

Since you use Maven, do mvn dependency:tree, find the artifact:

<dependency>
    <groupId>javax.persistence</groupId>
    <artifactId>persistence-api</artifactId>
    <version>1.0</version>
</dependency>

And remove it from your setup. (See Excluding Dependencies)

AFAIK there is no such general distribution for JPA 2, but you can use this Hibernate-specific version:

<dependency>
    <groupId>org.hibernate.javax.persistence</groupId>
    <artifactId>hibernate-jpa-2.0-api</artifactId>
    <version>1.0.1.Final</version>
</dependency>

OK, since that doesn't work, you still seem to have some JPA-1 version in there somewhere. In a test method, add this code:

System.out.println(EntityManager.class.getProtectionDomain()
                                      .getCodeSource()
                                      .getLocation());

See where that points you and get rid of that artifact.


Ahh, now I finally see the problem. Get rid of this:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jpa</artifactId>
    <version>2.0.8</version>
</dependency>

and replace it with

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-orm</artifactId>
    <version>3.2.5.RELEASE</version>
</dependency>

On a different note, you should set all test libraries (spring-test, easymock etc.) to

<scope>test</scope>

Iterating through a List Object in JSP

 <c:forEach items="${sessionScope.empL}" var="emp">
            <tr>
                <td>Employee ID: <c:out value="${emp.eid}"/></td>
                <td>Employee Pass: <c:out value="${emp.ename}"/></td>  
            </tr>
        </c:forEach>

Could not open input file: composer.phar

Try in command line:

curl -sS https://getcomposer.org/installer | php

ORA-12516, TNS:listener could not find available handler

I fixed this problem with sql command line:

connect system/<password>
alter system set processes=300 scope=spfile;
alter system set sessions=300 scope=spfile;

Restart database.

Launching Spring application Address already in use

first, check that who uses port 8080.

if the port 8080 is in use, change the listening port to 8181.

if you use IDEA, modify start configuration, Run-> Edit Configuration enter image description here

if you use mvn spring-boot, then use the command:

mvn spring-boot:run -Dserver.port=8181

if you use java -jar, then use the command:

java -jar xxxx.jar --server.port=8181

Read JSON data in a shell script

Similarly using Bash regexp. Shall be able to snatch any key/value pair.

key="Body"
re="\"($key)\": \"([^\"]*)\""

while read -r l; do
    if [[ $l =~ $re ]]; then
        name="${BASH_REMATCH[1]}"
        value="${BASH_REMATCH[2]}"
        echo "$name=$value"
    else
        echo "No match"
    fi
done

Regular expression can be tuned to match multiple spaces/tabs or newline(s). Wouldn't work if value has embedded ". This is an illustration. Better to use some "industrial" parser :)

@Autowired - No qualifying bean of type found for dependency

Faced the same issue in my spring boot application even though I had my package specific scans enabled like

@SpringBootApplication(scanBasePackages={"com.*"})

But, the issue was resolved by providing @ComponentScan({"com.*"}) in my Application class.

Could not resolve placeholder in string value

With Spring Boot :

In the pom.xml

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

Example in class Java

@Configuration
@Slf4j
public class MyAppConfig {
    @Value("${foo}")
    private String foo;
    @Value("${bar}")
    private String bar;
    @Bean("foo")
    public String foo() {
        log.info("foo={}", foo);
        return foo;
    }
    @Bean("bar")
    public String bar() {
        log.info("bar={}", bar);
        return bar;
    }
    [ ... ]

In the properties files :

src/main/resources/application.properties

foo=all-env-foo

src/main/resources/application-rec.properties

bar=rec-bar

src/main/resources/application-prod.properties

bar=prod-bar

In the VM arguments of Application.java

-Dspring.profiles.active=[rec|prod]

Don't forget to run mvn command after modifying the properties !

mvn clean package -Dmaven.test.skip=true

In the log file for -Dspring.profiles.active=rec :

The following profiles are active: rec
foo=all-env-foo
bar=rec-bar

In the log file for -Dspring.profiles.active=prod :

The following profiles are active: prod
foo=all-env-foo
bar=prod-bar

In the log file for -Dspring.profiles.active=local :

Could not resolve placeholder 'bar' in value "${bar}"

Oups, I forget to create application-local.properties.

ORA-01830: date format picture ends before converting entire input string / Select sum where date query

You can try this:

Select To_date ('15/2/2007 00:00:00', 'DD/MM/YYYY HH24:MI:SS'),
       To_date ('28/2/2007 10:12', 'DD/MM/YYYY HH24:MI:SS')
  From DUAL;

Source: http://notsyncing.org/2008/02/manipulando-fechas-con-horas-en-plsql-y-sql/

What is IllegalStateException?

public class UserNotFoundException extends Exception {
    public UserNotFoundException(String message) {
        super(message)

BeanFactory not initialized or already closed - call 'refresh' before

I had the same error and I had not made any changes to the application config or the web.xml. Multiple tries to revert back some minor changes to code was not clearing the exceptions. Finally it worked after restarting STS.

could not extract ResultSet in hibernate

I faced the same problem after migrating a database from online server to localhost. The schema changed so I had to define the schema manually for each table:

@Entity
@Table(name = "ESBCORE_DOMAIN", schema = "SYS")

"The import org.springframework cannot be resolved."

In my case I had to delete the jars inside .m2/repository and then did a Maven->Update Maven Project

Looks like the jars were corrupt and deleting and downloading the fresh jar fixed the issue.

JDBC ODBC Driver Connection

As mentioned in the comments to the question, the JDBC-ODBC Bridge is - as the name indicates - only a mechanism for the JDBC layer to "talk to" the ODBC layer. Even if you had a JDBC-ODBC Bridge on your Mac you would also need to have

  • an implementation of ODBC itself, and
  • an appropriate ODBC driver for the target database (ACE/Jet, a.k.a. "Access")

So, for most people, using JDBC-ODBC Bridge technology to manipulate ACE/Jet ("Access") databases is really a practical option only under Windows. It is also important to note that the JDBC-ODBC Bridge will be has been removed in Java 8 (ref: here).

There are other ways of manipulating ACE/Jet databases from Java, such as UCanAccess and Jackcess. Both of these are pure Java implementations so they work on non-Windows platforms. For details on how to use UCanAccess see

Manipulating an Access database from Java without ODBC

How to approach a "Got minus one from a read call" error when connecting to an Amazon RDS Oracle instance

The immediate cause of the problem is that the JDBC driver has attempted to read from a network Socket that has been closed by "the other end".

This could be due to a few things:

  • If the remote server has been configured (e.g. in the "SQLNET.ora" file) to not accept connections from your IP.

  • If the JDBC url is incorrect, you could be attempting to connect to something that isn't a database.

  • If there are too many open connections to the database service, it could refuse new connections.

Given the symptoms, I think the "too many connections" scenario is the most likely. That suggests that your application is leaking connections; i.e. creating connections and then failing to (always) close them.

Spring Data JPA - "No Property Found for Type" Exception

If you are using ENUM like MessageStatus, you may need a converter. Just add this class:

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;

/**
 * Convert ENUM type in JPA.
 */
@Converter(autoApply = true)
public class MessageStatusConverter implements AttributeConverter<MessageStatus, Integer> {
  @Override
  public Integer convertToDatabaseColumn(MessageStatus messageStatus) {
    return messageStatus.getValue();
  }

  @Override
  public MessageStatus convertToEntityAttribute(Integer i) {
    return MessageStatus.valueOf(i);
  }
}

Missing artifact com.microsoft.sqlserver:sqljdbc4:jar:4.0

The above answer only adds the sqljdbc4.jar to the local repository. As a result, when creating the final project jar for distribution, sqljdbc4 will again be missing as was indicated in the comment by @Tony regarding runtime error.

Microsoft (and Oracle and other third party providers) restrict the distribution of their software as per the ENU/EULA. Therefore those software modules do not get added in Maven produced jars for distribution. There are hacks to get around it (such as providing the location of the 3rd party jar file at runtime), but as a developer you must be careful about violating the licensing.

A better approach for jdbc connectors/drivers is to use jTDS, which is compatible to most DBMS's, more reliable, faster (as per benchmarks), and distributed under GNU license. It will make your life much easier to use this than trying to pound the square peg into the round hole following any of the other techniques above.

HTTP Status 500 - org.apache.jasper.JasperException: java.lang.NullPointerException

NullPointerException with JSP can also happen if:

A getter returns a non-public inner class.

This code will fail if you remove Getters's access modifier or make it private or protected.

JAVA:

package com.myPackage;
public class MyClass{ 
    //: Must be public or you will get:
    //: org.apache.jasper.JasperException: 
    //: java.lang.NullPointerException
    public class Getters{
        public String 
        myProperty(){ return(my_property); }
    };;

    //: JSP EL can only access functions:
    private Getters _get;
    public  Getters  get(){ return _get; }

    private String 
    my_property;

    public MyClass(String my_property){
        super();
        this.my_property    = my_property;
        _get = new Getters();
    };;
};;

JSP

<%@ taglib uri   ="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page import="com.myPackage.MyClass" %>
<%
    MyClass inst = new MyClass("[PROP_VALUE]");
    pageContext.setAttribute("my_inst", inst ); 
%><html lang="en"><body>
    ${ my_inst.get().myProperty() }
</body></html>

Java program to connect to Sql Server and running the sample query From Eclipse

you forgotten to add the sqlserver.jar in eclipse external library follow the process to add jar files

  1. Right click on your project.
  2. click buildpath
  3. click configure bulid path
  4. click add external jar and then give the path of jar

How to display a database table on to the table in the JSP page

you can also print the data onto your HTML/JSP document. like:-

<!DOCTYPE html>
<html>
<head>
    <title>Jsp Sample</title>
    <%@page import="java.sql.*;"%>
</head>
<body bgcolor=yellow>
    <%
    try
    {
        Class.forName("com.mysql.jdbc.Driver");
        Connection con=(Connection)DriverManager.getConnection(
            "jdbc:mysql://localhost:3306/forum","root","root");
        Statement st=con.createStatement();
        ResultSet rs=st.executeQuery("select * from student;");
    %><table border=1 align=center style="text-align:center">
      <thead>
          <tr>
             <th>ID</th>
             <th>NAME</th>
             <th>SKILL</th>
             <th>ACTION</th>
          </tr>
      </thead>
      <tbody>
        <%while(rs.next())
        {
            %>
            <tr>
                <td><%=rs.getString("id") %></td>
                <td><%=rs.getString("name") %></td>
                <td><%=rs.getString("skill") %></td>
                <td><%=rs.getString("action") %></td>
            </tr>
            <%}%>
           </tbody>
        </table><br>
    <%}
    catch(Exception e){
        out.print(e.getMessage());%><br><%
    }
    finally{
        st.close();
        con.close();
    }
    %>
</body>
</html>

<!--executeUpdate() mainupulation and executeQuery() for retriving-->

JDBC connection failed, error: TCP/IP connection to host failed

Open %windir%\System32 folder and find SQLServerManagerXX.msc

For example:

C:\Windows\System32\SQLServerManager14.msc

Go to protocols settings then enable TCP/IP port is 1433 by default

enter image description here

enter image description here

The APR based Apache Tomcat Native library was not found on the java.library.path

not found on the java.library.path: /usr/java/packages/lib/amd64:/usr/lib64:/lib64:/lib:/usr/lib

The native lib is expected in one of the following locations

/usr/java/packages/lib/amd64
/usr/lib64
/lib64
/lib
/usr/lib

and not in

tomcat/lib

The files in tomcat/lib are all jar file and are added by tomcat to the classpath so that they are available to your application.

The native lib is needed by tomcat to perform better on the platform it is installed on and thus cannot be a jar, for linux it could be a .so file, for windows it could be a .dll file.

Just download the native library for your platform and place it in the one of the locations tomcat is expecting it to be.

Note that you are not required to have this lib for development/test purposes. Tomcat runs just fine without it.

org.apache.catalina.startup.Catalina start INFO: Server startup in 2882 ms

EDIT

The output you are getting is very normal, it's just some logging outputs from tomcat, the line right above indicates that the server correctly started and is ready for operating.

If you are troubling with running your servlet then after the run on sever command eclipse opens a browser window (embeded (default) or external, depends on your config). If nothing shows on the browser, then check the url bar of the browser to see whether your servlet was requested or not.

It should be something like that

http://localhost:8080/<your-context-name>/<your-servlet-name>

EDIT 2

Try to call your servlet using the following url

http://localhost:8080/com.filecounter/FileCounter

Also each web project has a web.xml, you can find it in your project under WebContent\WEB-INF.

It is better to configure your servlets there using servlet-name servlet-class and url-mapping. It could look like that:

  <servlet>
    <description></description>
    <display-name>File counter - My first servlet</display-name>
    <servlet-name>file_counter</servlet-name>
    <servlet-class>com.filecounter.FileCounter</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>file_counter</servlet-name>
    <url-pattern>/FileFounter</url-pattern>
  </servlet-mapping>

In eclipse dynamic web project the default context name is the same as your project name.

http://localhost:8080/<your-context-name>/FileCounter

will work too.

Trouble Connecting to sql server Login failed. "The login is from an untrusted domain and cannot be used with Windows authentication"

In my case the Aliases within SQL Native Client 11.0 Configuration were pointing to invalid server/IP. Once updated it worked correctly.

To check: 1. Start "SQL Server Configuration Manager" 2. Navigate to "SQL Native Client 11.0 Configuration" and then "Aliases" 3. Ensure "Alias Name" and "Server" match correctly for TCP/IP

Simulate CREATE DATABASE IF NOT EXISTS for PostgreSQL?

I had to use a slightly extended version @Erwin Brandstetter used:

DO
$do$
DECLARE
  _db TEXT := 'some_db';
  _user TEXT := 'postgres_user';
  _password TEXT := 'password';
BEGIN
  CREATE EXTENSION IF NOT EXISTS dblink; -- enable extension 
  IF EXISTS (SELECT 1 FROM pg_database WHERE datname = _db) THEN
    RAISE NOTICE 'Database already exists';
  ELSE
    PERFORM dblink_connect('host=localhost user=' || _user || ' password=' || _password || ' dbname=' || current_database());
    PERFORM dblink_exec('CREATE DATABASE ' || _db);
  END IF;
END
$do$

I had to enable the dblink extension, plus i had to provide the credentials for dblink. Works with Postgres 9.4.

Inserting records into a MySQL table using Java

this can also be done like this if you don't want to use prepared statements.

String sql = "INSERT INTO course(course_code,course_desc,course_chair)"+"VALUES('"+course_code+"','"+course_desc+"','"+course_chair+"');"

Why it didnt insert value is because you were not providing values, but you were providing names of variables that you have used.

Get the current date in java.sql.Date format

all you have to do is this

    Calendar currenttime = Calendar.getInstance();               //creates the Calendar object of the current time
    Date sqldate = new Date((currenttime.getTime()).getTime());  //creates the sql Date of the above created object
    pstm.setDate(6, (java.sql.Date) date);              //assign it to the prepared statement (pstm in this case)

ORA-12505, TNS:listener does not currently know of SID given in connect descriptor

I encounter this problem because I did kill task to "Oracle" task in the Task Manager. To fix it you need to open the cmd -> type: services.msc -> the window with all services will open -> find service "OracleServiceXE" -> right click: start.

Fastest way to determine if record exists

SELECT COUNT(*) FROM products WHERE products.id = ?;

This is the cross relational database solution that works in all databases.

Could not get constructor for org.hibernate.persister.entity.SingleTableEntityPersister

I resolved this issue by excluding byte-buddy dependency from springfox

<dependency>
  <groupId>io.springfox</groupId>
  <artifactId>springfox-swagger2</artifactId>
  <version>2.7.0</version>
  <exclusions>
  <exclusion>
    <groupId>net.bytebuddy</groupId>
    <artifactId>byte-buddy</artifactId>
  </exclusion>
  </exclusions>
</dependency>

<dependency>
  <groupId>io.springfox</groupId>
  <artifactId>springfox-swagger-ui</artifactId>
  <version>2.7.0</version>
  <exclusions>
  <exclusion>
    <groupId>net.bytebuddy</groupId>
    <artifactId>byte-buddy</artifactId>
  </exclusion>
</exclusions>
</dependency>

The network adapter could not establish the connection - Oracle 11g

I had the similar issue. its resolved for me with a simple command.

lsnrctl start

The Network Adapter exception is caused because:

  1. The database host name or port number is wrong (OR)
  2. The database TNSListener has not been started. The TNSListener may be started with the lsnrctl utility.

Try to start the listener using the command prompt:

  1. Click Start, type cmd in the search field, and when cmd shows up in the list of options, right click it and select ‘Run as Administrator’.
  2. At the Command Prompt window, type lsnrctl start without the quotes and press Enter.
  3. Type Exit and press Enter.

Hope it helps.

How to delete and update a record in Hive

Once you have installed and configured Hive , create simple table :

hive>create table testTable(id int,name string)row format delimited fields terminated by ',';

Then, try to insert few rowsin test table.

hive>insert into table testTable values (1,'row1'),(2,'row2');

Now try to delete records , you just inserted in table.

hive>delete from testTable where id = 1;

Error! FAILED: SemanticException [Error 10294]: Attempt to do update or delete using transaction manager that does not support these operations.

By default transactions are configured to be off. It is been said that update is not supported with the delete operation used in the conversion manager. To support update/delete , you must change following configuration.

cd  $HIVE_HOME
vi conf/hive-site.xml

Add below properties to file

<property>
  <name>hive.support.concurrency</name>
  <value>true</value>
 </property>
 <property>
  <name>hive.enforce.bucketing</name>
  <value>true</value>
 </property>
 <property>
  <name>hive.exec.dynamic.partition.mode</name>
  <value>nonstrict</value>
 </property>
 <property>
  <name>hive.txn.manager</name>
  <value>org.apache.hadoop.hive.ql.lockmgr.DbTxnManager</value>
 </property>
 <property>
  <name>hive.compactor.initiator.on</name>
  <value>true</value>
 </property>
 <property>
  <name>hive.compactor.worker.threads</name>
  <value>2</value>
 </property>

Restart the service and then try delete command again :

Error!

FAILED: LockException [Error 10280]: Error communicating with the metastore.

There is problem with metastore. In order to use insert/update/delete operation, You need to change following configuration in conf/hive-site.xml as feature is currently in development.

<property>
  <name>hive.in.test</name>
  <value>true</value>
 </property>

Restart the service and then delete command again :

hive>delete from testTable where id = 1;

Error!

FAILED: SemanticException [Error 10297]: Attempt to do update or delete on table default.testTable that does not use an AcidOutputFormat or is not bucketed.

Only ORC file format is supported in this first release. The feature has been built such that transactions can be used by any storage format that can determine how updates or deletes apply to base records (basically, that has an explicit or implicit row id), but so far the integration work has only been done for ORC.

Tables must be bucketed to make use of these features. Tables in the same system not using transactions and ACID do not need to be bucketed.

See below built table example with ORCFileformat, bucket enabled and ('transactional'='true').

hive>create table testTableNew(id int ,name string ) clustered by (id) into 2 buckets stored as orc TBLPROPERTIES('transactional'='true');

Insert :

hive>insert into table testTableNew values (1,'row1'),(2,'row2'),(3,'row3');

Update :

hive>update testTableNew set name = 'updateRow2' where id = 2;

Delete :

hive>delete from testTableNew where id = 1;

Test :

hive>select * from testTableNew ;

Spring not autowiring in unit tests with JUnit

I'm using JUnit 5 and for me the problem was that I had imported Test from the wrong package:

import org.junit.Test;

Replacing it with the following worked for me:

import org.junit.jupiter.api.Test;

java.lang.ClassNotFoundException: com.mysql.jdbc.Driver in Eclipse

For Gradle-based projects you need a dependency on MySQL Java Connector:

dependencies {
    compile 'mysql:mysql-connector-java:6.0.+'
}

SqlServer: Login failed for user

In my case, I had to activate the option "SQL Server and Windows Authentication mode", follow all steps below:

1 - Right-click on your server enter image description here

2 - Go to option Security

3 - Check the option "SQL Server and Windows Authentication mode"

4 - Click on the Ok button enter image description here

5 - Restart your SQL Express Service ("Windows Key" on the keyboard and write "Services", and then Enter key) enter image description here

After that, I could log in with user and password

dll missing in JDBC

Set java.library.path to a directory containing this DLL which Java uses to find native libraries. Specify -D switch on the command line

java -Djava.library.path=C:\Java\native\libs YourProgram

C:\Java\native\libs should contain sqljdbc_auth.dll

Look at this SO post if you are using Eclipse or at this blog if you want to set programatically.

Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:2.3.2:compile (default-compile)

It is because your Maven not able to find settings file. If deleting .m2 not work, try below solution

Go to your JOB configuration

than to the Build section

Add build step :- Invoke top level maven target and fill Maven version and Goal

than click on Advance button and mention settings file path as mention in image enter image description here

JPA With Hibernate Error: [PersistenceUnit: JPA] Unable to build EntityManagerFactory

Suppress the @JoinColumn(name="categoria") on the ID field of the Categoria class and I think it will work.

JDBC connection to MSSQL server in windows authentication mode

From your exception trace, it looks like there is multiple possibility for this problem

1). You have to check that your port "1433" is blocked by firewall or not. If you find that it is blocked then you should have to write "Inbound Rule". It if found in control panel -> windows firewall -> Advance Setting (Option found at Left hand side) -> Inbound Rule.

2). In SQL Server configuration Manager, your TCP/IP protocol will find in disable mode. So, you should have to enable it.

SQL Error: 0, SQLState: 08S01 Communications link failure

Check your server config file /etc/mysql/my.cnf - verify bind_address is not set to 127.0.0.1. Set it to 0.0.0.0 or comment it out then restart server with:

sudo service mysql restart

c++ Read from .csv file

You can follow this answer to see many different ways to process CSV in C++.

In your case, the last call to getline is actually putting the last field of the first line and then all of the remaining lines into the variable genero. This is because there is no space delimiter found up until the end of file. Try changing the space character into a newline instead:

    getline(file, genero, file.widen('\n'));

or more succinctly:

    getline(file, genero);

In addition, your check for file.good() is premature. The last newline in the file is still in the input stream until it gets discarded by the next getline() call for ID. It is at this point that the end of file is detected, so the check should be based on that. You can fix this by changing your while test to be based on the getline() call for ID itself (assuming each line is well formed).

while (getline(file, ID, ',')) {
    cout << "ID: " << ID << " " ; 

    getline(file, nome, ',') ;
    cout << "User: " << nome << " " ;

    getline(file, idade, ',') ;
    cout << "Idade: " << idade << " "  ; 

    getline(file, genero);
    cout << "Sexo: " <<  genero<< " "  ;
}

For better error checking, you should check the result of each call to getline().

error: package javax.servlet does not exist

The javax.servlet dependency is missing in your pom.xml. Add the following to the dependencies-Node:

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.0.1</version>
    <scope>provided</scope>
</dependency>

Junit test case for database insert method with DAO and web service

This is one sample dao test using junit in spring project.

import java.util.List;

import junit.framework.Assert;

import org.jboss.tools.example.springmvc.domain.Member;
import org.jboss.tools.example.springmvc.repo.MemberDao;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Transactional;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:test-context.xml",
"classpath:/META-INF/spring/applicationContext.xml"})
@Transactional
@TransactionConfiguration(defaultRollback=true)
public class MemberDaoTest
{
    @Autowired
    private MemberDao memberDao;

    @Test
    public void testFindById()
    {
        Member member = memberDao.findById(0l);

        Assert.assertEquals("John Smith", member.getName());
        Assert.assertEquals("[email protected]", member.getEmail());
        Assert.assertEquals("2125551212", member.getPhoneNumber());
        return;
    }

    @Test
    public void testFindByEmail()
    {
        Member member = memberDao.findByEmail("[email protected]");

        Assert.assertEquals("John Smith", member.getName());
        Assert.assertEquals("[email protected]", member.getEmail());
        Assert.assertEquals("2125551212", member.getPhoneNumber());
        return;
    }

    @Test
    public void testRegister()
    {
        Member member = new Member();
        member.setEmail("[email protected]");
        member.setName("Jane Doe");
        member.setPhoneNumber("2125552121");

        memberDao.register(member);
        Long id = member.getId();
        Assert.assertNotNull(id);

        Assert.assertEquals(2, memberDao.findAllOrderedByName().size());
        Member newMember = memberDao.findById(id);

        Assert.assertEquals("Jane Doe", newMember.getName());
        Assert.assertEquals("[email protected]", newMember.getEmail());
        Assert.assertEquals("2125552121", newMember.getPhoneNumber());
        return;
    }

    @Test
    public void testFindAllOrderedByName()
    {
        Member member = new Member();
        member.setEmail("[email protected]");
        member.setName("Jane Doe");
        member.setPhoneNumber("2125552121");
        memberDao.register(member);

        List<Member> members = memberDao.findAllOrderedByName();
        Assert.assertEquals(2, members.size());
        Member newMember = members.get(0);

        Assert.assertEquals("Jane Doe", newMember.getName());
        Assert.assertEquals("[email protected]", newMember.getEmail());
        Assert.assertEquals("2125552121", newMember.getPhoneNumber());
        return;
    }
}

Transaction isolation levels relation with locks on table

As brb tea says, depends on the database implementation and the algorithm they use: MVCC or Two Phase Locking.

CUBRID (open source RDBMS) explains the idea of this two algorithms:

  • Two-phase locking (2PL)

The first one is when the T2 transaction tries to change the A record, it knows that the T1 transaction has already changed the A record and waits until the T1 transaction is completed because the T2 transaction cannot know whether the T1 transaction will be committed or rolled back. This method is called Two-phase locking (2PL).

  • Multi-version concurrency control (MVCC)

The other one is to allow each of them, T1 and T2 transactions, to have their own changed versions. Even when the T1 transaction has changed the A record from 1 to 2, the T1 transaction leaves the original value 1 as it is and writes that the T1 transaction version of the A record is 2. Then, the following T2 transaction changes the A record from 1 to 3, not from 2 to 4, and writes that the T2 transaction version of the A record is 3.

When the T1 transaction is rolled back, it does not matter if the 2, the T1 transaction version, is not applied to the A record. After that, if the T2 transaction is committed, the 3, the T2 transaction version, will be applied to the A record. If the T1 transaction is committed prior to the T2 transaction, the A record is changed to 2, and then to 3 at the time of committing the T2 transaction. The final database status is identical to the status of executing each transaction independently, without any impact on other transactions. Therefore, it satisfies the ACID property. This method is called Multi-version concurrency control (MVCC).

The MVCC allows concurrent modifications at the cost of increased overhead in memory (because it has to maintain different versions of the same data) and computation (in REPETEABLE_READ level you can't loose updates so it must check the versions of the data, like Hiberate does with Optimistick Locking).

In 2PL Transaction isolation levels control the following:

  • Whether locks are taken when data is read, and what type of locks are requested.

  • How long the read locks are held.

  • Whether a read operation referencing rows modified by another transaction:

    • Block until the exclusive lock on the row is freed.

    • Retrieve the committed version of the row that existed at the time the statement or transaction started.

    • Read the uncommitted data modification.

Choosing a transaction isolation level does not affect the locks that are acquired to protect data modifications. A transaction always gets an exclusive lock on any data it modifies and holds that lock until the transaction completes, regardless of the isolation level set for that transaction. For read operations, transaction isolation levels primarily define the level of protection from the effects of modifications made by other transactions.

A lower isolation level increases the ability of many users to access data at the same time, but increases the number of concurrency effects, such as dirty reads or lost updates, that users might encounter.

Concrete examples of the relation between locks and isolation levels in SQL Server (use 2PL except on READ_COMMITED with READ_COMMITTED_SNAPSHOT=ON)

  • READ_UNCOMMITED: do not issue shared locks to prevent other transactions from modifying data read by the current transaction. READ UNCOMMITTED transactions are also not blocked by exclusive locks that would prevent the current transaction from reading rows that have been modified but not committed by other transactions. [...]

  • READ_COMMITED:

    • If READ_COMMITTED_SNAPSHOT is set to OFF (the default): uses shared locks to prevent other transactions from modifying rows while the current transaction is running a read operation. The shared locks also block the statement from reading rows modified by other transactions until the other transaction is completed. [...] Row locks are released before the next row is processed. [...]
    • If READ_COMMITTED_SNAPSHOT is set to ON, the Database Engine uses row versioning to present each statement with a transactionally consistent snapshot of the data as it existed at the start of the statement. Locks are not used to protect the data from updates by other transactions.
  • REPETEABLE_READ: Shared locks are placed on all data read by each statement in the transaction and are held until the transaction completes.

  • SERIALIZABLE: Range locks are placed in the range of key values that match the search conditions of each statement executed in a transaction. [...] The range locks are held until the transaction completes.

java.lang.ClassNotFoundException:com.mysql.jdbc.Driver

if it is standalone program, download mysql connector jar and add it to your classpath.

if it is a maven project, add below dependency and run your program.

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.37</version>
</dependency>

Eclipse error ... cannot be resolved to a type

copying the jar files will resolve. If by any chance you are copying the code from any tutorials, make sure the class names are spelled in correct case...for example i copied a code from one of the tutorials which had solr in S cap. Eclipse was continiously throwing the error and i also did a bit of googling ...everything was ok and it took 30 mins for me to realise the cap small issue. Am sure this will help someone

How to add the JDBC mysql driver to an Eclipse project?

if you are getting this exception again and again then download my-sql connector and paste in tomcat/WEB-INF/lib folder...note that some times WEB-INF folder does not contains lib folder, at that time manually create lib folder and paste mysql connector in that folder..definitely this will work.if still you got problem then check that your jdk must match your system. i.e if your system is 64 bit then jdk must be 64 bit

oracle.jdbc.driver.OracleDriver ClassNotFoundException

You can add a JAR which having above specified class exist e.g.ojdbc jar which supported by installed java version, also make sure that you have added it into classpath.

SQL Server 2008 Connection Error "No process is on the other end of the pipe"

Came here looking for a solution to a similar issue, which I just introduced by changing Schannel settings of our IIS server using "IIS Crypto" by Nartac... By disabling the SHA-1 hash, the local SQL Server was not able to be reached anymore, even though I didn't use an encrypted connection (not useful for an ASP.Net site accessing a local SQL Express instance using shared memory).

The 'SHA' hash algorithm needs to be active for SQL Server to connect

Thanks Count Zero for pointing me in the right direction :-)

So, lesson learned: do not disable SHA-1 on your IIS server if you have a local SQL Server instance.

An Authentication object was not found in the SecurityContext - Spring 3.2.2

As pointed already by @Arun P Johny the root cause of the problem is that at the moment when AuthenticationSuccessEvent is processed SecurityContextHolder is not populated by Authentication object. So any declarative authorization checks (that must get user rights from SecurityContextHolder) will not work. I give you another idea how to solve this problem. There are two ways how you can run your custom code immidiately after successful authentication:

  1. Listen to AuthenticationSuccessEvent
  2. Provide your custom AuthenticationSuccessHandler implementation.

AuthenticationSuccessHandler has one important advantage over first way: SecurityContextHolder will be already populated. So just move your stateService.rowCount() call into loginsuccesshandler.LoginSuccessHandler#onAuthenticationSuccess(...) method and the problem will go away.

SQL state [99999]; error code [17004]; Invalid column type: 1111 With Spring SimpleJdbcCall

Probably, you need to insert schema identifier here:

in.addValue("po_system_users", null, OracleTypes.ARRAY, "your_schema.T_SYSTEM_USER_TAB");

com.microsoft.sqlserver.jdbc.SQLServerDriver not found error

intellij idea 2019

  1. Download Microsoft JDBC Driver for SQL Server

(https://docs.microsoft.com/en-us/sql/connect/jdbc/download-microsoft-jdbc-driver-for-sql-server?view=sql-server-2017)

  1. Unpack ("C:\opt\sqljdbc_7.2\enu\mssql-jdbc-7.2.2.jre11.jar")
  2. Add; (File->Project Structure->Global Libraries)
  3. Use; (Adding Jar files to IntellijIdea classpath (look video)) add import com.microsoft.sqlserver.jdbc.SQLServerDriver; enter image description here https://youtu.be/-2hjxoRKsyk

or ub Gradle set "compile" compile group: 'com.microsoft.sqlserver', name: 'mssql-jdbc', version: '7.2.2.jre11'

MySql with JAVA error. The last packet sent successfully to the server was 0 milliseconds ago

Search the file my.cnf and comment the line

skip-networking

to

#skip-networking

Restart mysql

Java java.sql.SQLException: Invalid column index on preparing statement

In date '?', the '?' is a literal string with value ?, not a parameter placeholder, so your query does not have any parameters. The date is a shorthand cast from (literal) string to date. You need to replace date '?' with ? to actually have a parameter.

Also if you know it is a date, then use setDate(..) and not setString(..) to set the parameter.

Autowiring fails: Not an managed Type

You get the same exception when you pass the incorrect Entity object to the CrudRepository in the repository class.

public interface XYZRepository extends CrudRepository<IncorrectEntityClass, Long>

java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver

I was getting same kinda error but after copying the ojdbc14.jar into lib folder, no more exception.(copy ojdbc14.jar from somewhere and paste it into lib folder inside WebContent.)

how to query for a list<String> in jdbctemplate

Use following code

List data = getJdbcTemplate().queryForList(query,String.class)

Hibernate Delete query

I'm not sure but:

  • If you call the delete method with a non transient object, this means first fetched the object from the DB. So it is normal to see a select statement. Perhaps in the end you see 2 select + 1 delete?

  • If you call the delete method with a transient object, then it is possible that you have a cascade="delete" or something similar which requires to retrieve first the object so that "nested actions" can be performed if it is required.


Edit: Calling delete() with a transient instance means doing something like that:

MyEntity entity = new MyEntity();
entity.setId(1234);
session.delete(entity);

This will delete the row with id 1234, even if the object is a simple pojo not retrieved by Hibernate, not present in its session cache, not managed at all by Hibernate.

If you have an entity association Hibernate probably have to fetch the full entity so that it knows if the delete should be cascaded to associated entities.

How to find difference between two Joda-Time DateTimes in minutes

This will get you the difference between two DateTime objects in milliseconds:

DateTime d1 = new DateTime();
DateTime d2 = new DateTime();

long diffInMillis = d2.getMillis() - d1.getMillis();

Unable to open debugger port in IntelliJ

Merely hitting the debug icon again fixed my problem in a few seconds.

Hibernate, @SequenceGenerator and allocationSize

allocationSize=1 It is a micro optimization before getting query Hibernate tries to assign value in the range of allocationSize and so try to avoid querying database for sequence. But this query will be executed every time if you set it to 1. This hardly makes any difference since if your data base is accessed by some other application then it will create issues if same id is used by another application meantime .

Next generation of Sequence Id is based on allocationSize.

By defualt it is kept as 50 which is too much. It will also only help if your going to have near about 50 records in one session which are not persisted and which will be persisted using this particular session and transation.

So you should always use allocationSize=1 while using SequenceGenerator. As for most of underlying databases sequence is always incremented by 1.

Passing parameters to a JDBC PreparedStatement

There is a problem in your query..

   statement =con.prepareStatement("SELECT * from employee WHERE  userID = "+"''"+userID);
   ResultSet rs = statement.executeQuery();

You are using Prepare Statement.. So you need to set your parameter using statement.setInt() or statement.setString() depending upon what is the type of your userId

Replace it with: -

   statement =con.prepareStatement("SELECT * from employee WHERE  userID = :userId");
   statement.setString(userId, userID);
   ResultSet rs = statement.executeQuery();

Or, you can use ? in place of named value - :userId..

   statement =con.prepareStatement("SELECT * from employee WHERE  userID = ?");
   statement.setString(1, userID);

IO Error: The Network Adapter could not establish the connection

I was having issues with this as well. I was using the jdbc connection string to connect to the database. The hostname was incorrectly configured in the string. I am using Mac, and the same string was being used on Windows machines without an issue. On my connection string, I had to make sure that I had the full url with the appending "organizationname.com" to the end of the hostname.

Hope this helps.

Returning a value even if no result

Do search with LEFT OUTER JOIN. I don't know if MySQL allows inline VALUES in join clauses but you can have predefined table for this purposes.

What does it mean when Statement.executeUpdate() returns -1?

For executeUpdate statements against a DB2 for z/OS server, the value that is returned depends on the type of SQL statement that is being executed:

For an SQL statement that can have an update count, such as an INSERT, UPDATE, or DELETE statement, the returned value is the number of affected rows. It can be:

A positive number, if a positive number of rows are affected by the operation, and the operation is not a mass delete on a segmented table space.

0, if no rows are affected by the operation.

-1, if the operation is a mass delete on a segmented table space.

For a DB2 CALL statement, a value of -1 is returned, because the DB2 database server cannot determine the number of affected rows. Calls to getUpdateCount or getMoreResults for a CALL statement also return -1. For any other SQL statement, a value of -1 is returned.

Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/JDBC_DBO]]

To resolve this issue, you have to delete the .snap file located in the directory:

<workspace-directory>\.metadata\.plugins\org.eclipse.core.resources.

After deleting this file, you could start Eclipse with no problem.

Connecting to MySQL from Android with JDBC

Do you want to keep your database on mobile? Use sqlite instead of mysql.

If the idea is to keep database on server and access from mobile. Use a webservice to fetch/ modify data.

java.sql.SQLException: - ORA-01000: maximum open cursors exceeded

ORA-01000, the maximum-open-cursors error, is an extremely common error in Oracle database development. In the context of Java, it happens when the application attempts to open more ResultSets than there are configured cursors on a database instance.

Common causes are:

  1. Configuration mistake

    • You have more threads in your application querying the database than cursors on the DB. One case is where you have a connection and thread pool larger than the number of cursors on the database.
    • You have many developers or applications connected to the same DB instance (which will probably include many schemas) and together you are using too many connections.
    • Solution:

  2. Cursor leak

    • The applications is not closing ResultSets (in JDBC) or cursors (in stored procedures on the database)
    • Solution: Cursor leaks are bugs; increasing the number of cursors on the DB simply delays the inevitable failure. Leaks can be found using static code analysis, JDBC or application-level logging, and database monitoring.

Background

This section describes some of the theory behind cursors and how JDBC should be used. If you don't need to know the background, you can skip this and go straight to 'Eliminating Leaks'.

What is a cursor?

A cursor is a resource on the database that holds the state of a query, specifically the position where a reader is in a ResultSet. Each SELECT statement has a cursor, and PL/SQL stored procedures can open and use as many cursors as they require. You can find out more about cursors on Orafaq.

A database instance typically serves several different schemas, many different users each with multiple sessions. To do this, it has a fixed number of cursors available for all schemas, users and sessions. When all cursors are open (in use) and request comes in that requires a new cursor, the request fails with an ORA-010000 error.

Finding and setting the number of cursors

The number is normally configured by the DBA on installation. The number of cursors currently in use, the maximum number and the configuration can be accessed in the Administrator functions in Oracle SQL Developer. From SQL it can be set with:

ALTER SYSTEM SET OPEN_CURSORS=1337 SID='*' SCOPE=BOTH;

Relating JDBC in the JVM to cursors on the DB

The JDBC objects below are tightly coupled to the following database concepts:

  • JDBC Connection is the client representation of a database session and provides database transactions. A connection can have only a single transaction open at any one time (but transactions can be nested)
  • A JDBC ResultSet is supported by a single cursor on the database. When close() is called on the ResultSet, the cursor is released.
  • A JDBC CallableStatement invokes a stored procedure on the database, often written in PL/SQL. The stored procedure can create zero or more cursors, and can return a cursor as a JDBC ResultSet.

JDBC is thread safe: It is quite OK to pass the various JDBC objects between threads.

For example, you can create the connection in one thread; another thread can use this connection to create a PreparedStatement and a third thread can process the result set. The single major restriction is that you cannot have more than one ResultSet open on a single PreparedStatement at any time. See Does Oracle DB support multiple (parallel) operations per connection?

Note that a database commit occurs on a Connection, and so all DML (INSERT, UPDATE and DELETE's) on that connection will commit together. Therefore, if you want to support multiple transactions at the same time, you must have at least one Connection for each concurrent Transaction.

Closing JDBC objects

A typical example of executing a ResultSet is:

Statement stmt = conn.createStatement();
try {
    ResultSet rs = stmt.executeQuery( "SELECT FULL_NAME FROM EMP" );
    try {
        while ( rs.next() ) {
            System.out.println( "Name: " + rs.getString("FULL_NAME") );
        }
    } finally {
        try { rs.close(); } catch (Exception ignore) { }
    }
} finally {
    try { stmt.close(); } catch (Exception ignore) { }
}

Note how the finally clause ignores any exception raised by the close():

  • If you simply close the ResultSet without the try {} catch {}, it might fail and prevent the Statement being closed
  • We want to allow any exception raised in the body of the try to propagate to the caller. If you have a loop over, for example, creating and executing Statements, remember to close each Statement within the loop.

In Java 7, Oracle has introduced the AutoCloseable interface which replaces most of the Java 6 boilerplate with some nice syntactic sugar.

Holding JDBC objects

JDBC objects can be safely held in local variables, object instance and class members. It is generally better practice to:

  • Use object instance or class members to hold JDBC objects that are reused multiple times over a longer period, such as Connections and PreparedStatements
  • Use local variables for ResultSets since these are obtained, looped over and then closed typically within the scope of a single function.

There is, however, one exception: If you are using EJBs, or a Servlet/JSP container, you have to follow a strict threading model:

  • Only the Application Server creates threads (with which it handles incoming requests)
  • Only the Application Server creates connections (which you obtain from the connection pool)
  • When saving values (state) between calls, you have to be very careful. Never store values in your own caches or static members - this is not safe across clusters and other weird conditions, and the Application Server may do terrible things to your data. Instead use stateful beans or a database.
  • In particular, never hold JDBC objects (Connections, ResultSets, PreparedStatements, etc) over different remote invocations - let the Application Server manage this. The Application Server not only provides a connection pool, it also caches your PreparedStatements.

Eliminating leaks

There are a number of processes and tools available for helping detect and eliminating JDBC leaks:

  1. During development - catching bugs early is by far the best approach:

    1. Development practices: Good development practices should reduce the number of bugs in your software before it leaves the developer's desk. Specific practices include:

      1. Pair programming, to educate those without sufficient experience
      2. Code reviews because many eyes are better than one
      3. Unit testing which means you can exercise any and all of your code base from a test tool which makes reproducing leaks trivial
      4. Use existing libraries for connection pooling rather than building your own
    2. Static Code Analysis: Use a tool like the excellent Findbugs to perform a static code analysis. This picks up many places where the close() has not been correctly handled. Findbugs has a plugin for Eclipse, but it also runs standalone for one-offs, has integrations into Jenkins CI and other build tools

  2. At runtime:

    1. Holdability and commit

      1. If the ResultSet holdability is ResultSet.CLOSE_CURSORS_OVER_COMMIT, then the ResultSet is closed when the Connection.commit() method is called. This can be set using Connection.setHoldability() or by using the overloaded Connection.createStatement() method.
    2. Logging at runtime.

      1. Put good log statements in your code. These should be clear and understandable so the customer, support staff and teammates can understand without training. They should be terse and include printing the state/internal values of key variables and attributes so that you can trace processing logic. Good logging is fundamental to debugging applications, especially those that have been deployed.
      2. You can add a debugging JDBC driver to your project (for debugging - don't actually deploy it). One example (I have not used it) is log4jdbc. You then need to do some simple analysis on this file to see which executes don't have a corresponding close. Counting the open and closes should highlight if there is a potential problem

        1. Monitoring the database. Monitor your running application using the tools such as the SQL Developer 'Monitor SQL' function or Quest's TOAD. Monitoring is described in this article. During monitoring, you query the open cursors (eg from table v$sesstat) and review their SQL. If the number of cursors is increasing, and (most importantly) becoming dominated by one identical SQL statement, you know you have a leak with that SQL. Search your code and review.

Other thoughts

Can you use WeakReferences to handle closing connections?

Weak and soft references are ways of allowing you to reference an object in a way that allows the JVM to garbage collect the referent at any time it deems fit (assuming there are no strong reference chains to that object).

If you pass a ReferenceQueue in the constructor to the soft or weak Reference, the object is placed in the ReferenceQueue when the object is GC'ed when it occurs (if it occurs at all). With this approach, you can interact with the object's finalization and you could close or finalize the object at that moment.

Phantom references are a bit weirder; their purpose is only to control finalization, but you can never get a reference to the original object, so it's going to be hard to call the close() method on it.

However, it is rarely a good idea to attempt to control when the GC is run (Weak, Soft and PhantomReferences let you know after the fact that the object is enqueued for GC). In fact, if the amount of memory in the JVM is large (eg -Xmx2000m) you might never GC the object, and you will still experience the ORA-01000. If the JVM memory is small relative to your program's requirements, you may find that the ResultSet and PreparedStatement objects are GCed immediately after creation (before you can read from them), which will likely fail your program.

TL;DR: The weak reference mechanism is not a good way to manage and close Statement and ResultSet objects.

SQLException: No suitable Driver Found for jdbc:oracle:thin:@//localhost:1521/orcl

For me I did enter a invalid url like : orcl only instead of jdbc:oracle:thin:@//localhost:1521/orcl

Java - Getting Data from MySQL database

This should work, I think...

ResultSet results = st.executeQuery(sql);

if(results.next()) { //there is a row
 int id = results.getInt(1); //ID if its 1st column
 String str1 = results.getString(2);
 ...
}

Could not autowire field in spring. why?

In java config,make sure you have import your config in RootConfig like this @Import(PersistenceJPAConfig.class)

rails generate model

The error shows you either didn't create the rails project yet or you're not in the rails project directory.

Suppose if you're working on myapp project. You've to move to that project directory on your command line and then generate the model. Here are some steps you can refer.

Example: Assuming you didn't create the Rails app yet:

$> rails new myapp
$> cd myapp

Now generate the model from your commandline.

$> rails generate model your_model_name 

java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)

I encountered this error. The problem was that I had the wrong database name.

JPA or JDBC, how are they different?

JDBC is a much lower-level (and older) specification than JPA. In it's bare essentials, JDBC is an API for interacting with a database using pure SQL - sending queries and retrieving results. It has no notion of objects or hierarchies. When using JDBC, it's up to you to translate a result set (essentially a row/column matrix of values from one or more database tables, returned by your SQL query) into Java objects.

Now, to understand and use JDBC it's essential that you have some understanding and working knowledge of SQL. With that also comes a required insight into what a relational database is, how you work with it and concepts such as tables, columns, keys and relationships. Unless you have at least a basic understanding of databases, SQL and data modelling you will not be able to make much use of JDBC since it's really only a thin abstraction on top of these things.

java.sql.SQLException: Missing IN or OUT parameter at index:: 1

In your INSERT statements:

INSERT INTO employee(hans,germany) values(?,?)

You've got your values where your field names belong. Change it to be:

INSERT INTO employee(emp_name,emp_address) values(?,?)

If you were to run that statement from a SQL prompt, it would look like this:

INSERT INTO employee(emp_name,emp_address) values('hans','germany');

Note that you'd need to put single quotes around the string/varchar values.

Additionally, you are also not adding any parameters to your prepared statement. That is what's actually causing the error you're seeing. Try this:

PreparedStatement ps = con.prepareStatement(inserting); 
ps.setString(1, "hans");
ps.setString(2, "germany");
ps.execute();

Also (according to Oracle), you can use "execute" for any SQL statement. Using "executeUpdate" would also be valid in this situation, which would return an integer to indicate the number of rows affected.

How to convert TimeStamp to Date in Java?

I feel obliged to respond since other answers seem to be time zone agnostic which a real world application cannot afford to be. To make timestamp-to-date conversion correct when the timestamp and the JVM are using different time zones you can use Joda Time's LocalDateTime (or LocalDateTime in Java8) like this:

Timestamp timestamp = resultSet.getTimestamp("time_column");
LocalDateTime localDateTime = new LocalDateTime(timestamp);
Date trueDate = localDateTime.toDate(DateTimeZone.UTC.toTimeZone());

The example below assumes that the timestamp is UTC (as is usually the case with databases). In case your timestamps are in different timezone, change the timezone parameter of the toDatestatement.

no sqljdbc_auth in java.library.path

To resolve I did the following:

  1. Copied sqljdbc_auth.dll into dir: C:\Windows\System32
  2. Restarted my application

deleted object would be re-saved by cascade (remove deleted object from associations)

I was able to resolve this by writing the code below. I used executeUpdate instead of .delete()

def publicSupport = caseObj?.client?.publicSupport
        if(publicSupport)
            PublicSupport.executeUpdate("delete PublicSupport c where c.id = :publicSupportId", [publicSupportId:publicSupport.id])
            //publicSupport.delete()

Cannot create JDBC driver of class ' ' for connect URL 'null' : I do not understand this exception

I was getting this problem because I put context.xml into the wrong path:

./src/main/resources/META-INF/context.xml

The correct path was:

./src/main/webapp/META-INF/context.xml

"Incorrect string value" when trying to insert UTF-8 into MySQL via JDBC?

However, it is important to note that the mysql connector driver version must be older than 5.1.47 and later.

Multiple queries executed in java in single statement

Hint: If you have more than one connection property then separate them with:

&amp;

To give you somthing like:

url="jdbc:mysql://localhost/glyndwr?autoReconnect=true&amp;allowMultiQueries=true"

I hope this helps some one.

Regards,

Glyn

Most simple code to populate JTable from ResultSet

I think this is the Easiest way to populate/model a table with ResultSet.. Download and include rs2xml.jar Get rs2xml.jar in your libraries..

import net.proteanit.sql.DbUtils;

    try
    {
    CreateConnection();
    PreparedStatement st =conn.prepareStatement("Select * from ABC;");
    ResultSet rs = st.executeQuery();
    tblToBeFilled.setModel(DbUtils.resultSetToTableModel(rs));
    conn.close();
    }
    catch(Exception ex)
    {
    JOptionPane.showMessageDialog(null, ex.toString());
    }

Jdbctemplate query for string: EmptyResultDataAccessException: Incorrect result size: expected 1, actual 0

You may also use a ResultSetExtractor instead of a RowMapper. Both are just as easy as one another, the only difference is you call ResultSet.next().

public String test() {
    String sql = "select ID_NMB_SRZ from codb_owner.TR_LTM_SLS_RTN "
                 + " where id_str_rt = '999' and ID_NMB_SRZ = '60230009999999'";
    return jdbc.query(sql, new ResultSetExtractor<String>() {
        @Override
        public String extractData(ResultSet rs) throws SQLException,
                                                       DataAccessException {
            return rs.next() ? rs.getString("ID_NMB_SRZ") : null;
        }
    });
}

The ResultSetExtractor has the added benefit that you can handle all cases where there are more than one row or no rows returned.

UPDATE: Several years on and I have a few tricks to share. JdbcTemplate works superbly with java 8 lambdas which the following examples are designed for but you can quite easily use a static class to achieve the same.

While the question is about simple types, these examples serve as a guide for the common case of extracting domain objects.

First off. Let's suppose that you have an account object with two properties for simplicity Account(Long id, String name). You would likely wish to have a RowMapper for this domain object.

private static final RowMapper<Account> MAPPER_ACCOUNT =
        (rs, i) -> new Account(rs.getLong("ID"),
                               rs.getString("NAME"));

You may now use this mapper directly within a method to map Account domain objects from a query (jt is a JdbcTemplate instance).

public List<Account> getAccounts() {
    return jt.query(SELECT_ACCOUNT, MAPPER_ACCOUNT);
}

Great, but now we want our original problem and we use my original solution reusing the RowMapper to perform the mapping for us.

public Account getAccount(long id) {
    return jt.query(
            SELECT_ACCOUNT,
            rs -> rs.next() ? MAPPER_ACCOUNT.mapRow(rs, 1) : null,
            id);
}

Great, but this is a pattern you may and will wish to repeat. So you can create a generic factory method to create a new ResultSetExtractor for the task.

public static <T> ResultSetExtractor singletonExtractor(
        RowMapper<? extends T> mapper) {
    return rs -> rs.next() ? mapper.mapRow(rs, 1) : null;
}

Creating a ResultSetExtractor now becomes trivial.

private static final ResultSetExtractor<Account> EXTRACTOR_ACCOUNT =
        singletonExtractor(MAPPER_ACCOUNT);

public Account getAccount(long id) {
    return jt.query(SELECT_ACCOUNT, EXTRACTOR_ACCOUNT, id);
}

I hope this helps to show that you can now quite easily combine parts in a powerful way to make your domain simpler.

UPDATE 2: Combine with an Optional for optional values instead of null.

public static <T> ResultSetExtractor<Optional<T>> singletonOptionalExtractor(
        RowMapper<? extends T> mapper) {
    return rs -> rs.next() ? Optional.of(mapper.mapRow(rs, 1)) : Optional.empty();
}

Which now when used could have the following:

private static final ResultSetExtractor<Optional<Double>> EXTRACTOR_DISCOUNT =
        singletonOptionalExtractor(MAPPER_DISCOUNT);

public double getDiscount(long accountId) {
    return jt.query(SELECT_DISCOUNT, EXTRACTOR_DISCOUNT, accountId)
            .orElse(0.0);
}

Autowiring two beans implementing same interface - how to set default bean to autowire?

What about @Primary?

Indicates that a bean should be given preference when multiple candidates are qualified to autowire a single-valued dependency. If exactly one 'primary' bean exists among the candidates, it will be the autowired value. This annotation is semantically equivalent to the <bean> element's primary attribute in Spring XML.

@Primary
public class HibernateDeviceDao implements DeviceDao

Or if you want your Jdbc version to be used by default:

<bean id="jdbcDeviceDao" primary="true" class="com.initech.service.dao.jdbc.JdbcDeviceDao">

@Primary is also great for integration testing when you can easily replace production bean with stubbed version by annotating it.

How to convert image into byte array and byte array to base64 String in android?

I wrote the following code to convert an image from sdcard to a Base64 encoded string to send as a JSON object.And it works great:

String filepath = "/sdcard/temp.png";
File imagefile = new File(filepath);
FileInputStream fis = null;
try {
    fis = new FileInputStream(imagefile);
    } catch (FileNotFoundException e) {
    e.printStackTrace();
}

Bitmap bm = BitmapFactory.decodeStream(fis);
ByteArrayOutputStream baos = new ByteArrayOutputStream();  
bm.compress(Bitmap.CompressFormat.JPEG, 100 , baos);    
byte[] b = baos.toByteArray(); 
encImage = Base64.encodeToString(b, Base64.DEFAULT);

PSQLException: current transaction is aborted, commands ignored until end of transaction block

I had the same issue but then realised there is a table with the same name in the database. After deleting that I was able to import the file.

org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'customerService' is defined

Please make sure that your applicationContext.xml file is loaded by specifying it in your web.xml file:

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param>

Tomcat 7 "SEVERE: A child container failed during start"

This same issue occurred for me and stack trace

SEVERE: A child container failed during start
java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Tomcat].StandardHost[localhost].StandardContext[/XXXXSearch]]
    at java.util.concurrent.FutureTask.report(FutureTask.java:122)
    at java.util.concurrent.FutureTask.get(FutureTask.java:192)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1123)
    at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:800)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Tomcat].StandardHost[localhost].StandardContext[/XXXXSearch]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
    ... 6 more
Caused by: java.lang.IllegalStateException: Unable to complete the scan for annotations for web application [/XXXXSearch]. Possible root causes include a too low setting for -Xss and illegal cyclic inheritance dependencies
    at org.apache.catalina.startup.ContextConfig.processAnnotationsStream(ContextConfig.java:2109)
    at org.apache.catalina.startup.ContextConfig.processAnnotationsJar(ContextConfig.java:1981)
    at org.apache.catalina.startup.ContextConfig.processAnnotationsUrl(ContextConfig.java:1947)
    at org.apache.catalina.startup.ContextConfig.processAnnotations(ContextConfig.java:1932)
    at org.apache.catalina.startup.ContextConfig.webConfig(ContextConfig.java:1326)
    at org.apache.catalina.startup.ContextConfig.configureStart(ContextConfig.java:878)
    at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:369)
    at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:119)
    at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5179)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 6 more
Caused by: java.lang.StackOverflowError
    at org.apache.catalina.startup.ContextConfig.populateSCIsForCacheEntry(ContextConfig.java:2269)
    at org.apache.catalina.startup.ContextConfig.populateSCIsForCacheEntry(ContextConfig.java:2269)
    at org.apache.catalina.startup.ContextConfig.populateSCIsForCacheEntry(ContextConfig.java:2269)
    at org.apache.catalina.startup.ContextConfig.populateSCIsForCacheEntry(ContextConfig.java:2269)
    at org.apache.catalina.startup.ContextConfig.populateSCIsForCacheEntry(ContextConfig.java:2269)
    at org.apache.catalina.startup.ContextConfig.populateSCIsForCacheEntry(ContextConfig.java:2269)
    at org.apache.catalina.startup.ContextConfig.populateSCIsForCacheEntry(ContextConfig.java:2269
    at org.apache.catalina.startup.ContextConfig.populateSCIsForCacheEntry(ContextConfig.java:2269)
    at org.apache.catalina.startup.ContextConfig.populateSCIsForCacheEntry(ContextConfig.java:2269)
    at org.apache.catalina.startup.ContextConfig.populateSCIsForCacheEntry(ContextConfig.java:2269)
    at org.apache.catalina.startup.ContextConfig.populateSCIsForCacheEntry(ContextConfig.java:2269)
    at org.apache.catalina.startup.ContextConfig.populateSCIsForCacheEntry(ContextConfig.java:2269)

In my analysis what i found was, this issue is occurred when illegal cyclic inheritance dependencies caused for Tomcat startup annotation processing.

But my project had lot of dependency JARs, and couldn't found which one is responsible for this.

After trying so many unhappy approaches What i did was , I have updated my tomcat plugin to following and ran the same scenario,

<plugin>
    <groupId>org.apache.tomcat.maven</groupId>
    <artifactId>tomcat8-maven-plugin</artifactId>
    <version>3.0-r1756463</version>
<\plugin>

Then i was able to find which JAR is caused to this issue ,

Aug 23, 2017 2:32:12 PM org.apache.catalina.startup.ContextConfig processAnnotationsJar
SEVERE: Unable to process Jar entry [cryptix/test/TestLOKI91.class] from Jar [jar:file:/C:/Users/Tharinda/.m2/repository/cryptix/cryptix/1.2.2/cryptix-1.2.2.jar!/] for annotations
java.io.EOFException
    at org.apache.tomcat.util.bcel.classfile.FastDataInputStream.readUnsignedShort(FastDataInputStream.java:120)
    at org.apache.tomcat.util.bcel.classfile.ClassParser.readAttributes(ClassParser.java:110)
    at org.apache.tomcat.util.bcel.classfile.ClassParser.parse(ClassParser.java:94)
    at org.apache.catalina.startup.ContextConfig.processAnnotationsStream(ContextConfig.java:1994)
    at org.apache.catalina.startup.ContextConfig.processAnnotationsJar(ContextConfig.java:1944)
    at org.apache.catalina.startup.ContextConfig.processAnnotationsUrl(ContextConfig.java:1919)
    at org.apache.catalina.startup.ContextConfig.processAnnotations(ContextConfig.java:1880)
    at org.apache.catalina.startup.ContextConfig.webConfig(ContextConfig.java:1149)
    at org.apache.catalina.startup.ContextConfig.configureStart(ContextConfig.java:771)
    at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:305)
    at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:117)
    at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5120)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1408)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1398)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

Then just solving the issue with cryptix-1.2.2.jar solved this problem.

I strongly recommend to move tomcat8-maven-plugin which seems stable and less buggy at the moment.

Error creating bean with name

It looks like your Spring component scan Base is missing UserServiceImpl

<context:component-scan base-package="org.assessme.com.controller." />

How to get Map data using JDBCTemplate.queryForMap

I know this is really old, but this is the simplest way to query for Map.

Simply implement the ResultSetExtractor interface to define what type you want to return. Below is an example of how to use this. You'll be mapping it manually, but for a simple map, it should be straightforward.

jdbcTemplate.query("select string1,string2 from table where x=1", new ResultSetExtractor<Map>(){
    @Override
    public Map extractData(ResultSet rs) throws SQLException,DataAccessException {
        HashMap<String,String> mapRet= new HashMap<String,String>();
        while(rs.next()){
            mapRet.put(rs.getString("string1"),rs.getString("string2"));
        }
        return mapRet;
    }
});

This will give you a return type of Map that has multiple rows (however many your query returned) and not a list of Maps. You can view the ResultSetExtractor docs here: http://docs.spring.io/spring-framework/docs/2.5.6/api/org/springframework/jdbc/core/ResultSetExtractor.html

Hibernate error - QuerySyntaxException: users is not mapped [from users]

In your Query you have to use class name(User) not table name(users) so your query is "from User"

Oracle JDBC ojdbc6 Jar as a Maven Dependency

I followed below command it worked:

mvn install:install-file -Dfile=E:\JAVA\Spring\ojdbc14-10.2.0.4.0.jar\ojdbc14-10.2.0.4.0.jar -DgroupId=com.oracle -DartifactId=ojdbc14 -Dversion=10.2.0.4.0 -Dpackaging=jar

After installation check that jar is installed correctly on your M2_repo.

How to display hidden characters by default (ZERO WIDTH SPACE ie. &#8203)

Not sure what you meant, but you can permanently turn showing whitespaces on and off in Settings -> Editor -> General -> Appearance -> Show whitespaces.

Also, you can set it for a current file only in View -> Active Editor -> Show WhiteSpaces.

Edit:

Had some free time since it looks like a popular issue, I had written a plugin to inspect the code for such abnormalities. It is called Zero Width Characters locator and you're welcome to give it a try.

DROP IF EXISTS VS DROP?

If no table with such name exists, DROP fails with error while DROP IF EXISTS just does nothing.

This is useful if you create/modifi your database with a script; this way you do not have to ensure manually that previous versions of the table are deleted. You just do a DROP IF EXISTS and forget about it.

Of course, your current DB engine may not support this option, it is hard to tell more about the error with the information you provide.

Spring JDBC Template for calling Stored Procedures

There are a number of ways to call stored procedures in Spring.

If you use CallableStatementCreator to declare parameters, you will be using Java's standard interface of CallableStatement, i.e register out parameters and set them separately. Using SqlParameter abstraction will make your code cleaner.

I recommend you looking at SimpleJdbcCall. It may be used like this:

SimpleJdbcCall jdbcCall = new SimpleJdbcCall(jdbcTemplate)
    .withSchemaName(schema)
    .withCatalogName(package)
    .withProcedureName(procedure)();
...
jdbcCall.addDeclaredParameter(new SqlParameter(paramName, OracleTypes.NUMBER));
...
jdbcCall.execute(callParams);

For simple procedures you may use jdbcTemplate's update method:

jdbcTemplate.update("call SOME_PROC (?, ?)", param1, param2);

Cannot create PoolableConnectionFactory (Io exception: The Network Adapter could not establish the connection)

Most of the cases issue is due to problem with hostname . Please check the hostname ,some times database team will maintain many hostname for connecting same database . Please check with database team regarding this connection issue.

org.hibernate.exception.SQLGrammarException: could not insert [com.sample.Person]

The problem in my case was that the database name was incorrect.
I solved the problem by referring the correct database name in the field as below

<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/myDatabase</property>

No matching bean of type ... found for dependency

IF this is only occurring on deployments, be sure that you have the dependency of the package you are referencing in the .war. For instance, this was working locally on my machine, with debug configurations working fine, but after deploying to Amazon's Elastic Beanstalk , I received this error and noticed one of the dependencies was not bundled in the .war package.

The specified DSN contains an architecture mismatch between the Driver and Application. JAVA

If you are using netbeans go to tools-> java Platform, change jdk_home which points to c:/programfiles/java/jdk1_7 to c:programFiles(x86)/java/jdk1_6_21

if not editable find netbeans.cnf and make change as stated abouve for jdk_home. restart neatbeans and how it works I had the same problem , but i worked .

Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect)

I had the same problem in my grails project. The Bug was, that i overwrite the getter method of a collection field. This returned always a new version of the collection in other thread.

class Entity {
    List collection

    List getCollection() {
        return collection.unique()
    }
}

The solution was to rename the getter method:

class Entity {
    List collection

    List getUniqueCollection() {
        return collection.unique()
    }
}

Enable Hibernate logging

We have a tomcat-8.5 + restlet-2.3.4 + hibernate-4.2.0 + log4j-1.2.14 java 8 app running on AlpineLinux in docker.

On adding these 2 lines to /usr/local/tomcat/webapps/ROOT/WEB-INF/classes/log4j.properties, I started seeing the HQL queries in the logs:

### log just the SQL
log4j.logger.org.hibernate.SQL=debug

### log JDBC bind parameters ###
log4j.logger.org.hibernate.type=debug

However, the JDBC bind parameters are not being logged.

JPA mapping: "QuerySyntaxException: foobar is not mapped..."

I got the same error while using other one entity, He was annotating the class wrongly by using the table name inside the @Entity annotation without using the @Table annotation

The correct format should be

@Entity //default name similar to class name 'FooBar' OR @Entity( name = "foobar" ) for differnt entity name
@Table( name = "foobar" ) // Table name 
public class FooBar{

H2 database error: Database may be already in use: "Locked by another process"

I had the same problem. in Intellj, when i want to use h2 database when my program was running i got the same error. For solve this problem i changed the connection url from

spring.datasource.url=jdbc:h2:file:~/ipinbarbot

to:

spring.datasource.url=jdbc:h2:~/ipinbarbot;DB_CLOSE_ON_EXIT=FALSE;AUTO_SERVER=TRUE

And then my problem gone away. now i can connect to "ipinbarbot" database when my program is. If you use Hibernate, also don't forget to have:

spring.jpa.hibernate.ddl-auto = update

goodluck

No suitable driver found for 'jdbc:mysql://localhost:3306/mysql

( If your url is correct and still get that error messege ) Do following steps to setup the Classpath in netbeans,

  1. Create a new folder in your project workspace and add the downloaded .jar file(eg:- mysql-connector-java-5.1.35-bin.jar )
  2. Right click your project > properties > Libraries > ADD jar/Folder Select the jar file in that folder you just make. And click OK.

Now you will see that .jar file will be included under the libraries. Now you will not need to use the line, Class.forName("com.mysql.jdbc.Driver"); also.

If above method did not work, check the mysql-connector version (eg:- 5.1.35) and try a newer or a suitable version for you.

how to change listen port from default 7001 to something different?

The following lines are used to control the listen-port of a server, both are necessary:

    <listen-port>7002</listen-port>
    <listen-port-enabled>true</listen-port-enabled>

How should I use try-with-resources with JDBC?

I realize this was long ago answered but want to suggest an additional approach that avoids the nested try-with-resources double block.

public List<User> getUser(int userId) {
    try (Connection con = DriverManager.getConnection(myConnectionURL);
         PreparedStatement ps = createPreparedStatement(con, userId); 
         ResultSet rs = ps.executeQuery()) {

         // process the resultset here, all resources will be cleaned up

    } catch (SQLException e) {
        e.printStackTrace();
    }
}

private PreparedStatement createPreparedStatement(Connection con, int userId) throws SQLException {
    String sql = "SELECT id, username FROM users WHERE id = ?";
    PreparedStatement ps = con.prepareStatement(sql);
    ps.setInt(1, userId);
    return ps;
}

What is the actual use of Class.forName("oracle.jdbc.driver.OracleDriver") while connecting to a database?

From the Java JDBC tutorial:

In previous versions of JDBC, to obtain a connection, you first had to initialize your JDBC driver by calling the method Class.forName. Any JDBC 4.0 drivers that are found in your class path are automatically loaded. (However, you must manually load any drivers prior to JDBC 4.0 with the method Class.forName.)

So, if you're using the Oracle 11g (11.1) driver with Java 1.6, you don't need to call Class.forName. Otherwise, you need to call it to initialise the driver.

Completely uninstall PostgreSQL 9.0.4 from Mac OSX Lion?

This blog post explains very well:

(just replace 9.X by your version. e.g: 9.6)

A. If installed PostgreSQL with homebrew, enter brew uninstall postgresql

B. If you used the EnterpriseDB installer, follow the following step.

Run the uninstaller on terminal window: sudo /Library/PostgreSQL/9.X/uninstall-postgresql.app/Contents/MacOS/installbuilder.sh

C. If installed with Postgres Installer, do:

open /Library/PostgreSQL/9.X/uninstall-postgresql.app

Remove the PostgreSQL and data folders. The Wizard will notify you that these were not removed.

sudo rm -rf /Library/PostgreSQL

Remove the ini file:

sudo rm /etc/postgres-reg.ini

Remove the PostgreSQL user using System Preferences -> Users & Groups.

Unlock the settings panel by clicking on the padlock and entering your password. Select the PostgreSQL user and click on the minus button. Restore your shared memory settings: sudo rm /etc/sysctl.conf

How to get row count using ResultSet in Java?

If you have access to the prepared statement that results in this resultset, you can use

connection.prepareStatement(sql, 
  ResultSet.TYPE_SCROLL_INSENSITIVE, 
  ResultSet.CONCUR_READ_ONLY);

This prepares your statement in a way that you can rewind the cursor. This is also documented in the ResultSet Javadoc

In general, however, forwarding and rewinding cursors may be quite inefficient for large result sets. Another option in SQL Server would be to calculate the total number of rows directly in your SQL statement:

SELECT my_table.*, count(*) over () total_rows
FROM my_table
WHERE ...

No more data to read from socket error

This is a very low-level exception, which is ORA-17410.

It may happen for several reasons:

  1. A temporary problem with networking.

  2. Wrong JDBC driver version.

  3. Some issues with a special data structure (on database side).

  4. Database bug.

In my case, it was a bug we hit on the database, which needs to be patched.

The Network Adapter could not establish the connection when connecting with Oracle DB

When a client connects to an Oracle server, it first connnects to the Oracle listener service. It often redirects the client to another port. So the client has to open another connection on a different port, which is blocked by the firewall.

So you might in fact have encountered a firewall problem due to Oracle port redirection. It should be possible to diagnose it with a network monitor on the client machine or with the firewall management software on the firewall.

Java JDBC connection status

If you are using MySQL

public static boolean isDbConnected() {
    final String CHECK_SQL_QUERY = "SELECT 1";
    boolean isConnected = false;
    try {
        final PreparedStatement statement = db.prepareStatement(CHECK_SQL_QUERY);
        isConnected = true;
    } catch (SQLException | NullPointerException e) {
        // handle SQL error here!
    }
    return isConnected;
}

I have not tested with other databases. Hope this is helpful.

Where do I download JDBC drivers for DB2 that are compatible with JDK 1.5?

you can download and install db2client and looking for - db2jcc.jar - db2jcc_license_cisuz.jar - db2jcc_license_cu.jar - and etc. at C:\Program Files (x86)\IBM\SQLLIB\java

Oracle SQL Developer and PostgreSQL

If there is no database with the same name as the username, then clicking "Choose Database" will fail with an error like "Status : Failure -FATAL: database "your_username" does not exist"

To work around this, put 5432/database_name? in the Port field, where 5432 is the port of your Postgres instance and database_name is the name of at an existing database that your_username has access to. Then click "Choose Database" again and it should work. Now you can choose the database you want and remove the extra /database_name? from the Port field.

com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: No operations allowed after connection closed

Please make sure you are using latest jdbc connector as per the mysql. I was facing this problem and when I replaced my old jdbc connector with the latest one, the problem was solved.

You can download latest jdbc driver from https://dev.mysql.com/downloads/connector/j/

Select Operating System as Platform Independent. It will show you two options. One as tar and one as zip. Download the zip and extract it to get the jar file and replace it with your old connector.

This is not only for hibernate framework, it can be used with any platform which requires a jdbc connector.

spring PropertyPlaceholderConfigurer and context:property-placeholder

First, you don't need to define both of those locations. Just use classpath:config/properties/database.properties. In a WAR, WEB-INF/classes is a classpath entry, so it will work just fine.

After that, I think what you mean is you want to use Spring's schema-based configuration to create a configurer. That would go like this:

<context:property-placeholder location="classpath:config/properties/database.properties"/>

Note that you don't need to "ignoreResourceNotFound" anymore. If you need to define the properties separately using util:properties:

<context:property-placeholder properties-ref="jdbcProperties" ignore-resource-not-found="true"/>

There's usually not any reason to define them separately, though.

How to start rails server?

You have to cd to your master directory and then rails s command will work without problems.

But do not forget bundle-install command when you didn't do it before.

How do I connect to a Websphere Datasource with a given JNDI name?

Jason,

This is how it works.

Localnamespace - java:comp/env is a local name space used by the application. The name that you use in it jdbc/db is just an alias. It does not refer to a physical resource.

During deployment this alias should be mapped to a physical resource (in your case a data source) that is defined on the WAS/WPS run time.

This is actually stored in ejb-bnd.xmi files. In the latest versions the XMIs are replaced with XML files. These files are referred to as the Binding files.

HTH Manglu

org.springframework.beans.factory.BeanCreationException: Error creating bean with name

According to the stack trace, your issue is that your app cannot find org.apache.commons.dbcp.BasicDataSource, as per this line:

java.lang.ClassNotFoundException: org.apache.commons.dbcp.BasicDataSource

I see that you have commons-dbcp in your list of jars, but for whatever reason, your app is not finding the BasicDataSource class in it.

inject bean reference into a Quartz job in Spring?

This is a quite an old post which is still useful. All the solutions that proposes these two had little condition that not suite all:

  • SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this); This assumes or requires it to be a spring - web based project
  • AutowiringSpringBeanJobFactory based approach mentioned in previous answer is very helpful, but the answer is specific to those who don't use pure vanilla quartz api but rather Spring's wrapper for the quartz to do the same.

If you want to remain with pure Quartz implementation for scheduling(Quartz with Autowiring capabilities with Spring), I was able to do it as follows:

I was looking to do it quartz way as much as possible and thus little hack proves helpful.

 public final class AutowiringSpringBeanJobFactory extends SpringBeanJobFactory{

    private AutowireCapableBeanFactory beanFactory;

    public AutowiringSpringBeanJobFactory(final ApplicationContext applicationContext){
        beanFactory = applicationContext.getAutowireCapableBeanFactory();
    }

    @Override
    protected Object createJobInstance(final TriggerFiredBundle bundle) throws Exception {
        final Object job = super.createJobInstance(bundle);
        beanFactory.autowireBean(job);
        beanFactory.initializeBean(job, job.getClass().getName());
        return job;
    }
}


@Configuration
public class SchedulerConfig {   
    @Autowired private ApplicationContext applicationContext;

    @Bean
    public AutowiringSpringBeanJobFactory getAutowiringSpringBeanJobFactory(){
        return new AutowiringSpringBeanJobFactory(applicationContext);
    }
}


private void initializeAndStartScheduler(final Properties quartzProperties)
            throws SchedulerException {
        //schedulerFactory.initialize(quartzProperties);
        Scheduler quartzScheduler = schedulerFactory.getScheduler();

        //Below one is the key here. Use the spring autowire capable job factory and inject here
        quartzScheduler.setJobFactory(autowiringSpringBeanJobFactory);
        quartzScheduler.start();
    }

quartzScheduler.setJobFactory(autowiringSpringBeanJobFactory); gives us an autowired job instance. Since AutowiringSpringBeanJobFactory implicitly implements a JobFactory, we now enabled an auto-wireable solution. Hope this helps!

Return Type for jdbcTemplate.queryForList(sql, object, classType)

A complete solution for JdbcTemplate, NamedParameterJdbcTemplate with or without RowMapper Example.

// Create a Employee table

create table employee(  
id number(10),  
name varchar2(100),  
salary number(10)  
);

======================================================================= //Employee.java

public class Employee {
private int id;  
private String name;  
private float salary;  

//no-arg and parameterized constructors  

public Employee(){};

public Employee(int  id, String name, float salary){
    this.id=id;
    this.name=name;
    this.salary=salary;
}

//getters and setters  
public int getId() {
    return id;
}
public void setId(int id) {
    this.id = id;
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public float getSalary() {
    return salary;
}
public void setSalary(float salary) {
    this.salary = salary;
}
public String toString(){  
   return id+" "+name+" "+salary;  
}   

}

========================================================================= //EmployeeDao.java

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;

public class EmployeeDao {  
  private JdbcTemplate jdbcTemplate;  
  private NamedParameterJdbcTemplate nameTemplate;  

  public void setnameTemplate(NamedParameterJdbcTemplate template) {  
    this.nameTemplate = template;  
 }   

 public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {  
  this.jdbcTemplate = jdbcTemplate;  
 }  

 // BY using JdbcTemplate
 public int saveEmployee(Employee e){  
 int id = e.getId();
 String name = e.getName();
 float salary = e.getSalary();
 Object p[] = {id, name, salary};
    String query="insert into employee values(?,?,?)";
      return jdbcTemplate.update(query, p);
    /*String query="insert into employee     values('"+e.getId()+"','"+e.getName()+"','"+e.getSalary()+"')"; 
      return jdbcTemplate.update(query);
    */

}  

//By using NameParameterTemplate
public void insertEmploye(Employee e) {  
String query="insert into employee values (:id,:name,:salary)";  
Map<String,Object> map=new HashMap<String,Object>();  
map.put("id",e.getId());  
map.put("name",e.getName());  
map.put("salary",e.getSalary());  

nameTemplate.execute(query,map,new MyPreparedStatement());

 }
// Updating Employee
public int updateEmployee(Employee e){  
String query="update employee set  name='"+e.getName()+"',salary='"+e.getSalary()+"' where id='"+e.getId()+"' ";  
  return jdbcTemplate.update(query);  
 }
 // Deleting a Employee row
 public int deleteEmployee(Employee e){  
 String query="delete from employee where id='"+e.getId()+"' ";  
 return jdbcTemplate.update(query);  
 }  
 //Selecting Single row with condition and also all rows
    public int selectEmployee(Employee e){  
     //String query="select * from employee where id='"+e.getId()+"' ";
      String query="select * from employee";
      List<Map<String, Object>> rows = jdbcTemplate.queryForList(query);
       for(Map<String, Object> row : rows){
          String id = row.get("id").toString();
          String name = (String)row.get("name");
          String salary = row.get("salary").toString();
          System.out.println(id + " " + name + " " + salary );
        }

      return 1;
   }  

   // Can use MyrowMapper class an implementation class for RowMapper interface
    public void getAllEmployee()
    {

    String query="select * from employee";
    List<Employee> l = jdbcTemplate.query(query, new MyrowMapper());

    Iterator it=l.iterator();
    while(it.hasNext())
    {
      Employee e=(Employee)it.next();
      System.out.println(e.getId()+" "+e.getName()+" "+e.getSalary());
    }
   }  

  //Can use directly a RowMapper implementation class without an object creation
  public List<Employee> getAllEmployee1(){
    return jdbcTemplate.query("select * from employee",new RowMapper<Employee>(){  
      @Override  
      public Employee mapRow(ResultSet rs, int rownumber) throws  SQLException    {  
            Employee e=new Employee();  
            e.setId(rs.getInt(1));  
            e.setName(rs.getString(2));  
            e.setSalary(rs.getFloat(3));  
            return e;  
          }  
      });  
      }
     // End of all the function

     }

================================================================ //MyrowMapper.java

 import java.sql.ResultSet;
 import java.sql.SQLException;
 import org.springframework.jdbc.core.RowMapper;

 public class MyrowMapper implements RowMapper<Employee> {

  @Override  
  public Employee mapRow(ResultSet rs, int rownumber) throws SQLException 
   {  
    System.out.println("mapRow()====:"+rownumber);
    Employee e=new Employee();  
     e.setId(rs.getInt("id"));  
     e.setName(rs.getString("name"));  
     e.setSalary(rs.getFloat("salary"));  
     return e;  
      }
    } 

========================================================== //MyPreparedStatement.java

import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.PreparedStatementCallback;


 public class MyPreparedStatement implements  PreparedStatementCallback<Object> {

 @Override
 public Object doInPreparedStatement(PreparedStatement ps)
        throws SQLException, DataAccessException {

     return ps.executeUpdate(); 
  } 

 } 

===================================================================== //Test.java

import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {  

public static void main(String[] args) {  
 ApplicationContext ctx=new     ClassPathXmlApplicationContext("applicationContext.xml");  

 EmployeeDao dao=(EmployeeDao)ctx.getBean("edao"); 

  // By calling constructor for insert
 /* 
    int status=dao.saveEmployee(new Employee(103,"Ajay",35000));  
    System.out.println(status);  
 */
 // By calling PreparedStatement
  dao.insertEmploye(new Employee(103,"Roh",25000));


 // By calling setter-getter for update
 /* 
    Employee e=new Employee(); 
    e.setId(102);
    e.setName("Rohit");
    e.setSalary(8000000);
    int status=dao.updateEmployee(e);
*/
 // By calling constructor for update
 /*
    int status=dao.updateEmployee(new Employee(102,"Sadhan",15000)); 
    System.out.println(status); 
 */ 
 // Deleting a record 
 /*      
    Employee e=new Employee(); 
    e.setId(102); 
    int status=dao.deleteEmployee(e); 
    System.out.println(status);
 */
 // Selecting single or all rows
 /*
    Employee e=new Employee(); 
    e.setId(102);
    int status=dao.selectEmployee(e);
    System.out.println(status);
*/
// Can use MyrowMapper class an implementation class for RowMapper interface

    dao.getAllEmployee();

// Can use directly a RowMapper implementation class without an object creation
 /*
    List<Employee> list=dao.getAllEmployee1();  
    for(Employee e1:list)  
    System.out.println(e1);  
  */   
   }  

 } 

================================================================== //applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>  
<beans  
 xmlns="http://www.springframework.org/schema/beans"  
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
 xmlns:p="http://www.springframework.org/schema/p"  
 xsi:schemaLocation="http://www.springframework.org/schema/beans   
 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">  

<bean id="ds"        class="org.springframework.jdbc.datasource.DriverManagerDataSource">  
 <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />  
 <property name="url" value="jdbc:oracle:thin:@localhost:1521:xe" />  
 <property name="username" value="hr" />  
 <property name="password" value="hr" />  
 </bean>  

 <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">  
 <property name="dataSource" ref="ds"></property>  
 </bean>  

<bean id="nameTemplate"   
class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">  
<constructor-arg ref="ds"></constructor-arg>  
</bean>  

<bean id="edao" class="EmployeeDao"> 
<!-- Can use both --> 
<property name="nameTemplate" ref="nameTemplate"></property>
<property name="jdbcTemplate" ref="jdbcTemplate"></property> 
</bean>  

===================================================================

Solving a "communications link failure" with JDBC and MySQL

In my case (I am a noob), I was testing Servlet that make database connection with MySQL and one of the Exception is the one mentioned above.

It made my head swing for some seconds but I came to realize that it was because I have not started my MySQL server in localhost.
After starting the server, the problem was fixed.

So, check whether MySQL server is running properly.

Oracle DB : java.sql.SQLException: Closed Connection

It means the connection was successfully established at some point, but when you tried to commit right there, the connection was no longer open. The parameters you mentioned sound like connection pool settings. If so, they're unrelated to this problem. The most likely cause is a firewall between you and the database that is killing connections after a certain amount of idle time. The most common fix is to make your connection pool run a validation query when a connection is checked out from it. This will immediately identify and evict dead connnections, ensuring that you only get good connections out of the pool.

How to lookup JNDI resources on WebLogic?

I had a similar problem to this one. It got solved by deleting the java:comp/env/ prefix and using jdbc/myDataSource in the context lookup. Just as someone pointed out in the comments.

How to increase Heap size of JVM

Start the program with -Xms=[size] -Xmx -XX:MaxPermSize=[size] -XX:MaxNewSize=[size]

For example -

-Xms512m -Xmx1152m -XX:MaxPermSize=256m -XX:MaxNewSize=256m

How do I execute a MS SQL Server stored procedure in java/jsp, returning table data?

Our server calls stored procs from Java like so - works on both SQL Server 2000 & 2008:

String SPsql = "EXEC <sp_name> ?,?";   // for stored proc taking 2 parameters
Connection con = SmartPoolFactory.getConnection();   // java.sql.Connection
PreparedStatement ps = con.prepareStatement(SPsql);
ps.setEscapeProcessing(true);
ps.setQueryTimeout(<timeout value>);
ps.setString(1, <param1>);
ps.setString(2, <param2>);
ResultSet rs = ps.executeQuery();

Maven2: Missing artifact but jars are in place

Ohh what a mess! My advise: When its comes to messy poms or project packaging, Eclipse is really bad at showing the real problem. It will tell you some dependencies are missing, when in fact for pom is malformed or some other problem are present in your pom.

Leave Eclipse alone are run a maven install. You will get to the real problem really quick!

SQLRecoverableException: I/O Exception: Connection reset

Your exception says it all "Connection reset". The connection between your java process and the db server was lost, which could have happened for almost any reason(like network issues). The SQLRecoverableException just means that its recoverable, but the root cause is connection reset.

How to change workspace and build record Root Directory on Jenkins?

I figured it out. In order to save your Jenkins data on other drive you'll need to do the following:

Workspace Root Directory: E:\Jenkins\${ITEM_FULL_NAME}\workspace
Build Record Root Directory: E:\Jenkins\${ITEM_FULL_NAME}\builds

Change Directory

linux find regex

Well, you may try this '.*[0-9]'

HTML5 iFrame Seamless Attribute

iO8 has removed support for the iframe seamless attribute.

  • Tested in Safari, HomeScreen, new WKWebView and UIWebView.

Full Details and performance review of other iOS 8 changes:

Exclude property from type

In Typescript 3.5+:

interface TypographyProps {
    variant: string
    fontSize: number
}

type TypographyPropsMinusVariant = Omit<TypographyProps, "variant">

How to remove whitespace from a string in typescript?

The trim() method removes whitespace from both sides of a string.

To remove all the spaces from the string use .replace(/\s/g, "")

 this.maintabinfo = this.inner_view_data.replace(/\s/g, "").toLowerCase();

Split string in Lua?

If you are splitting a string in Lua, you should try the string.gmatch() or string.sub() methods. Use the string.sub() method if you know the index you wish to split the string at, or use the string.gmatch() if you will parse the string to find the location to split the string at.

Example using string.gmatch() from Lua 5.1 Reference Manual:

 t = {}
 s = "from=world, to=Lua"
 for k, v in string.gmatch(s, "(%w+)=(%w+)") do
   t[k] = v
 end

No provider for Http StaticInjectorError

I was trying to fix the issue for about an hour and just deiced to restart the server. Only to see the issue is fixed.

If you make changes to APP module and the issue remains the same, stop the server and try running the serve command again.

Using ionic 4 with angular 7

How do you kill all current connections to a SQL Server 2005 database?

The reason that the approach that Adam suggested won't work is that during the time that you are looping over the active connections new one can be established, and you'll miss those. You could instead use the following approach which does not have this drawback:

-- set your current connection to use master otherwise you might get an error

use master
ALTER DATABASE YourDatabase SET SINGLE_USER WITH ROLLBACK IMMEDIATE 

--do you stuff here 

ALTER DATABASE YourDatabase SET MULTI_USER

how to draw smooth curve through N points using javascript HTML5 canvas?

The first answer will not pass through all the points. This graph will exactly pass through all the points and will be a perfect curve with the points as [{x:,y:}] n such points.

var points = [{x:1,y:1},{x:2,y:3},{x:3,y:4},{x:4,y:2},{x:5,y:6}] //took 5 example points
ctx.moveTo((points[0].x), points[0].y);

for(var i = 0; i < points.length-1; i ++)
{

  var x_mid = (points[i].x + points[i+1].x) / 2;
  var y_mid = (points[i].y + points[i+1].y) / 2;
  var cp_x1 = (x_mid + points[i].x) / 2;
  var cp_x2 = (x_mid + points[i+1].x) / 2;
  ctx.quadraticCurveTo(cp_x1,points[i].y ,x_mid, y_mid);
  ctx.quadraticCurveTo(cp_x2,points[i+1].y ,points[i+1].x,points[i+1].y);
}

don't fail jenkins build if execute shell fails

To stop further execution when command fails:

command || exit 0

To continue execution when command fails:

command || true

A circular reference was detected while serializing an object of type 'SubSonic.Schema .DatabaseColumn'.

//first: Create a class as your view model

public class EventViewModel 
{
 public int Id{get;set}
 public string Property1{get;set;}
 public string Property2{get;set;}
}
//then from your method
[HttpGet]
public async Task<ActionResult> GetEvent()
{
 var events = await db.Event.Find(x => x.ID != 0);
 List<EventViewModel> model = events.Select(event => new EventViewModel(){
 Id = event.Id,
 Property1 = event.Property1,
 Property1 = event.Property2
}).ToList();
 return Json(new{ data = model }, JsonRequestBehavior.AllowGet);
}

Move div to new line

I've found that you can move div elements to the next line simply by setting the property Display: block;

On each div.

Delete sql rows where IDs do not have a match from another table

DELETE FROM blob
WHERE NOT EXISTS (
    SELECT *
    FROM files
    WHERE id=blob.id
)

How to sort an ArrayList?

You can do like this:

List<String> yourList = new ArrayList<String>();
Collections.sort(yourList, Collections.reverseOrder());

Collection has a default Comparator that can help you with that.

Also, if you want to use some Java 8 new features, you can do like that:

List<String> yourList = new ArrayList<String>();
yourList = yourList.stream().sorted(Collections.reverseOrder()).collect(Collectors.toList());

create multiple tag docker image

You can't create tags with Dockerfiles but you can create multiple tags on your images via the command line.

Use this to list your image ids:

$ docker images

Then tag away:

$ docker tag 9f676bd305a4 ubuntu:13.10
$ docker tag 9f676bd305a4 ubuntu:saucy
$ docker tag eb601b8965b8 ubuntu:raring
...

What does print(... sep='', '\t' ) mean?

The sep='\t' can be use in many forms, for example if you want to read tab separated value: Example: I have a dataset tsv = tab separated value NOT comma separated value df = pd.read_csv('gapminder.tsv'). when you try to read this, it will give you an error because you have tab separated value not csv. so you need to give read csv a different parameter called sep='\t'.

Now you can read: df = pd.read_csv('gapminder.tsv, sep='\t'), with this you can read the it.

How to pass credentials to the Send-MailMessage command for sending emails

I found this blog site: Adam Kahtava
I also found this question: send-mail-via-gmail-with-powershell-v2s-send-mailmessage
The problem is, neither of them addressed both your needs (Attachment with a password), so I did some combination of the two and came up with this:

$EmailTo = "[email protected]"
$EmailFrom = "[email protected]"
$Subject = "Test" 
$Body = "Test Body" 
$SMTPServer = "smtp.gmail.com" 
$filenameAndPath = "C:\CDF.pdf"
$SMTPMessage = New-Object System.Net.Mail.MailMessage($EmailFrom,$EmailTo,$Subject,$Body)
$attachment = New-Object System.Net.Mail.Attachment($filenameAndPath)
$SMTPMessage.Attachments.Add($attachment)
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587) 
$SMTPClient.EnableSsl = $true 
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("username", "password"); 
$SMTPClient.Send($SMTPMessage)

Since I love to make functions for things, and I need all the practice I can get, I went ahead and wrote this:

Function Send-EMail {
    Param (
        [Parameter(`
            Mandatory=$true)]
        [String]$EmailTo,
        [Parameter(`
            Mandatory=$true)]
        [String]$Subject,
        [Parameter(`
            Mandatory=$true)]
        [String]$Body,
        [Parameter(`
            Mandatory=$true)]
        [String]$EmailFrom="[email protected]",  #This gives a default value to the $EmailFrom command
        [Parameter(`
            mandatory=$false)]
        [String]$attachment,
        [Parameter(`
            mandatory=$true)]
        [String]$Password
    )

        $SMTPServer = "smtp.gmail.com" 
        $SMTPMessage = New-Object System.Net.Mail.MailMessage($EmailFrom,$EmailTo,$Subject,$Body)
        if ($attachment -ne $null) {
            $SMTPattachment = New-Object System.Net.Mail.Attachment($attachment)
            $SMTPMessage.Attachments.Add($SMTPattachment)
        }
        $SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587) 
        $SMTPClient.EnableSsl = $true 
        $SMTPClient.Credentials = New-Object System.Net.NetworkCredential($EmailFrom.Split("@")[0], $Password); 
        $SMTPClient.Send($SMTPMessage)
        Remove-Variable -Name SMTPClient
        Remove-Variable -Name Password

} #End Function Send-EMail

To call it, just use this command:

Send-EMail -EmailTo "[email protected]" -Body "Test Body" -Subject "Test Subject" -attachment "C:\cdf.pdf" -password "Passowrd"

I know it's not secure putting the password in plainly like that. I'll see if I can come up with something more secure and update later, but at least this should get you what you need to get started. Have a great week!

Edit: Added $EmailFrom based on JuanPablo's comment

Edit: SMTP was spelled STMP in the attachments.

Changing the position of Bootstrap popovers based on the popover's X position in relation to window edge?

Based on the documentation you should be able to use auto in combination with the preferred placement e.g. auto left

http://getbootstrap.com/javascript/#popovers: "When "auto" is specified, it will dynamically reorient the popover. For example, if placement is "auto left", the tooltip will display to the left when possible, otherwise it will display right."

I was trying to do the same thing and then realised that this functionality already existed.

How do I set default values for functions parameters in Matlab?

Another slightly less hacky way is

function output = fun(input)
   if ~exist('input','var'), input='BlahBlahBlah'; end
   ...
end

Download and open PDF file using Ajax

Hope this will save you a few hours and spare you from a headache. It took me a while to figure this out, but doing regular $.ajax() request ruined my PDF file, while requesting it through address bar worked perfectly. Solution was this:

Include download.js: http://danml.com/download.html

Then use XMLHttpRequest instead of $.ajax() request.

    var ajax = new XMLHttpRequest(); 

    ajax.open("GET", '/Admin/GetPdf' + id, true); 
    ajax.onreadystatechange = function(data) { 
        if (this.readyState == 4)
        {
            if (this.status == 200)
            {
                download(this.response, "report.pdf", "application/pdf");

            }
            else if (this.responseText != "")
            {
                alert(this.responseText);
            }
        }
        else if (this.readyState == 2)
        {
            if (this.status == 200)
            {
                this.responseType = "blob";
            }
            else
            {
                this.responseType = "text";
            }
        }
    };

    ajax.send(null);

How to create a readonly textbox in ASP.NET MVC3 Razor

You can use the below code for creating a TextBox as read-only.

Method 1

 @Html.TextBoxFor(model => model.Fields[i].TheField, new { @readonly = true })

Method 2

@Html.TextBoxFor(model => model.Fields[i].TheField, new { htmlAttributes = new {disabled = "disabled"}})

Difference between request.getSession() and request.getSession(true)

request.getSession() is just a convenience method. It does exactly the same as request.getSession(true).

UUID max character length

Most databases have a native UUID type these days to make working with them easier. If yours doesn't, they're just 128-bit numbers, so you can use BINARY(16), and if you need the text format frequently, e.g. for troubleshooting, then add a calculated column to generate it automatically from the binary column. There is no good reason to store the (much larger) text form.

Android Linear Layout - How to Keep Element At Bottom Of View?

You should put the parameter gravity to bottom not in the textview but in the Linear Layout. Like this:

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="bottom|end">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Something"/>
</LinearLayout>

Please initialize the log4j system properly. While running web service

If the below statment is present in your class then your log4j.properties should be in java source(src) folder , if it is jar executable it should be packed in jar not a seperate file.

static Logger log = Logger.getLogger(MyClass.class);

Thanks,

How to get annotations of a member variable?

Everybody describes issue with getting annotations, but the problem is in definition of your annotation. You should to add to your annotation definition a @Retention(RetentionPolicy.RUNTIME):

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface MyAnnotation{
    int id();
}

How to decompile to java files intellij idea

As of August 2017 and IntelliJ V2017.2, the accepted answer does not seem to be entirely accurate anymore: there is no fernflower.jar to use.

The jar file is called java-decompiler.jar and does not include a main manifest... Instead you can use the following command (from a Mac install):

java -cp "/Applications/IntelliJ IDEA.app/Contents/plugins/java-decompiler/lib/java-decompiler.jar" org.jetbrains.java.decompiler.main.decompiler.ConsoleDecompiler

(you will get the wrong Usage command, but it does work).

org.hibernate.PersistentObjectException: detached entity passed to persist

Most likely the problem lies outside the code you are showing us here. You are trying to update an object that is not associated with the current session. If it is not the Invoice, then maybe it is an InvoiceItem that has already been persisted, obtained from the db, kept alive in some sort of session and then you try to persist it on a new session. This is not possible. As a general rule, never keep your persisted objects alive across sessions.

The solution will ie in obtaining the whole object graph from the same session you are trying to persist it with. In a web environment this would mean:

  • Obtain the session
  • Fetch the objects you need to update or add associations to. Preferabley by their primary key
  • Alter what is needed
  • Save/update/evict/delete what you want
  • Close/commit your session/transaction

If you keep having issues post some of the code that is calling your service.

Automatically create requirements.txt

Not a complete solution, but may help to compile a shortlist on Linux.

grep --include='*.py' -rhPo '^\s*(from|import)\s+\w+' . | sed -r 's/\s*(import|from)\s+//' | sort -u > requirements.txt

C# - How to convert string to char?

Use:

string str = "Hello";
char[] characters = str.ToCharArray();

If you have a single character string, You can also try

string str = "A";
char character = char.Parse(str);    

//OR 
string str = "A";
char character = str.ToCharArray()[0];

VB.Net: Dynamically Select Image from My.Resources

This works for me at runtime too:

UltraPictureBox1.Image = My.Resources.MyPicture

No strings involved and if I change the name it is automatically updated by refactoring.

How to populate/instantiate a C# array with a single value?

What about a parallel implementation

public static void InitializeArray<T>(T[] array, T value)
{
    var cores = Environment.ProcessorCount;

    ArraySegment<T>[] segments = new ArraySegment<T>[cores];

    var step = array.Length / cores;
    for (int i = 0; i < cores; i++)
    {
        segments[i] = new ArraySegment<T>(array, i * step, step);
    }
    var remaining = array.Length % cores;
    if (remaining != 0)
    {
        var lastIndex = segments.Length - 1;
        segments[lastIndex] = new ArraySegment<T>(array, lastIndex * step, array.Length - (lastIndex * step));
    }

    var initializers = new Task[cores];
    for (int i = 0; i < cores; i++)
    {
        var index = i;
        var t = new Task(() =>
        {
            var s = segments[index];
            for (int j = 0; j < s.Count; j++)
            {
                array[j + s.Offset] = value;
            }
        });
        initializers[i] = t;
        t.Start();
    }

    Task.WaitAll(initializers);
}

When only initializing an array the power of this code can't be seen but I think you should definitely forget about the "pure" for.

Wireshark localhost traffic capture

For some reason, none of previous answers worked in my case, so I'll post something that did the trick. There is a little jewel called RawCap that can capture localhost traffic on Windows. Advantages:

  • only 17 kB!
  • no external libraries needed
  • extremely simple to use (just start it, choose the loopback interface and destination file and that's all)

After the traffic has been captured, you can open it and examine in Wireshark normally. The only disadvantage that I found is that you cannot set filters, i.e. you have to capture all localhost traffic which can be heavy. There is also one bug regarding Windows XP SP 3.

Few more advices:

Reactive forms - disabled attribute

Use [attr.disabled] instead [disabled], in my case it works ok

jquery smooth scroll to an anchor?

I wanted a version that worked for <a href="#my-id"> and <a href="/page#my-id">

<script>        
    $('a[href*=#]:not([href=#])').on('click', function (event) {
        event.preventDefault();
        var element = $(this.hash);
        $('html,body').animate({ scrollTop: element.offset().top },'normal', 'swing');
    });
</script>

Error: Address already in use while binding socket with address but the port number is shown free by `netstat`

As already said, your socket probably enter in TIME_WAIT state. This issue is well described by Thomas A. Fine here.

To summary, socket closing process follow diagram below:

Socket closing process

Thomas says:

Looking at the diagram above, it is clear that TIME_WAIT can be avoided if the remote end initiates the closure. So the server can avoid problems by letting the client close first. The application protocol must be designed so that the client knows when to close. The server can safely close in response to an EOF from the client, however it will also need to set a timeout when it is expecting an EOF in case the client has left the network ungracefully. In many cases simply waiting a few seconds before the server closes will be adequate.

Using SO_REUSEADDR is commonly suggested on internet, but Thomas add:

Oddly, using SO_REUSEADDR can actually lead to more difficult "address already in use" errors. SO_REUSADDR permits you to use a port that is stuck in TIME_WAIT, but you still can not use that port to establish a connection to the last place it connected to. What? Suppose I pick local port 1010, and connect to foobar.com port 300, and then close locally, leaving that port in TIME_WAIT. I can reuse local port 1010 right away to connect to anywhere except for foobar.com port 300.

Objective-C for Windows

You can use Objective C inside the Windows environment. If you follow these steps, it should be working just fine:

  1. Visit the GNUstep website and download GNUstep MSYS Subsystem (MSYS for GNUstep), GNUstep Core (Libraries for GNUstep), and GNUstep Devel
  2. After downloading these files, install in that order, or you will have problems with configuration
  3. Navigate to C:\GNUstep\GNUstep\System\Library\Headers\Foundation1 and ensure that Foundation.h exists
  4. Open up a command prompt and run gcc -v to check that GNUstep MSYS is correctly installed (if you get a file not found error, ensure that the bin folder of GNUstep MSYS is in your PATH)
  5. Use this simple "Hello World" program to test GNUstep's functionality:

    #include <Foundation/Foundation.h>
    
    int main(void)
    {
        NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
        NSLog(@"Hello World!.");
        [pool drain];
     return;
    }
    
  6. Go back to the command prompt and cd to where you saved the "Hello World" program and then compile it:2

    gcc -o helloworld.exe <HELLOWORLD>.m -I /GNUstep/GNUstep/System/Library/Headers -L /GNUstep/GNUstep/System/Library/Libraries -std=c99 -lobjc -lgnustep-base -fconstant-string-class=NSConstantString
    
  7. Finally, from the command prompt, type helloworld to run it

All the best, and have fun with Objective-C!


NOTES:

  1. I used the default install path - adjust your command line accordingly
  2. Ensure the folder path of yours is similar to mine, otherwise you will get an error

jQuery calculate sum of values in all text fields

This will work 100%:

<script type="text/javascript">  
  function calculate() {
    var result = document.getElementById('result');
    var el, i = 0, total = 0; 
    while(el = document.getElementById('v'+(i++)) ) {
      el.value = el.value.replace(/\\D/,"");
      total = total + Number(el.value);
    }
    result.value = total;
    if(document.getElementById('v0').value =="" &&
      document.getElementById('v1').value =="" &&
      document.getElementById('v2').value =="" ) {
        result.value ="";
      }
    }
  }
</script>
Some number:<input type="text" id ="v0" onkeyup="calculate()">
Some number:<input type="text" id ="v1" onkeyup="calculate()">
Some number:<input type="text" id ="v2" onkeyup="calculate()">
Result: <input type="text" id="result" onkeyup="calculate()"  readonly>

Remove all newlines from inside a string

strip() returns the string with leading and trailing whitespaces(by default) removed.

So it would turn " Hello World " to "Hello World", but it won't remove the \n character as it is present in between the string.

Try replace().

str = "Hello \n World"
str2 = str.replace('\n', '')
print str2

How can I run another application within a panel of my C# program?

Using the win32 API it is possible to "eat" another application. Basically you get the top window for that application and set it's parent to be the handle of the panel you want to place it in. If you don't want the MDI style effect you also have to adjust the window style to make it maximised and remove the title bar.

Here is some simple sample code where I have a form with a button and a panel:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;

namespace WindowsFormsApplication2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Process p = Process.Start("notepad.exe");
            Thread.Sleep(500); // Allow the process to open it's window
            SetParent(p.MainWindowHandle, panel1.Handle);
        }

        [DllImport("user32.dll")]
        static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);
    }
}

I just saw another example where they called WaitForInputIdle instead of sleeping. So the code would be like this:

Process p = Process.Start("notepad.exe");
p.WaitForInputIdle();
SetParent(p.MainWindowHandle, panel1.Handle);

The Code Project has a good article one the whole process: Hosting EXE Applications in a WinForm project

Programmatically register a broadcast receiver

One important point that people forget to mention is the life time of the Broadcast Receiver. The difference of programmatically registering it from registering in AndroidManifest.xml is that. In the manifest file, it doesn't depend on application life time. While when programmatically registering it it does depend on the application life time. This means that if you register in AndroidManifest.xml, you can catch the broadcasted intents even when your application is not running.

Edit: The mentioned note is no longer true as of Android 3.1, the Android system excludes all receiver from receiving intents by default if the corresponding application has never been started by the user or if the user explicitly stopped the application via the Android menu (in Manage ? Application). https://developer.android.com/about/versions/android-3.1.html

This is an additional security feature as the user can be sure that only the applications he started will receive broadcast intents.

So it can be understood as receivers programmatically registered in Application's onCreate() would have same effect with ones declared in AndroidManifest.xml from Android 3.1 above.

Definition of "downstream" and "upstream"

When you read in git tag man page:

One important aspect of git is it is distributed, and being distributed largely means there is no inherent "upstream" or "downstream" in the system.

, that simply means there is no absolute upstream repo or downstream repo.
Those notions are always relative between two repos and depends on the way data flows:

If "yourRepo" has declared "otherRepo" as a remote one, then:

  • you are pulling from upstream "otherRepo" ("otherRepo" is "upstream from you", and you are "downstream for otherRepo").
  • you are pushing to upstream ("otherRepo" is still "upstream", where the information now goes back to).

Note the "from" and "for": you are not just "downstream", you are "downstream from/for", hence the relative aspect.


The DVCS (Distributed Version Control System) twist is: you have no idea what downstream actually is, beside your own repo relative to the remote repos you have declared.

  • you know what upstream is (the repos you are pulling from or pushing to)
  • you don't know what downstream is made of (the other repos pulling from or pushing to your repo).

Basically:

In term of "flow of data", your repo is at the bottom ("downstream") of a flow coming from upstream repos ("pull from") and going back to (the same or other) upstream repos ("push to").


You can see an illustration in the git-rebase man page with the paragraph "RECOVERING FROM UPSTREAM REBASE":

It means you are pulling from an "upstream" repo where a rebase took place, and you (the "downstream" repo) is stuck with the consequence (lots of duplicate commits, because the branch rebased upstream recreated the commits of the same branch you have locally).

That is bad because for one "upstream" repo, there can be many downstream repos (i.e. repos pulling from the upstream one, with the rebased branch), all of them having potentially to deal with the duplicate commits.

Again, with the "flow of data" analogy, in a DVCS, one bad command "upstream" can have a "ripple effect" downstream.


Note: this is not limited to data.
It also applies to parameters, as git commands (like the "porcelain" ones) often call internally other git commands (the "plumbing" ones). See rev-parse man page:

Many git porcelainish commands take mixture of flags (i.e. parameters that begin with a dash '-') and parameters meant for the underlying git rev-list command they use internally and flags and parameters for the other commands they use downstream of git rev-list. This command is used to distinguish between them.

What Process is using all of my disk IO

TL;DR

If you can use iotop, do so. Else this might help.


Use top, then use these shortcuts:

d 1 = set refresh time from 3 to 1 second

1   = show stats for each cpu, not cumulated

This has to show values > 1.0 wa for at least one core - if there are no diskwaits, there is simply no IO load and no need to look further. Significant loads usually start > 15.0 wa.

x       = highlight current sort column 
< and > = change sort column
R       = reverse sort order

Chose 'S', the process status column. Reverse the sort order so the 'R' (running) processes are shown on top. If you can spot 'D' processes (waiting for disk), you have an indicator what your culprit might be.

Where are logs located?

You should be checking the root directory and not the app directory.

Look in $ROOT/storage/laravel.log not app/storage/laravel.log, where root is the top directory of the project.

How do I encode and decode a base64 string?

I'm sharing my implementation with some neat features:

  • uses Extension Methods for Encoding class. Rationale is that someone may need to support different types of encodings (not only UTF8).
  • Another improvement is failing gracefully with null result for null entry - it's very useful in real life scenarios and supports equivalence for X=decode(encode(X)).

Remark: Remember that to use Extension Method you have to (!) import the namespace with using keyword (in this case using MyApplication.Helpers.Encoding).

Code:

namespace MyApplication.Helpers.Encoding
{
    public static class EncodingForBase64
    {
        public static string EncodeBase64(this System.Text.Encoding encoding, string text)
        {
            if (text == null)
            {
                return null;
            }

            byte[] textAsBytes = encoding.GetBytes(text);
            return System.Convert.ToBase64String(textAsBytes);
        }

        public static string DecodeBase64(this System.Text.Encoding encoding, string encodedText)
        {
            if (encodedText == null)
            {
                return null;
            }

            byte[] textAsBytes = System.Convert.FromBase64String(encodedText);
            return encoding.GetString(textAsBytes);
        }
    }
}

Usage example:

using MyApplication.Helpers.Encoding; // !!!

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Test1();
            Test2();
        }

        static void Test1()
        {
            string textEncoded = System.Text.Encoding.UTF8.EncodeBase64("test1...");
            System.Diagnostics.Debug.Assert(textEncoded == "dGVzdDEuLi4=");

            string textDecoded = System.Text.Encoding.UTF8.DecodeBase64(textEncoded);
            System.Diagnostics.Debug.Assert(textDecoded == "test1...");
        }

        static void Test2()
        {
            string textEncoded = System.Text.Encoding.UTF8.EncodeBase64(null);
            System.Diagnostics.Debug.Assert(textEncoded == null);

            string textDecoded = System.Text.Encoding.UTF8.DecodeBase64(textEncoded);
            System.Diagnostics.Debug.Assert(textDecoded == null);
        }
    }
}

Git merge without auto commit

If you only want to commit all the changes in one commit as if you typed yourself, --squash will do too

$ git merge --squash v1.0
$ git commit

Postgresql - unable to drop database because of some auto connections to DB

Stop your running application.(in Eclipse) After you try again.

Mobile Redirect using htaccess

Similarly, if you wanted to redirect to a sub-folder instead of a sub-domain, do the following:

Working off of Kevin's great solution you can add this to the .htaccess file in your site's root directory:

    <IfModule mod_rewrite.c>
        RewriteBase /
        RewriteEngine On

        # Check if mobile=1 is set and set cookie 'mobile' equal to 1
        RewriteCond %{QUERY_STRING} (^|&)mobile=1(&|$)
        RewriteRule ^ - [CO=mobile:1:%{HTTP_HOST}]

        # Check if mobile=0 is set and set cookie 'mobile' equal to 0
        RewriteCond %{QUERY_STRING} (^|&)mobile=0(&|$)
        RewriteRule ^ - [CO=mobile:0:%{HTTP_HOST}]

        # cookie can't be set and read in the same request so check
        RewriteCond %{QUERY_STRING} (^|&)mobile=0(&|$)
        RewriteRule ^ - [S=1]

        # Check if this looks like a mobile device
        RewriteCond %{HTTP:x-wap-profile} !^$ [OR]
        RewriteCond %{HTTP_USER_AGENT} "android|blackberry|ipad|iphone|ipod|iemobile|opera mobile|palmos|webos|googlebot-mobile" [NC,OR]
        RewriteCond %{HTTP:Profile}       !^$

        # Check if we're not already on the mobile site
        RewriteCond %{HTTP_HOST}          !^m\.
        # Check to make sure we haven't set the cookie before
        RewriteCond %{HTTP:Cookie}        !\mobile=0(;|$)
        # Now redirect to the mobile site
        RewriteRule ^ http://www.mysite.com/m/ [R]
    </IfModule>

Then, in the /m/ folder, add or create an .htaccess with the following:

    #Begin user agent loop fix

         RewriteEngine Off
         RewriteBase /

    #End user agent loop fix 

I know it's not a direct answer to the question, but somebody (like me) might stumble upon this question and wonder how that method would be accomplished as well.

Play/pause HTML 5 video using JQuery

As an extension of lonesomeday's answer, you can also use

$('#playMovie1').click(function(){
    $('#movie1')[0].play();
});

Notice that there is no get() or eq() jQuery function called. DOM's array used to call play() function. It's a shortcut to keep in mind.

New line in JavaScript alert box

Just in case this helps anyone, when doing this from C# code behind I had to use a double escape character or I got an "unterminated string constant" JavaScript error:

ScriptManager.RegisterStartupScript(this, this.GetType(), "scriptName", "alert(\"Line 1.\\n\\nLine 2.\");", true);

How to create EditText accepts Alphabets only in android?

EditText state = (EditText) findViewById(R.id.txtState);


                Pattern ps = Pattern.compile("^[a-zA-Z ]+$");
                Matcher ms = ps.matcher(state.getText().toString());
                boolean bs = ms.matches();
                if (bs == false) {
                    if (ErrorMessage.contains("invalid"))
                        ErrorMessage = ErrorMessage + "state,";
                    else
                        ErrorMessage = ErrorMessage + "invalid state,";

                }

Convert string to hex-string in C#

few Unicode alternatives

var s = "0";

var s1 = string.Concat(s.Select(c => $"{(int)c:x4}"));  // left padded with 0 - "0030d835dfcfd835dfdad835dfe5d835dff0d835dffb"

var sL = BitConverter.ToString(Encoding.Unicode.GetBytes(s)).Replace("-", "");       // Little Endian "300035D8CFDF35D8DADF35D8E5DF35D8F0DF35D8FBDF"
var sB = BitConverter.ToString(Encoding.BigEndianUnicode.GetBytes(s)).Replace("-", ""); // Big Endian "0030D835DFCFD835DFDAD835DFE5D835DFF0D835DFFB"

// no encodding "300035D8CFDF35D8DADF35D8E5DF35D8F0DF35D8FBDF"
byte[] b = new byte[s.Length * sizeof(char)];
Buffer.BlockCopy(s.ToCharArray(), 0, b, 0, b.Length);
var sb = BitConverter.ToString(b).Replace("-", "");

YAML mapping values are not allowed in this context

This is valid YAML:

jobs:
 - name: A
   schedule: "0 0/5 * 1/1 * ? *"
   type: mongodb.cluster
   config:
     host: mongodb://localhost:27017/admin?replicaSet=rs
     minSecondaries: 2
     minOplogHours: 100
     maxSecondaryDelay: 120
 - name: B
   schedule: "0 0/5 * 1/1 * ? *"
   type: mongodb.cluster
   config:
     host: mongodb://localhost:27017/admin?replicaSet=rs
     minSecondaries: 2
     minOplogHours: 100
     maxSecondaryDelay: 120

Note, that every '-' starts new element in the sequence. Also, indentation of keys in the map should be exactly same.

JavaScript Object Id

I've just come across this, and thought I'd add my thoughts. As others have suggested, I'd recommend manually adding IDs, but if you really want something close to what you've described, you could use this:

var objectId = (function () {
    var allObjects = [];

    var f = function(obj) {
        if (allObjects.indexOf(obj) === -1) {
            allObjects.push(obj);
        }
        return allObjects.indexOf(obj);
    }
    f.clear = function() {
      allObjects = [];
    };
    return f;
})();

You can get any object's ID by calling objectId(obj). Then if you want the id to be a property of the object, you can either extend the prototype:

Object.prototype.id = function () {
    return objectId(this);
}

or you can manually add an ID to each object by adding a similar function as a method.

The major caveat is that this will prevent the garbage collector from destroying objects when they drop out of scope... they will never drop out of the scope of the allObjects array, so you might find memory leaks are an issue. If your set on using this method, you should do so for debugging purpose only. When needed, you can do objectId.clear() to clear the allObjects and let the GC do its job (but from that point the object ids will all be reset).

Is there a way to get the XPath in Google Chrome?

Right click on the node => "Copy XPath"

How to define static constant in a class in swift

Perhaps a nice idiom for declaring constants for a class in Swift is to just use a struct named MyClassConstants like the following.

struct MyClassConstants{
    static let testStr = "test"
    static let testStrLength = countElements(testStr)

    static let arrayOfTests: [String] = ["foo", "bar", testStr]
}

In this way your constants will be scoped within a declared construct instead of floating around globally.

Update

I've added a static array constant, in response to a comment asking about static array initialization. See Array Literals in "The Swift Programming Language".

Notice that both string literals and the string constant can be used to initialize the array. However, since the array type is known the integer constant testStrLength cannot be used in the array initializer.

Can I access variables from another file?

You can export the variable from first file using export.

//first.js
const colorCode = {
    black: "#000",
    white: "#fff"
};
export { colorCode };

Then, import the variable in second file using import.

//second.js
import { colorCode } from './first.js'

export - MDN

MySQL DELETE FROM with subquery as condition

The alias should be included after the DELETE keyword:

DELETE th
FROM term_hierarchy AS th
WHERE th.parent = 1015 AND th.tid IN 
(
    SELECT DISTINCT(th1.tid)
    FROM term_hierarchy AS th1
    INNER JOIN term_hierarchy AS th2 ON (th1.tid = th2.tid AND th2.parent != 1015)
    WHERE th1.parent = 1015
);

Redis - Connect to Remote Server

I've been stuck with the same issue, and the preceding answer did not help me (albeit well written).

The solution is here : check your /etc/redis/redis.conf, and make sure to change the default

bind 127.0.0.1

to

bind 0.0.0.0

Then restart your service (service redis-server restart)

You can then now check that redis is listening on non-local interface with

redis-cli -h 192.168.x.x ping

(replace 192.168.x.x with your IP adress)

Important note : as several users stated, it is not safe to set this on a server which is exposed to the Internet. You should be certain that you redis is protected with any means that fits your needs.

How create table only using <div> tag and Css

A bit OFF-TOPIC, but may help someone for a cleaner HTML... CSS

.common_table{
    display:table;
    border-collapse:collapse;
    border:1px solid grey;
    }
.common_table DIV{
    display:table-row;
    border:1px solid grey;
    }
.common_table DIV DIV{
    display:table-cell;
    }

HTML

<DIV class="common_table">
   <DIV><DIV>this is a cell</DIV></DIV>
   <DIV><DIV>this is a cell</DIV></DIV>
</DIV>

Works on Chrome and Firefox

How can I determine the URL that a local Git repository was originally cloned from?

To get the answer:

git ls-remote --get-url [REMOTE]

This is better than reading the configuration; refer to the man page for git-ls-remote:

--get-url

Expand the URL of the given remote repository taking into account any "url.<base>.insteadOf" config setting (See git-config(1)) and exit without talking to the remote.

As pointed out by @Jefromi, this option was added in v1.7.5 and not documented until v1.7.12.2 (2012-09).

Generate a dummy-variable

another way you can do it is use

ifelse(year < 1965 , 1, 0)

How to get the selected index of a RadioGroup in Android

This should work,

int index = myRadioGroup.indexOfChild(findViewById(myRadioGroup.getCheckedRadioButtonId()));

What's the meaning of "=>" (an arrow formed from equals & greater than) in JavaScript?

I've read, this is a symbol of Arrow Functions in ES6

this

var a2 = a.map(function(s){ return s.length });

using Arrow Function can be written as

var a3 = a.map( s => s.length );

MDN Docs

"Use the new keyword if hiding was intended" warning

@wdavo is correct. The same is also true for functions.

If you override a base function, like Update, then in your subclass you need:

new void Update()
{
  //do stufff
}

Without the new at the start of the function decleration you will get the warning flag.

How to change the MySQL root account password on CentOS7?

All,

Here a little bit twist with mysql-community-server 5.7 I share some steps, how to reset mysql5.7 root password or set password. it will work centos7 and RHEL7 as well.

step1. 1st stop your databases

service mysqld stop

step2. 2nd modify /etc/my.cnf file add "skip-grant-tables"

vi /etc/my.cnf

[mysqld] skip-grant-tables

step3. 3rd start mysql

service mysqld start

step4. select mysql default database

mysql -u root

mysql>use mysql;

step4. set a new password

mysql> update user set authentication_string=PASSWORD("yourpassword") where User='root';

step5 restart mysql database

service mysqld restart

 mysql -u root -p

enjoy :)

IF EXISTS in T-SQL

There's no need for "else" in this case:

IF EXISTS(SELECT *  FROM  table1  WHERE Name='John' ) return 1
return 0

What does localhost:8080 mean?

Option 1

localhost/web is equal to localhost:80/web OR to 127.0.0.1:80/web

Option 2

localhost:8080/web is equal to localhost:8080/web OR to 127.0.0.1:8080/web

How to force addition instead of concatenation in javascript

Your code concatenates three strings, then converts the result to a number.

You need to convert each variable to a number by calling parseFloat() around each one.

total = parseFloat(myInt1) + parseFloat(myInt2) + parseFloat(myInt3);

Move the most recent commit(s) to a new branch with Git

This doesn't "move" them in the technical sense but it has the same effect:

A--B--C  (branch-foo)
 \    ^-- I wanted them here!
  \
   D--E--F--G  (branch-bar)
      ^--^--^-- Opps wrong branch!

While on branch-bar:
$ git reset --hard D # remember the SHAs for E, F, G (or E and G for a range)

A--B--C  (branch-foo)
 \
  \
   D-(E--F--G) detached
   ^-- (branch-bar)

Switch to branch-foo
$ git cherry-pick E..G

A--B--C--E'--F'--G' (branch-foo)
 \   E--F--G detached (This can be ignored)
  \ /
   D--H--I (branch-bar)

Now you won't need to worry about the detached branch because it is basically
like they are in the trash can waiting for the day it gets garbage collected.
Eventually some time in the far future it will look like:

A--B--C--E'--F'--G'--L--M--N--... (branch-foo)
 \
  \
   D--H--I--J--K--.... (branch-bar)

How to limit depth for recursive file list?

All I'm really interested in is the ownership and permissions information for the first level subdirectories.

I found a easy solution while playing my fish, which fits your need perfectly.

ll `ls`

or

ls -l $(ls)

Change size of axes title and labels in ggplot2

To change the size of (almost) all text elements, in one place, and synchronously, rel() is quite efficient:
g+theme(text = element_text(size=rel(3.5))

You might want to tweak the number a bit, to get the optimum result. It sets both the horizontal and vertical axis labels and titles, and other text elements, on the same scale. One exception is faceted grids' titles which must be manually set to the same value, for example if both x and y facets are used in a graph:
theme(text = element_text(size=rel(3.5)), strip.text.x = element_text(size=rel(3.5)), strip.text.y = element_text(size=rel(3.5)))

How do I find out which DOM element has the focus?

Reading other answers, and trying myself, it seems document.activeElement will give you the element you need in most browsers.

If you have a browser that doesn't support document.activeElement if you have jQuery around, you should be able populate it on all focus events with something very simple like this (untested as I don't have a browser meeting those criteria to hand):

if (typeof document.activeElement === 'undefined') { // Check browser doesn't do it anyway
  $('*').live('focus', function () { // Attach to all focus events using .live()
    document.activeElement = this; // Set activeElement to the element that has been focussed
  });
}

How do you dynamically allocate a matrix?

You can also use std::vectors for achieving this:

using std::vector< std::vector<int> >

Example:

std::vector< std::vector<int> > a;

  //m * n is the size of the matrix

    int m = 2, n = 4;
    //Grow rows by m
    a.resize(m);
    for(int i = 0 ; i < m ; ++i)
    {
        //Grow Columns by n
        a[i].resize(n);
    }
    //Now you have matrix m*n with default values

    //you can use the Matrix, now
    a[1][0]=1;
    a[1][1]=2;
    a[1][2]=3;
    a[1][3]=4;

//OR
for(i = 0 ; i < m ; ++i)
{
    for(int j = 0 ; j < n ; ++j)
    {      //modify matrix
        int x = a[i][j];
    }

}

Convert a String to int?

With a recent nightly, you can do this:

let my_int = from_str::<int>(&*my_string);

What's happening here is that String can now be dereferenced into a str. However, the function wants an &str, so we have to borrow again. For reference, I believe this particular pattern (&*) is called "cross-borrowing".

Remove attribute "checked" of checkbox

Try...

$("#captureAudio").prop('checked', false); 

Bash Templating: How to build configuration files from templates with Bash?

This page describes an answer with awk

awk '{while(match($0,"[$]{[^}]*}")) {var=substr($0,RSTART+2,RLENGTH -3);gsub("[$]{"var"}",ENVIRON[var])}}1' < input.txt > output.txt

How to compile and run C in sublime text 3?

After a rigorous code-hunting session over the internet, I finally came up with a solution which lets you compile + run your C code "together at once", in C99, in a dedicated terminal window. I know, a few people dont like C99. I dont like a few people either.

In most of the cases Sublime compiles and runs the code, but in C90 or a lesser version. So if you specifically want it to be C99, this is the way to go.

NOTE: Btw, I did this on a Windows machine, cannot guarantee for others! It probably won't work there.

1. Create a new build system in Sublime: Tools > Build System > New Build System...

New Build System

2. A new file called untitled.sublime-build would be created.

Most probably, Sublime will open it for you.

If not, go to Preferences > Browse Packages > User

Open new sublime-build

If the file untitled.sublime-build is there, then open it, if it isn't there, then create it manually and open it.

3. Copy and paste the given below code in the above mentioned untitled.sublime-build file and save it.

{
    "windows":
    {
        "cmd": ["gcc","-std=c99" ,"$file_name","-o", "${file_base_name}.exe", "-lm", "-Wall", "&","start", "${file_base_name}.exe"]
    },
    "selector" : "source.c",
    "shell": true,
    "working_dir" : "$file_path",
}

Close the file. You are almost done!

4. Finally rename your file from untitled.sublime-build to myC.sublime-build, or you might as well show your creativity here. Just keep the file extension same.

5. Finally set the current Build System to the filename which you wrote in the previous step. In this case, it is myC

Update current build system

Voila ! Compile + Run your C code using C99 by Tools > Build , or by simply pressing Ctrl + B

Tests not running in Test Explorer

What works for me is to delete the bin folder, then rebuild the project.

How do I create a singleton service in Angular 2?

Parent and child services

I was having trouble with a parent service and its child using different instances. To force one instance to be used, you can alias the parent with reference to the child in your app module providers. The parent will not be able to access the child's properties, but the same instance will be used for both services. https://angular.io/guide/dependency-injection-providers#aliased-class-providers

app.module.ts

providers: [
  ChildService,
  // Alias ParentService w/ reference to ChildService
  { provide: ParentService, useExisting: ChildService}
]

Services used by components outside of your app modules scope

When creating a library consisting of a component and a service, I ran into an issue where two instances would be created. One by my Angular project and one by the component inside of my library. The fix:

my-outside.component.ts

@Component({...})
export class MyOutsideComponent {
  @Input() serviceInstance: MyOutsideService;
  ...
}

my-inside.component.ts

  constructor(public myService: MyOutsideService) { }

my-inside.component.hmtl

<app-my-outside [serviceInstance]="myService"></app-my-outside>

Tool to compare directories (Windows 7)

I use WinMerge. It is free and works pretty well (works for files and directories).

SFTP Libraries for .NET

I've used IP*Works SSH and it is great. Easy to setup and use. Plus, their support is top-notch when you run into questions or problems.

How to set the value of a hidden field from a controller in mvc

You could set the corresponding value in the ViewData/ViewBag:

ViewData["hdnFlag"] = "some value";

But a much better approach is to of course use a view model:

model.hdnFlag = "some value";
return View(model);

and use a strongly typed helper in your view:

@Html.HiddenFor(x => x.hdnFlag, new { id = "hdnFlag" })

Windows: XAMPP vs WampServer vs EasyPHP vs alternative

I'm using EasyPHP in making my Thesis about Content Management System. So far, this tool is very good and easy to use.

Maven Out of Memory Build Failure

Answering late to mention yet another option rather than the common MAVEN_OPTS environment variable to pass to the Maven build the required JVM options.

Since Maven 3.3.1, you could have an .mvn folder as part of the concerned project and a jvm.config file as perfect place for such an option.

two new optional configuration files .mvn/jvm.config and .mvn/maven.config, located at the base directory of project source tree. If present, these files will provide default jvm and maven options. Because these files are part of the project source tree, they will be present in all project checkouts and will be automatically used every time the project is build.

As part of the official release notes

In Maven it is not simple to define JVM configuration on a per project base. The existing mechanism based on an environment variable MAVEN_OPTS and the usage of ${user.home}/.mavenrc is an other option with the drawback of not being part of the project.

Starting with this release you can define JVM configuration via ${maven.projectBasedir}/.mvn/jvm.config file which means you can define the options for your build on a per project base. This file will become part of your project and will be checked in along with your project. So no need anymore for MAVEN_OPTS, .mavenrc files. So for example if you put the following JVM options into the ${maven.projectBasedir}/.mvn/jvm.config file:

-Xmx2048m -Xms1024m -XX:MaxPermSize=512m -Djava.awt.headless=true

The main advantage of this approach is that the configuration is isolated to the concerned project and applied to the whole build as well, and less fragile than MAVEN_OPTS for other developers working on the same project (forgetting to setting it).
Moreover, the options will be applied to all modules in case of a multi-module project.

Using an HTML button to call a JavaScript function

There are a few ways to handle events with HTML/DOM. There's no real right or wrong way but different ways are useful in different situations.

1: There's defining it in the HTML:

<input id="clickMe" type="button" value="clickme" onclick="doFunction();" />

2: There's adding it to the DOM property for the event in Javascript:

//- Using a function pointer:
document.getElementById("clickMe").onclick = doFunction;

//- Using an anonymous function:
document.getElementById("clickMe").onclick = function () { alert('hello!'); };

3: And there's attaching a function to the event handler using Javascript:

var el = document.getElementById("clickMe");
if (el.addEventListener)
    el.addEventListener("click", doFunction, false);
else if (el.attachEvent)
    el.attachEvent('onclick', doFunction);

Both the second and third methods allow for inline/anonymous functions and both must be declared after the element has been parsed from the document. The first method isn't valid XHTML because the onclick attribute isn't in the XHTML specification.

The 1st and 2nd methods are mutually exclusive, meaning using one (the 2nd) will override the other (the 1st). The 3rd method will allow you to attach as many functions as you like to the same event handler, even if the 1st or 2nd method has been used too.

Most likely, the problem lies somewhere in your CapacityChart() function. After visiting your link and running your script, the CapacityChart() function runs and the two popups are opened (one is closed as per the script). Where you have the following line:

CapacityWindow.document.write(s);

Try the following instead:

CapacityWindow.document.open("text/html");
CapacityWindow.document.write(s);
CapacityWindow.document.close();

EDIT
When I saw your code I thought you were writing it specifically for IE. As others have mentioned you will need to replace references to document.all with document.getElementById. However, you will still have the task of fixing the script after this so I would recommend getting it working in at least IE first as any mistakes you make changing the code to work cross browser could cause even more confusion. Once it's working in IE it will be easier to tell if it's working in other browsers whilst you're updating the code.

Why does the 'int' object is not callable error occur when using the sum() function?

You probably redefined your "sum" function to be an integer data type. So it is rightly telling you that an integer is not something you can pass a range.

To fix this, restart your interpreter.

Python 2.7.3 (default, Apr 20 2012, 22:44:07) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> data1 = range(0, 1000, 3)
>>> data2 = range(0, 1000, 5)
>>> data3 = list(set(data1 + data2)) # makes new list without duplicates
>>> total = sum(data3) # calculate sum of data3 list's elements
>>> print total
233168

If you shadow the sum builtin, you can get the error you are seeing

>>> sum = 0
>>> total = sum(data3) # calculate sum of data3 list's elements
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable

Also, note that sum will work fine on the set there is no need to convert it to a list

JSON: why are forward slashes escaped?

The JSON spec says you CAN escape forward slash, but you don't have to.

Diff files present in two different directories

Try this:

diff -rq /path/to/folder1 /path/to/folder2      

How to compare two JSON have the same properties without order?

This question reminds of how to determine equality for two JavaScript objects. So, I would choose this general function

Compares JS objects:

function objectEquals(x, y) {
    // if both are function
    if (x instanceof Function) {
        if (y instanceof Function) {
            return x.toString() === y.toString();
        }
        return false;
    }
    if (x === null || x === undefined || y === null || y === undefined) { return x === y; }
    if (x === y || x.valueOf() === y.valueOf()) { return true; }

    // if one of them is date, they must had equal valueOf
    if (x instanceof Date) { return false; }
    if (y instanceof Date) { return false; }

    // if they are not function or strictly equal, they both need to be Objects
    if (!(x instanceof Object)) { return false; }
    if (!(y instanceof Object)) { return false; }

    var p = Object.keys(x);
    return Object.keys(y).every(function (i) { return p.indexOf(i) !== -1; }) ?
            p.every(function (i) { return objectEquals(x[i], y[i]); }) : false;
}

How to center align the cells of a UICollectionView?

Swift 2.0 Works fine for me!

 func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
        let edgeInsets = (screenWight - (CGFloat(elements.count) * 50) - (CGFloat(elements.count) * 10)) / 2
        return UIEdgeInsetsMake(0, edgeInsets, 0, 0);
    }

Where: screenWight: basically its my collection's width (full screen width) - I made constants: let screenWight:CGFloat = UIScreen.mainScreen().bounds.width because self.view.bounds shows every-time 600 - coz of SizeClasses elements - array of cells 50 - my manual cell width 10 - my distance between cells

Setting Elastic search limit to "unlimited"

use the scan method e.g.

 curl -XGET 'localhost:9200/_search?search_type=scan&scroll=10m&size=50' -d '
 {
    "query" : {
       "match_all" : {}
     }
 }

see here

CURLOPT_RETURNTRANSFER set to true doesnt work on hosting server

If you set CURLOPT_RETURNTRANSFER to true or 1 then the return value from curl_exec will be the actual result from the successful operation. In other words it will not return TRUE on success. Although it will return FALSE on failure.

As described in the Return Values section of curl-exec PHP manual page: http://php.net/manual/function.curl-exec.php

You should enable the CURLOPT_FOLLOWLOCATION option for redirects but this would be a problem if your server is in safe_mode and/or open_basedir is in effect which can cause issues with curl as well.

Counting Number of Letters in a string variable

What is wrong with using string.Length?

// len will be 5
int len = "Hello".Length;

Returning http status code from Web Api controller

An update to @Aliostads answer using the more moden IHttpActionResult introduced in Web API 2.

https://docs.microsoft.com/en-us/aspnet/web-api/overview/getting-started-with-aspnet-web-api/action-results#ihttpactionresult

public class TryController : ApiController
{
    public IHttpActionResult GetUser(int userId, DateTime lastModifiedAtClient)
    {
        var user = new DataEntities().Users.First(p => p.Id == userId);
        if (user.LastModified <= lastModifiedAtClient)
        {
            return StatusCode(HttpStatusCode.NotModified);
            // If you would like to return a Http Status code with any object instead:
            // return Content(HttpStatusCode.InternalServerError, "My Message");
        }
        return Ok(user);
    }
}

Hash function for a string

-- The way to go these days --

Use SipHash. For your own protection.

-- Old and Dangerous --

unsigned int RSHash(const std::string& str)
{
    unsigned int b    = 378551;
    unsigned int a    = 63689;
    unsigned int hash = 0;

    for(std::size_t i = 0; i < str.length(); i++)
    {
        hash = hash * a + str[i];
        a    = a * b;
    }

    return (hash & 0x7FFFFFFF);
 }

 unsigned int JSHash(const std::string& str)
 {
      unsigned int hash = 1315423911;

      for(std::size_t i = 0; i < str.length(); i++)
      {
          hash ^= ((hash << 5) + str[i] + (hash >> 2));
      }

      return (hash & 0x7FFFFFFF);
 }

Ask google for "general purpose hash function"

How to reference static assets within vue javascript

A better solution would be

Adding some good practices and safity to @acdcjunior's answer, to use @ instead of ./

In JavaScript

require("@/assets/images/user-img-placeholder.png")

In JSX Template

<img src="@/assets/images/user-img-placeholder.png"/>

using @ points to the src directory.

using ~ points to the project root, which makes it easier to access the node_modules and other root level resources

center image in div with overflow hidden

Found this nice solution by MELISSA PENTA (https://www.localwisdom.com/)

HTML

<div class="wrapper">
   <img src="image.jpg" />
</div>

CSS

div.wrapper {
  height:200px;
  line-height:200px;
  overflow:hidden;
  text-align:center;
  width:200px;
}
div.wrapper img {
  margin:-100%;
}

Center any size image in div
Used with rounded wrapper and different sized images.

CSS

.item-image {
    border: 5px solid #ccc;
    border-radius: 100%;
    margin: 0 auto;
    height: 200px;
    width: 200px;
    overflow: hidden;
    text-align: center;
}
.item-image img {
    height: 200px;    
    margin: -100%;
    max-width: none;
    width: auto;    
}

Working example here codepen

How to change the CHARACTER SET (and COLLATION) throughout a database?

Adding to what David Whittaker posted, I have created a query that generates the complete table and columns alter statement that will convert each table. It may be a good idea to run

SET SESSION group_concat_max_len = 100000;

first to make sure your group concat doesn't go over the very small limit as seen here.

     SELECT a.table_name, concat('ALTER TABLE ', a.table_schema, '.', a.table_name, ' DEFAULT CHARACTER SET utf8mb4 DEFAULT COLLATE utf8mb4_unicode_ci, ',
        group_concat(distinct(concat(' MODIFY ',  column_name, ' ', column_type, ' CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci ', if (is_nullable = 'NO', ' NOT', ''), ' NULL ',
        if (COLUMN_DEFAULT is not null, CONCAT(' DEFAULT \'', COLUMN_DEFAULT, '\''), ''), if (EXTRA != '', CONCAT(' ', EXTRA), '')))), ';') as alter_statement
    FROM information_schema.columns a
    INNER JOIN INFORMATION_SCHEMA.TABLES b ON a.TABLE_CATALOG = b.TABLE_CATALOG
        AND a.TABLE_SCHEMA = b.TABLE_SCHEMA
        AND a.TABLE_NAME = b.TABLE_NAME
        AND b.table_type != 'view'
    WHERE a.table_schema = ? and (collation_name = 'latin1_swedish_ci' or collation_name = 'utf8mb4_general_ci')
    GROUP BY table_name;

A difference here between the previous answer is it was using utf8 instead of ut8mb4 and using t1.data_type with t1.CHARACTER_MAXIMUM_LENGTH didn't work for enums. Also, my query excludes views since those will have to altered separately.

I simply used a Perl script to return all these alters as an array and iterated over them, fixed the columns that were too long (generally they were varchar(256) when the data generally only had 20 characters in them so that was an easy fix).

I found some data was corrupted when altering from latin1 -> utf8mb4. It appeared to be utf8 encoded latin1 characters in columns would get goofed in the conversion. I simply held data from the columns I knew was going to be an issue in memory from before and after the alter and compared them and generated update statements to fix the data.

Find the index of a char in string?

Contanis occur if using the method of the present letter, and store the corresponding number using the IndexOf method, see example below.

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
    Dim myString As String = "abcdef"
    Dim numberString As String = String.Empty

    If myString.Contains("d") Then
        numberString = myString.IndexOf("d")
    End If
End Sub

Another sample with TextBox

  Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
    Dim myString As String = "abcdef"
    Dim numberString As String = String.Empty

    If myString.Contains(me.TextBox1.Text) Then
        numberString = myString.IndexOf(Me.TextBox1.Text)
    End If
End Sub

Regards

frequent issues arising in android view, Error parsing XML: unbound prefix

This error may occurs in the case you use un-defined prefix such as:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<TabHost
    XYZ:id="@android:id/tabhost"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >


</TabHost>

Android compiler does not know what is XYZ since it was not defined yet.

In your case, you should add below define to root node of the xml file.

xmlns:android="http://schemas.android.com/apk/res/android"

Convert datatable to JSON in C#

Pass the datable to this method it would return json String.

public DataTable GetTable()
        {
            string str = "Select * from GL_V";
            OracleCommand cmd = new OracleCommand(str, con);
            cmd.CommandType = CommandType.Text;
            DataTable Dt = OracleHelper.GetDataSet(con, cmd).Tables[0];

            return Dt;
        }

        public string DataTableToJSONWithJSONNet(DataTable table)
        {
            string JSONString = string.Empty;
            JSONString = JsonConvert.SerializeObject(table);
            return JSONString;
        }



public static DataSet GetDataSet(OracleConnection con, OracleCommand cmd)
        {
            // create the data set  
            DataSet ds = new DataSet();
            try
            {
                //checking current connection state is open
                if (con.State != ConnectionState.Open)
                    con.Open();

                // create a data adapter to use with the data set
                OracleDataAdapter da = new OracleDataAdapter(cmd);

                // fill the data set
                da.Fill(ds);
            }
            catch (Exception ex)
            {

                throw;
            }
            return ds;
        }

Calling constructors in c++ without new

Quite simply, both lines create the object on the stack, rather than on the heap as 'new' does. The second line actually involves a second call to a copy constructor, so it should be avoided (it also needs to be corrected as indicated in the comments). You should use the stack for small objects as much as possible since it is faster, however if your objects are going to survive for longer than the stack frame, then it's clearly the wrong choice.

How can I add a .npmrc file?

In MacOS Catalina 10.15.5 the .npmrc file path can be found at

/Users/<user-name>/.npmrc

Open in it in (for first time users, create a new file) any editor and copy-paste your token. Save it.

You are ready to go.

Note: As mentioned by @oligofren, the command npm config ls -l will npm configurations. You will get the .npmrc file from config parameter userconfig

Apache shows PHP code instead of executing it

This solution worked for me. I purged apache2 and reinstall. It happened after purge and install. If it is the first install, you would not face this problem.

ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)

In my case I was trying to pass a command to a container. In which case only the first word was interpreted. Ensure that you're not running:

mysql

as opposed to:

mysql -uroot -ppassword schemaname

perhaps try quoting:

'mysql -uroot -ppassword schemaname'

Javascript Array inside Array - how can I call the child array name?

You can't. The array doesn't have a name.

You just have two references to the array, one in the variable and another in the third array.

There is no way to find all the references that exist for a given object.

If the name is important, then store it with the data.

var size = { data: ["S", "M", "L", "XL", "XXL"], name: 'size' };
var color = { data: ["Red", "Blue", "Green", "White", "Black"], name: 'color' };
var options = [size, color];

Obviously you'll have to modify the existing code which accesses the data (since you now have options[0].data[0] instead of options[0][0] but you also have options[0].name).

Reading Email using Pop3 in C#

I wouldn't recommend OpenPOP. I just spent a few hours debugging an issue - OpenPOP's POPClient.GetMessage() was mysteriously returning null. I debugged this and found it was a string index bug - see the patch I submitted here: http://sourceforge.net/tracker/?func=detail&aid=2833334&group_id=92166&atid=599778. It was difficult to find the cause since there are empty catch{} blocks that swallow exceptions.

Also, the project is mostly dormant... the last release was in 2004.

For now we're still using OpenPOP, but I'll take a look at some of the other projects people have recommended here.

The specified DSN contains an architecture mismatch between the Driver and Application. JAVA

The problem you were facing might be because: you were having Office 32 bit and Command Prompt 64 bit. To solve the problem you need to follow 2 steps:

  1. Open ODBC Manager for DSN using: C:\Windows\SysWOW64\odbcad32.exe This will open the ODBC Data Administrator for 32 bit version and you will see all the database drivers.

  2. After this you need to open the 32 bit command prompt using: C:\Windows\SysWOW64\cmd.exe This will open the 32 bit version of command prompt. In this new CMD please recompile your Java program and run your program.

Hope this will help.

The difference between "require(x)" and "import x"

This simple diagram that helps me to understand the difference between require and import.

enter image description here

Apart from that,

You can't selectively load only the pieces you need with require but with imports, you can selectively load only the pieces you need. That can save memory.

Loading is synchronous(step by step) for require on the other hand import can be asynchronous(without waiting for previous import) so it can perform a little better than require.

How can I convert integer into float in Java?

Here is how you can do it :

public static void main(String[] args) {
    // TODO Auto-generated method stub
    int x = 3;
    int y = 2;
    Float fX = new Float(x);
    float res = fX.floatValue()/y;
    System.out.println("res = "+res);
}

See you !

Eclipse: stop code from running (java)

Open the Console view, locate the console for your running app and hit the Big Red Button.

Alternatively if you open the Debug perspective you will see all running apps in (by default) the top left. You can select the one that's causing you grief and once again hit the Big Red Button.enter image description here

Auto-expanding layout with Qt-Designer

I've tried to find a "fit to screen" property but there is no such.

But setting widget's "maximumSize" to a "some big number" ( like 2000 x 2000 ) will automatically fit the widget to the parent widget space.

Copy a file list as text from Windows Explorer

If you paste the listing into your word processor instead of Notepad, (since each file name is in quotation marks with the full path name), you can highlight all the stuff you don't want on the first file, then use Find and Replace to replace every occurrence of that with nothing. Same with the ending quote (").

It makes a nice clean list of file names.

jQuery count number of divs with a certain class?

<!DOCTYPE html>
    <html>
    <head>
        <title></title>
        <style type="text/css">
            .test {
                background: #ff4040;
                color: #fff;
                display: block;
                font-size: 15px;
            }
        </style>
    </head>
    <body>
        <div class="test"> one </div>
        <div class="test"> two </div>
        <div class="test"> three </div>
        <div class="test"> four </div>
        <div class="test"> five </div>
        <div class="test"> six </div>
        <div class="test"> seven </div>
        <div class="test"> eight </div>
        <div class="test"> nine </div>
        <div class="test"> ten </div>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <script type="text/javascript">
        $(document).ready(function () {
            //get total length by class
            var numItems = $('.test').length;
            //get last three count
            var numItems3=numItems-3;         


            var i = 0;
            $('.test').each(function(){
                i++;
                if(i>numItems3)
                {

                    $(this).attr("class","");
                }
            })
        });
    </script>
    </body>
    </html>

How to have Java method return generic list of any type?

You can use the old way:

public List magicalListGetter() {
    List list = doMagicalVooDooHere();

    return list;
}

or you can use Object and the parent class of everything:

public List<Object> magicalListGetter() {
    List<Object> list = doMagicalVooDooHere();

    return list;
}

Note Perhaps there is a better parent class for all the objects you will put in the list. For example, Number would allow you to put Double and Integer in there.

Difference between adjustResize and adjustPan in android?

From the Android Developer Site link

"adjustResize"

The activity's main window is always resized to make room for the soft keyboard on screen.

"adjustPan"

The activity's main window is not resized to make room for the soft keyboard. Rather, the contents of the window are automatically panned so that the current focus is never obscured by the keyboard and users can always see what they are typing. This is generally less desirable than resizing, because the user may need to close the soft keyboard to get at and interact with obscured parts of the window.

according to your comment, use following in your activity manifest

<activity android:windowSoftInputMode="adjustResize"> </activity>

Converting String to Cstring in C++

.c_str() returns a const char*. If you need a mutable version, you will need to produce a copy yourself.

Reactjs convert html string to jsx

By default, React escapes the HTML to prevent XSS (Cross-site scripting). If you really want to render HTML, you can use the dangerouslySetInnerHTML property:

<td dangerouslySetInnerHTML={{__html: this.state.actions}} />

React forces this intentionally-cumbersome syntax so that you don't accidentally render text as HTML and introduce XSS bugs.

What is the correct way to create a single-instance WPF application?

MSDN actually has a sample application for both C# and VB to do exactly this: http://msdn.microsoft.com/en-us/library/ms771662(v=VS.90).aspx

The most common and reliable technique for developing single-instance detection is to use the Microsoft .NET Framework remoting infrastructure (System.Remoting). The Microsoft .NET Framework (version 2.0) includes a type, WindowsFormsApplicationBase, which encapsulates the required remoting functionality. To incorporate this type into a WPF application, a type needs to derive from it, and be used as a shim between the application static entry point method, Main, and the WPF application's Application type. The shim detects when an application is first launched, and when subsequent launches are attempted, and yields control the WPF Application type to determine how to process the launches.

  • For C# people just take a deep breath and forget about the whole 'I don't wanna include VisualBasic DLL'. Because of this and what Scott Hanselman says and the fact that this pretty much is the cleanest solution to the problem and is designed by people who know a lot more about the framework than you do.
  • From a usability standpoint the fact is if your user is loading an application and it is already open and you're giving them an error message like 'Another instance of the app is running. Bye' then they're not gonna be a very happy user. You simply MUST (in a GUI application) switch to that application and pass in the arguments provided - or if command line parameters have no meaning then you must pop up the application which may have been minimized.

The framework already has support for this - its just that some idiot named the DLL Microsoft.VisualBasic and it didn't get put into Microsoft.ApplicationUtils or something like that. Get over it - or open up Reflector.

Tip: If you use this approach exactly as is, and you already have an App.xaml with resources etc. you'll want to take a look at this too.

Scanner vs. BufferedReader

Following are the differences between BufferedReader and Scanner

  1. BufferedReader only read data but scanner also parse data.
  2. you can only read String using BufferedReader, but you can read int, long or float using Scanner.
  3. BufferedReader is older from Scanner,it exists from jdk 1.1 while Scanner was added on JDK 5 release.
  4. The Buffer size of BufferedReader is large(8KB) as compared to 1KB of Scanner.
  5. BufferedReader is more suitable for reading file with long String while Scanner is more suitable for reading small user input from command prompt.
  6. BufferedReader is synchronized but Scanner is not, which means you cannot share Scanner among multiple threads.
  7. BufferedReader is faster than Scanner because it doesn't spent time on parsing
  8. BufferedReader is a bit faster as compared to Scanner
  9. BufferedReader is from java.io package and Scanner is from java.util package on basis of the points we can select our choice.

Thanks

R for loop skip to next iteration ifelse

for(n in 1:5) {
  if(n==3) next # skip 3rd iteration and go to next iteration
  cat(n)
}

Catch checked change event of a checkbox

This code does what your need:

<input type="checkbox" id="check" >check it</input>

$("#check").change( function(){
   if( $(this).is(':checked') ) {
        alert("checked");
    }else{
        alert("unchecked");
   }
});

Also, you can check it on jsfiddle

'router-outlet' is not a known element

Here is the Quick and Simple Solution if anyone is getting the error:

"'router-outlet' is not a known element" in angular project,

Then,

Just go to the "app.module.ts" file & add the following Line:

import { AppRoutingModule } from './app-routing.module';

And also 'AppRoutingModule' in imports.

IE9 JavaScript error: SCRIPT5007: Unable to get value of the property 'ui': object is null or undefined

I was having same issue in IE9. I followed the above answer and I added the line:

<meta http-equiv="X-UA-Compatible" content="IE=8;FF=3;OtherUA=4" />

in my <head> and it worked.

Property 'json' does not exist on type 'Object'

The other way to tackle it is to use this code snippet:

JSON.parse(JSON.stringify(response)).data

This feels so wrong but it works

How do I check out an SVN project into Eclipse as a Java project?

Here are the steps:

  • Install the subclipse plugin (provides svn connectivity in eclipse) and connect to the repository. Instructions here: http://subclipse.tigris.org/install.html
  • Go to File->New->Other->Under the SVN category, select Checkout Projects from SVN.
  • Select your project's root folder and select checkout as a project in the workspace.

It seems you are checking the .project file into the source repository. I would suggest not checking in the .project file so users can have their own version of the file. Also, if you use the subclipse plugin it allows you to check out and configure a source folder as a java project. This process creates the correct .project for you(with the java nature),

Mean per group in a data.frame

This type of operation is exactly what aggregate was designed for:

d <- read.table(text=
'Name     Month  Rate1     Rate2
Aira       1      12        23
Aira       2      18        73
Aira       3      19        45
Ben        1      53        19
Ben        2      22        87
Ben        3      19        45
Cat        1      22        87
Cat        2      67        43
Cat        3      45        32', header=TRUE)

aggregate(d[, 3:4], list(d$Name), mean)

  Group.1    Rate1    Rate2
1    Aira 16.33333 47.00000
2     Ben 31.33333 50.33333
3     Cat 44.66667 54.00000

Here we aggregate columns 3 and 4 of data.frame d, grouping by d$Name, and applying the mean function.


Or, using a formula interface:

aggregate(. ~ Name, d[-2], mean)

JavaScript unit test tools for TDD

MochiKit has a testing framework called SimpleTest that seems to have caught on. Here's a blog post from the original author.

How to automatically close cmd window after batch file execution?

If you want to separate the commands into one command per file, you can do

cmd /c start C:\Users\Yiwei\Downloads\putty.exe -load "MathCS-labMachine1"

and in the other file, you can do

cmd /c start "" "C:\Program Files (x86)\Xming\Xming.exe" :0 -clipboard -multiwindow

The command cmd /c will close the command-prompt window after the exe was run.

Can you change what a symlink points to after it is created?

Just a warning to the correct answers above:

Using the -f / --force Method provides a risk to lose the file if you mix up source and target:

mbucher@server2:~/test$ ls -la
total 11448
drwxr-xr-x  2 mbucher www-data    4096 May 25 15:27 .
drwxr-xr-x 18 mbucher www-data    4096 May 25 15:13 ..
-rw-r--r--  1 mbucher www-data 4109466 May 25 15:26 data.tar.gz
-rw-r--r--  1 mbucher www-data 7582480 May 25 15:27 otherdata.tar.gz
lrwxrwxrwx  1 mbucher www-data      11 May 25 15:26 thesymlink -> data.tar.gz
mbucher@server2:~/test$ 
mbucher@server2:~/test$ ln -s -f thesymlink otherdata.tar.gz 
mbucher@server2:~/test$ 
mbucher@server2:~/test$ ls -la
total 4028
drwxr-xr-x  2 mbucher www-data    4096 May 25 15:28 .
drwxr-xr-x 18 mbucher www-data    4096 May 25 15:13 ..
-rw-r--r--  1 mbucher www-data 4109466 May 25 15:26 data.tar.gz
lrwxrwxrwx  1 mbucher www-data      10 May 25 15:28 otherdata.tar.gz -> thesymlink
lrwxrwxrwx  1 mbucher www-data      11 May 25 15:26 thesymlink -> data.tar.gz

Of course this is intended, but usually mistakes occur. So, deleting and rebuilding the symlink is a bit more work but also a bit saver:

mbucher@server2:~/test$ rm thesymlink && ln -s thesymlink otherdata.tar.gz 
ln: creating symbolic link `otherdata.tar.gz': File exists

which at least keeps my file.

Load vs. Stress testing

Load testing = putting a specified amount of load on the server for certain amount of time. 100 simultaneous users for 10 minutes. Ensure stability of software. Stress testing = increasing the amount of load steadily until the software crashes. 10 simultaneous users increasing every 2 minutes until the server crashes.

To make a comparison to weight lifting: You "max" your weight to see what you can do for 1 rep (stress testing) and then on regular workouts you do 85% of your max value for 3 sets of 10 reps (load testing)

How to detect Esc Key Press in React and how to handle it

React uses SyntheticKeyboardEvent to wrap native browser event and this Synthetic event provides named key attribute,
which you can use like this:

handleOnKeyDown = (e) => {
  if (['Enter', 'ArrowRight', 'Tab'].includes(e.key)) {
    // select item
    e.preventDefault();
  } else if (e.key === 'ArrowUp') {
    // go to top item
    e.preventDefault();
  } else if (e.key === 'ArrowDown') {
    // go to bottom item
    e.preventDefault();
  } else if (e.key === 'Escape') {
    // escape
    e.preventDefault();
  }
};

Installing PDO driver on MySQL Linux server

On Ubuntu you should be able to install the necessary PDO parts from apt using sudo apt-get install php5-mysql

There is no limitation between using PDO and mysql_ simultaneously. You will however need to create two connections to your DB, one with mysql_ and one using PDO.

How do I install the Nuget provider for PowerShell on a unconnected machine so I can install a nuget package from the PS command line?

MSDocs state this for your scenario:

In order to execute the first time, PackageManagement requires an internet connection to download the Nuget package provider. However, if your computer does not have an internet connection and you need to use the Nuget or PowerShellGet provider, you can download them on another computer and copy them to your target computer. Use the following steps to do this:

  1. Run Install-PackageProvider -Name NuGet -RequiredVersion 2.8.5.201 -Force to install the provider from a computer with an internet connection.

  2. After the install, you can find the provider installed in $env:ProgramFiles\PackageManagement\ReferenceAssemblies\\\<ProviderName\>\\\<ProviderVersion\> or $env:LOCALAPPDATA\PackageManagement\ProviderAssemblies\\\<ProviderName\>\\\<ProviderVersion\>.

  3. Place the folder, which in this case is the Nuget folder, in the corresponding location on your target computer. If your target computer is a Nano server, you need to run Install-PackageProvider from Nano Server to download the correct Nuget binaries.

  4. Restart PowerShell to auto-load the package provider. Alternatively, run Get-PackageProvider -ListAvailable to list all the package providers available on the computer. Then use Import-PackageProvider -Name NuGet -RequiredVersion 2.8.5.201 to import the provider to the current Windows PowerShell session.

How ViewBag in ASP.NET MVC works

ViewBag is of type dynamic. More, you cannot do ViewBag["Foo"]. You will get exception - Cannot apply indexing with [] to an expression of type 'System.Dynamic.DynamicObject'.

Internal implementation of ViewBag actually stores Foo into ViewData["Foo"] (type of ViewDataDictionary), so those 2 are interchangeable. ViewData["Foo"] and ViewBag.Foo.

And scope. ViewBag and ViewData are ment to pass data between Controller's Actions and View it renders.

Error - Android resource linking failed (AAPT2 27.0.3 Daemon #0)

I was having similar problem but I came out of the solution the problem was that you were using any thing in the dependency that correspond to same domain but with different versions make sure those all are same

How to tackle daylight savings using TimeZone in Java

Implementing the TimeZone class to set the timezone to the Calendar takes care of the daylight savings.

java.util.TimeZone represents a time zone offset, and also figures out daylight savings.

sample code:

TimeZone est_timeZone = TimeZoneIDProvider.getTimeZoneID(TimeZoneID.US_EASTERN).getTimeZone();
Calendar enteredCalendar = Calendar.getInstance();
enteredCalendar.setTimeZone(est_timeZone);

How to get client's IP address using JavaScript?

All the above answers have a server part, not pure client part. This should be provided by the web browser. At present, no web browser support this.

However, with this addon for firefox: https://addons.mozilla.org/en-US/firefox/addon/ip-address/ You will have to ask your users to install this addon. (it's good from me, a 3rd party).

you can test whether the user has installed it.

var installed=window.IP!==undefined;

you can get it with javascript, if it is installed, then var ip=IP.getClient(); var IPclient=ip.IP; //while ip.url is the url

ip=IP.getServer();
var IPserver=ip.IP;
var portServer=ip.port;
//while ip.url is the url

//or you can use IP.getBoth();

more information here: http://www.jackiszhp.info/tech/addon.IP.html

MINGW64 "make build" error: "bash: make: command not found"

Try using cmake itself. In the build directory, run:

cmake --build .

What is the difference between String and string in C#?

There is practically no difference

The C# keyword string maps to the .NET type System.String - it is an alias that keeps to the naming conventions of the language.

Raise warning in Python without interrupting program

By default, unlike an exception, a warning doesn't interrupt.

After import warnings, it is possible to specify a Warnings class when generating a warning. If one is not specified, it is literally UserWarning by default.

>>> warnings.warn('This is a default warning.')
<string>:1: UserWarning: This is a default warning.

To simply use a preexisting class instead, e.g. DeprecationWarning:

>>> warnings.warn('This is a particular warning.', DeprecationWarning)
<string>:1: DeprecationWarning: This is a particular warning.

Creating a custom warning class is similar to creating a custom exception class:

>>> class MyCustomWarning(UserWarning):
...     pass
... 
... warnings.warn('This is my custom warning.', MyCustomWarning)

<string>:1: MyCustomWarning: This is my custom warning.

For testing, consider assertWarns or assertWarnsRegex.


As an alternative, especially for standalone applications, consider the logging module. It can log messages having a level of debug, info, warning, error, etc. Log messages having a level of warning or higher are by default printed to stderr.

Using lambda expressions for event handlers

Performance-wise it's the same as a named method. The big problem is when you do the following:

MyButton.Click -= (o, i) => 
{ 
    //snip 
} 

It will probably try to remove a different lambda, leaving the original one there. So the lesson is that it's fine unless you also want to be able to remove the handler.

Recursive Fibonacci

I think that all that solutions are inefficient. They require a lot of recursive calls to get the result.

unsigned fib(unsigned n) {
    if(n == 0) return 0;
    if(n == 1) return 1;
    return fib(n-1) + fib(n-2);
}

This code requires 14 calls to get result for fib(5), 177 for fin(10) and 2.7kk for fib(30).

You should better use this approach or if you want to use recursion try this:

unsigned fib(unsigned n, unsigned prev1 = 0, unsigned prev2 = 1, int depth = 2)     
{
    if(n == 0) return 0;
    if(n == 1) return 1;
    if(depth < n) return fib(n, prev2, prev1+prev2, depth+1);
    return prev1+prev2;
}

This function requires n recursive calls to calculate Fibonacci number for n. You can still use it by calling fib(10) because all other parameters have default values.

"Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset" using PHP

Error display @ operator

For undesired and redundant notices, one could use the dedicated @ operator to »hide« undefined variable/index messages.

$var = @($_GET["optional_param"]);
  • This is usually discouraged. Newcomers tend to way overuse it.
  • It's very inappropriate for code deep within the application logic (ignoring undeclared variables where you shouldn't), e.g. for function parameters, or in loops.
  • There's one upside over the isset?: or ?? super-supression however. Notices still can get logged. And one may resurrect @-hidden notices with: set_error_handler("var_dump");
    • Additonally you shouldn't habitually use/recommend if (isset($_POST["shubmit"])) in your initial code.
    • Newcomers won't spot such typos. It just deprives you of PHPs Notices for those very cases. Add @ or isset only after verifying functionality.
    • Fix the cause first. Not the notices.

  • @ is mainly acceptable for $_GET/$_POST input parameters, specifically if they're optional.

And since this covers the majority of such questions, let's expand on the most common causes:

$_GET / $_POST / $_REQUEST undefined input

  • First thing you do when encountering an undefined index/offset, is check for typos:
    $count = $_GET["whatnow?"];

    • Is this an expected key name and present on each page request?
    • Variable names and array indicies are case-sensitive in PHP.
  • Secondly, if the notice doesn't have an obvious cause, use var_dump or print_r to verify all input arrays for their curent content:

    var_dump($_GET);
    var_dump($_POST);
    //print_r($_REQUEST);
    

    Both will reveal if your script was invoked with the right or any parameters at all.

  • Alternativey or additionally use your browser devtools (F12) and inspect the network tab for requests and parameters:

    browser developer tools / network tab

    POST parameters and GET input will be be shown separately.

  • For $_GET parameters you can also peek at the QUERY_STRING in

    print_r($_SERVER);
    

    PHP has some rules to coalesce non-standard parameter names into the superglobals. Apache might do some rewriting as well. You can also look at supplied raw $_COOKIES and other HTTP request headers that way.

  • More obviously look at your browser address bar for GET parameters:

    http://example.org/script.php?id=5&sort=desc

    The name=value pairs after the ? question mark are your query (GET) parameters. Thus this URL could only possibly yield $_GET["id"] and $_GET["sort"].

  • Finally check your <form> and <input> declarations, if you expect a parameter but receive none.

    • Ensure each required input has an <input name=FOO>
    • The id= or title= attribute does not suffice.
    • A method=POST form ought to populate $_POST.
    • Whereas a method=GET (or leaving it out) would yield $_GET variables.
    • It's also possible for a form to supply action=script.php?get=param via $_GET and the remaining method=POST fields in $_POST alongside.
    • With modern PHP configurations (= 5.6) it has become feasible (not fashionable) to use $_REQUEST['vars'] again, which mashes GET and POST params.
  • If you are employing mod_rewrite, then you should check both the access.log as well as enable the RewriteLog to figure out absent parameters.

$_FILES

  • The same sanity checks apply to file uploads and $_FILES["formname"].
  • Moreover check for enctype=multipart/form-data
  • As well as method=POST in your <form> declaration.
  • See also: PHP Undefined index error $_FILES?

$_COOKIE

  • The $_COOKIE array is never populated right after setcookie(), but only on any followup HTTP request.
  • Additionally their validity times out, they could be constraint to subdomains or individual paths, and user and browser can just reject or delete them.

how to add lines to existing file using python

Open the file for 'append' rather than 'write'.

with open('file.txt', 'a') as file:
    file.write('input')

MySQL JOIN ON vs USING?

Database tables

To demonstrate how the USING and ON clauses work, let's assume we have the following post and post_comment database tables, which form a one-to-many table relationship via the post_id Foreign Key column in the post_comment table referencing the post_id Primary Key column in the post table:

SQL USING vs ON clauses table relationship

The parent post table has 3 rows:

| post_id | title     |
|---------|-----------|
| 1       | Java      |
| 2       | Hibernate |
| 3       | JPA       |

and the post_comment child table has the 3 records:

| post_comment_id | review    | post_id |
|-----------------|-----------|---------|
| 1               | Good      | 1       |
| 2               | Excellent | 1       |
| 3               | Awesome   | 2       |

The JOIN ON clause using a custom projection

Traditionally, when writing an INNER JOIN or LEFT JOIN query, we happen to use the ON clause to define the join condition.

For example, to get the comments along with their associated post title and identifier, we can use the following SQL projection query:

SELECT
   post.post_id,
   title,
   review
FROM post
INNER JOIN post_comment ON post.post_id = post_comment.post_id
ORDER BY post.post_id, post_comment_id

And, we get back the following result set:

| post_id | title     | review    |
|---------|-----------|-----------|
| 1       | Java      | Good      |
| 1       | Java      | Excellent |
| 2       | Hibernate | Awesome   |

The JOIN USING clause using a custom projection

When the Foreign Key column and the column it references have the same name, we can use the USING clause, like in the following example:

SELECT
  post_id,
  title,
  review
FROM post
INNER JOIN post_comment USING(post_id)
ORDER BY post_id, post_comment_id

And, the result set for this particular query is identical to the previous SQL query that used the ON clause:

| post_id | title     | review    |
|---------|-----------|-----------|
| 1       | Java      | Good      |
| 1       | Java      | Excellent |
| 2       | Hibernate | Awesome   |

The USING clause works for Oracle, PostgreSQL, MySQL, and MariaDB. SQL Server doesn't support the USING clause, so you need to use the ON clause instead.

The USING clause can be used with INNER, LEFT, RIGHT, and FULL JOIN statements.

SQL JOIN ON clause with SELECT *

Now, if we change the previous ON clause query to select all columns using SELECT *:

SELECT *
FROM post
INNER JOIN post_comment ON post.post_id = post_comment.post_id
ORDER BY post.post_id, post_comment_id

We are going to get the following result set:

| post_id | title     | post_comment_id | review    | post_id |
|---------|-----------|-----------------|-----------|---------|
| 1       | Java      | 1               | Good      | 1       |
| 1       | Java      | 2               | Excellent | 1       |
| 2       | Hibernate | 3               | Awesome   | 2       |

As you can see, the post_id is duplicated because both the post and post_comment tables contain a post_id column.

SQL JOIN USING clause with SELECT *

On the other hand, if we run a SELECT * query that features the USING clause for the JOIN condition:

SELECT *
FROM post
INNER JOIN post_comment USING(post_id)
ORDER BY post_id, post_comment_id

We will get the following result set:

| post_id | title     | post_comment_id | review    |
|---------|-----------|-----------------|-----------|
| 1       | Java      | 1               | Good      |
| 1       | Java      | 2               | Excellent |
| 2       | Hibernate | 3               | Awesome   |

You can see that this time, the post_id column is deduplicated, so there is a single post_id column being included in the result set.

Conclusion

If the database schema is designed so that Foreign Key column names match the columns they reference, and the JOIN conditions only check if the Foreign Key column value is equal to the value of its mirroring column in the other table, then you can employ the USING clause.

Otherwise, if the Foreign Key column name differs from the referencing column or you want to include a more complex join condition, then you should use the ON clause instead.

Convert StreamReader to byte[]

For everyone saying to get the bytes, copy it to MemoryStream, etc. - if the content isn't expected to be larger than computer's memory should be reasonably be expected to allow, why not just use StreamReader's built in ReadLine() or ReadToEnd()? I saw these weren't even mentioned, and they do everything for you.

I had a use-case where I just wanted to store the path of a SQLite file from a FileDialogResult that the user picks during the synching/initialization process. My program then later needs to use this path when it is run for normal application processes. Maybe not the ideal way to capture/re-use the information, but it's not much different than writing to/reading from an .ini file - I just didn't want to set one up for one value. So I just read it from a flat, one-line text file. Here's what I did:

string filePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
if (!filePath.EndsWith(@"\")) temppath += @"\"; // ensures we have a slash on the end
filePath = filePath.Replace(@"\\", @"\"); // Visual Studio escapes slashes by putting double-slashes in their results - this ensures we don't have double-slashes
filePath += "SQLite.txt";

string path = String.Empty;
FileStream fs = new FileStream(filePath, FileMode.Open);
StreamReader sr = new StreamReader(fs);
path = sr.ReadLine();  // can also use sr.ReadToEnd();
sr.Close();
fs.Close();
fs.Flush();

return path;

If you REALLY need a byte[] instead of a string for some reason, using my example, you can always do:

byte[] toBytes;
FileStream fs = new FileStream(filePath, FileMode.Open);
StreamReader sr = new StreamReader(fs);
toBytes = Encoding.ASCII.GetBytes(path);
sr.Close();
fs.Close();
fs.Flush();

return toBytes;

(Returning toBytes instead of path.)

If you don't want ASCII you can easily replace that with UTF8, Unicode, etc.

java.io.FileNotFoundException: the system cannot find the file specified

I was reading path from a properties file and didn't mention there was a space in the end. Make sure you don't have one.

How can I calculate the difference between two ArrayLists?

In Java 8 with streams, it's pretty simple actually. EDIT: Can be efficient without streams, see lower.

List<String> listA = Arrays.asList("2009-05-18","2009-05-19","2009-05-21");
List<String> listB = Arrays.asList("2009-05-18","2009-05-18","2009-05-19","2009-05-19",
                                   "2009-05-20","2009-05-21","2009-05-21","2009-05-22");

List<String> result = listB.stream()
                           .filter(not(new HashSet<>(listA)::contains))
                           .collect(Collectors.toList());

Note that the hash set is only created once: The method reference is tied to its contains method. Doing the same with lambda would require having the set in a variable. Making a variable is not a bad idea, especially if you find it unsightly or harder to understand.

You can't easily negate the predicate without something like this utility method (or explicit cast), as you can't call the negate method reference directly (type inference is needed first).

private static <T> Predicate<T> not(Predicate<T> predicate) {
    return predicate.negate();
}

If streams had a filterOut method or something, it would look nicer.


Also, @Holger gave me an idea. ArrayList has its removeAll method optimized for multiple removals, it only rearranges its elements once. However, it uses the contains method provided by given collection, so we need to optimize that part if listA is anything but tiny.

With listA and listB declared previously, this solution doesn't need Java 8 and it's very efficient.

List<String> result = new ArrayList(listB);
result.removeAll(new HashSet<>(listA));

How can I initialize an array without knowing it size?

You can't... an array's size is always fixed in Java. Typically instead of using an array, you'd use an implementation of List<T> here - usually ArrayList<T>, but with plenty of other alternatives available.

You can create an array from the list as a final step, of course - or just change the signature of the method to return a List<T> to start with.

How to tell if a string contains a certain character in JavaScript?

To test for alphanumeric characters only:

if (/^[0-9A-Za-z]+$/.test(yourString))
{
    //there are only alphanumeric characters
}
else
{
    //it contains other characters
}

The regex is testing for 1 or more (+) of the set of characters 0-9, A-Z, and a-z, starting with the beginning of input (^) and stopping with the end of input ($).

Should URL be case sensitive?

Depends on the hosting os. Sites that are hosted on Windows tend to be case insensitive as the underlying file system is case insensitive. Sites hosted on Unix type systems tend to be case sensitive as their underlying file systems are typically case sensitive. The host name part of the URL is always case insensitive, it's the rest of the path that varies.

How to auto generate migrations with Sequelize CLI from Sequelize models?

I have recently tried the following approach which seems to work fine, although I am not 100% sure if there might be any side effects:

'use strict';

import * as models from "../../models";

module.exports = {

  up: function (queryInterface, Sequelize) {

    return queryInterface.createTable(models.Role.tableName, models.Role.attributes)
    .then(() => queryInterface.createTable(models.Team.tableName, models.Team.attributes))
    .then(() => queryInterface.createTable(models.User.tableName, models.User.attributes))

  },

  down: function (queryInterface, Sequelize) {
    ...
  }

};

When running the migration above using sequelize db:migrate, my console says:

Starting 'db:migrate'...
Finished 'db:migrate' after 91 ms
== 20160113121833-create-tables: migrating =======
== 20160113121833-create-tables: migrated (0.518s)

All the tables are there, everything (at least seems to) work as expected. Even all the associations are there if they are defined correctly.

Case-insensitive search

I noticed that if the user enters a string of text but leaves the input without selecting any of the autocomplete options no value is set in the hidden input, even if the string coincides with one in the array. So, with help of the other answers I made this:

var $local_source = [{
        value: 1,
        label: "c++"
    }, {
        value: 2,
        label: "java"
    }, {
        value: 3,
        label: "php"
    }, {
        value: 4,
        label: "coldfusion"
    }, {
        value: 5,
        label: "javascript"
    }, {
        value: 6,
        label: "asp"
    }, {
        value: 7,
        label: "ruby"
    }];
    $('#search-fld').autocomplete({
        source: $local_source,
        select: function (event, ui) {
            $("#search-fld").val(ui.item.label); // display the selected text
            $("#search-fldID").val(ui.item.value); // save selected id to hidden input
            return false;
        },
        change: function( event, ui ) {

            var isInArray = false;

            $local_source.forEach(function(element, index){

                if ($("#search-fld").val().toUpperCase() == element.label.toUpperCase()) {
                    isInArray = true;
                    $("#search-fld").val(element.label); // display the selected text
                    $("#search-fldID").val(element.value); // save selected id to hidden input
                    console.log('inarray: '+isInArray+' label: '+element.label+' value: '+element.value);
                };

            });

            if(!isInArray){

                $("#search-fld").val(''); // display the selected text
                $( "#search-fldID" ).val( ui.item? ui.item.value : 0 );

            }
        } 

Extending from two classes

it is possible

public class ParallaxViewController<T extends View & Parallaxor> extends ParallaxController<T> implements AbsListView.OnScrollListener {

//blah
}

How to "perfectly" override a dict?

How can I make as "perfect" a subclass of dict as possible?

The end goal is to have a simple dict in which the keys are lowercase.

  • If I override __getitem__/__setitem__, then get/set don't work. How do I make them work? Surely I don't need to implement them individually?

  • Am I preventing pickling from working, and do I need to implement __setstate__ etc?

  • Do I need repr, update and __init__?

  • Should I just use mutablemapping (it seems one shouldn't use UserDict or DictMixin)? If so, how? The docs aren't exactly enlightening.

The accepted answer would be my first approach, but since it has some issues, and since no one has addressed the alternative, actually subclassing a dict, I'm going to do that here.

What's wrong with the accepted answer?

This seems like a rather simple request to me:

How can I make as "perfect" a subclass of dict as possible? The end goal is to have a simple dict in which the keys are lowercase.

The accepted answer doesn't actually subclass dict, and a test for this fails:

>>> isinstance(MyTransformedDict([('Test', 'test')]), dict)
False

Ideally, any type-checking code would be testing for the interface we expect, or an abstract base class, but if our data objects are being passed into functions that are testing for dict - and we can't "fix" those functions, this code will fail.

Other quibbles one might make:

  • The accepted answer is also missing the classmethod: fromkeys.
  • The accepted answer also has a redundant __dict__ - therefore taking up more space in memory:

    >>> s.foo = 'bar'
    >>> s.__dict__
    {'foo': 'bar', 'store': {'test': 'test'}}
    

Actually subclassing dict

We can reuse the dict methods through inheritance. All we need to do is create an interface layer that ensures keys are passed into the dict in lowercase form if they are strings.

If I override __getitem__/__setitem__, then get/set don't work. How do I make them work? Surely I don't need to implement them individually?

Well, implementing them each individually is the downside to this approach and the upside to using MutableMapping (see the accepted answer), but it's really not that much more work.

First, let's factor out the difference between Python 2 and 3, create a singleton (_RaiseKeyError) to make sure we know if we actually get an argument to dict.pop, and create a function to ensure our string keys are lowercase:

from itertools import chain
try:              # Python 2
    str_base = basestring
    items = 'iteritems'
except NameError: # Python 3
    str_base = str, bytes, bytearray
    items = 'items'

_RaiseKeyError = object() # singleton for no-default behavior

def ensure_lower(maybe_str):
    """dict keys can be any hashable object - only call lower if str"""
    return maybe_str.lower() if isinstance(maybe_str, str_base) else maybe_str

Now we implement - I'm using super with the full arguments so that this code works for Python 2 and 3:

class LowerDict(dict):  # dicts take a mapping or iterable as their optional first argument
    __slots__ = () # no __dict__ - that would be redundant
    @staticmethod # because this doesn't make sense as a global function.
    def _process_args(mapping=(), **kwargs):
        if hasattr(mapping, items):
            mapping = getattr(mapping, items)()
        return ((ensure_lower(k), v) for k, v in chain(mapping, getattr(kwargs, items)()))
    def __init__(self, mapping=(), **kwargs):
        super(LowerDict, self).__init__(self._process_args(mapping, **kwargs))
    def __getitem__(self, k):
        return super(LowerDict, self).__getitem__(ensure_lower(k))
    def __setitem__(self, k, v):
        return super(LowerDict, self).__setitem__(ensure_lower(k), v)
    def __delitem__(self, k):
        return super(LowerDict, self).__delitem__(ensure_lower(k))
    def get(self, k, default=None):
        return super(LowerDict, self).get(ensure_lower(k), default)
    def setdefault(self, k, default=None):
        return super(LowerDict, self).setdefault(ensure_lower(k), default)
    def pop(self, k, v=_RaiseKeyError):
        if v is _RaiseKeyError:
            return super(LowerDict, self).pop(ensure_lower(k))
        return super(LowerDict, self).pop(ensure_lower(k), v)
    def update(self, mapping=(), **kwargs):
        super(LowerDict, self).update(self._process_args(mapping, **kwargs))
    def __contains__(self, k):
        return super(LowerDict, self).__contains__(ensure_lower(k))
    def copy(self): # don't delegate w/ super - dict.copy() -> dict :(
        return type(self)(self)
    @classmethod
    def fromkeys(cls, keys, v=None):
        return super(LowerDict, cls).fromkeys((ensure_lower(k) for k in keys), v)
    def __repr__(self):
        return '{0}({1})'.format(type(self).__name__, super(LowerDict, self).__repr__())

We use an almost boiler-plate approach for any method or special method that references a key, but otherwise, by inheritance, we get methods: len, clear, items, keys, popitem, and values for free. While this required some careful thought to get right, it is trivial to see that this works.

(Note that haskey was deprecated in Python 2, removed in Python 3.)

Here's some usage:

>>> ld = LowerDict(dict(foo='bar'))
>>> ld['FOO']
'bar'
>>> ld['foo']
'bar'
>>> ld.pop('FoO')
'bar'
>>> ld.setdefault('Foo')
>>> ld
{'foo': None}
>>> ld.get('Bar')
>>> ld.setdefault('Bar')
>>> ld
{'bar': None, 'foo': None}
>>> ld.popitem()
('bar', None)

Am I preventing pickling from working, and do I need to implement __setstate__ etc?

pickling

And the dict subclass pickles just fine:

>>> import pickle
>>> pickle.dumps(ld)
b'\x80\x03c__main__\nLowerDict\nq\x00)\x81q\x01X\x03\x00\x00\x00fooq\x02Ns.'
>>> pickle.loads(pickle.dumps(ld))
{'foo': None}
>>> type(pickle.loads(pickle.dumps(ld)))
<class '__main__.LowerDict'>

__repr__

Do I need repr, update and __init__?

We defined update and __init__, but you have a beautiful __repr__ by default:

>>> ld # without __repr__ defined for the class, we get this
{'foo': None}

However, it's good to write a __repr__ to improve the debugability of your code. The ideal test is eval(repr(obj)) == obj. If it's easy to do for your code, I strongly recommend it:

>>> ld = LowerDict({})
>>> eval(repr(ld)) == ld
True
>>> ld = LowerDict(dict(a=1, b=2, c=3))
>>> eval(repr(ld)) == ld
True

You see, it's exactly what we need to recreate an equivalent object - this is something that might show up in our logs or in backtraces:

>>> ld
LowerDict({'a': 1, 'c': 3, 'b': 2})

Conclusion

Should I just use mutablemapping (it seems one shouldn't use UserDict or DictMixin)? If so, how? The docs aren't exactly enlightening.

Yeah, these are a few more lines of code, but they're intended to be comprehensive. My first inclination would be to use the accepted answer, and if there were issues with it, I'd then look at my answer - as it's a little more complicated, and there's no ABC to help me get my interface right.

Premature optimization is going for greater complexity in search of performance. MutableMapping is simpler - so it gets an immediate edge, all else being equal. Nevertheless, to lay out all the differences, let's compare and contrast.

I should add that there was a push to put a similar dictionary into the collections module, but it was rejected. You should probably just do this instead:

my_dict[transform(key)]

It should be far more easily debugable.

Compare and contrast

There are 6 interface functions implemented with the MutableMapping (which is missing fromkeys) and 11 with the dict subclass. I don't need to implement __iter__ or __len__, but instead I have to implement get, setdefault, pop, update, copy, __contains__, and fromkeys - but these are fairly trivial, since I can use inheritance for most of those implementations.

The MutableMapping implements some things in Python that dict implements in C - so I would expect a dict subclass to be more performant in some cases.

We get a free __eq__ in both approaches - both of which assume equality only if another dict is all lowercase - but again, I think the dict subclass will compare more quickly.

Summary:

  • subclassing MutableMapping is simpler with fewer opportunities for bugs, but slower, takes more memory (see redundant dict), and fails isinstance(x, dict)
  • subclassing dict is faster, uses less memory, and passes isinstance(x, dict), but it has greater complexity to implement.

Which is more perfect? That depends on your definition of perfect.

Java RegEx meta character (.) and ordinary dot?

Perl-style regular expressions (which the Java regex engine is more or less based upon) treat the following characters as special characters:

.^$|*+?()[{\ have special meaning outside of character classes,

]^-\ have special meaning inside of character classes ([...]).

So you need to escape those (and only those) symbols depending on context (or, in the case of character classes, place them in positions where they can't be misinterpreted).

Needlessly escaping other characters may work, but some regex engines will treat this as syntax errors, for example \_ will cause an error in .NET.

Some others will lead to false results, for example \< is interpreted as a literal < in Perl, but in egrep it means "word boundary".

So write -?\d+\.\d+\$ to match 1.50$, -2.00$ etc. and [(){}[\]] for a character class that matches all kinds of brackets/braces/parentheses.

If you need to transform a user input string into a regex-safe form, use java.util.regex.Pattern.quote.

Further reading: Jan Goyvaert's blog RegexGuru on escaping metacharacters

XSLT getting last element

You need to put the last() indexing on the nodelist result, rather than as part of the selection criteria. Try:

(//element[@name='D'])[last()]

Is it possible to use raw SQL within a Spring Repository

we can use createNativeQuery("Here Nagitive SQL Query ");

for Example :

Query q = em.createNativeQuery("SELECT a.firstname, a.lastname FROM Author a");
List<Object[]> authors = q.getResultList();

Working with INTERVAL and CURDATE in MySQL

As suggested by A Star, I always use something along the lines of:

DATE(NOW()) - INTERVAL 1 MONTH

Similarly you can do:

NOW() + INTERVAL 5 MINUTE
"2013-01-01 00:00:00" + INTERVAL 10 DAY

and so on. Much easier than typing DATE_ADD or DATE_SUB all the time :)!

C++ printing spaces or tabs given a user input integer

Just use std::string:

std::cout << std::string( n, ' ' );

In many cases, however, depending on what comes next, is may be simpler to just add n to the parameter to an std::setw.

Testing pointers for validity (C/C++)

these links may be helpful

_CrtIsValidPointer Verifies that a specified memory range is valid for reading and writing (debug version only). http://msdn.microsoft.com/en-us/library/0w1ekd5e.aspx

_CrtCheckMemory Confirms the integrity of the memory blocks allocated in the debug heap (debug version only). http://msdn.microsoft.com/en-us/library/e73x0s4b.aspx

Combine two integer arrays

use ArrayUtils.addAll(T[], T...):

import org.apache.commons.lang3.ArrayUtils;

AnyObject[] array1 = ...;
AnyObject[] array2 = ...;
AnyObject[] mergedArray = ArrayUtils.addAll(array1, array2);

Get current index from foreach loop

IEnumerable list = DataGridDetail.ItemsSource as IEnumerable;
List<string> lstFile = new List<string>();

int i = 0;
foreach (var row in list)
{
bool IsChecked = (bool)((CheckBox)DataGridDetail.Columns[0].GetCellContent(row)).IsChecked;
if (IsChecked)
{
  MessageBox.show(i);
--Here i want to get the index or current row from the list                   

}
 ++i;
}

C++ calling base class constructors

The short answer for this is, "because that's what the C++ standard specifies".

Note that you can always specify a constructor that's different from the default, like so:

class Shape  {

  Shape()  {...} //default constructor
  Shape(int h, int w) {....} //some custom constructor


};

class Rectangle : public Shape {
  Rectangle(int h, int w) : Shape(h, w) {...} //you can specify which base class constructor to call

}

The default constructor of the base class is called only if you don't specify which one to call.

finished with non zero exit value

Just Make The Changes in The main/AndroidManifest.xml file. check for the tags and the values supplied i did this and all errors were removed

Remove the newline character in a list read from a file

Here are various optimisations and applications of proper Python style to make your code a lot neater. I've put in some optional code using the csv module, which is more desirable than parsing it manually. I've also put in a bit of namedtuple goodness, but I don't use the attributes that then provides. Names of the parts of the namedtuple are inaccurate, you'll need to correct them.

import csv
from collections import namedtuple
from time import localtime, strftime

# Method one, reading the file into lists manually (less desirable)
with open('grades.dat') as files:
    grades = [[e.strip() for e in s.split(',')] for s in files]

# Method two, using csv and namedtuple
StudentRecord = namedtuple('StudentRecord', 'id, lastname, firstname, something, homework1, homework2, homework3, homework4, homework5, homework6, homework7, exam1, exam2, exam3')
grades = map(StudentRecord._make, csv.reader(open('grades.dat')))
# Now you could have student.id, student.lastname, etc.
# Skipping the namedtuple, you could do grades = map(tuple, csv.reader(open('grades.dat')))

request = open('requests.dat', 'w')
cont = 'y'

while cont.lower() == 'y':
    answer = raw_input('Please enter the Student I.D. of whom you are looking: ')
    for student in grades:
        if answer == student[0]:
            print '%s, %s      %s      %s' % (student[1], student[2], student[0], student[3])
            time = strftime('%a, %b %d %Y %H:%M:%S', localtime())
            print time
            print 'Exams - %s, %s, %s' % student[11:14]
            print 'Homework - %s, %s, %s, %s, %s, %s, %s' % student[4:11]
            total = sum(int(x) for x in student[4:14])
            print 'Total points earned - %d' % total
            grade = total / 5.5
            if grade >= 90:
                letter = 'an A'
            elif grade >= 80:
                letter = 'a B'
            elif grade >= 70:
                letter = 'a C'
            elif grade >= 60:
                letter = 'a D'
            else:
                letter = 'an F'

            if letter = 'an A':
                print 'Grade: %s, that is equal to %s.' % (grade, letter)
            else:
                print 'Grade: %.2f, that is equal to %s.' % (grade, letter)

            request.write('%s %s, %s %s\n' % (student[0], student[1], student[2], time))


    print
    cont = raw_input('Would you like to search again? ')

print 'Goodbye.'

Remove the legend on a matplotlib figure

As of matplotlib v1.4.0rc4, a remove method has been added to the legend object.

Usage:

ax.get_legend().remove()

or

legend = ax.legend(...)
...
legend.remove()

See here for the commit where this was introduced.

How to remove a directory from git repository?

You can delete the folder locally and then push, as follow:

git rm -r folder_name
git commit -m "your commit"
git push origin master

How can I split a text file using PowerShell?

Same as all the answers here, but using StreamReader/StreamWriter to split on new lines (line by line, instead of trying to read the whole file into memory at once). This approach can split big files in the fastest way I know of.

Note: I do very little error checking, so I can't guarantee it'll work smoothly for your case. It did for mine (1.7 GB TXT file of 4 million lines split in 100,000 lines per file in 95 seconds).

#split test
$sw = new-object System.Diagnostics.Stopwatch
$sw.Start()
$filename = "C:\Users\Vincent\Desktop\test.txt"
$rootName = "C:\Users\Vincent\Desktop\result"
$ext = ".txt"

$linesperFile = 100000#100k
$filecount = 1
$reader = $null
try{
    $reader = [io.file]::OpenText($filename)
    try{
        "Creating file number $filecount"
        $writer = [io.file]::CreateText("{0}{1}.{2}" -f ($rootName,$filecount.ToString("000"),$ext))
        $filecount++
        $linecount = 0

        while($reader.EndOfStream -ne $true) {
            "Reading $linesperFile"
            while( ($linecount -lt $linesperFile) -and ($reader.EndOfStream -ne $true)){
                $writer.WriteLine($reader.ReadLine());
                $linecount++
            }

            if($reader.EndOfStream -ne $true) {
                "Closing file"
                $writer.Dispose();

                "Creating file number $filecount"
                $writer = [io.file]::CreateText("{0}{1}.{2}" -f ($rootName,$filecount.ToString("000"),$ext))
                $filecount++
                $linecount = 0
            }
        }
    } finally {
        $writer.Dispose();
    }
} finally {
    $reader.Dispose();
}
$sw.Stop()

Write-Host "Split complete in " $sw.Elapsed.TotalSeconds "seconds"

Output splitting a 1.7 GB file:

...
Creating file number 45
Reading 100000
Closing file
Creating file number 46
Reading 100000
Closing file
Creating file number 47
Reading 100000
Closing file
Creating file number 48
Reading 100000
Split complete in  95.6308289 seconds

Remove NaN from pandas series

>>> s = pd.Series([1,2,3,4,np.NaN,5,np.NaN])
>>> s[~s.isnull()]
0    1
1    2
2    3
3    4
5    5

update or even better approach as @DSM suggested in comments, using pandas.Series.dropna():

>>> s.dropna()
0    1
1    2
2    3
3    4
5    5

How to pass a form input value into a JavaScript function

Use onclick="foo(document.getElementById('formValueId').value)"

SQL Server: Difference between PARTITION BY and GROUP BY

When you use GROUP BY, the resulting rows will be usually less then incoming rows.

But, when you use PARTITION BY, the resulting row count should be the same as incoming.

Remove spacing between table cells and rows

You have cellspacing="0" twice, try replacing the second one with cellpadding="0" instead.

long long in C/C++

It depends in what mode you are compiling. long long is not part of the C++ standard but only (usually) supported as extension. This affects the type of literals. Decimal integer literals without any suffix are always of type int if int is big enough to represent the number, long otherwise. If the number is even too big for long the result is implementation-defined (probably just a number of type long int that has been truncated for backward compatibility). In this case you have to explicitly use the LL suffix to enable the long long extension (on most compilers).

The next C++ version will officially support long long in a way that you won't need any suffix unless you explicitly want the force the literal's type to be at least long long. If the number cannot be represented in long the compiler will automatically try to use long long even without LL suffix. I believe this is the behaviour of C99 as well.

Using CSS in Laravel views?

Since Laravel 5 the HTML class is not included by default anymore.

If you're using Form or HTML helpers, you will see an error stating class 'Form' not found or class 'Html' not found. The Form and HTML helpers have been deprecated in Laravel 5.0; however, there are community-driven replacements such as those maintained by the Laravel Collective.

You can make use of the following line to include your CSS or JS files:

<link href="{{ URL::asset('css/base.css') }}" rel="stylesheet">
<link href="{{ URL::asset('js/project.js') }}" rel="script">

Ruby on Rails generates model field:type - what are the options for field:type?

I had the same issue, but my code was a little bit different.

def new
 @project = Project.new
end

And my form looked like this:

<%= form_for @project do |f| %>
     and so on....
<% end %>

That was totally correct, so I didn't know how to figure it out.

Finally, just adding

url: { projects: :create }

after

<%= form-for @project ...%>

worked for me.

How to get PID of process by specifying process name and store it in a variable to use further?

pids=$(pgrep <name>)

will get you the pids of all processes with the given name. To kill them all, use

kill -9 $pids

To refrain from using a variable and directly kill all processes with a given name issue

pkill -9 <name>

Is the practice of returning a C++ reference variable evil?

It's not evil. Like many things in C++, it's good if used correctly, but there are many pitfalls you should be aware of when using it (like returning a reference to a local variable).

There are good things that can be achieved with it (like map[name] = "hello world")

Adding asterisk to required fields in Bootstrap 3

Assuming this is what the HTML looks like

<div class="form-group required">
   <label class="col-md-2 control-label">E-mail</label>
   <div class="col-md-4"><input class="form-control" id="id_email" name="email" placeholder="E-mail" required="required" title="" type="email" /></div>
</div>

To display an asterisk on the right of the label:

.form-group.required .control-label:after { 
    color: #d00;
    content: "*";
    position: absolute;
    margin-left: 8px;
    top:7px;
}

Or to the left of the label:

.form-group.required .control-label:before{
   color: red;
   content: "*";
   position: absolute;
   margin-left: -15px;
}

To make a nice big red asterisks you can add these lines:

font-family: 'Glyphicons Halflings';
font-weight: normal;
font-size: 14px;

Or if you are using Font Awesome add these lines (and change the content line):

font-family: 'FontAwesome';
font-weight: normal;
font-size: 14px;
content: "\f069";

What is git fast-forwarding?

When you try to merge one commit with a commit that can be reached by following the first commit’s history, Git simplifies things by moving the pointer forward because there is no divergent work to merge together – this is called a “fast-forward.”

For more : http://git-scm.com/book/en/v2/Git-Branching-Basic-Branching-and-Merging

In another way,

If Master has not diverged, instead of creating a new commit, git will just point master to the latest commit of the feature branch. This is a “fast forward.”

There won't be any "merge commit" in fast-forwarding merge.

GitHub - failed to connect to github 443 windows/ Failed to connect to gitHub - No Error

(Hope this answer help someone like me.)

The same problem happened to me in Windows using git for windows.

I set proxy setting as usual:

git config --global http.proxy http://username:[email protected]:port

In my situation, the username is email, so it has a @ sign. After encode the @ sign with %40 in username, the problem is resolved.

So, encode the special characters not only in password, but also in username. (Refer to the comments of this answer)

VBA paste range

I would try

Sheets("Sheet1").Activate
Set Ticker = Range(Cells(2, 1), Cells(65, 1))
Ticker.Copy

Worksheets("Sheet2").Range("A1").Offset(0,0).Cells.Select
Worksheets("Sheet2").paste

importing a CSV into phpmyadmin

This is happen due to the id(auto increment filed missing). If you edit it in a text editor by adding a comma for the ID field this will be solved.

Python's most efficient way to choose longest string in list?

From the Python documentation itself, you can use max:

>>> mylist = ['123','123456','1234']
>>> print max(mylist, key=len)
123456

MongoDB and "joins"

I came across lot of posts searching for the same - "Mongodb Joins" and alternatives or equivalents. So my answer would help many other who are like me. This is the answer I would be looking for.

I am using Mongoose with Express framework. There is a functionality called Population in place of joins.

As mentioned in Mongoose docs.

There are no joins in MongoDB but sometimes we still want references to documents in other collections. This is where population comes in.

This StackOverflow answer shows a simple example on how to use it.

Getting the name / key of a JToken with JSON.net

JObject obj = JObject.Parse(json);
var attributes = obj["parent"]["child"]...["your desired element"].ToList<JToken>(); 

foreach (JToken attribute in attributes)
{   
    JProperty jProperty = attribute.ToObject<JProperty>();
    string propertyName = jProperty.Name;
}

How to uninstall jupyter

For python 3.7:

  1. On windows command prompt, type: "py -m pip install pip-autoremove". You will get a successful message.
  2. Change directory, if you didn't add the following as your PATH: cd C:\Users{user_name}\AppData\Local\Programs\Python\Python37-32\Scripts To know where your package/application has been installed/located, type: "where program_name" like> where jupyter If you didn't find a location, you need to add the location in PATH.

  3. Type: pip-autoremove jupyter It will ask to type y/n to confirm the action.

Add Twitter Bootstrap icon to Input box

Updated Bootstrap 3.x

You can use the .input-group class like this:

<div class="input-group">
    <input type="text" class="form-control"/>
    <span class="input-group-addon">
        <i class="fa fa-search"></i>
    </span>
</div>

Working Demo in jsFiddle for 3.x


Bootstrap 2.x

You can use the .input-append class like this:

<div class="input-append">
    <input class="span2" type="text">
    <button type="submit" class="btn">
        <i class="icon-search"></i>
    </button>
</div>

Working Demo in jsFiddle for 2.x


Both will look like this:

screenshot outside

If you'd like the icon inside the input box, like this:

screenshot inside

Then see my answer to Add a Bootstrap Glyphicon to Input Box

Display Back Arrow on Toolbar

If your are using the androidx.appcompat.app.AppCompatActivity just use:

Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);

Then just define in the Manifest.xml the parent Activity.

<activity
    android:name=".MyActivity"
    ...>
  <meta-data
      android:name="android.support.PARENT_ACTIVITY"
      android:value=".ParentActivity" />
</activity>

Instead if you are using a Toolbar and you want a custom behavior just use:

<androidx.appcompat.widget.Toolbar
    android:id="@+id/toolbar" 
    app:navigationIcon="?attr/homeAsUpIndicator"
    .../>

and in your Activity:

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        //....
    }
});

How do I get the current time only in JavaScript

Assign to variables and display it.

time = new Date();

var hh = time.getHours();
var mm = time.getMinutes();
var ss = time.getSeconds() 

document.getElementById("time").value = hh + ":" + mm + ":" + ss;

How can I make a weak protocol reference in 'pure' Swift (without @objc)

Update: It looks like the manual has been updated and the example I was referring to has been removed. See the edit to @flainez's answer above.

Original: Using @objc is the right way to do it even if you're not interoperating with Obj-C. It ensures that your protocol is being applied to a class and not an enum or struct. See "Checking for Protocol Conformance" in the manual.

Show hide fragment in android

In addittion, you can do in a Fragment (for example when getting server data failed):

 getView().setVisibility(View.GONE);

Why is synchronized block better than synchronized method?

The difference is in which lock is being acquired:

  • synchronized method acquires a lock on the whole object. This means no other thread can use any synchronized method in the whole object while the method is being run by one thread.

  • synchronized blocks acquires a lock in the object between parentheses after the synchronized keyword. Meaning no other thread can acquire a lock on the locked object until the synchronized block exits.

So if you want to lock the whole object, use a synchronized method. If you want to keep other parts of the object accessible to other threads, use synchronized block.

If you choose the locked object carefully, synchronized blocks will lead to less contention, because the whole object/class is not blocked.

This applies similarly to static methods: a synchronized static method will acquire a lock in the whole class object, while a synchronized block inside a static method will acquire a lock in the object between parentheses.

std::string length() and size() member functions

When using coding practice tools(LeetCode) it seems that size() is quicker than length() (although basically negligible)

What Does This Mean in PHP -> or =>

=> is used in associative array key value assignment. Take a look at:

http://php.net/manual/en/language.types.array.php.

-> is used to access an object method or property. Example: $obj->method().